问:
My BottomAppBar is covering the last row in my RecyclerView
My reclerview's last row is being covered by my bottom app bar.

My code is as follows:

activity_home.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <fragment
                android:id="@id/Container_fromHomeActivity_BottomAppBarFragments"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="@bool/Navigation_NavigationHost_Default"
                app:navGraph="@navigation/bottomappbar_navigation"/>

            <com.google.android.material.bottomappbar.BottomAppBar
                    android:id="@id/BottomAppBar_fromHomeActivity_Main"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    app:fabAlignmentMode="center"
                    app:navigationIcon="@drawable/ic_menu_dark"
                    app:menu="@menu/menu_bottomappbar_main"/>

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                    android:id="@id/FAB_fromHomeActivity_BottomAppBarAttached"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_add_dark"
                    android:backgroundTint="@color/colorAccent"
                    app:layout_anchor="@id/BottomAppBar_fromHomeActivity_Main"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>
</code>```

My reclerview is in a fragment from my home activity:

fragment.xml

```<code><layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools">

<androidx.constraintlayout.widget.ConstraintLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/todoList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

</layout>
</code>```

However, the last row is only half visible as such:

From the material guidelines, the Bottom App Bar and FAB SHOULD be inside a coordinator layout for them to work together. So how am i supposed to lift my recyclerview above the bottom app bar so that the last row is visible too?

I don't want to add padding or margin at the end because it doesn't seem to be good coding...

Please help!

答: I used android:layout_marginBottom="?attr/actionBarSize" on my RecyclerView and it worked... Thanks

Body:
My reclerview's last row is being covered by my bottom app bar.

My code is as follows:

activity_home.xml

<?xml version="1.0" encoding="utf-8"?>

<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <fragment
                android:id="@id/Container_fromHomeActivity_BottomAppBarFragments"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="@bool/Navigation_NavigationHost_Default"
                app:navGraph="@navigation/bottomappbar_navigation"/>

            <com.google.android.material.bottomappbar.BottomAppBar
                    android:id="@id/BottomAppBar_fromHomeActivity_Main"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    app:fabAlignmentMode="center"
                    app:navigationIcon="@drawable/ic_menu_dark"
                    app:menu="@menu/menu_bottomappbar_main"/>

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                    android:id="@id/FAB_fromHomeActivity_BottomAppBarAttached"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_add_dark"
                    android:backgroundTint="@color/colorAccent"
                    app:layout_anchor="@id/BottomAppBar_fromHomeActivity_Main"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>

My reclerview is in a fragment from my home activity:

fragment.xml

<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools">

<androidx.constraintlayout.widget.ConstraintLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/todoList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

</layout>

However, the last row is only half visible as such:

From the material guidelines, the Bottom App Bar and FAB SHOULD be inside a coordinator layout for them to work together. So how am i supposed to lift my recyclerview above the bottom app bar so that the last row is visible too?

I don't want to add padding or margin at the end because it doesn't seem to be good coding...

Please help!


来源: stackexchange

问:
How to load other page inside the page in Angular 5
I have 4 pages in the project.

```<code>[
  { path: 'page1', component: Page1Component },
  { path: 'page2', component: Page2Component },
  { path: 'page3', component: Page3Component },
  { path: 'page4', component: Page4Component },
]
</code>```

In page4, I retrieve a URL from the backend which is one of /page1, /page2, /page3. And then I have to embed that page in /page4.

I am currently doing it with iframe but it's not good.

Is there any way to do it using ng-template or something else?

答:
You can have many router-outlet's as you want so you should try using one inside the page4 that will implies you have to modify your routing.

In that manner, when you go to page2, for example, it is going to appear in that router-outlet of the page4.

I understand that you don't want to import other modules maybe matter of perfomance and loadtimes, but in that case you can avoid that case using a SharedModule only sharing those components in that manner we avoid that module "x" doesn't know about the module "y".

I think is just matter of architecture but only you understand the project complexity.

Good luck developer!

ContentLicense: CC BY-SA 4.0

Body:
I have 4 pages in the project.

[
  { path: 'page1', component: Page1Component },
  { path: 'page2', component: Page2Component },
  { path: 'page3', component: Page3Component },
  { path: 'page4', component: Page4Component },
]

In page4, I retrieve a URL from the backend which is one of /page1, /page2, /page3. And then I have to embed that page in /page4.

I am currently doing it with iframe but it's not good.

Is there any way to do it using ng-template or something else?


问:
Give a number units when used through a class
I'm trying to get a class to spit out a number with units. The purpose of it having units would be to be able to work with the number later, but without the units getting in the way as a string. Though I have no idea how to do this. I'm quite new with (actually understanding) classes, I'm not even sure if what I ask is possible or not.

My goal is to make a class for making atoms, based on their protons, electrons and neutons. The thing I wanna try is to be able to see the units of the mass (in kgs for my purpose) when I try printing it. Here's what I have:

```<code>    class Atom:
        def __init__(self, protons, electrons, neutrons):
            ElemCharge = 1.6021765*(10**-19)
            UMAS = 1.66054*(10**-27)
            self.protons = protons
            self.electrons = electrons
            self.neutrons = neutrons
            self.charge = ElemCharge*(self.protons - self.electrons)
            self.mass = (self.protons + self.neutrons)*UMAS

    def main():

        Hydrogen = Atom(1,1,0)
        print (Hydrogen.mass)

        Argon = Atom(18,18,22)
        print (Argon.mass)

    if __name__ == "__main__":
        main()
</code>```

This code works completely fine, so no worries about that :p

Is there a way to even do this? If so, how can it be done? Thanks!

答:
I'm not sure if this is exactly what you're looking for, but you could have a method inside the Atom class that prints the mass of the atom plus a unit string.

```<code>class Atom:
    def __init__(self, protons, electrons, neutrons):
        ElemCharge = 1.6021765*(10**-19)
        UMAS = 1.66054*(10**-27)
        self.protons = protons
        self.electrons = electrons
        self.neutrons = neutrons
        self.charge = ElemCharge*(self.protons - self.electrons)
        self.mass = (self.protons + self.neutrons)*UMAS

    def print_mass_str(self):
      print('{} {}'.format(self.mass, 'kg'))
</code>```

Then this:

```<code>Argon = Atom(18,18,22)
print(Argon.mass)
Argon.print_mass_str()
</code>```

would print:

```<code>6.64216e-26
6.64216e-26 kg
</code>```

Body:
I'm trying to get a class to spit out a number with units. The purpose of it having units would be to be able to work with the number later, but without the units getting in the way as a string. Though I have no idea how to do this. I'm quite new with (actually understanding) classes, I'm not even sure if what I ask is possible or not.

My goal is to make a class for making atoms, based on their protons, electrons and neutons. The thing I wanna try is to be able to see the units of the mass (in kgs for my purpose) when I try printing it. Here's what I have:

    class Atom:
        def __init__(self, protons, electrons, neutrons):
            ElemCharge = 1.6021765*(10**-19)
            UMAS = 1.66054*(10**-27)
            self.protons = protons
            self.electrons = electrons
            self.neutrons = neutrons
            self.charge = ElemCharge*(self.protons - self.electrons)
            self.mass = (self.protons + self.neutrons)*UMAS

    def main():

        Hydrogen = Atom(1,1,0)
        print (Hydrogen.mass)

        Argon = Atom(18,18,22)
        print (Argon.mass)

    if __name__ == "__main__":
        main()

This code works completely fine, so no worries about that :p

Is there a way to even do this? If so, how can it be done? Thanks!

Body:
I'm not sure if this is exactly what you're looking for, but you could have a method inside the Atom class that prints the mass of the atom plus a unit string.

class Atom:
    def __init__(self, protons, electrons, neutrons):
        ElemCharge = 1.6021765*(10**-19)
        UMAS = 1.66054*(10**-27)
        self.protons = protons
        self.electrons = electrons
        self.neutrons = neutrons
        self.charge = ElemCharge*(self.protons - self.electrons)
        self.mass = (self.protons + self.neutrons)*UMAS

    def print_mass_str(self):
      print('{} {}'.format(self.mass, 'kg'))

Then this:

Argon = Atom(18,18,22)
print(Argon.mass)
Argon.print_mass_str()

would print:

6.64216e-26
6.64216e-26 kg


问:
How do I set a context path with embedded jetty?
I'm banging my head against the wall on this. I wrote a tiny embedded jetty server (jetty 9.4.18, jersey 1.19.4) and I cannot for the life of me get it to respect the context path and my REST services deployed.

I tried setContextPath, but that never worked on ServletContextHandler, so I went with WebAppContext.

This is about as simple as I can get it:

```<code>Server jettyServer = new Server(9999);

// set up the web app
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/app/");
webapp.setResourceBase("web");

jettyServer.setHandler(webapp);

// add REST service
ServletHolder jerseyServlet = webapp.addServlet(ServletContainer.class, "/service/*");
final ResourceConfig resourceConfig = new ResourceConfig(RestService.class);
resourceConfig.register(MultiPartFeature.class);
jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "org.futureboy.app.server.rest");

