问:
How do I tell programatically if I am running under Medium Trust?
In C# how do I tell if my assembly is running under medium trust in asp.net?  Is there something similar to Debugger.IsAttached for this?</p>

答:
From dmitryr's blog post:</p>

```<code>public static AspNetHostingPermissionLevel GetTrustLevel()
{
    foreach (AspNetHostingPermissionLevel trustLevel in new AspNetHostingPermissionLevel[]
                                                            {
                                                                AspNetHostingPermissionLevel.Unrestricted,
                                                                AspNetHostingPermissionLevel.High,
                                                                AspNetHostingPermissionLevel.Medium,
                                                                AspNetHostingPermissionLevel.Low,
                                                                AspNetHostingPermissionLevel.Minimal
                                                            })
    {
        try
        {
            new AspNetHostingPermission(trustLevel).Demand();
        }
        catch (System.Security.SecurityException)
        {
            continue;
        }

        return trustLevel;
    }

    return AspNetHostingPermissionLevel.None;
}
</code>```

Body:
From dmitryr's blog post:

public static AspNetHostingPermissionLevel GetTrustLevel()
{
    foreach (AspNetHostingPermissionLevel trustLevel in new AspNetHostingPermissionLevel[]
                                                            {
                                                                AspNetHostingPermissionLevel.Unrestricted,
                                                                AspNetHostingPermissionLevel.High,
                                                                AspNetHostingPermissionLevel.Medium,
                                                                AspNetHostingPermissionLevel.Low,
                                                                AspNetHostingPermissionLevel.Minimal
                                                            })
    {
        try
        {
            new AspNetHostingPermission(trustLevel).Demand();
        }
        catch (System.Security.SecurityException)
        {
            continue;
        }

        return trustLevel;
    }

    return AspNetHostingPermissionLevel.None;
}


来源: stackexchange

问:
AWS restrict access to port
Some advice please. We have an instance on AWS. It hosts a web app on a single server.  We would like to restrict access to the app (ports 80/443).  We can't simply restrict connections through the firewall to a range of white listed IP Addresses because we don't know where our users will be coming from or if they will have static addresses. They are not very tech aware and would most likely not connect if it is complicated.

Is Amazon virtual private cloud a solution or would another solution get us to where we want to be. We are a non profit org and will not be charging people so we would like to accomplish this within our budget.

Ideally we would provide individual logins/passwords that we can share with people that would grant them access to the url. We are not sure how this can be accomplished but we think that restricting access on a server must be possible and need some guidance on the approach. It is new to us.

Thanks for reading.

Howard

答: You can restrict access to the box over 80/443 using security groups. Then, restrict access to the application with user ids and passwords. </p>

ContentLicense: CC BY-SA 3.0

Title: AWS restrict access to port


问:
How to make my app a system app?
I can copy my apk from SD card to system/app using shell command:

```<code> Process process = Runtime.getRuntime().exec("su");
DataOutputStream out = new DataOutputStream(process.getOutputStream());
out.writeBytes("mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system\n");
out.writeBytes("cat /sdcard/myApp.apk > /system/app/myApp.apk\n");
out.writeBytes("mount -o remount,ro -t yaffs2 /dev/block/mtdblock3 /system\n");
out.writeBytes("exit\n");
out.flush();
process.waitFor();
</code>```

the problem is, my device ignores it because it has no attributes set.

when I change it to -rw-r--r-- using a root browser, it works!! how do I do this using code ? :)

答:
Just so you know, you won't be able to do that on a non-rooted device. To change the file perms,

```<code>out.writeBytes("chmod 644 /system/app/myApp.apk\n");
</code>```

Also,

```<code>out.writeBytes("cat /sdcard/myApp.apk > /system/app/myApp.apk\n");
</code>```

should be:

```<code>out.writeBytes("cp /sdcard/myApp.apk /system/app/myApp.apk\n");
</code>```

Title: How to make my app a system app?

Body:
I can copy my apk from SD card to system/app using shell command:

 Process process = Runtime.getRuntime().exec("su");
DataOutputStream out = new DataOutputStream(process.getOutputStream());
out.writeBytes("mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system\n");
out.writeBytes("cat /sdcard/myApp.apk > /system/app/myApp.apk\n");
out.writeBytes("mount -o remount,ro -t yaffs2 /dev/block/mtdblock3 /system\n");
out.writeBytes("exit\n");
out.flush();
process.waitFor();

the problem is, my device ignores it because it has no attributes set.

when I change it to -rw-r--r-- using a root browser, it works!! how do I do this using code ? :)

Body:
Just so you know, you won't be able to do that on a non-rooted device. To change the file perms,

out.writeBytes("chmod 644 /system/app/myApp.apk\n");

Also,

out.writeBytes("cat /sdcard/myApp.apk > /system/app/myApp.apk\n");

should be:

out.writeBytes("cp /sdcard/myApp.apk /system/app/myApp.apk\n");


问:
checking invariants in C++
Are there any established patterns for checking class invariants in C++?

Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special before and after member functions, but unfortunately, design by contract wasn't quite popular at the time and nobody except Bjarne used that feature, so he removed it.

Of course, manually inserting check_invariants() calls at the beginning and at the end of each public member function is tedious and error-prone. Since RAII is the weapon of choice to deal with exceptions, I came up with the following scheme of defining an invariance checker as the first local variable, and that invariance checker checks the invariants both at construction and destruction time:

```<code>template <typename T>
class invariants_checker
{
    const T* p;

public:

    invariants_checker(const T* p) : p(p)
    {
        p->check_invariants();
    }

    ~invariants_checker()
    {
        p->check_invariants();
    }
};

void Foo::bar()
{
    // class invariants checked by construction of _
    invariants_checker<Foo> _(this);

    // ... mutate the object

    // class invariants checked by destruction of _
}
</code>```

Question #0: I suppose there is no way to declare an unnamed local variable? :)

We would still have to call check_invariants() manually at the end of the Foo constructor and at the beginning of the Foo destructor. However, many constructor bodies and destructor bodies are empty. In that case, could we use an invariants_checker as the last member?

```<code>#include <string>
#include <stdexcept>

class Foo
{
    std::string str;
    std::string::size_type cached_length;
    invariants_checker<Foo> _;

public:

    Foo(const std::string& str)
    : str(str), cached_length(str.length()), _(this) {}

    void check_invariants() const
    {
        if (str.length() != cached_length)
            throw std::logic_error("wrong cached length");
    }

    // ...
};
</code>```

Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?

Question #2: Do you see any other problems with this approach? Can you improve it?

Question #3: Is this approach new or well-known? Are there better solutions available?

答: unit testing is better alternative that leads to smaller code with better performance</p>

ContentLicense: CC BY-SA 2.5

Title: checking invariants in C++

Body:
Are there any established patterns for checking class invariants in C++?

Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special before and after member functions, but unfortunately, design by contract wasn't quite popular at the time and nobody except Bjarne used that feature, so he removed it.

Of course, manually inserting check_invariants() calls at the beginning and at the end of each public member function is tedious and error-prone. Since RAII is the weapon of choice to deal with exceptions, I came up with the following scheme of defining an invariance checker as the first local variable, and that invariance checker checks the invariants both at construction and destruction time:

template <typename T>
class invariants_checker
{
    const T* p;

public:

    invariants_checker(const T* p) : p(p)
    {
        p->check_invariants();
    }

    ~invariants_checker()
    {
        p->check_invariants();
    }
};

void Foo::bar()
{
    // class invariants checked by construction of _
    invariants_checker<Foo> _(this);

    // ... mutate the object

    // class invariants checked by destruction of _
}

Question #0: I suppose there is no way to declare an unnamed local variable? :)

We would still have to call check_invariants() manually at the end of the Foo constructor and at the beginning of the Foo destructor. However, many constructor bodies and destructor bodies are empty. In that case, could we use an invariants_checker as the last member?

#include <string>
#include <stdexcept>

class Foo
{
    std::string str;
    std::string::size_type cached_length;
    invariants_checker<Foo> _;

public:

    Foo(const std::string& str)
    : str(str), cached_length(str.length()), _(this) {}

    void check_invariants() const
    {
        if (str.length() != cached_length)
            throw std::logic_error("wrong cached length");
    }

    // ...
};

Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?

Question #2: Do you see any other problems with this approach? Can you improve it?

Question #3: Is this approach new or well-known? Are there better solutions available?


问:
setState not updating when set to boolean
I have the following method in a react component:

```<code>handleCheckBoxClick() {
  var checkbox = document.getElementById("boldCheckbox").checked;
  this.setState({ischecked : checkbox});
  if(this.state.ischecked) {
    this.setState({weight:'bold'});
  } else {
    this.setState({weight:'normal'});
  }
}
</code>```

but if I change the if statement to:

```<code>if(checkbox) {
  this.setState({weight:'bold'});
} else {
  this.setState({weight:'normal'});
}
</code>```

it works fine but I can't figure out why the first way doesn't work.

答: Thats cause this.setState({ isChecked : checkbox }); has not finished before you ask it in the if statement.

Body:
I have the following method in a react component:

handleCheckBoxClick() {
  var checkbox = document.getElementById("boldCheckbox").checked;
  this.setState({ischecked : checkbox});
  if(this.state.ischecked) {
    this.setState({weight:'bold'});
  } else {
    this.setState({weight:'normal'});
  }
}

but if I change the if statement to:

if(checkbox) {
  this.setState({weight:'bold'});
} else {
  this.setState({weight:'normal'});
}

it works fine but I can't figure out why the first way doesn't work.


问:
WebApi HttpClient not sending client certificate
I am trying to secure my RESTful WebApi service with ssl and client authentication using client certificates.

