问:
How to access markerOptions of Leaflet Map Markers from another method than the creation method?
I am working on a project that creates lines and I need to link each line with its corresponding marker on a Leaflet Map.

Sometimes, I am required to delete a line, hence I am required to delete a marker, and sometimes I need to interact with the marker directly.

For that purpose I added markerOptions and for testing purposes, I added a title, which I wish to alert, each time the marker is pressed.

On the creation method, I am able to access the title with no problems, the problem arise when I try to access the title from the onClick method.

I tried markerOptions.title; this.markerOptions.title; getMarkerOptions(title); this.getMarkerOptions(title), to no avail. I also looked at Leaflet website, and couldn't find an explanation how to achieve that. Additionally, I tried to send as a parameter to the onClick function the title, but apparently, the function does not accepts arguments besides the object that was clicked.

Below is my code for both methods.

Thanks in advance!

```<code>function addMarker(latitude, longitude, flightID) {
    const markerOptions = {
        title: markerIndex, //Naming the marker, according to the flightID
        clickable: true, //Allowing clicks on the marker
        draggable: false //Preventing dragging it.
    }

    const icon1 = L.icon({
        iconUrl: '../path',
        iconSize: [50, 32],
        iconAnchor: [25, 16],
        popupAnchor: [-3, -76]

    });

    markerID[markerIndex] = L.marker([latitude, longitude], //Initializing the marker with the cordinates of the flight.
        { icon: icon1 },
        markerOptions).addTo(myMap).on('click', onClick); // Adding the marker to the map.
    markerIndex++; //Generating a suffix for the next marker.

    currentMarkers.push(markerID[markerIndex-1]); //Pushing the marker to the list of markers.

    if ((highLightFlightID != null) && (highLightFlightID == flightID)) {
        boldFlight(flightID);
    }

    return markerIndex;

}

function onClick(e) {
    alert(this.markerOptions.title); //FAILS.
    alert(this.getLatLng()); //WORKS.
    highLightFlightID = null;

}
</code>```

答:
As documented in https://leafletjs.com/reference-1.6.0.html#class-options , all instances of Leaflet objects (that spawn from a class that inherits from L.Class, and that includes L.Marker) store options passed to its constructor into a options property.

Also note that the L.marker factory method takes parameters as...

```<code>L.marker(latlng, options)
</code>```

...and not...

```<code>L.marker(latlng, options1, options2)
</code>```

...so doing something like...

```<code>L.marker(
    [latitude, longitude],
    { icon: icon1 },
    markerOptions
)
</code>```

...will not work as you would expect.

Instead, you might want to use Object.assign()...

```<code>L.marker(
    [latitude, longitude],
    Object.assign({ icon: icon1 }, markerOptions)
)
</code>```

...or Leaflet's L.Util.extend polyfill...

```<code>L.marker(
    [latitude, longitude],
    L.extend({ icon: icon1 }, markerOptions)
)
</code>```

...or the spread operator...

```<code>L.marker(
    [latitude, longitude],
    { icon: icon1, ...markerOptions }
)
</code>```

...or, if icon1 is applied unconditionally to all markers, just make it part of your markerOptions inconditionally:

```<code>const markerOptions = {
    title: markerIndex,
    clickable: true,
    draggable: false,
    icon: L.icon({
      iconUrl: '../path',
      iconSize: [50, 32],
      iconAnchor: [25, 16],
      popupAnchor: [-3, -76]
    }
});
L.marker([latitude, longitude], markerOptions)
</code>```

In any case, you can access the options property in an event handler (assuming that you passed the right options to the constructor, that is). Remember that the only parameter to a event handler attached to a Leaflet-specific event is a Leaflet-specific data structure, so:

```<code>function onMarkerClick(ev) {
  console.log(ev.target.options);
}
</code>```

Since your question has a slight taint of XY problem (it's not really about options, it's about scope), I'll point out that you can forfeit storing data into a marker's options and use closures for the same effect.

Approaches vary: you may use anonymous functions in the scope where you're instantiating the markers...

```<code>function addMarker(latitude, longitude, flightID) {
  var marker = L.marker([latitude, longitude]);
  marker.addTo(map);
  marker.on('click', function() {  console.log(flightID); });
}
</code>```

...or explicitly create closures by providing a function that, when called, will return a function to serve as the event handler (yes, the concept might be confusing)...

```<code>function addMarker(latitude, longitude, flightID) {
  var marker = L.marker([latitude, longitude]);
  marker.addTo(map);
  marker.on('click', getEventHandlerForId(flightID) );
}

function getEventHandlerForId(id) {
  return function(ev) {
    console.log(id);
  }
}
</code>```

Body:
I am working on a project that creates lines and I need to link each line with its corresponding marker on a Leaflet Map.

Sometimes, I am required to delete a line, hence I am required to delete a marker, and sometimes I need to interact with the marker directly.

For that purpose I added markerOptions and for testing purposes, I added a title, which I wish to alert, each time the marker is pressed.

On the creation method, I am able to access the title with no problems, the problem arise when I try to access the title from the onClick method.

I tried markerOptions.title; this.markerOptions.title; getMarkerOptions(title); this.getMarkerOptions(title), to no avail. I also looked at Leaflet website, and couldn't find an explanation how to achieve that. Additionally, I tried to send as a parameter to the onClick function the title, but apparently, the function does not accepts arguments besides the object that was clicked.

Below is my code for both methods.

Thanks in advance!

function addMarker(latitude, longitude, flightID) {
    const markerOptions = {
        title: markerIndex, //Naming the marker, according to the flightID
        clickable: true, //Allowing clicks on the marker
        draggable: false //Preventing dragging it.
    }

    const icon1 = L.icon({
        iconUrl: '../path',
        iconSize: [50, 32],
        iconAnchor: [25, 16],
        popupAnchor: [-3, -76]

    });

    markerID[markerIndex] = L.marker([latitude, longitude], //Initializing the marker with the cordinates of the flight.
        { icon: icon1 },
        markerOptions).addTo(myMap).on('click', onClick); // Adding the marker to the map.
    markerIndex++; //Generating a suffix for the next marker.

    currentMarkers.push(markerID[markerIndex-1]); //Pushing the marker to the list of markers.

    if ((highLightFlightID != null) && (highLightFlightID == flightID)) {
        boldFlight(flightID);
    }

    return markerIndex;

}

function onClick(e) {
    alert(this.markerOptions.title); //FAILS.
    alert(this.getLatLng()); //WORKS.
    highLightFlightID = null;

}

Body:
As documented in https://leafletjs.com/reference-1.6.0.html#class-options , all instances of Leaflet objects (that spawn from a class that inherits from L.Class, and that includes L.Marker) store options passed to its constructor into a options property.

Also note that the L.marker factory method takes parameters as...

L.marker(latlng, options)

...and not...

L.marker(latlng, options1, options2)

...so doing something like...

L.marker(
    [latitude, longitude],
    { icon: icon1 },
    markerOptions
)

...will not work as you would expect.

Instead, you might want to use Object.assign()...

L.marker(
    [latitude, longitude],
    Object.assign({ icon: icon1 }, markerOptions)
)

...or Leaflet's L.Util.extend polyfill...

L.marker(
    [latitude, longitude],
    L.extend({ icon: icon1 }, markerOptions)
)

...or the spread operator...

L.marker(
    [latitude, longitude],
    { icon: icon1, ...markerOptions }
)

...or, if icon1 is applied unconditionally to all markers, just make it part of your markerOptions inconditionally:

const markerOptions = {
    title: markerIndex,
    clickable: true,
    draggable: false,
    icon: L.icon({
      iconUrl: '../path',
      iconSize: [50, 32],
      iconAnchor: [25, 16],
      popupAnchor: [-3, -76]
    }
});
L.marker([latitude, longitude], markerOptions)

In any case, you can access the options property in an event handler (assuming that you passed the right options to the constructor, that is). Remember that the only parameter to a event handler attached to a Leaflet-specific event is a Leaflet-specific data structure, so:

function onMarkerClick(ev) {
  console.log(ev.target.options);
}

Since your question has a slight taint of XY problem (it's not really about options, it's about scope), I'll point out that you can forfeit storing data into a marker's options and use closures for the same effect.

Approaches vary: you may use anonymous functions in the scope where you're instantiating the markers...

function addMarker(latitude, longitude, flightID) {
  var marker = L.marker([latitude, longitude]);
  marker.addTo(map);
  marker.on('click', function() {  console.log(flightID); });
}

...or explicitly create closures by providing a function that, when called, will return a function to serve as the event handler (yes, the concept might be confusing)...

function addMarker(latitude, longitude, flightID) {
  var marker = L.marker([latitude, longitude]);
  marker.addTo(map);
  marker.on('click', getEventHandlerForId(flightID) );
}

function getEventHandlerForId(id) {
  return function(ev) {
    console.log(id);
  }
}


来源: stackexchange

问:
Interactive Popup/White Space
I am fairly new to the world of coding and am currently designing something using WAMP to assist the misses with her maths. In short I have a page with some basic maths questions on and I have JavaScript running on it to check whether the answers are correct or not.
What I would like to know is, can I use JavaScript or something similar to add in a link that if clicked will open a popup or something similar that the user can write a few bits down to help working out the sums?
I have seen a <button onclick="window.open('whitespace.html');">Thinking Space</button> but this doesnt allow the user to write anything down, obviously as its just a link to another page.

答:
Maybe not the best answer but works for me. I created a link to a blank page that the user can then open. They can work the questions out, minimise it, forget about it and if they were to try to open a fresh one, close it or try to refresh it, they will get a message asking if they are sure they want to continue. Works exactly as Id hoped.</p>