try {
    jettyServer.start();
    jettyServer.join();
} catch (Exception e) {
    e.printStackTrace();
    //jettyServer.stop();
    jettyServer.destroy();
}
</code>```

The static HTML files are served up in the web directory, and this works fine if I keep this line as follows:

```<code>ServletHolder jerseyServlet = webapp.addServlet(ServletContainer.class, "/service/*");
</code>```

However this means the REST service (which operates under /app/service) does not work. If I swap this line out:

```<code>ServletHolder jerseyServlet = webapp.addServlet(ServletContainer.class, "/*");
</code>```

Then the REST service works fine, but now the static HTML content does NOT work fine. So I either get a working static HTML service on /app/ or a working REST service underneath /app/service, but I can't have both. What am I doing wrong? The RestService.java file starts like:

```<code>@Path("/service")
public class RestService {
</code>```

Any help would be appreciated, for I feel I am stuck on the one-yard line here.

答:
Why do you want Jersey to serve static content?

That's not the role of a JAX-B server.

What do do ...

Switch from WebAppContext to ServletContextHandler (you don't need the overhead of WebAppContext or any of the bytecode scanning or annotation scanning deployment techniques that a full blown WebAppContext brings to the table.

Prevent Jersey from serving static content.

Setup a proper ResourceBase - use a fully qualified path or URI (no relative paths, no partial URIs)

Add a DefaultServlet on the default url-pattern "/" named "default".

Which these changes Jetty will serve static content, from your Resource Base.

Some prior answers/examples of the Jetty side configuration and DefaultServlet usage:

Deploying Jetty server via .jar. Why can't I access the index?

How to get embedded Jetty serving html files from a Jar, not a War

Serving static files from alternate path in embedded Jetty

What is difference between ServletContextHandler.setResourceBase and ResourceHandler.setResourceBase when using Jetty embedded container?

Jetty: default servlet context path

Display static HTML file from resources folder in Jetty Serverlet doGet method

And there's many many answers on how to configure Jersey to not serve static content.

One my favs is the solution provided at ...

Servlet for serving static content

Body:
I'm banging my head against the wall on this. I wrote a tiny embedded jetty server (jetty 9.4.18, jersey 1.19.4) and I cannot for the life of me get it to respect the context path and my REST services deployed.

I tried setContextPath, but that never worked on ServletContextHandler, so I went with WebAppContext.

This is about as simple as I can get it:

Server jettyServer = new Server(9999);

// set up the web app
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/app/");
webapp.setResourceBase("web");

jettyServer.setHandler(webapp);

// add REST service
ServletHolder jerseyServlet = webapp.addServlet(ServletContainer.class, "/service/*");
final ResourceConfig resourceConfig = new ResourceConfig(RestService.class);
resourceConfig.register(MultiPartFeature.class);
jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "org.futureboy.app.server.rest");

try {
    jettyServer.start();
    jettyServer.join();
} catch (Exception e) {
    e.printStackTrace();
    //jettyServer.stop();
    jettyServer.destroy();
}

The static HTML files are served up in the web directory, and this works fine if I keep this line as follows:

ServletHolder jerseyServlet = webapp.addServlet(ServletContainer.class, "/service/*");

However this means the REST service (which operates under /app/service) does not work. If I swap this line out:

ServletHolder jerseyServlet = webapp.addServlet(ServletContainer.class, "/*");

Then the REST service works fine, but now the static HTML content does NOT work fine. So I either get a working static HTML service on /app/ or a working REST service underneath /app/service, but I can't have both. What am I doing wrong? The RestService.java file starts like:

@Path("/service")
public class RestService {

Any help would be appreciated, for I feel I am stuck on the one-yard line here.


问:
Floating right pushes div to the end of the page
I am trying to put 2 divs side by side. However, when doing this, one div is pushed to the very right of the page? I am not sure why it is doing this. Any help is appreciated :)

JSFIDDLE:
https://jsfiddle.net/7crhg2L8/

HTML:

```<code><div class="navrectangle"></div>
<div class="addrectangle"></div>
</code>```

CSS:

```<code>.navrectangle{
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
float: left;
}
/** SECOND RECTANGLE **/
.addrectangle{
  float:right;
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
}
</code>```

答:
Put the divs in a parent div and style that parent div to have the width of the two divs combined, in your case 40vw.

The CSS:

```<code>.navrectangle {
  width: 20vw;
  height: 100vh;
  background-image: linear-gradient(to right, #002067, #013d98);
  float: left;
}
/** SECOND RECTANGLE **/
.addrectangle {
  float:right;
  display: inline-block;
  width: 20vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
}

#container {
  width: 40vw;
}
</code>```

The HTML:

```<code><div id="container">
<div class="navrectangle"></div>
<div class="addrectangle"></div>
</div>
</code>```

Hope this is what you were looking for

Body:
I am trying to put 2 divs side by side. However, when doing this, one div is pushed to the very right of the page? I am not sure why it is doing this. Any help is appreciated :)

JSFIDDLE:
https://jsfiddle.net/7crhg2L8/

HTML:

CSS:

.navrectangle{
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
float: left;
}
/** SECOND RECTANGLE **/
.addrectangle{
  float:right;
  width: 20Vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
}

Body:
Put the divs in a parent div and style that parent div to have the width of the two divs combined, in your case 40vw.

The CSS:

.navrectangle {
  width: 20vw;
  height: 100vh;
  background-image: linear-gradient(to right, #002067, #013d98);
  float: left;
}
/** SECOND RECTANGLE **/
.addrectangle {
  float:right;
  display: inline-block;
  width: 20vw;
  height: 100vh;
background-image: linear-gradient(to right, #002067, #013d98);
}

#container {
  width: 40vw;
}

The HTML:

<div id="container">
<div class="navrectangle"></div>
<div class="addrectangle"></div>
</div>

Hope this is what you were looking for


问:
webapi controller return csv data
I have a webapi controller code looks like:

```<code>        [HttpPost]
    public HttpResponseMessage DownloadForms(FormCriteria criteria)
    {
        string downloadData = new FormsToCsvHelper(Umbraco, criteria).GetCsv();
        return Request.CreateResponse(HttpStatusCode.OK, downloadData);
    }
</code>```

If i look at the data returned in debugger just before sending it back it looks like:

```<code>Created Date,IP,Form Name,Email address,Message,Full Name
</code>```

31/05/2019 10:43:08,127.0.0.1,Contact form - test,test12@hotmail.com,test,Ismail Mayat

If I copy and paste it into file and save as csv it looks fine in excel.

However the data i actually get back looks like:

```<code>"Created Date,IP,Form Name,Email address,Message,Full Name\r\n31/05/2019 10:43:08,127.0.0.1,Contact form - test,test12@hotmail.com,test,Ismail Mayat"
</code>```

The whole record set it wrapped in quote and the line feed is seen as a literal so when opening file in excel its all on one line.

There is a DelegatingHandler that fire but that is for a specific url request so for this request it does not do anything.

Anyone any ideas whats going on?

答:
WebAPI will serialize the value as JSON by default, so that's why your value is enclosed in double quotes.

To get around this, you can use the StringContent class:

return new HttpResponseMessage(statusCode) {
    Content = new StringContent(downloadData, Encoding.UTF8, "text/csv")
};
```

Title: webapi controller return csv data

Body:
I have a webapi controller code looks like:

        [HttpPost]
    public HttpResponseMessage DownloadForms(FormCriteria criteria)
    {
        string downloadData = new FormsToCsvHelper(Umbraco, criteria).GetCsv();
        return Request.CreateResponse(HttpStatusCode.OK, downloadData);
    }

If i look at the data returned in debugger just before sending it back it looks like:

Created Date,IP,Form Name,Email address,Message,Full Name

31/05/2019 10:43:08,127.0.0.1,Contact form - test,test12@hotmail.com,test,Ismail Mayat

If I copy and paste it into file and save as csv it looks fine in excel.

However the data i actually get back looks like:

"Created Date,IP,Form Name,Email address,Message,Full Name\r\n31/05/2019 10:43:08,127.0.0.1,Contact form - test,test12@hotmail.com,test,Ismail Mayat"

The whole record set it wrapped in quote and the line feed is seen as a literal so when opening file in excel its all on one line.

There is a DelegatingHandler that fire but that is for a specific url request so for this request it does not do anything.

Anyone any ideas whats going on?


答:
This works?
Basically I have added another property to the Atom class so that all objects of type Atom can use it. Another way of doing it would be to pass it as you are doing with the neutrons/protons/electrons. That way it you can perform your own calculations (if there was a requirement to do so) given a unit (say you wanted to show weight in grams for Hydrogen , while in KGs for Argon)

```<code>class Atom:
    def __init__(self, protons, electrons, neutrons):
        ElemCharge = 1.6021765*(10**-19)
        UMAS = 1.66054*(10**-27)
        self.protons = protons
        self.electrons = electrons
        self.neutrons = neutrons
        self.charge = ElemCharge*(self.protons - self.electrons)
        self.mass = (self.protons + self.neutrons)*UMAS
        self.massUnit = "kgs"

def main():

    Hydrogen = Atom(1,1,0)
    print ("{0} {1}".format(Hydrogen.mass,Hydrogen.massUnit))

    Argon = Atom(18,18,22)
    print ("{0} {1}".format(Argon.mass,Argon.massUnit))

if __name__ == "__main__":
    main()
</code>```

Output

```<code>1.66054e-27 kgs
6.64216e-26 kgs
</code>```

Title: Give a number units when used through a class

Body:
This works?
Basically I have added another property to the Atom class so that all objects of type Atom can use it. Another way of doing it would be to pass it as you are doing with the neutrons/protons/electrons. That way it you can perform your own calculations (if there was a requirement to do so) given a unit (say you wanted to show weight in grams for Hydrogen , while in KGs for Argon)

class Atom:
    def __init__(self, protons, electrons, neutrons):
        ElemCharge = 1.6021765*(10**-19)
        UMAS = 1.66054*(10**-27)
        self.protons = protons
        self.electrons = electrons
        self.neutrons = neutrons
        self.charge = ElemCharge*(self.protons - self.electrons)
        self.mass = (self.protons + self.neutrons)*UMAS
        self.massUnit = "kgs"

def main():

    Hydrogen = Atom(1,1,0)
    print ("{0} {1}".format(Hydrogen.mass,Hydrogen.massUnit))

