问:
Mongoexport exporting invalid json files
I collected some tweets from the twitter API and stored it to mongodb, I tried exporting the data to a JSON file and didn't have any issues there, until I tried to make a python script to read the JSON and convert it to a csv. I get this traceback error with my code:

```<code>json.decoder.JSONDecodeError: Extra data: line 367 column 1 (char 9745)
</code>```

So, after digging around the internet I was pointed to check the actual JSON data in an online validator, which I did. This gave me the error of:

```<code>Multiple JSON root elements
</code>```

from the site https://jsonformatter.curiousconcept.com/

Here are pictures of the 1st/2nd object beginning/end of the file:

or a link to the data here

Now, the problem is, I haven't found anything on the internet of how to handle that error. I'm not sure if it's an error with the data I've collected, exported, or if I just don't know how to work with it.

My end game with these tweets is to make a network graph. I was looking at either Networkx or Gephi, which is why I'd like to get a csv file.

答:
Elaborating on @MYGz suggestion to use --jsonArray

Your post doesn't show how you exported the data from mongo. If you use the following via the terminal, you will get valid json from mongodb:

```<code>mongoexport --collection=somecollection --db=somedb --jsonArray --out=validfile.json
</code>```

Replace somecollection, somedb and validfile.json with your target collection, target database, and desired output filename respectively.

The following: mongoexport --collection=somecollection --db=somedb --out=validfile.json...will NOT give you the results you are looking for because:

By default mongoexport writes data using one JSON document for every
  MongoDB document. Ref

Body:
I collected some tweets from the twitter API and stored it to mongodb, I tried exporting the data to a JSON file and didn't have any issues there, until I tried to make a python script to read the JSON and convert it to a csv. I get this traceback error with my code:

json.decoder.JSONDecodeError: Extra data: line 367 column 1 (char 9745)

So, after digging around the internet I was pointed to check the actual JSON data in an online validator, which I did. This gave me the error of:

Multiple JSON root elements

from the site https://jsonformatter.curiousconcept.com/

Here are pictures of the 1st/2nd object beginning/end of the file:

or a link to the data here

Now, the problem is, I haven't found anything on the internet of how to handle that error. I'm not sure if it's an error with the data I've collected, exported, or if I just don't know how to work with it.

My end game with these tweets is to make a network graph. I was looking at either Networkx or Gephi, which is why I'd like to get a csv file.

Body:
Elaborating on @MYGz suggestion to use --jsonArray

Your post doesn't show how you exported the data from mongo. If you use the following via the terminal, you will get valid json from mongodb:

mongoexport --collection=somecollection --db=somedb --jsonArray --out=validfile.json

Replace somecollection, somedb and validfile.json with your target collection, target database, and desired output filename respectively.

The following: mongoexport --collection=somecollection --db=somedb --out=validfile.json...will NOT give you the results you are looking for because:

By default mongoexport writes data using one JSON document for every
  MongoDB document. Ref


来源: stackexchange

问:
How do I submit a boolean parameter in Rails?
I'm submitting a parameter show_all with the value true. This value isn't associated with a model.

My controller is assigning this parameter to an instance variable:

```<code>@show_all = params[:show_all]
</code>```

However, @show_all.is_a? String, and if @show_all == true always fails.

What values does Rails parse as booleans? How can I explicitly specify that my parameter is a boolean, and not a string?

答:
It's worth noting that if you're passing down a value to an ActiveModel in Rails > 5.2, the simpler solution is to use attribute,

```<code>class Model
  include ActiveModel::Attributes

  attribute :show_all, :boolean
end

Model.new(show_all: '0').show_all # => false
</code>```

As can be seen here.

Before 5.2 I use:

```<code>class Model
  include ActiveModel::Attributes

  attribute_reader :show_all

  def show_all=(value)
    @show_all = ActiveModel::Type::Boolean.new.cast(value)
  end
end

Model.new(show_all: '0').show_all # => false
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm submitting a parameter show_all with the value true. This value isn't associated with a model.

My controller is assigning this parameter to an instance variable:

@show_all = params[:show_all]

However, @show_all.is_a? String, and if @show_all == true always fails.

What values does Rails parse as booleans? How can I explicitly specify that my parameter is a boolean, and not a string?

Body:
It's worth noting that if you're passing down a value to an ActiveModel in Rails > 5.2, the simpler solution is to use attribute,

class Model
  include ActiveModel::Attributes

  attribute :show_all, :boolean
end

Model.new(show_all: '0').show_all # => false

As can be seen here.

Before 5.2 I use:

class Model
  include ActiveModel::Attributes

  attribute_reader :show_all

  def show_all=(value)
    @show_all = ActiveModel::Type::Boolean.new.cast(value)
  end
end

Model.new(show_all: '0').show_all # => false

ContentLicense: CC BY-SA 4.0


问:
show/hide buttons on resizable navbar
I have a nivagation bar with button links in row on resize the window to smaller width each button wrap underneath which changing the navigation height, gets removed from the nav and appended into a dropdown menu.

I managed to append wrapped buttons when the navigation height is higher than 80, but it will only work if the initial size of the screen is big which will have all buttons in one row. but if the screen started at a smaller width it won't append all wrapped buttons in the menu.

80">

Here is my attempt

$(window).resize(function() {
  var navbar = $("#navbar");
  var list = $("#list");
  var btns = $("#btns");
  var last_element;
  for (var i = 0; i < list.children().length; i++) {
    setTimeout(function() {
      if (list.height() > 80) {
        last_element = list.children().last();
        setTimeout(function() {
          $("#btns .dropdown-menu").prepend(last_element);
        }, 300);
        last_element.remove();
      }
    }, 500);

  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#navbar {
  width: fit-content;
  background-color: #dbdbdb;
  box-shadow: 2px 2px 2px #999;
  border-radius: 10px;
  padding: 10px;
}

#list {
  margin: 0;
  padding: 0;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
}

.item {
  color: #333;
  font-size: 30px;
  font-weight: bold;
  background-color: #f5f5f5;
  /*    display: inline-block; */
  padding: 10px 30px;
  border-radius: 5px;
  box-shadow: 2px 2px 2px #888;
  margin: 4px 2px;
  list-style-type: none;
}

.dropdown-menu {
  width: 200px;
  padding: 0 20px;
}</code>```

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

item 1

item 2

item 3

item 4

item 5

item 6

item 7

      <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Dropdown button
         </button>

```

I would love to have similar action to this image,

Can someone offer a snippet suggestion or what should I use to implement such action?

答:
I see you're using bootstrap. You still can do this without any JS if a collapsible menu on mobile devices is what you need.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

          Dropdown

          Action
          Another action

          Something else here

        Disabled

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>

```

Title: show/hide buttons on resizable navbar

Body:
I have a nivagation bar with button links in row on resize the window to smaller width each button wrap underneath which changing the navigation height, gets removed from the nav and appended into a dropdown menu.

I managed to append wrapped buttons when the navigation height is higher than 80, but it will only work if the initial size of the screen is big which will have all buttons in one row. but if the screen started at a smaller width it won't append all wrapped buttons in the menu.

80">

Here is my attempt

$(window).resize(function() {
  var navbar = $("#navbar");
  var list = $("#list");
  var btns = $("#btns");
  var last_element;
  for (var i = 0; i < list.children().length; i++) {
    setTimeout(function() {
      if (list.height() > 80) {
        last_element = list.children().last();
        setTimeout(function() {
          $("#btns .dropdown-menu").prepend(last_element);
        }, 300);
        last_element.remove();
      }
    }, 500);

  }
});

#navbar {
  width: fit-content;
  background-color: #dbdbdb;
  box-shadow: 2px 2px 2px #999;
  border-radius: 10px;
  padding: 10px;
}

#list {
  margin: 0;
  padding: 0;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
}

.item {
  color: #333;
  font-size: 30px;
  font-weight: bold;
  background-color: #f5f5f5;
  /*    display: inline-block; */
  padding: 10px 30px;
  border-radius: 5px;
  box-shadow: 2px 2px 2px #888;
  margin: 4px 2px;
  list-style-type: none;
}