```<code><textarea placeholder="Please be aware no data will be saved here.
If closed or refreshed all data will be lost"</textarea>

<script>
window.addEventListener("beforeunload", function(event) {
  event.returnValue = "Reloading will cause any notes to be lost.";
});
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Interactive Popup/White Space

Body:
Maybe not the best answer but works for me. I created a link to a blank page that the user can then open. They can work the questions out, minimise it, forget about it and if they were to try to open a fresh one, close it or try to refresh it, they will get a message asking if they are sure they want to continue. Works exactly as Id hoped.

<textarea placeholder="Please be aware no data will be saved here.
If closed or refreshed all data will be lost"</textarea>

<script>
window.addEventListener("beforeunload", function(event) {
  event.returnValue = "Reloading will cause any notes to be lost.";
});
</script>


问:
Can't run web apps in new VS 2019 installation
So, I downloaded an example solution (called mini-profiler) from GitHub which has a couple web apps in it. The solution runs in VS 2019. I had VS 2017 Enterprise, so I installed the latest VS 2019 (16.6.1). And I installed almost every single feature.

The web apps build fine. But when I try to run (debug or not) them I get...

This happens no matter which web app I try to run, or if I run it on IIS Express or IIS.

The guy who wrote mini-profiler didn't know what the problem was. And it doesn't look like the problem is specific to his library.

I can run stuff fine in my VS 2017 Enterprise (not this solution though, this solution won't load in VS 2017).

Also, another thing which I noticed is that the .NET Core frameworks are not available in the dropdown...

Even though I have a lot of them installed...

The web app project I was trying to run, "Samples.Mvc5" is not a .NET Core project, but still, I wanted to point that out.

FYI: The beginning of the csproj file looks like this...

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
      <PropertyGroup>
        <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
        <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
        <OutputType>Library</OutputType>
        <RootNamespace>Samples.Mvc5</RootNamespace>
        <AssemblyName>Samples.Mvc5</AssemblyName>
        <TargetFramework>net462</TargetFramework>
        <UseIISExpress>true</UseIISExpress>
        <OutputPath>bin\</OutputPath>
        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
      </PropertyGroup>
</code>```

Here's what's installed in my VS 2019:

```<code>    "Component.Android.NDK.R16B",
    "Component.Android.SDK25.Private",
    "Component.Android.SDK28",
    "Component.Ant",
    "Component.CPython3.x64",
    "Component.Linux.CMake",
    "Component.MDD.Android",
    "Component.MDD.Linux",
    "Component.Microsoft.VisualStudio.LiveShare",
    "Component.Microsoft.VisualStudio.RazorExtension",
    "Component.Microsoft.VisualStudio.Web.AzureFunctions",
    "Component.Microsoft.Web.LibraryManager",
    "Component.OpenJDK",
    "Component.Xamarin",
    "Component.Xamarin.RemotedSimulator",
    "Microsoft.Component.Azure.DataLake.Tools",
    "Microsoft.Component.ClickOnce",
    "Microsoft.Component.CodeAnalysis.SDK",
    "Microsoft.Component.MSBuild",
    "Microsoft.Component.NetFX.Native",
    "Microsoft.Component.PythonTools",
    "Microsoft.Component.PythonTools.Miniconda",
    "Microsoft.Component.PythonTools.Web",
    "Microsoft.ComponentGroup.Blend",
    "Microsoft.Net.Component.3.5.DeveloperTools",
    "Microsoft.Net.Component.4.5.1.TargetingPack",
    "Microsoft.Net.Component.4.5.2.TargetingPack",
    "Microsoft.Net.Component.4.5.TargetingPack",
    "Microsoft.Net.Component.4.6.1.SDK",
    "Microsoft.Net.Component.4.6.1.TargetingPack",
    "Microsoft.Net.Component.4.6.2.SDK",
    "Microsoft.Net.Component.4.6.2.TargetingPack",
    "Microsoft.Net.Component.4.6.TargetingPack",
    "Microsoft.Net.Component.4.7.1.SDK",
    "Microsoft.Net.Component.4.7.1.TargetingPack",
    "Microsoft.Net.Component.4.7.2.SDK"
    "Microsoft.Net.Component.4.7.2.TargetingPack",
    "Microsoft.Net.Component.4.7.SDK",
    "Microsoft.Net.Component.4.7.TargetingPack",
    "Microsoft.Net.Component.4.8.SDK",
    "Microsoft.Net.Component.4.8.TargetingPack",
    "Microsoft.Net.Component.4.TargetingPack",
    "Microsoft.Net.ComponentGroup.DevelopmentPrerequisites",
    "Microsoft.Net.ComponentGroup.TargetingPacks.Common",
    "Microsoft.Net.Core.Component.SDK.2.1",
    "Microsoft.Net.Core.Component.SDK.2.2",
    "Microsoft.Net.Core.Component.SDK.3.0",
    "Microsoft.NetCore.Component.DevelopmentTools",
    "Microsoft.NetCore.Component.Runtime.3.1",
    "Microsoft.NetCore.Component.SDK",
    "Microsoft.NetCore.Component.Web",
    "Microsoft.NetCore.ComponentGroup.DevelopmentTools.2.1",
    "Microsoft.NetCore.ComponentGroup.Web.2.1",
    "Microsoft.VisualStudio.Component.AppInsights.Tools",
    "Microsoft.VisualStudio.Component.AspNet45",
    "Microsoft.VisualStudio.Component.Azure.AuthoringTools",
    "Microsoft.VisualStudio.Component.Azure.ClientLibs",
    "Microsoft.VisualStudio.Component.Azure.Compute.Emulator",
    "Microsoft.VisualStudio.Component.Azure.Kubernetes.Tools",
    "Microsoft.VisualStudio.Component.Azure.Powershell",
    "Microsoft.VisualStudio.Component.Azure.ResourceManager.Tools",
    "Microsoft.VisualStudio.Component.Azure.ServiceFabric.Tools",
    "Microsoft.VisualStudio.Component.Azure.Storage.AzCopy",
    "Microsoft.VisualStudio.Component.Azure.Storage.Emulator",
    "Microsoft.VisualStudio.Component.Azure.Waverton",
    "Microsoft.VisualStudio.Component.Azure.Waverton.BuildTools",
    "Microsoft.VisualStudio.Component.ClassDesigner",
    "Microsoft.VisualStudio.Component.CloudExplorer",
    "Microsoft.VisualStudio.Component.Common.Azure.Tools",
    "Microsoft.VisualStudio.Component.Debugger.JustInTime",
    "Microsoft.VisualStudio.Component.DependencyValidation.Community",
    "Microsoft.VisualStudio.Component.DiagnosticTools",
    "Microsoft.VisualStudio.Component.DockerTools",
    "Microsoft.VisualStudio.Component.DotNetModelBuilder",
    "Microsoft.VisualStudio.Component.EntityFramework",
    "Microsoft.VisualStudio.Component.FSharp",
    "Microsoft.VisualStudio.Component.FSharp.Desktop",
    "Microsoft.VisualStudio.Component.FSharp.WebTemplates",
    "Microsoft.VisualStudio.Component.GraphDocument",
    "Microsoft.VisualStudio.Component.Graphics",
    "Microsoft.VisualStudio.Component.Graphics.Tools",
    "Microsoft.VisualStudio.Component.IISExpress",
    "Microsoft.VisualStudio.Component.IntelliCode",
    "Microsoft.VisualStudio.Component.JavaScript.Diagnostics",
    "Microsoft.VisualStudio.Component.JavaScript.TypeScript",
    "Microsoft.VisualStudio.Component.LinqToSql",
    "Microsoft.VisualStudio.Component.MSODBC.SQL",
    "Microsoft.VisualStudio.Component.MSSQL.CMDLnUtils",
    "Microsoft.VisualStudio.Component.ManagedDesktop.Core",
    "Microsoft.VisualStudio.Component.ManagedDesktop.Prerequisites",
    "Microsoft.VisualStudio.Component.Merq",
    "Microsoft.VisualStudio.Component.MonoDebugger",
    "Microsoft.VisualStudio.Component.Node.Tools",
    "Microsoft.VisualStudio.Component.NuGet",
    "Microsoft.VisualStudio.Component.NuGet.BuildTools",
    "Microsoft.VisualStudio.Component.PortableLibrary",
    "Microsoft.VisualStudio.Component.Roslyn.Compiler",
    "Microsoft.VisualStudio.Component.Roslyn.LanguageServices",
    "Microsoft.VisualStudio.Component.SQL.ADAL",
    "Microsoft.VisualStudio.Component.SQL.CLR",
    "Microsoft.VisualStudio.Component.SQL.DataSources",
    "Microsoft.VisualStudio.Component.SQL.LocalDB.Runtime",
    "Microsoft.VisualStudio.Component.SQL.SSDT",
    "Microsoft.VisualStudio.Component.Sharepoint.Tools",
    "Microsoft.VisualStudio.Component.TeamOffice",
    "Microsoft.VisualStudio.Component.TextTemplating",
    "Microsoft.VisualStudio.Component.TypeScript.3.8",
    "Microsoft.VisualStudio.Component.VC.ASAN",
    "Microsoft.VisualStudio.Component.VC.ATL",
    "Microsoft.VisualStudio.Component.VC.CMake.Project",
    "Microsoft.VisualStudio.Component.VC.CoreIde",
    "Microsoft.VisualStudio.Component.VC.DiagnosticTools",
    "Microsoft.VisualStudio.Component.VC.Redist.14.Latest",
    "Microsoft.VisualStudio.Component.VC.TestAdapterForBoostTest",
    "Microsoft.VisualStudio.Component.VC.TestAdapterForGoogleTest",
    "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
    "Microsoft.VisualStudio.Component.VSSDK",
    "Microsoft.VisualStudio.Component.VisualStudioData",
    "Microsoft.VisualStudio.Component.Wcf.Tooling",
    "Microsoft.VisualStudio.Component.Web",
    "Microsoft.VisualStudio.Component.WebDeploy",
    "Microsoft.VisualStudio.Component.Windows10SDK.18362",
    "Microsoft.VisualStudio.Component.Workflow",
    "Microsoft.VisualStudio.ComponentGroup.Azure.CloudServices",
    "Microsoft.VisualStudio.ComponentGroup.Azure.Prerequisites",
    "Microsoft.VisualStudio.ComponentGroup.Azure.ResourceManager.Tools",
    "Microsoft.VisualStudio.ComponentGroup.AzureFunctions",
    "Microsoft.VisualStudio.ComponentGroup.IISDevelopment",
    "Microsoft.VisualStudio.ComponentGroup.MSIX.Packaging",
    "Microsoft.VisualStudio.ComponentGroup.NativeDesktop.Core",
    "Microsoft.VisualStudio.ComponentGroup.UWP.NetCoreAndStandard",
    "Microsoft.VisualStudio.ComponentGroup.UWP.Support",
    "Microsoft.VisualStudio.ComponentGroup.UWP.Xamarin",
    "Microsoft.VisualStudio.ComponentGroup.VisualStudioExtension.Prerequisites",
    "Microsoft.VisualStudio.ComponentGroup.Web",
    "Microsoft.VisualStudio.ComponentGroup.Web.CloudTools",
    "Microsoft.VisualStudio.ComponentGroup.WebToolsExtensions",
    "Microsoft.VisualStudio.ComponentGroup.WebToolsExtensions.CMake",
    "Microsoft.VisualStudio.ComponentGroup.WebToolsExtensions.TemplateEngine",
    "Microsoft.VisualStudio.Web.Mvc4.ComponentGroup",
    "Microsoft.VisualStudio.Workload.Azure",
    "Microsoft.VisualStudio.Workload.CoreEditor",
    "Microsoft.VisualStudio.Workload.Data",
    "Microsoft.VisualStudio.Workload.DataScience",
    "Microsoft.VisualStudio.Workload.ManagedDesktop",
    "Microsoft.VisualStudio.Workload.NativeCrossPlat",
    "Microsoft.VisualStudio.Workload.NativeDesktop",
    "Microsoft.VisualStudio.Workload.NativeMobile",
    "Microsoft.VisualStudio.Workload.NetCoreTools",
    "Microsoft.VisualStudio.Workload.NetCrossPlat",
    "Microsoft.VisualStudio.Workload.NetWeb",
    "Microsoft.VisualStudio.Workload.Node",
    "Microsoft.VisualStudio.Workload.Office",
    "Microsoft.VisualStudio.Workload.Python",
    "Microsoft.VisualStudio.Workload.Universal",
    "Microsoft.VisualStudio.Workload.VisualStudioExtension",
"Microsoft.VisualStudio.Component.CoreEditor",
</code>```

