问:
Multiple nested if in google sheets returning FALSE
I am trying to make a spreadsheet for my scouts.  I want to be able to put in their grade, and it to return their designated rank.  I have looked up how to use multiple IF statements, and how to use the IFS statement.  It either returns a #N/A or a FALSE whenever I put anything OTHER than the first statement.

This is the nested IF statement

=IF(J5="K","Lion", IF(J5="1","Tiger", IF(J5="2","Wolf", IF(J5="3","Bear", IF(J5="4","Webelos I", IF(J5="5","Webelos II"))))))

This is the IFS statement

=IFS(J4="K","Lion", J4="1","Tiger", J4="2","Wolf", J4="3","Bear", J4="4","Webelos I", J4="5","Webelos II")

It ONLY works right if I punch in K.  I do not get a proper response when I punch in 1, 2, etc.  What am I missing here?  I am having to do this in google sheets for others to be able to use.  I am getting the same or similar errors when I try it in excel as well.

答:
Try this:

```<code>=IF(J5="K","Lion", IF(J5=1,"Tiger", IF(J5=2,"Wolf", IF(J5=3,"Bear", IF(J5=4,"Webelos I", IF(J5=5,"Webelos II", 0))))))
</code>```

You were inputting the Integers as Strings.  Unless Excel is reading the numerical values as strings, your original formula will not work.

Body:
Try this:

=IF(J5="K","Lion", IF(J5=1,"Tiger", IF(J5=2,"Wolf", IF(J5=3,"Bear", IF(J5=4,"Webelos I", IF(J5=5,"Webelos II", 0))))))

You were inputting the Integers as Strings.  Unless Excel is reading the numerical values as strings, your original formula will not work.


来源: stackexchange

问:
how to prevent calling virtual function in constructor or desturctor?
Some C++ materials mention we can't call a virtual function inside ctor or dtor,

(

sorry ,I think it's better to change to

Some C++ materials mention we'd better not to  call a virtual function inside ctor or dtor,

)

but we may call them accidentally. Is there any way to prevent that?

For example:

```<code># include < iostream >
using namespace std;

class CAT
{
public:
    CAT(){ f();}
    virtual void f(){cout<<"void CAT:f()"<<std::endl;}
};

class SMALLCAT :public CAT
{
public:
    SMALLCAT():CAT()
    {
    }
    void f(){cout<<"void SMALLCAT:f()"<<std::endl;}
};

int main()
{
    SMALLCAT sc;

}
</code>```

output:

```<code>void CAT::f()  //not we expected!!!
</code>```

Thanks

答: You certainly CAN call a virtual function inside a ctor/dtor. The issue is that your vtable is set up in each constructor (and destructor), so your virtual function call will call the implementation of the class that is currently being set up. If that's what you want, cool. But then you may as well save yourself the vtable lookup and do a scoped function call.</p>

ContentLicense: CC BY-SA 2.5

Body:
Some C++ materials mention we can't call a virtual function inside ctor or dtor,

(

sorry ,I think it's better to change to

Some C++ materials mention we'd better not to  call a virtual function inside ctor or dtor,

)

but we may call them accidentally. Is there any way to prevent that?

For example:

# include < iostream >
using namespace std;

class CAT
{
public:
    CAT(){ f();}
    virtual void f(){cout<<"void CAT:f()"<<std::endl;}
};

class SMALLCAT :public CAT
{
public:
    SMALLCAT():CAT()
    {
    }
    void f(){cout<<"void SMALLCAT:f()"<<std::endl;}
};

int main()
{
    SMALLCAT sc;

}

output:

void CAT::f()  //not we expected!!!

Thanks


问:
How to write check_mk manual checks
I have a python scripts which checks for the processes
    import subprocess

```<code>s = subprocess.check_output('tasklist', shell=True)
if "cmd.exe" in s:
    if "java.exe" not in str(s):
        print "selenium server is not up"
    if "FreeSSHDService.exe" not in str(s):
        print "SSH is not up"
    else:
        print "Everything is awesome"
</code>```

I want to add a check on check_mk dashboard, what are the steps to add this check and where I have to up this script.

```<code>import subprocess

s = subprocess.check_output('tasklist', shell=True)
if "cmd.exe" in s:
    if "java.exe" not in str(s):
       return 2, "selenium server is not up")
    if "FreeSSHDService.exe" not in str(s):
       return 2, "SSH is not  up"
    else:
        return 0, "Everything is awesome"
</code>```

答:
First of all I'm assuming the node you want to check is MS Windows based, in which case I cannot help you much because my expertise is about UNIX and Linux.

This web link will help you to check your Windows based nodes, especially the paragrah 10. Extending the Windows agent.

In Linux, once the check_mk_agent is installed, there are three ways according to how deep you want to get into the check_mk guts. In Windows I think there are the same methods.

As a local service: you copy your python code into the local folder, whatever it is located in Windows, and edits the [global] section of the check_mk.ini configuration file to make run the py and pyc file name extensions.

As a MRPE check: you make your python program print its output according to the Nagios output check format and edit the [mrpe] section of the check_ini configuration file according to the notes in the paragraph 10.2. As a disadvantage, the WARNING and CRITICAL values/ranges are fixed in the check_ini file -- they cannot be changed in WATO.

As a check_mk agent: you turn your python program into a check_mk agent. I think this is the most difficult way because each check_mk agent has to have a counterpart definition/declaration/inventory file in the check_mk server in order to be used in WATO and to configure its parameters. I never wrote down one, but if you are keen on, you should read this guidelines.

Best regards.

ContentLicense: CC BY-SA 3.0

Title: How to write check_mk manual checks

Body:
I have a python scripts which checks for the processes
    import subprocess

s = subprocess.check_output('tasklist', shell=True)
if "cmd.exe" in s:
    if "java.exe" not in str(s):
        print "selenium server is not up"
    if "FreeSSHDService.exe" not in str(s):
        print "SSH is not up"
    else:
        print "Everything is awesome"

I want to add a check on check_mk dashboard, what are the steps to add this check and where I have to up this script.

import subprocess

s = subprocess.check_output('tasklist', shell=True)
if "cmd.exe" in s:
    if "java.exe" not in str(s):
       return 2, "selenium server is not up")
    if "FreeSSHDService.exe" not in str(s):
       return 2, "SSH is not  up"
    else:
        return 0, "Everything is awesome"


问:
PVLIB - DC Power From Irradiation - Simple Calculation
Dear pvlib users and devels.

I'm a researcher in computer science, not particularly expert in the simulation or modelling of solar panels. I'm interested in use pvlib since
we are trying to simulate the works of a small solar panel used for IoT
applications, in particular the panel spec are the following:
12.8% max efficiency, Vmp = 5.82V, size = 225 × 155 × 17 mm.

Before using pvlib, one of my collaborator wrote a code that compute the
irradiation directly from average monthly values calculated with PVWatt.
I was not really satisfied, so we are starting to use pvlib.
In the old code, we have the power and current of the panel calculated as:

W = Irradiation * PanelSize(m^2) * Efficiency
A = W / Vmp

The Irradiation, in Madrid, as been obtained with PVWatt, and this is
what my collaborator used:
    DIrradiance = (2030.0,2960.0,4290.0,5110.0,5950.0,7090.0,7200.0,6340.0,4870.0,3130.0,2130.0,1700.0)
I'm trying to understand if pvlib compute values similar to the ones above, as averages over a day for each month. And the curve of production in day.
I wrote this to compare pvlib with our old model:

```<code>import math
import numpy as np
import datetime as dt
import matplotlib.pyplot as plt
import pandas as pd
import pvlib
from pvlib.location import Location

def irradiance(day,m):
    DIrradiance =(2030.0,2960.0,4290.0,5110.0,5950.0,
                 7090.0,7200.0,6340.0,4870.0,3130.0,2130.0,1700.0)
    madrid = Location(40.42, -3.70, 'Europe/Madrid', 600, 'Madrid')
    times = pd.date_range(start=dt.datetime(2015,m,day,00,00),
                      end=dt.datetime(2015,m,day,23,59),
                      freq='60min')
    spaout = pvlib.solarposition.spa_python(times, madrid.latitude, madrid.longitude)
    spaout = spaout.assign(cosz=pd.Series(np.cos(np.deg2rad(spaout['zenith']))))
    z = np.array(spaout['cosz'])
    return z.clip(0)*(DIrradiance[m-1])

madrid = Location(40.42, -3.70, 'Europe/Madrid', 600, 'Madrid')
times = pd.date_range(start = dt.datetime(2015,8,15,00,00),
                  end = dt.datetime(2015,8,15,23,59),
                  freq='60min')

old = irradiance(15,8)              # old model
new = madrid.get_clearsky(times)    # pvlib irradiance
plt.plot(old,'r-')                  # compare them.
plt.plot(old/6.0,'y-')             # old seems 6 times more..I do not know why
plt.plot(new['ghi'].values,'b-')
plt.show()
</code>```

The code above compute the old irradiance, using the zenit angle. and compute the ghi values using the clear_sky. I do not understand if the values in ghi must be multiplied by the cos of zenit too, or not. Anyway
they are smaller by a factor of 6. What I'd like to have at the end is the
power and current in output from the panel (DC) without any inverter, and
we are not really interested at modelling it exactly, but at least, to
have a reasonable curve. We are able to capture from the panel the ampere
produced, and we want to compare the values from the measurements putting
the panel on the roof top with the values calculated by pvlib.

Any help on this would be really appreachiated. Thanks

Sorry Will I do not care a lot about my previous model since I'd like to move all code to pvlib. I followed your suggestion and I'm using irradiance.total_irrad, the code now looks in this way:

```<code>madrid = Location(40.42, -3.70, 'Europe/Madrid', 600, 'Madrid')
times = pd.date_range(start=dt.datetime(2015,1,1,00,00),
                  end=dt.datetime(2015,1,1,23,59),
                  freq='60min')
ephem_data = pvlib.solarposition.spa_python(times, madrid.latitude,
madrid.longitude)
irrad_data = madrid.get_clearsky(times)
AM = atmosphere.relativeairmass(ephem_data['apparent_zenith'])
total = irradiance.total_irrad(40, 180,
        ephem_data['apparent_zenith'], ephem_data['azimuth'],
        dni=irrad_data['dni'], ghi=irrad_data['ghi'],
        dhi=irrad_data['dhi'], airmass=AM,
        surface_type='urban')
poa = total['poa_global'].values
</code>```

Now, I know the irradiance on POA, and I want to compute the output in Ampere: It is just

```<code>(poa*PANEL_EFFICIENCY*AREA) / VOLT_OUTPUT   ?
</code>```

答:
It's not clear to me how you arrived at your values for DIrradiance or what the units are, so I can't comment much the discrepancies between the values. I'm guessing that it's some kind of monthly data since there are 12 values. If so, you'd need to calculate ~hourly pvlib irradiance data and then integrate it to check for consistency.

If your module will be tilted, you'll need to convert your ~hourly irradiance GHI, DNI, DHI values to plane of array (POA) irradiance using a transposition model. The irradiance.total_irrad function is the easiest way to do that.