    Argon = Atom(18,18,22)
    print ("{0} {1}".format(Argon.mass,Argon.massUnit))

if __name__ == "__main__":
    main()

Output

1.66054e-27 kgs
6.64216e-26 kgs


问:
Android Log Cat Error ContextResult::kFatalFailure
I am getting the following error in Logcat when I run my app in the device or emulator:

```<code>[ERROR:context_group.cc(137)] ContextResult::kFatalFailure: WebGL1 blacklisted
</code>```

Why am I getting this error?

答:
What's your device? I have that issue when using the emulator but it runs fine on my Samsung Galaxy J7 Pro.

From what I've found the issue is that software rendering is insufficient to handle webgl: https://bugreports.qt.io/browse/QTBUG-69236?focusedCommentId=413317&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel

Body:
I am getting the following error in Logcat when I run my app in the device or emulator:

[ERROR:context_group.cc(137)] ContextResult::kFatalFailure: WebGL1 blacklisted

Why am I getting this error?


问:
Allowing access to data remotely via xml?
If I wanted to allow someone to access data so they can put it on their site could I just have them point to a script on my server that takes certain queries via the url and that script queries my database, then sends back the data to the person requesting the script in an xml format? That would be a very basic api setup wouldnt it? There isnt a lot of data and not a lot of calls so not worried about it slowing down my site. I just wanted to know if that is a normal/basic way of creating an api?</p>

答:
What you described is basically a web service.

I'd suggest trying a RESTful API. It boils down to this: you provide certain URLs on your server for your clients. They invoke that URL and you send them information in some format (usually XML or JSON) that they can use for further processing.

Example: try going to this website:

http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=stackoverflow

You will receive this response:

```<code>{"responseData": {"results":[{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://stackoverflow.com/","url":"http://stackoverflow.com/","visibleUrl":"stackoverflow.com","cacheUrl":"http://www.google.com/search?q\u003dcache:U1GC2GYOToIJ:stackoverflow.com","title":"\u003cb\u003eStack Overflow\u003c/b\u003e","titleNoFormatting":"Stack Overflow","content":"A language-independent collaboratively edited question and answer site for   programmers."},{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://stackoverflow.com/users/login","url":"http://stackoverflow.com/users/login","visibleUrl":"stackoverflow.com","cacheUrl":"http://www.google.com/search?q\u003dcache:4nkh8ecRZGUJ:stackoverflow.com","title":"Log In - \u003cb\u003eStack Overflow\u003c/b\u003e","titleNoFormatting":"Log In - Stack Overflow","content":"\u003cb\u003estackoverflow\u003c/b\u003e.com ■ api/apps ■ careers ■ serverfault.com ■ superuser.com \u003cb\u003e...\u003c/b\u003e"},{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://blog.stackoverflow.com/","url":"http://blog.stackoverflow.com/","visibleUrl":"blog.stackoverflow.com","cacheUrl":"http://www.google.com/search?q\u003dcache:iqtvg9Ge1c0J:blog.stackoverflow.com","title":"Blog – Stack Exchange","titleNoFormatting":"Blog – Stack Exchange","content":"They seem to think that we only have 659000 visitors to \u003cb\u003estackoverflow\u003c/b\u003e.com \u003cb\u003e...\u003c/b\u003e"},{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://en.wikipedia.org/wiki/Stack_overflow","url":"http://en.wikipedia.org/wiki/Stack_overflow","visibleUrl":"en.wikipedia.org","cacheUrl":"http://www.google.com/search?q\u003dcache:mWu8b0BQAmwJ:en.wikipedia.org","title":"\u003cb\u003eStack overflow\u003c/b\u003e - Wikipedia, the free encyclopedia","titleNoFormatting":"Stack overflow - Wikipedia, the free encyclopedia","content":"In software, a \u003cb\u003estack overflow\u003c/b\u003e occurs when too much memory is used on the call   stack. The call stack contains a limited amount of memory, often determined at   \u003cb\u003e...\u003c/b\u003e"}],"cursor":{"pages":[{"start":"0","label":1},{"start":"4","label":2},{"start":"8","label":3},{"start":"12","label":4},{"start":"16","label":5},{"start":"20","label":6},{"start":"24","label":7},{"start":"28","label":8}],"estimatedResultCount":"1410000","currentPageIndex":0,"moreResultsUrl":"http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003dstackoverflow"}}, "responseDetails": null, "responseStatus": 200}
</code>```

which is Google's results when you search for "Stackoverflow".

ContentLicense: CC BY-SA 3.0

Body:
What you described is basically a web service.

I'd suggest trying a RESTful API. It boils down to this: you provide certain URLs on your server for your clients. They invoke that URL and you send them information in some format (usually XML or JSON) that they can use for further processing.

Example: try going to this website:

http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=stackoverflow

You will receive this response:

{"responseData": {"results":[{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://stackoverflow.com/","url":"http://stackoverflow.com/","visibleUrl":"stackoverflow.com","cacheUrl":"http://www.google.com/search?q\u003dcache:U1GC2GYOToIJ:stackoverflow.com","title":"\u003cb\u003eStack Overflow\u003c/b\u003e","titleNoFormatting":"Stack Overflow","content":"A language-independent collaboratively edited question and answer site for   programmers."},{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://stackoverflow.com/users/login","url":"http://stackoverflow.com/users/login","visibleUrl":"stackoverflow.com","cacheUrl":"http://www.google.com/search?q\u003dcache:4nkh8ecRZGUJ:stackoverflow.com","title":"Log In - \u003cb\u003eStack Overflow\u003c/b\u003e","titleNoFormatting":"Log In - Stack Overflow","content":"\u003cb\u003estackoverflow\u003c/b\u003e.com ■ api/apps ■ careers ■ serverfault.com ■ superuser.com \u003cb\u003e...\u003c/b\u003e"},{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://blog.stackoverflow.com/","url":"http://blog.stackoverflow.com/","visibleUrl":"blog.stackoverflow.com","cacheUrl":"http://www.google.com/search?q\u003dcache:iqtvg9Ge1c0J:blog.stackoverflow.com","title":"Blog – Stack Exchange","titleNoFormatting":"Blog – Stack Exchange","content":"They seem to think that we only have 659000 visitors to \u003cb\u003estackoverflow\u003c/b\u003e.com \u003cb\u003e...\u003c/b\u003e"},{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://en.wikipedia.org/wiki/Stack_overflow","url":"http://en.wikipedia.org/wiki/Stack_overflow","visibleUrl":"en.wikipedia.org","cacheUrl":"http://www.google.com/search?q\u003dcache:mWu8b0BQAmwJ:en.wikipedia.org","title":"\u003cb\u003eStack overflow\u003c/b\u003e - Wikipedia, the free encyclopedia","titleNoFormatting":"Stack overflow - Wikipedia, the free encyclopedia","content":"In software, a \u003cb\u003estack overflow\u003c/b\u003e occurs when too much memory is used on the call   stack. The call stack contains a limited amount of memory, often determined at   \u003cb\u003e...\u003c/b\u003e"}],"cursor":{"pages":[{"start":"0","label":1},{"start":"4","label":2},{"start":"8","label":3},{"start":"12","label":4},{"start":"16","label":5},{"start":"20","label":6},{"start":"24","label":7},{"start":"28","label":8}],"estimatedResultCount":"1410000","currentPageIndex":0,"moreResultsUrl":"http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003dstackoverflow"}}, "responseDetails": null, "responseStatus": 200}

which is Google's results when you search for "Stackoverflow".


问:
How to add roles to claims in IdentityServer4?
I am new to IdentityServer and I have been struggling with this issue all day. So much so that I'm almost about to give up on this. I know this question has been asked over and over again and I have tried many different solutions but none seem to work. Hopefully you can help me push me in the right direction with this.

First I installed the IdentityServer4 templates by running dotnet new -i identityserver4.templates and created a new project with the is4aspid template by running dotnet new is4aspid -o IdentityServer.

After that i created a new IdentityServer database and ran the migrations. By that time I had a the default Identity database structure.

In Config.cs I changed MVC client to the following:

```<code>new Client
{
    ClientId = "mvc",
    ClientName = "MVC Client",

    AllowedGrantTypes = GrantTypes.Implicit,
    ClientSecrets = { new Secret("47C2A9E1-6A76-3A19-F3C0-S37763QB36D9".Sha256()) },

    RedirectUris = { "https://localhost:44307/signin-oidc" },
    FrontChannelLogoutUri = "https://localhost:44307/signout-oidc",
    PostLogoutRedirectUris = { "https://localhost:44307/signout-callback-oidc" },

    AllowOfflineAccess = true,
    AllowedScopes = { "openid", "profile", "api1", JwtClaimTypes.Role }
},
</code>```

And changed the GetApis method to this:

```<code>public static IEnumerable<ApiResource> GetApis()
{
    return new ApiResource[]
    {
        new ApiResource("api1", "My API #1", new List<string>() { "role" })
    };
}
</code>```

There where of course no users in the database yet so i added a registration form and registered two dummy users, one with the username admin@example.com and one with the username subscriber@example.com.

To assign the roles to these user I created the following method in Startup.cs.

```<code>private async Task CreateUserRoles(IServiceProvider serviceProvider) {
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

    IdentityResult adminRoleResult;
    IdentityResult subscriberRoleResult;

    bool adminRoleExists = await RoleManager.RoleExistsAsync("Admin");
    bool subscriberRoleExists = await RoleManager.RoleExistsAsync("Subscriber");

    if (!adminRoleExists) {
        adminRoleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
    }

    if(!subscriberRoleExists) {
        subscriberRoleResult = await RoleManager.CreateAsync(new IdentityRole("Subscriber"));
    }

    ApplicationUser userToMakeAdmin = await UserManager.FindByNameAsync("admin@example.com");
    await UserManager.AddToRoleAsync(userToMakeAdmin, "Admin");

    ApplicationUser userToMakeSubscriber = await UserManager.FindByNameAsync("subscriber@example.com");
    await UserManager.AddToRoleAsync(userToMakeSubscriber, "Subscriber");
}
</code>```

In the Configure method of the same class I add the the parameter IServiceProvider services and called the above method like so: CreateUserRoles(services).Wait();. By this time my database did have two roles in it.

Next I created a new solution (within the same project) and in the Startup.cs file of that solution I added the following in the ConfigureServices method.

```<code>    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options => {
            options.SaveTokens = true;
            options.ClientId = "mvc";
            options.ClientSecret = "32D7A7W0-0ALN-2Q44-A1H4-A37990NN83BP";
            options.RequireHttpsMetadata = false;
            options.Authority = "http://localhost:5000/";
            options.ClaimActions.MapJsonKey("role", "role");
        });
</code>```

After that I added app.UseAuthentication(); in the Configure method of the same class.

Then I created a new page with the following if statements.

```<code>if(User.Identity.IsAuthenticated) {
 <div>Yes, user is authenticated</div>
}

if(User.IsInRole("ADMIN")) {
 <div>Yes, user is admin</div>
}
</code>```

I logged in with admin@example.com but the second if statement returns False. I inspected all the claims by looping over them like so.

```<code>@foreach (var claim in User.Claims) {
    <dt>@claim.Type</dt>
    <dd>@claim.Value</dd>
}
</code>```

But there was no role claim to be found, only sid, sub, idp, preferred_username and name.

I tried to get the role in there so that the second if statement returns True but after trying and trying I have not yet been able to make it work. Can someone see what I have to do in order to make this work? I am an absolute beginner in IdentityServer4 and trying my best to understand it. Any help will be appreciated. Thanks in advance!

EDIT 1:

Thanks to this question and this question I got the feeling that I'm on the right track. I have made some modifications but I still can not get it to work. I just tried the following.

Created a new ProfileService class in my IdentityServer project with the following content.

```<code>public class MyProfileService : IProfileService {
 public MyProfileService() { }
 public Task GetProfileDataAsync(ProfileDataRequestContext context) {
  var roleClaims = context.Subject.FindAll(JwtClaimTypes.Role);
  List<string> list = context.RequestedClaimTypes.ToList();
  context.IssuedClaims.AddRange(roleClaims);
  return Task.CompletedTask;
 }

 public Task IsActiveAsync(IsActiveContext context) {
  return Task.CompletedTask;
 }
}
</code>```

Next I registered this class in the ConfigureServices method by adding the line services.AddTransient<IProfileService, MyProfileService>();. After that I added a new a new line to the GetIdentityResources method, which looks like this now.

```<code>public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new IdentityResource[]
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
        new IdentityResource("roles", new[] { "role" })
};
}
</code>```

I also added the roles to my Mvc client like so: AllowedScopes = { "openid", "profile", "api1", "roles" }.

Next I switched over to the other project and added the following lines in the .AddOpenIdConnect oidc.

```<code>options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.RoleClaimType = "role";
</code>```

But still, I cannot get it to work like I want it to. Anyone knows what I am missing?

答:
Two things you need to do to make sure you will get users roles in the claims:

1- In IdentityServer4 project: you need to have implementation for IProfileService
http://docs.identityserver.io/en/latest/reference/profileservice.html

don't forget to add the class in startup.cs file like this

```<code>services.AddIdentityServer()
// I just removed some other configurations for clarity
                **.AddProfileService<IdentityProfileService>();**
</code>```

2- In Web Client project's startup.cs file: when configuring the openId, you have to mention this :

```<code>services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options =>
        {
            options.SignInScheme = "Cookies";
            options.Authority = "Identity URL ";
            options.RequireHttpsMetadata = true;

            options.ClientId = "saas_crm_webclient";
            options.ClientSecret = "49C1A7E1-0C79-4A89-A3D6-A37998FB86B0";
            options.ResponseType = "code id_token";
            options.SaveTokens = true;
            options.GetClaimsFromUserInfoEndpoint = false;

            options.Scope.Add("test.api");
            options.Scope.Add("identity.api");
            options.Scope.Add("offline_access");

            **options.ClaimActions.Add(new JsonKeyClaimAction("role", null, "role"));**

            **options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                NameClaimType = "name",
                RoleClaimType = "role"
            };**
        });
</code>```

Body:
I am new to IdentityServer and I have been struggling with this issue all day. So much so that I'm almost about to give up on this. I know this question has been asked over and over again and I have tried many different solutions but none seem to work. Hopefully you can help me push me in the right direction with this.

First I installed the IdentityServer4 templates by running dotnet new -i identityserver4.templates and created a new project with the is4aspid template by running dotnet new is4aspid -o IdentityServer.

After that i created a new IdentityServer database and ran the migrations. By that time I had a the default Identity database structure.

In Config.cs I changed MVC client to the following:

new Client
{
    ClientId = "mvc",
    ClientName = "MVC Client",

    AllowedGrantTypes = GrantTypes.Implicit,
    ClientSecrets = { new Secret("47C2A9E1-6A76-3A19-F3C0-S37763QB36D9".Sha256()) },

    RedirectUris = { "https://localhost:44307/signin-oidc" },
    FrontChannelLogoutUri = "https://localhost:44307/signout-oidc",
    PostLogoutRedirectUris = { "https://localhost:44307/signout-callback-oidc" },

    AllowOfflineAccess = true,
    AllowedScopes = { "openid", "profile", "api1", JwtClaimTypes.Role }
},

And changed the GetApis method to this:

public static IEnumerable<ApiResource> GetApis()
{
    return new ApiResource[]
    {
        new ApiResource("api1", "My API #1", new List<string>() { "role" })
    };
}

There where of course no users in the database yet so i added a registration form and registered two dummy users, one with the username admin@example.com and one with the username subscriber@example.com.

To assign the roles to these user I created the following method in Startup.cs.

private async Task CreateUserRoles(IServiceProvider serviceProvider) {
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

    IdentityResult adminRoleResult;
    IdentityResult subscriberRoleResult;

    bool adminRoleExists = await RoleManager.RoleExistsAsync("Admin");
    bool subscriberRoleExists = await RoleManager.RoleExistsAsync("Subscriber");

    if (!adminRoleExists) {
        adminRoleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
    }

    if(!subscriberRoleExists) {
        subscriberRoleResult = await RoleManager.CreateAsync(new IdentityRole("Subscriber"));
    }

    ApplicationUser userToMakeAdmin = await UserManager.FindByNameAsync("admin@example.com");
    await UserManager.AddToRoleAsync(userToMakeAdmin, "Admin");

    ApplicationUser userToMakeSubscriber = await UserManager.FindByNameAsync("subscriber@example.com");
    await UserManager.AddToRoleAsync(userToMakeSubscriber, "Subscriber");
}

In the Configure method of the same class I add the the parameter IServiceProvider services and called the above method like so: CreateUserRoles(services).Wait();. By this time my database did have two roles in it.

Next I created a new solution (within the same project) and in the Startup.cs file of that solution I added the following in the ConfigureServices method.

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options => {
            options.SaveTokens = true;
            options.ClientId = "mvc";
            options.ClientSecret = "32D7A7W0-0ALN-2Q44-A1H4-A37990NN83BP";
            options.RequireHttpsMetadata = false;
            options.Authority = "http://localhost:5000/";
            options.ClaimActions.MapJsonKey("role", "role");
        });

After that I added app.UseAuthentication(); in the Configure method of the same class.

Then I created a new page with the following if statements.

if(User.Identity.IsAuthenticated) {

Yes, user is authenticated

}

if(User.IsInRole("ADMIN")) {

Yes, user is admin

}

I logged in with admin@example.com but the second if statement returns False. I inspected all the claims by looping over them like so.

@foreach (var claim in User.Claims) {

@claim.Type

@claim.Value

}

But there was no role claim to be found, only sid, sub, idp, preferred_username and name.

I tried to get the role in there so that the second if statement returns True but after trying and trying I have not yet been able to make it work. Can someone see what I have to do in order to make this work? I am an absolute beginner in IdentityServer4 and trying my best to understand it. Any help will be appreciated. Thanks in advance!

EDIT 1:

Thanks to this question and this question I got the feeling that I'm on the right track. I have made some modifications but I still can not get it to work. I just tried the following.

Created a new ProfileService class in my IdentityServer project with the following content.

public class MyProfileService : IProfileService {
 public MyProfileService() { }
 public Task GetProfileDataAsync(ProfileDataRequestContext context) {
  var roleClaims = context.Subject.FindAll(JwtClaimTypes.Role);
  List<string> list = context.RequestedClaimTypes.ToList();
  context.IssuedClaims.AddRange(roleClaims);
  return Task.CompletedTask;
 }

 public Task IsActiveAsync(IsActiveContext context) {
  return Task.CompletedTask;
 }
}

Next I registered this class in the ConfigureServices method by adding the line services.AddTransient<IProfileService, MyProfileService>();. After that I added a new a new line to the GetIdentityResources method, which looks like this now.

public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new IdentityResource[]
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
        new IdentityResource("roles", new[] { "role" })
};
}

I also added the roles to my Mvc client like so: AllowedScopes = { "openid", "profile", "api1", "roles" }.

Next I switched over to the other project and added the following lines in the .AddOpenIdConnect oidc.

options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.RoleClaimType = "role";

But still, I cannot get it to work like I want it to. Anyone knows what I am missing?

Body:
Two things you need to do to make sure you will get users roles in the claims:

1- In IdentityServer4 project: you need to have implementation for IProfileService
http://docs.identityserver.io/en/latest/reference/profileservice.html

don't forget to add the class in startup.cs file like this

services.AddIdentityServer()
// I just removed some other configurations for clarity
                **.AddProfileService<IdentityProfileService>();**

2- In Web Client project's startup.cs file: when configuring the openId, you have to mention this :

services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options =>
        {
            options.SignInScheme = "Cookies";
            options.Authority = "Identity URL ";
            options.RequireHttpsMetadata = true;

            options.ClientId = "saas_crm_webclient";
            options.ClientSecret = "49C1A7E1-0C79-4A89-A3D6-A37998FB86B0";
            options.ResponseType = "code id_token";
            options.SaveTokens = true;
            options.GetClaimsFromUserInfoEndpoint = false;

            options.Scope.Add("test.api");
            options.Scope.Add("identity.api");
            options.Scope.Add("offline_access");

            **options.ClaimActions.Add(new JsonKeyClaimAction("role", null, "role"));**

            **options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                NameClaimType = "name",
                RoleClaimType = "role"
            };**
        });