答:
Have you try restart your computeur? I add the same issue and restarting work for me. Some time visual studio is not working properly. </p>

<p>If this does work try vs-code, it free! Whit all the plugin, vs-code is good as a IDE! </p>

Body:
So, I downloaded an example solution (called mini-profiler) from GitHub which has a couple web apps in it. The solution runs in VS 2019. I had VS 2017 Enterprise, so I installed the latest VS 2019 (16.6.1). And I installed almost every single feature.

The web apps build fine. But when I try to run (debug or not) them I get...

This happens no matter which web app I try to run, or if I run it on IIS Express or IIS.

The guy who wrote mini-profiler didn't know what the problem was. And it doesn't look like the problem is specific to his library.

I can run stuff fine in my VS 2017 Enterprise (not this solution though, this solution won't load in VS 2017).

Also, another thing which I noticed is that the .NET Core frameworks are not available in the dropdown...

Even though I have a lot of them installed...

The web app project I was trying to run, "Samples.Mvc5" is not a .NET Core project, but still, I wanted to point that out.

FYI: The beginning of the csproj file looks like this...

<Project Sdk="Microsoft.NET.Sdk.Web">
      <PropertyGroup>
        <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
        <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
        <OutputType>Library</OutputType>
        <RootNamespace>Samples.Mvc5</RootNamespace>
        <AssemblyName>Samples.Mvc5</AssemblyName>
        <TargetFramework>net462</TargetFramework>
        <UseIISExpress>true</UseIISExpress>
        <OutputPath>bin\</OutputPath>
        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
      </PropertyGroup>

Here's what's installed in my VS 2019:

    "Component.Android.NDK.R16B",
    "Component.Android.SDK25.Private",
    "Component.Android.SDK28",
    "Component.Ant",
    "Component.CPython3.x64",
    "Component.Linux.CMake",
    "Component.MDD.Android",
    "Component.MDD.Linux",
    "Component.Microsoft.VisualStudio.LiveShare",
    "Component.Microsoft.VisualStudio.RazorExtension",
    "Component.Microsoft.VisualStudio.Web.AzureFunctions",
    "Component.Microsoft.Web.LibraryManager",
    "Component.OpenJDK",
    "Component.Xamarin",
    "Component.Xamarin.RemotedSimulator",
    "Microsoft.Component.Azure.DataLake.Tools",
    "Microsoft.Component.ClickOnce",
    "Microsoft.Component.CodeAnalysis.SDK",
    "Microsoft.Component.MSBuild",
    "Microsoft.Component.NetFX.Native",
    "Microsoft.Component.PythonTools",
    "Microsoft.Component.PythonTools.Miniconda",
    "Microsoft.Component.PythonTools.Web",
    "Microsoft.ComponentGroup.Blend",
    "Microsoft.Net.Component.3.5.DeveloperTools",
    "Microsoft.Net.Component.4.5.1.TargetingPack",
    "Microsoft.Net.Component.4.5.2.TargetingPack",
    "Microsoft.Net.Component.4.5.TargetingPack",
    "Microsoft.Net.Component.4.6.1.SDK",
    "Microsoft.Net.Component.4.6.1.TargetingPack",
    "Microsoft.Net.Component.4.6.2.SDK",
    "Microsoft.Net.Component.4.6.2.TargetingPack",
    "Microsoft.Net.Component.4.6.TargetingPack",
    "Microsoft.Net.Component.4.7.1.SDK",
    "Microsoft.Net.Component.4.7.1.TargetingPack",
    "Microsoft.Net.Component.4.7.2.SDK"
    "Microsoft.Net.Component.4.7.2.TargetingPack",
    "Microsoft.Net.Component.4.7.SDK",
    "Microsoft.Net.Component.4.7.TargetingPack",
    "Microsoft.Net.Component.4.8.SDK",
    "Microsoft.Net.Component.4.8.TargetingPack",
    "Microsoft.Net.Component.4.TargetingPack",
    "Microsoft.Net.ComponentGroup.DevelopmentPrerequisites",
    "Microsoft.Net.ComponentGroup.TargetingPacks.Common",
    "Microsoft.Net.Core.Component.SDK.2.1",
    "Microsoft.Net.Core.Component.SDK.2.2",
    "Microsoft.Net.Core.Component.SDK.3.0",
    "Microsoft.NetCore.Component.DevelopmentTools",
    "Microsoft.NetCore.Component.Runtime.3.1",
    "Microsoft.NetCore.Component.SDK",
    "Microsoft.NetCore.Component.Web",
    "Microsoft.NetCore.ComponentGroup.DevelopmentTools.2.1",
    "Microsoft.NetCore.ComponentGroup.Web.2.1",
    "Microsoft.VisualStudio.Component.AppInsights.Tools",
    "Microsoft.VisualStudio.Component.AspNet45",
    "Microsoft.VisualStudio.Component.Azure.AuthoringTools",
    "Microsoft.VisualStudio.Component.Azure.ClientLibs",
    "Microsoft.VisualStudio.Component.Azure.Compute.Emulator",
    "Microsoft.VisualStudio.Component.Azure.Kubernetes.Tools",
    "Microsoft.VisualStudio.Component.Azure.Powershell",
    "Microsoft.VisualStudio.Component.Azure.ResourceManager.Tools",
    "Microsoft.VisualStudio.Component.Azure.ServiceFabric.Tools",
    "Microsoft.VisualStudio.Component.Azure.Storage.AzCopy",
    "Microsoft.VisualStudio.Component.Azure.Storage.Emulator",
    "Microsoft.VisualStudio.Component.Azure.Waverton",
    "Microsoft.VisualStudio.Component.Azure.Waverton.BuildTools",
    "Microsoft.VisualStudio.Component.ClassDesigner",
    "Microsoft.VisualStudio.Component.CloudExplorer",
    "Microsoft.VisualStudio.Component.Common.Azure.Tools",
    "Microsoft.VisualStudio.Component.Debugger.JustInTime",
    "Microsoft.VisualStudio.Component.DependencyValidation.Community",
    "Microsoft.VisualStudio.Component.DiagnosticTools",
    "Microsoft.VisualStudio.Component.DockerTools",
    "Microsoft.VisualStudio.Component.DotNetModelBuilder",
    "Microsoft.VisualStudio.Component.EntityFramework",
    "Microsoft.VisualStudio.Component.FSharp",
    "Microsoft.VisualStudio.Component.FSharp.Desktop",
    "Microsoft.VisualStudio.Component.FSharp.WebTemplates",
    "Microsoft.VisualStudio.Component.GraphDocument",
    "Microsoft.VisualStudio.Component.Graphics",
    "Microsoft.VisualStudio.Component.Graphics.Tools",
    "Microsoft.VisualStudio.Component.IISExpress",
    "Microsoft.VisualStudio.Component.IntelliCode",
    "Microsoft.VisualStudio.Component.JavaScript.Diagnostics",
    "Microsoft.VisualStudio.Component.JavaScript.TypeScript",
    "Microsoft.VisualStudio.Component.LinqToSql",
    "Microsoft.VisualStudio.Component.MSODBC.SQL",
    "Microsoft.VisualStudio.Component.MSSQL.CMDLnUtils",
    "Microsoft.VisualStudio.Component.ManagedDesktop.Core",
    "Microsoft.VisualStudio.Component.ManagedDesktop.Prerequisites",
    "Microsoft.VisualStudio.Component.Merq",
    "Microsoft.VisualStudio.Component.MonoDebugger",
    "Microsoft.VisualStudio.Component.Node.Tools",
    "Microsoft.VisualStudio.Component.NuGet",
    "Microsoft.VisualStudio.Component.NuGet.BuildTools",
    "Microsoft.VisualStudio.Component.PortableLibrary",
    "Microsoft.VisualStudio.Component.Roslyn.Compiler",
    "Microsoft.VisualStudio.Component.Roslyn.LanguageServices",
    "Microsoft.VisualStudio.Component.SQL.ADAL",
    "Microsoft.VisualStudio.Component.SQL.CLR",
    "Microsoft.VisualStudio.Component.SQL.DataSources",
    "Microsoft.VisualStudio.Component.SQL.LocalDB.Runtime",
    "Microsoft.VisualStudio.Component.SQL.SSDT",
    "Microsoft.VisualStudio.Component.Sharepoint.Tools",
    "Microsoft.VisualStudio.Component.TeamOffice",
    "Microsoft.VisualStudio.Component.TextTemplating",
    "Microsoft.VisualStudio.Component.TypeScript.3.8",
    "Microsoft.VisualStudio.Component.VC.ASAN",
    "Microsoft.VisualStudio.Component.VC.ATL",
    "Microsoft.VisualStudio.Component.VC.CMake.Project",
    "Microsoft.VisualStudio.Component.VC.CoreIde",
    "Microsoft.VisualStudio.Component.VC.DiagnosticTools",
    "Microsoft.VisualStudio.Component.VC.Redist.14.Latest",
    "Microsoft.VisualStudio.Component.VC.TestAdapterForBoostTest",
    "Microsoft.VisualStudio.Component.VC.TestAdapterForGoogleTest",
    "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
    "Microsoft.VisualStudio.Component.VSSDK",
    "Microsoft.VisualStudio.Component.VisualStudioData",
    "Microsoft.VisualStudio.Component.Wcf.Tooling",
    "Microsoft.VisualStudio.Component.Web",
    "Microsoft.VisualStudio.Component.WebDeploy",
    "Microsoft.VisualStudio.Component.Windows10SDK.18362",
    "Microsoft.VisualStudio.Component.Workflow",
    "Microsoft.VisualStudio.ComponentGroup.Azure.CloudServices",
    "Microsoft.VisualStudio.ComponentGroup.Azure.Prerequisites",
    "Microsoft.VisualStudio.ComponentGroup.Azure.ResourceManager.Tools",
    "Microsoft.VisualStudio.ComponentGroup.AzureFunctions",
    "Microsoft.VisualStudio.ComponentGroup.IISDevelopment",
    "Microsoft.VisualStudio.ComponentGroup.MSIX.Packaging",
    "Microsoft.VisualStudio.ComponentGroup.NativeDesktop.Core",
    "Microsoft.VisualStudio.ComponentGroup.UWP.NetCoreAndStandard",
    "Microsoft.VisualStudio.ComponentGroup.UWP.Support",
    "Microsoft.VisualStudio.ComponentGroup.UWP.Xamarin",
    "Microsoft.VisualStudio.ComponentGroup.VisualStudioExtension.Prerequisites",
    "Microsoft.VisualStudio.ComponentGroup.Web",
    "Microsoft.VisualStudio.ComponentGroup.Web.CloudTools",
    "Microsoft.VisualStudio.ComponentGroup.WebToolsExtensions",
    "Microsoft.VisualStudio.ComponentGroup.WebToolsExtensions.CMake",
    "Microsoft.VisualStudio.ComponentGroup.WebToolsExtensions.TemplateEngine",
    "Microsoft.VisualStudio.Web.Mvc4.ComponentGroup",
    "Microsoft.VisualStudio.Workload.Azure",
    "Microsoft.VisualStudio.Workload.CoreEditor",
    "Microsoft.VisualStudio.Workload.Data",
    "Microsoft.VisualStudio.Workload.DataScience",
    "Microsoft.VisualStudio.Workload.ManagedDesktop",
    "Microsoft.VisualStudio.Workload.NativeCrossPlat",
    "Microsoft.VisualStudio.Workload.NativeDesktop",
    "Microsoft.VisualStudio.Workload.NativeMobile",
    "Microsoft.VisualStudio.Workload.NetCoreTools",
    "Microsoft.VisualStudio.Workload.NetCrossPlat",
    "Microsoft.VisualStudio.Workload.NetWeb",
    "Microsoft.VisualStudio.Workload.Node",
    "Microsoft.VisualStudio.Workload.Office",
    "Microsoft.VisualStudio.Workload.Python",
    "Microsoft.VisualStudio.Workload.Universal",
    "Microsoft.VisualStudio.Workload.VisualStudioExtension",
"Microsoft.VisualStudio.Component.CoreEditor",

Body:
Have you try restart your computeur? I add the same issue and restarting work for me. Some time visual studio is not working properly.

If this does work try vs-code, it free! Whit all the plugin, vs-code is good as a IDE!


问:
Need explanation for C++ code
```<code>namespace Stack {
  struct Rep; // definition of stack layout is elsewhere
  typedef Rep& stack;
  stack create(); // make a new stack
  void destroy(stack s); // delete s
  void push(stack s, char c); // push c onto s
  char pop(stack s); // pop s
}
</code>```

This is in the "A Tour of C++" Unit, before even the basic material like functions, loops, and fundamental datatypes...I don't know if/how I'm supposed to understand this code or not.

Anyway, can someone please explain it? It's supposed to be part of an explanation on how to "define a stack manager with an interface"

For starters, I specifically don't know what "typedef Rep& stack" means.

答:
In short, stack is a typedef for a reference to the type Rep. That means, whenever you use stack, you denote the type "reference to Rep".

In my opinion, this is a weird C++ course material. From what the interface looks like, we can suppose the implementation will be something like

```<code>/* in darkcorner.cpp: */

stack create() { // make a new stack
  stack s = *new Rep;
  return s;
}

void destroy(stack s) { // delete s
  delete &s;
}

void push(stack s, char c) { // push c onto s
  s.push(c);
}

char pop(stack s) { // pop s
  return s.pop();
}
</code>```

Now, if you do the following, you violate the principle of least surprise for most C++ programmers.

```<code>stack p = create();
stack p2 = p;
</code>```

The "principle of least surprise" says that this shall copy the stack. But actually, stack stands for the type Rep&, which is a "reference to Rep". This means that the second line creates an alias to p (reference to what p refers to). It doesn't copy, but just creates another reference.

I recommend you: Stay clear of such code. If you want to hide the implementation or layout of Rep, then implement the Pimpl idiom.

ContentLicense: CC BY-SA 3.0

Title: Need explanation for C++ code

Body:
namespace Stack {
  struct Rep; // definition of stack layout is elsewhere
  typedef Rep& stack;
  stack create(); // make a new stack
  void destroy(stack s); // delete s
  void push(stack s, char c); // push c onto s
  char pop(stack s); // pop s
}

This is in the "A Tour of C++" Unit, before even the basic material like functions, loops, and fundamental datatypes...I don't know if/how I'm supposed to understand this code or not.

Anyway, can someone please explain it? It's supposed to be part of an explanation on how to "define a stack manager with an interface"

For starters, I specifically don't know what "typedef Rep& stack" means.

Body:
In short, stack is a typedef for a reference to the type Rep. That means, whenever you use stack, you denote the type "reference to Rep".

In my opinion, this is a weird C++ course material. From what the interface looks like, we can suppose the implementation will be something like

/* in darkcorner.cpp: */

stack create() { // make a new stack
  stack s = *new Rep;
  return s;
}

void destroy(stack s) { // delete s
  delete &s;
}

void push(stack s, char c) { // push c onto s
  s.push(c);
}

char pop(stack s) { // pop s
  return s.pop();
}

Now, if you do the following, you violate the principle of least surprise for most C++ programmers.

stack p = create();
stack p2 = p;

The "principle of least surprise" says that this shall copy the stack. But actually, stack stands for the type Rep&, which is a "reference to Rep". This means that the second line creates an alias to p (reference to what p refers to). It doesn't copy, but just creates another reference.

I recommend you: Stay clear of such code. If you want to hide the implementation or layout of Rep, then implement the Pimpl idiom.


问:
(R) Getting "variable length differ" for two different variable
I created two variable called "low.income"  and "mid.income" from survey, they are variables which obtained based on participants income. here you can see the variables how looks like:

```<code>low.income = 75  95  85 100  85 100  85  90  75  90  65  80  85  90  85  70  95  85 100  95  85  95  90  95  95
</code>```

mid.income = 95 100  90  90  85  95 100  95  80

But when try to call aov(low.income~mid.income) it gives me Error in model.frame.default(formula = low.income ~ mid.income, drop.unused.levels = TRUE) :
  variable lengths differ (found for 'mid.income')

So, what should i do ?

答:
That is not correct, I think you are looking for t.test ie

```<code> t.test(low.income, mid.income, var.equal = TRUE)
</code>```

To use the formula method, you have to create a dataframe with the level and the income. It should look like below:

```<code> data <-  data.frame(level = rep(paste0(c("low","mid"),".income"),c(25,9)), income = c(low.income,mid.income))

       level income
1 low.income     75
2 low.income     95
3 low.income     85
4 low.income    100
5 low.income     85
6 low.income    100
:    :           :
29 mid.income     90
30 mid.income     85
31 mid.income     95
32 mid.income    100
33 mid.income     95
34 mid.income     80
</code>```

Now you could do:

```<code>t.test(income~level,data,var.equal = TRUE)
</code>```

Well Since you are using aov, I will give you an example of how to do that:

```<code>aov(income~level,data)
</code>```

These two will lead to the exact same result. You can run TukeyHSD to see that the results are the same.

NOTE: You only run ANOVA when you have more than 2 groups. If you only have 2 groups, run a t.test. Recall that ANOVA is a generalization of the t.test

Body:
I created two variable called "low.income"  and "mid.income" from survey, they are variables which obtained based on participants income. here you can see the variables how looks like:

low.income = 75  95  85 100  85 100  85  90  75  90  65  80  85  90  85  70  95  85 100  95  85  95  90  95  95

mid.income = 95 100  90  90  85  95 100  95  80

But when try to call aov(low.income~mid.income) it gives me Error in model.frame.default(formula = low.income ~ mid.income, drop.unused.levels = TRUE) :
  variable lengths differ (found for 'mid.income')

So, what should i do ?

Body:
That is not correct, I think you are looking for t.test ie

 t.test(low.income, mid.income, var.equal = TRUE)

To use the formula method, you have to create a dataframe with the level and the income. It should look like below:

 data <-  data.frame(level = rep(paste0(c("low","mid"),".income"),c(25,9)), income = c(low.income,mid.income))

       level income
1 low.income     75
2 low.income     95
3 low.income     85
4 low.income    100
5 low.income     85
6 low.income    100
:    :           :
29 mid.income     90
30 mid.income     85
31 mid.income     95
32 mid.income    100
33 mid.income     95
34 mid.income     80

Now you could do:

t.test(income~level,data,var.equal = TRUE)

Well Since you are using aov, I will give you an example of how to do that:

aov(income~level,data)

These two will lead to the exact same result. You can run TukeyHSD to see that the results are the same.

NOTE: You only run ANOVA when you have more than 2 groups. If you only have 2 groups, run a t.test. Recall that ANOVA is a generalization of the t.test


问:
How to connect to AWS Elasticsearch?
I'm trying to connect to AWS Elasticsearch but I always get the following error:

Exception in thread "main" org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: []
at org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:278)
at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:197)
at org.elasticsearch.client.transport.support.InternalTransportClient.execute(InternalTransportClient.java:106)
at org.elasticsearch.client.support.AbstractClient.index(AbstractClient.java:98)
at org.elasticsearch.client.transport.TransportClient.index(TransportClient.java:334)
at org.elasticsearch.action.index.IndexRequestBuilder.doExecute(IndexRequestBuilder.java:313)
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:91)
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:65)
at com.c_backendcrawler.utility.ElasticSearch.uploadObject(ElasticSearch.java:25)
at com.c_backendcrawler.Start.main(Start.java:34)
```

<p>My code is following:</p>

``` //Create Client
    Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "zencubes-search").put("node.name","Darkhawk").build();
    TransportClient transportClient = new TransportClient(settings);
    transportClient.addTransportAddress(new InetSocketTransportAddress(
            "x.x.x.x",9300));
    return transportClient;