The next steps depend on the IV characteristics of your module, the rest of the circuit, and how accurate you need the model to be.

Body:
Dear pvlib users and devels.

I'm a researcher in computer science, not particularly expert in the simulation or modelling of solar panels. I'm interested in use pvlib since
we are trying to simulate the works of a small solar panel used for IoT
applications, in particular the panel spec are the following:
12.8% max efficiency, Vmp = 5.82V, size = 225 × 155 × 17 mm.

Before using pvlib, one of my collaborator wrote a code that compute the
irradiation directly from average monthly values calculated with PVWatt.
I was not really satisfied, so we are starting to use pvlib.
In the old code, we have the power and current of the panel calculated as:

W = Irradiation * PanelSize(m^2) * Efficiency
A = W / Vmp

The Irradiation, in Madrid, as been obtained with PVWatt, and this is
what my collaborator used:
    DIrradiance = (2030.0,2960.0,4290.0,5110.0,5950.0,7090.0,7200.0,6340.0,4870.0,3130.0,2130.0,1700.0)
I'm trying to understand if pvlib compute values similar to the ones above, as averages over a day for each month. And the curve of production in day.
I wrote this to compare pvlib with our old model:

import math
import numpy as np
import datetime as dt
import matplotlib.pyplot as plt
import pandas as pd
import pvlib
from pvlib.location import Location

def irradiance(day,m):
    DIrradiance =(2030.0,2960.0,4290.0,5110.0,5950.0,
                 7090.0,7200.0,6340.0,4870.0,3130.0,2130.0,1700.0)
    madrid = Location(40.42, -3.70, 'Europe/Madrid', 600, 'Madrid')
    times = pd.date_range(start=dt.datetime(2015,m,day,00,00),
                      end=dt.datetime(2015,m,day,23,59),
                      freq='60min')
    spaout = pvlib.solarposition.spa_python(times, madrid.latitude, madrid.longitude)
    spaout = spaout.assign(cosz=pd.Series(np.cos(np.deg2rad(spaout['zenith']))))
    z = np.array(spaout['cosz'])
    return z.clip(0)*(DIrradiance[m-1])

madrid = Location(40.42, -3.70, 'Europe/Madrid', 600, 'Madrid')
times = pd.date_range(start = dt.datetime(2015,8,15,00,00),
                  end = dt.datetime(2015,8,15,23,59),
                  freq='60min')

old = irradiance(15,8)              # old model
new = madrid.get_clearsky(times)    # pvlib irradiance
plt.plot(old,'r-')                  # compare them.
plt.plot(old/6.0,'y-')             # old seems 6 times more..I do not know why
plt.plot(new['ghi'].values,'b-')
plt.show()

The code above compute the old irradiance, using the zenit angle. and compute the ghi values using the clear_sky. I do not understand if the values in ghi must be multiplied by the cos of zenit too, or not. Anyway
they are smaller by a factor of 6. What I'd like to have at the end is the
power and current in output from the panel (DC) without any inverter, and
we are not really interested at modelling it exactly, but at least, to
have a reasonable curve. We are able to capture from the panel the ampere
produced, and we want to compare the values from the measurements putting
the panel on the roof top with the values calculated by pvlib.

Any help on this would be really appreachiated. Thanks

Sorry Will I do not care a lot about my previous model since I'd like to move all code to pvlib. I followed your suggestion and I'm using irradiance.total_irrad, the code now looks in this way:

madrid = Location(40.42, -3.70, 'Europe/Madrid', 600, 'Madrid')
times = pd.date_range(start=dt.datetime(2015,1,1,00,00),
                  end=dt.datetime(2015,1,1,23,59),
                  freq='60min')
ephem_data = pvlib.solarposition.spa_python(times, madrid.latitude,
madrid.longitude)
irrad_data = madrid.get_clearsky(times)
AM = atmosphere.relativeairmass(ephem_data['apparent_zenith'])
total = irradiance.total_irrad(40, 180,
        ephem_data['apparent_zenith'], ephem_data['azimuth'],
        dni=irrad_data['dni'], ghi=irrad_data['ghi'],
        dhi=irrad_data['dhi'], airmass=AM,
        surface_type='urban')
poa = total['poa_global'].values

Now, I know the irradiance on POA, and I want to compute the output in Ampere: It is just

(poa*PANEL_EFFICIENCY*AREA) / VOLT_OUTPUT   ?


问:
Query city names starting and ending with vowels
I wrote this code (db2) and it works just fine, but I'm wondering, is there a shorter way to write this?</p>
```<code>Select Distinct city
From   station
Where  city Like 'A%a'
       Or city Like 'A%e'
       Or city Like 'A%i'
       Or city Like 'A%o'
       Or city Like 'A%u'
       Or city Like 'E%a'
       Or city Like 'E%e'
       Or city Like 'E%i'
       Or city Like 'E%o'
       Or city Like 'E%u'
       Or city Like 'I%a'
       Or city Like 'I%e'
       Or city Like 'I%i'
       Or city Like 'I%o'
       Or city Like 'I%u'
       Or city Like 'O%a'
       Or city Like 'O%e'
       Or city Like 'O%i'
       Or city Like 'O%o'
       Or city Like 'O%u'
       Or city Like 'U%a'
       Or city Like 'U%e'
       Or city Like 'U%i'
       Or city Like 'U%o'
       Or city Like 'U%u';
</code>```

答:
I'm not an expert in DB2, but I think you can use a regular expression in your WHERE LIKE.

Check the documentation:
https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0061494.html

```<code>Example:
Select Distinct city
From   station
Where  REGEXP_LIKE(city,'[aeiou].*[aeiou]')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote this code (db2) and it works just fine, but I'm wondering, is there a shorter way to write this?

Select Distinct city
From   station
Where  city Like 'A%a'
       Or city Like 'A%e'
       Or city Like 'A%i'
       Or city Like 'A%o'
       Or city Like 'A%u'
       Or city Like 'E%a'
       Or city Like 'E%e'
       Or city Like 'E%i'
       Or city Like 'E%o'
       Or city Like 'E%u'
       Or city Like 'I%a'
       Or city Like 'I%e'
       Or city Like 'I%i'
       Or city Like 'I%o'
       Or city Like 'I%u'
       Or city Like 'O%a'
       Or city Like 'O%e'
       Or city Like 'O%i'
       Or city Like 'O%o'
       Or city Like 'O%u'
       Or city Like 'U%a'
       Or city Like 'U%e'
       Or city Like 'U%i'
       Or city Like 'U%o'
       Or city Like 'U%u';

Body:
I'm not an expert in DB2, but I think you can use a regular expression in your WHERE LIKE.

Check the documentation:
https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0061494.html

Example:
Select Distinct city
From   station
Where  REGEXP_LIKE(city,'[aeiou].*[aeiou]')


问:
JavaFX Animations: Quit an infinite transition by fading out
Have an animation like this starting with the program:

```<code>tr = new FadeTransition(Duration.millis(1000), rect);
tr.setFromValue(0.5);
tr.setToValue(0.1);
tr.setCycleCount(Timeline.INDEFINITE);
tr.setAutoReverse(true);
</code>```

Obviously it loops endlessly. Now I want a function which stops this, but only after it has faded out. that means just the next time it reaches its "to value" (or the "from value") it should stop animating.

Now I know that I can end the animation on the next iteration by setting the cycle count to 1. However that only works when the animation has been stopped before.

```<code>tr.stop();
tr.setCycleCount(1);
tr.play();
</code>```

But that means the .play() function restarts the animation, causing a flicker which isn't really pretty. This last cycle doesn't continue where it had been before.

How can I end the animation smoothly?

Huge thanks in advance!

答:
Have found a smooth solution myself after all.
Instead of using infinite cycle, it uses a cycle of 2 and a finish-event which just restarts the animation:

```<code>tr = new FadeTransition(Duration.millis(1000), rect);
tr.setFromValue(0.1);
tr.setToValue(0.5);
tr.setAutoReverse(true);
tr.setCycleCount(2);
tr.play();

tr.setOnFinished((ActionEvent event) -> tr.play());
</code>```

Then a simple call of

```<code>tr.setOnFinished(null);
</code>```

Suffices to smoothly quit the animation at the end of the last transition.

Body:
Have an animation like this starting with the program:

tr = new FadeTransition(Duration.millis(1000), rect);
tr.setFromValue(0.5);
tr.setToValue(0.1);
tr.setCycleCount(Timeline.INDEFINITE);
tr.setAutoReverse(true);

Obviously it loops endlessly. Now I want a function which stops this, but only after it has faded out. that means just the next time it reaches its "to value" (or the "from value") it should stop animating.

Now I know that I can end the animation on the next iteration by setting the cycle count to 1. However that only works when the animation has been stopped before.

tr.stop();
tr.setCycleCount(1);
tr.play();

But that means the .play() function restarts the animation, causing a flicker which isn't really pretty. This last cycle doesn't continue where it had been before.

How can I end the animation smoothly?

Huge thanks in advance!

Body:
Have found a smooth solution myself after all.
Instead of using infinite cycle, it uses a cycle of 2 and a finish-event which just restarts the animation:

tr = new FadeTransition(Duration.millis(1000), rect);
tr.setFromValue(0.1);
tr.setToValue(0.5);
tr.setAutoReverse(true);
tr.setCycleCount(2);
tr.play();

tr.setOnFinished((ActionEvent event) -> tr.play());

Then a simple call of

tr.setOnFinished(null);

Suffices to smoothly quit the animation at the end of the last transition.


问:
add two numbers in a linked list
I'm trying to add numbers from two linked lists and put it in a third one. It adds well but my code blocks compiler stops responding while running this code possibly because of an infinite loop or some exception.

Following code adds two numbers stored in reverse order in a linked list.

```<code>struct Node{
    int x;
    Node* next;
};

class LinkedList{

    public:
        Node* head;
        LinkedList(){
            head = NULL;
        }

        void addNode(int num){
            Node* n = new Node();
            n->x = num;
            n->next = NULL;
            if(head == NULL){
                head = n;
            }else{
                Node* n1 = head;
                while(n1 != NULL){
                    if(n1->next == NULL){
                        n1->next = n;
                        break;
                    }
                    n1 = n1->next;
                }
            }
        }

        int popNode(){
            int num = NULL;
            if (head != NULL){
                num = head->x;
                head = head->next;
            }else{
                cout << "Yay" << "\n";
                num = NULL;
            }

            return num;
        }

        void printList(){
            Node* n1 = head;
            while(n1 != NULL){
                if(n1->next == NULL){
                    cout << n1->x << "\n";
                }else{
                    cout << n1->x << "->";
                }

                n1 = n1->next;
            }
        }

};

LinkedList* add_nums(LinkedList* l1, LinkedList* l2) {
    LinkedList l3;

    int num1= (*l1).popNode();
    int num2= (*l2).popNode();
    int carry = 0;

    while(num1 != NULL || num2 != NULL){
        int num3 = num1+num2+carry;

        if (num3 > 9){
            int temp = num3 % 10;
            carry = (num3 - temp)/10;
            num3 = temp;
        }

        l3.addNode(num3);
        l3.printList();
        num1 = (*l1).popNode();
        num2 = (*l2).popNode();
    }

    return &l3;

}

