问:
I can't transfer my class variable into another class
Really desperate to ask this. I need to transfer my CipherText into another class, and it doesn't work. What am I missing? Sorry for the long post. (I've already removed the some GUI(tkinter) codes in those 2 class.) I can't seem to find solutions here. Would Gladly appreciate for some help. Thanks!!!

```<code>class Decmesbuttons():

   def decmescommand(self):
       datenow = str(datetime.datetime.now().date())
       timenow = str(datetime.datetime.now().time())

       privk = privkeyvarS.get()

       #No key found error
       try:
           pathpriv = r'/home/gene/Desktop/ppl/keys/' + privk
           loadprivkey = M2Crypto.RSA.load_key (pathpriv + '/' + privk + '-private.key')

       except IOError:
           tkMessageBox.showwarning("Warning!", "No "+ privk + " key found.")

       #Wrong key error & printing of the decrypted message
       try:
           PlainText = loadprivkey.private_decrypt (Ciphertext, M2Crypto.RSA.pkcs1_oaep_padding)

           if PlainText != "":
               tkMessageBox.showinfo("DECRYPTED!","Message decrypted by " + privk + " :" + Plaintext)

       except:
           tkMessageBox.showwarning("Warning!", "Wrong key!")

class Encmesbuttons():

    def encmescommand(self):
        datenow = str(datetime.datetime.now().date())
        timenow = str(datetime.datetime.now().time())

        m = messagevarS.get()
        pk = pubkeyvarS.get()

        #Input of selected message to encrypt

        em = m + '\n' + '-'
        if not m:
            tkMessageBox.showwarning("Warning!", "No message to encrypt")

        else:
            #add to log
            logkey = open ('log'+datenow+'.txt', 'a')
            logkey.write(timenow +'-'  + ' Some user inputted a message.' + "\n")
            logkey.close()

            f = open ('message.txt', 'w')
            f.write(str(m))
            f.close()

        try:
            #select the public key owner to send your encrypted message

            pathpub = r'/home/gene/Desktop/ppl/keys/' + pk
            loadpub = M2Crypto.RSA.load_pub_key (pathpub+ '/' + pk + '-public.key')

            global CT
            CipherText = loadpub.public_encrypt (m, M2Crypto.RSA.pkcs1_oaep_padding)
            CT = CipherText

            #Print the ciphered message

            tkMessageBox.showinfo("The encrypted message",str(CipherText.encode('base64')))

            #write ciphered text to file
            f = open ('encryption.txt', 'w')
            f.write(str(CipherText.encode ('base64')))
            f.close()

            #add to log
            logkey = open ('log'+datenow+'.txt', 'a')
            logkey.write(timenow +'-' + 'Some user has encrypted the message and selected ' + pk + ' as the receiver' +  "\n")
            logkey.close()

        except IOError:
            tkMessageBox.showwarning("Warning!", "No public key inputted")
</code>```

I need this variable:

```<code>CipherText = loadpub.public_encrypt (m, M2Crypto.RSA.pkcs1_oaep_padding)
</code>```

to be in this line (the one with the Here sign):

```<code> PlainText = loadprivkey.private_decrypt (**HERE**, M2Crypto.RSA.pkcs1_oaep_padding)
</code>```

答:
It is not preferred method but you can use global CipherText instead of global CT in decmescommand() and your variable will be accessible in all places. Currently variable CT has your CipherText and it is accessible in all places - so you can use CT instead of CipherText inside encmescommand().

There is one thing: method encmescommand() has to be executed before decmescommand() to assign value to CipherText / CT

EDIT:

see example

```<code>class Decmesbuttons():

    def decmescommand(self):
        print('execute decmescommand()')

        print('CipherText:', CipherText)

class Encmesbuttons():

    def encmescommand(self):
         print('execute encmescommand()')

         global CipherText

         CipherText = "hello world"

d = Decmesbuttons()
e = Encmesbuttons()

e.encmescommand() # <- you have to run it before decmescommand()
d.decmescommand()
</code>```

result:

```<code>execute encmescommand()
execute decmescommand()
CipherText: hello world
</code>```

EDIT: more prefered method

```<code>class Decmesbuttons():

    def decmescommand(self, text):
        print('execute decmescommand()')

        print('CipherText:', text)

class Encmesbuttons():

    def encmescommand(self):
        print('execute encmescommand()')

        CipherText = "hello world"

        return CipherText

d = Decmesbuttons()
e = Encmesbuttons()

result = e.encmescommand() # <- you have to run it before decmescommand()
d.decmescommand(result)
</code>```

Body:
Really desperate to ask this. I need to transfer my CipherText into another class, and it doesn't work. What am I missing? Sorry for the long post. (I've already removed the some GUI(tkinter) codes in those 2 class.) I can't seem to find solutions here. Would Gladly appreciate for some help. Thanks!!!

class Decmesbuttons():

   def decmescommand(self):
       datenow = str(datetime.datetime.now().date())
       timenow = str(datetime.datetime.now().time())

       privk = privkeyvarS.get()

       #No key found error
       try:
           pathpriv = r'/home/gene/Desktop/ppl/keys/' + privk
           loadprivkey = M2Crypto.RSA.load_key (pathpriv + '/' + privk + '-private.key')

       except IOError:
           tkMessageBox.showwarning("Warning!", "No "+ privk + " key found.")

       #Wrong key error & printing of the decrypted message
       try:
           PlainText = loadprivkey.private_decrypt (Ciphertext, M2Crypto.RSA.pkcs1_oaep_padding)

           if PlainText != "":
               tkMessageBox.showinfo("DECRYPTED!","Message decrypted by " + privk + " :" + Plaintext)

       except:
           tkMessageBox.showwarning("Warning!", "Wrong key!")

class Encmesbuttons():

    def encmescommand(self):
        datenow = str(datetime.datetime.now().date())
        timenow = str(datetime.datetime.now().time())

        m = messagevarS.get()
        pk = pubkeyvarS.get()

        #Input of selected message to encrypt

        em = m + '\n' + '-'
        if not m:
            tkMessageBox.showwarning("Warning!", "No message to encrypt")

        else:
            #add to log
            logkey = open ('log'+datenow+'.txt', 'a')
            logkey.write(timenow +'-'  + ' Some user inputted a message.' + "\n")
            logkey.close()

            f = open ('message.txt', 'w')
            f.write(str(m))
            f.close()

        try:
            #select the public key owner to send your encrypted message

            pathpub = r'/home/gene/Desktop/ppl/keys/' + pk
            loadpub = M2Crypto.RSA.load_pub_key (pathpub+ '/' + pk + '-public.key')

            global CT
            CipherText = loadpub.public_encrypt (m, M2Crypto.RSA.pkcs1_oaep_padding)
            CT = CipherText

            #Print the ciphered message

            tkMessageBox.showinfo("The encrypted message",str(CipherText.encode('base64')))

            #write ciphered text to file
            f = open ('encryption.txt', 'w')
            f.write(str(CipherText.encode ('base64')))
            f.close()

            #add to log
            logkey = open ('log'+datenow+'.txt', 'a')
            logkey.write(timenow +'-' + 'Some user has encrypted the message and selected ' + pk + ' as the receiver' +  "\n")
            logkey.close()

        except IOError:
            tkMessageBox.showwarning("Warning!", "No public key inputted")

I need this variable:

CipherText = loadpub.public_encrypt (m, M2Crypto.RSA.pkcs1_oaep_padding)

to be in this line (the one with the Here sign):

 PlainText = loadprivkey.private_decrypt (**HERE**, M2Crypto.RSA.pkcs1_oaep_padding)

Body:
It is not preferred method but you can use global CipherText instead of global CT in decmescommand() and your variable will be accessible in all places. Currently variable CT has your CipherText and it is accessible in all places - so you can use CT instead of CipherText inside encmescommand().

There is one thing: method encmescommand() has to be executed before decmescommand() to assign value to CipherText / CT

EDIT:

see example

class Decmesbuttons():

    def decmescommand(self):
        print('execute decmescommand()')

        print('CipherText:', CipherText)

class Encmesbuttons():

    def encmescommand(self):
         print('execute encmescommand()')

         global CipherText

         CipherText = "hello world"

d = Decmesbuttons()
e = Encmesbuttons()

e.encmescommand() # <- you have to run it before decmescommand()
d.decmescommand()

result:

execute encmescommand()
execute decmescommand()
CipherText: hello world

EDIT: more prefered method

class Decmesbuttons():

    def decmescommand(self, text):
        print('execute decmescommand()')

        print('CipherText:', text)

class Encmesbuttons():

    def encmescommand(self):
        print('execute encmescommand()')

        CipherText = "hello world"

        return CipherText

d = Decmesbuttons()
e = Encmesbuttons()

result = e.encmescommand() # <- you have to run it before decmescommand()
d.decmescommand(result)


来源: stackexchange

问:
How to check if a user is logged in and how to save their information? (React)
So pretty much I made a login page communicates with a backend to login a user. Now I want to take their data and store it for all my other components to know that there is

A user logged in

Have access to the user's information

I figured based on past StackOverflow answers, that the best way to do this is using JWT and LocalStorage. But all the answer's I've encountered seem to use Redux. I'm not using Redux at all for my application, and have no clue how to use it, so I was wondering if there's a way to do it without redux.

答:
You don't need Redux. You just have to store the JWT in localStorage. To do that, just use localStorage.setItem('token', data.token) when you receive the login success response from the API. It's that simple. You can read this article for more details. It's for React Redux applications but doesn't need Redux.

Then, assuming you are using react-router, you need two helper functions. The first will go on your protected routes and would look like this:

```<code>const requireAuth = (...) => {
  if(!localStorage.getItem('token')) {
    // go to login route
  }
  // stay on this route since the user is authenticated
}
</code>```

The second goes on your unprotected routes and looks like this:

```<code>const verifyAuth = (...) => {
  if(localStorage.getItem('token')) {
    // go to your dashboard or home route
  }
  // stay on this route since the user is not authenticated
}
</code>```

Keep in mind that you have to refresh the token according to the server expiration time. A good approach would be to create a call to the server asking if the token is still valid.

ContentLicense: CC BY-SA 3.0

Body:
You don't need Redux. You just have to store the JWT in localStorage. To do that, just use localStorage.setItem('token', data.token) when you receive the login success response from the API. It's that simple. You can read this article for more details. It's for React Redux applications but doesn't need Redux.

Then, assuming you are using react-router, you need two helper functions. The first will go on your protected routes and would look like this:

const requireAuth = (...) => {
  if(!localStorage.getItem('token')) {
    // go to login route
  }
  // stay on this route since the user is authenticated
}

