问:
Mocking ViewContext's StreamWriter to output ViewEngineResults.View.RenderAsync result?
I inherited an application with little-to-no unit testing and I'm trying to mock out a service class. The class takes in a viewModel as a string and a model as an object then returns the view as a string. It looks like the developer implemented something similar to this.

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using FluidMvcViewEngine;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace Some.Api.Services
{
    public class ViewRenderService
    {
        private readonly IActionContextAccessor _context;
        private readonly IFluidViewEngine _fluidViewEngine;
        private readonly ITempDataProvider _tempDataProvider;

        public ViewRenderService(IActionContextAccessor context, IFluidViewEngine razorViewEngine, ITempDataProvider tempDataProvider)
        {
            _context = context;
            _fluidViewEngine = razorViewEngine;
            _tempDataProvider = tempDataProvider;
        }

        public async Task<string> RenderToStringAsync(string viewName, object model, CancellationToken ct = default(CancellationToken))
        {
            var actionContext = _context.ActionContext;

            using (var writer = new StringWriter())
            {
                var viewResult = _fluidViewEngine.GetView(viewName, viewName, false);

                if (viewResult.View == null)
                {
                    throw new ArgumentNullException("exception message goes here");
                }

                var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = model
                };

                var viewContext = new ViewContext(
                    actionContext,
                    viewResult.View,
                    viewDictionary,
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    writer,
                    new HtmlHelperOptions()
                );

                await viewResult.View.RenderAsync(viewContext);
                return writer.ToString();
            }
        }
    }
}
```

<p>The code works, but there aren't any tests for the service. I was able to mock everything with nSubstitute and it runs through with no exceptions, but I really don't understand what <code>writer.ToString()</code> is supposed to be writing out or how to mock it. </p>

<p>I can see that <code>await viewResult.View.RenderAsync(viewContext);</code> is rendering the viewContext, and that the ViewContext is taking in an instance of the StringWriter. However, I'm not able to step into the ViewEngineResult.View.RenderAsync method to see how the StringWriter works.</p>

<pre class="lang-cs prettyprint-override"><code>using System.Threading.Tasks;
using FluentAssertions;
using FluidMvcViewEngine;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using NSubstitute;
using Xunit;

namespace Some.Tests.UnitTests.Services
{
    public class ViewRenderServiceTest
    {
        private readonly IActionContextAccessor _context;
        private readonly IFluidViewEngine _fluidViewEngine;
        private readonly ViewRenderService _service;
        private readonly ITempDataProvider _tempDataProvider;
        private readonly IView _view;
        private readonly IViewEngine _viewEngine;

        public ViewRenderServiceTest()
        {
            _context = Substitute.For<IActionContextAccessor>();
            _fluidViewEngine = Substitute.For<IFluidViewEngine>();
            _tempDataProvider = Substitute.For<ITempDataProvider>();
            _view = Substitute.For<IView>();
            _viewEngine = Substitute.For<IViewEngine>();

            _service = new ViewRenderService(_context, _fluidViewEngine, _tempDataProvider);
        }

        [Fact]
        public async Task RenderToStringAsyncTest()
        {
            // Arrange
            var stringToRender = "RENDERED";
            var someObject = new { Id = default(int), Name = "Bob" };

            // Mock IActionContextAccessor
            MockIActionContextAccessor();

            // Mock IFluidViewEngine
            MockIFluidViewEngine(stringToRender);

            // Act
            var test = await _service.RenderToStringAsync(stringToRender, someObject);

            // Assert
            test.Should().Be(stringToRender);
        }

        private void MockIActionContextAccessor()
        {
            var httpContext = Substitute.For<HttpContext>();
            var routeData = Substitute.For<RouteData>();
            var actionDescriptor = Substitute.For<ActionDescriptor>();
            var modelState = Substitute.For<ModelStateDictionary>();

            _context.ActionContext.Returns(new ActionContext(httpContext, routeData, actionDescriptor, modelState));
        }

        private void MockIFluidViewEngine(string stringToRender)
        {
            _view
                .RenderAsync(Arg.Any<ViewContext>())
                .Returns(Task.FromResult(stringToRender));

            _view
                .Path
                .Returns(string.Empty);

            _viewEngine
                .GetView(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>())
                .Returns(ViewEngineResult.Found(stringToRender, _view));

            _fluidViewEngine
                .GetView(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>())
                .Returns(ViewEngineResult.Found(stringToRender, _view));
        }
    }
}
</code>```

Once everything was wired up I was expecting to see RENDERED but all I get is an empty string.

答:
I am guessing _view.RenderAsync(...) will need to be mocked to write to  ViewContext.Writer.

You could try something like:

```<code>_view
    .RenderAsync(Arg.Any<ViewContext>())
    .Returns(x => x.Arg<ViewContext>().Writer.WriteAsync(stringToRender));
</code>```

Or:

```<code>_view
    .RenderAsync(Arg.Do<ViewContext>(vc => vc.Writer.Write(stringToRender));
</code>```

The first version probably works closer to the way we expect as the effect is wrapped in a Task to await (the second will write immediately regardless of what happens to the returned task).

I can't test this at the moment so let me know if this doesn't help or if you encounter problems getting it to compile. Hopefully this is enough to get you started.

Body:
I inherited an application with little-to-no unit testing and I'm trying to mock out a service class. The class takes in a viewModel as a string and a model as an object then returns the view as a string. It looks like the developer implemented something similar to this.

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using FluidMvcViewEngine;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace Some.Api.Services
{
    public class ViewRenderService
    {
        private readonly IActionContextAccessor _context;
        private readonly IFluidViewEngine _fluidViewEngine;
        private readonly ITempDataProvider _tempDataProvider;

        public ViewRenderService(IActionContextAccessor context, IFluidViewEngine razorViewEngine, ITempDataProvider tempDataProvider)
        {
            _context = context;
            _fluidViewEngine = razorViewEngine;
            _tempDataProvider = tempDataProvider;
        }

        public async Task<string> RenderToStringAsync(string viewName, object model, CancellationToken ct = default(CancellationToken))
        {
            var actionContext = _context.ActionContext;

            using (var writer = new StringWriter())
            {
                var viewResult = _fluidViewEngine.GetView(viewName, viewName, false);

                if (viewResult.View == null)
                {
                    throw new ArgumentNullException("exception message goes here");
                }

                var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = model
                };

                var viewContext = new ViewContext(
                    actionContext,
                    viewResult.View,
                    viewDictionary,
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    writer,
                    new HtmlHelperOptions()
                );

                await viewResult.View.RenderAsync(viewContext);
                return writer.ToString();
            }
        }
    }
}

The code works, but there aren't any tests for the service. I was able to mock everything with nSubstitute and it runs through with no exceptions, but I really don't understand what writer.ToString() is supposed to be writing out or how to mock it.

I can see that await viewResult.View.RenderAsync(viewContext); is rendering the viewContext, and that the ViewContext is taking in an instance of the StringWriter. However, I'm not able to step into the ViewEngineResult.View.RenderAsync method to see how the StringWriter works.

using System.Threading.Tasks;
using FluentAssertions;
using FluidMvcViewEngine;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using NSubstitute;
using Xunit;

namespace Some.Tests.UnitTests.Services
{
    public class ViewRenderServiceTest
    {
        private readonly IActionContextAccessor _context;
        private readonly IFluidViewEngine _fluidViewEngine;
        private readonly ViewRenderService _service;
        private readonly ITempDataProvider _tempDataProvider;
        private readonly IView _view;
        private readonly IViewEngine _viewEngine;

        public ViewRenderServiceTest()
        {
            _context = Substitute.For<IActionContextAccessor>();
            _fluidViewEngine = Substitute.For<IFluidViewEngine>();
            _tempDataProvider = Substitute.For<ITempDataProvider>();
            _view = Substitute.For<IView>();
            _viewEngine = Substitute.For<IViewEngine>();

            _service = new ViewRenderService(_context, _fluidViewEngine, _tempDataProvider);
        }

        [Fact]
        public async Task RenderToStringAsyncTest()
        {
            // Arrange
            var stringToRender = "RENDERED";
            var someObject = new { Id = default(int), Name = "Bob" };

            // Mock IActionContextAccessor
            MockIActionContextAccessor();

            // Mock IFluidViewEngine
            MockIFluidViewEngine(stringToRender);

            // Act
            var test = await _service.RenderToStringAsync(stringToRender, someObject);

            // Assert
            test.Should().Be(stringToRender);
        }

        private void MockIActionContextAccessor()
        {
            var httpContext = Substitute.For<HttpContext>();
            var routeData = Substitute.For<RouteData>();
            var actionDescriptor = Substitute.For<ActionDescriptor>();
            var modelState = Substitute.For<ModelStateDictionary>();

            _context.ActionContext.Returns(new ActionContext(httpContext, routeData, actionDescriptor, modelState));
        }

        private void MockIFluidViewEngine(string stringToRender)
        {
            _view
                .RenderAsync(Arg.Any<ViewContext>())
                .Returns(Task.FromResult(stringToRender));

            _view
                .Path
                .Returns(string.Empty);

            _viewEngine
                .GetView(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>())
                .Returns(ViewEngineResult.Found(stringToRender, _view));

            _fluidViewEngine
                .GetView(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>())
                .Returns(ViewEngineResult.Found(stringToRender, _view));
        }
    }
}

Once everything was wired up I was expecting to see RENDERED but all I get is an empty string.

Body:
I am guessing _view.RenderAsync(...) will need to be mocked to write to  ViewContext.Writer.

You could try something like:

_view
    .RenderAsync(Arg.Any<ViewContext>())
    .Returns(x => x.Arg<ViewContext>().Writer.WriteAsync(stringToRender));

Or:

_view
    .RenderAsync(Arg.Do<ViewContext>(vc => vc.Writer.Write(stringToRender));

The first version probably works closer to the way we expect as the effect is wrapped in a Task to await (the second will write immediately regardless of what happens to the returned task).

I can't test this at the moment so let me know if this doesn't help or if you encounter problems getting it to compile. Hopefully this is enough to get you started.


来源: stackexchange

问:
Group data based on unique ID and then pasting it onto the same row
I have a subset of my data :

```<code>a3 <- structure(list(Employee.Number = c("10034", "10034", "10034"),
               Employee.Full.Name = c("Wayne, Bruce", "Wayne, Bruce",
                                      "Wayne, Bruce"), Case.No = c("78582", "87758", "87758"),
               Diagnoses.No = c("1", "2", "1"), Diagnosis.Medical.Code.Code = c("151.9",
                                                                                "285.9", "V70-V82"), Diagnosis.Medical.Code.Description = c("Stomach, unspecified",
                                                                                "Anemia, unspecified", "Tummy AChe"
                                                                                )), row.names = c(NA, -3L), class = "data.frame")

</code>```

How would I go about grouping the Case.No and if the "Diagnoses.No" equals 2 (the actual data has numbers >2), then the last 3 columns will be pasted onto the column of the same Case.no with the Diagnoses.No with 1 with the original column removed?

Desired results:

```<code>
10034  Wayne, Bruce  78582  1  151.9    Stomach, unspecified   NA

10034  Wayne, Bruce  87758  1  V70-V82  Tummy AChe 2  285.9    Anemia, unspecified
</code>```

答:
The presentation is a bit different to what you wanted but see if it works for you.

tidyverse solution:

```<code># function to concartinate columns
cat_function <- function(df){
  map_df(df, ~paste(unlist(.), collapse = " / "))
}

a3 %>%
  group_by(Employee.Number, Employee.Full.Name, Case.No) %>%
  nest %>%
  transmute(Employee.Number, Employee.Full.Name, Case.No,
             res = map(data, cat_function)) %>%
  unnest
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a subset of my data :

a3 <- structure(list(Employee.Number = c("10034", "10034", "10034"),
               Employee.Full.Name = c("Wayne, Bruce", "Wayne, Bruce",
                                      "Wayne, Bruce"), Case.No = c("78582", "87758", "87758"),
               Diagnoses.No = c("1", "2", "1"), Diagnosis.Medical.Code.Code = c("151.9",
                                                                                "285.9", "V70-V82"), Diagnosis.Medical.Code.Description = c("Stomach, unspecified",
                                                                                "Anemia, unspecified", "Tummy AChe"
                                                                                )), row.names = c(NA, -3L), class = "data.frame")

How would I go about grouping the Case.No and if the "Diagnoses.No" equals 2 (the actual data has numbers >2), then the last 3 columns will be pasted onto the column of the same Case.no with the Diagnoses.No with 1 with the original column removed?

Desired results:

10034  Wayne, Bruce  78582  1  151.9    Stomach, unspecified   NA

10034  Wayne, Bruce  87758  1  V70-V82  Tummy AChe 2  285.9    Anemia, unspecified

Body:
The presentation is a bit different to what you wanted but see if it works for you.

tidyverse solution:

# function to concartinate columns
cat_function <- function(df){
  map_df(df, ~paste(unlist(.), collapse = " / "))
}

a3 %>%
  group_by(Employee.Number, Employee.Full.Name, Case.No) %>%
  nest %>%
  transmute(Employee.Number, Employee.Full.Name, Case.No,
             res = map(data, cat_function)) %>%
  unnest


问:
Reversing a string in JavaScript
I'm trying to reverse an input string

```<code>var oneway = document.getElementById('input_field').value();
var backway = oneway.reverse();
</code>```

but firebug is telling me that oneway.reverse() is not a function. Any ideas?

Thank you

答:
If it's necessary to revert the string, but return the original value of the error:</p>

```<code>function reverseString(s) {
    let valuePrintS;
    try {
        valuePrintS = s.split("").reverse().join("");
    } catch {
        console.log("s.split is not a function");
        valuePrintS = s;
    } finally {
        console.log(valuePrintS);
    }
}
</code>```

Title: Reversing a string in JavaScript

Body:
I'm trying to reverse an input string

var oneway = document.getElementById('input_field').value();
var backway = oneway.reverse();

but firebug is telling me that oneway.reverse() is not a function. Any ideas?

Thank you

Body:
If it's necessary to revert the string, but return the original value of the error:

function reverseString(s) {
    let valuePrintS;
    try {
        valuePrintS = s.split("").reverse().join("");
    } catch {
        console.log("s.split is not a function");
        valuePrintS = s;
    } finally {
        console.log(valuePrintS);
    }
}


问:
Difference between update and update_attributes
In Rails 5, what is the difference between update and update_attributes methods. I'm seeing the following results for both the methods

Returns true/false

Checking for active record validation

Call backs are triggered

and also regarding update method a new thing was introduced in active record relation. I'm not able to understand it. What is the difference?

Moreover are we using update_attributes in Rails 5. It's not there in active record documentation.

I'm confused with all update methods. I need clarity

答:
As of Rails 4.0.2, #update returns false if the update failed. Before Rails 4.0.2, #update returned the object that got updated. The main difference therefore was the return value. After this change, #update_attributes is just an alias of #update.

As of Rails 6.0, #update_attributes is deprecated in favor of #update.


问:
Additional whitespace appearing at bottom of auto-resizing textarea element
I have a textarea which I have added an onChange listener to in order to update the field's height whenever a new line is required (or if a line is no longer required). The issue I'm having is that, when the cursor approaches the end of the (current) final line of the textarea, additional whitespace is created which does not actually "exist" (i.e. it consists of no characters - sort of an "empty line").

My description probably isn't sufficient to explain the issue I'm having, but the same effect can be observed in the JSFiddle below (I'm using an identical implementation for my own form):

https://jsfiddle.net/d9fqaest/

As you can see, when the end of the first line is reached, a new line is added without issue:

But when the end of the second line (or any following lines) is reached, a new "empty" line is added too soon (with any following lines requiring fewer and fewer characters before adding the erroneous line):

I suspect the issue lies somewhere in the way the row count is calculated:

```<code>handleChange(e) {
    const oldRows = e.target.rows;
    e.target.rows = 1;
    const newRows = ~~(e.target.scrollHeight/lineHeight);

    if (newRows === oldRows) {
        e.target.rows = newRows;
    }

    this.setState({
        value: e.target.value,
        rows: newRows
    });
}
</code>```

I've tried a few different flows of logic here, including simply setting the element's height to its scrollHeight, but I haven't been able to produce the desired behaviour (the aforementioned approach somewhat worked, but I was unable to figure out how to remove lines as text was deleted). I'm aware of several external libraries which would solve this problem, but I'd like to avoid using those if at all possible.

Thanks!

答: So it turns out all that was needed was overflow-y: hidden on the textarea to prevent the scrollbar from being included in the height calculation. Simple fix!

Body:
I have a textarea which I have added an onChange listener to in order to update the field's height whenever a new line is required (or if a line is no longer required). The issue I'm having is that, when the cursor approaches the end of the (current) final line of the textarea, additional whitespace is created which does not actually "exist" (i.e. it consists of no characters - sort of an "empty line").

My description probably isn't sufficient to explain the issue I'm having, but the same effect can be observed in the JSFiddle below (I'm using an identical implementation for my own form):

https://jsfiddle.net/d9fqaest/

As you can see, when the end of the first line is reached, a new line is added without issue:

But when the end of the second line (or any following lines) is reached, a new "empty" line is added too soon (with any following lines requiring fewer and fewer characters before adding the erroneous line):

I suspect the issue lies somewhere in the way the row count is calculated:

handleChange(e) {
    const oldRows = e.target.rows;
    e.target.rows = 1;
    const newRows = ~~(e.target.scrollHeight/lineHeight);

    if (newRows === oldRows) {
        e.target.rows = newRows;
    }

    this.setState({
        value: e.target.value,
        rows: newRows
    });
}

I've tried a few different flows of logic here, including simply setting the element's height to its scrollHeight, but I haven't been able to produce the desired behaviour (the aforementioned approach somewhat worked, but I was unable to figure out how to remove lines as text was deleted). I'm aware of several external libraries which would solve this problem, but I'd like to avoid using those if at all possible.

Thanks!


答:
I am not sure about the output you want, but I think this script could help. It uses data.table package:

```<code>library(data.table)
a3<-data.table(a3)

a2 <-a3[Diagnoses.No==2,list(Employee.Number,Employee.Full.Name,Case.No,
                             x=paste0(Diagnoses.No, ' ', Diagnosis.Medical.Code.Code), Diagnosis.Medical.Code.Description),]

a1 <-a3[Diagnoses.No==1,]

a3 <- merge(a1,a2, by=c('Employee.Number','Employee.Full.Name','Case.No'), all.x=T)
a3 <- a3[,list(Employee.Number,Employee.Full.Name,Case.No,Diagnosis.Medical.Code.Code,
            Diagnosis.Medical.Code.Description.x= paste0(Diagnosis.Medical.Code.Description.x,' ',x),
            Diagnosis.Medical.Code.Description.y)]
</code>```

The output is similar to your request:

```<code>> a3
   Employee.Number Employee.Full.Name Case.No Diagnosis.Medical.Code.Code Diagnosis.Medical.Code.Description.x Diagnosis.Medical.Code.Description.y
1:           10034       Wayne, Bruce   78582                       151.9              Stomach, unspecified NA                                 <NA>
2:           10034       Wayne, Bruce   87758                     V70-V82                   Tummy AChe 2 285.9                  Anemia, unspecified
</code>```

Hope it helps!

Title: Group data based on unique ID and then pasting it onto the same row

Body:
I am not sure about the output you want, but I think this script could help. It uses data.table package:

library(data.table)
a3<-data.table(a3)

a2 <-a3[Diagnoses.No==2,list(Employee.Number,Employee.Full.Name,Case.No,
                             x=paste0(Diagnoses.No, ' ', Diagnosis.Medical.Code.Code), Diagnosis.Medical.Code.Description),]

a1 <-a3[Diagnoses.No==1,]

a3 <- merge(a1,a2, by=c('Employee.Number','Employee.Full.Name','Case.No'), all.x=T)
a3 <- a3[,list(Employee.Number,Employee.Full.Name,Case.No,Diagnosis.Medical.Code.Code,
            Diagnosis.Medical.Code.Description.x= paste0(Diagnosis.Medical.Code.Description.x,' ',x),
            Diagnosis.Medical.Code.Description.y)]

The output is similar to your request:

> a3
   Employee.Number Employee.Full.Name Case.No Diagnosis.Medical.Code.Code Diagnosis.Medical.Code.Description.x Diagnosis.Medical.Code.Description.y
1:           10034       Wayne, Bruce   78582                       151.9              Stomach, unspecified NA                                 <NA>
2:           10034       Wayne, Bruce   87758                     V70-V82                   Tummy AChe 2 285.9                  Anemia, unspecified

Hope it helps!


Title: How to print elements in a vector of vectors

Body:
I have a vector of vectors, and I want to print elements in each vector

I tried the pprint but did not work as wanted

This is the vector of vectors I wish to print:

[["+" "+" "+" "#" "!" "-" "#" "#" "#" "-" "-" "-" "-"]
 ["!" "#" "+" "+" "+" "#" "+" "+" "+" "-" "#" "#" "-"]
 ["#" "#" "#" "#" "+" "#" "+" "#" "+" "#" "-" "#" "#"]
 ["+" "+" "+" "#" "+" "+" "+" "#" "+" "#" "-" "-" "-"]
 ["+" "#" "+" "#" "#" "#" "#" "+" "+" "-" "#" "#" "-"]
 ["+" "#" "+" "+" "+" "+" "+" "+" "#" "-" "-" "-" "-"]
 ["+" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
 ["+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "@"]]

This is the output I want:

+++#--###--#-
!#+++#+++-##-
####+#+#+#!##
+++#+++#+#!!!
+#+####++!##!
+#++++++#!!!!
+############
++++++++++++@

Body:
You don't need any fancy formatting or side-effects (although I do appreciate the information in those answers). Just use clojure.string/join to create the string you want and print it any old way.

> (join "\n" (map join input))
+++#!-###----
!#+++#+++-##-
####+#+#+#-##
+++#+++#+#---
+#+####++-##-
+#++++++#----
+############
++++++++++++@

e.g.

> (let [s (join "\n" (map join input))] (println s))
+++#!-###----
!#+++#+++-##-
####+#+#+#-##
+++#+++#+#---
+#+####++-##-
+#++++++#----
+############
++++++++++++@
nil


问:
Any reason not to start using the HTML 5 doctype?

It is supposed to be backwards compatible with HTML4 and XHTML. John Resig posted about some of the benefits.

As long as we don't use any of the new and not supported yet features, would there be any downside to start building sites with this doctype?

答: I'd say use it and test extensively. Then let us know if it blew your house up or something. :')</p>

ContentLicense: CC BY-SA 2.5


问:
Iterators in C++ (stl) vs Java, is there a conceptual difference?
I'm returning to c++ after being away for a bit and trying to dust off the old melon.

In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed.

```<code>//with an Iterator
Iterator<String> iter = trees.iterator();
while (iter.hasNext())
{
    System.out.println(iter.next());
}
</code>```

In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.

```<code>vector<int> vec;
vector<int>::iterator iter;

// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);

for (iter= v.begin(); iter != v.end(); iter++)
{
    cout << *i << " "; //Should output 1 4 8
}
</code>```

The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.

It there any further subtlety to this that I am missing?

答:
Yes, there is a large conceptual difference. C++ utilizes different "classes" of iterators. Some are used for random access (unlike Java), some are used for forward access (like java). While even others are used for writing data (for use with, say, transform).

See the iterators concept in the C++ Documentation:

Input Iterator

Output Iterator

Forward Iterator

Bidirectional Iterator

Random Access Iterator

These are far more interesting and powerful compared to Java/C#'s puny iterators. Hopefully these conventions will be codified using C++0x's Concepts.

OwnerDisplayName: Jeff V

Body:
I'm returning to c++ after being away for a bit and trying to dust off the old melon.

In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed.

//with an Iterator
Iterator<String> iter = trees.iterator();
while (iter.hasNext())
{
    System.out.println(iter.next());
}

In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.

vector<int> vec;
vector<int>::iterator iter;

// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);

for (iter= v.begin(); iter != v.end(); iter++)
{
    cout << *i << " "; //Should output 1 4 8
}

The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.

It there any further subtlety to this that I am missing?

OwnerDisplayName: Frank Krueger

ContentLicense: CC BY-SA 3.0


问:
PHP join help with two tables
I am just learning php as I go along, and I'm completely lost here.  I've never really used join before, and I think I need to here, but I don't know.  I'm not expecting anyone to do it for me but if you could just point me in the right direction it would be amazing, I've tried reading up on joins but there are like 20 different methods and I'm just lost.

Basically, I hand coded a forum, and it works fine but is not efficient.

I have board_posts (for posts) and board_forums (for forums, the categories as well as the sections).

The part I'm redoing is how I get the information for the last post for the index page. The way I set it up is that to avoid using joins, I have it store the info for latest post in the table for board_forums, so say there is a section called "Off Topic" there I would have a field for "forum_lastpost_username/userid/posttitle/posttime" which I woudl update when a user posts etc.  But this is bad, I'm trying to grab it all dynamically and get rid of those fields.

Right now my query is just like:

```<code>`SELECT * FROM board_forums WHERE forum_parent='$forum_id''
</code>```

And then I have the stuff where I grab the info for that forum (name, description, etc) and all the data for the last post is there:

```<code>    $last_thread_title = $forumrow["forum_lastpost_title"];
    $last_thread_time = $forumrow["forum_lastpost_time"];
    $lastpost_username = $forumrow["forum_lastpost_username"];
    $lastpost_threadid = $forumrow["forum_lastpost_threadid"];
</code>```

But I need to get rid of that, and get it from board_posts. The way it's set up in board_posts is that if it's a thread, post_parentpost is NULL, if it's a reply, then that field has the id of the thread (first post of the topic).  So, I need to grab the latest post_date, see which user posted that, THEN see if parentpost is NULL (if it's null then the last post is a new thread, so I can get all the info of the title and user there, but if it's not, then I need to get the info (title, id) of the first post in that thread (which can be found by seeing what post_parentpost is, looking up that ID and getting the title from it.

Does that make any sense? If so please help me out :(

Any help is greatly appreciated!!!!

答:
The simple solution will result in numerous queries, some optional, as you're already discovered.

The classic approach to this is to cache the results, and only retrieve it once in a while. The cache doesn't have to live long; even two or three seconds on a busy site will make a significant difference.

De-normalizing the data into a table you're already reading anyway will help. This approach saves you figuring out optional queries and can be a bit of a cheap win because it's just one more update when an insert is already happening. But it shifts some data integrity to the application.

As an aside, you might be running into the recursive-query problem with your threads. Relational databases do not store heirarchical data all that well if you use a "simple" algorithim. A better way is something sometimes called 'set trees'. It's a bit hard to Google, unfortunately, so here are some links.

OwnerDisplayName: Vadim

LastEditorDisplayName: Vadim

Title: PHP join help with two tables

Body:
I am just learning php as I go along, and I'm completely lost here.  I've never really used join before, and I think I need to here, but I don't know.  I'm not expecting anyone to do it for me but if you could just point me in the right direction it would be amazing, I've tried reading up on joins but there are like 20 different methods and I'm just lost.

Basically, I hand coded a forum, and it works fine but is not efficient.

I have board_posts (for posts) and board_forums (for forums, the categories as well as the sections).

The part I'm redoing is how I get the information for the last post for the index page. The way I set it up is that to avoid using joins, I have it store the info for latest post in the table for board_forums, so say there is a section called "Off Topic" there I would have a field for "forum_lastpost_username/userid/posttitle/posttime" which I woudl update when a user posts etc.  But this is bad, I'm trying to grab it all dynamically and get rid of those fields.

Right now my query is just like:

`SELECT * FROM board_forums WHERE forum_parent='$forum_id''

And then I have the stuff where I grab the info for that forum (name, description, etc) and all the data for the last post is there:

    $last_thread_title = $forumrow["forum_lastpost_title"];
    $last_thread_time = $forumrow["forum_lastpost_time"];
    $lastpost_username = $forumrow["forum_lastpost_username"];
    $lastpost_threadid = $forumrow["forum_lastpost_threadid"];

But I need to get rid of that, and get it from board_posts. The way it's set up in board_posts is that if it's a thread, post_parentpost is NULL, if it's a reply, then that field has the id of the thread (first post of the topic).  So, I need to grab the latest post_date, see which user posted that, THEN see if parentpost is NULL (if it's null then the last post is a new thread, so I can get all the info of the title and user there, but if it's not, then I need to get the info (title, id) of the first post in that thread (which can be found by seeing what post_parentpost is, looking up that ID and getting the title from it.

Does that make any sense? If so please help me out :(

Any help is greatly appreciated!!!!

OwnerDisplayName: staticsan


问:
jQuery Dialog Button Text
I am using jQuery UI to create an AJAX form.
My form is working correctly, however the text attribute of the buttons is not being displayed for some reason.

This is what I am using:

```<code>$( "#help_form" ).dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: [
            {
                text: "Send Request",
                id: "submit_help_form",
                click: function() {}
            }
        ]
    });