int main(int argc, char const *argv[]) {
  LinkedList list1;
  LinkedList list2;
  list1.addNode(2);
  list1.addNode(4);
  list1.addNode(3);
  list2.addNode(5);
  list2.addNode(6);
  list2.addNode(4);
  (*(add_nums(&list1, &list2))).printList();
  return 0;
}
</code>```

Can anyone tell me what I'm doing wrong?

Changes to code i should do after inputs from answers below:

I should change integer initializations from NULL to 0.

Should use LinkedList objects to terminate my loop.

Should change how i access the functions from a pointer

Thanks everyone.

答:
Can anyone tell me what I'm doing wrong?

IMHO you might be making a wrong choice. The STL provides data structures for (doubly linked) list and forward list (which is singly linked). Maybe you want to use those. You can expect them to be efficient enough, bug free and important to know about if you want to be a proficient C++ programmer.

It would make sense to let someone do a code review (there is a code review StackExchange site); e.g. naming the integer variable x in the linked list is probably not considered a good practise.

You did not tell us what is wrong about your program. This is expected in SO. Your question qualifies for "off-topic (why is this code not working?)". You provided the program, which is good. But you did not provide your expected input and output. What is your program expected to do? If I consider your main function as a test, then what result did you expect ?

see below some errors/warnings

In the function popNode

```<code>int num = NULL; // should be 0, it's an integer
...
num = NULL; // same reason
</code>```

In the functions add_nums

```<code>LinkedList l3; // it's a local variable (see return below)
...
while(num1 != NULL || num2 != NULL) // again num1 and num2 are integers
....
return &l3; // address of a local variable :-(
</code>```

I think it is better you declare the variable l3 as a pointer to LinkedList:

```<code>LinkedList *l3 = new LinkedList;
... // adapt the code to use l3 appropriately
return l3;
</code>```

Title: add two numbers in a linked list

Body:
I'm trying to add numbers from two linked lists and put it in a third one. It adds well but my code blocks compiler stops responding while running this code possibly because of an infinite loop or some exception.

Following code adds two numbers stored in reverse order in a linked list.

struct Node{
    int x;
    Node* next;
};

class LinkedList{

    public:
        Node* head;
        LinkedList(){
            head = NULL;
        }

        void addNode(int num){
            Node* n = new Node();
            n->x = num;
            n->next = NULL;
            if(head == NULL){
                head = n;
            }else{
                Node* n1 = head;
                while(n1 != NULL){
                    if(n1->next == NULL){
                        n1->next = n;
                        break;
                    }
                    n1 = n1->next;
                }
            }
        }

        int popNode(){
            int num = NULL;
            if (head != NULL){
                num = head->x;
                head = head->next;
            }else{
                cout << "Yay" << "\n";
                num = NULL;
            }

            return num;
        }

        void printList(){
            Node* n1 = head;
            while(n1 != NULL){
                if(n1->next == NULL){
                    cout << n1->x << "\n";
                }else{
                    cout << n1->x << "->";
                }

                n1 = n1->next;
            }
        }

};

LinkedList* add_nums(LinkedList* l1, LinkedList* l2) {
    LinkedList l3;

    int num1= (*l1).popNode();
    int num2= (*l2).popNode();
    int carry = 0;

    while(num1 != NULL || num2 != NULL){
        int num3 = num1+num2+carry;

        if (num3 > 9){
            int temp = num3 % 10;
            carry = (num3 - temp)/10;
            num3 = temp;
        }

        l3.addNode(num3);
        l3.printList();
        num1 = (*l1).popNode();
        num2 = (*l2).popNode();
    }

    return &l3;

}

int main(int argc, char const *argv[]) {
  LinkedList list1;
  LinkedList list2;
  list1.addNode(2);
  list1.addNode(4);
  list1.addNode(3);
  list2.addNode(5);
  list2.addNode(6);
  list2.addNode(4);
  (*(add_nums(&list1, &list2))).printList();
  return 0;
}

Can anyone tell me what I'm doing wrong?

Changes to code i should do after inputs from answers below:

I should change integer initializations from NULL to 0.

Should use LinkedList objects to terminate my loop.

Should change how i access the functions from a pointer

Thanks everyone.

Body:
Can anyone tell me what I'm doing wrong?

IMHO you might be making a wrong choice. The STL provides data structures for (doubly linked) list and forward list (which is singly linked). Maybe you want to use those. You can expect them to be efficient enough, bug free and important to know about if you want to be a proficient C++ programmer.

It would make sense to let someone do a code review (there is a code review StackExchange site); e.g. naming the integer variable x in the linked list is probably not considered a good practise.

You did not tell us what is wrong about your program. This is expected in SO. Your question qualifies for "off-topic (why is this code not working?)". You provided the program, which is good. But you did not provide your expected input and output. What is your program expected to do? If I consider your main function as a test, then what result did you expect ?

see below some errors/warnings

In the function popNode

int num = NULL; // should be 0, it's an integer
...
num = NULL; // same reason

In the functions add_nums

LinkedList l3; // it's a local variable (see return below)
...
while(num1 != NULL || num2 != NULL) // again num1 and num2 are integers
....
return &l3; // address of a local variable :-(

I think it is better you declare the variable l3 as a pointer to LinkedList:

LinkedList *l3 = new LinkedList;
... // adapt the code to use l3 appropriately
return l3;


问:
Regular expression to match any word followed by a literal string
So I have the following:

```<code>^[a-zA-Z]+\b(myword+-)\b*
</code>```

which I thought would match

^ start of string

[a-zA-Z] any alpha character

+ of one or more characters

\b followed by a word break

(myword+-) followed by myword which could include one or more special characters

\b followed by a word break

\* followed by anything at all

One: it does not work - it does not match anything

Two: any special characters included in {myword+-) throws an error

I could escape the special characters, but I don't know in advance what they might be, so I would have to escape all the possibilites, or perhaps I could just escape every character in {\m\y\w\o\r\d\\+\\-)

Edited to add:

Sorry, I knew I should have given more information

I have a series of strings to seach through in the form:

extra android-sdk and more that is of no interest

extra android-ndk and more that is of no interest

extra anjuta-extra and more that is of no interest

community c++-gtk-utils and more that is of no interest

and I have a list of items to search for in the strings:

android-sdk

android-ndk

extra

c++-gtk-utils

The item should only match if the second word in the string is an exact match to the item, so:

android-sdk will match the first string

android-ndk will match the second string

extra wuill NOT match the third string

c++-gtk-utils will match the fourth string

So (myword+-) is the item I am searching for "which could include one or more special characters"

Thanks for the help

Andrew

答:
OK, with the help from above I worked it out.

This regex does exactly what I wanted, bear in mind that I am working in tcl (note the spaces to delimit the search word):

^[a-zA-Z]+\y extra \y *

where the search word is "extra".

It is necessary to escape any characters in the search string which may be interpreted by regex as qualifiers etc e.g +

So this will also work:

^[a-zA-Z]+\y dbus-c\+\+ \y *

Andrew

Body:
So I have the following:

^[a-zA-Z]+\b(myword+-)\b*

which I thought would match

^ start of string

[a-zA-Z] any alpha character

+ of one or more characters

\b followed by a word break

(myword+-) followed by myword which could include one or more special characters

\b followed by a word break

\* followed by anything at all

One: it does not work - it does not match anything

Two: any special characters included in {myword+-) throws an error

I could escape the special characters, but I don't know in advance what they might be, so I would have to escape all the possibilites, or perhaps I could just escape every character in {\m\y\w\o\r\d\\+\\-)

Edited to add:

Sorry, I knew I should have given more information

I have a series of strings to seach through in the form:

extra android-sdk and more that is of no interest

extra android-ndk and more that is of no interest

extra anjuta-extra and more that is of no interest

community c++-gtk-utils and more that is of no interest

and I have a list of items to search for in the strings:

android-sdk

android-ndk

extra

c++-gtk-utils

The item should only match if the second word in the string is an exact match to the item, so:

android-sdk will match the first string

android-ndk will match the second string

extra wuill NOT match the third string

c++-gtk-utils will match the fourth string

So (myword+-) is the item I am searching for "which could include one or more special characters"

Thanks for the help

Andrew


问:
How to mix categorical, discrete and continuous data as input in tensorflow?
I am new to tensorflow. I have a dataset that has continuous, discrete and categorical values. The sample data is as follows:

```<code>     col1    col2    col3  col4  col5  col6  Class
0    22    23.40   45.60  11    1.0   0.0    0.0
1   346    67.40  235.60  23    1.0   1.0    0.0
2    22    67.34  364.66  17    0.0   0.0    1.0
3  1231   124.44  213.89  14    1.0   0.0    1.0
</code>```

col1 and col4 are discrete variables.
col2 and col3 are continuous variables.
col5 and col6 are categorical variables.
Class is the target variable.

I was wondering if I can pass along the above data directly as input to the placeholder X.

```<code>X = tf.placeholder(tf.float32, [None, numFeatures])
</code>```

I do not have to apply tf.one_hot, correct? Since my categorical variables are binary.

How does tensorflow detect that col5 and col6 are categorical variables?

Any help would be appreciated. Thank you!

答:
Since your variables are binary it's ok to treat them as int
you have to create placeholders that you will later use during the training part by passing batches.

Here is how you could declare your tensorflow placeholders so that they have the right dtype.

```<code>var1 = tf.placeholder(tf.int32, shape)
var4 = tf.placeholder(tf.int32, shape)

var2 = tf.placeholder(tf.float32, shape)
var3 = tf.placeholder(tf.float32, shape)

var5 = tf.placeholder(tf.int32, shape)
var6 = tf.placeholder(tf.int32, shape)

class_ = tf.placeholder(tf.int32, shape)
</code>```

In order for you to feed the set of variables to a model you will later have to concatenate them but before that you should cast your tensor in order to have all in the same dtypes for concatenation.

```<code>var1 = tf.cast(var1, tf.float32)
...
data = tf.concat([var1,var4, var2,var3, var5, var6], axis=1)
</code>```

Body:
I am new to tensorflow. I have a dataset that has continuous, discrete and categorical values. The sample data is as follows:

     col1    col2    col3  col4  col5  col6  Class
0    22    23.40   45.60  11    1.0   0.0    0.0
1   346    67.40  235.60  23    1.0   1.0    0.0
2    22    67.34  364.66  17    0.0   0.0    1.0
3  1231   124.44  213.89  14    1.0   0.0    1.0

col1 and col4 are discrete variables.
col2 and col3 are continuous variables.
col5 and col6 are categorical variables.
Class is the target variable.

I was wondering if I can pass along the above data directly as input to the placeholder X.

X = tf.placeholder(tf.float32, [None, numFeatures])

I do not have to apply tf.one_hot, correct? Since my categorical variables are binary.

How does tensorflow detect that col5 and col6 are categorical variables?

Any help would be appreciated. Thank you!

Body:
Since your variables are binary it's ok to treat them as int
you have to create placeholders that you will later use during the training part by passing batches.

Here is how you could declare your tensorflow placeholders so that they have the right dtype.

var1 = tf.placeholder(tf.int32, shape)
var4 = tf.placeholder(tf.int32, shape)

var2 = tf.placeholder(tf.float32, shape)
var3 = tf.placeholder(tf.float32, shape)

var5 = tf.placeholder(tf.int32, shape)
var6 = tf.placeholder(tf.int32, shape)

class_ = tf.placeholder(tf.int32, shape)

In order for you to feed the set of variables to a model you will later have to concatenate them but before that you should cast your tensor in order to have all in the same dtypes for concatenation.

var1 = tf.cast(var1, tf.float32)
...
data = tf.concat([var1,var4, var2,var3, var5, var6], axis=1)


问:
How to use the type of an object's property in flow?
How do you use the type of an object's property in flow? e.g.</p>

```<code>type A = {
  someproperty: string
}