```

<p>Output from AWS Elasticsearch:</p>

```    {
status: 200,
name: "Darkhawk",
cluster_name: "817880037706:zencubes-search",
version: {
number: "1.5.2",
build_hash: "62ff9868b4c8a0c45860bebb259e21980778ab1c",
build_timestamp: "2015-04-27T09:21:06Z",
build_snapshot: false,
lucene_version: "4.10.4"
},
tagline: "You Know, for Search"
}
```

I tried to curl (https://search-zencubes-search-xxxxxxxx.eu-west-1.es.amazonaws.com/ ) and it works - but not on port 9300. What am I doing wrong here?

答:
How to get the AWS ES URL

Go to the Elasticsearch Domain console and get the Endpoint in the Overview tab.

Port to use is 443.

Make sure the access control has been configured.

Options for granting or denying access to Amazon ES endpoints

FYI

Create an Elasticsearch Index

```<code>curl -v -XPUT "${ES_ENDPOINT}/article/" -H 'Content-Type: application/json' -d '{
    "settings" : {
        "index" : {
            "number_of_shards" : 1,
            "number_of_replicas" : 0
        }
    }
}'
</code>```

Title: How to connect to AWS Elasticsearch?

Body:
I'm trying to connect to AWS Elasticsearch but I always get the following error:

Exception in thread "main" org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: []
at org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:278)
at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:197)
at org.elasticsearch.client.transport.support.InternalTransportClient.execute(InternalTransportClient.java:106)
at org.elasticsearch.client.support.AbstractClient.index(AbstractClient.java:98)
at org.elasticsearch.client.transport.TransportClient.index(TransportClient.java:334)
at org.elasticsearch.action.index.IndexRequestBuilder.doExecute(IndexRequestBuilder.java:313)
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:91)
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:65)
at com.c_backendcrawler.utility.ElasticSearch.uploadObject(ElasticSearch.java:25)
at com.c_backendcrawler.Start.main(Start.java:34)

My code is following:

 //Create Client
    Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "zencubes-search").put("node.name","Darkhawk").build();
    TransportClient transportClient = new TransportClient(settings);
    transportClient.addTransportAddress(new InetSocketTransportAddress(
            "x.x.x.x",9300));
    return transportClient;

Output from AWS Elasticsearch:

    {
status: 200,
name: "Darkhawk",
cluster_name: "817880037706:zencubes-search",
version: {
number: "1.5.2",
build_hash: "62ff9868b4c8a0c45860bebb259e21980778ab1c",
build_timestamp: "2015-04-27T09:21:06Z",
build_snapshot: false,
lucene_version: "4.10.4"
},
tagline: "You Know, for Search"
}

I tried to curl (https://search-zencubes-search-xxxxxxxx.eu-west-1.es.amazonaws.com/ ) and it works - but not on port 9300. What am I doing wrong here?

Body:
How to get the AWS ES URL

Go to the Elasticsearch Domain console and get the Endpoint in the Overview tab.

Port to use is 443.

Make sure the access control has been configured.

Options for granting or denying access to Amazon ES endpoints

FYI

Create an Elasticsearch Index

curl -v -XPUT "${ES_ENDPOINT}/article/" -H 'Content-Type: application/json' -d '{
    "settings" : {
        "index" : {
            "number_of_shards" : 1,
            "number_of_replicas" : 0
        }
    }
}'


问:
How to run JavaFx application from command line
```<code>import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class app extends Application
{
   @Override
   public void start(final Stage stage) throws Exception
   {
      final Circle circ = new Circle(40, 40, 30);
      final Group root = new Group(circ);
      final Scene scene = new Scene(root, 400, 300);

      stage.setTitle("Hello JavaFX 2.0!");
      stage.setScene(scene);
      stage.show();
   }

   public static void main(String[] arguments)
   {
      Application.launch(arguments);
   }
}
</code>```

I have this JavaFx code that I want to run from the command line.
 I tried the command javac -d app.java it gives me an error: no source files and if I try with the command java -cp D:\javafx-sdk-13.0.2\lib\jfxrt.jar app.java. The error message is app not found.
What am I doing wrong and how can I fix it so that GUI application runs from the command line?

答:
This is the command I used to make it run from the command line

to compile:

javac --module-path D:\javafx-sdk-13.0.2\lib --add-modules javafx.controls app.java
```
<p>to run:</p>
<pre class="lang-none prettyprint-override"><code>java --module-path D:\javafx-sdk-13.0.2\lib --add-modules javafx.controls app
</code>```

Body:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class app extends Application
{
   @Override
   public void start(final Stage stage) throws Exception
   {
      final Circle circ = new Circle(40, 40, 30);
      final Group root = new Group(circ);
      final Scene scene = new Scene(root, 400, 300);

      stage.setTitle("Hello JavaFX 2.0!");
      stage.setScene(scene);
      stage.show();
   }

   public static void main(String[] arguments)
   {
      Application.launch(arguments);
   }
}

I have this JavaFx code that I want to run from the command line.
 I tried the command javac -d app.java it gives me an error: no source files and if I try with the command java -cp D:\javafx-sdk-13.0.2\lib\jfxrt.jar app.java. The error message is app not found.
What am I doing wrong and how can I fix it so that GUI application runs from the command line?

Body:
This is the command I used to make it run from the command line

to compile:

javac --module-path D:\javafx-sdk-13.0.2\lib --add-modules javafx.controls app.java

to run:

java --module-path D:\javafx-sdk-13.0.2\lib --add-modules javafx.controls app


问:
Cannot use instance member 'userCard1' within property initializer; property initializers run before 'self' is available error
Trying to make a simple Blackjack app to get comfortable with using Xcode. I've never coded in Swift before and have a little experience in C++. Having an error I don't know how to fix. I'm having trouble applying other answers to similar questions to my situation.

I'm not totally sure what's causing the problem, let alone how to fix it :)

```<code>
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    var balance = 500

    let suits = ["h","d","c","s"]

    //user card declarations
    @IBOutlet weak var userCard1: UIImageView!

    @IBOutlet weak var userCard2: UIImageView!

    @IBOutlet weak var userCard3: UIImageView!

    @IBOutlet weak var userCard4: UIImageView!

    @IBOutlet weak var userCard5: UIImageView!

    @IBOutlet weak var userCard6: UIImageView!

    @IBOutlet weak var userCard7: UIImageView!

    @IBOutlet weak var userCard8: UIImageView!

    @IBOutlet weak var userCard9: UIImageView!

    @IBOutlet weak var userCard10: UIImageView!

    //dealer card declarations
    @IBOutlet weak var dealerCard1: UIImageView!

    @IBOutlet weak var dealerCard2: UIImageView!

    @IBOutlet weak var dealerCard3: UIImageView!

    @IBOutlet weak var dealerCard4: UIImageView!

    @IBOutlet weak var dealerCard5: UIImageView!

    var win = false

    var bet = 0

    //bet label
    @IBOutlet weak var betLabel: UILabel!

    //bet slider
    @IBAction func betSlider(_ sender: UISlider) {
        betLabel.text = String(Int(sender.value))
    }
    @IBOutlet weak var betSliderValue: UISlider!

    var userCardSlot = 3
    var dealerCardSlot = 3

    var userTotal = 0
    var dealerTotal = 0

    //user cards displayed
    var userCardArray = [userCard1, userCard2, userCard3, userCard4, userCard5, userCard6, userCard7, userCard8, userCard9, userCard10]

    //dealer cards displayed
    var dealerCardArray = [dealerCard1, dealerCard2, dealerCard3, dealerCard4, dealerCard5]

    //hit button
    @IBAction func hitTapped(_ sender: Any) {
        var cardNum = Int.random(in: 2...14)
        var cardSuit = Int(arc4random()) % 4
        userCardArray[userCardSlot].image = UIImage(named: "\(cardSuit)card\(cardNum)")
    }

    //stand button
    @IBAction func standTapped(_ sender: Any) {
        for userTotal in userCardArray.reversed() {
            userTotal += cardNum
        }
        for dealerTotal in dealerCardArray {
            dealerTotal += cardNum
        }
        while dealerTotal < 17 {
            dealerCardSlot += 1
            dealerCardArray[dealerCardSlot].image = UIImage(named: "\(cardSuit)card\(cardNum)")
        }
        if dealerTotal <= userTotal {
            win = true
        } else {
            win = false
        }
    }

    @IBAction func newRoundTapped(_ sender: Any) {

        bet = Int(betSliderValue.value)

        userCardArray[0].image = UIImage(named: "\(cardSuit)card\(cardNum)")
        userCardArray[1].image = UIImage(named: "\(cardSuit)card\(cardNum)")

        dealerCardArray[0].image = UIImage(named: "\(cardSuit)card\(cardNum)")
        dealerCardArray[0].image = UIImage(named: "Red_back.jpg")

        //prompt for hit or stand

        if win == true {
            balance += (bet * 2)
        } else {
            balance -= bet
        }

    }

}