To test; I have generated a self signed certificate and placed in the local machine, trusted root certification authorities folder and i have generated a "server" and "client" certificates.
Standard https to the server works without issue.

However I have some code in the server to validate the certificate, this never gets called when I connect using my test client which supplies my client certificate and the test client is returned a 403 Forbidden status.

This imples the server is failing my certificate before it reaches my validation code.
However if i fire up fiddler it knows a client certificate is required and asks me to supply one to My Documents\Fiddler2. I gave it the same client certificate i use in my test client and my server now works and received the client certificate i expect!
This implies that the WebApi client is not properly sending the certificate, my client code below is pretty much the same as other examples i have found.

```<code>    static async Task RunAsync()
    {
        try
        {
            var handler = new WebRequestHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.ClientCertificates.Add(GetClientCert());
            handler.ServerCertificateValidationCallback += Validate;
            handler.UseProxy = false;

            using (var client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri("https://hostname:10001/");

                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

                var response = await client.GetAsync("api/system/");
                var str = await response.Content.ReadAsStringAsync();

                Console.WriteLine(str);
            }
        } catch(Exception ex)
        {
            Console.Write(ex.Message);
        }
    }
</code>```

Any ideas why it would work in fiddler but not my test client?

Edit: Here is the code to GetClientCert()

```<code>private static X509Certificate GetClientCert()
    {
        X509Store store = null;
        try
        {
            store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);

            var certs = store.Certificates.Find(X509FindType.FindBySubjectName, "Integration Client Certificate", true);

            if (certs.Count == 1)
            {
                var cert = certs[0];
                return cert;
            }
        }
        finally
        {
            if (store != null)
                store.Close();
        }

        return null;
    }
</code>```

Granted the test code does not handle a null certificate but i am debugging to enssure that the correct certificate is located.

答:
In the code you are using store = new X509Store(StoreName.My, StoreLocation.LocalMachine);.

Client certificates are not picked up from LocalMachine, you should instead use StoreLocation.CurrentUser.

Checking MMC -> File -> Add or Remove Snap-ins -> Certificates -> My user account you will see the certificate that fiddler uses. If you remove it from My user account and only have it imported in Computer account you will see that Fiddler can not pick it up either.

A side note is when finding certificates you also have to address for culture.

Example:

```<code>var certificateSerialNumber= "83 c6 62 0a 73 c7 b1 aa 41 06 a3 ce 62 83 ae 25".ToUpper().Replace(" ", string.Empty);

//0 certs
var certs = store.Certificates.Find(X509FindType.FindBySerialNumber, certificateSerialNumber, true);

//null
var cert = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x => x.GetSerialNumberString() == certificateSerialNumber);

//1 cert
var cert1 = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x =>
                x.GetSerialNumberString().Equals(certificateSerialNumber, StringComparison.InvariantCultureIgnoreCase));
</code>```

Body:
I am trying to secure my RESTful WebApi service with ssl and client authentication using client certificates.

To test; I have generated a self signed certificate and placed in the local machine, trusted root certification authorities folder and i have generated a "server" and "client" certificates.
Standard https to the server works without issue.

However I have some code in the server to validate the certificate, this never gets called when I connect using my test client which supplies my client certificate and the test client is returned a 403 Forbidden status.

This imples the server is failing my certificate before it reaches my validation code.
However if i fire up fiddler it knows a client certificate is required and asks me to supply one to My Documents\Fiddler2. I gave it the same client certificate i use in my test client and my server now works and received the client certificate i expect!
This implies that the WebApi client is not properly sending the certificate, my client code below is pretty much the same as other examples i have found.

    static async Task RunAsync()
    {
        try
        {
            var handler = new WebRequestHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.ClientCertificates.Add(GetClientCert());
            handler.ServerCertificateValidationCallback += Validate;
            handler.UseProxy = false;

            using (var client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri("https://hostname:10001/");

                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

                var response = await client.GetAsync("api/system/");
                var str = await response.Content.ReadAsStringAsync();

                Console.WriteLine(str);
            }
        } catch(Exception ex)
        {
            Console.Write(ex.Message);
        }
    }

Any ideas why it would work in fiddler but not my test client?

Edit: Here is the code to GetClientCert()

private static X509Certificate GetClientCert()
    {
        X509Store store = null;
        try
        {
            store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);

            var certs = store.Certificates.Find(X509FindType.FindBySubjectName, "Integration Client Certificate", true);

            if (certs.Count == 1)
            {
                var cert = certs[0];
                return cert;
            }
        }
        finally
        {
            if (store != null)
                store.Close();
        }

        return null;
    }

Granted the test code does not handle a null certificate but i am debugging to enssure that the correct certificate is located.

Body:
In the code you are using store = new X509Store(StoreName.My, StoreLocation.LocalMachine);.

Client certificates are not picked up from LocalMachine, you should instead use StoreLocation.CurrentUser.

Checking MMC -> File -> Add or Remove Snap-ins -> Certificates -> My user account you will see the certificate that fiddler uses. If you remove it from My user account and only have it imported in Computer account you will see that Fiddler can not pick it up either.

A side note is when finding certificates you also have to address for culture.

Example:

var certificateSerialNumber= "83 c6 62 0a 73 c7 b1 aa 41 06 a3 ce 62 83 ae 25".ToUpper().Replace(" ", string.Empty);

//0 certs
var certs = store.Certificates.Find(X509FindType.FindBySerialNumber, certificateSerialNumber, true);

//null
var cert = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x => x.GetSerialNumberString() == certificateSerialNumber);

//1 cert
var cert1 = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x =>
                x.GetSerialNumberString().Equals(certificateSerialNumber, StringComparison.InvariantCultureIgnoreCase));


问:
How to create a React Native component library?
How do I create a React Native component library?

I want to import it using:

```<code>npm install
</code>```

答:
You can either publish it on NPM, or just use a github dependency. This applies to any library, and is not react specific.

https://docs.npmjs.com/getting-started/publishing-npm-packages

https://docs.npmjs.com/files/package.json#git-urls-as-dependencies

Body:
How do I create a React Native component library?

I want to import it using:

npm install


问:
how to interpolate the section-name with configparser
I'm using configparser to read configuration for a backup-system.
one of the options (the output path) often includes the section-name itself.

```<code>[DEFAULT]
compression=gzip

[foo]
output=/Backups/foo/
[pizza]
output=/BigDisk/Backups/
[bar]
output=/Backups/bar/
</code>```

Now I would like to get rid manually appending the section name, and instead would like to use string interpolation. Something like the following:

```<code>[DEFAULT]
compression=gzip
output=/Backups/%(SECTION)s/

[foo]
[pizza]
output=/BigDisk/Backups/
[bar]
</code>```

Unfortunately i haven't found the variable-name that would expand to the section name yet (it's obviously not SECTION).

Is it possible at all (ideally without having to build my own ConfigParser sub-class)?

An ugly workaround would be to add an option append_section_name (and set it to yes in the DEFAULT section and to no in the pizza section) and manually do the interpolation. I'd rather not...

答:
The idea of user @andy20170414 is good but has an unexpected behavior of breaking the escape procedure.

He replaces the original string using that Template() and that will escape the all th $. When the Interpolation receives the text to interpolate, it will receive only one $ (already escaped) and will give you error during parsing.

I think that the correct way to accomplish what op wants is as the @andy20170414 answer with this modification:

```<code>    class MyExtendedInterpolation(ExtendedInterpolation):
    def before_get(self, parser, section, option, value, defaults):
        defaults.maps.append({'section': section})
        return super().before_get(parser, section, option, value, defaults)
</code>```

Keep in mind that the keys are compared in a .tolower() manner, as such keep that section key in lower case.

Body:
I'm using configparser to read configuration for a backup-system.
one of the options (the output path) often includes the section-name itself.

[DEFAULT]
compression=gzip

[foo]
output=/Backups/foo/
[pizza]
output=/BigDisk/Backups/
[bar]
output=/Backups/bar/

Now I would like to get rid manually appending the section name, and instead would like to use string interpolation. Something like the following:

[DEFAULT]
compression=gzip
output=/Backups/%(SECTION)s/

[foo]
[pizza]
output=/BigDisk/Backups/
[bar]

Unfortunately i haven't found the variable-name that would expand to the section name yet (it's obviously not SECTION).

Is it possible at all (ideally without having to build my own ConfigParser sub-class)?

An ugly workaround would be to add an option append_section_name (and set it to yes in the DEFAULT section and to no in the pizza section) and manually do the interpolation. I'd rather not...

Body:
The idea of user @andy20170414 is good but has an unexpected behavior of breaking the escape procedure.

He replaces the original string using that Template() and that will escape the all th $. When the Interpolation receives the text to interpolate, it will receive only one $ (already escaped) and will give you error during parsing.

I think that the correct way to accomplish what op wants is as the @andy20170414 answer with this modification:

    class MyExtendedInterpolation(ExtendedInterpolation):
    def before_get(self, parser, section, option, value, defaults):
        defaults.maps.append({'section': section})
        return super().before_get(parser, section, option, value, defaults)

Keep in mind that the keys are compared in a .tolower() manner, as such keep that section key in lower case.


问:
Why isn't my background image showing up in CSS?
this is my first posting here and I am new to CSS. I am trying to get a sprite of Mario with dimensions of 32 x 16. When I open the html file nothing appears. I try to inspect element the html but I cannot see a div.

CSS

#stillMario {
    width: 16px;
    height: 32px;
    margin: auto;
    background-image: url("sprites/still.png");
    position:absolute;
    left: 0px;
    top: 0px;
    bottom:0px;
}```
</div>
</div>
</p>

<p>HTML</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
        <title>Super Mario</title>
        <link href="style.css" rel="stylesheet" type="text/css"/>
    </head>

    <body>
        <div id="stillMario"></div>

        <script src="myjs.js"></script>
    </body>
</html></code>```