</code>```

The button is displayed at the bottom of the form, but no text is shown on it.

Can anyone see what I have done wrong?

Any advice appreciated.

Thanks.

答:
Your code works here, I could see the button label. What browser are you using?
I tried change some parts and it worked too:</p>

```<code>$(function(){
    $( "#help_form" ).dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "Send Request":function() {alert(0);}
            ,"Send Request2":function() {alert(2);}
        }
    });

    $( "#help_form" ).dialog('open');
});
</code>```

Title: jQuery Dialog Button Text

Body:
I am using jQuery UI to create an AJAX form.
My form is working correctly, however the text attribute of the buttons is not being displayed for some reason.

This is what I am using:

$( "#help_form" ).dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: [
            {
                text: "Send Request",
                id: "submit_help_form",
                click: function() {}
            }
        ]
    });

The button is displayed at the bottom of the form, but no text is shown on it.

Can anyone see what I have done wrong?

Any advice appreciated.

Thanks.

Body:
Your code works here, I could see the button label. What browser are you using?
I tried change some parts and it worked too:

$(function(){
    $( "#help_form" ).dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "Send Request":function() {alert(0);}
            ,"Send Request2":function() {alert(2);}
        }
    });

    $( "#help_form" ).dialog('open');
});


问:
How to run a downloaded Jupyter notebook on Google Colaboratory?
I am using Google Colaboratory & github.
I create a new Google Colab notebook, and I clone my github project into it using a simple !git clone <github_link> in the notebook.

Now, I have a Jupyter notebook in my github project that I need to run on Google Colab. How do I do that?

答:
```<code>import sys, os

sys.path.append('models/research')