问:
How to swap TRUE and FALSE in a dataframe with dplyr
I'm looking to change values into their opposite (T becomes F, and vice versa) in specific rows in a column in a datatable

I know that x <- !x works for T/F variables but how to finish this dplyr approach:

```<code>library(dplyr)
library(datatable)
library(magrittr)
mtcars$selected <- T
mtcars %>% select(selected) %>% slice(c(1,4,5)) %>% mutate(??)
</code>```

Body:
I'm looking to change values into their opposite (T becomes F, and vice versa) in specific rows in a column in a datatable

I know that x <- !x works for T/F variables but how to finish this dplyr approach:

library(dplyr)
library(datatable)
library(magrittr)
mtcars$selected <- T
mtcars %>% select(selected) %>% slice(c(1,4,5)) %>% mutate(??)

Body:
If you just want to subset those rows, then @Shree's answer is likely right. If you want to invert just those rows but otherwise keep all, then something like:

In dplyr:

library(dplyr)
mtcars %>%
  mutate(selected = TRUE) %>%
  # the heart of the answer
  mutate(selected = if_else(row_number() %in% c(1, 4, 5), !selected, selected))
#     mpg cyl  disp  hp drat    wt  qsec vs am gear carb selected
# 1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4    FALSE
# 2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4     TRUE
# 3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1     TRUE
# 4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1    FALSE
# 5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2    FALSE
# 6  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1     TRUE
# 7  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4     TRUE
# 8  24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2     TRUE
# ...