The second goes on your unprotected routes and looks like this:

const verifyAuth = (...) => {
  if(localStorage.getItem('token')) {
    // go to your dashboard or home route
  }
  // stay on this route since the user is not authenticated
}

Keep in mind that you have to refresh the token according to the server expiration time. A good approach would be to create a call to the server asking if the token is still valid.


问:
How to add a where clause to a Hibernate @ManyToMany relationship?
Given two entities:

PurchaseProductGroup

PurchaseProduct, which has a status column that can be 'A' (active) or 'D' (deleted)

and a many-to-many relationship defined in PurchaseProductGroup:

```<code>/** The purchase products linked to this group. */
@ManyToMany
@JoinTable(name = "purchaseprodgrp_purchaseprod",
           joinColumns = @JoinColumn(name = "ppg_id"),
           inverseJoinColumns = @JoinColumn(name = "ppr_id"))
private List<PurchaseProduct> purchaseProducts;
</code>```

How can I restrict this so that purchaseProducts with a status of 'D' are excluded?

Things I've tried

Have tried adding the following just below the @ManyToMany annotation but both failed with an "invalid identifier" exception for the column:

@Where(clause = "status <> 'D'")

@WhereJoinTable(clause = "purchaseProduct.status <> 'D'")

Also tried using adding @Where(clause = "status <> 'D'") at the entity level but this doesn't seem to affect the contents of relationship collections - as backed up by this question.

答:
Please try the following code:

```<code>@ManyToMany
@JoinTable(name = "purchaseprodgrp_purchaseprod",
       joinColumns = @JoinColumn(name = "ppg_id"),
       inverseJoinColumns = @JoinColumn(name = "ppr_id"))
@Where(clause = "ppr_status <> 'D'")
private List<PurchaseProduct> purchaseProducts;
</code>```

This may be similar to something you have tried before, but a critical point to get this working is that ppr_status is the actual column name.  Hence the PurchaseProduct entity should have the following:

```<code>@Column(name="ppr_status")
public String getStatus() {
    return status;
}
</code>```

If you had named the field ppr_status then the @Column may not be necessary.  But based on your comments above we need to tell Hibernate how to map this column.

Reference: Hibernate annotations. @Where vs @WhereJoinTable

Body:
Given two entities:

PurchaseProductGroup

PurchaseProduct, which has a status column that can be 'A' (active) or 'D' (deleted)

and a many-to-many relationship defined in PurchaseProductGroup:

/** The purchase products linked to this group. */
@ManyToMany
@JoinTable(name = "purchaseprodgrp_purchaseprod",
           joinColumns = @JoinColumn(name = "ppg_id"),
           inverseJoinColumns = @JoinColumn(name = "ppr_id"))
private List<PurchaseProduct> purchaseProducts;

How can I restrict this so that purchaseProducts with a status of 'D' are excluded?

Things I've tried

Have tried adding the following just below the @ManyToMany annotation but both failed with an "invalid identifier" exception for the column:

@Where(clause = "status <> 'D'")

@WhereJoinTable(clause = "purchaseProduct.status <> 'D'")

Also tried using adding @Where(clause = "status <> 'D'") at the entity level but this doesn't seem to affect the contents of relationship collections - as backed up by this question.

Body:
Please try the following code:

@ManyToMany
@JoinTable(name = "purchaseprodgrp_purchaseprod",
       joinColumns = @JoinColumn(name = "ppg_id"),
       inverseJoinColumns = @JoinColumn(name = "ppr_id"))
@Where(clause = "ppr_status <> 'D'")
private List<PurchaseProduct> purchaseProducts;

This may be similar to something you have tried before, but a critical point to get this working is that ppr_status is the actual column name.  Hence the PurchaseProduct entity should have the following:

@Column(name="ppr_status")
public String getStatus() {
    return status;
}

If you had named the field ppr_status then the @Column may not be necessary.  But based on your comments above we need to tell Hibernate how to map this column.

Reference: Hibernate annotations. @Where vs @WhereJoinTable


问:
Return null if generic type is nullable
I am writing a function that checks if an output is DBNull and returns null if the generic type is nullable. If not it simply throws the error.

Update: added all recommendations

```<code>public T Get<T>(string key)
{
    int ordinal = reader.GetOrdinal(key);
    if (reader.IsDBNull(ordinal))
    {
        if (typeof(T).GetTypeInfo().IsValueType && Nullable.GetUnderlyingType(typeof(T)) == null) // isn't a nullable field
            throw new InvalidCastException();
        else return default(T);
    }
    return reader.GetFieldValue<T>(ordinal);
}
</code>```

However I am not sure if default(T) returns null for every nullable field. If now is there any other way to make it return null?

答:
Yes, default(T) is the right kind of null-like value for every T that is actually a SomeType? / Nullable<SomeType>, so what you have should work fine.

You might want to consider things like string and byte[] though - these can also come from databases and can be null.

You might also want to think about what the error should be if someone simply makes a mistake and asks for <int> when the value is a <decimal>. That would cause InvalidCastException. There is an IsDBNull() method on IDataReader that might be more appropriate than using the exception.

Finally: prefer throw; to throw e;

Title: Return null if generic type is nullable

Body:
I am writing a function that checks if an output is DBNull and returns null if the generic type is nullable. If not it simply throws the error.

Update: added all recommendations

public T Get<T>(string key)
{
    int ordinal = reader.GetOrdinal(key);
    if (reader.IsDBNull(ordinal))
    {
        if (typeof(T).GetTypeInfo().IsValueType && Nullable.GetUnderlyingType(typeof(T)) == null) // isn't a nullable field
            throw new InvalidCastException();
        else return default(T);
    }
    return reader.GetFieldValue<T>(ordinal);
}

However I am not sure if default(T) returns null for every nullable field. If now is there any other way to make it return null?


问:
How can I set the MAX capacity of an autoscaling group with boto3?
Lets say I have a cluster with 3 instances, and when it was created I wanted 3 instances. I can use a scaling policy to manipulate it between 0-3 but obviously it hits the limit of the MAX capacity.

I can update this on the front end but don't see an API call for it.

How do I set the max capacity of an autoscaling group?

Ideally there is a way to do this without creating a new one then deleting the old one. If that is the only way, do I need to make the cluster "aware" of the new scaling group?

答:
You don't need to recreate the group.  http://boto3.readthedocs.io/en/latest/reference/services/autoscaling.html#AutoScaling.Client.update_auto_scaling_group can adjust the Max capacity .  Other than adjusting the desired capacity down to the max if necessary, you can change only the max capacity without side effects.  </p>

<p>You can also do so from the cli.  Boto3 clients and awscli  commands are both usually pretty faithful to the underlying apis.  </p>

Body:
You don't need to recreate the group.  http://boto3.readthedocs.io/en/latest/reference/services/autoscaling.html#AutoScaling.Client.update_auto_scaling_group can adjust the Max capacity .  Other than adjusting the desired capacity down to the max if necessary, you can change only the max capacity without side effects.

You can also do so from the cli.  Boto3 clients and awscli  commands are both usually pretty faithful to the underlying apis.


问:
IntelliJ external libraries?
I have added json-simple-1.1.jar to my project dependency through my modules. I am planning on sending this project to another person and I want them to be able to run the (command line) program, but it uses json-simple which looks like it is stored in the "external libraries" folder next to my project folder. My question is if theres is any way I can send the project with no installation of json-simple on their end, or will it work fine on other computers? </p>

答:
Usually it is best to build everything into one .jar file; that is easiest to run.

Here is some info on how to do that in IntelliJ.

Title: IntelliJ external libraries?


问:
Azure Functions without public endpoint
Is there a way to deploy some code as an Azure Function, but not expose it publicly? From what I see in documentation, AF always gets a public endpoint. Is that the only solution? I would like to build a solution in which AF are accessible only internally, by services which are behind firewall (no public access either). Is that possible?</p>

答:
Only HTTP trigger functions get a public endpoint. All other functions do not.

So you could create a queue trigger function, which has no public endpoint, and then have an internal service place a message in the queue that would cause the function to trigger.

Title: Azure Functions without public endpoint


问:
'For loop' to arrange Numbers in ascending order. [ERROR] pointer and integer comparision
This is a very simple program, to arrange numbers in ascending order. Now here I don't know how it says there is the comparison between integer and pointer, in all the for loops. I am a noob by the way. </p>

```<code>#include <stdio.h>

int main()
{

    int number[100],total,i,j,temp;;

    printf("Enter the quantity of the numbers you want \n");
    scanf("%d",&total);

    printf("Enter the numbers \n");
    for(i=0; i<total; i++){

        scanf("%d",&number[i]);
    }

    for(i=0; i < (number-1); i++){

        for(j=(i+1); j  < number; j++){

            if(number[i]>number[j]){
                temp = number[i];
                number[i] = number[j];
                number[j] = temp;
           }

        }

    }
    for(i=0; i < number; i++){

        printf("%d \n", number[i]);
    }

    return 0;
}
</code>```

答:
You are using i < number where i is int and number is an array

Just change those lines to below

```<code>for(i=0; i < (total-1); i++){

        for(j=(i+1); j  < total; j++){

for(i=0; i < total; i++){
</code>```

Body:
This is a very simple program, to arrange numbers in ascending order. Now here I don't know how it says there is the comparison between integer and pointer, in all the for loops. I am a noob by the way.

#include <stdio.h>

int main()
{

    int number[100],total,i,j,temp;;

    printf("Enter the quantity of the numbers you want \n");
    scanf("%d",&total);

    printf("Enter the numbers \n");
    for(i=0; i<total; i++){

        scanf("%d",&number[i]);
    }

    for(i=0; i < (number-1); i++){

        for(j=(i+1); j  < number; j++){

            if(number[i]>number[j]){
                temp = number[i];
                number[i] = number[j];
                number[j] = temp;
           }

        }

    }
    for(i=0; i < number; i++){

        printf("%d \n", number[i]);
    }

    return 0;
}

Body:
You are using i < number where i is int and number is an array

Just change those lines to below