</code>```

Any help's appreciated!

答:
You generally cannot use one property to initialize another outside of init, because when you do:

```<code>var b = a + 1
</code>```

the compiler implicitly does:

```<code>var b = self.a + 1
</code>```

but self is not yet available; it's only available during the init.

The only exception is a lazy property initializer:

```<code>lazy var b: Int = self.a + 1
</code>```

In your case, you can move the initialization into init:

```<code>var userCardArray: [UIImageView]

init() {
   self.userCardArray = [userCard1, userCard2, ... ]
}
</code>```

Body:
Trying to make a simple Blackjack app to get comfortable with using Xcode. I've never coded in Swift before and have a little experience in C++. Having an error I don't know how to fix. I'm having trouble applying other answers to similar questions to my situation.

I'm not totally sure what's causing the problem, let alone how to fix it :)

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    var balance = 500

    let suits = ["h","d","c","s"]

    //user card declarations
    @IBOutlet weak var userCard1: UIImageView!

    @IBOutlet weak var userCard2: UIImageView!

    @IBOutlet weak var userCard3: UIImageView!

    @IBOutlet weak var userCard4: UIImageView!

    @IBOutlet weak var userCard5: UIImageView!

    @IBOutlet weak var userCard6: UIImageView!

    @IBOutlet weak var userCard7: UIImageView!

    @IBOutlet weak var userCard8: UIImageView!

    @IBOutlet weak var userCard9: UIImageView!

    @IBOutlet weak var userCard10: UIImageView!

    //dealer card declarations
    @IBOutlet weak var dealerCard1: UIImageView!

    @IBOutlet weak var dealerCard2: UIImageView!

    @IBOutlet weak var dealerCard3: UIImageView!

    @IBOutlet weak var dealerCard4: UIImageView!

    @IBOutlet weak var dealerCard5: UIImageView!

    var win = false

    var bet = 0

    //bet label
    @IBOutlet weak var betLabel: UILabel!

    //bet slider
    @IBAction func betSlider(_ sender: UISlider) {
        betLabel.text = String(Int(sender.value))
    }
    @IBOutlet weak var betSliderValue: UISlider!

    var userCardSlot = 3
    var dealerCardSlot = 3

    var userTotal = 0
    var dealerTotal = 0

    //user cards displayed
    var userCardArray = [userCard1, userCard2, userCard3, userCard4, userCard5, userCard6, userCard7, userCard8, userCard9, userCard10]

    //dealer cards displayed
    var dealerCardArray = [dealerCard1, dealerCard2, dealerCard3, dealerCard4, dealerCard5]

    //hit button
    @IBAction func hitTapped(_ sender: Any) {
        var cardNum = Int.random(in: 2...14)
        var cardSuit = Int(arc4random()) % 4
        userCardArray[userCardSlot].image = UIImage(named: "\(cardSuit)card\(cardNum)")
    }

    //stand button
    @IBAction func standTapped(_ sender: Any) {
        for userTotal in userCardArray.reversed() {
            userTotal += cardNum
        }
        for dealerTotal in dealerCardArray {
            dealerTotal += cardNum
        }
        while dealerTotal < 17 {
            dealerCardSlot += 1
            dealerCardArray[dealerCardSlot].image = UIImage(named: "\(cardSuit)card\(cardNum)")
        }
        if dealerTotal <= userTotal {
            win = true
        } else {
            win = false
        }
    }

    @IBAction func newRoundTapped(_ sender: Any) {

        bet = Int(betSliderValue.value)

        userCardArray[0].image = UIImage(named: "\(cardSuit)card\(cardNum)")
        userCardArray[1].image = UIImage(named: "\(cardSuit)card\(cardNum)")

        dealerCardArray[0].image = UIImage(named: "\(cardSuit)card\(cardNum)")
        dealerCardArray[0].image = UIImage(named: "Red_back.jpg")

        //prompt for hit or stand

        if win == true {
            balance += (bet * 2)
        } else {
            balance -= bet
        }

    }

}

Any help's appreciated!

Body:
You generally cannot use one property to initialize another outside of init, because when you do:

var b = a + 1

the compiler implicitly does:

var b = self.a + 1

but self is not yet available; it's only available during the init.

The only exception is a lazy property initializer:

lazy var b: Int = self.a + 1

In your case, you can move the initialization into init:

var userCardArray: [UIImageView]

init() {
   self.userCardArray = [userCard1, userCard2, ... ]
}


问:
Android Studio how to set constraints for a view inside a fragment
Attempting to attach a view to the bottom left of a fragment and it is not obeying my commands :(

The code compiles and runs but the button is very much in the top left of the screen.

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">

    <ImageButton
        android:id="@+id/searchBtn"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:adjustViewBounds="true"
        android:background="@null"
        android:scaleType="centerInside"
        map:layout_constraintBottom_toBottomOf="parent"
        map:layout_constraintStart_toStartOf="parent"
        map:srcCompat="@drawable/loupe"/>
</fragment>

</code>```