You said datatable, I think you meant data.table, in which case

library(data.table)
DT <- as.data.table(mtcars)
DT[, selected := TRUE]
DT[, selected := ifelse(.I %in% c(1, 3, 4), !selected, selected)]
head(DT, n = 8)
#      mpg cyl  disp  hp drat    wt  qsec vs am gear carb selected
#  1: 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4    FALSE
#  2: 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4     TRUE
#  3: 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1    FALSE
#  4: 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1    FALSE
#  5: 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2     TRUE
#  6: 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1     TRUE
#  7: 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4     TRUE
#  8: 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2     TRUE

Or pipe-wise as

library(magrittr)
DT <- as.data.table(mtcars)
DT %>%
  .[, selected := TRUE] %>%
  .[, selected := ifelse(.I %in% c(1, 3, 4), !selected, selected)]
head(DT, n = 8)
#     mpg cyl  disp  hp drat    wt  qsec vs am gear carb selected
# 1: 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4    FALSE
# 2: 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4     TRUE
# 3: 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1    FALSE
# 4: 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1    FALSE
# 5: 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2     TRUE
# 6: 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1     TRUE
# 7: 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4     TRUE
# 8: 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2     TRUE

In Base R, you can do it this way:

mtcars$selected <- TRUE
mtcars$selected[c(1, 3, 4)] <- !mtcars$selected[c(1, 3, 4)]
head(mtcars, n = 8)
#                    mpg cyl  disp  hp drat    wt  qsec vs am gear carb selected
# Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4    FALSE
# Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4     TRUE
# Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1    FALSE
# Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1    FALSE
# Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2     TRUE
# Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1     TRUE
# Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4     TRUE
# Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2     TRUE


问:
Flask Mail does not send email
I am trying to send a reset password email using flask-mail. The code executes without errors but I didn't receive any email.

I tried the following:

adding those line to the app.config in the init.py file:

app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_DEBUG'] = True
app.config['DEBUG'] = True
app.config['MAIL_FAIL_SILENTLY'] = False
app.config['TESTING'] = False
```

<ol start="2">
<li>Changing the (Less secure app access) setting in Gmail to be on.</li>
</ol>

<p>Here are some lines of my code:</p>

<p>In <strong>init</strong>.py file:</p>

<pre class="lang-py prettyprint-override"><code>import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_DEBUG'] = True
app.config['DEBUG'] = True
app.config['MAIL_FAIL_SILENTLY'] = False
app.config['TESTING'] = False
mail = Mail(app)
</code>```

In routes.py file:

def send_reset_email(user):
    token = user.get_reset_token()
    msg = Message(subject='Password Reset Request', sender='noreply@demo.com', recipients=[user.email])

    msg.body = f''' To reset your password, visit the following link!:
{url_for('reset_token', token=token, _external=True)}

If you did not make this request then simply ignore this email and no changes will be made
'''

@app.route("/reset_password", methods=['GET', 'POST'])
def reset_request():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash('An email has been sent with instructions to reset your password.', 'info')
        return redirect(url_for('login'))
    return render_template('reset_request.html', title='Reset Password', form=form)
```

I expected to receive the reset email but I didn't and it fails silently.

答: You will need to call mail.send(msg)

Title: Flask Mail does not send email

Body:
I am trying to send a reset password email using flask-mail. The code executes without errors but I didn't receive any email.

I tried the following:

adding those line to the app.config in the init.py file:

app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_DEBUG'] = True
app.config['DEBUG'] = True
app.config['MAIL_FAIL_SILENTLY'] = False
app.config['TESTING'] = False

Changing the (Less secure app access) setting in Gmail to be on.

Here are some lines of my code:

In init.py file:

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_DEBUG'] = True
app.config['DEBUG'] = True
app.config['MAIL_FAIL_SILENTLY'] = False
app.config['TESTING'] = False
mail = Mail(app)

In routes.py file:

def send_reset_email(user):
    token = user.get_reset_token()
    msg = Message(subject='Password Reset Request', sender='noreply@demo.com', recipients=[user.email])

    msg.body = f''' To reset your password, visit the following link!:
{url_for('reset_token', token=token, _external=True)}

If you did not make this request then simply ignore this email and no changes will be made
'''

@app.route("/reset_password", methods=['GET', 'POST'])
def reset_request():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash('An email has been sent with instructions to reset your password.', 'info')
        return redirect(url_for('login'))
    return render_template('reset_request.html', title='Reset Password', form=form)

I expected to receive the reset email but I didn't and it fails silently.

Body: You will need to call mail.send(msg)


问:
Regex Capturing Group within a Capture Group
I am searching through a database to find span tags with video information for the purpose of migration.

My regex works well and I can extract all of the information I need for the most part.   The trouble I run into is when the style tag is in a different position than expected.   This throws off the expression and results in about 2/3rds of the captures I would expect.

If I try and nest the style capture group inside the main capture group, it fails to capture anything.   I also tried using negative/positive lookaheads as well, but it only ever works if I make it an optional capture group.   I think the problem is im not nesting it correctly.   Most of the related questions give the answer of a negative lookbehind, but my understanding is that's more of a assertion/quantifier.

So how can I always capture the style tag regardless of its position in the span tag?

Regex flavor is .NET (server side)

I have a Regexr setup

/(?<tag><span class='vidly-vid' data-thumb='(?<thumb>http.+\.jpg)'.+aspect-ratio='(?<aspect>\d{1,3}:\d{1,3})'.+sources='\[{"file":.+"(?<src>(?<uri>https:\/\/cf1234.cloudfront\.net\/Vids\/)(?<key>(?<ident>[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}|[a-z0-9]{6})\/(?<mp4>mp4_1080.mp4|mp4_720.mp4|mp4_480.mp4|mp4_360.mp4|mp4.mp4))).+style='(?

答:
I'd personally just split up the regex into more manageable chunks, like so:

```<code>var spanRegex = new Regex(@"<span class='vidly-vid'.+<\/span>");
var attrRegexes = new[]{
    @"data-thumb='(?<thumb>http.+\.jpg)'",
    @"aspect-ratio='(?<aspect>\d{1,3}:\d{1,3})'",
    @"sources='\[{""file"":.+""(?<src>(?<uri>https:\/\/cf1234.cloudfront\.net\/Vids\/)(?<key>(?<ident>[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}|[a-z0-9]{6})\/(?<mp4>mp4_1080.mp4|mp4_720.mp4|mp4_480.mp4|mp4_360.mp4|mp4.mp4)))",
    @"style='(?<style>.+width: (?<width>.+)px.+height: (?<height>.+)px.+)'",
}
.Select(r => new Regex(r))
.ToList();
var results = inputs.Select(i => spanRegex.Match(i).Value)
    .Select(i => new
    {
        i,
        attributes =
            from r in attrRegexes
            let match = r.Match(i)
            from g in match.Groups.Cast<Group>().Skip(1)
            select new {g.Name, capture = g.Value}
    });
</code>```

Linqpad example

Body:
I'd personally just split up the regex into more manageable chunks, like so:

var spanRegex = new Regex(@"<span class='vidly-vid'.+<\/span>");
var attrRegexes = new[]{
    @"data-thumb='(?<thumb>http.+\.jpg)'",
    @"aspect-ratio='(?<aspect>\d{1,3}:\d{1,3})'",
    @"sources='\[{""file"":.+""(?<src>(?<uri>https:\/\/cf1234.cloudfront\.net\/Vids\/)(?<key>(?<ident>[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}|[a-z0-9]{6})\/(?<mp4>mp4_1080.mp4|mp4_720.mp4|mp4_480.mp4|mp4_360.mp4|mp4.mp4)))",
    @"style='(?<style>.+width: (?<width>.+)px.+height: (?<height>.+)px.+)'",
}
.Select(r => new Regex(r))
.ToList();
var results = inputs.Select(i => spanRegex.Match(i).Value)
    .Select(i => new
    {
        i,
        attributes =
            from r in attrRegexes
            let match = r.Match(i)
            from g in match.Groups.Cast<Group>().Skip(1)
            select new {g.Name, capture = g.Value}
    });

Linqpad example


问:
How do I manually cancel / dispose of an RXJava2 Flowable?
I have an Android project that is using the FileStack dependency that is relying on RX Java 2. Specifically, io.reactivex.rxjava2:rxjava:2.1.2. This has not really been a problem up until now as I have been unable to figure out how to specifically cancel a Flowable.

I have implemented the

Here is my code below:

```<code>private Flowable<Progress<FileLink>> upload;

private void myMethod(){
    upload = new Client(myConfigOptionsHere)
      .uploadAsync(filePath, false, storageOptions);

        upload.doOnNext(progress -> {
                    double progressPercent = progress.getPercent();
                    if(progressPercent > 0){
                        //Updating progress here
                    }
                    if (progress.getData() != null) {
                        //Sending successful upload callback here
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //Logging he complete action here
                    }
                })
                .doOnCancel(new Action() {
                    @Override
                    public void run() throws Exception {
                        //Logging the cancel here
                    }
                })
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable t) throws Exception {
                        //Logging the error here
                    }
                })
                .subscribe();

}

public void cancelUpload(){
    //What do I do here to manually stop the upload Flowable?
    //IE upload.cancel();
}
</code>```

What do I need to do / call against the upload Flowable so that I can manually trigger a cancel when the user cancels the upload via a button click? I see people recommending calling dispose, but I don't see that option when checking the available methods to use against the Flowable.

答:
Turns out the issue was that I was attempting to dispose of / cancel the wrong object. I adjusted my code to the following:

```<code>private Disposable disposable;