for(i=0; i < (total-1); i++){

        for(j=(i+1); j  < total; j++){

for(i=0; i < total; i++){


问:
raymarching and rasterizing
I am trying to integrate ShaderToy code into a basic OpenGL renderer that only has one plane at y=0, nothing else. However, I do not even know where to start. ShaderToy renders to a uv texture while my plane is rendered real-time in 3D. Are there any examples of how I could integrate or even intermix the two rendering techniques?</p>

答:
Forget about the MVP matrices, and just render as a 2D image.

Suppose this is what you get from shaderToy.

void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
    // some code you download from shaderToy
    fragColor = color; // suppose
}
```

<p>Change this to</p>

<pre class="lang-c prettyprint-override"><code>vec4 mainImage( in vec2 fragCoord ) {
    // some code you download from shaderToy
    return color;
}
</code>```

Vertex shader is trivial, you simply let the OpenGL do the calculation.

#version 330

in vec2 v_vert;
out vec2 f_vert;

void main() {
    f_vert = v_vert;
}
```

<p>Use what you get from the vertex shader to calculate the fragColor, (remember to pass the time varying uniform to the fragment shader), hence the fragment shader should be like the following:</p>

<pre class="lang-c prettyprint-override"><code>#version 330

uniform float iTime; // this might vary, depends on the version of shaderToy

in vec2 f_vert;
out vec4 FragColor;

vec4 mainImage( in vec2 fragCoord ) {
    // some code you download from shaderToy
    return color;
}

void main() {
    FragColor = mainImage( f_vert );
}
</code>```

Title: raymarching and rasterizing

Body:
Forget about the MVP matrices, and just render as a 2D image.

Suppose this is what you get from shaderToy.

void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
    // some code you download from shaderToy
    fragColor = color; // suppose
}

Change this to

vec4 mainImage( in vec2 fragCoord ) {
    // some code you download from shaderToy
    return color;
}

Vertex shader is trivial, you simply let the OpenGL do the calculation.

#version 330

in vec2 v_vert;
out vec2 f_vert;

void main() {
    f_vert = v_vert;
}

Use what you get from the vertex shader to calculate the fragColor, (remember to pass the time varying uniform to the fragment shader), hence the fragment shader should be like the following:

#version 330

uniform float iTime; // this might vary, depends on the version of shaderToy

in vec2 f_vert;
out vec4 FragColor;

vec4 mainImage( in vec2 fragCoord ) {
    // some code you download from shaderToy
    return color;
}

void main() {
    FragColor = mainImage( f_vert );
}


问:
Error C2679 binary '=': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
I'm trying to make a dynamic array in C++ using DirectX 12. I found a good one on here made some miner changes because it was created for DirectX 11.

I get this error when I run it.

Severity Code Description Project File Line Suppression State

Error C2679   binary '=': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)

Here is the code it is saying has the issue.

```<code>    Vector(int a)
{
  size = a;
  obj = new T[size];
  for(int i = 0 ; i<size; i++)
  {
    obj[i] = NULL;
  }
}
</code>```

Here is the full header.

```<code>#include<iostream>
using namespace std;
template <class T>
class Vector
{
private:
    int size,capacity;
    T *obj;
public:
    Vector()
    {
        size = capacity = 0;
        obj = NULL;
    }
    ~Vector()
    {
        delete [] obj;
    }
    Vector(int a)
    {
        size = a;
        obj = new T[size];
        for(int i = 0 ; i<size; i++)
        {
            obj[i] = NULL;
        }
    }
    int size_of_list();
    bool empty();
    void reserve(int);
    T& operator[](int);
    T at(int);
    T front();
    T back();
    void push_back(T element);
    void pop_back();
    void insert(int,T);
    void erase(int);
};
</code>```

The .cpp file is available on request.

答: You're writing java or C#, not c++ there. C++ has value semantics. Objects generally can't be set to NULL (which is just a macro for the value zero). Nor is there any need, generally, as you have a proper value: T{}, the default constructed object

Body:
I'm trying to make a dynamic array in C++ using DirectX 12. I found a good one on here made some miner changes because it was created for DirectX 11.

I get this error when I run it.

Severity Code Description Project File Line Suppression State

Error C2679   binary '=': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)

Here is the code it is saying has the issue.

    Vector(int a)
{
  size = a;
  obj = new T[size];
  for(int i = 0 ; i<size; i++)
  {
    obj[i] = NULL;
  }
}

Here is the full header.

#include<iostream>
using namespace std;
template <class T>
class Vector
{
private:
    int size,capacity;
    T *obj;
public:
    Vector()
    {
        size = capacity = 0;
        obj = NULL;
    }
    ~Vector()
    {
        delete [] obj;
    }
    Vector(int a)
    {
        size = a;
        obj = new T[size];
        for(int i = 0 ; i<size; i++)
        {
            obj[i] = NULL;
        }
    }
    int size_of_list();
    bool empty();
    void reserve(int);
    T& operator[](int);
    T at(int);
    T front();
    T back();
    void push_back(T element);
    void pop_back();
    void insert(int,T);
    void erase(int);
};

The .cpp file is available on request.


问:
If statements in Where Condition with possible empty or Null parameters Power Query Excel SQL
I have a parameter in an Excel spreadsheet for serial number and work order number. Lets say the Cell itself is named SerialNumber and WorkOrderNumber

Note that sometimes we know a value for serial and or work order but sometimes we don't

Using a Get Parameter function in PowerQuery

```<code>    let GetValue=(rangeName) =>
        let
          name = Excel.CurrentWorkbook(){[Name=rangeName]}[Content],
          value = name{0}[Column1]
        in
          value
        in GetValue
</code>```

I was able to get the SerialNumber and WorkOrderNumber as a parameter named SerialNumberP and WorkOrderNumberP in the let statement below:

```<code>    Let

      SerialNumberP = GetParamater("SerialNumber"),
      WorkOrderNumberP = GetParameter("WorkOrderNumber")
</code>```

Then I have an SQL Select statement as such:

```<code>    Select
       a.SerialNumber,
       b.WorkOrderNumber,
       a.PartNumber,
       a.BatchNumber,
       a.CreateDate,
       b.CreatedBy,
       b.ComponentSerialNumber,
</code>```

Our database is in an SQL Database in the network therefore my From statement is:

```<code>    From [Database].[Category].[Table1] as a
    inner join [Database].[Category].[Table2] as b
    on a.WorkOrderNumber = b.WorkOrderNumber
</code>```

Now I want to use a where statement where I can search for Either a known SerialNumber Or a WorkOrderNumber, Or both if applicable. However when I use the following code:

```<code>    Where
    a.SerialNumber in ('"& SerialNumberP &"')
    and b.WorkOrderNumber in ('"& WorkOrderNumberP &"')
</code>```

It picks up that when one field is empty (Either SerialNumber or WorkOrderNumber), that the empty field is null and the query does not pass.

The error i get is :DataSource.Error: Microsoft SQL: This database function doesn't support the query option 'Query' with value 'null'. Whereas if i fill in both fields it works

What would be the best way around this?

Thanks in advance

Edit: I have tried using If statements in the Where conditions and it doesn't seem to work

e.g.

```<code>    Where
    If SerialNumberP Is Not Null Then a.SerialNumber In ('"& SerialNumberP &"')
    If WorkOrderNumberP Is Not Null Then b.WorkOrderNumber In ('"& WorkOrderNumberP &"')
</code>```

答:
Give this a try:</p>

```<code>Where
(a.SerialNumber Is Null Or a.SerialNumber in ('"& SerialNumberP &"')) and
(b.WorkOrderNumber Is Null Or b.WorkOrderNumber in ('"& WorkOrderNumberP &"'))
</code>```

Body:
I have a parameter in an Excel spreadsheet for serial number and work order number. Lets say the Cell itself is named SerialNumber and WorkOrderNumber

Note that sometimes we know a value for serial and or work order but sometimes we don't

Using a Get Parameter function in PowerQuery

    let GetValue=(rangeName) =>
        let
          name = Excel.CurrentWorkbook(){[Name=rangeName]}[Content],
          value = name{0}[Column1]
        in
          value
        in GetValue

I was able to get the SerialNumber and WorkOrderNumber as a parameter named SerialNumberP and WorkOrderNumberP in the let statement below:

    Let

      SerialNumberP = GetParamater("SerialNumber"),
      WorkOrderNumberP = GetParameter("WorkOrderNumber")

Then I have an SQL Select statement as such:

    Select
       a.SerialNumber,
       b.WorkOrderNumber,
       a.PartNumber,
       a.BatchNumber,
       a.CreateDate,
       b.CreatedBy,
       b.ComponentSerialNumber,

Our database is in an SQL Database in the network therefore my From statement is:

    From [Database].[Category].[Table1] as a
    inner join [Database].[Category].[Table2] as b
    on a.WorkOrderNumber = b.WorkOrderNumber

Now I want to use a where statement where I can search for Either a known SerialNumber Or a WorkOrderNumber, Or both if applicable. However when I use the following code:

    Where
    a.SerialNumber in ('"& SerialNumberP &"')
    and b.WorkOrderNumber in ('"& WorkOrderNumberP &"')

It picks up that when one field is empty (Either SerialNumber or WorkOrderNumber), that the empty field is null and the query does not pass.

The error i get is :DataSource.Error: Microsoft SQL: This database function doesn't support the query option 'Query' with value 'null'. Whereas if i fill in both fields it works

What would be the best way around this?

Thanks in advance

Edit: I have tried using If statements in the Where conditions and it doesn't seem to work

e.g.

    Where
    If SerialNumberP Is Not Null Then a.SerialNumber In ('"& SerialNumberP &"')
    If WorkOrderNumberP Is Not Null Then b.WorkOrderNumber In ('"& WorkOrderNumberP &"')

Body:
Give this a try:

Where
(a.SerialNumber Is Null Or a.SerialNumber in ('"& SerialNumberP &"')) and
(b.WorkOrderNumber Is Null Or b.WorkOrderNumber in ('"& WorkOrderNumberP &"'))


问:
AWS How to re-schedule a S3 lambda event?
I have a lambda which runs when a object is created in S3, in some cases I need to reschedule this lambda to happen lets say 15 minutes later.

When my lambda runs by second time I need to have the same event argument, I dont mind about other fields than the bucket and path.
event.Records[0].s3.bucket.name event.Records[0].s3.object.key . But it is easy to have same event

My alternative is to save that data in dynamo and have another lambda which will read from there each 15 minutes (awful).

But it will be nicer to just reschedule my current function and pass same arguments to it.
Something like this:

```<code>exports.handler = (event, context, callback) => {
   if(xyz)
      reschedule(15 * 1000 * 60, 'ThisLambdaName', event, context);
}
</code>```

Something like setTimeout but without AWS charging me for those 15 minutes lol.

答:
You can use DynamoDB with TTL, DynamoDB Streams and AWS Lambda for this.

Save the data in DynamoDB and set the TTL to 15 minutes after.

When the TTL is reached for an item, it will create a DynamoDB Stream which you can then use to trigger the original function again with the original data. You most likely have to make some changes in your handler to address events from S3 and DynamoDB Streams differently.

References:

DynamoDB Streams and Time To Live

DynamoDB Streams and AWS Lambda Triggers

Body:
I have a lambda which runs when a object is created in S3, in some cases I need to reschedule this lambda to happen lets say 15 minutes later.

When my lambda runs by second time I need to have the same event argument, I dont mind about other fields than the bucket and path.
event.Records[0].s3.bucket.name event.Records[0].s3.object.key . But it is easy to have same event

My alternative is to save that data in dynamo and have another lambda which will read from there each 15 minutes (awful).

But it will be nicer to just reschedule my current function and pass same arguments to it.
Something like this:

exports.handler = (event, context, callback) => {
   if(xyz)
      reschedule(15 * 1000 * 60, 'ThisLambdaName', event, context);
}

Something like setTimeout but without AWS charging me for those 15 minutes lol.


问:
Laravel Parameter passing error from controller to view
I want to pass the parameter  $questions to view, but it gives the following error:

ErrorException (E_ERROR)
      Undefined variable: questions (View: C:\Users\Krishan\Documents\GitHub\GroupProject\lcurve\resources\views\quizz\questions\index.blade.php)

This is my controller index function part:

```<code>public function index()
{
    $questions = Question::all();
    return view('quizz/questions.index', compact('questions'));
}
</code>```

This is a part Of my view:

```<code><tbody>
    @if (count($questions_options) > 0)
        @foreach ($questions_options as $questions_option)
            <tr data-entry-id="{{ $questions_option->id }}">
                <td></td>
                <td>{{ $questions_option->question->question_text or '' }}</td>
                <td>{{ $questions_option->option }}</td>
                <td>{{ $questions_option->correct == 1 ? 'Yes' : 'No' }}</td>
                <td>
                    <a href="{{ route('quizz/questions_options.show',[$questions_option->id]) }}" class="btn btn-xs btn-primary">View</a>-->
                    <!--<a href="{{ route('questions_options.edit',[$questions_option->id]) }}" class="btn btn-xs btn-info">Edit</a>-->
                    {!! Form::open(array(
                                        'style' => 'display: inline-block;',
                                        'method' => 'DELETE',
                                        'onsubmit' => "return confirm('".trans("quickadmin.are_you_sure")."');",
                                        'route' => ['questions_options.destroy', $questions_option->id])) !!}
                                    {!! Form::submit(trans('quickadmin.delete'), array('class' => 'btn btn-xs btn-danger')) !!}
                                    {!! Form::close() !!}
                </td>
            </tr>
        @endforeach
    @else
        <tr>
            <td colspan="5">no_entries_in_table</td>
        </tr>
    @endif
</tbody>
</code>```

enter image description here

答:
where is questions_options coming from? You are passing questions. So your for loop should be

```<code>@if (count($questions) > 0)
  @foreach ($questions as $question)
     //rest of your code
  @endforeach
@endif
</code>```

and your return view part can be return view(quizz.questions.index, compact('questions'))

Body:
I want to pass the parameter  $questions to view, but it gives the following error:

ErrorException (E_ERROR)
      Undefined variable: questions (View: C:\Users\Krishan\Documents\GitHub\GroupProject\lcurve\resources\views\quizz\questions\index.blade.php)

This is my controller index function part:

public function index()
{
    $questions = Question::all();
    return view('quizz/questions.index', compact('questions'));
}

This is a part Of my view:

    @if (count($questions_options) > 0)
        @foreach ($questions_options as $questions_option)

id }}">

                {{ $questions_option->question->question_text or '' }}
                {{ $questions_option->option }}
                {{ $questions_option->correct == 1 ? 'Yes' : 'No' }}

                    id]) }}" class="btn btn-xs btn-primary">View-->

                    {!! Form::open(array(
                                        'style' => 'display: inline-block;',
                                        'method' => 'DELETE',
                                        'onsubmit' => "return confirm('".trans("quickadmin.are_you_sure")."');",
                                        'route' => ['questions_options.destroy', $questions_option->id])) !!}
                                    {!! Form::submit(trans('quickadmin.delete'), array('class' => 'btn btn-xs btn-danger')) !!}
                                    {!! Form::close() !!}

        @endforeach
    @else

            no_entries_in_table

    @endif

enter image description here

Body:
where is questions_options coming from? You are passing questions. So your for loop should be

@if (count($questions) > 0)
  @foreach ($questions as $question)
     //rest of your code
  @endforeach
@endif

and your return view part can be return view(quizz.questions.index, compact('questions'))


问:
What's the standard way to add a selectable config item with ionic?
I would like to know the standard way to build something like this (see Manage Labels entry in the picture):

Does it look like this?

```<code><ion-list>
  <button ion-item (click)="selectLabelsOption()">
    Manage labels
    <p>{{selectedLabelsOption}}</p>
  </button>
<ion-list>
</code>```

Then when you click on the row, an alert is displayed like this:

How do you achieve this?

With an alert controller that contains a cancel button and a handler on each radio button?

Or is there another component for this?

答:
You can use ion-select:

```<code><ion-item>
  <ion-label>Chose Assist App</ion-label>
  <ion-select [(ngModel)]="choice">
    <ion-option value="a">Google App</ion-option>
    <ion-option value="b">Clip Layer</ion-option>
    <ion-option value="b">None</ion-option>
  </ion-select>
</ion-item>
</code>```

See the docs here.

Body:
I would like to know the standard way to build something like this (see Manage Labels entry in the picture):

Does it look like this?

<ion-list>
  <button ion-item (click)="selectLabelsOption()">
    Manage labels

{{selectedLabelsOption}}

  </button>
<ion-list>

Then when you click on the row, an alert is displayed like this:

How do you achieve this?

With an alert controller that contains a cancel button and a handler on each radio button?

Or is there another component for this?

Body:
You can use ion-select:

<ion-item>
  <ion-label>Chose Assist App</ion-label>
  <ion-select [(ngModel)]="choice">
    <ion-option value="a">Google App</ion-option>
    <ion-option value="b">Clip Layer</ion-option>
    <ion-option value="b">None</ion-option>
  </ion-select>
</ion-item>

See the docs here.


问:
asp pages and paypal button
I have an asp.net page in 3.5 that I have a pay pal button on but when I click on the button it just refreshes the page.  I think I need to encapsulate the paypal button in something so it is not trigging the refresh but goes to pay pal.

Anyone know a solution?  Can I use an updatePanel or iframe?

答: I would recommend you to use the PayPal Developer Toolkit for this. They're having a lot of good code samples and how to implement PayPal the best in your ASP.NET page.</p>

ContentLicense: CC BY-SA 2.5

Title: asp pages and paypal button


问:
How to limit 1 request at a time per client?
Unlike ngx_http_limit_req_module, I'm looking for a way to limit 1 request at a time per IP. In other words, if the previous request hasn't been responded to yet by the upstream application server, Nginx should 444 or 429 any further requests.

Intuition says that this would save memory compared to ngx_http_limit_req_module since there are no counters to increment.

Under certain circumstance (ex. bots, brute-force attacks, etc.), the upstream application server may choose to deliberately hold the request for a penalty of eg. 10 seconds or 10 minutes - but if Nginx still allows users to make requests in parallel, then the penalty is simply a wall that attackers can walk around.

答:
you can use ngx_http_limit_conn

but due of NAT usage in almost all ISP in the world you may face some problem


问:
Spring Data flow server - RDBMS
We developing a service and the target datastore for my service is Cassandra. I want to use spring data flow for ingesting feed. As data flow server requires RDBMS to keep track of workflow, i am forced to choose an RDBMS (eg:postgres) and need to provision it for SDFS. My question is that should DB(used by SDFS) be highly available & scalable to keep my service up/running on target runtime(eg: kubernetes)?</p>

答: Dataflow usage of DB is very light. It does not mean you should not provide a high available DB in production though. As far as it concerns to scaling concerns it's very light on accessing the DB so you don't need to worry about it being a burden on it. It only uses db to store metadata not during the ingestion of data over the streams</p>

Title: Spring Data flow server - RDBMS


问:
Lucene Taxonomy Writer Overflowing?
I have a Lucene index with over 120 million records in it and it has been working smoothly and quickly up to this point. However, today I started receiving:

```<code>java.lang.ArrayIndexOutOfBoundsException: -65536
lemur   at org.apache.lucene.util.ByteBlockPool.setBytesRef(ByteBlockPool.java:308)
lemur   at org.apache.lucene.util.BytesRefHash.equals(BytesRefHash.java:183)
lemur   at org.apache.lucene.util.BytesRefHash.findHash(BytesRefHash.java:330)
lemur   at org.apache.lucene.util.BytesRefHash.find(BytesRefHash.java:319)
lemur   at org.apache.lucene.facet.taxonomy.writercache.UTF8TaxonomyWriterCache.get(UTF8TaxonomyWriterCache.java:65)
lemur   at org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter.addCategory(DirectoryTaxonomyWriter.java:411)
lemur   at org.apache.lucene.facet.FacetsConfig.processFacetFields(FacetsConfig.java:322)
lemur   at org.apache.lucene.facet.FacetsConfig.build(FacetsConfig.java:285)
</code>```

I don't know if this is due to memory issues, the 22gig index, or something else, but digging through this trace it has something to do with the taxonomy writer cache system.  I've validated that this is not consistently happening with the same record, but seems like some sort of memory overflow issue.  Unfortunately, I have no idea what to do from here or if I'm even on the right track of understanding the actual problem.

答: After some additional digging I was able to figure out that UTF8TaxonomyWriterCache is not a good caching mechanism for big data. After switching to using LruTaxonomyWriterCache everything is working smoothly again.

Title: Lucene Taxonomy Writer Overflowing?

Body:
I have a Lucene index with over 120 million records in it and it has been working smoothly and quickly up to this point. However, today I started receiving:

java.lang.ArrayIndexOutOfBoundsException: -65536
lemur   at org.apache.lucene.util.ByteBlockPool.setBytesRef(ByteBlockPool.java:308)
lemur   at org.apache.lucene.util.BytesRefHash.equals(BytesRefHash.java:183)
lemur   at org.apache.lucene.util.BytesRefHash.findHash(BytesRefHash.java:330)
lemur   at org.apache.lucene.util.BytesRefHash.find(BytesRefHash.java:319)
lemur   at org.apache.lucene.facet.taxonomy.writercache.UTF8TaxonomyWriterCache.get(UTF8TaxonomyWriterCache.java:65)
lemur   at org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter.addCategory(DirectoryTaxonomyWriter.java:411)
lemur   at org.apache.lucene.facet.FacetsConfig.processFacetFields(FacetsConfig.java:322)
lemur   at org.apache.lucene.facet.FacetsConfig.build(FacetsConfig.java:285)