// throws error
const b: A.someproperty = "hello"
</code>```

答:
As you have already said in your self-answer, you can use $PropertyType. But bear in mind that this is not official and may not always work the same in the future. It could even be removed altogether. React uses $PropertyType behind the scenes, but developers at Facebook have the luxury of working together with the Flow team, and have better visibility on the feature roadmap.

If you have control of all the types, you are better off designing them in such a way that you can refer to the property's type by name. In a lot of cases, a simple type alias will work:

```<code>type SomePropertyOfA = string;
type A = {
  someproperty: SomePropertyOfA
}

const b: SomePropertyOfA = "hello"
</code>```

Body:
How do you use the type of an object's property in flow? e.g.

type A = {
  someproperty: string
}

// throws error
const b: A.someproperty = "hello"

Body:
As you have already said in your self-answer, you can use $PropertyType. But bear in mind that this is not official and may not always work the same in the future. It could even be removed altogether. React uses $PropertyType behind the scenes, but developers at Facebook have the luxury of working together with the Flow team, and have better visibility on the feature roadmap.

If you have control of all the types, you are better off designing them in such a way that you can refer to the property's type by name. In a lot of cases, a simple type alias will work:

type SomePropertyOfA = string;
type A = {
  someproperty: SomePropertyOfA
}

const b: SomePropertyOfA = "hello"


问:
Query to check if an attribute was in the table from LAST YEAR
Im trying to write a CASE statement to see if school_name with the school_form_status = completed, in the current year has been also completed the previous year.

```<code>   school_name | School_status | Report date|  FORM_PREVIOUS_YEAR
________________________________________________________________________________

     Paul Keys |    Completed  | 03/31/2016  |      YES
</code>```

This is what I have but but not working , im a beginner

```<code>    select
    CASE REPORTED_DATE YEAR = REPORTED_DATE, YEAR,-1,DateAdd(Year,DATEDIFF(YEAR,0,getdate()),0))
    THEN 'Y'
     ELSE 'N'
    END AS FORM_PREV_YEAR,
    from
    TABLE1
</code>```

答:
Normally you would JOIN the table against itself:

```<code>SELECT this_year.school_name,
       this_year.school_status,
       this_year.reported_date,
       CASE WHEN last_year.school_status = 'Completed' THEN 'Y' ELSE 'N' END AS form_previous_year
FROM table1 AS this_year
LEFT OUTER JOIN table1 AS last_year ON last_year.school_name = this_year.school_name
WHERE this_year.reported_date >= TO_DATE('2017-01-01', 'YYYY-MM-DD')
  AND last_year.reported_date BETWEEN TO_DATE('2016-01-01', 'YYYY-MM-DD') AND TO_DATE('2016-12-31', 'YYYY-MM-DD')
  AND this_year.school_status = 'Completed'
</code>```

The statement looks for all schools with the status completed and a reported_date from this year ad then finds the schools with the same name and the reported_date from last year if it exists (LEFT OUTER JOIN). If the last year's status is 'Completed' it will return 'Y' else 'N'.

Body:
Im trying to write a CASE statement to see if school_name with the school_form_status = completed, in the current year has been also completed the previous year.

   school_name | School_status | Report date|  FORM_PREVIOUS_YEAR
________________________________________________________________________________

     Paul Keys |    Completed  | 03/31/2016  |      YES

This is what I have but but not working , im a beginner

    select
    CASE REPORTED_DATE YEAR = REPORTED_DATE, YEAR,-1,DateAdd(Year,DATEDIFF(YEAR,0,getdate()),0))
    THEN 'Y'
     ELSE 'N'
    END AS FORM_PREV_YEAR,
    from
    TABLE1

Body:
Normally you would JOIN the table against itself:

SELECT this_year.school_name,
       this_year.school_status,
       this_year.reported_date,
       CASE WHEN last_year.school_status = 'Completed' THEN 'Y' ELSE 'N' END AS form_previous_year
FROM table1 AS this_year
LEFT OUTER JOIN table1 AS last_year ON last_year.school_name = this_year.school_name
WHERE this_year.reported_date >= TO_DATE('2017-01-01', 'YYYY-MM-DD')
  AND last_year.reported_date BETWEEN TO_DATE('2016-01-01', 'YYYY-MM-DD') AND TO_DATE('2016-12-31', 'YYYY-MM-DD')
  AND this_year.school_status = 'Completed'

The statement looks for all schools with the status completed and a reported_date from this year ad then finds the schools with the same name and the reported_date from last year if it exists (LEFT OUTER JOIN). If the last year's status is 'Completed' it will return 'Y' else 'N'.


问:
Really Slow MySQL Insert Query
I've got a table with about half a million records in it. It's not huge. A couple varchar(255) fields, some ints, a float, and a couple timestamps. There are indices on the ints as well as foreign key constraints. Inserts are taking forever. I'm talking 1-4 seconds to insert one row. I've had to deal with slow select queries plenty of times, but I'm stuck trying to figure out what's going on with this insert.

EDIT: Okay, I was really just asking for ideas on how to debug this, but, here's all the tables involved. Inserting into "ingredients" is what takes forever. Hopefully throwing a good portion of my schema onto the web doesn't bite me later...

```<code>CREATE TABLE `ingredients` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `quantity` float DEFAULT NULL,
  `food` varchar(255) NOT NULL,
  `unit_id` int(11) DEFAULT NULL,
  `ingredient_group_id` int(11) DEFAULT NULL,
  `order_by` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `range` float DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `unit_id` (`unit_id`),
  KEY `ingredient_group_id` (`ingredient_group_id`),
  CONSTRAINT `ingredients_ibfk_1` FOREIGN KEY (`unit_id`) REFERENCES `units` (`id`),
  CONSTRAINT `ingredients_ibfk_2` FOREIGN KEY (`ingredient_group_id`) REFERENCES `ingredient_groups` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=269974 DEFAULT CHARSET=utf8

CREATE TABLE `units` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `abbreviation` varchar(255) CHARACTER SET latin1 NOT NULL,
  `type` int(11) NOT NULL,
  `si` float NOT NULL,
  `lower_bound` float DEFAULT NULL,
  `lower_unit_id` int(11) DEFAULT NULL,
  `upper_bound` float DEFAULT NULL,
  `upper_unit_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `lower_unit_id` (`lower_unit_id`),
  KEY `upper_unit_id` (`upper_unit_id`),
  CONSTRAINT `units_ibfk_1` FOREIGN KEY (`lower_unit_id`) REFERENCES `units` (`id`),
  CONSTRAINT `units_ibfk_2` FOREIGN KEY (`upper_unit_id`) REFERENCES `units` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8

CREATE TABLE `ingredient_groups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `recipe_id` int(11) NOT NULL,
  `order_by` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `recipe_id` (`recipe_id`),
  CONSTRAINT `ingredient_groups_ibfk_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipes` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=32739 DEFAULT CHARSET=utf8
</code>```

答:
lots of information missing, but the things i'd check first:

if on MyISAM tables: extremely fragmented files, especially index files.  Use filefrag to check that.  This can happen if the database grew slowly with time.  If so, just shut down MySQL, copy the database directory, rename the original and new copies and restart MySQL

if you use InnoDB tables: a file-based datastore, again too fragmented.  In this case, fragmentation can be both at filesystem level (check and handle as above) or at datastore level, for that use the InnoDB tools. In the worst case a block-device-based datastore (which can't get externally fragmented) can exhibit a bad case of internal fragmentation.

some index with extremely low cardinality. That is, a non-unique index with few distinct values present, that is, lots of repeats. This indexes approach asymptotically a linear list, with O(n) time profiles.  This can be either an index on the table or the referred foreign index.

reader contention.  unlikely, but a huge number of concurrent readers can stall a single writer.

Edit:

After reading your definitions, i think ingredients.unit_id and ingredients.ingredient_group_id are the first candidates to check, since they seem to have very low cardinality.

The first one is unlikely to be useful (do you plan to select all ingredients that are measured in spoons?), so you can probably just drop it.

The second one can be very useful; but if there are few ingredient groups, the cardinality can be very low, degrading performance.  To raise cardinality, add some part to make it more discriminating.  If no other field is likely to appear in a query together with group id, just add the main id or creation date, making it (ingredient_group_id, id) or (ingredient_group_id, created_at).  Seems counterintuitive to add complexity to make it faster, but it can really help.  As a bonus, you can add a sort by created_at to any query that selects by ingredient_group_id without performance penalty.

Title: Really Slow MySQL Insert Query

Body:
I've got a table with about half a million records in it. It's not huge. A couple varchar(255) fields, some ints, a float, and a couple timestamps. There are indices on the ints as well as foreign key constraints. Inserts are taking forever. I'm talking 1-4 seconds to insert one row. I've had to deal with slow select queries plenty of times, but I'm stuck trying to figure out what's going on with this insert.

EDIT: Okay, I was really just asking for ideas on how to debug this, but, here's all the tables involved. Inserting into "ingredients" is what takes forever. Hopefully throwing a good portion of my schema onto the web doesn't bite me later...

CREATE TABLE `ingredients` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `quantity` float DEFAULT NULL,
  `food` varchar(255) NOT NULL,
  `unit_id` int(11) DEFAULT NULL,
  `ingredient_group_id` int(11) DEFAULT NULL,
  `order_by` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `range` float DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `unit_id` (`unit_id`),
  KEY `ingredient_group_id` (`ingredient_group_id`),
  CONSTRAINT `ingredients_ibfk_1` FOREIGN KEY (`unit_id`) REFERENCES `units` (`id`),
  CONSTRAINT `ingredients_ibfk_2` FOREIGN KEY (`ingredient_group_id`) REFERENCES `ingredient_groups` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=269974 DEFAULT CHARSET=utf8

CREATE TABLE `units` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `abbreviation` varchar(255) CHARACTER SET latin1 NOT NULL,
  `type` int(11) NOT NULL,
  `si` float NOT NULL,
  `lower_bound` float DEFAULT NULL,
  `lower_unit_id` int(11) DEFAULT NULL,
  `upper_bound` float DEFAULT NULL,
  `upper_unit_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `lower_unit_id` (`lower_unit_id`),
  KEY `upper_unit_id` (`upper_unit_id`),
  CONSTRAINT `units_ibfk_1` FOREIGN KEY (`lower_unit_id`) REFERENCES `units` (`id`),
  CONSTRAINT `units_ibfk_2` FOREIGN KEY (`upper_unit_id`) REFERENCES `units` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8