private void myMethod(){
    Flowable<Progress<FileLink>> upload = new Client(myConfigOptionsHere)
      .uploadAsync(filePath, false, storageOptions);

        this.disposable = upload.doOnNext(progress -> {
                    double progressPercent = progress.getPercent();
                    if(progressPercent > 0){
                        //Updating progress here
                    }
                    if (progress.getData() != null) {
                        //Sending successful upload callback here
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //Logging he complete action here
                    }
                })
                .doOnCancel(new Action() {
                    @Override
                    public void run() throws Exception {
                        //Logging the cancel here
                    }
                })
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable t) throws Exception {
                        //Logging the error here
                    }
                })
                .subscribe();

}

public void cancelUpload(){
    if(this.disposable != null){
        this.disposable.dispose();
        this.disposable = null;
    }
}
</code>```

and was able to get it working just fine. Essentially you need to call the dispose() method against the dispose object, not the Flowable.

Thanks for the assistance / message jschuss

Body:
I have an Android project that is using the FileStack dependency that is relying on RX Java 2. Specifically, io.reactivex.rxjava2:rxjava:2.1.2. This has not really been a problem up until now as I have been unable to figure out how to specifically cancel a Flowable.

I have implemented the

Here is my code below:

private Flowable<Progress<FileLink>> upload;

private void myMethod(){
    upload = new Client(myConfigOptionsHere)
      .uploadAsync(filePath, false, storageOptions);

        upload.doOnNext(progress -> {
                    double progressPercent = progress.getPercent();
                    if(progressPercent > 0){
                        //Updating progress here
                    }
                    if (progress.getData() != null) {
                        //Sending successful upload callback here
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //Logging he complete action here
                    }
                })
                .doOnCancel(new Action() {
                    @Override
                    public void run() throws Exception {
                        //Logging the cancel here
                    }
                })
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable t) throws Exception {
                        //Logging the error here
                    }
                })
                .subscribe();

}

public void cancelUpload(){
    //What do I do here to manually stop the upload Flowable?
    //IE upload.cancel();
}

What do I need to do / call against the upload Flowable so that I can manually trigger a cancel when the user cancels the upload via a button click? I see people recommending calling dispose, but I don't see that option when checking the available methods to use against the Flowable.

Body:
Turns out the issue was that I was attempting to dispose of / cancel the wrong object. I adjusted my code to the following:

private Disposable disposable;

private void myMethod(){
    Flowable<Progress<FileLink>> upload = new Client(myConfigOptionsHere)
      .uploadAsync(filePath, false, storageOptions);

        this.disposable = upload.doOnNext(progress -> {
                    double progressPercent = progress.getPercent();
                    if(progressPercent > 0){
                        //Updating progress here
                    }
                    if (progress.getData() != null) {
                        //Sending successful upload callback here
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //Logging he complete action here
                    }
                })
                .doOnCancel(new Action() {
                    @Override
                    public void run() throws Exception {
                        //Logging the cancel here
                    }
                })
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable t) throws Exception {
                        //Logging the error here
                    }
                })
                .subscribe();

}

public void cancelUpload(){
    if(this.disposable != null){
        this.disposable.dispose();
        this.disposable = null;
    }
}

and was able to get it working just fine. Essentially you need to call the dispose() method against the dispose object, not the Flowable.

Thanks for the assistance / message jschuss


问:
Warning: Found conflicts between different versions of the same dependent assembly
I am currently developing a .NET application, which consists of 20 projects. Some of those projects are compiled using .NET 3.5, some others are still .NET 2.0 projects (so far no problem).

The problem is that if I include an external component I always get the following warning:

Found conflicts between different versions of the same dependent assembly.

What exactly does this warning mean and is there maybe a possibility to exclude this warning (like using #pragma disable in the source code files)?

答:
If using NuGet all I had to do was:

right click project and click Manage NuGet Packages..

click the cog in top right

click General tab in NuGet Package Manager above Package Sources

check "Skip Applying binding redirects" in Binding Redirects

Clean and rebuild and the warning's gone

Easy peasy


答:
To override the string representation of the number, make a wrapper class:

```<code>class FloatWrapper:
    def __init__(self, float, unit):
        self.float = float
        self.unit = unit

    def __getattr__(self, key):
        try:
            return object.__getattr__(self, key)
        except AttributeError:
            return getattr(self.float, key)

    def __str__(self):
        return str(self.float) + self.unit
</code>```

Now in your __init__, after defining self.mass, add:

```<code>self.mass = FloatWrapper(self.mass, 'kg')
</code>```

Body:
I'm trying to get a class to spit out a number with units. The purpose of it having units would be to be able to work with the number later, but without the units getting in the way as a string. Though I have no idea how to do this. I'm quite new with (actually understanding) classes, I'm not even sure if what I ask is possible or not.

My goal is to make a class for making atoms, based on their protons, electrons and neutons. The thing I wanna try is to be able to see the units of the mass (in kgs for my purpose) when I try printing it. Here's what I have:

    class Atom:
        def __init__(self, protons, electrons, neutrons):
            ElemCharge = 1.6021765*(10**-19)
            UMAS = 1.66054*(10**-27)
            self.protons = protons
            self.electrons = electrons
            self.neutrons = neutrons
            self.charge = ElemCharge*(self.protons - self.electrons)
            self.mass = (self.protons + self.neutrons)*UMAS

    def main():

        Hydrogen = Atom(1,1,0)
        print (Hydrogen.mass)

        Argon = Atom(18,18,22)
        print (Argon.mass)

    if __name__ == "__main__":
        main()

This code works completely fine, so no worries about that :p

Is there a way to even do this? If so, how can it be done? Thanks!

Body:
To override the string representation of the number, make a wrapper class:

class FloatWrapper:
    def __init__(self, float, unit):
        self.float = float
        self.unit = unit

    def __getattr__(self, key):
        try:
            return object.__getattr__(self, key)
        except AttributeError:
            return getattr(self.float, key)

    def __str__(self):
        return str(self.float) + self.unit

Now in your __init__, after defining self.mass, add:

self.mass = FloatWrapper(self.mass, 'kg')


问:
Salesforce : How to prevent 'upsert' (executed from an apex Job) of a record, if the record has a checkbox field which is marked false?
Salesforce question :

We have to update the accounts from a schedulable Job. New records inserting are no problem, but existing records should only be updated if a particular checkbox field is set to true on that (otherwise not to be updated). Also since we know that the apex code runs from a system context.

I am looking for a way which DOES NOT involve pulling the record from the code by searching using the Id and then checking that field value before upserting.

Thank you for helping.

Code

```<code>List<Account> accountList = new List<Account>(accountsToUpdate);
upsert accountList MY_COMPOSITE_KEY__c;
</code>```

答:
Make a validation rule simply has Your_Checkbox__c as error condition. Or make a before insert, before update trigger on Account (if you don't have one already) that would inspect all records in trigger.new and call addError() on them. Validation rule is slightly preferred because it's just config, no code.

The problem with either is that it will cause your whole transaction to die. If your batch updates 200 accounts and one of them has this checkbox - this fail will block updating them all. This is done to ensure system's state is stable (read up about "atomic operations" or "ACID"), you wouldn't want data that's halfway updated...

So probably you'll have to mitigate that by calling Database.upsert(accountsToUpdate, External_ID__c, false); so it saves what it can and doesn't throw exceptions...

Body:
Salesforce question :

We have to update the accounts from a schedulable Job. New records inserting are no problem, but existing records should only be updated if a particular checkbox field is set to true on that (otherwise not to be updated). Also since we know that the apex code runs from a system context.

I am looking for a way which DOES NOT involve pulling the record from the code by searching using the Id and then checking that field value before upserting.

Thank you for helping.

Code

List<Account> accountList = new List<Account>(accountsToUpdate);
upsert accountList MY_COMPOSITE_KEY__c;


答:
There are ways of doing it, but firstly you should ask yourself whether you want this. Having different units can get confusing. You can put conversions at the appropriate places (e.g. after reading the input from user) and have your system work solely on a given unit (that's why we have SI units, after all). Being able to support multiple units internally not only complicates the code, but introduces another source of possible confusion.

There are packages which do this for you, such as units, numericalunits or pint.

An example taken from units documentation is:

```<code>>>> from units import unit
>>> metre = unit('m')
>>> second = unit('s')
>>> print(metre(10) / second(2))
5.00 m / s
>>> print(metre(10) ** 3)
1000.00 m * m * m
</code>```

See how metre creates a meter value, and it keeps track of its usage. It has also support for defining custom units.

Therefore, you could simply store the values in your class as values from units or other package, and you're all set. I looked a bit into the code of units and is quite short and I think it's a good source of learning how to handle stuff like this in your own code.

I have to cite the failure of Nasa Mars Climate Orbiter, which was due to a unit discrepancy.

Body:
There are ways of doing it, but firstly you should ask yourself whether you want this. Having different units can get confusing. You can put conversions at the appropriate places (e.g. after reading the input from user) and have your system work solely on a given unit (that's why we have SI units, after all). Being able to support multiple units internally not only complicates the code, but introduces another source of possible confusion.

There are packages which do this for you, such as units, numericalunits or pint.

An example taken from units documentation is:

>>> from units import unit
>>> metre = unit('m')
>>> second = unit('s')
>>> print(metre(10) / second(2))
5.00 m / s
>>> print(metre(10) ** 3)
1000.00 m * m * m

See how metre creates a meter value, and it keeps track of its usage. It has also support for defining custom units.

Therefore, you could simply store the values in your class as values from units or other package, and you're all set. I looked a bit into the code of units and is quite short and I think it's a good source of learning how to handle stuff like this in your own code.

I have to cite the failure of Nasa Mars Climate Orbiter, which was due to a unit discrepancy.


问:
How to determine if a nested list structure is the same as another, but with elements exchanged for new ones
Let's say we have two nested lists: L1 = [[0, 1], [0, 2]] and L2 = [[1, 2], [1, 3]]

The question is, does there exist a bijection between the integers in one list and the integers in the other list which transforms L1 into L2?  For L1 and L2 given above, the answer is yes.

BIJECTION:

old 0 becomes new 1

old 1 becomes new 2

old 2becomes new 3

Recall our nested list L1 = [[0, 1], [0, 2]]. If we apply the mapping described above, then we get L2 = [[1, 2], [1, 3]] Therefore, foo(L1, L2) should return True. foo is the name of the equality operator we are trying to implement.

Also, order does not matter. Each list should be treated as a mathematical "set."

Some examples are shown below:

Left list: [[2, 1], [3, 1]]

Right list: [[1, 2], [1, 3]] : True
foo(left,right) returns True

why?

order doesn't matter

Left list: [[2, 1], [3, 1]]

Right list: [[1, 2], [3, 4]]

foo(left,right) returns False

why?

Two integers inside of the left list are the same, but all integers inside of the right list are different from each-other.

left= [[2, 1], [3, 1]]

right = [[0, 1], [0, 1]]

foo(left, right) returns False

why?

the right list contains only 2 distinct integers (0 and 1). The left list contains 3 distinct integers (1, 2, 3)

Some longer examples are shown below:

Original list: [[0, 1], [0, 2], [1, 2], [1, 3], [0, 1, 2]]

A1: [[4, 1], [4, 0], [1, 0], [1, 3], [4, 1, 0]] : True

A2: [[4, 1], [4, 0], [1, 3], [1, 0], [4, 0, 1]] : True

B: [[1, 2], [3, 1], [2, 4], [1, 4], [2, 4, 1]] : True

C: [[3, 2], [5, 2], [5, 0], [0, 2], [5, 0, 2]] : True

D: [[5, 2], [5, 2], [3, 0], [0, 2], [5, 0, 2]] : False

E: [[3, 0], [0, 3], [5, 0], [0, 2], [5, 0, 2]] : False

Bijection for Example A1:

```<code>ORIGINAL  A
 0        4
 1        1
 2        0
 3        3