I don't know if this is due to memory issues, the 22gig index, or something else, but digging through this trace it has something to do with the taxonomy writer cache system.  I've validated that this is not consistently happening with the same record, but seems like some sort of memory overflow issue.  Unfortunately, I have no idea what to do from here or if I'm even on the right track of understanding the actual problem.


答: It looks like the problem is that you are assuming that obj[i] is a pointer to a type T, but it actually is an object of type T. obj is a pointer to the first allocated T object, obj[i] it the T object at address obj + i*sizeof(T)</p>

Title: Error C2679 binary '=': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)


问:
MongoDB - finding common value count between a set of documents
I have the documents in the with the two fields and I want to find common value count between a same set (category) of rows:  e.g.

Current data look something like this (assume in Json format):

I need an output like this:

Will be grateful for any guidance/pointers. Thanks

答:
First, get your data in the form of an array of objects. Then, we can use the following algorithm to get what you need:

Get the unique categories ["Music", "Film", "History", "Science"]

Get the combinations of those categories [["Music", "Film"], ["Music", "History"], ["Music", "Science"], ["Film", "History"], ...]

Create a mapping of category name to the books that are contained in that category. We can use a Set to ensure that the values are unique. The map will have the structure like {"Music": Set("A", "B"), "Film": Set("A", "B", "C"), "History": Set("C", "B"), "Science": Set("C")}

Use the objects and arrays that you just created to find the duplicates between the combinations.

When all is said and done, you'll have an array that has the following structure: [ [cat1, cat2, [bookInCommon1, bookInCommon2]], [cat1, cat3, [bookInCommon1, bookInCommon2]], ...]

Run the code below to see it in action. mongoData holds the data that is fetched from Mongo.

const mongoData = [{
    category: "Music",
    book: "A"
}, {
    category: "Music",
    book: "B"
},{
    category: "Music",
    book: "A"
},{
    category: "Film",
    book: "A"
},{
    category: "Film",
    book: "A"
},{
    category: "Film",
    book: "B"
},{
    category: "Film",
    book: "C"
},{
    category: "Film",
    book: "C"
},{
    category: "Film",
    book: "A"
},{
    category: "History",
    book: "C"
},{
    category: "History",
    book: "C"
},{
    category: "History",
    book: "B"
},{
    category: "History",
    book: "B"
},{
    category: "Science",
    book: "C"
},{
    category: "Science",
    book: "C"
},{
    category: "Science",
    book: "C"
}];

// Step 1: Get the categories
const categories = Array.from(new Set(mongoData.map(x => x.category)));

// Step 2: Get combinations of those categories
const combos = [];
for(let i = 0; i < categories.length - 1; i++) {

    let outerCat = categories[i];

    for(let j = i + 1; j < categories.length; j++) {

        let innerCat = categories[j];

        combos.push([
            outerCat,
            innerCat
        ]);
    }
}

// Step 3: Map the categories to the books that they contain
const catBooks = mongoData.reduce((map, entry) => {

    map[entry.category] = map[entry.category] || new Set();
    map[entry.category] = map[entry.category].add(entry.book);

    return map;

}, {});

// Step 4: Get the duplicate books for each combo
combos.forEach((combo, index) => {

    const cat1 = combo[0];
    const cat2 = combo[1];

    const cat1BooksArr = Array.from(catBooks[cat1]);
    const cat2BooksSet = catBooks[cat2];

    const dupes = cat1BooksArr.filter(book => {
        return cat2BooksSet.has(book);
    });

    combos[index].push(dupes); // push into combos array
});

// Done! Your combos array contains arrays that look like this: [cat1, cat2, [dupes]]
combos.forEach(combo => {
    console.log("Combo: " + combo[0] + ", " + combo[1]);
    console.log("\tNumber of dupes: " + combo[2].length);
});```


问:
opendialog.onhint crash
I have checked 100% I am closing all handles on a file I recently created. But when I call "opendialog.execute;" the dialog pop up as usual but on the mouse over hint of a recently created file the entire thing crashes with a out of bounds error.

I know this is not any of my out of bounds as if I open the file without causing a (onhint) event there is no problem and hardcoding a list of filenames for testing showed that there was nothing wrong with opening or saving a file. Its purely on the onhint event of the open dialog. Like I said if I am quick or I use arrow keys there is nothing wrong with my program.

Whats more interesting is that it doesnt even happen 100% of the time about 70% which has led to me thinking I have fixed it several time if not only for a short amount of time. Does anyone know what could be happening? And if not how can I disable the onhint event?

as aked for the code not that helps at all

```<code>OpenDialog.execute;    // crashes here
if fileexists(form1.OpenDialog.FileName) then
  form1.Address.Text:=form1.OpenDialog.FileName;
</code>```

and the error
link text

EDIT: ok i have some new information a new instance of opendialog still has the same issues. and more interestingly i seem to have solved the 30% issue its on hint of a file with a double tag for example "test.jpg.enc" the thing is its fine with it the first time it runs, and it only crashes on hint of these encoded files, but only if i have encoded that file white the applicatuion has benn open. for example if i encode it,, then try to decode and it crashes.. i can run it again and decode it fine,, but there is no problem with decoding and then encoding in one instance of the aplication.

答:
Two things:

Compile your application with Debug DCU's (Project / Options / Use Debug DCU's - then do a full build) and then see where the exception is occurring.  This will give you some more information when and exception is occurring in vcl/rtl code.  Post us the full error message and where in what unit it failed.

Second, and probably more importantly, is how the file behaves outside your application.  You suggest it fails about 30% of the time, so every time after you save the file, browse to it in a regular explorer window and mouse over it there and see if the hint displays fine.  Then open it in notepad.  If both of those work, and then it fails in your application that would be interesting.

Also, when you are posting a follow up question to a previous question it is helpful if you link to the previous question so we can see what you previously tried.

Gook luck!

OwnerDisplayName: Arthur

Title: opendialog.onhint crash

Body:
I have checked 100% I am closing all handles on a file I recently created. But when I call "opendialog.execute;" the dialog pop up as usual but on the mouse over hint of a recently created file the entire thing crashes with a out of bounds error.

I know this is not any of my out of bounds as if I open the file without causing a (onhint) event there is no problem and hardcoding a list of filenames for testing showed that there was nothing wrong with opening or saving a file. Its purely on the onhint event of the open dialog. Like I said if I am quick or I use arrow keys there is nothing wrong with my program.

Whats more interesting is that it doesnt even happen 100% of the time about 70% which has led to me thinking I have fixed it several time if not only for a short amount of time. Does anyone know what could be happening? And if not how can I disable the onhint event?

as aked for the code not that helps at all

OpenDialog.execute;    // crashes here
if fileexists(form1.OpenDialog.FileName) then
  form1.Address.Text:=form1.OpenDialog.FileName;

and the error
link text

EDIT: ok i have some new information a new instance of opendialog still has the same issues. and more interestingly i seem to have solved the 30% issue its on hint of a file with a double tag for example "test.jpg.enc" the thing is its fine with it the first time it runs, and it only crashes on hint of these encoded files, but only if i have encoded that file white the applicatuion has benn open. for example if i encode it,, then try to decode and it crashes.. i can run it again and decode it fine,, but there is no problem with decoding and then encoding in one instance of the aplication.

LastEditorDisplayName: Arthur

OwnerDisplayName: Jim McKeeth


问:
How to pass the dropdown and text value to email subject line using Javascript
Need your urgent help

I have one HTML page with 2 text box, 1 dropdown and 1 button, on button click I want to open the email(as currently I am doing with javascript) with subject line as whatever is selected in the drop down and whatever is written in text box.

```<code><body>
<form id='sampleform' method='post' action='' >
   Emp Number: <input type='text' name='empnum' />

   </p>

   <p>
       Unit Name: <input type='text' name='unit' />
   </p>
   <p>
       Type of subscription you want:
   <p>
       <select name="type">
           <option value="standard">Standard - Free</option>
           <option value="prof">Professional - Paid</option>
       </select>
   </p>
   </p>
   <p>
      <input type='submit' name='Submit' value='Submit' onClick="parent.location='mailto:er.saurav1@gmail.com?subject=Thanks for writing &body=Hi,%0A%0CThanks for writing. We will get back to you soon. %0A%0C%0D%0AThanks and Regards,%0A%0CSaurav Kumar%0A%0C%0A%0CFor further assistance call 81111'">
   </p>
</form>

</body>
</code>```

I want when my email will open the subject line output should be:

Emp Num | Unit Name | Selected value
  from the drop down

答:
I re-edited the post from Srikanth Rayabhagi. Now it should work

```<code><script type='text/javascript'>
    function sendMail(){
        var form = document.forms.sampleform;
        var empnum = form.empnum.value;
        var uname = form.unit.value;
        var ddvalue = form.type.options[form.type.selectedIndex].value;
        var subj = empnum + '|' + uname + '|' + ddvalue;
        parent.location='mailto:abc@gmail.com?subject=' + encodeURIComponent(subj) +'&body=Thanks for writing. We will get back to you soon';
    }
</script>
</code>```

Just call sendMail() within any Button onClick event.

hth

Body:
Need your urgent help

I have one HTML page with 2 text box, 1 dropdown and 1 button, on button click I want to open the email(as currently I am doing with javascript) with subject line as whatever is selected in the drop down and whatever is written in text box.

<form id='sampleform' method='post' action='' >
   Emp Number: <input type='text' name='empnum' />

       Unit Name: <input type='text' name='unit' />

       Type of subscription you want:

       <select name="type">
           <option value="standard">Standard - Free</option>
           <option value="prof">Professional - Paid</option>
       </select>

      <input type='submit' name='Submit' value='Submit' onClick="parent.location='mailto:er.saurav1@gmail.com?subject=Thanks for writing &body=Hi,%0A%0CThanks for writing. We will get back to you soon. %0A%0C%0D%0AThanks and Regards,%0A%0CSaurav Kumar%0A%0C%0A%0CFor further assistance call 81111'">

</form>

I want when my email will open the subject line output should be:

Emp Num | Unit Name | Selected value
  from the drop down

Body:
I re-edited the post from Srikanth Rayabhagi. Now it should work

<script type='text/javascript'>
    function sendMail(){
        var form = document.forms.sampleform;
        var empnum = form.empnum.value;
        var uname = form.unit.value;
        var ddvalue = form.type.options[form.type.selectedIndex].value;
        var subj = empnum + '|' + uname + '|' + ddvalue;
        parent.location='mailto:abc@gmail.com?subject=' + encodeURIComponent(subj) +'&body=Thanks for writing. We will get back to you soon';
    }
</script>

Just call sendMail() within any Button onClick event.

hth


问:
AWS Classic Load Balancer End-to-End Encryption
Is it possible to configure an AWS Classic Balancer to do something like this:

Client  <-- SSL (Signed Certificate) --> ELB <-- SSL (Self-Signed Certificate) --> EC2

Looking at listener configurations, it looks like there is a one to one relationship between the listener and the certificate it uses.

If anyone knows how I could achieve this, being pointed to some documentation would also be helpful.

答:
You can create a load balancer that listens on both the HTTP (80) and
  HTTPS (443) ports. If you specify that the HTTPS listener sends
  requests to the instances on port 80, the load balancer terminates the
  requests and communication from the load balancer to the instances is
  not encrypted. If the HTTPS listener sends requests to the instances
  on port 443, communication from the load balancer to the instances is
  encrypted.

Create a Classic Load Balancer with an HTTPS Listener


问:
using stack to index multiple columns by a single column
I'm trying to take a format starting with:

```<code> Global_Code | Retailer_X_Code | Retailer_Y_Code | Info | ...
  -----------------------------------------------------------
 'A'              'a'              'a_a'            1     ...
 'B'              'b'              'b_b'            2     ...
 ...              ...               ...            ...    ...