CREATE TABLE `ingredient_groups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `recipe_id` int(11) NOT NULL,
  `order_by` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `recipe_id` (`recipe_id`),
  CONSTRAINT `ingredient_groups_ibfk_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipes` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=32739 DEFAULT CHARSET=utf8


问:
Use dkpro semantic similarity with uby
I want to compute similarity between strings with dkpro similarity (https://dkpro.github.io/dkpro-similarity/), it works, like so:

```<code>import org.dkpro.similarity.algorithms.api.SimilarityException;
import org.dkpro.similarity.algorithms.api.TextSimilarityMeasure;
import org.dkpro.similarity.algorithms.lsr.LexSemResourceComparator;
import org.dkpro.similarity.algorithms.lsr.gloss.GlossOverlapComparator;
import org.dkpro.similarity.algorithms.lsr.path.JiangConrathComparator;
import org.dkpro.similarity.algorithms.lsr.path.LeacockChodorowComparator;
import org.dkpro.similarity.algorithms.lsr.path.LinComparator;
import org.dkpro.similarity.algorithms.lsr.path.ResnikComparator;
import org.dkpro.similarity.algorithms.lsr.path.WuPalmerComparator;

import de.tudarmstadt.ukp.dkpro.lexsemresource.LexicalSemanticResource;
import de.tudarmstadt.ukp.dkpro.lexsemresource.core.ResourceFactory;
import de.tudarmstadt.ukp.dkpro.lexsemresource.exception.LexicalSemanticResourceException;
import de.tudarmstadt.ukp.dkpro.lexsemresource.exception.ResourceLoaderException;
import learninggoals.analysis.controller.settingtypes.SimilarityAlgorithm;

public class SemResourceComparator implements WordsComparator{
private LexicalSemanticResource resource;
private LexSemResourceComparator comparator;

//en lang
public SemResourceComparator(String resourcetype, SimilarityAlgorithm algorithm, String lang) {

        try {
            resource = ResourceFactory.getInstance().get(resourcetype, lang);
        } catch (ResourceLoaderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
        switch(algorithm){
        /*case ESA://this is vector
            comparator = new GlossOverlapComparator(resource, false);
            break;*/
        case GLOSSOVERLAP:

            comparator = new GlossOverlapComparator(resource, false);
            break;
        case JIANG_CONRATH:
            comparator = new JiangConrathComparator(resource, resource.getRoot());
            break;
        case LEACOCK_CHODOROW:
            comparator = new LeacockChodorowComparator(resource);
            break;
        case LIN:
            comparator = new LinComparator(resource, resource.getRoot());
            break;
        case RESNIK:
            comparator = new ResnikComparator(resource, resource.getRoot());
            break;
        case WUPALMER:
            comparator = new WuPalmerComparator(resource, resource.getRoot());
            break;
        default:
            break;

        }
        } catch (LexicalSemanticResourceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

@Override
public double compareWords(String w1, String w2) {

   try {
    return comparator.getSimilarity(resource.getEntity(w1), resource.getEntity(w2));
} catch (SimilarityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (LexicalSemanticResourceException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
   return 0;
}
</code>```

i use the class like this:

```<code>double intermscore = comparator.compareWords(word1, word2);
</code>```

I use LexicalSemanticResource as resource for comparing, it can be wordnet, wikipedia, germanet etc. Now i noticed that all of the resources i need are in uby (https://www.ukp.tu-darmstadt.de/data/lexical-resources/uby/, https://github.com/dkpro/dkpro-uby/blob/master/de.tudarmstadt.ukp.uby.lmf.api-asl/src/main/java/de/tudarmstadt/ukp/lmf/api/Uby.java).

My question is: can i replace the resource with a resource from uby so I don't have to include a new resource again each time i need one? so instead of ResourceFactory.getInstance().get("wordnet"), i want to use the uby resource, so sth like new Uby().getLexicalResource("wordnet") - however lexicalresource from uby is not the same as LexicalSemanticResource i use now for semantic comparison. So: Instead of using e.g. LexicalSemanticResource wordnet, i want to use wordnet from uby for the comparators. Is there a way to do this?

答:
There currently is no way to do this. Uby resources and LSR resources are not compatible.

There were plans to switch, but the issue has been open for a while:
https://github.com/dkpro/dkpro-similarity/issues/39

Title: Use dkpro semantic similarity with uby

Body:
I want to compute similarity between strings with dkpro similarity (https://dkpro.github.io/dkpro-similarity/), it works, like so:

import org.dkpro.similarity.algorithms.api.SimilarityException;
import org.dkpro.similarity.algorithms.api.TextSimilarityMeasure;
import org.dkpro.similarity.algorithms.lsr.LexSemResourceComparator;
import org.dkpro.similarity.algorithms.lsr.gloss.GlossOverlapComparator;
import org.dkpro.similarity.algorithms.lsr.path.JiangConrathComparator;
import org.dkpro.similarity.algorithms.lsr.path.LeacockChodorowComparator;
import org.dkpro.similarity.algorithms.lsr.path.LinComparator;
import org.dkpro.similarity.algorithms.lsr.path.ResnikComparator;
import org.dkpro.similarity.algorithms.lsr.path.WuPalmerComparator;

import de.tudarmstadt.ukp.dkpro.lexsemresource.LexicalSemanticResource;
import de.tudarmstadt.ukp.dkpro.lexsemresource.core.ResourceFactory;
import de.tudarmstadt.ukp.dkpro.lexsemresource.exception.LexicalSemanticResourceException;
import de.tudarmstadt.ukp.dkpro.lexsemresource.exception.ResourceLoaderException;
import learninggoals.analysis.controller.settingtypes.SimilarityAlgorithm;

public class SemResourceComparator implements WordsComparator{
private LexicalSemanticResource resource;
private LexSemResourceComparator comparator;

//en lang
public SemResourceComparator(String resourcetype, SimilarityAlgorithm algorithm, String lang) {

        try {
            resource = ResourceFactory.getInstance().get(resourcetype, lang);
        } catch (ResourceLoaderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
        switch(algorithm){
        /*case ESA://this is vector
            comparator = new GlossOverlapComparator(resource, false);
            break;*/
        case GLOSSOVERLAP:

            comparator = new GlossOverlapComparator(resource, false);
            break;
        case JIANG_CONRATH:
            comparator = new JiangConrathComparator(resource, resource.getRoot());
            break;
        case LEACOCK_CHODOROW:
            comparator = new LeacockChodorowComparator(resource);
            break;
        case LIN:
            comparator = new LinComparator(resource, resource.getRoot());
            break;
        case RESNIK:
            comparator = new ResnikComparator(resource, resource.getRoot());
            break;
        case WUPALMER:
            comparator = new WuPalmerComparator(resource, resource.getRoot());
            break;
        default:
            break;

        }
        } catch (LexicalSemanticResourceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

@Override
public double compareWords(String w1, String w2) {

   try {
    return comparator.getSimilarity(resource.getEntity(w1), resource.getEntity(w2));
} catch (SimilarityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (LexicalSemanticResourceException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
   return 0;
}

i use the class like this:

double intermscore = comparator.compareWords(word1, word2);

I use LexicalSemanticResource as resource for comparing, it can be wordnet, wikipedia, germanet etc. Now i noticed that all of the resources i need are in uby (https://www.ukp.tu-darmstadt.de/data/lexical-resources/uby/, https://github.com/dkpro/dkpro-uby/blob/master/de.tudarmstadt.ukp.uby.lmf.api-asl/src/main/java/de/tudarmstadt/ukp/lmf/api/Uby.java).

My question is: can i replace the resource with a resource from uby so I don't have to include a new resource again each time i need one? so instead of ResourceFactory.getInstance().get("wordnet"), i want to use the uby resource, so sth like new Uby().getLexicalResource("wordnet") - however lexicalresource from uby is not the same as LexicalSemanticResource i use now for semantic comparison. So: Instead of using e.g. LexicalSemanticResource wordnet, i want to use wordnet from uby for the comparators. Is there a way to do this?


问:
Python: How to write to file and download it?
I a have flask based web service where I trying to download the results to a file to user's desktop (via https).

I tried :

```<code>def write_results_to_file(results):
    with open('output', 'w') as f:
     f.write('\t'.join(results[1:]) + '\n')
</code>```

this method gets activated when I click export button in the ui.

But I am getting :

```<code><type 'exceptions.IOError'>: [Errno 13] Permission denied: 'output'
      args = (13, 'Permission denied')
      errno = 13
      filename = 'output'
      message = ''
      strerror = 'Permission denied'
</code>```

Can some one tell me what I am doing wrong here ?

答:
Can some one tell me what I am doing wrong here ?

The function you posted isn't an actual Flask view function (app.route()), so it isn't entirely clear what your server is doing.

This may be closer to the code you need:

```<code>@app.route("/get_results")
def get_results():
    tsv_plaintext = ''

    # I'm assuming 'results' is a 2D array
    for row in results:
        tsv_plaintext += '\t'.join(row)
        tsv_plaintext += '\n'

    return Response(
        tsv_plaintext,
        mimetype="text/tab-separated-values",
        headers={"Content-disposition":
                 "attachment; filename=results.tsv"})
</code>```

(With assistance from Flask: Download a csv file on clicking a button)

Body:
I a have flask based web service where I trying to download the results to a file to user's desktop (via https).

I tried :

def write_results_to_file(results):
    with open('output', 'w') as f:
     f.write('\t'.join(results[1:]) + '\n')

this method gets activated when I click export button in the ui.

But I am getting :

<type 'exceptions.IOError'>: [Errno 13] Permission denied: 'output'
      args = (13, 'Permission denied')
      errno = 13
      filename = 'output'
      message = ''
      strerror = 'Permission denied'

Can some one tell me what I am doing wrong here ?

Body:
Can some one tell me what I am doing wrong here ?

The function you posted isn't an actual Flask view function (app.route()), so it isn't entirely clear what your server is doing.

This may be closer to the code you need:

@app.route("/get_results")
def get_results():
    tsv_plaintext = ''

    # I'm assuming 'results' is a 2D array
    for row in results:
        tsv_plaintext += '\t'.join(row)
        tsv_plaintext += '\n'

    return Response(
        tsv_plaintext,
        mimetype="text/tab-separated-values",
        headers={"Content-disposition":
                 "attachment; filename=results.tsv"})

(With assistance from Flask: Download a csv file on clicking a button)


问:
ValueError: Dimensions must be equal, but are 784 and 500 for 'MatMul_1' (op: 'MatMul') with input shapes: [?,784], [500,500]
I'm new to tensorflow and I'm following a tutorial by sentdex. I keep on getting the error -

```<code>ValueError: Dimensions must be equal, but are 784 and 500 for
'MatMul_1' (op: 'MatMul') with input shapes: [?,784], [500,500].
</code>```

The snippet where I believe is causing the issue is -

```<code>l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']),
hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)

l2 = tf.add(tf.matmul(data, hidden_2_layer['weights']),
hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)

l3 = tf.add(tf.matmul(data, hidden_3_layer['weights']),
hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)

output = tf.add(tf.matmul(l3, output_layer['weights']),
output_layer['biases'])

return output
</code>```

Although I'm a noob and may be wrong. My entire code is -

```<code>mnist = input_data.read_data_sets("/tmp/ data/", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')

def neural_network_model(data):
hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,
n_nodes_hl1])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl1]))}