New to android studio and don't yet completely understand all the patterns, so I feel like I might be attempting to do something the wrong way.

Should I be defining some sort of container and then putting the map fragment and the button inside of that?

But if I do that it brakes the map code in my main.

答:
Thanks @Tyler for your comment which i cannot accept as an answer because it is a comment.

"The commands layout_constraintBottom_toBottomOf and layout_constraintStart_toStartOf are for a ConstraintLayout. If you want them to be used, you need to put the view inside a ConstraintLayout. However, check out this question on how to lay out a fragment. The fragment layout shouldn't go inside the  tag, it should be its own file."

The fixed xml code looks like this (no need to change any of the other code) -

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map_fragment"
        android:name="com.google.android.gms.maps.SupportMapFragment" />

    <ImageButton
        android:id="@+id/searchBtn"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:adjustViewBounds="true"
        android:background="@null"
        android:scaleType="centerInside"
        map:layout_constraintBottom_toBottomOf="@id/map"
        map:layout_constraintStart_toStartOf="@id/map"
        map:srcCompat="@drawable/loupe"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
Attempting to attach a view to the bottom left of a fragment and it is not obeying my commands :(

The code compiles and runs but the button is very much in the top left of the screen.

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">

    <ImageButton
        android:id="@+id/searchBtn"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:adjustViewBounds="true"
        android:background="@null"
        android:scaleType="centerInside"
        map:layout_constraintBottom_toBottomOf="parent"
        map:layout_constraintStart_toStartOf="parent"
        map:srcCompat="@drawable/loupe"/>
</fragment>

New to android studio and don't yet completely understand all the patterns, so I feel like I might be attempting to do something the wrong way.

Should I be defining some sort of container and then putting the map fragment and the button inside of that?

But if I do that it brakes the map code in my main.

Body:
Thanks @Tyler for your comment which i cannot accept as an answer because it is a comment.

"The commands layout_constraintBottom_toBottomOf and layout_constraintStart_toStartOf are for a ConstraintLayout. If you want them to be used, you need to put the view inside a ConstraintLayout. However, check out this question on how to lay out a fragment. The fragment layout shouldn't go inside the  tag, it should be its own file."

The fixed xml code looks like this (no need to change any of the other code) -

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map_fragment"
        android:name="com.google.android.gms.maps.SupportMapFragment" />

    <ImageButton
        android:id="@+id/searchBtn"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:adjustViewBounds="true"
        android:background="@null"
        android:scaleType="centerInside"
        map:layout_constraintBottom_toBottomOf="@id/map"
        map:layout_constraintStart_toStartOf="@id/map"
        map:srcCompat="@drawable/loupe"/>

</androidx.constraintlayout.widget.ConstraintLayout>


问:
I want all rows of the excel file to be saved as a list. What to do
```<code>data=[]
workbook=openpyxl.load_workbook(filename='crawling.xlsx')
sheet=workbook.active
for row in sheet.rows:
    data.append(row[0].value)
</code>```

This prints only part. I want to bring the whole. Excel files are only stored in column A.

答: If I understand you correctly can't you just merge them?</p>

Body:
data=[]
workbook=openpyxl.load_workbook(filename='crawling.xlsx')
sheet=workbook.active
for row in sheet.rows:
    data.append(row[0].value)

This prints only part. I want to bring the whole. Excel files are only stored in column A.


问:
How to get data before the component mount?
I've a screen in my app that loads some data. But I think the component is mounting before the them load. Probably because the token was not generated yet. How can I do to this not happen without using a timeout, maybe using a life cycle method from react native?
ps: When I save the file 2 or three times the data loads, before the component is empty.

My code:

```<code>import React, { Component } from 'react'
import {
    View,
    FlatList,
    Text
} from 'react-native'

import Intl from 'intl'
import 'intl/locale-data/jsonp/pt-BR'
import { connect } from 'react-redux'

import { loadPortifolio } from '../../../../store/actions/portifolio'
import CardTitle from '../CardComponents/CardTitle'
import MoneyIcon from '../../../../assets/images/money.svg'
import SavingsIcon from '../../../../assets/images/savings.svg'
import BankIcon from '../../../../assets/images/bank.svg'
import CartIcon from '../../../../assets/images/cart.svg'

import styles from './styles'

class Portifolio extends Component {
    state = {
        list: [],
    }

    componentDidMount = async() => {
        await this.props.onLoadPortifolio()
        this.setState({list: Object.entries(this.props.list).sort()}) //This is the part that I want to load before the component mount.
    }

    renderListDescription = (description) => {
        let newDescription = ''
        if (description == 'money'){
            return newDescription = 'DINHEIRO'
        } else if (description == 'contacorrente') {
            return newDescription = 'CONTA CORRENTE'
        } else if (description == 'credit') {
            return newDescription = 'CARTÃO DE CRÉDITO'
        } else {
            return newDescription = 'POUPANÇA'
        }
    }

    renderListIcon = (description) => {
        if (description == 'money'){
            return <MoneyIcon width={24} height={24} />
        } else if (description == 'contacorrente') {
            return <BankIcon width={24} height={24} />
        } else if (description == 'credit') {
            return <CartIcon width={24} height={24} />
        } else {
            return <SavingsIcon width={24} height={24} />
        }
    }

    render(){
        return (
            <View style={styles.container}>
                <CardTitle title='SALDOS CARTEIRAS'/>

                <FlatList
                    data={this.state.list.slice(0, 4)}
                    keyExtractor={(item, index) => item.key}
                    renderItem={({item}) =>

                        <View style={styles.list}>
                            <View style={styles.listIconDescription}>
                                {this.renderListIcon(item[0])}
                                <Text style={styles.descriptionText}>{this.renderListDescription(item[0])}</Text>
                            </View>
                            <Text
                                style={[item[1] >= 0 ?  {color: '#028FFF'} :
                                    {color: '#9F261A'}, styles.valueText]}>
                                        {Intl.NumberFormat('pt-BR',
                                            { style: 'currency', currency: 'BRL' })
                                            .format(item[1])}
                            </Text>
                        </View>
                    }
                />
            </View>
        )
    }
}

const mapStateToProps = ({ portifolio }) => {
    return {
        list: portifolio.list,
        loadError: portifolio.loadError,
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onLoadPortifolio: () => dispatch(loadPortifolio())
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Portifolio)
</code>```

答:
You can use the lifecycle method

componentWillMount

This is the most logical place to fetch data. Fetch it just before the component will mount, right? Although there is a big but...

There are a couple of problems though.

1) First, the big one: componentWillMount is deprecated as of React 16.3 (March 2018).

2) An API call with fetch or axios inside componentWillMount will not return before the first render. This means the component will render with empty data at least once.

Because of the nature of async events in JavaScript, when you kick off an API call, the browser goes back to doing other work in the meantime. When React is rendering a component, it doesn’t wait for componentWillMount to finish whatever it started – React marches on and continues to render.

There is no way to “pause” rendering to wait for data to arrive. You cannot return a promise from componentWillMount or wrangle in a setTimeout somehow. The right way to handle this is to set up the component’s initial state so that even when it renders with no data, it still looks acceptable.

So what can you do? You could render an empty list or display placeholders, or maybe show a little hint to the new user about how to get started. Whatever you do, don’t try to iterate over an array of undefined or you’ll get the dreaded “Cannot read property ‘map’ of undefined” error.

Body:
I've a screen in my app that loads some data. But I think the component is mounting before the them load. Probably because the token was not generated yet. How can I do to this not happen without using a timeout, maybe using a life cycle method from react native?
ps: When I save the file 2 or three times the data loads, before the component is empty.

My code:

import React, { Component } from 'react'
import {
    View,
    FlatList,
    Text
} from 'react-native'

import Intl from 'intl'
import 'intl/locale-data/jsonp/pt-BR'
import { connect } from 'react-redux'

import { loadPortifolio } from '../../../../store/actions/portifolio'
import CardTitle from '../CardComponents/CardTitle'
import MoneyIcon from '../../../../assets/images/money.svg'
import SavingsIcon from '../../../../assets/images/savings.svg'
import BankIcon from '../../../../assets/images/bank.svg'
import CartIcon from '../../../../assets/images/cart.svg'