</code>```

And stack the Retailer_X_Code and Retailer_Y_Code into a single Retailer_Name column, indexed by Global_Code. I'd also like to keep other columns in the row such as Info.

So starting off with stack(), I get:

```<code> stacked_df = mapping_df.stack()

 ========

 Global_Code          'A'
 Retailer_X_Code      'a'
 Retailer_Y_Code      'a_a'
 Info                 1
 ...more columns

 Global_Code          'B'
 Retailer_X_Code      'b'
 Retailer_Y_Code      'b_b'
 Info                 2
 ...more columns
</code>```

Great, now I don't all the columns, and want Retailer_X_Code and Retailer_Y_Code to be under one column. So I select these columns, organized by Global_Code:

```<code>stacked_df = mapping_df[['Global_Code', 'Retailer_X_Code', 'Retailer_Y_Code']].set_index('Global_Code').stack().reset_index().rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Code'})

========

Global_Code |  Retailer_Name   | Retailer_Code
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'
</code>```

So far so good. Now I want to grab Info and include is as part of the stacked column result. The desired output should look like this:

```<code>Global_Code |  Retailer_Name   | Retailer_Code | Info
------------------------------------------------------
'A'           'Retailer_X_Code'   'a'            1
'A'           'Retailer_Y_Code'   'a_a'          1
...           ...                 ...           ...
'B'           'Retailer_X_Code'   'b'            2
'B'           'Retailer_Y_Code'   'b_b'          2
</code>```

But if I add Info as part of the selected columns, then rename it to Product_Info, it doesn't add the Info column.

Instead, it inserts Info values incorrectly under Retailer_Name.

```<code>stacked_df = mapping_df[['Global_Code', 'Retailer_X_Code', 'Retailer_Y_Code', 'Info']].set_index('Global_Code').stack().reset_index().rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Code', 1: 'Product_Info'})

========

Global_Code |  Retailer_Name   | Retailer_Code
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
'A'           'Info'              1
'A'           'Info'              1
'A'           'Info'              1
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'
'B'           'Info'              2
</code>```

The above without column renaming, .rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Pack'}), gives me:

```<code>Global_Code |  level_1          | 0
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
'A'           'Info'              1
'A'           'Info'              1
'A'           'Info'              1
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'
'B'           'Info'              2
</code>```

答:
We using wide_to_long..:-), if you want to change the column name you can do , rename..

```<code>pd.wide_to_long(df,stubnames='Retailer',i=['Global_Code','Info'],j='Retailer_Name',sep='_',suffix='\\w+').reset_index()
Out[155]:
  Global_Code  Info Retailer_Name Retailer
0         'A'     1        X_Code      'a'
1         'A'     1        Y_Code    'a_a'
2         'B'     2        X_Code      'b'
3         'B'     2        Y_Code    'b_b'
</code>```

Body:
I'm trying to take a format starting with:

 Global_Code | Retailer_X_Code | Retailer_Y_Code | Info | ...
  -----------------------------------------------------------
 'A'              'a'              'a_a'            1     ...
 'B'              'b'              'b_b'            2     ...
 ...              ...               ...            ...    ...

And stack the Retailer_X_Code and Retailer_Y_Code into a single Retailer_Name column, indexed by Global_Code. I'd also like to keep other columns in the row such as Info.

So starting off with stack(), I get:

 stacked_df = mapping_df.stack()

 ========

 Global_Code          'A'
 Retailer_X_Code      'a'
 Retailer_Y_Code      'a_a'
 Info                 1
 ...more columns

 Global_Code          'B'
 Retailer_X_Code      'b'
 Retailer_Y_Code      'b_b'
 Info                 2
 ...more columns

Great, now I don't all the columns, and want Retailer_X_Code and Retailer_Y_Code to be under one column. So I select these columns, organized by Global_Code:

stacked_df = mapping_df[['Global_Code', 'Retailer_X_Code', 'Retailer_Y_Code']].set_index('Global_Code').stack().reset_index().rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Code'})

========

Global_Code |  Retailer_Name   | Retailer_Code
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'

So far so good. Now I want to grab Info and include is as part of the stacked column result. The desired output should look like this:

Global_Code |  Retailer_Name   | Retailer_Code | Info
------------------------------------------------------
'A'           'Retailer_X_Code'   'a'            1
'A'           'Retailer_Y_Code'   'a_a'          1
...           ...                 ...           ...
'B'           'Retailer_X_Code'   'b'            2
'B'           'Retailer_Y_Code'   'b_b'          2

But if I add Info as part of the selected columns, then rename it to Product_Info, it doesn't add the Info column.

Instead, it inserts Info values incorrectly under Retailer_Name.

stacked_df = mapping_df[['Global_Code', 'Retailer_X_Code', 'Retailer_Y_Code', 'Info']].set_index('Global_Code').stack().reset_index().rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Code', 1: 'Product_Info'})

========

Global_Code |  Retailer_Name   | Retailer_Code
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
'A'           'Info'              1
'A'           'Info'              1
'A'           'Info'              1
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'
'B'           'Info'              2

The above without column renaming, .rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Pack'}), gives me:

Global_Code |  level_1          | 0
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
'A'           'Info'              1
'A'           'Info'              1
'A'           'Info'              1
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'
'B'           'Info'              2

Body:
We using wide_to_long..:-), if you want to change the column name you can do , rename..

pd.wide_to_long(df,stubnames='Retailer',i=['Global_Code','Info'],j='Retailer_Name',sep='_',suffix='\\w+').reset_index()
Out[155]:
  Global_Code  Info Retailer_Name Retailer
0         'A'     1        X_Code      'a'
1         'A'     1        Y_Code    'a_a'
2         'B'     2        X_Code      'b'
3         'B'     2        Y_Code    'b_b'


问:
length of value changes (Java)
I am currently writing a code that uses hex values. For some reason, during the program, the hex values change from 32-bit long values to 64 bit long values. Can anyone provide insight as to why this is happening?

```<code>     final private long feedbackValue = 0x87654321;
     private long state;

public void initialize(long initialValue) {
    int count = 0;
    state = feedbackValue ^ initialValue;

    System.out.println("State "+count+":"+ String.format("0x%08X",state));
    while (count < 8) {
        update();

        count++;
        System.out.println("State "+count+":"+ String.format("0x%08x",state));
    }

}//end initialize method

private void update() {
    if ((state & 1) == 0) {
        state = state >>> 1;

    } else {
        state = (state >>> 1)^feedbackValue;

    }

}//end update method
</code>```

When initialValue = 0xffffffff, here are the results:

```<code>    State 0:0x789ABCDE
    State 1:0x3c4d5e6f
    State 2:0xffffffff9943ec16
    State 3:0x7fffffffcca1f60b
    State 4:0xc00000006135b824
    State 5:0x60000000309adc12
    State 6:0x30000000184d6e09
    State 7:0xe7ffffff8b43f425
    State 8:0x8c00000042c4b933