sys.path.append('models/research/object_detection')
</code>```

It helped me. I was also looking  for it, and found it in this COLAB work

https://colab.research.google.com/drive/1EQ3Lt_ez-oKTtVMebh6Tm3XSyPPOHAf3#scrollTo=oC-_mxCxCNP6

Body:
import sys, os

sys.path.append('models/research')

sys.path.append('models/research/object_detection')

It helped me. I was also looking  for it, and found it in this COLAB work

https://colab.research.google.com/drive/1EQ3Lt_ez-oKTtVMebh6Tm3XSyPPOHAf3#scrollTo=oC-_mxCxCNP6


问:
How to restrict the access to undefined class/instance variable?
Python allowing access to undefined class/instance variable

I have defined a simple/empty python class as below. Now if I set a value for an undefined variable either with an instance variable or with class name, Python freely allows me to set the value for undefined variable and also allows me to access it like a instance or class variable without throwing any error. So in a nut shell, I am able to set undefined instance & class variables without any issues.

How do we restrict users from setting undefined instance and class variables in Python.

Here, how does Python treat these undefined variables (undefined_variable_1 and undefined_variable_2)? Are these treated as instance variable or class variable or something else?

```<code>class Test:

  pass

### #Now instantiate the class and try setting & it accessing undefined variables
t1 = Test()

t1.undefined_variable_1 = "Undefined class/instance variable being set through instance variable (t1)"

### #Access the undefined variable through instance variable
print(t1.undefined_variable_1)

Test.undefined_variable_2 = "Undefined class/instance variable being set through Class name (Test)"

### #Access the undefined variable through Class name
print(Test.undefined_variable_2)
</code>```

How do we restrict user from setting/accessing undefined instance/instance variable?

答:
For this purpose, you can set __slots__, which constrains the attributes that an instance of a class can have:

```<code>class Restricted:

    __slots__ = ('a', 'b')

r = Restricted()
r.a = 1  # okay
r.b = 2  # okay
r.c = 3  # error
</code>```

If you want to have the same functionality for the class object, you can create a custom metaclass and override __setattr__:

```<code>class RestrictedMeta(type):

    def __setattr__(self, attr, value):
        if attr in ('a', 'b'):
            super().__setattr__(attr, value)

        else:
            raise TypeError(f"Can't assign to attribute '{attr}' of class 'Restricted'")

class Restricted(metaclass=RestrictedMeta):
    pass

Restricted.a = 1  # okay
Restricted.b = 2  # okay
Restricted.c = 3  # error
</code>```

Body:
Python allowing access to undefined class/instance variable

I have defined a simple/empty python class as below. Now if I set a value for an undefined variable either with an instance variable or with class name, Python freely allows me to set the value for undefined variable and also allows me to access it like a instance or class variable without throwing any error. So in a nut shell, I am able to set undefined instance & class variables without any issues.

How do we restrict users from setting undefined instance and class variables in Python.

Here, how does Python treat these undefined variables (undefined_variable_1 and undefined_variable_2)? Are these treated as instance variable or class variable or something else?

class Test:

  pass

### #Now instantiate the class and try setting & it accessing undefined variables
t1 = Test()

t1.undefined_variable_1 = "Undefined class/instance variable being set through instance variable (t1)"

### #Access the undefined variable through instance variable
print(t1.undefined_variable_1)

Test.undefined_variable_2 = "Undefined class/instance variable being set through Class name (Test)"

### #Access the undefined variable through Class name
print(Test.undefined_variable_2)

How do we restrict user from setting/accessing undefined instance/instance variable?

Body:
For this purpose, you can set __slots__, which constrains the attributes that an instance of a class can have:

class Restricted:

    __slots__ = ('a', 'b')

r = Restricted()
r.a = 1  # okay
r.b = 2  # okay
r.c = 3  # error

If you want to have the same functionality for the class object, you can create a custom metaclass and override __setattr__:

class RestrictedMeta(type):

    def __setattr__(self, attr, value):
        if attr in ('a', 'b'):
            super().__setattr__(attr, value)

        else:
            raise TypeError(f"Can't assign to attribute '{attr}' of class 'Restricted'")

class Restricted(metaclass=RestrictedMeta):
    pass

Restricted.a = 1  # okay
Restricted.b = 2  # okay
Restricted.c = 3  # error


问:
Problem with loading data from the XML
I have XML file

```<code><contact>
<title>Flex</title>
<title>Flash</title>
<title>Illustrator</title>
<title>Photoshop</title>
<title>Dreamweawer</title>
<title>Flash player</title>
</code>```

in my application is tilelist which loads data from XML
why I can not take the name of the selected item in the TextInput?

```<code><s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" applicationComplete="contactsService.send()">
<fx:Declarations>
<mx:HTTPService id="contactsService"
                resultFormat="e4x"
                url="contacts.xml"/>
</fx:Declarations>

<fx:Script>
    <![CDATA[
        import mx.events.ItemClickEvent;
        import mx.events.ListEvent;

        public function SomthingSelected ():void {
            txt.text = this.tileList.selectedItem.@title;
        }

    ]]>
</fx:Script>
<mx:TileList id="tileList"
             dataProvider="{contactsService.lastResult.title}"
             columnCount="4"
             columnWidth="125"
             rowCount="2"
             rowHeight="100"
             verticalScrollPolicy="on"
             itemClick="SomthingSelected ()"/>

<s:TextInput x="10" y="223" id="txt" text="Sergii hi"/>
</code>```

Help me please (

答:
You don't need to specify the tag as the data is already there.  Try doing this:</p>

```<code>private function SomthingSelected ():void {
            txt.text = this.tileList.selectedItem.toString();
        }
</code>```

Title: Problem with loading data from the XML

Body:
I have XML file

<contact>
<title>Flex</title>
<title>Flash</title>
<title>Illustrator</title>
<title>Photoshop</title>
<title>Dreamweawer</title>
<title>Flash player</title>

in my application is tilelist which loads data from XML
why I can not take the name of the selected item in the TextInput?

<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" applicationComplete="contactsService.send()">
<fx:Declarations>
<mx:HTTPService id="contactsService"
                resultFormat="e4x"
                url="contacts.xml"/>
</fx:Declarations>

<fx:Script>
    <![CDATA[
        import mx.events.ItemClickEvent;
        import mx.events.ListEvent;

        public function SomthingSelected ():void {
            txt.text = this.tileList.selectedItem.@title;
        }

    ]]>
</fx:Script>
<mx:TileList id="tileList"
             dataProvider="{contactsService.lastResult.title}"
             columnCount="4"
             columnWidth="125"
             rowCount="2"
             rowHeight="100"
             verticalScrollPolicy="on"
             itemClick="SomthingSelected ()"/>

<s:TextInput x="10" y="223" id="txt" text="Sergii hi"/>

Help me please (

Body:
You don't need to specify the tag as the data is already there.  Try doing this:

private function SomthingSelected ():void {
            txt.text = this.tileList.selectedItem.toString();
        }


问:
R. Split column with sequential values into 2 columns with consecutive start and end positions
I have a data frame A like this one:

```<code>CHR POS X Y
1 447892 0.994 0.994
1 651929 0.988 1.982
1 741566 0.982 2.964
1 741566+n
...
2 2000 0.347 0.347
2 3444 0.421 0.768
2 3444+m
...
</code>```

Here, observations are grouped by CHR, whereas POS has an ordered sequence of values. Y is the cumulative sum of X. For each row in CHR, I want to split POS into two columns N1 and N2 obtaining something like this:

```<code>CHR N1 N2 X Y
1 447892 651929 0.994 0.994
1 651929 741566 0.988 1.982
1 741566 741566+n 0.982 2.964
2 2000 3444 0.347 0.347
2 3444 3444+m 0.421 0.768
</code>```

Body:
I have a data frame A like this one:

CHR POS X Y
1 447892 0.994 0.994
1 651929 0.988 1.982
1 741566 0.982 2.964
1 741566+n
...
2 2000 0.347 0.347
2 3444 0.421 0.768
2 3444+m
...

Here, observations are grouped by CHR, whereas POS has an ordered sequence of values. Y is the cumulative sum of X. For each row in CHR, I want to split POS into two columns N1 and N2 obtaining something like this:

CHR N1 N2 X Y
1 447892 651929 0.994 0.994
1 651929 741566 0.988 1.982
1 741566 741566+n 0.982 2.964
2 2000 3444 0.347 0.347
2 3444 3444+m 0.421 0.768

Body:
An option would be to take the lead of the 'POS' after grouping by 'CHR'

library(dplyr)
df1 %>%
   group_by(CHR) %>%
   transmute(X, Y, N1 = POS, N2 = lead(POS)) %>%
   na.omit
# A tibble: 4 x 5
# Groups:   CHR [2]
#    CHR     X     Y     N1     N2
#  <int> <dbl> <dbl>  <int>  <int>
#1     1 0.994 0.994 447892 651929
#2     1 0.988 1.98  651929 741566
#3     1 0.982 2.96  741566 741566
#4     2 0.347 0.347   2000   3444

data

df1 <- structure(list(CHR = c(1L, 1L, 1L, 1L, 2L, 2L), POS = c(447892L,
651929L, 741566L, 741566L, 2000L, 3444L), X = c(0.994, 0.988,
0.982, 0.55, 0.347, 0.421), Y = c(0.994, 1.982, 2.964, 2.54,
0.347, 0.768)), class = "data.frame", row.names = c(NA, -6L))


问:
Create new elements dynamically
I am trying to create new elements with name and time. I want to let the user customize them(ex. can be able to change color).

The dropdown option is only working for the first class it changes the color but the rest of them are not working. How can I fix it?

function f_color() {
  var x = document.getElementById('Tcolor1').value;
  window.alert(x);
  if (x == 0) {
    document.getElementById('input1').style.color = "black";
    document.getElementById('input2').style.color = "black";
    document.getElementById('input3').style.color = "black";
  }
  if (document.getElementById('Tcolor').value == 1) {
    document.getElementById('input1').style.color = "red";
    document.getElementById('input2').style.color = "red";
    document.getElementById('input3').style.color = "red";
  }
  if (document.getElementById('Tcolor').value == 2) {
    document.getElementById('input1').style.color = "blue";
    document.getElementById('input2').style.color = "blue";
    document.getElementById('input3').style.color = "blue";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="btn2">Add Another Class</button>

  <form>

    <select class="form-control" id="Tcolor" name="Tcolor" style="color:black;

           font-size: 20px; " onchange="f_color()">

      <option value=0>black </option>

      <option value=1>red</option>

      <option value=2>blue </option>

    </select>

  </form>

  <form>
    <input id="input1" name="className"><br>
    <input id="input2" name="classTime"><br>
    <input id="input3" name="classNote"><br>
  </form></code>```