hidden_2_layer = {'weights':
tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl2]))}

hidden_3_layer = {'weights':
tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3,
n_classes])),
                'biases': tf.Variable(tf.random_normal([n_classes]))}

l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']),
hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)

l2 = tf.add(tf.matmul(data, hidden_2_layer['weights']),
hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)

l3 = tf.add(tf.matmul(data, hidden_3_layer['weights']),
hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)

output = tf.add(tf.matmul(l3, output_layer['weights']),
output_layer['biases'])

return output

def train_neural_network(x):
prediction = neural_network_model(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits
(logits=prediction, labels=y))
optimizer = tf.train.AdamOptimizer().minimize(cost)

hm_epochs = 10

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(hm_epochs):
        epoch_loss = 0
        for _ in range(int(mnist.train.num_examples / batch_size)):
            epoch_x, epoch_y = mnist.train.next_batch(batch_size)
            _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x,
y: epoch_y})
            epoch_loss += c
        print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:',
epoch_loss)

    correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
    print('Accuracy:', accuracy.eval({x: mnist.test.images, y:
mnist.test.labels}))

train_neural_network(x)
</code>```

Please help. By the way, I'm running on Mac in a virtual environment with Python 3.6.1 and Tensorflow 1.2. And I am using the IDE Pycharm CE. If any of that information is useful.

答:
The problem is that you are referencing data instead of l1. Instead of

```<code>l2 = tf.add(tf.matmul(data, hidden_2_layer['weights']),
                      hidden_2_layer['biases'])
</code>```

your code should read

```<code>l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']),
                      hidden_2_layer['biases'])
</code>```

and ditto for l3. Instead of

```<code>l3 = tf.add(tf.matmul(data, hidden_3_layer['weights']),
                      hidden_3_layer['biases'])
</code>```

you should have

```<code>l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']),
                      hidden_3_layer['biases'])
</code>```

The following code ran without error for me:

```<code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')

def print_shape(obj):
    print(obj.get_shape().as_list())

def neural_network_model(data):
    hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,
                                                               n_nodes_hl1])),
                      'biases':
                      tf.Variable(tf.random_normal([n_nodes_hl1]))}

    hidden_2_layer = {'weights':
                      tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                      'biases':
                      tf.Variable(tf.random_normal([n_nodes_hl2]))}

    hidden_3_layer = {'weights':
                      tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                      'biases':
                      tf.Variable(tf.random_normal([n_nodes_hl3]))}

    output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3,
                                                             n_classes])),
                    'biases': tf.Variable(tf.random_normal([n_classes]))}
    print_shape(data)
    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']),
                hidden_1_layer['biases'])
    print_shape(l1)
    l1 = tf.nn.relu(l1)
    print_shape(l1)
    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']),
                hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']),
                hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.add(tf.matmul(l3, output_layer['weights']),
                    output_layer['biases'])

    return output

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits
                          (logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 10

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples / batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x,
                                                              y: epoch_y})
                epoch_loss += c
            print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:',
                  epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        print('Accuracy:', accuracy.eval({x: mnist.test.images, y:
                                          mnist.test.labels}))