答:
Use  element instead of setting the background of the
.

Example:

Body:
this is my first posting here and I am new to CSS. I am trying to get a sprite of Mario with dimensions of 32 x 16. When I open the html file nothing appears. I try to inspect element the html but I cannot see a div.

CSS

#stillMario {
    width: 16px;
    height: 32px;
    margin: auto;
    background-image: url("sprites/still.png");
    position:absolute;
    left: 0px;
    top: 0px;
    bottom:0px;
}

HTML

<!DOCTYPE html>

        <title>Super Mario</title>
        <link href="style.css" rel="stylesheet" type="text/css"/>

Body:
Use <img> element instead of setting the background of the <div>.

Example: <img src=""sprites/still.png"" alt="Mario" height="32" width="16">


问:
Ajax random changes URL query parameter
I am using AJAX only to prevent redirect to a shopping cart.

As the result I have an item with random quantity in the cart.

Link itself pasted to an address bar works perfect, and gives specified quantity.
But when I do it with AJAX it gives wrong quantity.

What is wrong in this code, or how could I specify quantity in other way?

```<code>    <script type="text/javascript">
        $(document).on('click', '#url_cart', function(event) {
           event.preventDefault(); //prevent redirect
          $.ajax($(this).attr('href')).done(function(response) {
               });
         });
        </script>
        <!-- link for the item -->
<a
    id="url_cart"
    href="http://localhost:4000/cart.php?action=add&product_id={{id}}&variation_id=currency_id=&qty[]=1">
    {{lang 'products.add_to_cart'}}
</a>
</code>```

答:
This is Bigcommerce Stencil. In my case main page render 1 card.html for each item. So 12 times repeating. My AJAX is in this card.html.
@Taplar said right, I am

binding multiple times on an element

So I gave unique ID for each link (in this case {{id}} == item ID):

```<code>    <script type="text/javascript">
    $(document).on('click', '#{{id}}', function(event) {
       event.preventDefault();
      $.ajax($(this).attr('href')).done(function(response) {
           });
     });
    </script>

     <a id="{{id}}"
href="http://localhost:4000/cart.php?action=add&product_id={{id}}&variation_id=currency_id=&qty[]=1">
   {{lang 'products.add_to_cart'}}
      </a>
</code>```

Now it works perfect!
Thanks Taplar!

Title: Ajax random changes URL query parameter

Body:
I am using AJAX only to prevent redirect to a shopping cart.

As the result I have an item with random quantity in the cart.

Link itself pasted to an address bar works perfect, and gives specified quantity.
But when I do it with AJAX it gives wrong quantity.

What is wrong in this code, or how could I specify quantity in other way?

    {{lang 'products.add_to_cart'}}

Body:
This is Bigcommerce Stencil. In my case main page render 1 card.html for each item. So 12 times repeating. My AJAX is in this card.html.
@Taplar said right, I am

binding multiple times on an element

So I gave unique ID for each link (in this case {{id}} == item ID):

    <script type="text/javascript">
    $(document).on('click', '#{{id}}', function(event) {
       event.preventDefault();
      $.ajax($(this).attr('href')).done(function(response) {
           });
     });
    </script>

     <a id="{{id}}"
href="http://localhost:4000/cart.php?action=add&product_id={{id}}&variation_id=currency_id=&qty[]=1">
   {{lang 'products.add_to_cart'}}
      </a>

Now it works perfect!
Thanks Taplar!


问:
3D Max - Plane question
I've only a basic knowledge of 3D Max. I'm creating a plane using MaxScript, converting it to an editable Poly and then extruding certain faces. The thing is, I only have 16 faces to work from. Is there a way to have more than 16 faces?</p>

答: And in case you have similar questions in the future, just turn on the MAXScript macro recorder and perform the edit in the 3ds Max UI. Most of the times, the recorder will show you the MAXScript code for your action.</p>

Title: 3D Max - Plane question


问:
Same representation for GET and PUT?
As other people (for example: here) I'm struggling with the question, if the representation for GET and PUT should be the same?

Example:

GET representation:

```<code>{
    "id": "0815",
    "name": "jdoe",
    "emailAddress": "jd@example.com",
    "displayName": "John Doe",
    "active": true
}
</code>```

PUT representation:

```<code>{
    "emailAddress": "jd@example.com",
    "displayName": "John Doe"
}
</code>```

Research:

I read in REST question: PUT one representation, GET a different one? that it is ok, to get another media type with GET as I saved with PUT.

I read in REST - put IDs in body or not? that it is ok, to omit the id with PUT and get the id with GET.

I read in GET Representation != POST Representation that it is ok, to omit a lot of properties with PUT and get them with GET. An example is JIRA REST API - api/2/myself. GET returns the hole user model and PUT saves only 3 properties.

Is that good practice? I could also use PATCH, for example GitHub REST API - users. What's the reason to add PATCH to HTTP, if PUT with another smaller representation is already enough?

Further more I read in Best practice for partial updates in a RESTful service that most big REST APIs (for example: Google) use PATCH or POST for partial updates and PUT only for complete/full updates (for example: Goolge - Updating an entity).

答:
I struggled with this exact same question. Thanks for your research into it and for articulating it well. I think the issue here is that there is data that has to be determined/created by the server/backend that REST hasn't really addressed a best practice for. For example:

GUID's

Unique/Sequential Ids

Timestamps

In every trivial REST example you see it appears to be pretty symmetrical between what you GET vs what you POST/PUT. For example, REST would lead you to believe that if you do a GET on a collection (or resource) and then POST (or PUT) that response body back that there should be no change, but that's just not realistic considering the aforementioned examples. So in essence your GET response becomes a superset of the actual POST/PUT body.

The terminology I've used for this as a head nod to the relational asymmetry between the two has been to say that my GET returns a Readonly representation of the collection/resource, versus that the POST/PUT body accepts. That lends itself nicely to code where you can inherit a Readonly representation from the object to augment it with the properties that your server/backend is responsible for creating/managing. For example, here's two TypeScript interfaces showing what data a user could PUT (IPet) versus what data the server would respond with for a GET (IReadonlyPet)

```<code>interface IPet {
    name: string, // The user can change the pet's name
}
interface IReadonlyPet extends IPet {
    id: number,  // The user should not be able to change the pet's id
}
</code>```

I don't know if I'd force a user to strip off things like id when making a POST/PUT subsequent to a GET request as that's a lot of data transformation work to ask of your API consumers. I can see two valid and opposing arguments:

It's borderline bad practice to allow them to create/update with data where you're only accepting some of the properties but silently ignoring others (i.e. they can PUT with a different id than they received and you're just silently ignoring it could potentially give them a false sense of the actual state of the collection/resource)

The adage "be liberal about what you accept and strict about what you generate" would dictate that properties that are superfluous to the schema that your API defines can safely be ignored without generating any errors for the client. So someone could do a GET, then modify the id, then do a POST/PUT and you would simply ignore the id property.

If I had to choose one, I'd probably go with the second option because I think it makes for a simpler, more symmetrical experience for your API consumers in that they can do a full circle GET, POST/PUT the GET response, and GET again to receive the same original response. Additionally, your API consumers can't really complain about implementation behavior for data that goes beyond the defined schema since you're already off the beaten path of standardization.

Title: Same representation for GET and PUT?

Body:
As other people (for example: here) I'm struggling with the question, if the representation for GET and PUT should be the same?

Example:

GET representation:

{
    "id": "0815",
    "name": "jdoe",
    "emailAddress": "jd@example.com",
    "displayName": "John Doe",
    "active": true
}

PUT representation:

{
    "emailAddress": "jd@example.com",
    "displayName": "John Doe"
}

Research:

I read in REST question: PUT one representation, GET a different one? that it is ok, to get another media type with GET as I saved with PUT.

I read in REST - put IDs in body or not? that it is ok, to omit the id with PUT and get the id with GET.

I read in GET Representation != POST Representation that it is ok, to omit a lot of properties with PUT and get them with GET. An example is JIRA REST API - api/2/myself. GET returns the hole user model and PUT saves only 3 properties.

Is that good practice? I could also use PATCH, for example GitHub REST API - users. What's the reason to add PATCH to HTTP, if PUT with another smaller representation is already enough?

Further more I read in Best practice for partial updates in a RESTful service that most big REST APIs (for example: Google) use PATCH or POST for partial updates and PUT only for complete/full updates (for example: Goolge - Updating an entity).

Body:
I struggled with this exact same question. Thanks for your research into it and for articulating it well. I think the issue here is that there is data that has to be determined/created by the server/backend that REST hasn't really addressed a best practice for. For example:

GUID's

Unique/Sequential Ids

Timestamps

In every trivial REST example you see it appears to be pretty symmetrical between what you GET vs what you POST/PUT. For example, REST would lead you to believe that if you do a GET on a collection (or resource) and then POST (or PUT) that response body back that there should be no change, but that's just not realistic considering the aforementioned examples. So in essence your GET response becomes a superset of the actual POST/PUT body.

The terminology I've used for this as a head nod to the relational asymmetry between the two has been to say that my GET returns a Readonly representation of the collection/resource, versus that the POST/PUT body accepts. That lends itself nicely to code where you can inherit a Readonly representation from the object to augment it with the properties that your server/backend is responsible for creating/managing. For example, here's two TypeScript interfaces showing what data a user could PUT (IPet) versus what data the server would respond with for a GET (IReadonlyPet)

interface IPet {
    name: string, // The user can change the pet's name
}
interface IReadonlyPet extends IPet {
    id: number,  // The user should not be able to change the pet's id
}

I don't know if I'd force a user to strip off things like id when making a POST/PUT subsequent to a GET request as that's a lot of data transformation work to ask of your API consumers. I can see two valid and opposing arguments:

It's borderline bad practice to allow them to create/update with data where you're only accepting some of the properties but silently ignoring others (i.e. they can PUT with a different id than they received and you're just silently ignoring it could potentially give them a false sense of the actual state of the collection/resource)

The adage "be liberal about what you accept and strict about what you generate" would dictate that properties that are superfluous to the schema that your API defines can safely be ignored without generating any errors for the client. So someone could do a GET, then modify the id, then do a POST/PUT and you would simply ignore the id property.

If I had to choose one, I'd probably go with the second option because I think it makes for a simpler, more symmetrical experience for your API consumers in that they can do a full circle GET, POST/PUT the GET response, and GET again to receive the same original response. Additionally, your API consumers can't really complain about implementation behavior for data that goes beyond the defined schema since you're already off the beaten path of standardization.


问:
set difference for pandas
A simple pandas question:

Is there a drop_duplicates() functionality to drop every row involved in the duplication?

An equivalent question is the following: Does pandas have a set difference for dataframes?

For example:

```<code>In [5]: df1 = pd.DataFrame({'col1':[1,2,3], 'col2':[2,3,4]})

In [6]: df2 = pd.DataFrame({'col1':[4,2,5], 'col2':[6,3,5]})

In [7]: df1
Out[7]:
   col1  col2
0     1     2
1     2     3
2     3     4

In [8]: df2
Out[8]:
   col1  col2
0     4     6
1     2     3
2     5     5
</code>```

so maybe something like df2.set_diff(df1) will produce this:

```<code>   col1  col2
0     4     6
2     5     5
</code>```

However, I don't want to rely on indexes because in my case, I have to deal with dataframes that have distinct indexes.

By the way, I initially thought about an extension of the current drop_duplicates() method, but now I realize that the second approach using properties of set theory would be far more useful in general. Both approaches solve my current problem, though.

Thanks!

答:
Assumption:

df1 and df2 have identical columns

it is a set operation so duplicates are ignored

sets are not extremely large so you do not worry about memory

```<code>union = pd.concat([df1,df2])
sym_diff = union[~union.duplicated(keep=False)]
union_of_df1_and_sym_diff = pd.concat([df1, sym_diff])
diff = union_of_df1_and_sym_diff[union_of_df1_and_sym_diff.duplicated()]
</code>```

Title: set difference for pandas

Body:
A simple pandas question:

Is there a drop_duplicates() functionality to drop every row involved in the duplication?

An equivalent question is the following: Does pandas have a set difference for dataframes?

For example:

In [5]: df1 = pd.DataFrame({'col1':[1,2,3], 'col2':[2,3,4]})

In [6]: df2 = pd.DataFrame({'col1':[4,2,5], 'col2':[6,3,5]})

In [7]: df1
Out[7]:
   col1  col2
0     1     2
1     2     3
2     3     4

In [8]: df2
Out[8]:
   col1  col2
0     4     6
1     2     3
2     5     5

so maybe something like df2.set_diff(df1) will produce this:

   col1  col2
0     4     6
2     5     5

However, I don't want to rely on indexes because in my case, I have to deal with dataframes that have distinct indexes.

By the way, I initially thought about an extension of the current drop_duplicates() method, but now I realize that the second approach using properties of set theory would be far more useful in general. Both approaches solve my current problem, though.

Thanks!

Body:
Assumption:

df1 and df2 have identical columns

it is a set operation so duplicates are ignored

sets are not extremely large so you do not worry about memory

union = pd.concat([df1,df2])
sym_diff = union[~union.duplicated(keep=False)]
union_of_df1_and_sym_diff = pd.concat([df1, sym_diff])
diff = union_of_df1_and_sym_diff[union_of_df1_and_sym_diff.duplicated()]


问:
Why does a const update a property via the spread operator?
During a code review, it was pointed out that I could use spread operator and a constant to update an object:

const props = {
  hairColor: 'brown',
};

const hairColor = 'red';
const newProps = { ...props, hairColor};

console.log(newProps); // -> hairColor now equals 'red'```
</div>
</div>
</p>

<p>The question is, how does this work? </p>

<p>I understand how actually passing an object works:</p>

```const newProps = { ...props, { hairColor: 'red' }};
```

<p>But how does it know to update <code>hairColor</code> with the value 'red'? A quick test shows it is using the variable name, but how?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const props = {
  hairColor: 'brown',
};

const colorOfHair = 'red';
const newProps = { ...props, colorOfHair};

// -> hairColor still equals 'brown'
// with new property 'colorOfHair'
console.log(newProps);</code>```

答:
This is ES6 shorthand property names. When you write name in an object, it's a shortcut for name: name. So

```<code>const newProps = { ...props, hairColor};
</code>```

is short for

```<code>const newProps = { ...props, hairColor: hairColor};
</code>```

This is unrelated to the spread operator, the same thing happens if you write:

```<code>const newProps = { prop1: 1, prop2: 2, hairColor };
</code>```

Body:
During a code review, it was pointed out that I could use spread operator and a constant to update an object:

const props = {
  hairColor: 'brown',
};

const hairColor = 'red';
const newProps = { ...props, hairColor};

console.log(newProps); // -> hairColor now equals 'red'

The question is, how does this work?

I understand how actually passing an object works:

const newProps = { ...props, { hairColor: 'red' }};

But how does it know to update hairColor with the value 'red'? A quick test shows it is using the variable name, but how?

const props = {
  hairColor: 'brown',
};

const colorOfHair = 'red';
const newProps = { ...props, colorOfHair};

// -> hairColor still equals 'brown'
// with new property 'colorOfHair'
console.log(newProps);

Body:
This is ES6 shorthand property names. When you write name in an object, it's a shortcut for name: name. So

const newProps = { ...props, hairColor};

is short for

const newProps = { ...props, hairColor: hairColor};

This is unrelated to the spread operator, the same thing happens if you write:

const newProps = { prop1: 1, prop2: 2, hairColor };


问:
How to write both h1 and h2 in the same line?
I have a page and I want simply to make a header. This header is an
 text aligned to the left, and an
 aligned to the right, in the same line, and after them, an
. My code so far look as follows (if you test it, you'll see that it's wrong):

```<code><h1 align="left">Title</h1>
<h2 align="right">Context</h2>
<hr/>
</code>```

Thanks guys!

答:
h1 and h2 are native display: block elements.

Make them display: inline so they behave like normal text.

You should also reset the default padding and margin that the elements have.

ContentLicense: CC BY-SA 4.0

Body:
I have a page and I want simply to make a header. This header is an
 text aligned to the left, and an
 aligned to the right, in the same line, and after them, an
. My code so far look as follows (if you test it, you'll see that it's wrong):

Title

Context

Thanks guys!


问:
factory pattern in autofac
I want to implement factory pattern in Autofac. This is how it was done in Ninject:

```<code>Bind<ICarFilter>().To<CarFilter >();
Bind<IBikeFilter>().To<BikeFilter>();
Bind<IFilterFacade>().ToFactory().InSingletonScope();
</code>```

This is a definitnion of IFilterFacade

```<code>public interface IFilterFacade
    {
        ICarFilter CreateCarFilter();

        IBikeFIlter CreateBikeFilter();
    }
</code>```

If I want an instance of CarFilter type, all I need to do is the following:

```<code>public class HomeController(IFilterFacade filterFacade)
{
    FilterFacade = filterFacade;
}

public IFilterFacade FilterFacade { get;set; }

public ActionResult Index()
{
  var bikeFilter = FilterFacade.CreateBikeFilter();
}
</code>```

Any example how to do that in AutoFac. I checked AutoFac documentation, but was not able to find the answer or example.

答:
There is no equivalent of ToFactory in Autofac but you can easily implement a generic factory equivalent.

```<code>public interface IFilterFactory
{
    TFilter Get() where TFilter : IFilter;
}

public class FilterFactory : IFilterFactory
{

    public FilterFactory(ILifetimeScope scope)
    {
        this._scope = scope;
    }

    private readonly ILifetimeScope _scope;

    public TFilter Get<TFilter>()
    {
        return this._scope.Resolve<TFilter>();
    }
}
</code>```

Then register it like this :

```<code>builder.RegisterType<FilterFactory>().As<IFilterFactory>();
builder.RegisterType<BikeFilter>().As<IBikeFilter>();
builder.RegisterType<CarFilter>().As<ICarFilter>();
</code>```

and use it this way

```<code>public class HomeController
{
    private readonly IFilterFactory _filters;

    public HomeController(IFilterFactory filters)
    {
        this._filters = filters;
    }

    public ActionResult Index()
    {
        var bikeFilter = this._filters.Get<IBikeFilter>();
        // ...
    }
}
</code>```

I rename the Create method to Get because the method will look up an instance in the lifetime scope and create one only if needed.

Another possible solution may be to use Named and Keyed Service and the built-in IIndex type.

```<code>builder.RegisterType<BikeFilter>().Named<IFilter>("Bike");
builder.RegisterType<CarFilter>().Named<IFilter>("Car");
</code>```

then on your controller

```<code>public class HomeController
{
    private readonly IIndex<String, IFilter> _filters;

    public HomeController(IIndex<String, IFilter> filters)
    {
        this._filters = filters;
    }

    public ActionResult Index()
    {
        var bikeFilter = this._filters["Bike"];
        // ...
    }
}
</code>```

Title: factory pattern in autofac

Body:
I want to implement factory pattern in Autofac. This is how it was done in Ninject:

Bind<ICarFilter>().To<CarFilter >();
Bind<IBikeFilter>().To<BikeFilter>();
Bind<IFilterFacade>().ToFactory().InSingletonScope();

This is a definitnion of IFilterFacade

public interface IFilterFacade
    {
        ICarFilter CreateCarFilter();

        IBikeFIlter CreateBikeFilter();
    }

If I want an instance of CarFilter type, all I need to do is the following:

public class HomeController(IFilterFacade filterFacade)
{
    FilterFacade = filterFacade;
}

public IFilterFacade FilterFacade { get;set; }

public ActionResult Index()
{
  var bikeFilter = FilterFacade.CreateBikeFilter();
}

Any example how to do that in AutoFac. I checked AutoFac documentation, but was not able to find the answer or example.

Body:
There is no equivalent of ToFactory in Autofac but you can easily implement a generic factory equivalent.

public interface IFilterFactory
{
    TFilter Get() where TFilter : IFilter;
}

public class FilterFactory : IFilterFactory
{

    public FilterFactory(ILifetimeScope scope)
    {
        this._scope = scope;
    }

    private readonly ILifetimeScope _scope;

    public TFilter Get<TFilter>()
    {
        return this._scope.Resolve<TFilter>();
    }
}

Then register it like this :

builder.RegisterType<FilterFactory>().As<IFilterFactory>();
builder.RegisterType<BikeFilter>().As<IBikeFilter>();
builder.RegisterType<CarFilter>().As<ICarFilter>();

and use it this way

public class HomeController
{
    private readonly IFilterFactory _filters;

    public HomeController(IFilterFactory filters)
    {
        this._filters = filters;
    }

    public ActionResult Index()
    {
        var bikeFilter = this._filters.Get<IBikeFilter>();
        // ...
    }
}

I rename the Create method to Get because the method will look up an instance in the lifetime scope and create one only if needed.

Another possible solution may be to use Named and Keyed Service and the built-in IIndex type.

builder.RegisterType<BikeFilter>().Named<IFilter>("Bike");
builder.RegisterType<CarFilter>().Named<IFilter>("Car");

then on your controller

public class HomeController
{
    private readonly IIndex<String, IFilter> _filters;

    public HomeController(IIndex<String, IFilter> filters)
    {
        this._filters = filters;
    }

    public ActionResult Index()
    {
        var bikeFilter = this._filters["Bike"];
        // ...
    }
}


问:
Finding a subset of numbers that will give you the max sum
How to find a subset of numbers from 2 to 1000 that will give you the max sum under the condition that any two numbers from the subset don't share common prime factors (e.g., 1000 and 500 share the prime factor 2)?

One (maybe easier) variation to the above question: what is the largest number in the subset? We know that 997 is a prime number, and it is easy to rule out 1000 and 998, thus the question becomes whether is 999 in the subset?

答:
I don't know the answer to this, it seems non-trivial to me. Here are a few thoughts.

The sum consists of a variable number of summands, say s0 + s1 + ... sk, where si is an integer in the interval [2, 1000]. Now each si has a prime-power factorization si=(p1e1)*(p2e2) ... where ei ≥ 1.

The condition that "that any two numbers from the subset don't share common prime factors" is equivalent to stating that si are pairwise relatively prime, i.e. gcd(si, sj)=1 for i ≠ j. Also equivalently, whenever one summand si contains a prime p that means that no other summand may contain that prime.

So how do you arrange the primes into summands? One simple rule is immediately obvious. All the primes in [500, 1000] can only appear in the sum alone as individual summands. If they are multiplied by anything else, even the smallest prime 2, the product will be too large. So that leaves the task of arranging the smaller primes. And I don't know they best way to do that. For the sake of completeness I'll provide the following short python program that shows one way.

def sieve_prime_set(n):
    # sieve[i] = set(p1, p2, ...pn) for each prime p_i that divides i.

    sieve = [set() for i in range(n + 1)]
    primes = []
    next_prime = 1
    while True:
        # find the next prime
        for i in range(next_prime + 1, len(sieve)):
            if not sieve[i]:
                next_prime = i
                break
        else:
            break

        primes.append(next_prime)
        # sieve out by this prime
        for kp in range(next_prime, n + 1, next_prime):
            sieve[kp].add(next_prime)

    return sieve, primes

def max_sum_strategy1(sieve):
    last = len(sieve) - 1
    summands = [last]
    max_sum = last
    prime_set = sieve[last]
    while last >= 2:
        last -= 1
        if not sieve[last] & prime_set:
            max_sum += last
            prime_set |= sieve[last]
            summands.append(last)

    return max_sum, summands, prime_set

def max_sum_strategy2(primes, n):
    return sum(p ** int(log(n, p)) for p in primes)

if __name__ == '__main__':
    sieve, primes = sieve_prime_set(1000)
    max_sum, _, _ = max_sum_strategy1(sieve)
    print(max_sum)
    print(max_sum_strategy2(primes, 1000))
```

<p>Output is</p>

<pre class="lang-none prettyprint-override"><code>84972
81447
</code>```

showing that "strategy 1" is superior.

Superior, but not necessarily optimal. For example, including 1000 seems good, but it forces us to exclude every other even summand and every summand divisible by 5. If we leave 1000 out but include 998 instead, we get to use another summand that includes 5 in it's prime factorization. But including 998 forces other summands to be excluded. So maximizing the sum is not trivial.

Body:
I don't know the answer to this, it seems non-trivial to me. Here are a few thoughts.

The sum consists of a variable number of summands, say s0 + s1 + ... sk, where si is an integer in the interval [2, 1000]. Now each si has a prime-power factorization si=(p1e1)*(p2e2) ... where ei ≥ 1.

The condition that "that any two numbers from the subset don't share common prime factors" is equivalent to stating that si are pairwise relatively prime, i.e. gcd(si, sj)=1 for i ≠ j. Also equivalently, whenever one summand si contains a prime p that means that no other summand may contain that prime.

So how do you arrange the primes into summands? One simple rule is immediately obvious. All the primes in [500, 1000] can only appear in the sum alone as individual summands. If they are multiplied by anything else, even the smallest prime 2, the product will be too large. So that leaves the task of arranging the smaller primes. And I don't know they best way to do that. For the sake of completeness I'll provide the following short python program that shows one way.

def sieve_prime_set(n):
    # sieve[i] = set(p1, p2, ...pn) for each prime p_i that divides i.

    sieve = [set() for i in range(n + 1)]
    primes = []
    next_prime = 1
    while True:
        # find the next prime
        for i in range(next_prime + 1, len(sieve)):
            if not sieve[i]:
                next_prime = i
                break
        else:
            break

        primes.append(next_prime)
        # sieve out by this prime
        for kp in range(next_prime, n + 1, next_prime):
            sieve[kp].add(next_prime)

    return sieve, primes

def max_sum_strategy1(sieve):
    last = len(sieve) - 1
    summands = [last]
    max_sum = last
    prime_set = sieve[last]
    while last >= 2:
        last -= 1
        if not sieve[last] & prime_set:
            max_sum += last
            prime_set |= sieve[last]
            summands.append(last)

    return max_sum, summands, prime_set

def max_sum_strategy2(primes, n):
    return sum(p ** int(log(n, p)) for p in primes)

if __name__ == '__main__':
    sieve, primes = sieve_prime_set(1000)
    max_sum, _, _ = max_sum_strategy1(sieve)
    print(max_sum)
    print(max_sum_strategy2(primes, 1000))

Output is

84972
81447

showing that "strategy 1" is superior.

Superior, but not necessarily optimal. For example, including 1000 seems good, but it forces us to exclude every other even summand and every summand divisible by 5. If we leave 1000 out but include 998 instead, we get to use another summand that includes 5 in it's prime factorization. But including 998 forces other summands to be excluded. So maximizing the sum is not trivial.


问:
C++ - Is there a way for a template class specialization to contain code from the general template?
Given a C++ class:

```<code>template<typename T>
class A {
public:
    int a;
    T x;
    int getA() {return a;}
};
</code>```

Is it possible for a template specialization to 'inherit' (without actual C++ inheritance) members like a and getA() from A? Furthermore, when writing code that does a lot of template specializations for classes, should I type the same code many times (which kinda defeats the whole purpose of templates), or restructure the class so that it accommodates for the specializations (e.g. by encapsulating another template class member inside so that specializations are limited to that class only)?

答:
Is it possible for a template specialization to 'inherit' (without actual C++ inheritance) members like a and getA() from A?

Short answer: no.

Long answer: no, A is a class template and thus it's not something from which you can inherit members (either data or functions).

Moreover, what you are asking for sounds like - how can I defeat the whole purpose of a specialization?. Well, go with inheritance from a base class for members that don't depend on template parameters. That's the more straightforward way to do that and what the language offers you.

You cannot just inherit a member function from a type without extending that type.

There a lot of techniques to achieve the purpose: direct inheritance, mixin, inherit-from-above idiom and so on.

All of them go through inheritance to compose interfaces. I don't see why one should demonize it.

Body:
Given a C++ class:

template<typename T>
class A {
public:
    int a;
    T x;
    int getA() {return a;}
};

Is it possible for a template specialization to 'inherit' (without actual C++ inheritance) members like a and getA() from A? Furthermore, when writing code that does a lot of template specializations for classes, should I type the same code many times (which kinda defeats the whole purpose of templates), or restructure the class so that it accommodates for the specializations (e.g. by encapsulating another template class member inside so that specializations are limited to that class only)?


问:
Append strings with File Pointer for Bison
I wrote a simple Interpreter using Flex and Bison in C. I am reading the file to be interpreted using the Line 'yyin = fopen( argv[0], "r" );'. Well. Now I getting some request from browser using CGI. This is my sample data Which i receive from Broswer.

abc="Hello"

cfg="Welcome"

count=10

Now I need to add these lines to my file which is to interpreted . How can I do this task ?
I tried to connect yyin with c++ file Streams. So that I can convert my data which received from browser to StringStream . And Append it with file streams. But yyin pointer only accepts I/O Pointers. Is there any other way to merge these data with my language codes ?

答:
Since you're using flex, you can use yy_scan_string to parse from a buffer instead of a file:

```<code>YY_BUFFER_STATE buffer = yy_scan_string(my_string_buffer);
yyparse();
yy_delete_buffer(buffer);
</code>```

Here my_string_buffer is just a pointer to memory containing the text to be parsed as a NUL terminated string.  yy_scan_string makes a copy of the string (so you can reuse the buffer for something else immediately), which will be freed when you call yy_delete_buffer

Body:
Since you're using flex, you can use yy_scan_string to parse from a buffer instead of a file:

YY_BUFFER_STATE buffer = yy_scan_string(my_string_buffer);
yyparse();
yy_delete_buffer(buffer);

Here my_string_buffer is just a pointer to memory containing the text to be parsed as a NUL terminated string.  yy_scan_string makes a copy of the string (so you can reuse the buffer for something else immediately), which will be freed when you call yy_delete_buffer


问:
bash exec sending output to a pipe, how?
I experiment with exec'ing the bash itself only to redirect the output. If I use redirection like

```<code>exec >bla.log
ls
exec 1>&2
</code>```

it works as expected: the ls output ends up in bla.log and after the second exec things are back to normal, mainly because handle 2 is still bound to the terminal.

Now I thought to send the output through a pipe instead of into a file, a trivial example being exec | cat >bla.log. However, the command immediately returns. To figure out what is going on, I did this:

```<code>exec | bash -c 'echo $$; ls -l /proc/$$/fd /proc/23084/fd'
</code>```

where 23084 is the bash currently running and got this:

```<code>24002
/proc/23084/fd:
total 0
lrwx------ 1 harald harald 64 Aug 14 20:17 0 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 20:17 1 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 20:17 2 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 20:17 255 -> /dev/pts/1

/proc/24002/fd:
total 0
lr-x------ 1 harald harald 64 Aug 14 21:56 0 -> pipe:[58814]
lrwx------ 1 harald harald 64 Aug 14 21:56 1 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 21:56 2 -> /dev/pts/1
</code>```

As we can see, the sub-process 24002 is indeed listening to a pipe. But it certainly is not the parent process, 23084, which has this pipe open.

Any ideas what is going on here?

答:
It took me a while to figure out how to get the combination of redirections right for stdout and stderr, so this might be useful to others.

The following examples illustrate using redirections with tee as a "pipe" target while distinguishing stdout and stderr.

```<code>#!/bin/bash

echo "stdout"
echo "stderr" >&2

echo "stdout to out.log" | tee out.log
echo "stderr to err.log" 2>&1 >&2 | tee err.log >&2

exec 2> >(tee -a err.log >&2)
exec > >(tee -a out.log)

echo "exec stdout to out.log"
echo "exec stderr to err.log" >&2
</code>```

Run this in the CLI with stdout redirected to /dev/null and you only see the stderr messages.  Plus within each log file you only see the relevant messages.

Note that the order of the exec 2> line and the exec > lines is important.  Essentially we first want to redirect stderr to an error file, then stdout to a log file.  If these lines appear in the opposite order the results would not be correct.

Body:
I experiment with exec'ing the bash itself only to redirect the output. If I use redirection like

exec >bla.log
ls
exec 1>&2

it works as expected: the ls output ends up in bla.log and after the second exec things are back to normal, mainly because handle 2 is still bound to the terminal.

Now I thought to send the output through a pipe instead of into a file, a trivial example being exec | cat >bla.log. However, the command immediately returns. To figure out what is going on, I did this:

exec | bash -c 'echo $$; ls -l /proc/$$/fd /proc/23084/fd'

where 23084 is the bash currently running and got this:

24002
/proc/23084/fd:
total 0
lrwx------ 1 harald harald 64 Aug 14 20:17 0 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 20:17 1 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 20:17 2 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 20:17 255 -> /dev/pts/1

/proc/24002/fd:
total 0
lr-x------ 1 harald harald 64 Aug 14 21:56 0 -> pipe:[58814]
lrwx------ 1 harald harald 64 Aug 14 21:56 1 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 21:56 2 -> /dev/pts/1

As we can see, the sub-process 24002 is indeed listening to a pipe. But it certainly is not the parent process, 23084, which has this pipe open.

Any ideas what is going on here?

Body:
It took me a while to figure out how to get the combination of redirections right for stdout and stderr, so this might be useful to others.

The following examples illustrate using redirections with tee as a "pipe" target while distinguishing stdout and stderr.

#!/bin/bash

echo "stdout"
echo "stderr" >&2

echo "stdout to out.log" | tee out.log
echo "stderr to err.log" 2>&1 >&2 | tee err.log >&2

exec 2> >(tee -a err.log >&2)
exec > >(tee -a out.log)

echo "exec stdout to out.log"
echo "exec stderr to err.log" >&2

Run this in the CLI with stdout redirected to /dev/null and you only see the stderr messages.  Plus within each log file you only see the relevant messages.

Note that the order of the exec 2> line and the exec > lines is important.  Essentially we first want to redirect stderr to an error file, then stdout to a log file.  If these lines appear in the opposite order the results would not be correct.


问:
nodejs https client certificate not sent error, but is sent
I have a nodejs client and server interacting via https. I have self signed certificate authority, server certificate and a couple of test client certificates. I have tested the certificates are 'working' using openssl s_server and s_client, using the necessary command line options for self signed certs and no errors are generated.

When the client connects to server via https, the server immediately generates an error stating it could not get peer certificate:

```<code>`Error: 140735833322304:error:140890C7:SSL routines:ssl3_get_client_certificate:peer did not return a certificate:../deps/openssl/openssl/ssl/s3_srvr.c:3330:`
</code>```

On the client the error is:

```<code>`{ Error: socket hang up
    at TLSSocket.onConnectEnd (_tls_wrap.js:1073:19)
    at Object.onceWrapper (events.js:322:30)
    at emitNone (events.js:120:20)
    at TLSSocket.emit (events.js:218:7)
    at endReadableNT (_stream_readable.js:1054:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  code: 'ECONNRESET',
  path: null,
  host: 'localhost',
  port: 443,
  localAddress: undefined }`

`140735833322304:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:1494:SSL alert number 40`

`140735833322304:error:140940E5:SSL routines:ssl3_read_bytes:ssl handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:1217:
`
</code>```

However the handler for the URL executes and calls req.socket.getPeerCertificate() and the client certificate has clearly been sent:

```<code>`{ subject:
   { C: 'US',
     ST: 'MA',
     L: 'Boston',
     O: 'Example Co',
     OU: 'techops',
     CN: 'client2',
     emailAddress: 'certs@example.com' },
  issuer:
   { C: 'US',
     ST: 'MA',
     L: 'Boston',
     O: 'Example Co',
     OU: 'techops',
     CN: 'ca',
     emailAddress: 'certs@example.com' },
  modulus: 'B97D65....etc....}`
</code>```

Why would I get these errors when the client has indeed sent the certificate?

Any help would be appreciated.

答:
Looks like I had two issues. Firstly the reason I was still able to read the certificate was because there was a second https get request being issued elsewhere in the code unknowingly.

Secondly the error of client not sending certificate is a little miss leading as the the certificate was sent, It ultimately was the inappropriate CA chain the server was using to verify the client.

Thank you for your help

Body:
I have a nodejs client and server interacting via https. I have self signed certificate authority, server certificate and a couple of test client certificates. I have tested the certificates are 'working' using openssl s_server and s_client, using the necessary command line options for self signed certs and no errors are generated.

When the client connects to server via https, the server immediately generates an error stating it could not get peer certificate:

`Error: 140735833322304:error:140890C7:SSL routines:ssl3_get_client_certificate:peer did not return a certificate:../deps/openssl/openssl/ssl/s3_srvr.c:3330:`

On the client the error is:

`{ Error: socket hang up
    at TLSSocket.onConnectEnd (_tls_wrap.js:1073:19)
    at Object.onceWrapper (events.js:322:30)
    at emitNone (events.js:120:20)
    at TLSSocket.emit (events.js:218:7)
    at endReadableNT (_stream_readable.js:1054:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  code: 'ECONNRESET',
  path: null,
  host: 'localhost',
  port: 443,
  localAddress: undefined }`

`140735833322304:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:1494:SSL alert number 40`

`140735833322304:error:140940E5:SSL routines:ssl3_read_bytes:ssl handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:1217:
`

However the handler for the URL executes and calls req.socket.getPeerCertificate() and the client certificate has clearly been sent:

`{ subject:
   { C: 'US',
     ST: 'MA',
     L: 'Boston',
     O: 'Example Co',
     OU: 'techops',
     CN: 'client2',
     emailAddress: 'certs@example.com' },
  issuer:
   { C: 'US',
     ST: 'MA',
     L: 'Boston',
     O: 'Example Co',
     OU: 'techops',
     CN: 'ca',
     emailAddress: 'certs@example.com' },
  modulus: 'B97D65....etc....}`

Why would I get these errors when the client has indeed sent the certificate?

Any help would be appreciated.


问:
SQL how can I have sql return one row instead of multiple per distinct ID?
According to my coworker, We are using IBM DB2

Having real hard time trying to make my sql return one row per ID.  Asked around at work but no girl here are good with SQL...  I can do some sql but am no SQL expert.

To explain it better, I set up the example below

Here is the TABLE and its data

```<code>ID  DATE        CODE  PERCENT
01  2016-08-21  1111  52
01  2016-09-06  1111  60
01  2016-10-06  1112  38
02  2016-05-01  6666  50
02  2016-10-01  1111  50
</code>```

I want one record returned per each ID with earliest DATE.
so I wrote below SQL

```<code>SELECT ID, MIN(DATE)
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID
</code>```

that worked fine.  I would get

```<code>01 2016-08-21
02 2016-10-01
</code>```

I soon realized that I also need PERCENT column.

```<code>SELECT ID, MIN(DATE), PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID, PERCENT
</code>```

but now, I'm getting the multiple rows for ID 01 which is wrong...

```<code>01  2016-08-21  1111  52
01  2016-09-06  1111  60
02  2016-10-01  1111  50
</code>```

Can somebody help me fix this SQL or point me to the right direction so that I can have one row per ID like below?

```<code>01  2016-08-21  1111  52
02  2016-10-01  1111  50
</code>```

答:
GROUP BY ID will do the necessary, no need to GROUP BY percent. A new row will be added if you GROUP BY percent since it has a different value.

```<code>SELECT ID, MIN(DATE), code, percent
FROM table
WHERE DATE BETWEEN '2016-01-01' AND '2017-11-01'
AND   CODE = 1111
GROUP BY ID;
</code>```

Hope this helps.

Body:
According to my coworker, We are using IBM DB2

Having real hard time trying to make my sql return one row per ID.  Asked around at work but no girl here are good with SQL...  I can do some sql but am no SQL expert.

To explain it better, I set up the example below

Here is the TABLE and its data

ID  DATE        CODE  PERCENT
01  2016-08-21  1111  52
01  2016-09-06  1111  60
01  2016-10-06  1112  38
02  2016-05-01  6666  50
02  2016-10-01  1111  50

I want one record returned per each ID with earliest DATE.
so I wrote below SQL

SELECT ID, MIN(DATE)
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID

that worked fine.  I would get

01 2016-08-21
02 2016-10-01

I soon realized that I also need PERCENT column.

SELECT ID, MIN(DATE), PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID, PERCENT

but now, I'm getting the multiple rows for ID 01 which is wrong...

01  2016-08-21  1111  52
01  2016-09-06  1111  60
02  2016-10-01  1111  50

Can somebody help me fix this SQL or point me to the right direction so that I can have one row per ID like below?

01  2016-08-21  1111  52
02  2016-10-01  1111  50

Body:
GROUP BY ID will do the necessary, no need to GROUP BY percent. A new row will be added if you GROUP BY percent since it has a different value.

SELECT ID, MIN(DATE), code, percent
FROM table
WHERE DATE BETWEEN '2016-01-01' AND '2017-11-01'
AND   CODE = 1111
GROUP BY ID;

Hope this helps.


答:
If you are sure that the folder 'sprites' is in the root of your project, then try prefixing it with '../', then try without the absolute positioning first. If it works, then return the positioning again as follows;

```<code>#stillMario {
  width: 16px;
  height: 32px;
  margin: auto;
  background-image: url("../sprites/still.png");
  //position:absolute;
  //left: 0px;
  //top: 0px;
  //bottom:0px;
}
</code>```

Let me know if it works

Title: Why isn't my background image showing up in CSS?

Body:
this is my first posting here and I am new to CSS. I am trying to get a sprite of Mario with dimensions of 32 x 16. When I open the html file nothing appears. I try to inspect element the html but I cannot see a div.

CSS

#stillMario {
    width: 16px;
    height: 32px;
    margin: auto;
    background-image: url("sprites/still.png");
    position:absolute;
    left: 0px;
    top: 0px;
    bottom:0px;
}

HTML

<!DOCTYPE html>

        <title>Super Mario</title>
        <link href="style.css" rel="stylesheet" type="text/css"/>

Body:
If you are sure that the folder 'sprites' is in the root of your project, then try prefixing it with '../', then try without the absolute positioning first. If it works, then return the positioning again as follows;

#stillMario {
  width: 16px;
  height: 32px;
  margin: auto;
  background-image: url("../sprites/still.png");
  //position:absolute;
  //left: 0px;
  //top: 0px;
  //bottom:0px;
}

Let me know if it works


问:
Replace content of each HTML controls javascript jquery
I'm trying again to replace each text content of each control in a page using javascript and jquery.

I need to search in each text content (WITHOUT MODIFING TAGS, ONLY THE TEXT) any word and replace it with another any word.

One try is:

```<code>jQuery.fn.replaceEachOne = function (objective, rep) {
   this.each( function(){
                //$(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
    $(this).html( $(this).html().replace( new RegExp('('+objective+'(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}
</code>```

Please help!!

答:
Something like this should do the trick:

```<code>$.fn.replaceEachOne = function(search, replace) {
    this.contents().each(function(){
        if (this.nodeType == Node.ELEMENT_NODE) {
            $(this).replaceEachOne(search, replace);
        } else if (this.nodeType == Node.TEXT_NODE) {
            this.nodeValue = this.nodeValue.replace(search, replace);
        }
    });
};
</code>```

This does the replacement on text nodes directly, rather than modifying the HTML of an entire element.  Note that it is case-sensitive.  You'd need to change the call to replace to use a regular expression if you want a case-insensitive search.

Body:
I'm trying again to replace each text content of each control in a page using javascript and jquery.

I need to search in each text content (WITHOUT MODIFING TAGS, ONLY THE TEXT) any word and replace it with another any word.

One try is:

jQuery.fn.replaceEachOne = function (objective, rep) {
   this.each( function(){
                //$(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
    $(this).html( $(this).html().replace( new RegExp('('+objective+'(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}

Please help!!

Body:
Something like this should do the trick:

$.fn.replaceEachOne = function(search, replace) {
    this.contents().each(function(){
        if (this.nodeType == Node.ELEMENT_NODE) {
            $(this).replaceEachOne(search, replace);
        } else if (this.nodeType == Node.TEXT_NODE) {
            this.nodeValue = this.nodeValue.replace(search, replace);
        }
    });
};

This does the replacement on text nodes directly, rather than modifying the HTML of an entire element.  Note that it is case-sensitive.  You'd need to change the call to replace to use a regular expression if you want a case-insensitive search.


问:
Conditional Validation will not allow form to submit
I have the below Conditional Validation, this validation only check the cc_number when the payment_method_id is 1, so it should not validate when there is other payment_method_id being used, but problem in my view page, even if I dont select the payment method, the form will not submit to the controller, unless the cc_number is filled, is there anyway to disable this cc_number check ? thank you</p>

```<code>$validator->creditCard ( 'cc_number', [ 'mc','visa' ], __ ( 'invalid card number' ), function ($context)
        {
            if ($context ['data'] ['payment_method_id'] == 1)
             return true;
        } );
</code>```

答: sorry for wasting space in this area, i just code cakephp3.5 recently, seems that this problem can be easily solve by putting ,'novalidate' => true at the $this->Form->create method</p>

Body:
I have the below Conditional Validation, this validation only check the cc_number when the payment_method_id is 1, so it should not validate when there is other payment_method_id being used, but problem in my view page, even if I dont select the payment method, the form will not submit to the controller, unless the cc_number is filled, is there anyway to disable this cc_number check ? thank you

$validator->creditCard ( 'cc_number', [ 'mc','visa' ], __ ( 'invalid card number' ), function ($context)
        {
            if ($context ['data'] ['payment_method_id'] == 1)
             return true;
        } );


问:
Fortran constructor of abstract class initializing private variables
I'm beginning with Fortran and I wanted to try a pretty simple example - one abstract class Connection, then its derived class IntervalConnection, while Connection class would have a constructor defined and IntervalConnection would inherit this constructor.

In this constructor I have several private variables, which I need to initialize.

The problem is, I'm getting following error, when trying to create a new object:
Connection.f08:152:10:

```<code>    con = IntervalConnection(n1_p, n2_p, 5.0)
          1
Error: Component ‘input_neuron’ at (1) is a PRIVATE component of ‘connection’
</code>```

I suppose I'm not defining the constructor new_connection correctly. Could you, please, tell me, how should I implement it in a better way?

My code

```<code>module Connection_mod
    implicit none

    public

    ! TODO smazat
    type :: Neuron
        real, private :: state

        contains
            procedure :: get_state => get_state_impl
            procedure :: set_state => set_state_impl
    end type Neuron

    !------------------!------------------------------------------------------------------------
    ! Type definitions !
    !------------------!
    type, abstract :: Connection
        class(Neuron), pointer, private :: input_neuron
        class(Neuron), pointer, private :: output_neuron
        real, private                   :: weight

        contains

            procedure :: adjust_weight     => adjust_weight_impl

            ! Getters and setters
            procedure :: get_input_neuron  => get_input_neuron_impl
            procedure :: get_output_neuron => get_output_neuron_impl
            procedure :: get_weight        => get_weight_impl

    end type Connection

    type, extends(Connection) :: IntervalConnection
       contains
          procedure :: pass_signal => pass_signal_impl
    end type IntervalConnection

    !------------!------------------------------------------------------------------------------
    ! Interfaces !
    !------------!
    interface Connection
        module procedure new_connection
    end interface Connection

    contains
    !------------------------!------------------------------------------------------------------
    ! Method implementations !
    ! -----------------------!

        !--------------!
        ! class Neuron !
        !--------------!
        ! TODO smazat
        function get_state_impl(this) result(state)
            class(Neuron), intent(in) :: this
            real                      :: state

            state = this%state
        end function get_state_impl

        ! TODO smazat
        function set_state_impl(this, new_state) result(ret_this)
            class(Neuron), target  :: this
            real, intent(in)       :: new_state
            class(Neuron), pointer :: ret_this

            ret_this   => this
            this%state = new_state
        end function set_state_impl

        !------------------!
        ! class Connection !
        !------------------!
        subroutine adjust_weight_impl(this, added_value)
            class(Connection), intent(inout) :: this
            real, intent(in)                 :: added_value

            this%weight = this%weight + added_value
        end subroutine adjust_weight_impl

        !--------------------------!
        ! class IntervalConnection !
        !--------------------------!
        subroutine pass_signal_impl(this)
            ! TODO dokoncit
            class(IntervalConnection), intent(in) :: this
            real :: a
            class(Neuron), pointer :: dummy

            a=this%weight * this%input_neuron%get_state()

            dummy => this%output_neuron%set_state(5.0)

            !this%output_neuron%set_state(this%weight * this%input_neuron%get_state())
        end subroutine pass_signal_impl

        !--------------!------------------------------------------------------------------------
        ! Constructors !
        !--------------!
        function new_connection(this, input_neuron, output_neuron, weight) result(ret_this)
            class(Connection), target  :: this
            class(Connection), pointer :: ret_this
            class(Neuron), pointer     :: input_neuron
            class(Neuron), pointer     :: output_neuron
            real, intent(in)           :: weight

            ret_this           => this
            this%input_neuron  => input_neuron
            this%output_neuron => output_neuron
            this%weight        = weight
        end function new_connection

        !-------------------!-------------------------------------------------------------------
        ! Getters & Setters !
        !-------------------!
        function get_input_neuron_impl(this) result (input_neuron)
            class(Connection), target, intent(in) :: this
            class(Neuron), pointer                :: input_neuron

            input_neuron => this%input_neuron
        end function get_input_neuron_impl

        function get_output_neuron_impl(this) result (output_neuron)
            class(Connection), target, intent(in) :: this
            class(Neuron), pointer                :: output_neuron

            output_neuron => this%output_neuron
        end function get_output_neuron_impl

        function get_weight_impl(this) result (weight)
            class(Connection), intent(in) :: this
            real                          :: weight

            weight = this%weight
        end function get_weight_impl
end module Connection_mod

program a
    use Connection_mod

    type(Neuron), target :: n1
    type(Neuron), target :: n2

    type(Neuron), pointer :: n1_p
    type(Neuron), pointer :: n2_p

    type(IntervalConnection) :: con

    n1_p => n1
    n2_p => n2
    con = IntervalConnection(n1_p, n2_p, 5.0)

end program a
</code>```

答:
The function you created as a constructor takes four arguments

```<code>function new_connection(this, input_neuron, output_neuron, weight)
</code>```

but you call it with three arguments

```<code>class(IntervalConnection) :: con

con = IntervalConnection(n1_p, n2_p, 5.0)
</code>```

I moved the assignment out. It is not strictly necessary.

Therefore the generic resolution (TKR) cannot be successful and the default constructor will be tried.

And you also overloaded the Constructor or Connection, but then you call IntervalConection(). These are different!

You probably misunderstood how a constructor works with the arguments and return values. There is no place for any this argument. A constructor is NOT a type-bound procedure. It is not inherited. But the child connection can call the parent constructor if needed. Sometimes you want that, sometimes not. Notice the returned value is type, not class!

```<code>function new_interval_connection(input_neuron, output_neuron, weight) result(ret)
        type(IntervalConnection) :: ret
        class(Neuron), pointer     :: input_neuron
        class(Neuron), pointer     :: output_neuron
        real, intent(in)           :: weight

        ret%input_neuron  => input_neuron
        ret%output_neuron => output_neuron
        ret%weight        = weight
end function new_interval_connection
</code>```

You want to create an instance of make the constructor for IntervalConnection, not for Connection, as you tried

```<code>interface IntervalConnection
    module procedure new_interval_connection
end interface Connection

con = IntervalConnection(n1, n2, 5.0)
</code>```

Body:
I'm beginning with Fortran and I wanted to try a pretty simple example - one abstract class Connection, then its derived class IntervalConnection, while Connection class would have a constructor defined and IntervalConnection would inherit this constructor.

In this constructor I have several private variables, which I need to initialize.

The problem is, I'm getting following error, when trying to create a new object:
Connection.f08:152:10:

    con = IntervalConnection(n1_p, n2_p, 5.0)
          1
Error: Component ‘input_neuron’ at (1) is a PRIVATE component of ‘connection’

I suppose I'm not defining the constructor new_connection correctly. Could you, please, tell me, how should I implement it in a better way?

My code

module Connection_mod
    implicit none

    public

    ! TODO smazat
    type :: Neuron
        real, private :: state

        contains
            procedure :: get_state => get_state_impl
            procedure :: set_state => set_state_impl
    end type Neuron

    !------------------!------------------------------------------------------------------------
    ! Type definitions !
    !------------------!
    type, abstract :: Connection
        class(Neuron), pointer, private :: input_neuron
        class(Neuron), pointer, private :: output_neuron
        real, private                   :: weight

        contains

            procedure :: adjust_weight     => adjust_weight_impl

            ! Getters and setters
            procedure :: get_input_neuron  => get_input_neuron_impl
            procedure :: get_output_neuron => get_output_neuron_impl
            procedure :: get_weight        => get_weight_impl

    end type Connection

    type, extends(Connection) :: IntervalConnection
       contains
          procedure :: pass_signal => pass_signal_impl
    end type IntervalConnection

    !------------!------------------------------------------------------------------------------
    ! Interfaces !
    !------------!
    interface Connection
        module procedure new_connection
    end interface Connection

    contains
    !------------------------!------------------------------------------------------------------
    ! Method implementations !
    ! -----------------------!

        !--------------!
        ! class Neuron !
        !--------------!
        ! TODO smazat
        function get_state_impl(this) result(state)
            class(Neuron), intent(in) :: this
            real                      :: state

            state = this%state
        end function get_state_impl

        ! TODO smazat
        function set_state_impl(this, new_state) result(ret_this)
            class(Neuron), target  :: this
            real, intent(in)       :: new_state
            class(Neuron), pointer :: ret_this

            ret_this   => this
            this%state = new_state
        end function set_state_impl

        !------------------!
        ! class Connection !
        !------------------!
        subroutine adjust_weight_impl(this, added_value)
            class(Connection), intent(inout) :: this
            real, intent(in)                 :: added_value

            this%weight = this%weight + added_value
        end subroutine adjust_weight_impl

        !--------------------------!
        ! class IntervalConnection !
        !--------------------------!
        subroutine pass_signal_impl(this)
            ! TODO dokoncit
            class(IntervalConnection), intent(in) :: this
            real :: a
            class(Neuron), pointer :: dummy

            a=this%weight * this%input_neuron%get_state()

            dummy => this%output_neuron%set_state(5.0)

            !this%output_neuron%set_state(this%weight * this%input_neuron%get_state())
        end subroutine pass_signal_impl

        !--------------!------------------------------------------------------------------------
        ! Constructors !
        !--------------!
        function new_connection(this, input_neuron, output_neuron, weight) result(ret_this)
            class(Connection), target  :: this
            class(Connection), pointer :: ret_this
            class(Neuron), pointer     :: input_neuron
            class(Neuron), pointer     :: output_neuron
            real, intent(in)           :: weight

            ret_this           => this
            this%input_neuron  => input_neuron
            this%output_neuron => output_neuron
            this%weight        = weight
        end function new_connection

        !-------------------!-------------------------------------------------------------------
        ! Getters & Setters !
        !-------------------!
        function get_input_neuron_impl(this) result (input_neuron)
            class(Connection), target, intent(in) :: this
            class(Neuron), pointer                :: input_neuron

            input_neuron => this%input_neuron
        end function get_input_neuron_impl

        function get_output_neuron_impl(this) result (output_neuron)
            class(Connection), target, intent(in) :: this
            class(Neuron), pointer                :: output_neuron

            output_neuron => this%output_neuron
        end function get_output_neuron_impl

        function get_weight_impl(this) result (weight)
            class(Connection), intent(in) :: this
            real                          :: weight

            weight = this%weight
        end function get_weight_impl
end module Connection_mod

program a
    use Connection_mod

    type(Neuron), target :: n1
    type(Neuron), target :: n2

    type(Neuron), pointer :: n1_p
    type(Neuron), pointer :: n2_p

    type(IntervalConnection) :: con

    n1_p => n1
    n2_p => n2
    con = IntervalConnection(n1_p, n2_p, 5.0)

end program a

Body:
The function you created as a constructor takes four arguments

function new_connection(this, input_neuron, output_neuron, weight)

but you call it with three arguments

class(IntervalConnection) :: con

con = IntervalConnection(n1_p, n2_p, 5.0)

I moved the assignment out. It is not strictly necessary.

Therefore the generic resolution (TKR) cannot be successful and the default constructor will be tried.

And you also overloaded the Constructor or Connection, but then you call IntervalConection(). These are different!

You probably misunderstood how a constructor works with the arguments and return values. There is no place for any this argument. A constructor is NOT a type-bound procedure. It is not inherited. But the child connection can call the parent constructor if needed. Sometimes you want that, sometimes not. Notice the returned value is type, not class!

function new_interval_connection(input_neuron, output_neuron, weight) result(ret)
        type(IntervalConnection) :: ret
        class(Neuron), pointer     :: input_neuron
        class(Neuron), pointer     :: output_neuron
        real, intent(in)           :: weight

        ret%input_neuron  => input_neuron
        ret%output_neuron => output_neuron
        ret%weight        = weight
end function new_interval_connection

You want to create an instance of make the constructor for IntervalConnection, not for Connection, as you tried

interface IntervalConnection
    module procedure new_interval_connection
end interface Connection

con = IntervalConnection(n1, n2, 5.0)