.dropdown-menu {
  width: 200px;
  padding: 0 20px;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

item 1

item 2

item 3

item 4

item 5

item 6

item 7

      <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Dropdown button
         </button>

I would love to have similar action to this image,

Can someone offer a snippet suggestion or what should I use to implement such action?

Body:
I see you're using bootstrap. You still can do this without any JS if a collapsible menu on mobile devices is what you need.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>


问:
Retrieving routes and their paths from Spring Cloud Gateway (vs Zuul)
I’m trying to migrate JHipster from using Zuul to Spring Cloud Gateway. In the current Zuul implementation, there's a GatewayResource that's used to get a list of routes and their service instances.

package com.mycompany.myapp.web.rest;

import com.mycompany.myapp.web.rest.vm.RouteVM;

import java.util.ArrayList;
import java.util.List;

import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.http.*;
import org.springframework.security.access.annotation.Secured;
import com.mycompany.myapp.security.AuthoritiesConstants;
import org.springframework.web.bind.annotation.*;

/**
 * REST controller for managing Gateway configuration.
 */
@RestController
@RequestMapping("/api/gateway")
public class GatewayResource {

    private final RouteLocator routeLocator;

    private final DiscoveryClient discoveryClient;

    public GatewayResource(RouteLocator routeLocator, DiscoveryClient discoveryClient) {
        this.routeLocator = routeLocator;
        this.discoveryClient = discoveryClient;
    }

    /**
     * {@code GET  /routes} : get the active routes.
     *
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the list of routes.
     */
    @GetMapping("/routes")
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<List<RouteVM>> activeRoutes() {
        List<Route> routes = routeLocator.getRoutes();
        List<RouteVM> routeVMs = new ArrayList<>();
        routes.forEach(route -> {
            RouteVM routeVM = new RouteVM();
            routeVM.setPath(route.getFullPath());
            routeVM.setServiceId(route.getId());
            routeVM.setServiceInstances(discoveryClient.getInstances(route.getLocation()));
            routeVMs.add(routeVM);
        });
        return ResponseEntity.ok(routeVMs);
    }
}
```

<p>The <code>/api/gateway/routes</code> endpoint returns data like the following:</p>

```[
  {
    "path": "/services/blog/**",
    "serviceId": "blog",
    "serviceInstances": [
      {
        "serviceId": "BLOG",
        "secure": false,
        "instanceId": "blog:17c5482e0ccf49f19efb6dba8c5e5aa1",
        "instanceInfo": {
          "instanceId": "blog:17c5482e0ccf49f19efb6dba8c5e5aa1",
          "app": "BLOG",
          "appGroupName": null,
          "ipAddr": "192.168.0.20",
          "sid": "na",
          "homePageUrl": "http://192.168.0.20:8081/",
          "statusPageUrl": "http://192.168.0.20:8081/management/info",
          "healthCheckUrl": "http://192.168.0.20:8081/management/health",
          "secureHealthCheckUrl": null,
          "vipAddress": "blog",
          "secureVipAddress": "blog",
          "countryId": 1,
          "dataCenterInfo": {
            "@class": "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo",
            "name": "MyOwn"
          },
          "hostName": "192.168.0.20",
          "status": "UP",
          "overriddenStatus": "UNKNOWN",
          "leaseInfo": {
            "renewalIntervalInSecs": 5,
            "durationInSecs": 10,
            "registrationTimestamp": 1581934876730,
            "lastRenewalTimestamp": 1581935287273,
            "evictionTimestamp": 0,
            "serviceUpTimestamp": 1581934876214
          },
          "isCoordinatingDiscoveryServer": false,
          "metadata": {
            "zone": "primary",
            "profile": "dev",
            "management.port": "8081",
            "version": "0.0.1-SNAPSHOT"
          },
          "lastUpdatedTimestamp": 1581934876730,
          "lastDirtyTimestamp": 1581934876053,
          "actionType": "ADDED",
          "asgName": null
        },
        "port": 8081,
        "host": "192.168.0.20",
        "metadata": {
          "zone": "primary",
          "profile": "dev",
          "management.port": "8081",
          "version": "0.0.1-SNAPSHOT"
        },
        "uri": "http://192.168.0.20:8081",
        "scheme": null
      }
    ]
  }
]
```

<p>How can I implement the same endpoint in Spring Cloud Gateway? My config in <code>application.yml</code> is as follows:</p>

```spring:
  application:
    name: jhipster
  cloud:
    gateway:
      default-filters:
        - TokenRelay
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
          predicates:
            - name: Path
              args:
                pattern: "'/services/'+serviceId.toLowerCase()+'/**'"
          filters:
            - name: RewritePath
              args:
                regexp: "'/services/' + serviceId.toLowerCase() + '/(?<remaining>.*)'"
                replacement: "'/${remaining}'"
          route-id-prefix: ""
      httpclient:
        pool:
          max-connections: 1000
```

<p>I tried using <code>RouteLocator</code> as follows:</p>

<pre class="lang-java prettyprint-override"><code>package com.mycompany.myapp.web.rest;

import com.mycompany.myapp.security.AuthoritiesConstants;
import com.mycompany.myapp.web.rest.vm.RouteVM;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.route.*;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

/**
 * REST controller for managing Gateway configuration.
 */
@RestController
@RequestMapping("/api/gateway")
public class GatewayResource {

    private final RouteLocator routeLocator;

    private final DiscoveryClient discoveryClient;

    public GatewayResource(RouteLocator routeLocator, DiscoveryClient discoveryClient) {
        this.routeLocator = routeLocator;
        this.discoveryClient = discoveryClient;
    }

    /**
     * {@code GET  /routes} : get the active routes.
     *
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the list of routes.
     */
    @GetMapping("/routes")
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<List<RouteVM>> activeRoutes() {
        Flux<Route> routes = routeLocator.getRoutes();
        List<RouteVM> routeVMs = new ArrayList<>();
        routes.subscribe(route -> {
            System.out.println("route: " + route.toString());
            RouteVM routeVM = new RouteVM();
            routeVM.setPath(route.getPredicate().toString());
            String serviceId = route.getId().substring(route.getId().indexOf("_") + 1).toLowerCase();
            routeVM.setServiceId(serviceId);
            routeVM.setServiceInstances(discoveryClient.getInstances(serviceId));
            routeVMs.add(routeVM);
        });
        return ResponseEntity.ok(routeVMs);
    }
}
</code>```

This is close as it returns the following:

```<code>[
  {
    "path": "Paths: [/services/blog/**], match trailing slash: true",
    "serviceId": "blog",
    "serviceInstances": [
      {
        "uri": "http://192.168.0.20:8081",
        "serviceId": "BLOG",
        "port": 8081,
        "host": "192.168.0.20",
        "instanceId": "blog:17c5482e0ccf49f19efb6dba8c5e5aa1",
        "secure": false,
        "instanceInfo": {
          "instanceId": "blog:17c5482e0ccf49f19efb6dba8c5e5aa1",
          "app": "BLOG",
          "appGroupName": null,
          "ipAddr": "192.168.0.20",
          "sid": "na",
          "homePageUrl": "http://192.168.0.20:8081/",
          "statusPageUrl": "http://192.168.0.20:8081/management/info",
          "healthCheckUrl": "http://192.168.0.20:8081/management/health",
          "secureHealthCheckUrl": null,
          "vipAddress": "blog",
          "secureVipAddress": "blog",
          "countryId": 1,
          "dataCenterInfo": {
            "@class": "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo",
            "name": "MyOwn"
          },
          "hostName": "192.168.0.20",
          "status": "UP",
          "overriddenStatus": "UNKNOWN",
          "leaseInfo": {
            "renewalIntervalInSecs": 5,
            "durationInSecs": 10,
            "registrationTimestamp": 1581934876730,
            "lastRenewalTimestamp": 1581965726885,
            "evictionTimestamp": 0,
            "serviceUpTimestamp": 1581934876214
          },
          "isCoordinatingDiscoveryServer": false,
          "metadata": {
            "zone": "primary",
            "profile": "dev",
            "management.port": "8081",
            "version": "0.0.1-SNAPSHOT"
          },
          "lastUpdatedTimestamp": 1581934876730,
          "lastDirtyTimestamp": 1581934876053,
          "actionType": "ADDED",
          "asgName": null
        },
        "metadata": {
          "zone": "primary",
          "profile": "dev",
          "management.port": "8081",
          "version": "0.0.1-SNAPSHOT"
        },
        "scheme": null
      }
    ]
  },
  {
    "path": "Paths: [/services/jhipster/**], match trailing slash: true",
    "serviceId": "jhipster",
    "serviceInstances": [{...}]
  }
]
</code>```

The printing of routes looks as follows:

```<code>route: Route{id='ReactiveCompositeDiscoveryClient_BLOG', uri=lb://BLOG, order=0, predicate=Paths: [/services/blog/**], match trailing slash: true, gatewayFilters=[[org.springframework.cloud.security.oauth2.gateway.TokenRelayGatewayFilterFactory$$Lambda$1404/0x0000000800a2dc40@2b9e183d, order = 1], [[RewritePath /services/blog/(?<remaining>.*) = '/${remaining}'], order = 1]], metadata={}}
route: Route{id='ReactiveCompositeDiscoveryClient_JHIPSTER', uri=lb://JHIPSTER, order=0, predicate=Paths: [/services/jhipster/**], match trailing slash: true, gatewayFilters=[[org.springframework.cloud.security.oauth2.gateway.TokenRelayGatewayFilterFactory$$Lambda$1404/0x0000000800a2dc40@59032a74, order = 1], [[RewritePath /services/jhipster/(?<remaining>.*) = '/${remaining}'], order = 1]], metadata={}}
</code>```

A couple of questions:

How do I get the predicate's path? route.getPredicate().toString() gives me "Paths: [/services/blog/**], match trailing slash: true" and I just want /services/blog/**.

Why doesn't spring.cloud.gateway.discovery.location.route-id-prefix: "" strip the default prefix? I have to strip it manually using route.getId().substring(route.getId().indexOf("_") + 1).toLowerCase().

Why does RouteLocator return the /services/jhipster route? This is a route to the gateway. With Zuul, only one route was returned.

答: I believe what you're looking for is already built in.  https://cloud.spring.io/spring-cloud-gateway/reference/html/#retrieving-the-routes-defined-in-the-gateway</p>

Body:
I’m trying to migrate JHipster from using Zuul to Spring Cloud Gateway. In the current Zuul implementation, there's a GatewayResource that's used to get a list of routes and their service instances.

package com.mycompany.myapp.web.rest;

import com.mycompany.myapp.web.rest.vm.RouteVM;

import java.util.ArrayList;
import java.util.List;

import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.http.*;
import org.springframework.security.access.annotation.Secured;
import com.mycompany.myapp.security.AuthoritiesConstants;
import org.springframework.web.bind.annotation.*;

/**
 * REST controller for managing Gateway configuration.
 */
@RestController
@RequestMapping("/api/gateway")
public class GatewayResource {

    private final RouteLocator routeLocator;

    private final DiscoveryClient discoveryClient;

    public GatewayResource(RouteLocator routeLocator, DiscoveryClient discoveryClient) {
        this.routeLocator = routeLocator;
        this.discoveryClient = discoveryClient;
    }

    /**
     * {@code GET  /routes} : get the active routes.
     *
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the list of routes.
     */
    @GetMapping("/routes")
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<List<RouteVM>> activeRoutes() {
        List<Route> routes = routeLocator.getRoutes();
        List<RouteVM> routeVMs = new ArrayList<>();
        routes.forEach(route -> {
            RouteVM routeVM = new RouteVM();
            routeVM.setPath(route.getFullPath());
            routeVM.setServiceId(route.getId());
            routeVM.setServiceInstances(discoveryClient.getInstances(route.getLocation()));
            routeVMs.add(routeVM);
        });
        return ResponseEntity.ok(routeVMs);
    }
}

The /api/gateway/routes endpoint returns data like the following:

[
  {
    "path": "/services/blog/**",
    "serviceId": "blog",
    "serviceInstances": [
      {
        "serviceId": "BLOG",
        "secure": false,
        "instanceId": "blog:17c5482e0ccf49f19efb6dba8c5e5aa1",
        "instanceInfo": {
          "instanceId": "blog:17c5482e0ccf49f19efb6dba8c5e5aa1",
          "app": "BLOG",
          "appGroupName": null,
          "ipAddr": "192.168.0.20",
          "sid": "na",
          "homePageUrl": "http://192.168.0.20:8081/",
          "statusPageUrl": "http://192.168.0.20:8081/management/info",
          "healthCheckUrl": "http://192.168.0.20:8081/management/health",
          "secureHealthCheckUrl": null,
          "vipAddress": "blog",
          "secureVipAddress": "blog",
          "countryId": 1,
          "dataCenterInfo": {
            "@class": "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo",
            "name": "MyOwn"
          },
          "hostName": "192.168.0.20",
          "status": "UP",
          "overriddenStatus": "UNKNOWN",
          "leaseInfo": {
            "renewalIntervalInSecs": 5,
            "durationInSecs": 10,
            "registrationTimestamp": 1581934876730,
            "lastRenewalTimestamp": 1581935287273,
            "evictionTimestamp": 0,
            "serviceUpTimestamp": 1581934876214
          },
          "isCoordinatingDiscoveryServer": false,
          "metadata": {
            "zone": "primary",
            "profile": "dev",
            "management.port": "8081",
            "version": "0.0.1-SNAPSHOT"
          },
          "lastUpdatedTimestamp": 1581934876730,
          "lastDirtyTimestamp": 1581934876053,
          "actionType": "ADDED",
          "asgName": null
        },
        "port": 8081,
        "host": "192.168.0.20",
        "metadata": {
          "zone": "primary",
          "profile": "dev",
          "management.port": "8081",
          "version": "0.0.1-SNAPSHOT"
        },
        "uri": "http://192.168.0.20:8081",
        "scheme": null
      }
    ]
  }
]

How can I implement the same endpoint in Spring Cloud Gateway? My config in application.yml is as follows:

spring:
  application:
    name: jhipster
  cloud:
    gateway:
      default-filters:
        - TokenRelay
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
          predicates:
            - name: Path
              args:
                pattern: "'/services/'+serviceId.toLowerCase()+'/**'"
          filters:
            - name: RewritePath
              args:
                regexp: "'/services/' + serviceId.toLowerCase() + '/(?<remaining>.*)'"
                replacement: "'/${remaining}'"
          route-id-prefix: ""
      httpclient:
        pool:
          max-connections: 1000

I tried using RouteLocator as follows:

package com.mycompany.myapp.web.rest;

import com.mycompany.myapp.security.AuthoritiesConstants;
import com.mycompany.myapp.web.rest.vm.RouteVM;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.route.*;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

/**
 * REST controller for managing Gateway configuration.
 */
@RestController
@RequestMapping("/api/gateway")
public class GatewayResource {

    private final RouteLocator routeLocator;

    private final DiscoveryClient discoveryClient;

    public GatewayResource(RouteLocator routeLocator, DiscoveryClient discoveryClient) {
        this.routeLocator = routeLocator;
        this.discoveryClient = discoveryClient;
    }

    /**
     * {@code GET  /routes} : get the active routes.
     *
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the list of routes.
     */
    @GetMapping("/routes")
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<List<RouteVM>> activeRoutes() {
        Flux<Route> routes = routeLocator.getRoutes();
        List<RouteVM> routeVMs = new ArrayList<>();
        routes.subscribe(route -> {
            System.out.println("route: " + route.toString());
            RouteVM routeVM = new RouteVM();
            routeVM.setPath(route.getPredicate().toString());
            String serviceId = route.getId().substring(route.getId().indexOf("_") + 1).toLowerCase();
            routeVM.setServiceId(serviceId);
            routeVM.setServiceInstances(discoveryClient.getInstances(serviceId));
            routeVMs.add(routeVM);
        });
        return ResponseEntity.ok(routeVMs);
    }
}

This is close as it returns the following:

[
  {
    "path": "Paths: [/services/blog/**], match trailing slash: true",
    "serviceId": "blog",
    "serviceInstances": [
      {
        "uri": "http://192.168.0.20:8081",
        "serviceId": "BLOG",
        "port": 8081,
        "host": "192.168.0.20",
        "instanceId": "blog:17c5482e0ccf49f19efb6dba8c5e5aa1",
        "secure": false,
        "instanceInfo": {
          "instanceId": "blog:17c5482e0ccf49f19efb6dba8c5e5aa1",
          "app": "BLOG",
          "appGroupName": null,
          "ipAddr": "192.168.0.20",
          "sid": "na",
          "homePageUrl": "http://192.168.0.20:8081/",
          "statusPageUrl": "http://192.168.0.20:8081/management/info",
          "healthCheckUrl": "http://192.168.0.20:8081/management/health",
          "secureHealthCheckUrl": null,
          "vipAddress": "blog",
          "secureVipAddress": "blog",
          "countryId": 1,
          "dataCenterInfo": {
            "@class": "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo",
            "name": "MyOwn"
          },
          "hostName": "192.168.0.20",
          "status": "UP",
          "overriddenStatus": "UNKNOWN",
          "leaseInfo": {
            "renewalIntervalInSecs": 5,
            "durationInSecs": 10,
            "registrationTimestamp": 1581934876730,
            "lastRenewalTimestamp": 1581965726885,
            "evictionTimestamp": 0,
            "serviceUpTimestamp": 1581934876214
          },
          "isCoordinatingDiscoveryServer": false,
          "metadata": {
            "zone": "primary",
            "profile": "dev",
            "management.port": "8081",
            "version": "0.0.1-SNAPSHOT"
          },
          "lastUpdatedTimestamp": 1581934876730,
          "lastDirtyTimestamp": 1581934876053,
          "actionType": "ADDED",
          "asgName": null
        },
        "metadata": {
          "zone": "primary",
          "profile": "dev",
          "management.port": "8081",
          "version": "0.0.1-SNAPSHOT"
        },
        "scheme": null
      }
    ]
  },
  {
    "path": "Paths: [/services/jhipster/**], match trailing slash: true",
    "serviceId": "jhipster",
    "serviceInstances": [{...}]
  }
]

The printing of routes looks as follows:

route: Route{id='ReactiveCompositeDiscoveryClient_BLOG', uri=lb://BLOG, order=0, predicate=Paths: [/services/blog/**], match trailing slash: true, gatewayFilters=[[org.springframework.cloud.security.oauth2.gateway.TokenRelayGatewayFilterFactory$$Lambda$1404/0x0000000800a2dc40@2b9e183d, order = 1], [[RewritePath /services/blog/(?<remaining>.*) = '/${remaining}'], order = 1]], metadata={}}
route: Route{id='ReactiveCompositeDiscoveryClient_JHIPSTER', uri=lb://JHIPSTER, order=0, predicate=Paths: [/services/jhipster/**], match trailing slash: true, gatewayFilters=[[org.springframework.cloud.security.oauth2.gateway.TokenRelayGatewayFilterFactory$$Lambda$1404/0x0000000800a2dc40@59032a74, order = 1], [[RewritePath /services/jhipster/(?<remaining>.*) = '/${remaining}'], order = 1]], metadata={}}

A couple of questions:

How do I get the predicate's path? route.getPredicate().toString() gives me "Paths: [/services/blog/**], match trailing slash: true" and I just want /services/blog/**.

Why doesn't spring.cloud.gateway.discovery.location.route-id-prefix: "" strip the default prefix? I have to strip it manually using route.getId().substring(route.getId().indexOf("_") + 1).toLowerCase().

Why does RouteLocator return the /services/jhipster route? This is a route to the gateway. With Zuul, only one route was returned.


问:
Django detailview filter by other fields like isbn
If I have another field like ISBN in book so how do I filter with this field in from django.views.generic import DetailField

here is my book/urls.py file code

```<code>urlpatterns = [
    path('',BookListView.as_view(), name="book_list"),
    path('<isbn>/',BookDetailView.as_view(), name="book_detail")
]
</code>```

book/views.py

```<code>class BookDetailView(DetailView):
    template_name = "book/detail.html"
    def get_queryset(self,*args, **kwargs):
        print(self.kwargs['isbn'])
        return BookModel.objects.filter(isbn=self.kwargs['isbn'])
</code>```

and the Error is

Generic detail view BookDetailView must be called with either an object pk or a slug in the URLconf.

答:
you can use isbn as slug

book/urls.py

```<code>urlpatterns = [
    path('',BookListView.as_view(), name="book_list"),
    path('<slug:isbn>/',BookDetailView.as_view(), name="book_detail")
]
</code>```

book/views.py

```<code>class BookDetailView(DetailView):
    model = BookModel
    template_name = "book/detail.html"
    slug_field = 'isbn'
    slug_url_kwarg = 'isbn'
</code>```

Body:
If I have another field like ISBN in book so how do I filter with this field in from django.views.generic import DetailField

here is my book/urls.py file code

urlpatterns = [
    path('',BookListView.as_view(), name="book_list"),
    path('<isbn>/',BookDetailView.as_view(), name="book_detail")
]

book/views.py

class BookDetailView(DetailView):
    template_name = "book/detail.html"
    def get_queryset(self,*args, **kwargs):
        print(self.kwargs['isbn'])
        return BookModel.objects.filter(isbn=self.kwargs['isbn'])

and the Error is

Generic detail view BookDetailView must be called with either an object pk or a slug in the URLconf.

Body:
you can use isbn as slug

book/urls.py

urlpatterns = [
    path('',BookListView.as_view(), name="book_list"),
    path('<slug:isbn>/',BookDetailView.as_view(), name="book_detail")
]

book/views.py

class BookDetailView(DetailView):
    model = BookModel
    template_name = "book/detail.html"
    slug_field = 'isbn'
    slug_url_kwarg = 'isbn'


问:
UseStatusCodePagesWithReExecute shows blank page
I've been trying to use the UseStatusCodePagesWithReExecute method to show a page that shows customized messages per status code on the application I'm trying to make with ASP.NET Core 3.0

I've followed the instructions on this website, but right now, if I try to test this by accessing a non-existant webpage, a blank page shows up, and the code doesn't pass through the OnGet method on the Razor Page I want to be shown (I used breakpoints).

However, I am able to get the status page to show by accessing manually the page on my browser using the /Status/404 URI.

On the startup file, I've added the required lines, as shown in the tutorial.

```<code>// Startup.cs
public static void Configure(IApplicationBuilder app,
                             IWebHostEnvironment env,
                             IHostApplicationLifetime appLifetime)
    {
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePagesWithReExecute("/Status/{0}");
        app.UseExceptionHandler("/Status");

        // Irrelevant code below
    }
</code>```

The status model contains a OnGet method that takes the code number as a parameter

```<code>// Status.cshtml.cs

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class StatusModel : PageModel
{
    public void OnGet(string? code = null)
    {
        if (null == code)
            code = HttpContext.Response.StatusCode.ToString();

        PageTitle = $"HTTP status {code}";
        StatusNumber = code;

        if (code.CompareTo("404") == 0)
        {
            StatusName = "Not found";
            StatusDescription = "The requested page was not found.";
        }
        else
        {
            StatusName = "Unknown error";
            StatusDescription = "An unknown error occurred.";
        }
    }
}
</code>```

The status view is quite simple:

```<code>@page "{code?}"
@model StatusModel
@{
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@Model.PageTitle</title>
</head>
<body>
    <div>
        <h1>@Model.StatusNumber</h1>
        <h2>@Model.StatusName</h2>
        <h2>@Model.StatusDescription</h2>
    </div>
    <p>RID: @Model.RequestId</p>
</body>
</html>
</code>```

On the output console, I can see that indeed the application noticed that it caught the 404, but it doesn't appear to do anything:

```<code>info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
      Executing HttpStatusCodeResult, setting HTTP status code 404
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[4]
      Executed page /Index in 225.4469ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint '/Index'
</code>```

Is there something that's changed when passing from ASP.NET Core 2.2 to 3.0 that I forgot to edit / add to make this work, or is this already supposed to work?

答:
Is there something that's changed when passing from ASP.NET Core 2.2 to 3.0 that I forgot to edit / add to make this work, or is this already supposed to work?

This is already supposed to work.

Status.cshtml:

```<code>@page "{code?}"
@model StatusModel
@{
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@Model.PageTitle</title>
</head>
<body>
    <div>
        <h1>@Model.StatusNumber</h1>
        <h2>@Model.StatusName</h2>
        <h2>@Model.StatusDescription</h2>
    </div>
</body>
</html>
</code>```

Status.cshtml.cs:

```<code>[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class StatusModel : PageModel
{
    public string PageTitle { get;  set; }
    public string StatusNumber { get;  set; }
    public string StatusName { get;  set; }
    public string StatusDescription { get;  set; }

    public void OnGet(string? code = null)
    {
        if (null == code)
            code = HttpContext.Response.StatusCode.ToString();

        PageTitle = $"HTTP status {code}";
        StatusNumber = code;

        if (code.CompareTo("404") == 0)
        {
            StatusName = "Not found";
            StatusDescription = "The requested page was not found.";
        }
        else
        {
            StatusName = "Unknown error";
            StatusDescription = "An unknown error occurred.";
        }
    }
}
</code>```

Result:

Update：

```<code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePagesWithReExecute("/Status/{0}");
        app.UseExceptionHandler("/Status");
    }
    else
    {
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePagesWithReExecute("/Status/{0}");
        app.UseExceptionHandler("/Status");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.Use(async (context, next) =>
    {
        await next();

        if (context.Response.StatusCode == 401)
        {

            var newPath = new PathString("/Status/401");
            var originalPath = context.Request.Path;
            var originalQueryString = context.Request.QueryString;
            context.Features.Set<IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature()
            {
                OriginalPathBase = context.Request.PathBase.Value,
                OriginalPath = originalPath.Value,
                OriginalQueryString = originalQueryString.HasValue ? originalQueryString.Value : null,
            });

            // An endpoint may have already been set. Since we're going to re-invoke the middleware pipeline we need to reset
            // the endpoint and route values to ensure things are re-calculated.
            context.SetEndpoint(endpoint: null);
            var routeValuesFeature = context.Features.Get<IRouteValuesFeature>();
            routeValuesFeature?.RouteValues?.Clear();

            context.Request.Path = newPath;
            try
            {
                await next();
            }
            finally
            {
                context.Request.QueryString = originalQueryString;
                context.Request.Path = originalPath;
                context.Features.Set<IStatusCodeReExecuteFeature>(null);
            }

            // which policy failed? need to inform consumer which requirement was not met
            //await next();
        }

    });
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}
</code>```

Result:

Body:
I've been trying to use the UseStatusCodePagesWithReExecute method to show a page that shows customized messages per status code on the application I'm trying to make with ASP.NET Core 3.0

I've followed the instructions on this website, but right now, if I try to test this by accessing a non-existant webpage, a blank page shows up, and the code doesn't pass through the OnGet method on the Razor Page I want to be shown (I used breakpoints).

However, I am able to get the status page to show by accessing manually the page on my browser using the /Status/404 URI.

On the startup file, I've added the required lines, as shown in the tutorial.

// Startup.cs
public static void Configure(IApplicationBuilder app,
                             IWebHostEnvironment env,
                             IHostApplicationLifetime appLifetime)
    {
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePagesWithReExecute("/Status/{0}");
        app.UseExceptionHandler("/Status");

        // Irrelevant code below
    }

The status model contains a OnGet method that takes the code number as a parameter

// Status.cshtml.cs

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class StatusModel : PageModel
{
    public void OnGet(string? code = null)
    {
        if (null == code)
            code = HttpContext.Response.StatusCode.ToString();

        PageTitle = $"HTTP status {code}";
        StatusNumber = code;

        if (code.CompareTo("404") == 0)
        {
            StatusName = "Not found";
            StatusDescription = "The requested page was not found.";
        }
        else
        {
            StatusName = "Unknown error";
            StatusDescription = "An unknown error occurred.";
        }
    }
}

The status view is quite simple:

@page "{code?}"
@model StatusModel
@{
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>@Model.PageTitle</title>

@Model.StatusNumber

@Model.StatusName

@Model.StatusDescription

RID: @Model.RequestId

On the output console, I can see that indeed the application noticed that it caught the 404, but it doesn't appear to do anything:

info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
      Executing HttpStatusCodeResult, setting HTTP status code 404
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[4]
      Executed page /Index in 225.4469ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint '/Index'

Is there something that's changed when passing from ASP.NET Core 2.2 to 3.0 that I forgot to edit / add to make this work, or is this already supposed to work?

Body:
Is there something that's changed when passing from ASP.NET Core 2.2 to 3.0 that I forgot to edit / add to make this work, or is this already supposed to work?

This is already supposed to work.

Status.cshtml:

@page "{code?}"
@model StatusModel
@{
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@Model.PageTitle</title>
</head>
<body>
    <div>
        <h1>@Model.StatusNumber</h1>
        <h2>@Model.StatusName</h2>
        <h2>@Model.StatusDescription</h2>
    </div>
</body>
</html>

Status.cshtml.cs:

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class StatusModel : PageModel
{
    public string PageTitle { get;  set; }
    public string StatusNumber { get;  set; }
    public string StatusName { get;  set; }
    public string StatusDescription { get;  set; }

    public void OnGet(string? code = null)
    {
        if (null == code)
            code = HttpContext.Response.StatusCode.ToString();

        PageTitle = $"HTTP status {code}";
        StatusNumber = code;

        if (code.CompareTo("404") == 0)
        {
            StatusName = "Not found";
            StatusDescription = "The requested page was not found.";
        }
        else
        {
            StatusName = "Unknown error";
            StatusDescription = "An unknown error occurred.";
        }
    }
}

Result:

Update：

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePagesWithReExecute("/Status/{0}");
        app.UseExceptionHandler("/Status");
    }
    else
    {
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePagesWithReExecute("/Status/{0}");
        app.UseExceptionHandler("/Status");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.Use(async (context, next) =>
    {
        await next();

        if (context.Response.StatusCode == 401)
        {

            var newPath = new PathString("/Status/401");
            var originalPath = context.Request.Path;
            var originalQueryString = context.Request.QueryString;
            context.Features.Set<IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature()
            {
                OriginalPathBase = context.Request.PathBase.Value,
                OriginalPath = originalPath.Value,
                OriginalQueryString = originalQueryString.HasValue ? originalQueryString.Value : null,
            });

            // An endpoint may have already been set. Since we're going to re-invoke the middleware pipeline we need to reset
            // the endpoint and route values to ensure things are re-calculated.
            context.SetEndpoint(endpoint: null);
            var routeValuesFeature = context.Features.Get<IRouteValuesFeature>();
            routeValuesFeature?.RouteValues?.Clear();

            context.Request.Path = newPath;
            try
            {
                await next();
            }
            finally
            {
                context.Request.QueryString = originalQueryString;
                context.Request.Path = originalPath;
                context.Features.Set<IStatusCodeReExecuteFeature>(null);
            }

            // which policy failed? need to inform consumer which requirement was not met
            //await next();
        }

    });
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

Result:


问:
Is there a way to import multiple excel sheets using code in SAS Enterprise when DBMS errors occur?
I wrote some code with the hope of importing multiple sheets, but I receive an error:
"ERROR: DBMS type XLSX not valid for import."

I looked into the error and tried XLS etc, and then checked

```<code>proc setinit; run;
</code>```

The output did not include  "---SAS/ACCESS Interface to PC Files" in which case I see that the advice is to use a csv file instead.  That would be fine, except I am trying to import dozens of sheets in a macro (see below) from a single excel workbook.  I'm not sure that it makes sense to save each sheet as a csv so that the macro can pull in all of the files.  That would be labor intensive in the future, as these sheets will be updated maybe multiple times a year.

```<code>%let path = 'C:/Desktop/Folder';

%macro importsheet(sheet);
proc import out= &sheet
    datafile = &path
    dbms=XLSX replace;
    getnames=yes;
run;
%mend;

%importsheet(sheet1);
</code>```

My core question is this:
Is the csv option the only/best solution for what I am asking?  My back up plan is to just do an autoexec, but I would like to make sure I've thoroughly explored writing a macro and discarded it as an option before I do that.

答:
The fastest and easiest way to import all Excel Sheets is to use a libname reference. </p>

```<code>libname myXL xlsx 'path to xlsx file';

proc copy in=myXL out=work; run;
</code>```

<p>This will not work if you're importing from a specific range. </p>

Body:
I wrote some code with the hope of importing multiple sheets, but I receive an error:
"ERROR: DBMS type XLSX not valid for import."

I looked into the error and tried XLS etc, and then checked

proc setinit; run;

The output did not include  "---SAS/ACCESS Interface to PC Files" in which case I see that the advice is to use a csv file instead.  That would be fine, except I am trying to import dozens of sheets in a macro (see below) from a single excel workbook.  I'm not sure that it makes sense to save each sheet as a csv so that the macro can pull in all of the files.  That would be labor intensive in the future, as these sheets will be updated maybe multiple times a year.

%let path = 'C:/Desktop/Folder';

%macro importsheet(sheet);
proc import out= &sheet
    datafile = &path
    dbms=XLSX replace;
    getnames=yes;
run;
%mend;

%importsheet(sheet1);

My core question is this:
Is the csv option the only/best solution for what I am asking?  My back up plan is to just do an autoexec, but I would like to make sure I've thoroughly explored writing a macro and discarded it as an option before I do that.

Body:
The fastest and easiest way to import all Excel Sheets is to use a libname reference.

libname myXL xlsx 'path to xlsx file';

proc copy in=myXL out=work; run;

This will not work if you're importing from a specific range.


问:
AngularJs filter selected option from other select
I have two arrays. The first array name is titles has titles. The second array name is columns has option values. I repeated the first array. If I choose an option I want to hide selected option from other selects. How can I do?

```<code>$scope.titles = [
    {id: 1, name: 'A1'},
    {id: 2, name: 'A2'},
    {id: 3, name: 'A3'},
    {id: 4, name: 'A4'}
];

$scope.columns = [
    {id: 1, name: 'Title'},
    {id: 2, name: 'City'},
    {id: 3, name: 'Town'},
    {id: 4, name: 'Nh'}
];

$scope.setColumn = function (id, type) {
    for (var a = 0; a < $scope.columns.length; a++) {
        if ($scope.columns[a].name == type) {
            $scope.titles[id].selectedId = $scope.columns[a].id;
            $scope.titles[id].selectedValue = $scope.columns[a].name;
            $scope.columns[a].selected = true;
        }
    }
}
</code>```

        {{i.name}}

            <select ng-options="item.name for item in columns"
                    class="form-control"
                    ng-model="selectedItem"
                    ng-change="setColumn(i.id, selectedItem.name);">
                <option value="">Set options</option>
            </select>

```

答:
One approach to inputs inside an ng-repeat is to bind the input to the iterator:

```<code><div class="col-md-4 mt-5" data-ng-repeat="i in titles"
     ng-init="titleIndex = $index">
    <div class="form-group">
        <label for="s1" class="col-md-3 col-form-label">{{i.name}}</label>
        <div class="col-md-9">
            <select ng-options="item.id as item.name for item in columns"
                    class="form-control"
                    ng-model="i.selectedColumnId"
                    ng-change="setColumn(titleIndex, i)">
                <option value="">Set options</option>
            </select>
        </div>
    </div>
</div>
</code>```

This allows the controller to control the selection for each <select> input.

Body:
I have two arrays. The first array name is titles has titles. The second array name is columns has option values. I repeated the first array. If I choose an option I want to hide selected option from other selects. How can I do?

$scope.titles = [
    {id: 1, name: 'A1'},
    {id: 2, name: 'A2'},
    {id: 3, name: 'A3'},
    {id: 4, name: 'A4'}
];

$scope.columns = [
    {id: 1, name: 'Title'},
    {id: 2, name: 'City'},
    {id: 3, name: 'Town'},
    {id: 4, name: 'Nh'}
];

$scope.setColumn = function (id, type) {
    for (var a = 0; a < $scope.columns.length; a++) {
        if ($scope.columns[a].name == type) {
            $scope.titles[id].selectedId = $scope.columns[a].id;
            $scope.titles[id].selectedValue = $scope.columns[a].name;
            $scope.columns[a].selected = true;
        }
    }
}

        {{i.name}}

            <select ng-options="item.name for item in columns"
                    class="form-control"
                    ng-model="selectedItem"
                    ng-change="setColumn(i.id, selectedItem.name);">
                <option value="">Set options</option>
            </select>

Body:
One approach to inputs inside an ng-repeat is to bind the input to the iterator:

<div class="col-md-4 mt-5" data-ng-repeat="i in titles"
     ng-init="titleIndex = $index">
    <div class="form-group">
        <label for="s1" class="col-md-3 col-form-label">{{i.name}}</label>
        <div class="col-md-9">
            <select ng-options="item.id as item.name for item in columns"
                    class="form-control"
                    ng-model="i.selectedColumnId"
                    ng-change="setColumn(titleIndex, i)">
                <option value="">Set options</option>
            </select>
        </div>
    </div>
</div>

This allows the controller to control the selection for each <select> input.


问:
Google Data Studio - format date YEAR MONTH (YYYYMM) is not working
With Google Datastudio,
I have 1 dimension called createdAt. I want to show the format YYYYMM in my reports:

Tentative 1

1/ The report show the data correctly:

2/ Change the format of the dimension createdAt to YYYYMM

Tentative 2

1/ Duplicate dimension:

2/ The report is not showing the good format for dimension createdAt YYYYMM:

Issue related to: https://issuetracker.google.com/issues/149668303#comment1

答:
It can be achieved using the two step process below:

1) Calculated Field

The current createdAt field is a Text field; one way to change it into a Date field (that Google Data Studio recognises) is using the REGEXP_REPLACE function to remove the milliseconds, and the TODATE function to extract a YYYYMMDD format:

```<code> TODATE(REGEXP_REPLACE(createdAt, "(\\.\\d+)$", ""), "%Y-%m-%d %H:%M:%S", "%Y%m%d")
</code>```

GIF to demonstrate:

2) Granularity

To display the Date in a YYYYMM format, change the Granularity to Year Month.

Google Data Studio Report and a GIF to elaborate:

Body:
It can be achieved using the two step process below:

1) Calculated Field

The current createdAt field is a Text field; one way to change it into a Date field (that Google Data Studio recognises) is using the REGEXP_REPLACE function to remove the milliseconds, and the TODATE function to extract a YYYYMMDD format:

 TODATE(REGEXP_REPLACE(createdAt, "(\\.\\d+)$", ""), "%Y-%m-%d %H:%M:%S", "%Y%m%d")

GIF to demonstrate:

2) Granularity

To display the Date in a YYYYMM format, change the Granularity to Year Month.

Google Data Studio Report and a GIF to elaborate:


问:
Visual Studio breakpoints break in the wrong source file (or multiple files simultaneously) if multiple files have the same name
In a team project I'm working on, setting a breakpoint in a file (say IdeasController.cs) will lead to erratic debugger behaviour if there's another file with the same name in the solution. I've reproduced the problem on several developers' workstations.

Example

I set a breakpoint in IdeasController.cs in our Web API:

Another file called IdeasController.cs exists in our separate MVC 4 web project. In the screenshot below, the debugger shows the Api->IdeasController source code, but the line highlight matches the code structure of Web->IdeasController. The breakpoint is duplicated, with one of them in the middle of a comment block.

The Breakpoint window shows the breakpoint in both files simultaneously:

On some workstations the debugger steps through the correct lines (regardless of the line highlight); on others it cheerfully steps through irrelevant lines (including comments and whitespace). I'm guessing this depends on which source file it chooses to display.

What I've tried

I've trawled the Internet. This kind of problem seems to occur when there's a mismatch between the debug file (*.pdb), the source file, and the compiled code. There are a lot of possible causes: duplicate file names (which can confuse the debugger[5]), outdated project build files, invalid solution cache, or incorrect build configuration.

These are the solutions I've found and tried:

Checked my build configuration.

Made sure the project isn't built in release mode.

Made sure we don't have code optimization enabled.

Made sure the project's debug module was loaded correctly. (Started debugging the project and checked Debug > Windows > Modules. Both assemblies are listed, not optimized, and have a symbol status of "Symbols loaded".)

Reset the debugging metadata & Visual Studio cache.

Closed Visual Studio and deleted the solution cache file (*.suo).[1]

Deleted each project's build output (the bin and obj folders). (For future reference: open the solution folder in Windows Explorer and type this in the search box: "type:folder AND (name:=bin OR name:=obj)".

Deleted the assembly cache folder (C:\Documents and Settings\<user>\Local Settings\Application Data\dl3).[2][3]

None of these had any effect. I can rename one of the files (without renaming the class) to temporarily work around the problem, but that's far from ideal.

Where I am now

Page 14 of my latest Google search. Suggestions would be much appreciated. :)

答:
I was having the same issue. In my case both the projects had same port numbers. I was able to resolve it by changing the port number of the project whose file's breakpoints were not hitting. </p>

<p>My guess is that IIS Express was caching the pdb file from the second project since both files had the same name, and the projects had the same port number. </p>

ContentLicense: CC BY-SA 3.0

Body:
I was having the same issue. In my case both the projects had same port numbers. I was able to resolve it by changing the port number of the project whose file's breakpoints were not hitting.

My guess is that IIS Express was caching the pdb file from the second project since both files had the same name, and the projects had the same port number.


问:
Cross Validate and Get Precision, Recall, F-Score for Each Class Label
Is there a scikit learn function which can perform cross validation on my dataset and output not just the overall, precision, recall and f-score but all the precision, recall and f-score for each class label.</p>

答:
These two links may something you are looking for.
Confusion matrix &  f1_score</p>


问:
Repository, IRepository and structuremap
I have an interface IRepository and an implementation EFRepository.

I use structuremap injection in order to get the repository implementation.

Right now the EFRepository has constructor with no parameter so structuremap knows to retrieve instances on EFRepository easily.

Now I need to change the repository implementation so that it will recieve in the constructor parameter that holds the unit of work.

My question in such case, how I use structuremap in order to return an instance that initialized with the unit of work?

EXAMPLE

Until today I used:

```<code>using(IUnitOfWork uow=UnitOfWork.current) {
    IRepository rep = ObjectFactory.GetInstance<IRepository<T>>();
    //repository operations that uses UnitOfWork.current that initialized above
}// here dispose of UnitOfWork.current
</code>```

Now I want to use:

```<code>using(IUnitOfWork uow=new UnitOfWork()) {
    //Not sure is this is how I tell sructure map to use contractor that
    //get IUnitOfWork)
    IRepository rep = ObjectFactory.GetInstance<IRepository<T>>(uow);
    //repository operations that uses uow that initialized above
}// here dispose of UnitOfWork
</code>```

答:
I'm assuming here that your unit of work is request-specific... So you have a service (WCF?) and each incoming request gets its own unit of work.

Then you can configure StructureMap to define a separate unit of work per HTTP Request. If you need unit testing without HTTP Requests, you can choose for a hybrid lifecycle: per HTTP Request OR per thread. StructureMap will figure out what to do at runtime.

```<code>ObjectFactory.Configure(x => x.For<IUnitOfWork>()
              .HybridHttpOrThreadLocalScoped()
              .Use<MyUnitOfWork>());
</code>```

Your class that needs the constructor injection simply states that it needs an IUnitOfWork:

```<code>public MyClass(IUnitOfWork unit) { ... }
</code>```

This of course requires that MyClass is also managed/instantiated using StructureMap.

Body:
I have an interface IRepository and an implementation EFRepository.

I use structuremap injection in order to get the repository implementation.

Right now the EFRepository has constructor with no parameter so structuremap knows to retrieve instances on EFRepository easily.

Now I need to change the repository implementation so that it will recieve in the constructor parameter that holds the unit of work.

My question in such case, how I use structuremap in order to return an instance that initialized with the unit of work?

EXAMPLE

Until today I used:

using(IUnitOfWork uow=UnitOfWork.current) {
    IRepository rep = ObjectFactory.GetInstance<IRepository<T>>();
    //repository operations that uses UnitOfWork.current that initialized above
}// here dispose of UnitOfWork.current

Now I want to use:

using(IUnitOfWork uow=new UnitOfWork()) {
    //Not sure is this is how I tell sructure map to use contractor that
    //get IUnitOfWork)
    IRepository rep = ObjectFactory.GetInstance<IRepository<T>>(uow);
    //repository operations that uses uow that initialized above
}// here dispose of UnitOfWork

Body:
I'm assuming here that your unit of work is request-specific... So you have a service (WCF?) and each incoming request gets its own unit of work.

Then you can configure StructureMap to define a separate unit of work per HTTP Request. If you need unit testing without HTTP Requests, you can choose for a hybrid lifecycle: per HTTP Request OR per thread. StructureMap will figure out what to do at runtime.

ObjectFactory.Configure(x => x.For<IUnitOfWork>()
              .HybridHttpOrThreadLocalScoped()
              .Use<MyUnitOfWork>());

Your class that needs the constructor injection simply states that it needs an IUnitOfWork:

public MyClass(IUnitOfWork unit) { ... }

This of course requires that MyClass is also managed/instantiated using StructureMap.


问:
Is There an Alternative Way to Incorporate Firebase into my iOS App Other Than Cocoapods?
My iPhone recently automatically updated to iOS 13.3.1, and unknown to me until it was to late apparently Apple blocked the use of some external frameworks when testing apps on a physical device within Xcode.

I can no longer run my app on my iPhone (although the simulator still works but it's SO much more inconvenient). I'm using cocoapods and the one that's causing the issue is Firebase. I need Firebase, so my question is: Is there another way to integrate Firebase into my app without using pods? I'm still using cocoapods for other things and they seem to work fine, but for Firebase is there a way to manually add the frameworks so as to still be able to launch it on my physical device?

For reference, here's another question that was asked on StackOverflow that shows my exact issue I'm having: Library not loaded: @rpath/FBLPromises.framework/FBLPromises iOS 13.3.1

Suggestions included:

Exchanging use_frameworks! in my podfile with use_modular_headers!, but that doesn't work with Firebase as many other things break... like it NEEDS to be dynamic in order for Firebase to work.

Reverting back to iOS 13.3 from 13.3.1. I'd be willing to do this of course and I tried for several days, but looks like Apple stopped signing 13.3 now so I'm unable to use the 13.3 firmware in order to restore my iPhone to the previous version... meaning I'm stuck with 13.3.1

Upgrading to a paid developer account. Some people are saying that this issue is only with free developer accounts, but I'm not willing to take the risk of upgrading my account right now for 2 reasons: 1) I have no way of knowing for sure that this issue will be fixed by upgrading my account and I don't want to spend the cash without a guarantee and 2) I'm still a ways away from submitting my app the the App Store so there's no need to pay a fee to Apple while I'm still in development for an indefinite amount of time.

Back to the question at hand: Can I manually add Firebase frameworks to my app without experiencing the problems associated with adding it via cocoapods such as in the linked question above?

EDIT 1

This is my Podfile for reference:

```<code>    # Uncomment the next line to define a global platform for your project

platform :ios, '8.0'

target 'JeegO' do
  # Comment the next line if you don't want to use dynamic frameworks

#use_frameworks!

use_modular_headers!

  # Pods for JeegO

pod 'Firebase'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'SVProgressHUD'
pod 'ReachabilitySwift'
pod 'SendGrid', :git => 'https://github.com/scottkawai/sendgrid-swift.git'
pod 'iCarousel'
#pod 'PromisesSwift'

end
</code>```

EDIT 2

I ultimately removed my Firebase pods and tried using Firebase's zip binary distribution as suggested below, but for the life of me I can't get it to work so I'm chalking it up to a lost cause, unfortunately. Following the readme to integrate the static Firebase SDKs seemed straightforward but it just added about 50 "undefined symbol" issues among other things, so I ended up adding the pods back in and will probably just have to bite the bullet and register for the paid apple developer program in order to debug on my device... eye roll to Apple...

答:
Firebase does support use_modular_headers!  If you're seeing a problem, please file an issue with the details.

Alternatively, Firebase also provides a zip binary distribution and an experimental Carthage distribution.

Body:
My iPhone recently automatically updated to iOS 13.3.1, and unknown to me until it was to late apparently Apple blocked the use of some external frameworks when testing apps on a physical device within Xcode.

I can no longer run my app on my iPhone (although the simulator still works but it's SO much more inconvenient). I'm using cocoapods and the one that's causing the issue is Firebase. I need Firebase, so my question is: Is there another way to integrate Firebase into my app without using pods? I'm still using cocoapods for other things and they seem to work fine, but for Firebase is there a way to manually add the frameworks so as to still be able to launch it on my physical device?

For reference, here's another question that was asked on StackOverflow that shows my exact issue I'm having: Library not loaded: @rpath/FBLPromises.framework/FBLPromises iOS 13.3.1

Suggestions included:

Exchanging use_frameworks! in my podfile with use_modular_headers!, but that doesn't work with Firebase as many other things break... like it NEEDS to be dynamic in order for Firebase to work.

Reverting back to iOS 13.3 from 13.3.1. I'd be willing to do this of course and I tried for several days, but looks like Apple stopped signing 13.3 now so I'm unable to use the 13.3 firmware in order to restore my iPhone to the previous version... meaning I'm stuck with 13.3.1

Upgrading to a paid developer account. Some people are saying that this issue is only with free developer accounts, but I'm not willing to take the risk of upgrading my account right now for 2 reasons: 1) I have no way of knowing for sure that this issue will be fixed by upgrading my account and I don't want to spend the cash without a guarantee and 2) I'm still a ways away from submitting my app the the App Store so there's no need to pay a fee to Apple while I'm still in development for an indefinite amount of time.

Back to the question at hand: Can I manually add Firebase frameworks to my app without experiencing the problems associated with adding it via cocoapods such as in the linked question above?

EDIT 1

This is my Podfile for reference:

    # Uncomment the next line to define a global platform for your project

platform :ios, '8.0'

target 'JeegO' do
  # Comment the next line if you don't want to use dynamic frameworks

#use_frameworks!

use_modular_headers!

  # Pods for JeegO

pod 'Firebase'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'SVProgressHUD'
pod 'ReachabilitySwift'
pod 'SendGrid', :git => 'https://github.com/scottkawai/sendgrid-swift.git'
pod 'iCarousel'
#pod 'PromisesSwift'

end

EDIT 2

I ultimately removed my Firebase pods and tried using Firebase's zip binary distribution as suggested below, but for the life of me I can't get it to work so I'm chalking it up to a lost cause, unfortunately. Following the readme to integrate the static Firebase SDKs seemed straightforward but it just added about 50 "undefined symbol" issues among other things, so I ended up adding the pods back in and will probably just have to bite the bullet and register for the paid apple developer program in order to debug on my device... eye roll to Apple...


问:
Can't seem to get Boto's dynamodb.update_item to work
I'm trying to use this Boto function,
But can't seem to get it right..
Any idea?
Doc Link

```<code>    tablename = 'name_table'
    response = dynamodb.update_item(
        TableName=tablename,
        Key={
            'name': 'Tony',
        },
        UpdateExpression="set name= :r",
        ExpressionAttributeValues={
            ':r': 'Ralph',
        },
        ReturnValues="UPDATED_NEW"
    )
</code>```

This are the errors I get :

```<code>Invalid type for parameter Key.name, value: set(['Tony', 0]), type: <type 'set'>, valid types: <type 'dict'>
</code>```

I've tried to change the name from str to dict,
So now I'm with this error

```<code>ValueError: dictionary update sequence element #0 has length 1; 2 is required
</code>```

Where to go from here ?
Many thanks..

答:
The keys in the API you referenced expect the values to be DynamoDB attributes, so the Key should be like this:

```<code>{
    'name': {
        'S': 'Tony'
    }
}
</code>```

The ExpressionAttributeValues should be like this:

```<code>{
    ':r': {
        'S': 'Ralph'
    }
}
</code>```

So the whole thing looks like this:

    tablename = 'name_table'
    response = dynamodb.update_item(
        TableName=tablename,
        Key={
            'name': {
                'S': 'Tony'
             }
        },
        UpdateExpression="set name= :r",
        ExpressionAttributeValues={
            ':r': {
                'S': 'Ralph'
            }
        },
        ReturnValues="UPDATED_NEW"
    )
```

Body:
I'm trying to use this Boto function,
But can't seem to get it right..
Any idea?
Doc Link

    tablename = 'name_table'
    response = dynamodb.update_item(
        TableName=tablename,
        Key={
            'name': 'Tony',
        },
        UpdateExpression="set name= :r",
        ExpressionAttributeValues={
            ':r': 'Ralph',
        },
        ReturnValues="UPDATED_NEW"
    )

This are the errors I get :

Invalid type for parameter Key.name, value: set(['Tony', 0]), type: <type 'set'>, valid types: <type 'dict'>

I've tried to change the name from str to dict,
So now I'm with this error

ValueError: dictionary update sequence element #0 has length 1; 2 is required

Where to go from here ?
Many thanks..

Body:
The keys in the API you referenced expect the values to be DynamoDB attributes, so the Key should be like this:

{
    'name': {
        'S': 'Tony'
    }
}

The ExpressionAttributeValues should be like this:

{
    ':r': {
        'S': 'Ralph'
    }
}

So the whole thing looks like this:

    tablename = 'name_table'
    response = dynamodb.update_item(
        TableName=tablename,
        Key={
            'name': {
                'S': 'Tony'
             }
        },
        UpdateExpression="set name= :r",
        ExpressionAttributeValues={
            ':r': {
                'S': 'Ralph'
            }
        },
        ReturnValues="UPDATED_NEW"
    )


问:
Is there a way to a variable to change according to a class index?
i did this code so I could mirror textareas:

```<code><body>
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>
    <br>
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>

<script>
    var a = document.getElementsByClassName("caixa1");
    var b = document.getElementsByClassName("caixa2");
    a[0].oninput = function(e) {
      b[0].value = a[0].value;
    }
          b[0].oninput = function(e) {
      a[0].value = b[0].value;
    }
             a[1].oninput = function(e) {
      b[1].value = a[1].value;
    }
          b[1].oninput = function(e) {
      a[1].value = b[1].value;
    }
</script>
</body>

</code>```

But I need to repeat this 8 times. Is there any way I could create a variable that changes according to the class index of the current textarea?

答:
Iterate over each index of one of the collections, and access the same index on the other collection:

var a = document.getElementsByClassName("caixa1");
var b = document.getElementsByClassName("caixa2");
for (let i = 0; i  t2.value = t1.value;
  t2.oninput = () => t1.value = t2.value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>
<br>
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea></code>```

An alternative would be to use event delegation on the container, and from the event target textarea, dynamically identify which is the linked adjacent textarea to assign a value to (either the next or previous sibling):

document.body.addEventListener('input', ({ target }) => {
  const other = target[target.matches('.caixa1') ? 'nextElementSibling' : 'previousElementSibling'];
  other.value = target.value;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>
    <br>
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea></code>```

Body:
i did this code so I could mirror textareas:

<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>

<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>

But I need to repeat this 8 times. Is there any way I could create a variable that changes according to the class index of the current textarea?

Body:
Iterate over each index of one of the collections, and access the same index on the other collection:

var a = document.getElementsByClassName("caixa1");
var b = document.getElementsByClassName("caixa2");
for (let i = 0; i < a.length; i++) {
  const t1 = a[i];
  const t2 = b[i];
  t1.oninput = () => t2.value = t1.value;
  t2.oninput = () => t1.value = t2.value;
}

<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>
<br>
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>

An alternative would be to use event delegation on the container, and from the event target textarea, dynamically identify which is the linked adjacent textarea to assign a value to (either the next or previous sibling):

document.body.addEventListener('input', ({ target }) => {
  const other = target[target.matches('.caixa1') ? 'nextElementSibling' : 'previousElementSibling'];
  other.value = target.value;
});

<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>
    <br>
<textarea class="caixa1"></textarea>
<textarea class="caixa2"></textarea>


问:
How to debug background notifications in iOS?
I am trying to debug background push notifications on iOS, and more specifically to set breakpoints into code that should handle a notification to configure internationalized content using custom logic.

I set a breakpoints in my AppDelegate's userNotificationCenter(_:willPresent:withCompletionHandler:) and userNotificationCenter(_:didReceive:withCompletionHandler:).

And I also created a notification service extension and added a breakpoint to its didReceive(_:withContentHandler:) because I want to mutate the content of my notification.

When I send the following payload and my app is in the foreground, the breakpoint in userNotificationCenter(_:willPresent:withCompletionHandler:) gets a hit and everything is fine:

```<code>{
  "aps" : {
    "badge" : 1012,
    "category" : "GENERIC_MESSAGE",
    "mutable-content" : 1
  },
  "translations" : [
    {
      "LanguageCode" : "fr",
      "Title" : "Aimant détaché",
      "Body" : "L'aimant du capteur 002F51AB, associé à l'outil HT-1225 Hitachi Tas, a été détaché."
    },
    {
      "LanguageCode" : "en",
      "Body" : "The magnet of the tag 002F51AB, link to tool HT-1225 Hitachi Tas, was detached.",
      "Title" : "Magnet detached"
    },
    {
      "LanguageCode" : "nl",
      "Body" : "De magneet van de tag 002F51AB, gelinkt aan het gereedschap HT-1225 Hitachi Tas, is losgekoppeld.",
      "Title" : "Magneet losgekoppeld"
    }
  ],
  "messageId" : "90073ebb-ce51-ea11-a94c-000d3a213771"
}
</code>```

But if the application is in the background and I send the exact same notification, I don't get a hit on userNotificationCenter(_:didReceive:withCompletionHandler:). Same thing when I run the notification service extension, I don't get a hit in didReceive(_:withContentHandler:)

Am I forgetting something? Is it because my notification payload doesn't have an aps alert field?

答: I figured it out: when I add an alert field to my push notification, even with a dummy string, then it get forwarded to my Notification Service. Otherwise it doesn't.</p>

Body:
I am trying to debug background push notifications on iOS, and more specifically to set breakpoints into code that should handle a notification to configure internationalized content using custom logic.

I set a breakpoints in my AppDelegate's userNotificationCenter(_:willPresent:withCompletionHandler:) and userNotificationCenter(_:didReceive:withCompletionHandler:).

And I also created a notification service extension and added a breakpoint to its didReceive(_:withContentHandler:) because I want to mutate the content of my notification.

When I send the following payload and my app is in the foreground, the breakpoint in userNotificationCenter(_:willPresent:withCompletionHandler:) gets a hit and everything is fine:

{
  "aps" : {
    "badge" : 1012,
    "category" : "GENERIC_MESSAGE",
    "mutable-content" : 1
  },
  "translations" : [
    {
      "LanguageCode" : "fr",
      "Title" : "Aimant détaché",
      "Body" : "L'aimant du capteur 002F51AB, associé à l'outil HT-1225 Hitachi Tas, a été détaché."
    },
    {
      "LanguageCode" : "en",
      "Body" : "The magnet of the tag 002F51AB, link to tool HT-1225 Hitachi Tas, was detached.",
      "Title" : "Magnet detached"
    },
    {
      "LanguageCode" : "nl",
      "Body" : "De magneet van de tag 002F51AB, gelinkt aan het gereedschap HT-1225 Hitachi Tas, is losgekoppeld.",
      "Title" : "Magneet losgekoppeld"
    }
  ],
  "messageId" : "90073ebb-ce51-ea11-a94c-000d3a213771"
}

But if the application is in the background and I send the exact same notification, I don't get a hit on userNotificationCenter(_:didReceive:withCompletionHandler:). Same thing when I run the notification service extension, I don't get a hit in didReceive(_:withContentHandler:)

Am I forgetting something? Is it because my notification payload doesn't have an aps alert field?


问:
How to pass context to Angular 5 template from *ngIf
Angular's NgTemplateOutlet allows you to pass a context to the outlet for property binding.

```<code><ng-container *ngTemplateOutlet="eng; context: {$implicit: 'World'}"></ng-container>
<ng-template #eng let-name><span>Hello {{name}}!</span></ng-template>
</code>```

Angular's *ngIf allows you to embed one template or another based on a boolean condition:

```<code><ng-container *ngIf="isConditionTrue; then one else two"></ng-container>
<ng-template #one>This shows when condition is true</ng-template>
<ng-template #two>This shows when condition is false</ng-template>
</code>```

How can I pass context to these templates referred to within the *ngIf syntax?

答:
The accepted answer works when you have a single expression but will get complex where you have multiple ngIf expressions and templates.

A full example for cases where you have multiple expressions, resulting templates and even different context variables:

```<code><!-- Example ngFor -->
<mat-list-item
    *ngFor="let location of locations$; let l = index"
    [ngSwitch]="location.type"
    >
    <!-- ngSwitch could be ngIf on each node according to needs & readability -->

    <!-- Create ngTemplateOutlet foreach switch case, pass context -->
    <ng-container *ngSwitchCase="'input'">
        <ng-container
            *ngTemplateOutlet="inputField; context: { location: location, placeholder: 'Irrigation Start', otherOptions: 'value123' }">
        </ng-contaier>
    </ng-container>

    <ng-container *ngSwitchCase="'select'">
        <ng-container
            *ngTemplateOutlet="selectField; context: { location: location, selectSpecificOptions: 'scope.someSelectOptions' }">
        </ng-contaier>
    </ng-container>

    <!-- ngSwitchCase="'others'", etc. -->

</mat-list-item>

<!-- Shared ngTemplates & note let-[variable] to read context object into scope -->
<ng-template
    #inputField
    let-location="location"
    let-placeholder="placeholder
    let-otherOptions="otherOptions"
    <!-- Context is now accessible using let-[variable] -->
    INPUT: {{ location.value }} {{ placeholder }} {{ otherOptions }}
</ng-template>

<ng-template
    #selectField
    let-location="location"
    let-options="selectSpecificOptions"
    <!-- Context is now accessible using let-[variable] -->
    SELECT: {{ location.value }} {{ options }}
</ng-template>
</code>```

Where;

```<code>location$ = [
    {type: 'input',  value: 'test'},
    {type: 'input',  value: 'test 2'},
    {type: 'select', value: 'test 3'}
];
</code>```

Body:
Angular's NgTemplateOutlet allows you to pass a context to the outlet for property binding.

<ng-container *ngTemplateOutlet="eng; context: {$implicit: 'World'}"></ng-container>
<ng-template #eng let-name>Hello {{name}}!</ng-template>

Angular's *ngIf allows you to embed one template or another based on a boolean condition:

<ng-container *ngIf="isConditionTrue; then one else two"></ng-container>
<ng-template #one>This shows when condition is true</ng-template>
<ng-template #two>This shows when condition is false</ng-template>

How can I pass context to these templates referred to within the *ngIf syntax?

Body:
The accepted answer works when you have a single expression but will get complex where you have multiple ngIf expressions and templates.

A full example for cases where you have multiple expressions, resulting templates and even different context variables:

<!-- Example ngFor -->
<mat-list-item
    *ngFor="let location of locations$; let l = index"
    [ngSwitch]="location.type"
    >
    <!-- ngSwitch could be ngIf on each node according to needs & readability -->

    <!-- Create ngTemplateOutlet foreach switch case, pass context -->
    <ng-container *ngSwitchCase="'input'">
        <ng-container
            *ngTemplateOutlet="inputField; context: { location: location, placeholder: 'Irrigation Start', otherOptions: 'value123' }">
        </ng-contaier>
    </ng-container>

    <ng-container *ngSwitchCase="'select'">
        <ng-container
            *ngTemplateOutlet="selectField; context: { location: location, selectSpecificOptions: 'scope.someSelectOptions' }">
        </ng-contaier>
    </ng-container>

    <!-- ngSwitchCase="'others'", etc. -->

</mat-list-item>

<!-- Shared ngTemplates & note let-[variable] to read context object into scope -->
<ng-template
    #inputField
    let-location="location"
    let-placeholder="placeholder
    let-otherOptions="otherOptions"
    <!-- Context is now accessible using let-[variable] -->
    INPUT: {{ location.value }} {{ placeholder }} {{ otherOptions }}
</ng-template>

<ng-template
    #selectField
    let-location="location"
    let-options="selectSpecificOptions"
    <!-- Context is now accessible using let-[variable] -->
    SELECT: {{ location.value }} {{ options }}
</ng-template>

Where;

location$ = [
    {type: 'input',  value: 'test'},
    {type: 'input',  value: 'test 2'},
    {type: 'select', value: 'test 3'}
];


问:
Getting a thumbnail from a video url or data in iOS
I am trying to acquire a thumbnail (of the first frame) from a video taken from iphone 3GS camera so I can display it. How to do this?</p>

答:
```<code>NSURL *videoURL = [NSURL fileURLWithPath:url];

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];

        UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];

        //Player autoplays audio on init
        [player stop];
        [player release];
</code>```

Check this link for an alternative:
thumbnailImageAtTime: now deprecated - What's the alternative?

Body:
NSURL *videoURL = [NSURL fileURLWithPath:url];

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];

        UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];

        //Player autoplays audio on init
        [player stop];
        [player release];

Check this link for an alternative:
thumbnailImageAtTime: now deprecated - What's the alternative?


问:
What's the correct header to use when using API Key based authentication
I'm trying to create an API that uses API key based protection. The key is generated when a user is created, with a hook. Now I'm not sure what authorization schema to use with it. The avialable ones (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) don't seem correct. I have in my applications_controller:

```<code># frozen_string_literal: true

class ApplicationController < ActionController::API
  include ActionController::HttpAuthentication::Token::ControllerMethods

  protected

  def authenticate
    authenticate_token || render_unauthorized
  end

  def authenticate_token
    authenticate_with_http_token do |token, options|
      @current_user = User.find_by_api_key(token)
    end
  end

  def render_unauthorized(realm = 'Application')
    self.headers['WWW-Authenticate'] = %(Token realm='#{realm}')
    render json: 'Bad credentials', status: :unauthorized
  end
end
</code>```

But I know that this is not correct:

self.headers['WWW-Authenticate'] = %(Token realm='#{realm}')

There is no Token authorization schema. What should I use instead? I'm not finding much information about it.

I also know that Basic is not the correct type because it's not a user:password encoded in base64. Maybe X-Api-Key? I would like some help in the matter if possible :].

答:
You need HTTP_AUTHORIZATION header of the form Token token="####################", though you don't need to do this yourself. Use the code provided in the documentation:

```<code>authorization = ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
get "/notes/1.xml", headers: { 'HTTP_AUTHORIZATION' => authorization }
</code>```

Body:
I'm trying to create an API that uses API key based protection. The key is generated when a user is created, with a hook. Now I'm not sure what authorization schema to use with it. The avialable ones (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) don't seem correct. I have in my applications_controller:

# frozen_string_literal: true

class ApplicationController < ActionController::API
  include ActionController::HttpAuthentication::Token::ControllerMethods

  protected

  def authenticate
    authenticate_token || render_unauthorized
  end

  def authenticate_token
    authenticate_with_http_token do |token, options|
      @current_user = User.find_by_api_key(token)
    end
  end

  def render_unauthorized(realm = 'Application')
    self.headers['WWW-Authenticate'] = %(Token realm='#{realm}')
    render json: 'Bad credentials', status: :unauthorized
  end
end

But I know that this is not correct:

self.headers['WWW-Authenticate'] = %(Token realm='#{realm}')

There is no Token authorization schema. What should I use instead? I'm not finding much information about it.

I also know that Basic is not the correct type because it's not a user:password encoded in base64. Maybe X-Api-Key? I would like some help in the matter if possible :].

Body:
You need HTTP_AUTHORIZATION header of the form Token token="####################", though you don't need to do this yourself. Use the code provided in the documentation:

authorization = ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
get "/notes/1.xml", headers: { 'HTTP_AUTHORIZATION' => authorization }


问:
Python - Determine if Item is in a List Using a Function
I'm trying to write a function in Python to determine whether or not an item is in a list. I've been trying variations of this code.

No matter how I try it, it always returns a FALSE Boolean value. Even if I put the print commands inside the functions, it only prints with the results for a false value. I'm pretty sure I'm passing the list to the function properly, but I can't figure out why it only determines FALSE values. Any ideas?

```<code>def newFunction(x, y, z):
   z = 0
   if y in x:
      z = True
   else:
      z = False
   return (z)

newList = [2,4,6,8,10]
r = input ('Enter a number: ')
s = 0
newFunction(newList, r, s)
if s == True:
   print ('The no. IS in the list.')
else:
   print ('The no. IS NOT in the list.')
</code>```

答:
There are a few things going on here:

input() returns a string, so you need to convert it into an int.

You're not doing anything with the value returned by the function.

Related to the above, you don't need the z parameter in the function. Were you expecting the value of the variable outside the function to change?

If you absolutely need to explicitly compare a value with a boolean, use is, not ==. In this case, if found: is all you need.

The if statement inside the function can be removed entirely.

Variable and function names should follow the lower_case_with_underscores style.

A refactored version of your code would look something like this:

def in_list(targ_list, elem):
    return elem in targ_list

nums_list = [2, 4, 6, 8, 10]
num_in = int(input("Enter a number: "))

res = in_list(nums_list, num_in)

print(res)

if res:
    print('The no. IS in the list.')
else:
    print('The no. IS NOT in the list.')
```

Body:
I'm trying to write a function in Python to determine whether or not an item is in a list. I've been trying variations of this code.

No matter how I try it, it always returns a FALSE Boolean value. Even if I put the print commands inside the functions, it only prints with the results for a false value. I'm pretty sure I'm passing the list to the function properly, but I can't figure out why it only determines FALSE values. Any ideas?

def newFunction(x, y, z):
   z = 0
   if y in x:
      z = True
   else:
      z = False
   return (z)

newList = [2,4,6,8,10]
r = input ('Enter a number: ')
s = 0
newFunction(newList, r, s)
if s == True:
   print ('The no. IS in the list.')
else:
   print ('The no. IS NOT in the list.')