import styles from './styles'

class Portifolio extends Component {
    state = {
        list: [],
    }

    componentDidMount = async() => {
        await this.props.onLoadPortifolio()
        this.setState({list: Object.entries(this.props.list).sort()}) //This is the part that I want to load before the component mount.
    }

    renderListDescription = (description) => {
        let newDescription = ''
        if (description == 'money'){
            return newDescription = 'DINHEIRO'
        } else if (description == 'contacorrente') {
            return newDescription = 'CONTA CORRENTE'
        } else if (description == 'credit') {
            return newDescription = 'CARTÃO DE CRÉDITO'
        } else {
            return newDescription = 'POUPANÇA'
        }
    }

    renderListIcon = (description) => {
        if (description == 'money'){
            return <MoneyIcon width={24} height={24} />
        } else if (description == 'contacorrente') {
            return <BankIcon width={24} height={24} />
        } else if (description == 'credit') {
            return <CartIcon width={24} height={24} />
        } else {
            return <SavingsIcon width={24} height={24} />
        }
    }

    render(){
        return (
            <View style={styles.container}>
                <CardTitle title='SALDOS CARTEIRAS'/>

                <FlatList
                    data={this.state.list.slice(0, 4)}
                    keyExtractor={(item, index) => item.key}
                    renderItem={({item}) =>

                        <View style={styles.list}>
                            <View style={styles.listIconDescription}>
                                {this.renderListIcon(item[0])}
                                <Text style={styles.descriptionText}>{this.renderListDescription(item[0])}</Text>
                            </View>
                            <Text
                                style={[item[1] >= 0 ?  {color: '#028FFF'} :
                                    {color: '#9F261A'}, styles.valueText]}>
                                        {Intl.NumberFormat('pt-BR',
                                            { style: 'currency', currency: 'BRL' })
                                            .format(item[1])}
                            </Text>
                        </View>
                    }
                />
            </View>
        )
    }
}

const mapStateToProps = ({ portifolio }) => {
    return {
        list: portifolio.list,
        loadError: portifolio.loadError,
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onLoadPortifolio: () => dispatch(loadPortifolio())
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Portifolio)


问:
python 3: How to rearrange dictionaries in list by new variable without adding new key and value
I want to rearrange dictionaries with new variable which is newly defined with existing variables.
For example,

```<code>security_info = [{'date': '19.04.15', 'price': 785000, 'trade': 79620},
                 {'date': '19.04.16', 'price': 785000, 'trade': 68203},
                 {'date': '19.04.17', 'price': 754000, 'trade': 165929},
                 {'date': '19.04.18', 'price': 779000, 'trade': 94462},
                 {'date': '19.04.19', 'price': 770000, 'trade': 76814},
                 {'date': '19.04.22', 'price': 774000, 'trade': 58079},
                 {'date': '19.04.23', 'price': 775000, 'trade': 79128},
                 {'date': '19.04.24', 'price': 771000, 'trade': 61650},
                 {'date': '19.04.25', 'price': 757000, 'trade': 111805},
                 {'date': '19.04.26', 'price': 764000, 'trade': 68237}]
</code>```

I want rearrange this list by 'net return', which is defined by 'price today/price yesterday *100' (of course 'net return' of first date does not exist).
But I don't want to solve this by adding new key and value.

Thanks.

答:
I should preface this by making a few comments:

This is not a great structure for these data. I would recommend looking into pandas, which can handle dates and would work well in this situation.

Making a new value for the net return would probably be a good idea, since this is what you are using to sort the values by.

Nevertheless, if you want to sort the values based on the net return, and the list is currently sorted by date (as in your example), then something like this could work:

```<code>def net_return(entry):
     i = security_info.index(entry)
     if i>0:
         return security_info[i]['price']/security_info[i-1]['price']
     else:
         return -1

sorted(security_info, key=net_return)
</code>```

This returns the following list:

```<code>[{'date': '19.04.15', 'price': 785000, 'trade': 79620},
 {'date': '19.04.17', 'price': 754000, 'trade': 165929},
 {'date': '19.04.25', 'price': 757000, 'trade': 111805},
 {'date': '19.04.19', 'price': 770000, 'trade': 76814},
 {'date': '19.04.24', 'price': 771000, 'trade': 61650},
 {'date': '19.04.16', 'price': 785000, 'trade': 68203},
 {'date': '19.04.23', 'price': 775000, 'trade': 79128},
 {'date': '19.04.22', 'price': 774000, 'trade': 58079},
 {'date': '19.04.26', 'price': 764000, 'trade': 68237},
 {'date': '19.04.18', 'price': 779000, 'trade': 94462}]
</code>```

Hope this helps.

Body:
I want to rearrange dictionaries with new variable which is newly defined with existing variables.
For example,

security_info = [{'date': '19.04.15', 'price': 785000, 'trade': 79620},
                 {'date': '19.04.16', 'price': 785000, 'trade': 68203},
                 {'date': '19.04.17', 'price': 754000, 'trade': 165929},
                 {'date': '19.04.18', 'price': 779000, 'trade': 94462},
                 {'date': '19.04.19', 'price': 770000, 'trade': 76814},
                 {'date': '19.04.22', 'price': 774000, 'trade': 58079},
                 {'date': '19.04.23', 'price': 775000, 'trade': 79128},
                 {'date': '19.04.24', 'price': 771000, 'trade': 61650},
                 {'date': '19.04.25', 'price': 757000, 'trade': 111805},
                 {'date': '19.04.26', 'price': 764000, 'trade': 68237}]

I want rearrange this list by 'net return', which is defined by 'price today/price yesterday *100' (of course 'net return' of first date does not exist).
But I don't want to solve this by adding new key and value.

Thanks.

Body:
I should preface this by making a few comments:

This is not a great structure for these data. I would recommend looking into pandas, which can handle dates and would work well in this situation.

Making a new value for the net return would probably be a good idea, since this is what you are using to sort the values by.

Nevertheless, if you want to sort the values based on the net return, and the list is currently sorted by date (as in your example), then something like this could work:

def net_return(entry):
     i = security_info.index(entry)
     if i>0:
         return security_info[i]['price']/security_info[i-1]['price']
     else:
         return -1

sorted(security_info, key=net_return)

This returns the following list:

[{'date': '19.04.15', 'price': 785000, 'trade': 79620},
 {'date': '19.04.17', 'price': 754000, 'trade': 165929},
 {'date': '19.04.25', 'price': 757000, 'trade': 111805},
 {'date': '19.04.19', 'price': 770000, 'trade': 76814},
 {'date': '19.04.24', 'price': 771000, 'trade': 61650},
 {'date': '19.04.16', 'price': 785000, 'trade': 68203},
 {'date': '19.04.23', 'price': 775000, 'trade': 79128},
 {'date': '19.04.22', 'price': 774000, 'trade': 58079},
 {'date': '19.04.26', 'price': 764000, 'trade': 68237},
 {'date': '19.04.18', 'price': 779000, 'trade': 94462}]

Hope this helps.


问:
Um, Hi I'm a Beginner and don't know how to speed my code up. My homework is to write a program for CCC '20 S2 - Escape Room faster than two seconds
Um, hi I'm a beginner and don't know how to speed my code up. My homework is to write a program for CCC '20 S2 - Escape Room faster than two seconds.
The objective is to determine if it is possible to escape from a room. The room is an M-by-N grid with each position (cell) containing a positive integer. The rows are numbered 1,2,…,M and the columns are numbered 1,2,…,N. We use (r,c) to refer to the cell in row r and column c.

You start in the top-left corner at (1,1) and exit from the bottom-right corner at (M,N). If you are in a cell containing the value x, then you can jump to any cell (a,b) satisfying a×b=x. For example, if you are in a cell containing a 6, you can jump to cell (2,3).

Note that from a cell containing a 6, there are up to four cells you can jump to: (2,3),(3,2),(1,6), or (6,1). If the room is a 5-by-6 grid, there isn't a row 6 so only the first three jumps would be possible.
Here is my Code:

```<code>package programs;

import java.util.ArrayList;
import java.util.Scanner;

public class Escape_Room {

    static boolean method(int[][] array, int m, int n, int x, int y, boolean check, ArrayList<String> list) {
        boolean flag=false;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(array[i][j]==(x*y) && !list.contains(i+", "+j)) {
                    list.add(i+", "+j);
                    flag=true;
                    if (i==0 && j==0) {
                        check=true;
                        return check;
                    }
                    boolean o=method(array, m, n, i+1, j+1, check, list);
                    if (o==true) {
                        return o;
                    }
                }
            }
        }
        if (flag==false) {
            return flag;
        }
        return check;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input=new Scanner(System.in);
        int m=Integer.parseInt(input.nextLine());
        int n=Integer.parseInt(input.nextLine());
        int[][] array=new int[m][n];
        String[] strarray=new String[m];
        for (int i=0; i<m; i++) {
            strarray=input.nextLine().split(" ");
            for (int j=0; j<n; j++) {
                array[i][j]=Integer.parseInt(strarray[j]);
            }
        }
        ArrayList<String> list=new ArrayList<String>();
        boolean o=method(array, m, n, m, n, false, list);
        if (o==true) {
            System.out.println("yes");
        }
        else if (o==false) {
            System.out.println("no");
        }
    }

}
</code>```

答:
Take a look at this. I have tried grids 10x10 - solved in cca 3-4ms (including input), which is far below 2s.

```<code>class Escape_Room {

    static boolean method(Map<Integer, Set<Integer>> transitionMap, int size, int start) {
        Set<Integer> closed = new HashSet<Integer>(size);
        Queue<Integer> q = new LinkedList<>();
        q.add(start);
        int key;
        while(!q.isEmpty()) {
            key = q.poll();
            if(closed.contains(key)) {
                continue;
            }
            if(key == size) {
                return true;
            }
            closed.add(key);
            if(transitionMap.containsKey(key)) {
                for (int i : transitionMap.get(key)) {
                    if(i == size) {
                        return true;
                    }
                    if (!closed.contains(i)) {
                        q.add(i);
                    }
                }
            }
        }
        return false;
    }

}

public class Solution {
    static StringBuilder str;
    static InputStreamReader in;
    static int buf;

    private static int readInt() throws IOException {
        buf = 0;
        int c;
        do {
            c = in.read();
        } while (c < '0' || c > '9' );
        do {
            buf = 10*buf + c - 48;
            c = in.read();
        } while (!(c < '0' || c > '9' ));
        return buf;
    }

    public static void main(String[] args) throws IOException {
        long t1 = System.currentTimeMillis();
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        in = new InputStreamReader(new BufferedInputStream(System.in));
        int m=readInt();
        int n=readInt();
        int size = m*n;
        Map<Integer, Set<Integer>> transitionMap = new HashMap<>(size);
        Set<Integer> temp;
        int start = 0, key = 0;

        for (int i = 0, j, value; i < m; i++) {
            for(j = 0; j < n; ++j) {
                key = (i+1)*(j+1);
                value = readInt();
                if(i == 0 && j == 0) {
                    start = key;
                }
                if (transitionMap.containsKey(key)) {
                    transitionMap.get(key).add(value);
                } else {
                    temp = new HashSet<>(size);
                    temp.add(value);
                    transitionMap.put(key, temp);
                }
            }
        }
        long t2 = System.currentTimeMillis();
        boolean o = Escape_Room.method(transitionMap, size, start);
        long t3 = System.currentTimeMillis();
        System.out.println(o?"yes":"no");
        System.out.println("Finished in: " + (t3 - t1) + "ms. Input: " + (t2 - t1)  + "ms. Solving: " + (t3 - t2) + " ms.");
    }
}
</code>```

Body:
Um, hi I'm a beginner and don't know how to speed my code up. My homework is to write a program for CCC '20 S2 - Escape Room faster than two seconds.
The objective is to determine if it is possible to escape from a room. The room is an M-by-N grid with each position (cell) containing a positive integer. The rows are numbered 1,2,…,M and the columns are numbered 1,2,…,N. We use (r,c) to refer to the cell in row r and column c.

You start in the top-left corner at (1,1) and exit from the bottom-right corner at (M,N). If you are in a cell containing the value x, then you can jump to any cell (a,b) satisfying a×b=x. For example, if you are in a cell containing a 6, you can jump to cell (2,3).

Note that from a cell containing a 6, there are up to four cells you can jump to: (2,3),(3,2),(1,6), or (6,1). If the room is a 5-by-6 grid, there isn't a row 6 so only the first three jumps would be possible.
Here is my Code:

package programs;

import java.util.ArrayList;
import java.util.Scanner;

public class Escape_Room {

    static boolean method(int[][] array, int m, int n, int x, int y, boolean check, ArrayList<String> list) {
        boolean flag=false;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(array[i][j]==(x*y) && !list.contains(i+", "+j)) {
                    list.add(i+", "+j);
                    flag=true;
                    if (i==0 && j==0) {
                        check=true;
                        return check;
                    }
                    boolean o=method(array, m, n, i+1, j+1, check, list);
                    if (o==true) {
                        return o;
                    }
                }
            }
        }
        if (flag==false) {
            return flag;
        }
        return check;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input=new Scanner(System.in);
        int m=Integer.parseInt(input.nextLine());
        int n=Integer.parseInt(input.nextLine());
        int[][] array=new int[m][n];
        String[] strarray=new String[m];
        for (int i=0; i<m; i++) {
            strarray=input.nextLine().split(" ");
            for (int j=0; j<n; j++) {
                array[i][j]=Integer.parseInt(strarray[j]);
            }
        }
        ArrayList<String> list=new ArrayList<String>();
        boolean o=method(array, m, n, m, n, false, list);
        if (o==true) {
            System.out.println("yes");
        }
        else if (o==false) {
            System.out.println("no");
        }
    }

}