</code>```

A2 is simply a reordering of A1

In example B, 2 and 4 are playing the same role as 0 and 2 in the original list. 1 is in the same role in both lists, as is 3.

In example C, 0 and 5 are playing the same role as 0 and 2 in the original list, 2 is playing the same role as 1 in the original list, and 3 is playing the same role in both lists.
In example D, there are two sub-lists which are the same ([5, 2]), while the original list has no repeating sub-lists.
In example E, 0 is in all four length-2 sub-lists, while in the original list, no number is in all four length-2 sub-lists.

Here is the code I have from my attempt, however it does not work when a low number (like 0) is exchanged for one of the largest numbers in the lists (like say 4). When it does the sorting, it fails to recognize that the 4 is playing the same role as the 0. Since low numbers can be exchanged for high numbers, sorting will not work.

def CheckUnique(configs, newconfig):
    sortednewconfig = sorted([sorted(i) for i in newconfig])
    presentnumbers = []
    canonicalnewconfig = []
    for sub in sortednewconfig:
        for i in sub:
            if i not in presentnumbers:
                presentnumbers.append(i)
    for sub in sortednewconfig:
        cansub = []
        for i in sub:
            cansub.append(presentnumbers.index(i))
        canonicalnewconfig.append(cansub)
    if canonicalnewconfig not in configs:
        return True
    else:
        return False

```

答:
You are trying to solve a modified form of what is known as the "graph isomorphism problem." There are existing algorithms which will determine if two graphs are isomorphic, but existing algorithms are all very slow, particularly for large graphs.

"Graphs" are diagrams with dots and lines.

Suppose we have two nested lists:

```<code>L1 = [[0, 1], [0, 2], [1, 2], [1, 3], [0, 1, 2]]
L2 = [[4, 1], [4, 0], [1, 3], [1, 0], [4, 0, 1]]
</code>```

Draw a picture L1 by from the following instructions:

For each element of a sublist, draw a dot. For example consider the sublist
[0, 1]. It will get two dots, one dot for 0 and one dot for 1.

Draw a circle around a cluster of dots if they are in the same
sub-list.

Draw a line between two dots if the two dots represent the same integer.

After that, condense each group of dots (sublist) into a single dot.

You can draw a similar diagram for nested list L2 The question is, after you remove the all of the numbers, do the two diagrams for L1 and L2 look the same? You might have to swap the colors around (blue edges become red, red become, blue, etc...) Also the dots might have to be moved around until it looks the same.

The traditional graph isomorphism problem has the lines connecting dots all of the same color. Your problem is slightly different from traditional in that your edges are colored.

I think that you can get rid of the separate colors and simply number each edge with the number of colors that used to be there. It then becomes an "edge-weighted graph"

Do a google search for "graph isomorphism for edge-weighted graphs."

What you are working on is extremely difficult. I recommend looking at local university math department websites for people you can contact. Looking for email address of professors whose job title is "graph theorist." Contact them, and ask for their advice.

Like I said, what you are working on is extremely difficult.

I think that you can solve it as follows:

Build the edge-weighted graph for the left list

Build the edge-weighted graph for the right list

Determine if the two graphs are isomorphic or not.

Body:
Let's say we have two nested lists: L1 = [[0, 1], [0, 2]] and L2 = [[1, 2], [1, 3]]

The question is, does there exist a bijection between the integers in one list and the integers in the other list which transforms L1 into L2?  For L1 and L2 given above, the answer is yes.

BIJECTION:

old 0 becomes new 1

old 1 becomes new 2

old 2becomes new 3

Recall our nested list L1 = [[0, 1], [0, 2]]. If we apply the mapping described above, then we get L2 = [[1, 2], [1, 3]] Therefore, foo(L1, L2) should return True. foo is the name of the equality operator we are trying to implement.

Also, order does not matter. Each list should be treated as a mathematical "set."

Some examples are shown below:

Left list: [[2, 1], [3, 1]]

Right list: [[1, 2], [1, 3]] : True
foo(left,right) returns True

why?

order doesn't matter

Left list: [[2, 1], [3, 1]]

Right list: [[1, 2], [3, 4]]

foo(left,right) returns False

why?

Two integers inside of the left list are the same, but all integers inside of the right list are different from each-other.

left= [[2, 1], [3, 1]]

right = [[0, 1], [0, 1]]

foo(left, right) returns False

why?

the right list contains only 2 distinct integers (0 and 1). The left list contains 3 distinct integers (1, 2, 3)

Some longer examples are shown below:

Original list: [[0, 1], [0, 2], [1, 2], [1, 3], [0, 1, 2]]

A1: [[4, 1], [4, 0], [1, 0], [1, 3], [4, 1, 0]] : True

A2: [[4, 1], [4, 0], [1, 3], [1, 0], [4, 0, 1]] : True

B: [[1, 2], [3, 1], [2, 4], [1, 4], [2, 4, 1]] : True

C: [[3, 2], [5, 2], [5, 0], [0, 2], [5, 0, 2]] : True

D: [[5, 2], [5, 2], [3, 0], [0, 2], [5, 0, 2]] : False

E: [[3, 0], [0, 3], [5, 0], [0, 2], [5, 0, 2]] : False

Bijection for Example A1:

ORIGINAL  A
 0        4
 1        1
 2        0
 3        3

A2 is simply a reordering of A1

In example B, 2 and 4 are playing the same role as 0 and 2 in the original list. 1 is in the same role in both lists, as is 3.

In example C, 0 and 5 are playing the same role as 0 and 2 in the original list, 2 is playing the same role as 1 in the original list, and 3 is playing the same role in both lists.
In example D, there are two sub-lists which are the same ([5, 2]), while the original list has no repeating sub-lists.
In example E, 0 is in all four length-2 sub-lists, while in the original list, no number is in all four length-2 sub-lists.

Here is the code I have from my attempt, however it does not work when a low number (like 0) is exchanged for one of the largest numbers in the lists (like say 4). When it does the sorting, it fails to recognize that the 4 is playing the same role as the 0. Since low numbers can be exchanged for high numbers, sorting will not work.

def CheckUnique(configs, newconfig):
    sortednewconfig = sorted([sorted(i) for i in newconfig])
    presentnumbers = []
    canonicalnewconfig = []
    for sub in sortednewconfig:
        for i in sub:
            if i not in presentnumbers:
                presentnumbers.append(i)
    for sub in sortednewconfig:
        cansub = []
        for i in sub:
            cansub.append(presentnumbers.index(i))
        canonicalnewconfig.append(cansub)
    if canonicalnewconfig not in configs:
        return True
    else:
        return False

Body:
You are trying to solve a modified form of what is known as the "graph isomorphism problem." There are existing algorithms which will determine if two graphs are isomorphic, but existing algorithms are all very slow, particularly for large graphs.

"Graphs" are diagrams with dots and lines.

Suppose we have two nested lists:

L1 = [[0, 1], [0, 2], [1, 2], [1, 3], [0, 1, 2]]
L2 = [[4, 1], [4, 0], [1, 3], [1, 0], [4, 0, 1]]

Draw a picture L1 by from the following instructions:

For each element of a sublist, draw a dot. For example consider the sublist
[0, 1]. It will get two dots, one dot for 0 and one dot for 1.

Draw a circle around a cluster of dots if they are in the same
sub-list.

Draw a line between two dots if the two dots represent the same integer.

After that, condense each group of dots (sublist) into a single dot.

You can draw a similar diagram for nested list L2 The question is, after you remove the all of the numbers, do the two diagrams for L1 and L2 look the same? You might have to swap the colors around (blue edges become red, red become, blue, etc...) Also the dots might have to be moved around until it looks the same.

The traditional graph isomorphism problem has the lines connecting dots all of the same color. Your problem is slightly different from traditional in that your edges are colored.

I think that you can get rid of the separate colors and simply number each edge with the number of colors that used to be there. It then becomes an "edge-weighted graph"

Do a google search for "graph isomorphism for edge-weighted graphs."

What you are working on is extremely difficult. I recommend looking at local university math department websites for people you can contact. Looking for email address of professors whose job title is "graph theorist." Contact them, and ask for their advice.

Like I said, what you are working on is extremely difficult.

I think that you can solve it as follows:

Build the edge-weighted graph for the left list

Build the edge-weighted graph for the right list

Determine if the two graphs are isomorphic or not.


问:
Istio Gateway and VirtualService issue with Kubernetes Dashboard
I'm using Istio 1.1.7 and tried the following Gateway and VirtualService to the Kubernetes Dashboard.

But I'm seeing the following:

```<code>kubectl -n kube-system logs -f kubernetes-dashboard-7cf9657c74-5fsmq
2019/05/31 15:53:04 http: TLS handshake error from 10.244.3.11:54392: tls: first record does not look like a TLS handshake
</code>```