答:
<button id="btn2">Add Another Class</button>

    <form>

     <select class="form-control"  id="Tcolor" name = "Tcolor" style="color:black;

       font-size: 20px; "  onchange="f_color()"  >

            <option value=0 >black </option>

            <option value=1 >red</option>

            <option value=2 >blue </option>

        </select >

    </form>

        <form>
            <input id="input1"   name="className" >

        <input id="input2"   name="classTime" >

        <input id="input3"   name="classNote" >

      </form>

      ```

remove comment

Title: Create new elements dynamically

Body:
I am trying to create new elements with name and time. I want to let the user customize them(ex. can be able to change color).

The dropdown option is only working for the first class it changes the color but the rest of them are not working. How can I fix it?

function f_color() {
  var x = document.getElementById('Tcolor1').value;
  window.alert(x);
  if (x == 0) {
    document.getElementById('input1').style.color = "black";
    document.getElementById('input2').style.color = "black";
    document.getElementById('input3').style.color = "black";
  }
  if (document.getElementById('Tcolor').value == 1) {
    document.getElementById('input1').style.color = "red";
    document.getElementById('input2').style.color = "red";
    document.getElementById('input3').style.color = "red";
  }
  if (document.getElementById('Tcolor').value == 2) {
    document.getElementById('input1').style.color = "blue";
    document.getElementById('input2').style.color = "blue";
    document.getElementById('input3').style.color = "blue";
  }
}

<button id="btn2">Add Another Class</button>

  <form>

    <select class="form-control" id="Tcolor" name="Tcolor" style="color:black;

           font-size: 20px; " onchange="f_color()">

      <option value=0>black </option>

      <option value=1>red</option>

      <option value=2>blue </option>

    </select>

  </form>

  <form>
    <input id="input1" name="className">

    <input id="input2" name="classTime">

    <input id="input3" name="classNote">

  </form>

Body:
<button id="btn2">Add Another Class</button>

    <form>

     <select class="form-control"  id="Tcolor" name = "Tcolor" style="color:black;

       font-size: 20px; "  onchange="f_color()"  >

            <option value=0 >black </option>

            <option value=1 >red</option>

            <option value=2 >blue </option>

        </select >

    </form>

        <form>
            <input id="input1"   name="className" ><br>
        <input id="input2"   name="classTime" ><br>
        <input id="input3"   name="classNote" ><br>
      </form>

      <script>

          function f_color(){
         var x=document.getElementById('Tcolor1').value;
          window.alert(x);
        if ( x == 0) {
        document.getElementById('input1').style.color = "black";
        document.getElementById('input2').style.color = "black";
        document.getElementById('input3').style.color = "black";
    }
    if (document.getElementById('Tcolor').value ==  1 ) {
        document.getElementById('input1').style.color = "red";
        document.getElementById('input2').style.color = "red";
        document.getElementById('input3').style.color = "red";
    }
    if (document.getElementById('Tcolor').value ==  2) {
        document.getElementById('input1').style.color = "blue";
        document.getElementById('input2').style.color = "blue";
        document.getElementById('input3').style.color = "blue";
  }
  }
   </script>

remove comment


问:
How to auto play youtube video in amazon fire tv
I used this url http://www.youtube.com/embed/uGNhirSbWW0?autoplay=1 to auto play this video in my amazon fireTv app using web View, i am getting the video but the video is not playing automatically? How to auto play the video in amazon firetv. any other way to play the youtube video

答:
For someone who stumbled upon this problem when using Amazon Web Apps:

Somewhere in your code load Iframe Player API code

```<code>var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</code>```

Create an iframe and call event.target.playVideo() when onReady event fires

```<code>var player;
function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }
</code>```

Reference

Body:
For someone who stumbled upon this problem when using Amazon Web Apps:

Somewhere in your code load Iframe Player API code

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

Create an iframe and call event.target.playVideo() when onReady event fires

var player;
function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }

Reference


问:
Can I make Wordpress searchbar filter to give only articles from blog and not from woocommerce?
When using the searchbar in the "news" page of my Wordpress, it displays posts from the blog but also posts that are products from Woocommerce, or other pages / content. I would like it to display only blog posts.

I haven't found any solution yet. Also, Wordpress won't let me update the php files of the theme, so I think I need on-site settings / plugins.

Here is the news page : https://champagne-oudart.com/actualites/
The client wanted the news categories to be years.

答:
I recommend to use a plugin like Relevanssi https://wordpress.org/plugins/relevanssi/

It enables you to limit/control the search in many ways, also the one you asked for, and it's very simple to handle.


问:
How can I use breakpoints inside createMuiTheme? Material UI & React.js
Maybe not the right approach but I want to create some 'global' styles for headings for example. Something like this:

```<code>const myTheme = createMuiTheme({
    headings: {
        h1: {
            fontSize: 28,
            // Obviously this does not work...
            [theme.breakpoints.down('sm')]: {
                fontSize: 24
            },
        },
        h2: {
            fontSize: 24,
        }
    }
}
</code>```

then I can use them in my components like this:

```<code>const styles = (theme) => ({
    myElement: {
        ...theme.headings.h1,
        // ... other styles
    }
}
</code>```

This does work but the issue I face is I want the headings to be responsive and respect Material UI's breakpoints, but I can't use them inside the createMuiTheme itself? What is the way to do this correctly so I can just spread in my styles that INCLUDE the responsive styles all in one?

答:
You can use the createBreakpoints method

Example:

```<code>// theme.js

import createBreakpoints from '@material-ui/core/styles/createBreakpoints'
import { createMuiTheme } from '@material-ui/core/styles'

const breakpoints = createBreakpoints({})

const theme = createMuiTheme({
  overrides: {
    MuiTab: {
      root: {
        [breakpoints.up('md')]: {
          minWidth: '200px',
          backgroundColor: 'yellow',
        },
      },
    },
  },
})

export default theme
</code>```

(tested: material-ui 4.0.1)

Body:
Maybe not the right approach but I want to create some 'global' styles for headings for example. Something like this:

const myTheme = createMuiTheme({
    headings: {
        h1: {
            fontSize: 28,
            // Obviously this does not work...
            [theme.breakpoints.down('sm')]: {
                fontSize: 24
            },
        },
        h2: {
            fontSize: 24,
        }
    }
}

then I can use them in my components like this:

const styles = (theme) => ({
    myElement: {
        ...theme.headings.h1,
        // ... other styles
    }
}

This does work but the issue I face is I want the headings to be responsive and respect Material UI's breakpoints, but I can't use them inside the createMuiTheme itself? What is the way to do this correctly so I can just spread in my styles that INCLUDE the responsive styles all in one?

Body:
You can use the createBreakpoints method

Example:

// theme.js

import createBreakpoints from '@material-ui/core/styles/createBreakpoints'
import { createMuiTheme } from '@material-ui/core/styles'

const breakpoints = createBreakpoints({})

const theme = createMuiTheme({
  overrides: {
    MuiTab: {
      root: {
        [breakpoints.up('md')]: {
          minWidth: '200px',
          backgroundColor: 'yellow',
        },
      },
    },
  },
})

export default theme

(tested: material-ui 4.0.1)


问:
How to set a variable value based on if-statement in batch file
I am trying to assign a value to a variable based on an if-else statement in a batch file. I am searching a text file for a string and if the string is found I need to assign a certain value to the variable.

I have used the if-else statement to assign the value but after exiting the if-else statement when I try to echo the variable i get value as 0

```<code>@echo off

set "logfile=results.txt"
find /n /i "Orientation      : 0" "%logfile%" >nul
if %errorlevel% equ 0 (
    set org = "landscape"

) else (
    set org = "portrait"

)

echo %org%
</code>```

The output for this should be 'landscape', I have verified that the string does exist in the file. For some reason, I am getting 0 as the output.

答:
Remove the space around the equal sign:</p>

```<code>set org="landscape"
set org="portrait"
</code>```

Body:
I am trying to assign a value to a variable based on an if-else statement in a batch file. I am searching a text file for a string and if the string is found I need to assign a certain value to the variable.

I have used the if-else statement to assign the value but after exiting the if-else statement when I try to echo the variable i get value as 0

@echo off

set "logfile=results.txt"
find /n /i "Orientation      : 0" "%logfile%" >nul
if %errorlevel% equ 0 (
    set org = "landscape"

) else (
    set org = "portrait"

)

echo %org%

The output for this should be 'landscape', I have verified that the string does exist in the file. For some reason, I am getting 0 as the output.

Body:
Remove the space around the equal sign:

set org="landscape"
set org="portrait"


问:
rubocop on VScode not working.Error "rubocop is not executable"
Recently I installed rubocop on vscode. However, it doesn't work.Error message is below.

```<code>rubocop is not excutable
execute path is empty! please check ruby.rubocop.executePath
</code>```

How should I fix it? I searched some articles, never solved...

cf. vscode-ruby-rubocop
https://github.com/misogi/vscode-ruby-rubocop

答:
The accepted answer didn't work for me. However, I did find a comment by jdarnok on this GitHub issue that worked for me.

First, to get the user's path of the program file, I ran:

rbenv which rubocop

which gave me this result:

/Users/<your username>/.rbenv/versions/2.6.2/gemsets/Rails4.2_EnergyLink/bin/rubocop

Then I ran:

which rubocop

which gave me this result:

/Users/<your username>/.rbenv/shims/rubocop

SOLUTION

In the settings of VS Code under Ruby > Rubocop: Execute Path I pasted:

/Users/<your username>/.rbenv/shims/

Other potential solutions

This Stackoverflow post refers to a few other potential solutions, such as:

Replace bin in the PATH with wrappers

Refresh executable hooks

Update bundler

Update gems

Body:
Recently I installed rubocop on vscode. However, it doesn't work.Error message is below.

rubocop is not excutable
execute path is empty! please check ruby.rubocop.executePath

How should I fix it? I searched some articles, never solved...

cf. vscode-ruby-rubocop
https://github.com/misogi/vscode-ruby-rubocop


问:
Component input parameter is received as "undefined" but a value has been specified
I have the following TableMultipleEditComponent in my Angular application:

```<code>export class TableMultipleEditComponent implements OnInit {
    @Output() emitMultipleClose: EventEmitter<boolean> = new EventEmitter<
    boolean
    >();
    @Output() emitHoverAndData: EventEmitter<any> = new EventEmitter<any>();

    showBar: boolean;
    @Input()
    table: Table;
    @Input()
    checkedRows;
    @Input()
    recordId: string ;

    ngOnInit() {
        console.log(">> rId-oninit" , this.recordId) ;
        .....
    }
}
</code>```

And in the html I am passing the [recordId] input value as _INSERT_:

```<code><app-table-multiple-edit
     [table]="table"
     [checkedRows]="checkedRows"
     [recordId]="_INSERT_"
     (emitMultipleClose)="closeSingleRowInsert($event)"
     (emitHoverAndData)="showMultipleEditStatus($event)">
</app-table-multiple-edit>
</code>```

When I run this in the console I always get >> rId-oninit undefined

I have tried using other values like "-1" and cleaning the cache, as you probably guess that means I am running out of options.

What am I doing wrong ? what can be changing the value between my html and the ngOnInit method

答:
In Angular, when you use [input]="data" in your HTML, data is basically a template expression. Template expressions are similar to JavaScript.

Angular executes the data and assigns it to a property of a binding target, here input. This allows us to dynamically change the value assigned to the input from the component by changing data.

This is similar to interpolation in AngularJS, where in order to display {{data}} in your HTML, data needs to be defined in your controller.

In your case, [recordId]="_INSERT_", recordId is the Input() binding target and _INSERT_ is your template expression. Angular tries to execute this expression but since you have not defined _INSERT_ in your component, it evaluates to undefined.

If you require to pass a constant string to your @Input(), simply pass a string as the expression like so [recordId]="'This is just an example'". If you require it to be dynamic, you should assign a value to _INSERT_ in your component.

Since the template expression is similar to JavaScript, you may even pass a conditional expression if required, [recordId]="recordExists ? '1' : null"

Hope this answers your question.

For more info, here's a reference to the documentation: https://angular.io/guide/template-syntax#template-expressions

Body:
I have the following TableMultipleEditComponent in my Angular application:

export class TableMultipleEditComponent implements OnInit {
    @Output() emitMultipleClose: EventEmitter<boolean> = new EventEmitter<
    boolean
    >();
    @Output() emitHoverAndData: EventEmitter<any> = new EventEmitter<any>();

    showBar: boolean;
    @Input()
    table: Table;
    @Input()
    checkedRows;
    @Input()
    recordId: string ;

    ngOnInit() {
        console.log(">> rId-oninit" , this.recordId) ;
        .....
    }
}

And in the html I am passing the [recordId] input value as _INSERT_:

<app-table-multiple-edit
     [table]="table"
     [checkedRows]="checkedRows"
     [recordId]="_INSERT_"
     (emitMultipleClose)="closeSingleRowInsert($event)"
     (emitHoverAndData)="showMultipleEditStatus($event)">
</app-table-multiple-edit>

When I run this in the console I always get >> rId-oninit undefined

I have tried using other values like "-1" and cleaning the cache, as you probably guess that means I am running out of options.

What am I doing wrong ? what can be changing the value between my html and the ngOnInit method


问:
The value of the variable don't show in the other class
I make a program in Eclipse to Android and I have a problem. I have this class where I show the artists. Inside the onClick method I want to send the "value" of the clicked listitem.

```<code>...public class ArtistActivity extends ListActivity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview);

    String[] artists = getResources().getStringArray(R.array.artists_array);
    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, artists));

    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {
                StringActivity sA = new StringActivity();
                sA.setArtist(((TextView) v).getText().toString());
                String asd = sA.getArtist();
                //Toast.makeText(getApplicationContext(), asd/*((TextView) v).getText()*/, Toast.LENGTH_SHORT).show();
                Intent i = new Intent().setClass(getApplicationContext(), AlbumActivity.class);
                startActivity(i);
            }
    });
}}
</code>```

Inside onClick when I do it with Toast then it shows the picked item, but in the other class don't. Here are the code where I store the value:

```<code>public class StringActivity {
private String artist="";

public String getArtist() {
    return(artist);
}

public void setArtist(String artist) {
    this.artist=artist;
}

public String toString() {
    return(getArtist());
}}
</code>```

And here is the other class where it should show the value:

```<code>public class AlbumActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    StringActivity sA = new StringActivity();

    String asd = sA.getArtist();
    TextView textview = new TextView(this);
    textview.setText("Hello " + asd + " World!");
    setContentView(textview);
}}
</code>```

The hello world is there just because to see that there is nothing wrong with the textview. Maybe the problem is that it don't refresh (it's stay the same from the launch of the program - because when I give a value for the artist string in the StringActivity class then it shows, but when I click on an item it stay the same) or there is another problem?
Thanks!

答:
The StringActivity you create in your onClick listener is only visible inside the listener, not in your second activity! You have to use Intent.putExtra() to push some extras into the Intent, then use Intent.getExtras() in your second activity to get them back.

So change the onClick to:

```<code>public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
   String artist = ((TextView) v).getText().toString();
   Intent i = new Intent().setClass(ArtistActivity.this, AlbumActivity.class);
   i.putExtra("artist", artist);
   startActivity(i);
}
</code>```

And in the second activity's onCreate you can do:

```<code>public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   Bundle extras = getIntent().getExtras();

   String asd = extras.getString("artist");
   TextView textview = new TextView(this);
   textview.setText("Hello " + asd + " World!");
   setContentView(textview);
}
</code>```

Body:
I make a program in Eclipse to Android and I have a problem. I have this class where I show the artists. Inside the onClick method I want to send the "value" of the clicked listitem.

...public class ArtistActivity extends ListActivity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview);

    String[] artists = getResources().getStringArray(R.array.artists_array);
    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, artists));

    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {
                StringActivity sA = new StringActivity();
                sA.setArtist(((TextView) v).getText().toString());
                String asd = sA.getArtist();
                //Toast.makeText(getApplicationContext(), asd/*((TextView) v).getText()*/, Toast.LENGTH_SHORT).show();
                Intent i = new Intent().setClass(getApplicationContext(), AlbumActivity.class);
                startActivity(i);
            }
    });
}}

Inside onClick when I do it with Toast then it shows the picked item, but in the other class don't. Here are the code where I store the value:

public class StringActivity {
private String artist="";

public String getArtist() {
    return(artist);
}

public void setArtist(String artist) {
    this.artist=artist;
}

public String toString() {
    return(getArtist());
}}

And here is the other class where it should show the value:

public class AlbumActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    StringActivity sA = new StringActivity();

    String asd = sA.getArtist();
    TextView textview = new TextView(this);
    textview.setText("Hello " + asd + " World!");
    setContentView(textview);
}}

The hello world is there just because to see that there is nothing wrong with the textview. Maybe the problem is that it don't refresh (it's stay the same from the launch of the program - because when I give a value for the artist string in the StringActivity class then it shows, but when I click on an item it stay the same) or there is another problem?
Thanks!

Body:
The StringActivity you create in your onClick listener is only visible inside the listener, not in your second activity! You have to use Intent.putExtra() to push some extras into the Intent, then use Intent.getExtras() in your second activity to get them back.

So change the onClick to:

public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
   String artist = ((TextView) v).getText().toString();
   Intent i = new Intent().setClass(ArtistActivity.this, AlbumActivity.class);
   i.putExtra("artist", artist);
   startActivity(i);
}

And in the second activity's onCreate you can do:

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   Bundle extras = getIntent().getExtras();

   String asd = extras.getString("artist");
   TextView textview = new TextView(this);
   textview.setText("Hello " + asd + " World!");
   setContentView(textview);
}


问:
I have a DF with 2 columns. I wanna do a boolean check on it
I have a DF that has 3 columns and i wanna perform a Boolean check. The code is shown below.

```<code>import pandas as pd
df = pd.DataFrame({
    'Col1':[A,A,A,B,B,C,C,C],
    'Col2':[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3, 4, 5,6,7],[1, 2, 3, 4, 5,6,7] ]
    'Col3': [[1, 2, 3, 4],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9],[1, 2, 3, 4, 5],[1, 2, 3], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3],[1, 2, 3, 4] ]
})
</code>```

I want a DF that gives me for a unique value of Col1 and if one row of Col2, Col3 are equal, print True, else False.  The result i would like to see is:

```<code>'Col1' 'Col2'                         'Col3'          'Col4'
  A    [1,2,3,4,5,6,7,8,9,10,11,12]  [1,2,3,4]         False