Body:
Take a look at this. I have tried grids 10x10 - solved in cca 3-4ms (including input), which is far below 2s.

class Escape_Room {

    static boolean method(Map<Integer, Set<Integer>> transitionMap, int size, int start) {
        Set<Integer> closed = new HashSet<Integer>(size);
        Queue<Integer> q = new LinkedList<>();
        q.add(start);
        int key;
        while(!q.isEmpty()) {
            key = q.poll();
            if(closed.contains(key)) {
                continue;
            }
            if(key == size) {
                return true;
            }
            closed.add(key);
            if(transitionMap.containsKey(key)) {
                for (int i : transitionMap.get(key)) {
                    if(i == size) {
                        return true;
                    }
                    if (!closed.contains(i)) {
                        q.add(i);
                    }
                }
            }
        }
        return false;
    }

}

public class Solution {
    static StringBuilder str;
    static InputStreamReader in;
    static int buf;

    private static int readInt() throws IOException {
        buf = 0;
        int c;
        do {
            c = in.read();
        } while (c < '0' || c > '9' );
        do {
            buf = 10*buf + c - 48;
            c = in.read();
        } while (!(c < '0' || c > '9' ));
        return buf;
    }

    public static void main(String[] args) throws IOException {
        long t1 = System.currentTimeMillis();
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        in = new InputStreamReader(new BufferedInputStream(System.in));
        int m=readInt();
        int n=readInt();
        int size = m*n;
        Map<Integer, Set<Integer>> transitionMap = new HashMap<>(size);
        Set<Integer> temp;
        int start = 0, key = 0;

        for (int i = 0, j, value; i < m; i++) {
            for(j = 0; j < n; ++j) {
                key = (i+1)*(j+1);
                value = readInt();
                if(i == 0 && j == 0) {
                    start = key;
                }
                if (transitionMap.containsKey(key)) {
                    transitionMap.get(key).add(value);
                } else {
                    temp = new HashSet<>(size);
                    temp.add(value);
                    transitionMap.put(key, temp);
                }
            }
        }
        long t2 = System.currentTimeMillis();
        boolean o = Escape_Room.method(transitionMap, size, start);
        long t3 = System.currentTimeMillis();
        System.out.println(o?"yes":"no");
        System.out.println("Finished in: " + (t3 - t1) + "ms. Input: " + (t2 - t1)  + "ms. Solving: " + (t3 - t2) + " ms.");
    }
}


问:
How to catch html compile errors from invalid attributes by binding in AngularJS
I'm quite new to AngularJS.
So I have an SVG which I need to modify from the controller:

```<code><svg class="rotate" viewbox="0 0 250 250">
   <path transform="translate(125, 125)" d="{{user.timerAnim}}"/>
</svg>
</code>```

user.timerAnim is populated from the controller in a timeout.
This works, but it throws exceptions to the console, because initially the browser reads the d attribute as invalid, after which AngularJS binds to it and starts working normally.

I had a similar problem before with img tag's src attribute, which had a solution by using ng-src

How do I catch these errors? Is this not a good way to animate an SVG in AngularJS?

答:
If anyone's interested, I found out you can use ng-attr prefix for any html (and svg) attributes to use bind to angularjs. So this solved the problem:</p>

```<code><svg class="rotate" viewbox="0 0 250 250">
   <path transform="translate(125, 125)" ng-attr-d="{{user.timerAnim}}"/>
</svg>
</code>```

Body:
I'm quite new to AngularJS.
So I have an SVG which I need to modify from the controller:

<svg class="rotate" viewbox="0 0 250 250">
   <path transform="translate(125, 125)" d="{{user.timerAnim}}"/>
</svg>

user.timerAnim is populated from the controller in a timeout.
This works, but it throws exceptions to the console, because initially the browser reads the d attribute as invalid, after which AngularJS binds to it and starts working normally.

I had a similar problem before with img tag's src attribute, which had a solution by using ng-src

How do I catch these errors? Is this not a good way to animate an SVG in AngularJS?

Body:
If anyone's interested, I found out you can use ng-attr prefix for any html (and svg) attributes to use bind to angularjs. So this solved the problem:

<svg class="rotate" viewbox="0 0 250 250">
   <path transform="translate(125, 125)" ng-attr-d="{{user.timerAnim}}"/>
</svg>


问:
Maximum call stack size exceeded - aws-cdk
Getting the below error while running any cdk cli command:

```<code>Maximum call stack size exceeded
(node:46265) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 beforeExit listeners added to [process]. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)
Subprocess exited with error 1
</code>```

sample code using cdk cli against:

```<code>import { Stack, Construct, StackProps } from '@aws-cdk/core';
import * as s3 from '@aws-cdk/aws-s3'

export class MyFirstS3Stack extends Stack {
    constructor(scope: Construct, id: string, props?: StackProps) {
        super(scope,id,props);

        new s3.Bucket(this,'MyFirstBucket');

    }
}
</code>```

答: I was able to resolve the above issue, after deleting the old compiled js files for above construct. I have re-complied with the above file and everything started working again. </p>

Body:
Getting the below error while running any cdk cli command:

Maximum call stack size exceeded
(node:46265) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 beforeExit listeners added to [process]. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)
Subprocess exited with error 1

sample code using cdk cli against:

import { Stack, Construct, StackProps } from '@aws-cdk/core';
import * as s3 from '@aws-cdk/aws-s3'

export class MyFirstS3Stack extends Stack {
    constructor(scope: Construct, id: string, props?: StackProps) {
        super(scope,id,props);

        new s3.Bucket(this,'MyFirstBucket');

    }
}


问:
angularjs force uppercase in textbox
I've tried using the uppercase filter but it does not work. I've tried doing it two ways:

```<code><input type="text" ng-model="test" uppercase/>
</code>```

and

```<code><input type="text" ng-model="{{test | uppercase}}"/>
</code>```

The 2nd triggers a javascript error:

Syntax Error: Token 'test' is unexpected, expecting [:]

I want the text to be forced to uppercase as the user types in the textbox.

How can I do that?

答:
If you want to change model and value, use:

```<code>angular.module('MyApp').directive('uppercased', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            element.bind("blur change input", function () {
                ngModel.$setViewValue($(this).val().toUpperCase());
                $(this).val($(this).val().toUpperCase());
            });
            element.css("text-transform","uppercase");
        }
    };
});
</code>```

Then add uppercased to your html input text

```<code><input  type="text" uppercased />
</code>```

Title: angularjs force uppercase in textbox

Body:
I've tried using the uppercase filter but it does not work. I've tried doing it two ways:

<input type="text" ng-model="test" uppercase/>

and

<input type="text" ng-model="{{test | uppercase}}"/>

The 2nd triggers a javascript error:

Syntax Error: Token 'test' is unexpected, expecting [:]

I want the text to be forced to uppercase as the user types in the textbox.

How can I do that?

Body:
If you want to change model and value, use:

angular.module('MyApp').directive('uppercased', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            element.bind("blur change input", function () {
                ngModel.$setViewValue($(this).val().toUpperCase());
                $(this).val($(this).val().toUpperCase());
            });
            element.css("text-transform","uppercase");
        }
    };
});

Then add uppercased to your html input text

<input  type="text" uppercased />


问:
How can I detect the user sign up event from Azure API Management?
I've been using Azure API Management recently, and I would like to know if there is a way to detect the sign up process performed from the included Developer Portal.
Basically I need to be able to get the user unique id, to be able to map data stored in a database.
Is configuring Delegation the only way to capture this event?</p>

答:
Try to enable the Resource Logs, it includes the userId.

Reference - https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-use-azure-monitor#resource-logs