```<code>apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: default-ingressgateway
  namespace: default
spec:
  selector:
    istio: ingressgateway
  servers:

  - hosts:
    - "*"
    port:
      name: http
      number: 80
      protocol: HTTP

  - hosts:
    - "*"
    port:
      name: https
      number: 443
      protocol: HTTPS
    tls:
      mode: SIMPLE
      privateKey: /etc/istio/ingressgateway-certs/tls.key
      serverCertificate: /etc/istio/ingressgateway-certs/tls.crt
</code>```

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: dashboard-virtualservice
  namespace: kube-system
spec:
  hosts:
  - "*"
  gateways:
  - default/default-ingressgateway
  http:
  - match:
    - uri:
        prefix: "/dashboard"
    rewrite:
      uri: "/"
    route:
    - destination:
        host: kubernetes-dashboard
        port:
          number: 443
</code>```

NOTE: I've also tried change the Gateway Server-TLSOptions-TLSmode from mode: SIMPLE to mode mode: PASSTHROUGH, but PASSTHROUGH I just get We can’t connect to the server in my Browser.

答: I think PASSTHROUGH should work, if you configure it properly. Here is an example that does something similar. https://istio.io/docs/examples/advanced-gateways/ingress-sni-passthrough/

Body:
I'm using Istio 1.1.7 and tried the following Gateway and VirtualService to the Kubernetes Dashboard.

But I'm seeing the following:

kubectl -n kube-system logs -f kubernetes-dashboard-7cf9657c74-5fsmq
2019/05/31 15:53:04 http: TLS handshake error from 10.244.3.11:54392: tls: first record does not look like a TLS handshake

apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: default-ingressgateway
  namespace: default
spec:
  selector:
    istio: ingressgateway
  servers:

  - hosts:
    - "*"
    port:
      name: http
      number: 80
      protocol: HTTP

  - hosts:
    - "*"
    port:
      name: https
      number: 443
      protocol: HTTPS
    tls:
      mode: SIMPLE
      privateKey: /etc/istio/ingressgateway-certs/tls.key
      serverCertificate: /etc/istio/ingressgateway-certs/tls.crt

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: dashboard-virtualservice
  namespace: kube-system
spec:
  hosts:
  - "*"
  gateways:
  - default/default-ingressgateway
  http:
  - match:
    - uri:
        prefix: "/dashboard"
    rewrite:
      uri: "/"
    route:
    - destination:
        host: kubernetes-dashboard
        port:
          number: 443

NOTE: I've also tried change the Gateway Server-TLSOptions-TLSmode from mode: SIMPLE to mode mode: PASSTHROUGH, but PASSTHROUGH I just get We can’t connect to the server in my Browser.


问:
Why is webpage scrolling when modal popup is closed?
When closing certain modal popups, page jumps to top.

Note:
I've built this page with Wordpress, using a combination of custom HTML and the Beaver Builder website builder. Wordpress theme is Astra.

Link to page with issue:
http://retirementinsuranceoptions.com/consuelo-avila

Once you get to web page, click on the "Book" option to navigate to the section that I'm having issues with. You'll notice that when you click on "Book an Appointment" or "Schedule a Chat", then close these popups, the page will jump to the top of the screen.

But, if you click on "Ask Consuelo a Question", then close the popup, the page doesn't scroll (which is what I'm interested in achieving for all other modal popups).

All buttons you see are styled anchor tags with href="#0".

I do notice a pattern...
The popup for the "Ask A Question" button contains a Form (from a Wordpress Plugin, Ninja Forms) which is a local asset on my site's server.
The popup content for "Book an Appointment" and "Schedule a Chat" are s and

Expected/Desired Result:
No "scroll to top" when modal popup is closed out.

Actual Result:
Some popups cause the page to scroll to top, some don't.

(I've been learning to code for the past year or so now. I love it, but I still have lots to learn! Thanks in advance S.O.!!)

答: This is a pretty redundant feature! It's not worth your trouble</p>


问:
Cannot use class constructor using equals sign notation when class copy constructor is deleted
While testing some classes I run into an interesting problem: When invoking class constructor using the equals sign notation (=) if the copy constructor is deleted an error is encountered error: copying variable of type 'Class' invokes deleted constructor. While using the parenthesis the code compiles normally.

What is going on here? Can this be a compiler bug?

Consider the following class:

```<code>class Test
{
    public:
        int Int;

    public:
        Test() = default;
        Test(Test &) = delete;
        Test(Test &&) = delete;
        Test(int i)
        {
            Int = i;
        }
};
</code>```

Constructors invoked like so:

```<code>Test t1(3);  //No error
Test t2 = 3; //error: copying variable of type 'Class' invokes deleted constructor
</code>```

Just to check I tried to add some checks and allow these functions and compile the code.
Both constructors compiled using MSVC in the exact same way.

```<code>class Test
{
    public:
        int Int;

    public:
        Test()
        {
            Int = 0;
            cout << "Constructor";
        }
        Test(Test &t)
        {
            Int = t.Int;
            cout << "Copy Constructor";
        }
        Test(Test &&t)
        {
            Int = t.Int;
            cout << "Move Constructor";
        }
        Test(int i)
        {
            Int = i;
            cout << "Constructor from int";
        }
};
</code>```

```<code>Test t1(3);  //Constructor from int
Test t2 = 3; //Constructor from int
</code>```

What exactly is going on here?

答:
You're seeing the results of the copy elision rule.

Basically, saying T var = expr; constructs an unnamed temp from expr and then copies or moves it into var using the copy or move construtor.  If the copy and move constructors are deleted, then this gives an error about the deleted constructor.  But then, the compiler is required to elide that copy or move and construct var directly from expr, even if the copy or move constructor has visible side effects.  Its one of those weird corner cases that arises from language design by de-facto standardization of what disparate implementations do (or did at some time in the past), plus design-by-committee and slow evolution over time while trying to keep backwards compatibility.

see here for more discussion

Body:
While testing some classes I run into an interesting problem: When invoking class constructor using the equals sign notation (=) if the copy constructor is deleted an error is encountered error: copying variable of type 'Class' invokes deleted constructor. While using the parenthesis the code compiles normally.

What is going on here? Can this be a compiler bug?

Consider the following class:

class Test
{
    public:
        int Int;

    public:
        Test() = default;
        Test(Test &) = delete;
        Test(Test &&) = delete;
        Test(int i)
        {
            Int = i;
        }
};

Constructors invoked like so:

Test t1(3);  //No error
Test t2 = 3; //error: copying variable of type 'Class' invokes deleted constructor

Just to check I tried to add some checks and allow these functions and compile the code.
Both constructors compiled using MSVC in the exact same way.

class Test
{
    public:
        int Int;

    public:
        Test()
        {
            Int = 0;
            cout << "Constructor";
        }
        Test(Test &t)
        {
            Int = t.Int;
            cout << "Copy Constructor";
        }
        Test(Test &&t)
        {
            Int = t.Int;
            cout << "Move Constructor";
        }
        Test(int i)
        {
            Int = i;
            cout << "Constructor from int";
        }
};

Test t1(3);  //Constructor from int
Test t2 = 3; //Constructor from int

What exactly is going on here?


问:
Import python functions into a .NET language?
I am a C# .NET programmer and am learning Python.  I have downloaded IronPython, and know that it can call into .NET libraries.

I'm wondering whether there is a way to do the reverse, that is to call into some existing "classic" Python libraries in my C# code, maybe using .NET Interop.

I'd like to be able to access functions in libraries such as pygame.

答:
You can use Python for .Net, which allows you to 'use CLR services and continue to use existing Python code and C-based extensions while maintaining native execution speeds for Python code.'

Further, 'A key goal for this project has been that Python for .NET should "work just the way you'd expect in Python", except for cases that are .NET specific (in which case the goal is to work "just the way you'd expect in C#"). In addition, with the IronPython project gaining traction, it is my goal that code written for IronPython run without modification under Python for .NET.'

Hope this helps

OwnerDisplayName: Buggieboy

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Buggieboy

OwnerDisplayName: jle


问:
Ktor: Serialize/Deserialize JSON with List as root in Multiplatform
How can we use kotlin.serialize with Ktor's HttpClient to deserialize/serialize JSON with lists as root?  I am creating the HttpClient as follows:

```<code>HttpClient {
       install(JsonFeature) {
           serializer = KotlinxSerializer().apply {
               setMapper(MyClass::class, MyClass.serializer())
               setMapper(AnotherClass::class, AnotherClass.serializer())
           }
       }
       install(ExpectSuccess)
   }
</code>```

Appears I need to setMapper for List, however that is not possible with generics.  I see I can get the serializer for it with MyClass.serializer().list, but registering it to deserialize/serialize on http requests is not straight forward.  Anyone know of a good solution?

答:
I happened to have the same problem on Kotlin/JS, and managed to fix it this way:

```<code>private val client = HttpClient(Js) {
  install(JsonFeature) {
    serializer = KotlinxSerializer().apply {
      register(User.serializer().list)
    }
  }
}
...
private suspend fun fetchUsers(): Sequence<User> =
    client.get<List<User>> {
      url("$baseUrl/users")
    }.asSequence()
</code>```

Hope this helps :)

Body:
How can we use kotlin.serialize with Ktor's HttpClient to deserialize/serialize JSON with lists as root?  I am creating the HttpClient as follows:

HttpClient {
       install(JsonFeature) {
           serializer = KotlinxSerializer().apply {
               setMapper(MyClass::class, MyClass.serializer())
               setMapper(AnotherClass::class, AnotherClass.serializer())
           }
       }
       install(ExpectSuccess)
   }

Appears I need to setMapper for List, however that is not possible with generics.  I see I can get the serializer for it with MyClass.serializer().list, but registering it to deserialize/serialize on http requests is not straight forward.  Anyone know of a good solution?

Body:
I happened to have the same problem on Kotlin/JS, and managed to fix it this way:

private val client = HttpClient(Js) {
  install(JsonFeature) {
    serializer = KotlinxSerializer().apply {
      register(User.serializer().list)
    }
  }
}
...
private suspend fun fetchUsers(): Sequence<User> =
    client.get<List<User>> {
      url("$baseUrl/users")
    }.asSequence()

Hope this helps :)