print(map(type, df['Col2']) == map(type,df['Col3']))
</code>```

This returned me value true, but I want it as a new column Col4 in the df

For multiple codes i tried , I always found errors as unhashable type: 'list'

答:
Convert to Strings to allow the comparison:</p>

```<code>    df['Col4'] = df.Col2.map(str) == df.Col3.map(str)
</code>```

Body:
I have a DF that has 3 columns and i wanna perform a Boolean check. The code is shown below.

import pandas as pd
df = pd.DataFrame({
    'Col1':[A,A,A,B,B,C,C,C],
    'Col2':[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3, 4, 5,6,7],[1, 2, 3, 4, 5,6,7] ]
    'Col3': [[1, 2, 3, 4],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9],[1, 2, 3, 4, 5],[1, 2, 3], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3],[1, 2, 3, 4] ]
})

I want a DF that gives me for a unique value of Col1 and if one row of Col2, Col3 are equal, print True, else False.  The result i would like to see is:

'Col1' 'Col2'                         'Col3'          'Col4'
  A    [1,2,3,4,5,6,7,8,9,10,11,12]  [1,2,3,4]         False

print(map(type, df['Col2']) == map(type,df['Col3']))

This returned me value true, but I want it as a new column Col4 in the df

For multiple codes i tried , I always found errors as unhashable type: 'list'

Body:
Convert to Strings to allow the comparison:

    df['Col4'] = df.Col2.map(str) == df.Col3.map(str)


问:
Parse file name and path from full path
I need to parse file name and file path from full path using SQL Query.

Eg. Fullpath - \SERVER\D$\EXPORTFILES\EXPORT001.csv

```<code>FileName        Path
EXPORT001.csv   \\SERVER\D$\EXPORTFILES\
</code>```

答:
For anyone that wants to perform this operation and also trim off the file extension:

```<code>SELECT
    LEFT(
        RIGHT(<FIELD>, CHARINDEX('\', REVERSE(<FIELD>)) - 1),
        LEN(RIGHT(<FIELD>, CHARINDEX('\', REVERSE(<FIELD>)) - 1)) -
          CHARINDEX('.', REVERSE(<FIELD>))
    )
FROM <TABLE>
</code>```

Note that this doesn't allow for when there are no slashes - it will need modification if this is the case

Title: Parse file name and path from full path

Body:
I need to parse file name and file path from full path using SQL Query.

Eg. Fullpath - \SERVER\D$\EXPORTFILES\EXPORT001.csv

FileName        Path
EXPORT001.csv   \\SERVER\D$\EXPORTFILES\

Body:
For anyone that wants to perform this operation and also trim off the file extension:

SELECT
    LEFT(
        RIGHT(<FIELD>, CHARINDEX('\', REVERSE(<FIELD>)) - 1),
        LEN(RIGHT(<FIELD>, CHARINDEX('\', REVERSE(<FIELD>)) - 1)) -
          CHARINDEX('.', REVERSE(<FIELD>))
    )
FROM <TABLE>

Note that this doesn't allow for when there are no slashes - it will need modification if this is the case


问:
How to get the type of an object in a collection of objects at runtime?
In my code I get the type of an object (Party object) in a for loop and get the property info of a particular property "firstname". All the objects in the Parties[] collection return the same type so I would like to get the type outside of do while loop only once and still need to be able to get the property "firstname" from the correct party object.
Is it possible to do this way? Thanks for any help.</p>

```<code>public List<Party> Parties { get; set; }

PropertyInfo info = null;

i = 1
do
{

    foreach (Field field in TotalFields)
    {

        info = Parties[i - 1].GetType().GetProperty("firstname");

        //some other code here

    }
i++;
} while (i <= Parties.Count);
</code>```

答:
When you get the value for a property through a PropertyInfo object, you need to pass an object instance from which to fetch the value. This means that you can reuse the same PropertyInfo instance for several objects, given that they are of the same type as the PropertyInfo was created for:

```<code>// Note how we get the PropertyInfo from the Type itself, not an object
// instance of that type.
PropertyInfo propInfo = typeof(YourType).GetProperty("SomeProperty");

foreach (YourType item in SomeList)
{
    // this assumes that YourType.SomeProperty is a string, just as an example
    string value = (string)propInfo.GetValue(item, null);
    // do something sensible with value
}
</code>```

Your question is tagged as being C# 3, but for completeness it's worth mentioning that this can be made somewhat simpler in C# 4 by using dynamic:

```<code>foreach (dynamic item in SomeList)
{
    string value = item.SomeProperty;
    // do something sensible with value
}
</code>```

Body:
In my code I get the type of an object (Party object) in a for loop and get the property info of a particular property "firstname". All the objects in the Parties[] collection return the same type so I would like to get the type outside of do while loop only once and still need to be able to get the property "firstname" from the correct party object.
Is it possible to do this way? Thanks for any help.

public List<Party> Parties { get; set; }

PropertyInfo info = null;

i = 1
do
{

    foreach (Field field in TotalFields)
    {

        info = Parties[i - 1].GetType().GetProperty("firstname");

        //some other code here

    }
i++;
} while (i <= Parties.Count);

Body:
When you get the value for a property through a PropertyInfo object, you need to pass an object instance from which to fetch the value. This means that you can reuse the same PropertyInfo instance for several objects, given that they are of the same type as the PropertyInfo was created for:

// Note how we get the PropertyInfo from the Type itself, not an object
// instance of that type.
PropertyInfo propInfo = typeof(YourType).GetProperty("SomeProperty");

foreach (YourType item in SomeList)
{
    // this assumes that YourType.SomeProperty is a string, just as an example
    string value = (string)propInfo.GetValue(item, null);
    // do something sensible with value
}

Your question is tagged as being C# 3, but for completeness it's worth mentioning that this can be made somewhat simpler in C# 4 by using dynamic:

foreach (dynamic item in SomeList)
{
    string value = item.SomeProperty;
    // do something sensible with value
}


问:
How to simulate key presses in JS
I wish to click on an  and make the browser simulate the typing out of a variable + [ENTER]. This should basically simulate the same thing that would happen if a scanner scanned a barcode

I'm developing an add-on for a webapp that we use at work. This work includes needing to scan barcodes which I've gotten to show on screen and we can scan, however in some instances it has proven to be a little difficult to scan. I'd like to be able to click on the barcode that is generated and have it simulate keystrokes. The characters don't need to end up in any input field as I assume the webapp is set to capture keystrokes for the whole window. I just need the keystrokes to be entered pretty fast to simulate a barcode scanner.

The jsfiddle provided currently has the variable being sent to an input field but that is not necessary for the final results.

I'd like to keep this vanilla javascript as I'm still learning it and don't wish to move on to Jquery until i have my feet firmly planted in JS.

https://jsfiddle.net/pshock13/o2gtzaj5/215

```<code>document.getElementById('barcode').addEventListener('click', function() {
      //this is where I want theBarcode to be typed out + [ENTER] automatically.
      main_input.value = theBarcode;
    })
</code>```

答:
You can simulate a keypress by dispatching a KeyboardEvent for keydown and keyup.

E.g. simulating keypresses for your barcode:

```<code>document.getElementById('barcode').addEventListener('click', function() {
    main_input.value = theBarcode;

    [...theBarcode].forEach(function(c) {
        window.dispatchEvent(new KeyboardEvent('keydown',{'key':c}));
        window.dispatchEvent(new KeyboardEvent('keyup',{'key':c}));
    });

    window.dispatchEvent(new KeyboardEvent('keydown',{'key':'Enter'}));
    window.dispatchEvent(new KeyboardEvent('keyup',{'key':'Enter'}));
});
</code>```

Title: How to simulate key presses in JS

Body:
I wish to click on an  and make the browser simulate the typing out of a variable + [ENTER]. This should basically simulate the same thing that would happen if a scanner scanned a barcode

I'm developing an add-on for a webapp that we use at work. This work includes needing to scan barcodes which I've gotten to show on screen and we can scan, however in some instances it has proven to be a little difficult to scan. I'd like to be able to click on the barcode that is generated and have it simulate keystrokes. The characters don't need to end up in any input field as I assume the webapp is set to capture keystrokes for the whole window. I just need the keystrokes to be entered pretty fast to simulate a barcode scanner.

The jsfiddle provided currently has the variable being sent to an input field but that is not necessary for the final results.

I'd like to keep this vanilla javascript as I'm still learning it and don't wish to move on to Jquery until i have my feet firmly planted in JS.

https://jsfiddle.net/pshock13/o2gtzaj5/215

document.getElementById('barcode').addEventListener('click', function() {
      //this is where I want theBarcode to be typed out + [ENTER] automatically.
      main_input.value = theBarcode;
    })

Body:
You can simulate a keypress by dispatching a KeyboardEvent for keydown and keyup.

E.g. simulating keypresses for your barcode:

document.getElementById('barcode').addEventListener('click', function() {
    main_input.value = theBarcode;

    [...theBarcode].forEach(function(c) {
        window.dispatchEvent(new KeyboardEvent('keydown',{'key':c}));
        window.dispatchEvent(new KeyboardEvent('keyup',{'key':c}));
    });

    window.dispatchEvent(new KeyboardEvent('keydown',{'key':'Enter'}));
    window.dispatchEvent(new KeyboardEvent('keyup',{'key':'Enter'}));
});


问:
Error - Unexpected } at the end of While Loop
I'm using while true loop to constantly check run this script. After adding the if expression with whitelist ahk gives an error about unexpected } at the end of code. As far as I know there should be }.

Using Loop command gives the same error.
Removing the problematic } at the end causes the code running in background but not doing anything.

```<code>;Setup
Sleep, 1000
whiteList = "none"

;Main Loop
While True
{
    siteName = YouTube
    WinGetActiveTitle, tabName
    Sleep, 10000

    if tabName = %whiteList%{
        Continue
    }

    ;If current website is Youtube, ask if am I supposted to be here
    if InStr(tabName, siteName){
        Sleep, 10000
        MsgBox, 292, Reality Check, Should you do this?
        IfMsgBox, Yes
        {
            whiteList = tabName
        }

        ;Close tab in mozilla
        else
        {
            WinActivate, %tabName%
            Sleep, 10
            Send ^w
        }
    }
}
</code>```

Code is unfinished, It should run in background and when the user is using YouTube fore some time it should ask him whether is he supposted to watch Youtube.

If he clicks yes, the program should ignore that specific page.
Else it should close it.

答:
The % around the whiteList-var shouldn't be there. When I wrote it like below it seems to work:

```<code>if tabName = whiteList
    Continue
</code>```

Also the whiteList = tabName will just assign the string "tabName" to whiteList. Use whiteList := tabName for assigning, and if var1 = var2 for comparison.

Body:
I'm using while true loop to constantly check run this script. After adding the if expression with whitelist ahk gives an error about unexpected } at the end of code. As far as I know there should be }.

Using Loop command gives the same error.
Removing the problematic } at the end causes the code running in background but not doing anything.

;Setup
Sleep, 1000
whiteList = "none"

;Main Loop
While True
{
    siteName = YouTube
    WinGetActiveTitle, tabName
    Sleep, 10000

    if tabName = %whiteList%{
        Continue
    }

    ;If current website is Youtube, ask if am I supposted to be here
    if InStr(tabName, siteName){
        Sleep, 10000
        MsgBox, 292, Reality Check, Should you do this?
        IfMsgBox, Yes
        {
            whiteList = tabName
        }

        ;Close tab in mozilla
        else
        {
            WinActivate, %tabName%
            Sleep, 10
            Send ^w
        }
    }
}

Code is unfinished, It should run in background and when the user is using YouTube fore some time it should ask him whether is he supposted to watch Youtube.

If he clicks yes, the program should ignore that specific page.
Else it should close it.

Body:
The % around the whiteList-var shouldn't be there. When I wrote it like below it seems to work:

if tabName = whiteList
    Continue

Also the whiteList = tabName will just assign the string "tabName" to whiteList. Use whiteList := tabName for assigning, and if var1 = var2 for comparison.


问:
ruby exact number log (logarithm) function
As the base 10 logarithm of 1000 is 3 you might expect Math::log(1000, 10) to return 3. Instead it returns 2.9999999999999996.

This is due to the fact floats in Ruby are not exact numbers as discussed for example here:

Float isn't an exact number representation, as stated in the ruby
  docs:

Float objects represent inexact real numbers using the native architecture's double-precision floating point representation.

This not ruby fault, as floats can only be represented by a fixed
  number of bytes and therefor cannot store decimal numbers correctly.

Alternatively, you can use ruby Rational or BigDecimal

Sadly when calling Math::log(BigDecimal('1000'), BigDecimal('10')) the result is exactly the same. Same goes for Math::log(Rational('1000'), Rational('10')). There is also a BigMath::log which does something completely different.

Now the big question is: how can we calculate the base 10 logarithm of 1000 such that we get the exact result: 3?

答:
You can use the change of base formula: If you can calculate a log with base d but you need log base b then log_b(n) = log_d(n) / log_d(b). So:

```<code>> BigMath.log(1000, 50) / BigMath.log(10, 50)
=> 0.3e1
</code>```

Now let's try with something that needs more precision:

```<code>> BigMath.log(999, 50) / BigMath.log(10, 50)
=> 0.2999565488225982308693534399304475375583359282738400141107276831709276456467950527020061473296516829369378125e1
</code>```

Compare that with, say, https://www.wolframalpha.com/input/?i=log_10+999

Body:
You can use the change of base formula: If you can calculate a log with base d but you need log base b then log_b(n) = log_d(n) / log_d(b). So:

> BigMath.log(1000, 50) / BigMath.log(10, 50)
=> 0.3e1

Now let's try with something that needs more precision:

> BigMath.log(999, 50) / BigMath.log(10, 50)
=> 0.2999565488225982308693534399304475375583359282738400141107276831709276456467950527020061473296516829369378125e1

Compare that with, say, https://www.wolframalpha.com/input/?i=log_10+999


问:
What Are Some Best Practices When Asserting iOS Elements Are Displayed?
I'm trying to write my first UI Automation test for an iOS app with Appium/Python.

I find that when I list 10 assertions like the one below, I get very inconsistent results ... sometimes it passes, but it usually fails the third assertion, sometimes it fails the eighth.

```<code>assert driver.find_element_by_name('Settings').is_displayed()
</code>```

I've also tried to use waits:

```<code>driver.wait_for_element_by_name_to_display('Settings')
assert driver.find_element_by_name('Settings').is_displayed()
</code>```

答:
There is a good util class that can be used for this EC. Hereès the link to the git documentation

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
</code>```

Then you can use it this way to detect if an element is present:

```<code>from appium.webdriver.common.mobileby import MobileBy
# time in seconds
timeout = 10
wait = WebDriverWait(driver, timeout)
wait.until(EC.presence_of_element_located((MobileBy.NAME, 'Settings'))
</code>```

If you need to detect present and visible use:

```<code>wait.until(EC.visibility_of_any_elements_located((MobileBy.NAME, 'Settings'))
</code>```

Body:
I'm trying to write my first UI Automation test for an iOS app with Appium/Python.

I find that when I list 10 assertions like the one below, I get very inconsistent results ... sometimes it passes, but it usually fails the third assertion, sometimes it fails the eighth.

assert driver.find_element_by_name('Settings').is_displayed()

I've also tried to use waits:

driver.wait_for_element_by_name_to_display('Settings')
assert driver.find_element_by_name('Settings').is_displayed()

Body:
There is a good util class that can be used for this EC. Hereès the link to the git documentation

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Then you can use it this way to detect if an element is present:

from appium.webdriver.common.mobileby import MobileBy
# time in seconds
timeout = 10
wait = WebDriverWait(driver, timeout)
wait.until(EC.presence_of_element_located((MobileBy.NAME, 'Settings'))

If you need to detect present and visible use:

wait.until(EC.visibility_of_any_elements_located((MobileBy.NAME, 'Settings'))


问:
How to efficiently find a specific substring in PHP?
OK, I know how to do this but I'm interested in better/more elegant solutions (if any) for this problem.

Imagine I have the following string :

Mozilla/4.0 (compatible; MSIE 7.0;
  Windows NT 5.1; Trident/4.0; GTB6.6;
  Mozilla/4.0 (compatible; MSIE 6.0;
  Windows NT 5.1; SV1) ; .NET CLR
  1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)

I'm interested to find the highest MSIE version in that string (in that case 7.0).

Currently I use explode and preg_match a couple of times in combination with str_replace then I loop between matches and then compare the version string. It works but it's far from elegant. Any ideas on how to improve this?

Keep in mind that:

The string can have any number of MSIE occurrences (or even none)

MSIE is case insensitive

MSIE is followed by a white space (space, tab...) then by the version. The version can contain number letters and dots. The version string is ended by either a white space, a ; or the end of the line.

Thanks!

答:
stripos() does exactly what you are describing. I'm not sure how it can get any more efficient than than in PHP.

Returns the numeric position of the first occurrence of needle in the haystack  string.
   Unlike strpos(), stripos() is case-insensitive.


问:
MongoDB is returning all Results in the find function
I'm trying to perform a simple find using MongoDB, I'm new on it, so I don't know what is wrong, but it seems that it's always bringing all the results without filtering it.

You can run the code here and see what is happening:
https://mongoplayground.net/

Collection - Paste it here https://mongoplayground.net/ - FIRST Text Area

[
  {
    "collection": "collection",
    "count": 10,
    "content": [
      {
        "_id": "apples",
        "qty": 5
      },
      {
        "_id": "bananas",
        "qty": 7
      },
      {
        "_id": "oranges",
        "qty": {
          "in stock": 8,
          "ordered": 12
        }
      },
      {
        "_id": "avocados",
        "qty": "fourteen"
      }
    ]
  }
]```
</div>
</div>
</p>

<p>Find - Paste it here https://mongoplayground.net/ - SECOND Text Area</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>db.collection.find({
  "content.qty": 5
})</code>```

Check the results and you will see the entire JSON as a result.
What Am I doing wrong? Thanks!

答:
First, the query is bringing back what it should do. it bring you the document that satisfy your query, try to add element or more in the array you search in to see the difference.
Secondly, what you want to reach - to get only the specific elements in the nested array - can be done by aggregation you can read in it more here:
https://docs.mongodb.com/manual/aggregation/</p>

Body:
I'm trying to perform a simple find using MongoDB, I'm new on it, so I don't know what is wrong, but it seems that it's always bringing all the results without filtering it.

You can run the code here and see what is happening:
https://mongoplayground.net/

Collection - Paste it here https://mongoplayground.net/ - FIRST Text Area

[
  {
    "collection": "collection",
    "count": 10,
    "content": [
      {
        "_id": "apples",
        "qty": 5
      },
      {
        "_id": "bananas",
        "qty": 7
      },
      {
        "_id": "oranges",
        "qty": {
          "in stock": 8,
          "ordered": 12
        }
      },
      {
        "_id": "avocados",
        "qty": "fourteen"
      }
    ]
  }
]

Find - Paste it here https://mongoplayground.net/ - SECOND Text Area

db.collection.find({
  "content.qty": 5
})

Check the results and you will see the entire JSON as a result.
What Am I doing wrong? Thanks!


问:
How to correctly change state of a multiple nested array of objects in React?
What would be the best way to change the state of multiple nested arrays of objects in React? Let's see the example below: I have a component that will display the top playlist for each genre. I have a property genre which is an array of objects and each object has a property songs which is also an array of objects. If I want to change the song named Soldier of Fortune to Child in Time (Let's suppose in Change function as parameters I have indexes of Song and Genre already provided from the UI change). How can I access multiple levels of nested objects and not mutate the state?

```<code>this.state = {
    title: 'Top playlists',
    genres: [
      {
        genreName: 'pop',
        followers: 2456,
        songs: [
          {
            title: 'Soldier of fortune',
            author: 'Deep Purple',
          },
        ],
      },
    ],
  };

handleChangeSongName = (e, genreIndex, songIndex) => {
    // genreIndex = 0;
    // songIndex = 0;
    // e.target.name = title;
    // e.target.value = "Child in time"
    ...What to do here?
  }

</code>```

答:
you can modify your handleChangeSongName function to this:

```<code>  handleChangeSongName = (e, genreIndex, songIndex) => {
// genreIndex = 0;
// songIndex = 0;
// e.target.name = title;
// e.target.value = "Child in time"
this.setState((prevState) => {
  let temp = {
    ...prevState,
    genres: [...prevState.genres]
  }

  // change title "Soldier of fortune" to "Child in time"
  temp.genres[genreIndex].songs[songIndex][e.target.name] = e.target.value

  return temp
})
</code>```

}

Body:
What would be the best way to change the state of multiple nested arrays of objects in React? Let's see the example below: I have a component that will display the top playlist for each genre. I have a property genre which is an array of objects and each object has a property songs which is also an array of objects. If I want to change the song named Soldier of Fortune to Child in Time (Let's suppose in Change function as parameters I have indexes of Song and Genre already provided from the UI change). How can I access multiple levels of nested objects and not mutate the state?

this.state = {
    title: 'Top playlists',
    genres: [
      {
        genreName: 'pop',
        followers: 2456,
        songs: [
          {
            title: 'Soldier of fortune',
            author: 'Deep Purple',
          },
        ],
      },
    ],
  };

handleChangeSongName = (e, genreIndex, songIndex) => {
    // genreIndex = 0;
    // songIndex = 0;
    // e.target.name = title;
    // e.target.value = "Child in time"
    ...What to do here?
  }

Body:
you can modify your handleChangeSongName function to this:

  handleChangeSongName = (e, genreIndex, songIndex) => {
// genreIndex = 0;
// songIndex = 0;
// e.target.name = title;
// e.target.value = "Child in time"
this.setState((prevState) => {
  let temp = {
    ...prevState,
    genres: [...prevState.genres]
  }

  // change title "Soldier of fortune" to "Child in time"
  temp.genres[genreIndex].songs[songIndex][e.target.name] = e.target.value

  return temp
})

}