train_neural_network(x)
</code>```

Body:
I'm new to tensorflow and I'm following a tutorial by sentdex. I keep on getting the error -

ValueError: Dimensions must be equal, but are 784 and 500 for
'MatMul_1' (op: 'MatMul') with input shapes: [?,784], [500,500].

The snippet where I believe is causing the issue is -

l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']),
hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)

l2 = tf.add(tf.matmul(data, hidden_2_layer['weights']),
hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)

l3 = tf.add(tf.matmul(data, hidden_3_layer['weights']),
hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)

output = tf.add(tf.matmul(l3, output_layer['weights']),
output_layer['biases'])

return output

Although I'm a noob and may be wrong. My entire code is -

mnist = input_data.read_data_sets("/tmp/ data/", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')

def neural_network_model(data):
hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,
n_nodes_hl1])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl1]))}

hidden_2_layer = {'weights':
tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl2]))}

hidden_3_layer = {'weights':
tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                  'biases':
tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3,
n_classes])),
                'biases': tf.Variable(tf.random_normal([n_classes]))}

l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']),
hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)

l2 = tf.add(tf.matmul(data, hidden_2_layer['weights']),
hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)

l3 = tf.add(tf.matmul(data, hidden_3_layer['weights']),
hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)

output = tf.add(tf.matmul(l3, output_layer['weights']),
output_layer['biases'])

return output

def train_neural_network(x):
prediction = neural_network_model(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits
(logits=prediction, labels=y))
optimizer = tf.train.AdamOptimizer().minimize(cost)

hm_epochs = 10

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(hm_epochs):
        epoch_loss = 0
        for _ in range(int(mnist.train.num_examples / batch_size)):
            epoch_x, epoch_y = mnist.train.next_batch(batch_size)
            _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x,
y: epoch_y})
            epoch_loss += c
        print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:',
epoch_loss)

    correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
    print('Accuracy:', accuracy.eval({x: mnist.test.images, y:
mnist.test.labels}))

train_neural_network(x)

Please help. By the way, I'm running on Mac in a virtual environment with Python 3.6.1 and Tensorflow 1.2. And I am using the IDE Pycharm CE. If any of that information is useful.

Body:
The problem is that you are referencing data instead of l1. Instead of

l2 = tf.add(tf.matmul(data, hidden_2_layer['weights']),
                      hidden_2_layer['biases'])

your code should read

l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']),
                      hidden_2_layer['biases'])

and ditto for l3. Instead of

l3 = tf.add(tf.matmul(data, hidden_3_layer['weights']),
                      hidden_3_layer['biases'])

you should have

l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']),
                      hidden_3_layer['biases'])

The following code ran without error for me:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')

def print_shape(obj):
    print(obj.get_shape().as_list())

def neural_network_model(data):
    hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,
                                                               n_nodes_hl1])),
                      'biases':
                      tf.Variable(tf.random_normal([n_nodes_hl1]))}

    hidden_2_layer = {'weights':
                      tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                      'biases':
                      tf.Variable(tf.random_normal([n_nodes_hl2]))}

    hidden_3_layer = {'weights':
                      tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                      'biases':
                      tf.Variable(tf.random_normal([n_nodes_hl3]))}

    output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3,
                                                             n_classes])),
                    'biases': tf.Variable(tf.random_normal([n_classes]))}
    print_shape(data)
    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']),
                hidden_1_layer['biases'])
    print_shape(l1)
    l1 = tf.nn.relu(l1)
    print_shape(l1)
    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']),
                hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']),
                hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.add(tf.matmul(l3, output_layer['weights']),
                    output_layer['biases'])

    return output

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits
                          (logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 10

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples / batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x,
                                                              y: epoch_y})
                epoch_loss += c
            print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:',
                  epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        print('Accuracy:', accuracy.eval({x: mnist.test.images, y:
                                          mnist.test.labels}))

train_neural_network(x)


问:
Good spam filter options for django blogs/comments
I am working on a simple django app that allows users to create posts and then comment on them. I would like to have some sort of spam filtering implemented. At the moment I am only doing honeypot checking and a captchta. But the problem is that users can still post spam (links/ads/etc), my main concern is links.

I have been looking at SpamBayes and am not sure how to apply it to my site at the moment.

Are there any simple lightweight solutions that will filter most spam from the posts?

I am thinking of creating a simple regexp filter that will scan each token and check to see if it matches urls/emails etc. The problem with this approach is that it might get ineffecient depending on how regexp's are used.

答: You could always use Akismet via a Django module.  I use Akismet with my WordPress blog and it's over 99% effective at flagging spam.</p>


问:
Get modules names from a package in python
Lets say that I have a python package and I want to list out all the modules within this package. i.e.

```<code>>>> import my_package
>>> import inspect
>>> inspect.getmembers(my_package, inspect.ismodule)
>>> []
</code>```

For some reason I am getting an empty list. Now if I manually load a module from the package then:

```<code>>>> import my_package.module_a
>>> inspect.getmembers(my_package, inspect.ismodule)
>>> ['module_a, <module '....'>]
</code>```

Assuming that I have multiple modules and I don't want to load them one by one is there any other way to do it? (p.s. from my_package import * won't work).

Furthermore do you know what is causing this behavior? Is anything that has to do with namespaces?

P.S Packages are not locally installed, I am loading everything from a server.

答: There isn't really a guaranteed way to get every possible module that could ever exist within a package namespace.  You can search the package directory for subpackage directories and module files, but there's nothing stopping some bit of code from just creating a types.ModuleType object and attaching it the top package.  If the package you're dealing with is a namespace package, there could be any number of modules and subpackages located in different locations on disk.

Body:
Lets say that I have a python package and I want to list out all the modules within this package. i.e.

>>> import my_package
>>> import inspect
>>> inspect.getmembers(my_package, inspect.ismodule)
>>> []

For some reason I am getting an empty list. Now if I manually load a module from the package then:

>>> import my_package.module_a
>>> inspect.getmembers(my_package, inspect.ismodule)
>>> ['module_a, <module '....'>]

Assuming that I have multiple modules and I don't want to load them one by one is there any other way to do it? (p.s. from my_package import * won't work).

Furthermore do you know what is causing this behavior? Is anything that has to do with namespaces?

P.S Packages are not locally installed, I am loading everything from a server.


答:
Use regular expressions in your LIKE clause. Look at the example here Using RegEx in SQL Server

In Sql server your LIKE clause might look like this.

```<code>LIKE '[AEIOU]%[aeiou]'
</code>```

In DB2 the syntax is slightly different. Look few examples down on this page.

https://www.ibm.com/developerworks/data/library/techarticle/0301stolze/0301stolze.html

Title: Query city names starting and ending with vowels

Body:
I wrote this code (db2) and it works just fine, but I'm wondering, is there a shorter way to write this?

Select Distinct city
From   station
Where  city Like 'A%a'
       Or city Like 'A%e'
       Or city Like 'A%i'
       Or city Like 'A%o'
       Or city Like 'A%u'
       Or city Like 'E%a'
       Or city Like 'E%e'
       Or city Like 'E%i'
       Or city Like 'E%o'
       Or city Like 'E%u'
       Or city Like 'I%a'
       Or city Like 'I%e'
       Or city Like 'I%i'
       Or city Like 'I%o'
       Or city Like 'I%u'
       Or city Like 'O%a'
       Or city Like 'O%e'
       Or city Like 'O%i'
       Or city Like 'O%o'
       Or city Like 'O%u'
       Or city Like 'U%a'
       Or city Like 'U%e'
       Or city Like 'U%i'
       Or city Like 'U%o'
       Or city Like 'U%u';

Body:
Use regular expressions in your LIKE clause. Look at the example here Using RegEx in SQL Server

In Sql server your LIKE clause might look like this.

LIKE '[AEIOU]%[aeiou]'

In DB2 the syntax is slightly different. Look few examples down on this page.

https://www.ibm.com/developerworks/data/library/techarticle/0301stolze/0301stolze.html


问:
Data not showing up intermittently on the OpenTSDB UI
We are running some high volume tests by pushing metrics to OpenTSDB (2.3.0) with BigTable, and a curious problem surfaces from time to time. For some metrics, an hour of data stops showing up on the web UI when we run a query. The span of "missing" data is very clearcut and borders on the hour (UTC). After a while, while rerunning the same query, the data shows up. There does not seem to be any pattern that we can deduce here, other than the hour span. Any pointers on what to look for and debug this?</p>

答:
How long do you have to wait before the data shows up? Is it always the most recent hour that is missing?

Have you tried using OpenTSDB CLI when this is happening and issuing a scan to see if the data is available that way?

http://opentsdb.net/docs/build/html/user_guide/cli/scan.html

You could also check via an HBase shell scan to see if you can get the raw data that way (here's information on how it's stored in HBase):

http://opentsdb.net/docs/build/html/user_guide/backends/hbase.html

If you can verify the data is there then it seems likely to be a web UI problem. If not, the next likely culprit is something getting backed up in the write pipeline.

I am not aware of any particular issue in the Google Cloud Bigtable backend layer that would cause this behavior, but I believe some folks have encountered issues with OpenTSDB compactions during periods of high load that result in degraded performance.

It's worth checking in the Google Cloud Console to see if there's any outliers in the latency, CPU or throughput graphs that correlate with the times during which you experience the issue.


问:
Do I need to create a different awk script if I don't want to perform the same actions on all of the files i pass as parameters?
I'm a noob writing an awk script to combine two differently formatted files and insert specific data from each into another file, and I was wondering how I could specify which actions to perform on which files? In constructing the pattern statement I want to reference a different field number depending on which file I'm dealing with. Would that require a separate script? Ex:

```<code>file 1:
blue 6'0
brown 5'8
green 5'4

file 2:
36 28 20
</code>```

and then I'd like to combine these two into (after a specfic string)

```<code>file 3:
*string*
blue 6'0 36
brown 5'8 20
green 5'4 28
</code>```

I know in bash scripting the $ references parameter number, but in awk that sign references field number. Any insight you could provide would be helpful. Thanks

答:
Apart from whatever it is you need to do with *string*, all you need is:

```<code>$ awk 'NR==FNR{split($0,a);next} {print $0,a[FNR]}' file2 file1
blue 6'0 36
brown 5'8 28
green 5'4 20
</code>```

Given your clarified requirement that the above output has to go after the text "string" in file3:

```<code>$ cat file3
foo
string
bar

$ awk '
    ARGIND==1 { split($0,a) }
    ARGIND==2 { new = new $0 OFS a[FNR] ORS }
    ARGIND==3 { print; if (/string/) printf "%s", new }
' file2 file1 file3
foo
string
blue 6'0 36
brown 5'8 28
green 5'4 20
bar
</code>```

The above uses GNU awk for ARGIND, if you don't have GNU awk then just add a line FNR==1{ARGIND++} at the start of the script.

Body:
I'm a noob writing an awk script to combine two differently formatted files and insert specific data from each into another file, and I was wondering how I could specify which actions to perform on which files? In constructing the pattern statement I want to reference a different field number depending on which file I'm dealing with. Would that require a separate script? Ex:

file 1:
blue 6'0
brown 5'8
green 5'4

file 2:
36 28 20

and then I'd like to combine these two into (after a specfic string)

file 3:
*string*
blue 6'0 36
brown 5'8 20
green 5'4 28

I know in bash scripting the $ references parameter number, but in awk that sign references field number. Any insight you could provide would be helpful. Thanks

Body:
Apart from whatever it is you need to do with *string*, all you need is:

$ awk 'NR==FNR{split($0,a);next} {print $0,a[FNR]}' file2 file1
blue 6'0 36
brown 5'8 28
green 5'4 20

Given your clarified requirement that the above output has to go after the text "string" in file3:

$ cat file3
foo
string
bar

$ awk '
    ARGIND==1 { split($0,a) }
    ARGIND==2 { new = new $0 OFS a[FNR] ORS }
    ARGIND==3 { print; if (/string/) printf "%s", new }
' file2 file1 file3
foo
string
blue 6'0 36
brown 5'8 28
green 5'4 20
bar

The above uses GNU awk for ARGIND, if you don't have GNU awk then just add a line FNR==1{ARGIND++} at the start of the script.


问:
Iterating through table columns until null value
I'm working with some data on SQL Server through Access 2010 that I have no flexibility to change, only query on. Each individual entity gets one ID, and may have a list of attributes that follow it with no particular max or min entries. The solution that the person who created this dataset had was to create 37 different column sets of attributes. For each attribute, there are 4 columns (though only 2 are useful). In effect, there are 148 columns to represent possibly having 37 items, though most columns past group 3 or 4 are NULL. There is some consistency though- values go to the first column groups first. As soon as any column has a null value, it can be assumed that every column after it is also null. If the first column is null, it has no attributes. Data looks somewhat like this:

| ID | Attr1 | Code1 | Attr2  | Code2  | Attr3  | Code3  |
|----|-------|-------|--------|--------|--------|--------|
| 1  | Foo   | 2     | Bar    | 1      | (null) | (null) |
| 2  | Bar   | 2     | (null) | (null) | (null) | (null) |
| 3  | Bar   | 1     | Foo    | 1      | Bar    | 2      |

What would be the best way to query on this so that if someone wants CodeX=1(X being any number), the query returns results even if that row has Code1=1 or Code37=1. I considered doing something like this:

```<code>A.Mod1=1
Or A.Mod2=1
Or A.Mod3=1
Or A.Mod4=1
...
</code>```

But that looks hideous and is about as DRY as a flash flood. It becomes especially horrendous if I want to target both attributes and codes, which I likely will do. I looked over CASE briefly in hopes that I could think of a way to use that to iterate through and bring me back the value of the first null value, but my drafts don't make a lot of sense and are just as messy/heavily nested.

Any thoughts on how to get through these aside from the really ugly method suggested above?

答:
Here's two ways to unpivot your data. Doing this, allows you to just add a where clause for your parameter. I.e. just add where code = 1 to the first query or where codes = 1 to the second. You could also pivot this back up if necessary, but this normalizes it a ton. As you said, you could do this with a crazy long CASE statement, but it's dry and lengthy.

```<code>declare @table table(ID int, Attr1 varchar(16), Code1 varchar(16),Attr2 varchar(16), Code2 varchar(16), Attr3 varchar(16), Code3 varchar(16))
insert into @table
values
(1,'Foo',2,'Bar',1,NULL,NULL),
(2,'Bar',2,NULL,NULL,NULL,NULL),
(3,'Bar',1,'Foo',1,'Bar',2)

select
    t.ID,
    c.Attribute,
    c.Code
from @table t
cross apply (
            select Attr1, Code1 union all
            select Attr2, Code2 union all
            select Attr3, Code3
            ) c (Attribute, Code)
where
    Attribute is not null

select
    ID,
    Attributes,
    Codes
from(
     select ID, Attr1, Code1, Attr2, Code2, Attr3, Code3
     from @table) main
unpivot
(Attributes for Attribute in (Attr1, Attr2, Attr3)) attr
unpivot
(Codes for Code in (Code1, Code2, Code3)) cod
where
    right(Attribute,1) = right(Code,1)
</code>```

Performance wise, it will likely be faster to NOT unpivot the data, but let the optimizer use the logic below with simple boolean comparisions

```<code>declare @Code int = 2
declare @Attr varchar(64) = null

select
    t.*
from @table t
where
    (Code1 = @Code or
     Code2 = @Code or
     Code3 = @Code or
     @Code is null)
     and
     (Attr1 = @Attr or
      Attr2 = @Attr or
      Attr3 = @Attr or
      @Attr is null)
</code>```

Body:
I'm working with some data on SQL Server through Access 2010 that I have no flexibility to change, only query on. Each individual entity gets one ID, and may have a list of attributes that follow it with no particular max or min entries. The solution that the person who created this dataset had was to create 37 different column sets of attributes. For each attribute, there are 4 columns (though only 2 are useful). In effect, there are 148 columns to represent possibly having 37 items, though most columns past group 3 or 4 are NULL. There is some consistency though- values go to the first column groups first. As soon as any column has a null value, it can be assumed that every column after it is also null. If the first column is null, it has no attributes. Data looks somewhat like this:

| ID | Attr1 | Code1 | Attr2  | Code2  | Attr3  | Code3  |
|----|-------|-------|--------|--------|--------|--------|
| 1  | Foo   | 2     | Bar    | 1      | (null) | (null) |
| 2  | Bar   | 2     | (null) | (null) | (null) | (null) |
| 3  | Bar   | 1     | Foo    | 1      | Bar    | 2      |

What would be the best way to query on this so that if someone wants CodeX=1(X being any number), the query returns results even if that row has Code1=1 or Code37=1. I considered doing something like this:

A.Mod1=1
Or A.Mod2=1
Or A.Mod3=1
Or A.Mod4=1
...

But that looks hideous and is about as DRY as a flash flood. It becomes especially horrendous if I want to target both attributes and codes, which I likely will do. I looked over CASE briefly in hopes that I could think of a way to use that to iterate through and bring me back the value of the first null value, but my drafts don't make a lot of sense and are just as messy/heavily nested.

Any thoughts on how to get through these aside from the really ugly method suggested above?

Body:
Here's two ways to unpivot your data. Doing this, allows you to just add a where clause for your parameter. I.e. just add where code = 1 to the first query or where codes = 1 to the second. You could also pivot this back up if necessary, but this normalizes it a ton. As you said, you could do this with a crazy long CASE statement, but it's dry and lengthy.

declare @table table(ID int, Attr1 varchar(16), Code1 varchar(16),Attr2 varchar(16), Code2 varchar(16), Attr3 varchar(16), Code3 varchar(16))
insert into @table
values
(1,'Foo',2,'Bar',1,NULL,NULL),
(2,'Bar',2,NULL,NULL,NULL,NULL),
(3,'Bar',1,'Foo',1,'Bar',2)

select
    t.ID,
    c.Attribute,
    c.Code
from @table t
cross apply (
            select Attr1, Code1 union all
            select Attr2, Code2 union all
            select Attr3, Code3
            ) c (Attribute, Code)
where
    Attribute is not null

select
    ID,
    Attributes,
    Codes
from(
     select ID, Attr1, Code1, Attr2, Code2, Attr3, Code3
     from @table) main
unpivot
(Attributes for Attribute in (Attr1, Attr2, Attr3)) attr
unpivot
(Codes for Code in (Code1, Code2, Code3)) cod
where
    right(Attribute,1) = right(Code,1)

Performance wise, it will likely be faster to NOT unpivot the data, but let the optimizer use the logic below with simple boolean comparisions

declare @Code int = 2
declare @Attr varchar(64) = null

select
    t.*
from @table t
where
    (Code1 = @Code or
     Code2 = @Code or
     Code3 = @Code or
     @Code is null)
     and
     (Attr1 = @Attr or
      Attr2 = @Attr or
      Attr3 = @Attr or
      @Attr is null)


问:
Are technologies like LINQ, WPF, WF just libraries or development changing methodologies
Lately, Microsoft keeps coming out with new technologies Linq, WF, WPF, etc... Seems to me that they are presented like technology inovations that completely change the way your applications are designed and coded.

Yet,they are based on the same underlying framework (2.0) If I look at Java, there are a lot of libraries that provide critical functionality (Hibernate, Spring for example), yet they are considered to be still just libraries.

So my question is, Do people think that these technologies are really changing the way we write windows code? Is it worth learning every development methodology that Microsoft is putting out with Visual Studio releases.

Or is this just hype. As libraries, they are important, however, not critical to get job done. Will they make as big of an impact and ss I learn it, it will considerably effect my future as a developer?

EDIT: The same goes for some of the language futures that are implemented. Some are changing the way we program (Generics) Others, are much less critical (Partial Classes) That makes learning Generics a critical part of learning .NET, unlike learning to use Partial Classes

答:
To me, technology innovations change the way users feel about and interact with computers.  Google search and phone based applications are good examples of this that everyone experiences.  Of the latest Microsoft tech stack, I think only WPF is at all innovative.  It actually allows developers to create new stunning UIs which before were too expensive or impossible to build.  This then changes how the users interface with our software.  All the rest are just a bunch more tools(libraries) for a developer to put in his tool bag to pull out when/if he needs them.  You certainly can code great applications without them.

I am actually starting to find that the continual stream of new MS development "improvements" are starting to make worse developers.  Now instead of having time to focus on learning the business, creating great interfaces, talking with users, testing, and designing maintainable applications; we barely have time to keep up on buzzwords and new libraries.

Don't get me wrong. Linq is great (especially over xml), but it doesn't allow me to accomplish anything I couldn't before with ADO.net (or ADO or DAO or OLEDB before that).

OwnerDisplayName: Timur Fanshteyn

LastEditorDisplayName: Timur Fanshteyn

OwnerDisplayName: DancesWithBamboo

LastEditorDisplayName: DancesWithBamboo


问:
Why does my MaybeT (State <type>) () ignore state changes?
Short version: when I use runMaybeT and then runState on a monad of type MaybeT (State <type>) (), it looks like no state changes occur even though the Maybe result is equal to Just (). Why?

Full version: I'm writing a program to solve the Towers of Hanoi. I represent the solution as a list of State monads that, when sequenced, manipulate an initial Towers state:

```<code>data Towers = Towers [Int] [Int] [Int]
    deriving (Show)
type Move = State Towers ()

towerMoves :: Int -> Rod -> Rod -> [Move]
towerMoves 1 r1 r2 = [pop r1 >>= push r2]
towerMoves n r1 r2 = topToTemp ++ (towerMoves 1 r1 r2) ++ topToFinal
  where
    r3 = other r1 r2
    topToTemp = towerMoves (n - 1) r1 r3
    topToFinal = towerMoves (n - 1) r3 r2

moves = towerMoves 5 First Third
initTowers = Towers [1,2,3,4,5] [] []

main = print $ snd $ runState (sequence_ moves) initTowers
</code>```

Thus far, this program produces the correct output:

```<code>Towers [] [] [1,2,3,4,5]
</code>```

Then, I wanted to verify that the program respected the rules of the puzzle, namely that no larger disc (represented by numbers here) comes before a smaller disc. I wanted to insert some kind of verification after every Move, so I tried to use the MaybeT monad transformer to send a failure down the list of moves:

```<code>verifiedMoves :: [MaybeT (State Towers) ()]
verifiedMoves = map ((>> verify) . return) moves
  where
    check :: [Int] -> Bool
    check [] = True
    check [_] = True
    check (x:y:ys) = (x < y) && check (y:ys)
    verify :: MaybeT (State Towers) ()
    verify = do
        (Towers xs ys zs) <- lift get
        guard (check xs && check ys && check zs)
</code>```

Accordingly I changed the main monad:

```<code>main = maybe (putStrLn "violation") (const $ print finalTowers) v
  where
    (v, finalTowers) = runState (runMaybeT $ sequence_ verifiedMoves) initTowers
</code>```

Now the output looks wrong, like no state changes occurred:

```<code>Towers [1,2,3,4,5] [] []
</code>```

If I make the initial state invalid, it indeed fails the verification. So if there is no state change because the effects of the Moves got interrupted, I would expect the output to be the word "violation."

Why, after applying runMaybeT, is the result of applying runState equal to (Just (), Towers [1,2,3,4,5] [] [])?

Here is the rest of the code, for reference. I tried lifting the get and put monads in my pop and push functions, but that produced the same output.

```<code>import Control.Monad
import Data.Functor.Identity
import Control.Monad.State
import Control.Monad.Trans.Maybe
import qualified Data.Map as M

data Rod = First | Second | Third
    deriving (Show)

other :: Rod -> Rod -> Rod
other First Second = Third
other Second First = Third
other First Third = Second
other Third First = Second
other Second Third = First
other Third Second = First

getRod :: Towers -> Rod -> [Int]
getRod (Towers x y z) First  = x
getRod (Towers x y z) Second = y
getRod (Towers x y z) Third  = z

setRod :: Rod -> Towers -> [Int] -> Towers
setRod First t ds  = Towers ds r2 r3
  where
    r2 = t `getRod` Second
    r3 = t `getRod` Third
setRod Second t ds = Towers r1 ds r3
  where
    r1 = t `getRod` First
    r3 = t `getRod` Third
setRod Third t ds  = Towers r1 r2 ds
  where
    r1 = t `getRod` First
    r2 = t `getRod` Second

pop :: Rod -> State Towers Int
pop r = do
    t <- get
    let ds = t `getRod` r
        d = head ds
        load = setRod r
    put $ t `load` (tail ds)
    return d

push :: Rod -> Int -> State Towers ()
push r d = do
    t <- get
    let ds = t `getRod` r
        load = setRod r
    put $ t `load` (d:ds)
</code>```

答:
Look at this line

```<code>verifiedMoves = map ((>> verify) . return) moves
</code>```

equivalent to

```<code>= map (\m -> return m >> verify) moves
</code>```

but for all x, we have return x >> a = a, thus

```<code>= map (\_ -> verify) moves
</code>```

So you discarded the moves. You probably meant to use lift instead of return there.

Body:
Short version: when I use runMaybeT and then runState on a monad of type MaybeT (State <type>) (), it looks like no state changes occur even though the Maybe result is equal to Just (). Why?

Full version: I'm writing a program to solve the Towers of Hanoi. I represent the solution as a list of State monads that, when sequenced, manipulate an initial Towers state:

data Towers = Towers [Int] [Int] [Int]
    deriving (Show)
type Move = State Towers ()

towerMoves :: Int -> Rod -> Rod -> [Move]
towerMoves 1 r1 r2 = [pop r1 >>= push r2]
towerMoves n r1 r2 = topToTemp ++ (towerMoves 1 r1 r2) ++ topToFinal
  where
    r3 = other r1 r2
    topToTemp = towerMoves (n - 1) r1 r3
    topToFinal = towerMoves (n - 1) r3 r2

moves = towerMoves 5 First Third
initTowers = Towers [1,2,3,4,5] [] []

main = print $ snd $ runState (sequence_ moves) initTowers

Thus far, this program produces the correct output:

Towers [] [] [1,2,3,4,5]

Then, I wanted to verify that the program respected the rules of the puzzle, namely that no larger disc (represented by numbers here) comes before a smaller disc. I wanted to insert some kind of verification after every Move, so I tried to use the MaybeT monad transformer to send a failure down the list of moves:

verifiedMoves :: [MaybeT (State Towers) ()]
verifiedMoves = map ((>> verify) . return) moves
  where
    check :: [Int] -> Bool
    check [] = True
    check [_] = True
    check (x:y:ys) = (x < y) && check (y:ys)
    verify :: MaybeT (State Towers) ()
    verify = do
        (Towers xs ys zs) <- lift get
        guard (check xs && check ys && check zs)

Accordingly I changed the main monad:

main = maybe (putStrLn "violation") (const $ print finalTowers) v
  where
    (v, finalTowers) = runState (runMaybeT $ sequence_ verifiedMoves) initTowers

Now the output looks wrong, like no state changes occurred:

Towers [1,2,3,4,5] [] []

If I make the initial state invalid, it indeed fails the verification. So if there is no state change because the effects of the Moves got interrupted, I would expect the output to be the word "violation."

Why, after applying runMaybeT, is the result of applying runState equal to (Just (), Towers [1,2,3,4,5] [] [])?

Here is the rest of the code, for reference. I tried lifting the get and put monads in my pop and push functions, but that produced the same output.

import Control.Monad
import Data.Functor.Identity
import Control.Monad.State
import Control.Monad.Trans.Maybe
import qualified Data.Map as M

data Rod = First | Second | Third
    deriving (Show)

other :: Rod -> Rod -> Rod
other First Second = Third
other Second First = Third
other First Third = Second
other Third First = Second
other Second Third = First
other Third Second = First

getRod :: Towers -> Rod -> [Int]
getRod (Towers x y z) First  = x
getRod (Towers x y z) Second = y
getRod (Towers x y z) Third  = z

setRod :: Rod -> Towers -> [Int] -> Towers
setRod First t ds  = Towers ds r2 r3
  where
    r2 = t `getRod` Second
    r3 = t `getRod` Third
setRod Second t ds = Towers r1 ds r3
  where
    r1 = t `getRod` First
    r3 = t `getRod` Third
setRod Third t ds  = Towers r1 r2 ds
  where
    r1 = t `getRod` First
    r2 = t `getRod` Second

pop :: Rod -> State Towers Int
pop r = do
    t <- get
    let ds = t `getRod` r
        d = head ds
        load = setRod r
    put $ t `load` (tail ds)
    return d

push :: Rod -> Int -> State Towers ()
push r d = do
    t <- get
    let ds = t `getRod` r
        load = setRod r
    put $ t `load` (d:ds)

Body:
Look at this line

verifiedMoves = map ((>> verify) . return) moves

equivalent to

= map (\m -> return m >> verify) moves

but for all x, we have return x >> a = a, thus

= map (\_ -> verify) moves

So you discarded the moves. You probably meant to use lift instead of return there.