</code>```

答: Place an "L" at the end of feedbackValue and initialValue variables so that it is read as a long.</p>

Title: length of value changes (Java)

Body:
I am currently writing a code that uses hex values. For some reason, during the program, the hex values change from 32-bit long values to 64 bit long values. Can anyone provide insight as to why this is happening?

     final private long feedbackValue = 0x87654321;
     private long state;

public void initialize(long initialValue) {
    int count = 0;
    state = feedbackValue ^ initialValue;

    System.out.println("State "+count+":"+ String.format("0x%08X",state));
    while (count < 8) {
        update();

        count++;
        System.out.println("State "+count+":"+ String.format("0x%08x",state));
    }

}//end initialize method

private void update() {
    if ((state & 1) == 0) {
        state = state >>> 1;

    } else {
        state = (state >>> 1)^feedbackValue;

    }

}//end update method

When initialValue = 0xffffffff, here are the results:

    State 0:0x789ABCDE
    State 1:0x3c4d5e6f
    State 2:0xffffffff9943ec16
    State 3:0x7fffffffcca1f60b
    State 4:0xc00000006135b824
    State 5:0x60000000309adc12
    State 6:0x30000000184d6e09
    State 7:0xe7ffffff8b43f425
    State 8:0x8c00000042c4b933


问:
In Rails, how can I stub a websocket message for a test?
The application is using Minitest on Rails 4 with Capybara.

I'd like to write an integration or feature test that stubs a websocket connection (the application uses Faye as a client) to return a specific message (like I'm used to doing with Webmock).

Is this possible? If so, can you provide an example? My research has not turned up any examples.

答:
Your research hasn't shown up any examples because it's not really what you're supposed to be doing in feature tests. Feature tests are supposed to be end-to-end black box tests where you configure the data as required for the app to generate the desired results and then all interaction is done via the browser (no mocking/stubbing which technically alter your apps code).  Additionally when connections between the browser and a 3rd party service are involved there is nowhere in your app where you can mock it.

It may be possible to stub a websocket connection from the browser with  a programmable proxy like puffing-billy, however it's generally cleaner to produce a small fake version of the 3rd party service for testing purposes (sinatra app, etc) and point the browser at that rather than the original service when you need to craft custom responses. Additionally, there are a lot of fakes already out there, depending on what service you are using (fake-stripe, fake-s3, etc), which may provide the functionality you're looking for.


问:
static if in plain c++?
Problem in short:

How could one implement static if functionality, proposed in c++11, in plain c++ ?

History and original problem:

Recently I came up with a problem like this. I need a class Sender with an interface like

```<code>class Sender
{
   void sendMessage( ... );
   void sendRequest( ... );
   void sendFile( ... );
   // lots of different send methods, not important actually
}
</code>```

In some cases I will need to create a DoubleSender, i.e. an instance of this class, which would call its methods twice, i.e. when calling, let's say, a sendMessage(...) method, the same message has to be sent twice.

My solutions:

First approach:

Have an isDouble member, and in the end of each method call make a check

```<code>sendMessage(...) { ... if( isDouble ) { sendMessage( ... ); }
</code>```

Well, I don't want this, because actually I will need double posting very recently, and this part of code in time-critical section will be 98% passive.

Second approach:

Inherit a class DoubleSender from Sender, and implement its methods like:

```<code>void DoubleSender::sendMessage( ... )
{
   Sender::sendMessage(...);
   Sender::sendMessage(...);
}
</code>```

Well, this is acceptable, but takes much space of unpleasant code (really much, because there are lots of different send.. methods.

Third approach:

Imagine that I am using c++11 :). Then I can make this class generic and produce the necessary part of code according to tempalte argument using static if:

```<code>enum SenderType { Single, Double };
template<SenderType T>
class Sender
{
   void sendMessage(...)
   {
      // do stuff
      static if ( T == Single )
      {
         sendMessage(...);
      }
   }
};
</code>```

This is shorter, easier to read than previous solutions, does not generate additional code and... it's c++11, which I unfortunately cannot use in my work.

So, here is where I came to my question - how can I implement static if analog in c++ ?
 Also, I would appreciate any other suggestions about how to solve my original problem.

Thanks in advance.

答:
```<code>std::string a("hello world");
// bool a = true;
if(std::is_same<std::string, decltype(a)>::value) {
    std::string &la = *(std::string*)&a;
    std::cout << "std::string " << la.c_str() << std::endl;
} else {
    bool &la = *(bool*)&a;
    std::cout << "other type" << std::endl;
}
</code>```

Title: static if in plain c++?

Body:
Problem in short:

How could one implement static if functionality, proposed in c++11, in plain c++ ?

History and original problem:

Recently I came up with a problem like this. I need a class Sender with an interface like

class Sender
{
   void sendMessage( ... );
   void sendRequest( ... );
   void sendFile( ... );
   // lots of different send methods, not important actually
}

In some cases I will need to create a DoubleSender, i.e. an instance of this class, which would call its methods twice, i.e. when calling, let's say, a sendMessage(...) method, the same message has to be sent twice.

My solutions:

First approach:

Have an isDouble member, and in the end of each method call make a check

sendMessage(...) { ... if( isDouble ) { sendMessage( ... ); }

Well, I don't want this, because actually I will need double posting very recently, and this part of code in time-critical section will be 98% passive.

Second approach:

Inherit a class DoubleSender from Sender, and implement its methods like:

void DoubleSender::sendMessage( ... )
{
   Sender::sendMessage(...);
   Sender::sendMessage(...);
}

Well, this is acceptable, but takes much space of unpleasant code (really much, because there are lots of different send.. methods.

Third approach:

Imagine that I am using c++11 :). Then I can make this class generic and produce the necessary part of code according to tempalte argument using static if:

enum SenderType { Single, Double };
template<SenderType T>
class Sender
{
   void sendMessage(...)
   {
      // do stuff
      static if ( T == Single )
      {
         sendMessage(...);
      }
   }
};

This is shorter, easier to read than previous solutions, does not generate additional code and... it's c++11, which I unfortunately cannot use in my work.

So, here is where I came to my question - how can I implement static if analog in c++ ?
 Also, I would appreciate any other suggestions about how to solve my original problem.

Thanks in advance.


问:
Vector of object pointers returns odd values
I have a task to create an object Stos which would feature a heap of objects Obiekt, to which I could add things as I please.

In order to make the program better support dynamic arrays I decided to use a Vector.
The whole implementation seems to run perfectly, the returned value is completely off.
Here is an example with code:

```<code>class Obiekt {
private:
    int id;

public:
    Obiekt::Obiekt(int i) {
        id = i;
    }

    void Obiekt::display() {
        cout << "This object has id of: " << id << endl;
    }
};

class Stos {
private:
    vector < Obiekt* > stos;
public:
    Stos::Stos(Obiekt n) {
        add(n);
    }

    void Stos::add(Obiekt n) {
        stos.push_back(&n);
    }

    void Stos::display() {
        cout << endl << "===HEAP DISPLAY===" << endl;
        for (int i = 0; i < stos.size(); i++) {
            stos[i]->display();
        }
    }
};

void Zad1()
{
    Obiekt obj1(5);
    Obiekt obj2(23);

    Stos s1(obj1);
    s1.add(obj2);
    s1.display();

    getchar();
}
</code>```

And the outcome being:

===HEAP DISPLAY===

This object has id of: -858993460

This object has id of:9805925

I'm not a cpp expert, and believe the issue is related to the stos.push_back(&n) portion, but I can't catch the moment the id gets so distorted.

It's probably a noob question, so sorry for that on start.

Any help would be amazing.

答:
I'm reluctant to assert that the objects exist at the time display is called.

Problem(s)

According to GCC's implementation they don't.
They fall out of scope and are immediately destructed. Give "Obiekt" a non-trivial destructor and this behavior becomes obvious:

```<code>~Obiekt(){std::cout << "Bye from: " << it << std::endl;}
</code>```

Secondarily, note that you shouldn't specify the class membership for functions defined within the class itself (no class_name::function_name(parameters), just function_name(parameters) )

Possible Fix

You (might) want to changing "Stos" such that:

```<code>Stos(Obiekt &n) {add(n);}
void add(Obiekt &n) {stos.push_back(&n);}
</code>```

Body:
I have a task to create an object Stos which would feature a heap of objects Obiekt, to which I could add things as I please.

In order to make the program better support dynamic arrays I decided to use a Vector.
The whole implementation seems to run perfectly, the returned value is completely off.
Here is an example with code:

class Obiekt {
private:
    int id;

public:
    Obiekt::Obiekt(int i) {
        id = i;
    }

    void Obiekt::display() {
        cout << "This object has id of: " << id << endl;
    }
};

class Stos {
private:
    vector < Obiekt* > stos;
public:
    Stos::Stos(Obiekt n) {
        add(n);
    }

    void Stos::add(Obiekt n) {
        stos.push_back(&n);
    }

    void Stos::display() {
        cout << endl << "===HEAP DISPLAY===" << endl;
        for (int i = 0; i < stos.size(); i++) {
            stos[i]->display();
        }
    }
};

void Zad1()
{
    Obiekt obj1(5);
    Obiekt obj2(23);

    Stos s1(obj1);
    s1.add(obj2);
    s1.display();

    getchar();
}

And the outcome being:

===HEAP DISPLAY===

This object has id of: -858993460

This object has id of:9805925

I'm not a cpp expert, and believe the issue is related to the stos.push_back(&n) portion, but I can't catch the moment the id gets so distorted.

It's probably a noob question, so sorry for that on start.

Any help would be amazing.

Body:
I'm reluctant to assert that the objects exist at the time display is called.

Problem(s)

According to GCC's implementation they don't.
They fall out of scope and are immediately destructed. Give "Obiekt" a non-trivial destructor and this behavior becomes obvious:

~Obiekt(){std::cout << "Bye from: " << it << std::endl;}

Secondarily, note that you shouldn't specify the class membership for functions defined within the class itself (no class_name::function_name(parameters), just function_name(parameters) )

Possible Fix

You (might) want to changing "Stos" such that:

Stos(Obiekt &n) {add(n);}
void add(Obiekt &n) {stos.push_back(&n);}


问:
Formatting of sequential if statements with similar returns (C++)

In my program, I use the map map<name,labscores> to store pairs of classes that store data about students and their grades. The overloaded operator< returns true if the mean of the first is lower than the second, but if they're equal, it then checks which has a smaller median, then which was a smaller name. The data_t class contains an iterator of the map which points to a specific pair.

```<code>bool operator<(const data_t &d){
    if(it->second.get_mean() < d.it->second.get_mean())
        return true;
    else if((it->second.get_mean() == d.it->second.get_mean()) && (it->second.get_median() < d.it->second.get_median()))
        return true;
    else if((it->second.get_mean() == d.it->second.get_mean()) && (it->second.get_median() == d.it->second.get_median()) && (it->first < d.it->first))
        return true;
    else
        return false;
}
</code>```

The above code works, but I'm trying to learn more efficient ways of coding, and I wanted to know if there was a simpler way of doing this or if there was a command that can help.

答:
I consider the if ... return ... else to be messy coding since the else is totally superfluous.

You can neaten up your code to be more readable by applying that guideline, and with some judicious variable usage, something like:

```<code>bool operator<(const data_t &d) {
    // Check means first.

    auto myMean = it->second.get_mean();
    auto otherMean = d.it->second.get_mean();
    if(myMean < otherMean) return true;
    if(myMean > otherMean) return false;

    // Means are equal, medians comes into play.

    auto myMedian = it->second.get_median();
    auto otherMedian = d.it->second.get_median();
    if (myMedian < otherMedian) return true;
    if (myMedian > otherMedian) return false;

    // Means and medians are equal, use the names.

    return (it->first < d.it->first);
}
</code>```

Body:
In my program, I use the map map<name,labscores> to store pairs of classes that store data about students and their grades. The overloaded operator< returns true if the mean of the first is lower than the second, but if they're equal, it then checks which has a smaller median, then which was a smaller name. The data_t class contains an iterator of the map which points to a specific pair.

bool operator<(const data_t &d){
    if(it->second.get_mean() < d.it->second.get_mean())
        return true;
    else if((it->second.get_mean() == d.it->second.get_mean()) && (it->second.get_median() < d.it->second.get_median()))
        return true;
    else if((it->second.get_mean() == d.it->second.get_mean()) && (it->second.get_median() == d.it->second.get_median()) && (it->first < d.it->first))
        return true;
    else
        return false;
}

The above code works, but I'm trying to learn more efficient ways of coding, and I wanted to know if there was a simpler way of doing this or if there was a command that can help.

Body:
I consider the if ... return ... else to be messy coding since the else is totally superfluous.

You can neaten up your code to be more readable by applying that guideline, and with some judicious variable usage, something like:

bool operator<(const data_t &d) {
    // Check means first.

    auto myMean = it->second.get_mean();
    auto otherMean = d.it->second.get_mean();
    if(myMean < otherMean) return true;
    if(myMean > otherMean) return false;

    // Means are equal, medians comes into play.

    auto myMedian = it->second.get_median();
    auto otherMedian = d.it->second.get_median();
    if (myMedian < otherMedian) return true;
    if (myMedian > otherMedian) return false;

    // Means and medians are equal, use the names.

    return (it->first < d.it->first);
}


问:
Shiny image upload
Not certain why this simple code is not working. The goal is to upload an image from a device and view as shiny output. I keep getting an error,
*****Error: invalid filename argument*****</p>

```<code>library(jpeg)
library(shiny)
library(magick)
library(magrittr)

  ui <- fluidPage(

#-------------------------------------Header Panel--------------------------------------------------#

titlePanel('Invoice Recognition & Interpretation -IRI'),

#--------------------------------Sidebar : Image Upload---------------------------------------------#
sidebarLayout(

  sidebarPanel(
    fileInput(inputId = "file1",
              label = "Upload Invoice",
             accept = c('image/png', 'image/jpeg','image/jpg')
    ),

    tags$hr()

  ),

  mainPanel(

  imageOutput(outputId = "Invoice")

    )
)
)

server <- function(input, output) {

re1<-reactive({ input$file1})

output$Invoice<-renderImage({re1()})

 }
shinyApp(ui, server)
</code>```

答:
You are most of the way there, however, you need to understand that your fileInput returns a data frame and not just the path. Also, the renderImage is similar to an  and you need to assign the src.

```<code>library(shiny)

ui <- fluidPage(

  titlePanel('Invoice Recognition & Interpretation -IRI'),

  sidebarLayout(
    sidebarPanel(
      fileInput(
        inputId = "file1",
        label = "Upload Invoice",
        accept = c('image/png', 'image/jpeg','image/jpg')
      ),
      tags$hr()
    ),
    mainPanel(
      textOutput("filename"),
      imageOutput(outputId = "Invoice")
    )
  )
)

server <- function(input, output) {

  re1 <- reactive({gsub("\\\\", "/", input$file1$datapath)})

  output$Invoice <- renderImage({list(src = re1())})

}

shinyApp(ui, server)
</code>```

Title: Shiny image upload

Body:
Not certain why this simple code is not working. The goal is to upload an image from a device and view as shiny output. I keep getting an error,
*****Error: invalid filename argument*****

library(jpeg)
library(shiny)
library(magick)
library(magrittr)

  ui <- fluidPage(

#-------------------------------------Header Panel--------------------------------------------------#

titlePanel('Invoice Recognition & Interpretation -IRI'),

#--------------------------------Sidebar : Image Upload---------------------------------------------#
sidebarLayout(

  sidebarPanel(
    fileInput(inputId = "file1",
              label = "Upload Invoice",
             accept = c('image/png', 'image/jpeg','image/jpg')
    ),

    tags$hr()

  ),

  mainPanel(

  imageOutput(outputId = "Invoice")

    )
)
)

server <- function(input, output) {

re1<-reactive({ input$file1})

output$Invoice<-renderImage({re1()})

 }
shinyApp(ui, server)

Body:
You are most of the way there, however, you need to understand that your fileInput returns a data frame and not just the path. Also, the renderImage is similar to an <img> and you need to assign the src.

library(shiny)

ui <- fluidPage(

  titlePanel('Invoice Recognition & Interpretation -IRI'),

  sidebarLayout(
    sidebarPanel(
      fileInput(
        inputId = "file1",
        label = "Upload Invoice",
        accept = c('image/png', 'image/jpeg','image/jpg')
      ),
      tags$hr()
    ),
    mainPanel(
      textOutput("filename"),
      imageOutput(outputId = "Invoice")
    )
  )
)

server <- function(input, output) {

  re1 <- reactive({gsub("\\\\", "/", input$file1$datapath)})

  output$Invoice <- renderImage({list(src = re1())})

}

shinyApp(ui, server)


问:
Eclipse ECJ accepts this code, javac doesn't - who is right?
Consider the following returnsNull function and a call to it with a generic type:

```<code>public static <T> List<T> returnNull(Class<? extends T> clazz) {
    return null;
}

public static void main( String[] args )
{
    List<AtomicReference<?>> l = returnNull(AtomicReference.class);
}
</code>```

The Eclipse compiler, when set to Java 8, accepts it, but javac in Java 8 rejects it with:

```<code>incompatible types: cannot infer type-variable(s) T
    (argument mismatch; java.lang.Class<java.util.concurrent.atomic.AtomicReference> cannot be converted to java.lang.Class<? extends java.util.concurrent.atomic.AtomicReference<?>>)
</code>```

The underlying difference seems to be that given a two parameterized types P1<T> and P2<T>, Eclipse allows conversion from the outer type parameterized with the raw inner type: P1<P2> to the outer type parameterized with a lower bound of the of the inner-type with an unbounded wildcard like P1<? extends P2<?>>. javac doesn't.

This isn't just a theoretical musing: if this code was accepted it would solve my generics filtering problem.

Who is right?

答:
During applicability inference ECJ infers <T> to AtomicReference#RAW, which let's the signature of returnNull appear as

```<code>List<AtomicReference#RAW> returnNull(Class<? extends AtomicReference#RAW>)
</code>```

The exact steps being:

initial constraint:

⟨Class<AtomicReference#RAW> → Class<? extends T#0>⟩

reduced to:

⟨Class<AtomicReference#RAW> <: Class<? extends T#0>⟩

⟨AtomicReference#RAW <= ? extends T#0⟩

⟨AtomicReference#RAW <: T#0⟩

AtomicReference#RAW <: T#0

resolved to:

T#0 = AtomicReference#RAW

Now, there's no problem passing a value of type Class<AtomicReference#RAW> into that method.

(the suffix #RAW is an implementation specific denotation for raw types, reproduced here for clarity).

EDIT: Things look different during invocation type inference: By adding the target type into the mix we end up (during incorporation) with the following constraint:

⟨AtomicReference#RAW <: AtomicReference<?>⟩

This constraint should reduce to FALSE, but ecj reduces to TRUE. From this, rejecting the program seems to be the correct answer.

I filed bug 528970 for further investigation in ECJ.

There is some irony in this, because javac has a long standing bug whereby it wrongly assumes T#RAW <: T<X>. For compatibility reasons, ECJ explicitly copied this bug into many locations, but apparently in one particular code location it's the opposite: javac applies subtyping where ECJ checks for compatibility.

EDIT 2: One year later it seems that the bug in ECJ can only be fixed after JLS has been improved in and around JDK-8054721.

Body:
Consider the following returnsNull function and a call to it with a generic type:

public static <T> List<T> returnNull(Class<? extends T> clazz) {
    return null;
}

public static void main( String[] args )
{
    List<AtomicReference<?>> l = returnNull(AtomicReference.class);
}

The Eclipse compiler, when set to Java 8, accepts it, but javac in Java 8 rejects it with:

incompatible types: cannot infer type-variable(s) T
    (argument mismatch; java.lang.Class<java.util.concurrent.atomic.AtomicReference> cannot be converted to java.lang.Class<? extends java.util.concurrent.atomic.AtomicReference<?>>)

The underlying difference seems to be that given a two parameterized types P1<T> and P2<T>, Eclipse allows conversion from the outer type parameterized with the raw inner type: P1<P2> to the outer type parameterized with a lower bound of the of the inner-type with an unbounded wildcard like P1<? extends P2<?>>. javac doesn't.

This isn't just a theoretical musing: if this code was accepted it would solve my generics filtering problem.

Who is right?

Body:
During applicability inference ECJ infers <T> to AtomicReference#RAW, which let's the signature of returnNull appear as

List<AtomicReference#RAW> returnNull(Class<? extends AtomicReference#RAW>)

The exact steps being:

initial constraint:

⟨Class<AtomicReference#RAW> → Class<? extends T#0>⟩

reduced to:

⟨Class<AtomicReference#RAW> <: Class<? extends T#0>⟩

⟨AtomicReference#RAW <= ? extends T#0⟩

⟨AtomicReference#RAW <: T#0⟩

AtomicReference#RAW <: T#0

resolved to:

T#0 = AtomicReference#RAW

Now, there's no problem passing a value of type Class<AtomicReference#RAW> into that method.

(the suffix #RAW is an implementation specific denotation for raw types, reproduced here for clarity).

EDIT: Things look different during invocation type inference: By adding the target type into the mix we end up (during incorporation) with the following constraint:

⟨AtomicReference#RAW <: AtomicReference<?>⟩

This constraint should reduce to FALSE, but ecj reduces to TRUE. From this, rejecting the program seems to be the correct answer.

I filed bug 528970 for further investigation in ECJ.

There is some irony in this, because javac has a long standing bug whereby it wrongly assumes T#RAW <: T<X>. For compatibility reasons, ECJ explicitly copied this bug into many locations, but apparently in one particular code location it's the opposite: javac applies subtyping where ECJ checks for compatibility.

EDIT 2: One year later it seems that the bug in ECJ can only be fixed after JLS has been improved in and around JDK-8054721.

ContentLicense: CC BY-SA 4.0


问:
UISearchBar No Background Landscape Mode
I have the following snippet to remove the background from a UISearchBar:

```<code>for (UIView *subview in self.searchDisplayController.searchBar.subviews)
{
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
    {
        [subview removeFromSuperview];
        break;
    }
}
</code>```

However, if the device is rotated to landscape a black background appears behind the search bar. Any ideas how to fix it? I'm not exactly sure if this is undocumented.

Thanks!

答:
I just ran across this problem and found little help searching. Unfortunately, removing the feature was not an option so I had to figure it out. It seems as the the UISearchBar view has a background that goes black when you change orientation. So my code now looks like this:</p>

```<code>[searchBar setBackgroundColor:[UIColor clearColor]];
for (UIView *subview in searchBar.subviews)
{
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        [subview removeFromSuperview];
}
</code>```

Body:
I have the following snippet to remove the background from a UISearchBar:

for (UIView *subview in self.searchDisplayController.searchBar.subviews)
{
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
    {
        [subview removeFromSuperview];
        break;
    }
}

However, if the device is rotated to landscape a black background appears behind the search bar. Any ideas how to fix it? I'm not exactly sure if this is undocumented.

Thanks!

Body:
I just ran across this problem and found little help searching. Unfortunately, removing the feature was not an option so I had to figure it out. It seems as the the UISearchBar view has a background that goes black when you change orientation. So my code now looks like this:

[searchBar setBackgroundColor:[UIColor clearColor]];
for (UIView *subview in searchBar.subviews)
{
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        [subview removeFromSuperview];
}