问:
How to force overriding a method in a descendant, without having an abstract base class?
Question Heading seems to be little confusing, But I will Try to clear my question here.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public abstract class Employee
    {
        private string name;
        private int empid;
        BenefitPackage _BenefitPackage = new BenefitPackage();
        public string Name
         {
             get { return this.name; }
             set { this.name = value; }
            }
        public int EmpId
        {
            get { return this.empid; }
            set
            {
                if (value == 1)
                    return;
                this.empid = value; }
        }
        public Employee(string Name, int EmpId)
        {
            this.Name = Name;
            this.EmpId = EmpId;
        }
        public Employee()
        { }

        public abstract void GiveBonus();

    }

    public class Manager : Employee
    {
        private int noofstockoptions;
        public override void GiveBonus()
        {
            Console.WriteLine("Manger GiveBonus Override");
        }
        public int NoOfStockOptions
        {
            get { return this.noofstockoptions; }
            set { this.noofstockoptions = value; }
        }

        public Manager(string Name,int EmpId, int NoOfStockOptions):base(Name,EmpId)
        {
            this.NoOfStockOptions=NoOfStockOptions;
        }

    }
    public class SalesPerson:Employee
    {
        private int noofsales;
        public int NoOfSales
        {
            get { return this.noofsales; }
            set { this.noofsales = value; }
        }

        public SalesPerson(string Name, int EmpId, int NoOfSales):base(Name,EmpId)
        {
            this.NoOfSales = NoOfSales;
        }
        public override void GiveBonus()
        {
            Console.WriteLine("Hi from salesperson");
        }
    }
    public sealed class PTSalesPerson : SalesPerson
    {
        private int noofhrworked;
        public int NoOfHrWorked
        {
            get { return this.noofhrworked; }
            set { this.noofhrworked = value; }

        }
        public PTSalesPerson(string Name, int EmpId, int NoOfSales,int NoOfHrWorked):base(Name,EmpId,NoOfSales)
        {
            this.NoOfHrWorked = NoOfHrWorked;

        }
        //public new void GiveBonus()
        //{
        //    Console.WriteLine("hi from ptsalesperson");
        //}
    }

    class BenefitPackage
    {
        public int Bonus;
        public int GiveBonus()
        {
            int i = 200;
            return i;
        }

        private class innerPublic
        {
            public int innerBonus;

        }

    }

    class MainClass
    {
        public static void Main()
        {
        Manager _Manager=new Manager("Vaibhav",1,50);
        PTSalesPerson _PTSalesPerson = new PTSalesPerson("Shantanu", 1, 4, 6);
        _Manager.GiveBonus();

        Employee _emp;
        //_emp = new Employee("new emp",4);
        //_emp.GiveBonus();
        _PTSalesPerson.GiveBonus();
        ((SalesPerson)_PTSalesPerson).GiveBonus();
        Console.ReadLine();
        }

    }
}
</code>```

Please do not try to understand the whole code. I am summarising it.

Employee is a Abstract class, which have an abstract method GiveBonus

SalesPerson is a deriving from Employee. SalesPerson has to give definition to abstract Method GiveBonus.(SalesPerson can not be Abstract)

PTSalesPerson is deriving from SalesPerson.

Now my question is, How can I force PTSalesPerson to have its own implementation of GiveBonus.

答:
I very much hope my answer will help some people confused by this issue.

Bear with me, but I'll try to re-summarise what is being asked, just to ensure that I am answering the right question. Then I'll give the answer!

I think the essence of the question is: How do I declare a method in an abstract class so that is has an implementation but still requires a derived class to override the method?

C# doesn't appear to support this. If you declare the method 'abstract', it is not permitted to have an implementation (body). But if you declare it 'virtual', a derived class is not forced to override it. C# deosn't allow a method to be marked as both abstract and virtual.

I believe there are many situations where you wish to do this (what is being asked).

The way to solve this riddle is as follows: Declare two methods! One of them is marked 'abstract'; the other is marked 'virtual' and calls the first one somewhere in its body.

This way, the derived class is forced to override the abstract method, but the (partial) implementation in the virtual method can be safely inherited.

So, for example, the Employee method GiveBonus might be declared thus:

```<code>public abstract decimal ComputeBonus();
public virtual void GiveBonus() {
    decimal amount = ComputeBonus();
    if (amount > 0.0) PostBonus(amount);
}
</code>```

I'll leave the details of PostBonus to the imagination, but the beauty of this approach is that derived classes are forced to override ComputeBonus, yet GiveBonus benefits from the partial implementation provided in the base class. HTH

Body:
Question Heading seems to be little confusing, But I will Try to clear my question here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public abstract class Employee
    {
        private string name;
        private int empid;
        BenefitPackage _BenefitPackage = new BenefitPackage();
        public string Name
         {
             get { return this.name; }
             set { this.name = value; }
            }
        public int EmpId
        {
            get { return this.empid; }
            set
            {
                if (value == 1)
                    return;
                this.empid = value; }
        }
        public Employee(string Name, int EmpId)
        {
            this.Name = Name;
            this.EmpId = EmpId;
        }
        public Employee()
        { }

        public abstract void GiveBonus();

    }

    public class Manager : Employee
    {
        private int noofstockoptions;
        public override void GiveBonus()
        {
            Console.WriteLine("Manger GiveBonus Override");
        }
        public int NoOfStockOptions
        {
            get { return this.noofstockoptions; }
            set { this.noofstockoptions = value; }
        }

        public Manager(string Name,int EmpId, int NoOfStockOptions):base(Name,EmpId)
        {
            this.NoOfStockOptions=NoOfStockOptions;
        }

    }
    public class SalesPerson:Employee
    {
        private int noofsales;
        public int NoOfSales
        {
            get { return this.noofsales; }
            set { this.noofsales = value; }
        }

        public SalesPerson(string Name, int EmpId, int NoOfSales):base(Name,EmpId)
        {
            this.NoOfSales = NoOfSales;
        }
        public override void GiveBonus()
        {
            Console.WriteLine("Hi from salesperson");
        }
    }
    public sealed class PTSalesPerson : SalesPerson
    {
        private int noofhrworked;
        public int NoOfHrWorked
        {
            get { return this.noofhrworked; }
            set { this.noofhrworked = value; }

        }
        public PTSalesPerson(string Name, int EmpId, int NoOfSales,int NoOfHrWorked):base(Name,EmpId,NoOfSales)
        {
            this.NoOfHrWorked = NoOfHrWorked;

        }
        //public new void GiveBonus()
        //{
        //    Console.WriteLine("hi from ptsalesperson");
        //}
    }

    class BenefitPackage
    {
        public int Bonus;
        public int GiveBonus()
        {
            int i = 200;
            return i;
        }

        private class innerPublic
        {
            public int innerBonus;

        }

    }

    class MainClass
    {
        public static void Main()
        {
        Manager _Manager=new Manager("Vaibhav",1,50);
        PTSalesPerson _PTSalesPerson = new PTSalesPerson("Shantanu", 1, 4, 6);
        _Manager.GiveBonus();

        Employee _emp;
        //_emp = new Employee("new emp",4);
        //_emp.GiveBonus();
        _PTSalesPerson.GiveBonus();
        ((SalesPerson)_PTSalesPerson).GiveBonus();
        Console.ReadLine();
        }

    }
}

Please do not try to understand the whole code. I am summarising it.

Employee is a Abstract class, which have an abstract method GiveBonus

SalesPerson is a deriving from Employee. SalesPerson has to give definition to abstract Method GiveBonus.(SalesPerson can not be Abstract)

PTSalesPerson is deriving from SalesPerson.

Now my question is, How can I force PTSalesPerson to have its own implementation of GiveBonus.

Body:
I very much hope my answer will help some people confused by this issue.

Bear with me, but I'll try to re-summarise what is being asked, just to ensure that I am answering the right question. Then I'll give the answer!

I think the essence of the question is: How do I declare a method in an abstract class so that is has an implementation but still requires a derived class to override the method?

C# doesn't appear to support this. If you declare the method 'abstract', it is not permitted to have an implementation (body). But if you declare it 'virtual', a derived class is not forced to override it. C# deosn't allow a method to be marked as both abstract and virtual.

I believe there are many situations where you wish to do this (what is being asked).

The way to solve this riddle is as follows: Declare two methods! One of them is marked 'abstract'; the other is marked 'virtual' and calls the first one somewhere in its body.

This way, the derived class is forced to override the abstract method, but the (partial) implementation in the virtual method can be safely inherited.

So, for example, the Employee method GiveBonus might be declared thus:

public abstract decimal ComputeBonus();
public virtual void GiveBonus() {
    decimal amount = ComputeBonus();
    if (amount > 0.0) PostBonus(amount);
}

I'll leave the details of PostBonus to the imagination, but the beauty of this approach is that derived classes are forced to override ComputeBonus, yet GiveBonus benefits from the partial implementation provided in the base class. HTH


来源: stackexchange

问:
How to send webcam frames from client to flask server?
I'm using openCV for face recognition and would like to do the same for a client by getting their webcam frames on the flask server side and performing face recognition.

I was able to do it on the server side but I want the client's webcam to be used instead of the server's.

答:
Create a client script and a server script and use sockets to communicate between the two.

server.py:

```<code>import socket

s = socket.socket()
s.bind(("0.0.0.0",789)) #Whatever port
try:
   s.listen(1)
except:
   print("[*]Start the script with more permissions")
   exit(0)
conn , adds = s.accept()
print("[*]Received connection")
while True:
    data = str(conn.recv(99999))  #This is the image you receive
    display_image_on_screen_and_facial_recognicion(data)
</code>```

client.py:

```<code>import socket
s = socket.socket
try:
    s.connect(("0.0.0.0",789)) #Same port as server side
except:
    print("[*]Server is not up!")
    exit(0)
else:
    while True:
        data = capture_webcam()
        s.send(data.encode())
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Create a client script and a server script and use sockets to communicate between the two.

server.py:

import socket

s = socket.socket()
s.bind(("0.0.0.0",789)) #Whatever port
try:
   s.listen(1)
except:
   print("[*]Start the script with more permissions")
   exit(0)
conn , adds = s.accept()
print("[*]Received connection")
while True:
    data = str(conn.recv(99999))  #This is the image you receive
    display_image_on_screen_and_facial_recognicion(data)

client.py:

import socket
s = socket.socket
try:
    s.connect(("0.0.0.0",789)) #Same port as server side
except:
    print("[*]Server is not up!")
    exit(0)
else:
    while True:
        data = capture_webcam()
        s.send(data.encode())


问:
Missing intercepts of OLS Regression models in Python statsmodels
I am running a rolling for example of 100 window OLS regression estimation of the dataset found in this link (https://drive.google.com/drive/folders/0B2Iv8dfU4fTUMVFyYTEtWXlzYkk) as in the following format.

```<code> time     X   Y
0.000543  0  10
0.000575  0  10
0.041324  1  10
0.041331  2  10
0.041336  3  10
0.04134   4  10
  ...
9.987735  55 239
9.987739  56 239
9.987744  57 239
9.987749  58 239
9.987938  59 239
</code>```

The third column (Y) in my dataset is my true value - that's what I wanted to predict (estimate). I want to do a prediction of Y (i.e. predict the current value of Y according to the previous 3 rolling values of X. For this, I have the following python script work using statsmodels.

```<code># /usr/bin/python -tt
import pandas as pd
import numpy as np
import statsmodels.api as sm

df=pd.read_csv('estimated_pred.csv')
df=df.dropna() # to drop nans in case there are any
window = 100
#print(df.index) # to print index
df['a']=None #constant
df['b1']=None #beta1
df['b2']=None #beta2
for i in range(window,len(df)):
    temp=df.iloc[i-window:i,:]
    RollOLS=sm.OLS(temp.loc[:,'Y'],sm.add_constant(temp.loc[:,['time','X']], has_constant = 'add')).fit()
    df.iloc[i,df.columns.get_loc('a')]=RollOLS.params[0]
    df.iloc[i,df.columns.get_loc('b1')]=RollOLS.params[1]
    df.iloc[i,df.columns.get_loc('b2')]=RollOLS.params[2]

# Predicted values in a row
 df['predicted']=df['a'].shift(1)+df['b1'].shift(1)*df['time']+df['b2'].shift(1)*df['X']

#print(df['predicted'])

print(temp)
</code>```

Which gives me a sample output of the following format.

```<code>         time   X   Y        a           b1           b2  predicted
0    0.000543   0  10     None         None         None       NaN
1    0.000575   0  10     None         None         None       NaN
2    0.041324   1  10     None         None         None       NaN
3    0.041331   2  10     None         None         None       NaN
4    0.041336   3  10     None         None         None       NaN
..        ...  ..  ..      ...          ...          ...       ...
50    0.041340   4  10       10            0  1.55431e-15       NaN
51    0.041345   5  10       10   1.7053e-13  7.77156e-16        10
52    0.041350   6  10       10  1.74623e-09 -7.99361e-15        10
53    0.041354   7  10       10  6.98492e-10 -6.21725e-15        10
..        ...  ..  ..      ...          ...          ...       ...
509  0.160835  38  20       20  4.88944e-09 -1.15463e-14        20
510  0.160839  39  20       20  1.86265e-09  5.32907e-15        20
..        ...  ..  ..      ...          ...          ...       ...
</code>```

Finally, I want to include the mean squared error (MSE) for all the prediction (a summary of the OLS regression analysis) values. For example, if we look at row 5, the value of X is 2 and the value of Y is 10. Let's say the prediction value of y at the current row is 6 and therefore the mse will be (10-6)^2. The sm.OLS returns an instance of this class <class 'statsmodels.regression.linear_model.OLS'> when we do print (RollOLS.summary()).

```<code>OLS Regression Results
==============================================================================
Dep. Variable:                      Y   R-squared:                        -inf
Model:                            OLS   Adj. R-squared:                   -inf
Method:                 Least Squares   F-statistic:                    -48.50
Date:                Tue, 04 Jul 2017   Prob (F-statistic):               1.00
Time:                        22:19:18   Log-Likelihood:                 2359.7
No. Observations:                 100   AIC:                            -4713.
Df Residuals:                      97   BIC:                            -4706.
Df Model:                           2
Covariance Type:            nonrobust
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
const        239.0000   2.58e-09   9.26e+10      0.000       239.000   239.000
time        4.547e-13   2.58e-10      0.002      0.999     -5.12e-10  5.13e-10
X          -3.886e-16    1.1e-13     -0.004      0.997     -2.19e-13  2.19e-13
==============================================================================
Omnibus:                       44.322   Durbin-Watson:                   0.000
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               86.471
Skew:                          -1.886   Prob(JB):                     1.67e-19
Kurtosis:                       5.556   Cond. No.                     9.72e+04
==============================================================================
</code>```

But the value of rsquared(print (RollOLS.rsquared)), for example, should have been between 0 and 1 instead of -inf and this seems to be the issue with missing intercepts. If we want to print the mse, we do print (RollOLS.mse_model)... etc as per the documentation. How can we add the intercepts and print the regression statistics with the correct values as we do for the predicted values? What am I doing wrong in here? Or is there another way of doing this using scikit-learnlibraries?

答:
Short Answer

The value of r^2 is going to be +/- inf as long as y remains constant over the regression window (100 observations in your case). You can find more details below, but intuition is that r^2 is the proportion of y's variance explained by X: if y's variance is zero, r^2 is simply not well defined.

Possible solution: Try to use a longer window, or resample Y and X so that Y does not remain constant for so many consecutive observations.

Long Answer

Looking at this I honestly think this is not the right dataset for the regression.
This is a simple plot of the data:

Does a linear combination of X and time explain Y? Mmm...doesn't look plausible.
Y almost looks like a discrete variable, so you probably want to look at logistic regressions.

To come to your question, the R^2 is the "the proportion of the variance in the dependent variable that is predictable from the independent variable(s)".
From wikipedia:

In your case it is very likely that Y is constant over 100 observations, hence it has 0 variance, that produces a division by zero hence the inf.

So I am afraid you should not look to fixes in the code, but you should rethink the problem and the way of fitting the data.

Body:
I am running a rolling for example of 100 window OLS regression estimation of the dataset found in this link (https://drive.google.com/drive/folders/0B2Iv8dfU4fTUMVFyYTEtWXlzYkk) as in the following format.

 time     X   Y
0.000543  0  10
0.000575  0  10
0.041324  1  10
0.041331  2  10
0.041336  3  10
0.04134   4  10
  ...
9.987735  55 239
9.987739  56 239
9.987744  57 239
9.987749  58 239
9.987938  59 239

The third column (Y) in my dataset is my true value - that's what I wanted to predict (estimate). I want to do a prediction of Y (i.e. predict the current value of Y according to the previous 3 rolling values of X. For this, I have the following python script work using statsmodels.

# /usr/bin/python -tt
import pandas as pd
import numpy as np
import statsmodels.api as sm

df=pd.read_csv('estimated_pred.csv')
df=df.dropna() # to drop nans in case there are any
window = 100
#print(df.index) # to print index
df['a']=None #constant
df['b1']=None #beta1
df['b2']=None #beta2
for i in range(window,len(df)):
    temp=df.iloc[i-window:i,:]
    RollOLS=sm.OLS(temp.loc[:,'Y'],sm.add_constant(temp.loc[:,['time','X']], has_constant = 'add')).fit()
    df.iloc[i,df.columns.get_loc('a')]=RollOLS.params[0]
    df.iloc[i,df.columns.get_loc('b1')]=RollOLS.params[1]
    df.iloc[i,df.columns.get_loc('b2')]=RollOLS.params[2]

# Predicted values in a row
 df['predicted']=df['a'].shift(1)+df['b1'].shift(1)*df['time']+df['b2'].shift(1)*df['X']

#print(df['predicted'])

print(temp)

Which gives me a sample output of the following format.

         time   X   Y        a           b1           b2  predicted
0    0.000543   0  10     None         None         None       NaN
1    0.000575   0  10     None         None         None       NaN
2    0.041324   1  10     None         None         None       NaN
3    0.041331   2  10     None         None         None       NaN
4    0.041336   3  10     None         None         None       NaN
..        ...  ..  ..      ...          ...          ...       ...
50    0.041340   4  10       10            0  1.55431e-15       NaN
51    0.041345   5  10       10   1.7053e-13  7.77156e-16        10
52    0.041350   6  10       10  1.74623e-09 -7.99361e-15        10
53    0.041354   7  10       10  6.98492e-10 -6.21725e-15        10
..        ...  ..  ..      ...          ...          ...       ...
509  0.160835  38  20       20  4.88944e-09 -1.15463e-14        20
510  0.160839  39  20       20  1.86265e-09  5.32907e-15        20
..        ...  ..  ..      ...          ...          ...       ...

Finally, I want to include the mean squared error (MSE) for all the prediction (a summary of the OLS regression analysis) values. For example, if we look at row 5, the value of X is 2 and the value of Y is 10. Let's say the prediction value of y at the current row is 6 and therefore the mse will be (10-6)^2. The sm.OLS returns an instance of this class <class 'statsmodels.regression.linear_model.OLS'> when we do print (RollOLS.summary()).

OLS Regression Results
==============================================================================
Dep. Variable:                      Y   R-squared:                        -inf
Model:                            OLS   Adj. R-squared:                   -inf
Method:                 Least Squares   F-statistic:                    -48.50
Date:                Tue, 04 Jul 2017   Prob (F-statistic):               1.00
Time:                        22:19:18   Log-Likelihood:                 2359.7
No. Observations:                 100   AIC:                            -4713.
Df Residuals:                      97   BIC:                            -4706.
Df Model:                           2
Covariance Type:            nonrobust
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
const        239.0000   2.58e-09   9.26e+10      0.000       239.000   239.000
time        4.547e-13   2.58e-10      0.002      0.999     -5.12e-10  5.13e-10
X          -3.886e-16    1.1e-13     -0.004      0.997     -2.19e-13  2.19e-13
==============================================================================
Omnibus:                       44.322   Durbin-Watson:                   0.000
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               86.471
Skew:                          -1.886   Prob(JB):                     1.67e-19
Kurtosis:                       5.556   Cond. No.                     9.72e+04
==============================================================================

But the value of rsquared(print (RollOLS.rsquared)), for example, should have been between 0 and 1 instead of -inf and this seems to be the issue with missing intercepts. If we want to print the mse, we do print (RollOLS.mse_model)... etc as per the documentation. How can we add the intercepts and print the regression statistics with the correct values as we do for the predicted values? What am I doing wrong in here? Or is there another way of doing this using scikit-learnlibraries?


问:
bash what is the test attribute for hidden directories and files
In bash script, to test if a directory entry is a folder, we use -d ,

```<code>shopt -s dotglob nullglob # to include hidden fille
for entry in *
if [ -d "$entry" ]; then # regular directory, not hidden ones...
</code>```

To test for file, -f

```<code>if [ -f "$entry" ]; then # regular file, not hidden ones...
</code>```

What attribute for hidden directory? ,  and hidden file?

答:
Hidden files / directories exist only by name convention in UNIX. Their names start with a dot:

```<code>if [[ -d "${entry}" && "${entry}" =~ ^\. ]] ; then
    echo "${entry} is a hidden folder"
fi
</code>```

Further (interesting) read: https://plus.google.com/u/0/+RobPikeTheHuman/posts/R58WgWwN9jp

Body:
In bash script, to test if a directory entry is a folder, we use -d ,

shopt -s dotglob nullglob # to include hidden fille
for entry in *
if [ -d "$entry" ]; then # regular directory, not hidden ones...

To test for file, -f

if [ -f "$entry" ]; then # regular file, not hidden ones...

What attribute for hidden directory? ,  and hidden file?

Body:
Hidden files / directories exist only by name convention in UNIX. Their names start with a dot:

if [[ -d "${entry}" && "${entry}" =~ ^\. ]] ; then
    echo "${entry} is a hidden folder"
fi

Further (interesting) read: https://plus.google.com/u/0/+RobPikeTheHuman/posts/R58WgWwN9jp


问:
How can I ensure two tasks are running on different threads or even different processors with the new Task Parallel Library?
I have two long running tasks that read and write simultaneously from a network stream which requires me to use two different threads.

I have marked them as long running but according to the docs marking them as long running only recommends but doesn't guarantee that they will run on different threads.

Do I need to write my own Task Scheduler? Should I use the thread pool instead?

答:
If "network stream" means the NetworkStream class, I'm not sure why you really need two separate threads here. Are you basing that on the following quote from the documentation:

"As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required"

If so, that's only a suggestion - they're saying that if you do things this way, you don't need to do any synchronization. The main reason they're saying this is that NetworkStream is unusual in that it supports access from two threads simultaneously as long as one is reading and one is writing.

But it's clear from the documentation that you also have the option to perform synchronization - they're just saying that synchronization is unnecessary if you choose to go down the path of having exactly one read thread, and exactly one write thread.

But if for some reason you really do need two dedicated threads, then...I'd just use the Thread class. Trying to get Task to do that for you (either directly, or indirectly via a TaskScheduler) is probably just making things more complex. This doesn't prevent you from using the TPL - you could use the TaskCompletionSource to create tasks, and finish them at your own leisure. (TCS is the normal solution for situations where you want to control how tasks execute, but still expose them as a Task object.)

ContentLicense: CC BY-SA 2.5


问:
Best class structure practice for step by step object manipulation in python
Hi I want to create a class with multiple methods. Each method depends on the result of another method. A simplified example looks like:

```<code>class klass(object):
def __init__(self, x, y):
    self.x = x
    self.y = y
    self.results = 0

def method1(self):
    self.results = self.x + self.y
    return self.results

def method2(self):
    self.results = math.sqrt(self.results)
    return self.results
</code>```

method2 should called only after method1. i.e:

```<code>>>> b=klass(3.0, 4.0)
>>> b.method1()
7.0
>>> b.method2()
2.6457513110645907
</code>```

The idea is that someone may need only the result of method1 and someone else may need the result of method2 as well. So the first person needs to run only method1 and the second person needs to run method1 and then method2.

What is the best(most readable and simplest) way  to do that.

Note that this is a much more simple version of a complex class

答:
I would switch results to be a dictionary and save the results for each level separately. Then you can check in each method if "level1" not in self.results: raise an exception but then you can still provide the output of each level to users. Furthermore you could start each method by checking to see if the results exist already. An example would be like so:

```<code>class klass(object):
def __init__(self, x, y):
    self.x = x
    self.y = y
    self.results = {"level0": 0}

def method1(self):
    if "level1" not in self.results:
        self.results["level1"] = self.x + self.y
    return self.results["level1"]

def method2(self):
    if "level1" not in self.results:
        raise ValueError("The results of method1 are not yet available")
    if "level2" not in self.results:
        self.results["level2"] = math.sqrt(self.results["level1"])
    return self.results["level2"]
</code>```

P.S. Don't use the name klass

Body:
Hi I want to create a class with multiple methods. Each method depends on the result of another method. A simplified example looks like:

class klass(object):
def __init__(self, x, y):
    self.x = x
    self.y = y
    self.results = 0

def method1(self):
    self.results = self.x + self.y
    return self.results

def method2(self):
    self.results = math.sqrt(self.results)
    return self.results

method2 should called only after method1. i.e:

>>> b=klass(3.0, 4.0)
>>> b.method1()
7.0
>>> b.method2()
2.6457513110645907

The idea is that someone may need only the result of method1 and someone else may need the result of method2 as well. So the first person needs to run only method1 and the second person needs to run method1 and then method2.

What is the best(most readable and simplest) way  to do that.

Note that this is a much more simple version of a complex class

Body:
I would switch results to be a dictionary and save the results for each level separately. Then you can check in each method if "level1" not in self.results: raise an exception but then you can still provide the output of each level to users. Furthermore you could start each method by checking to see if the results exist already. An example would be like so:

class klass(object):
def __init__(self, x, y):
    self.x = x
    self.y = y
    self.results = {"level0": 0}

def method1(self):
    if "level1" not in self.results:
        self.results["level1"] = self.x + self.y
    return self.results["level1"]

def method2(self):
    if "level1" not in self.results:
        raise ValueError("The results of method1 are not yet available")
    if "level2" not in self.results:
        self.results["level2"] = math.sqrt(self.results["level1"])
    return self.results["level2"]

P.S. Don't use the name klass


问:
Eclipse Neon with JDK 7 or below
When I compile / run the build on ant with eclipse neon on JDK 7 and below I got error message saying Unsupported must run on 1.8 or higher. If I changed my ant and jdk to 8 on ant I got unsupported minior/major version....

Is there a way to build with jdk 7 and below with eclipse neon? if I made this upgrade am I sacrificing all my previous changes and development?

答:
You can edit like this following(make sure with your installation path),</p>

```<code>-vm
/usr/lib/jvm/java-7-openjdk-amd64/jre/bin
-vmargs
-Dosgi.requiredJavaVersion=1.7
-XX:+UseG1GC
-XX:+UseStringDeduplication
-Dosgi.requiredJavaVersion=1.7
-Xms256m
-Xmx1024m
-Declipse.p2.max.threads=10
-Doomph.update.url=http://download.eclipse.org/oomph/updates/milestone/latest
-Doomph.redirection.index.redirection=index:/->http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/
</code>```

Title: Eclipse Neon with JDK 7 or below

Body:
You can edit like this following(make sure with your installation path),

-vm
/usr/lib/jvm/java-7-openjdk-amd64/jre/bin
-vmargs
-Dosgi.requiredJavaVersion=1.7
-XX:+UseG1GC
-XX:+UseStringDeduplication
-Dosgi.requiredJavaVersion=1.7
-Xms256m
-Xmx1024m
-Declipse.p2.max.threads=10
-Doomph.update.url=http://download.eclipse.org/oomph/updates/milestone/latest
-Doomph.redirection.index.redirection=index:/->http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/


问:
T-SQL set trailing numbers to zeros
I'm working on a stored procedure on SQL Server 2014.

I have a variable:

```<code>DECLARE @VersionNumber DECIMAL(18,1);
</code>```

This VersionNumber can have values such as 1.0 or 1.4.

In my logic, I increase the number +0.1 if there is a minor change and +1 if there is a major change.

If there is a major change though, I want to reset the trailing numbers to 0.

Example: Version 1.4 should become 2.0 after a major change

My current query looks like this:

```<code>IF @IsMajor = 'true'
BEGIN
    SELECT @VersionNumber = COALESCE(1 + MAX([VersionNumber]), 1)
    FROM [MySchema].[Project]
END
IF @IsMajor = 'false'
BEGIN
    SELECT @VersionNumber = COALESCE(0.1 + MAX([VersionNumber]), 1)
    FROM [MySchema].[Project]
END
</code>```

Do you know how to reset the trailing number to 0 on a decimal number?

Thank you!

答:
Use FLOOR

```<code>IF @IsMajor = 'true'
BEGIN
    SELECT @VersionNumber = FLOOR(COALESCE(1 + MAX([VersionNumber]), 1))
    FROM [MySchema].[Project]
END
IF @IsMajor = 'false'
BEGIN
    SELECT @VersionNumber = COALESCE(0.1 + MAX([VersionNumber]), 1)
    FROM [MySchema].[Project]
END
</code>```

Title: T-SQL set trailing numbers to zeros

Body:
I'm working on a stored procedure on SQL Server 2014.

I have a variable:

DECLARE @VersionNumber DECIMAL(18,1);

This VersionNumber can have values such as 1.0 or 1.4.

In my logic, I increase the number +0.1 if there is a minor change and +1 if there is a major change.

If there is a major change though, I want to reset the trailing numbers to 0.

Example: Version 1.4 should become 2.0 after a major change

My current query looks like this:

IF @IsMajor = 'true'
BEGIN
    SELECT @VersionNumber = COALESCE(1 + MAX([VersionNumber]), 1)
    FROM [MySchema].[Project]
END
IF @IsMajor = 'false'
BEGIN
    SELECT @VersionNumber = COALESCE(0.1 + MAX([VersionNumber]), 1)
    FROM [MySchema].[Project]
END

Do you know how to reset the trailing number to 0 on a decimal number?

Thank you!

Body:
Use FLOOR

IF @IsMajor = 'true'
BEGIN
    SELECT @VersionNumber = FLOOR(COALESCE(1 + MAX([VersionNumber]), 1))
    FROM [MySchema].[Project]
END
IF @IsMajor = 'false'
BEGIN
    SELECT @VersionNumber = COALESCE(0.1 + MAX([VersionNumber]), 1)
    FROM [MySchema].[Project]
END


问:
Can Hbase table be partitioned based on time?
I need to get data based on time range.Is there any way to partition hbase table based on the time range. Ex : I want data say from 9:00 to 9:05 . </p>

答:
For me the problem is duplicate entries. I canhave many events occurring at the same time. For example : I can have 10 events occurring at say 10:05. If I convert it into epoch time and insert it, they can overwrite each other ( or fail to write ) in hbase.

I can append an ID along with timestamp, but can I set start and end time in mapreduce job if I add this ID  ?


问:
How to POST data to an HTTP endpoint using NodeJs
I am New to AWS Lambda

I was trying to POST a simple data from AWS data to HTTP endpoint, but i am unable to do that.

I was using NodeJs language.
And I want the POST method to be done using http module not using request module.
How to solve this.

答:
If you really want to use only the http module, you can start from this example:

```<code>const http = require('http');

const requestBody = 'your=post&content=here';
const options = {
    host: 'httpbin.org',
    path: '/post',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': requestBody.length
    }
};

const req = http.request(options, (res) => {
    var responseString = '';

    res.on('data', function (data) {
        responseString += data;
        // save all the data from response
    });
    res.on('end', function () {
        console.log(responseString);
        // print to console when response ends
    });
});
req.write(requestBody);
req.end();
</code>```

Body:
If you really want to use only the http module, you can start from this example:

const http = require('http');

const requestBody = 'your=post&content=here';
const options = {
    host: 'httpbin.org',
    path: '/post',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': requestBody.length
    }
};

const req = http.request(options, (res) => {
    var responseString = '';

    res.on('data', function (data) {
        responseString += data;
        // save all the data from response
    });
    res.on('end', function () {
        console.log(responseString);
        // print to console when response ends
    });
});
req.write(requestBody);
req.end();


答:
You can write separate functions to aggregate functions you need in a single place:</p>

```<code>class klass(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.results = 0

    def method1(self):
        self.results = self.x + self.y
        return self.results

    def method2(self):
        self.results = math.sqrt(self.results)
        return self.results

    def both_methods(self):
        self.method1()
        self.method2()
        return self.results
</code>```

Title: Best class structure practice for step by step object manipulation in python

Body:
You can write separate functions to aggregate functions you need in a single place:

class klass(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.results = 0

    def method1(self):
        self.results = self.x + self.y
        return self.results

    def method2(self):
        self.results = math.sqrt(self.results)
        return self.results

    def both_methods(self):
        self.method1()
        self.method2()
        return self.results


问:
PHP _FILES array and SELinux - forbidden file access
I have this issue with PHP and SELinux on Red Hat Enterprise Linux (RHEL) for AWS. When I use _FILES array to get the file (jpg) from POST, it makes the SELinux type to be user_tmp_t instead of httpd_sys_content_1 which is necessary when move_uploaded_file moves the file to the upload directory which is in the standard var/www/html/ directory. Because move_uploaded_file never changes the SELinux type on the file, the jpg file becomes forbidden to use. How do I solve this problem?

move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir) is what I am using.

I've tried changing the php.ini sys_upload_dir and upload_tmp_dir but the problem still exists. I've also tried creating a new folder to store tmp files and using sudo semanage fcontext -a -t httpd_sys_content_t "/phptmp(/.*)?" but still does not work.

semanage fcontext -a -t httpd_sys_content_t '/var/www/html(/.*)?' and restorecon -R -v /var/www/html/ does solve the problem for the existing files, but it doesn't work in the future though because PHP is causing it to be user_tmp_t every time.

I would like to use SELinux but this is very frustrating since I don't know a way to change SELinux properties on PHP really.

I know this is a SELinux problem because if I do setenforce 0 it "solves" the problem.

答: I ended up "solving it" by changing both php.ini directories to another tmp directory I made on root and using semanage fcontext -a -t httpd_sys_content_t '/phptmp(/.*)?' as well as restorecon -R -v /phptmp/ and making sure to reboot instance after restorecon or else it will not work. Still unsure about how to do it on the PHP programming side but I doubt you could do much with it.


问:
Find all grouped records where a records are newer than a certain type of record
That would be the intermediary output I need:

```<code>Id1, Id2, Type,   Date
1,   2,    test,  2010-10-10
1,   3,    stage, 2010-05-05
1,   2,    stage, 2010-12-12
1,   3,    test,  2010-04-04
1,   3,    prod,  2010-12-31
</code>```

From that point I want to know how many grouped (Id1,Id2) records do exist after the record with Type = 'test'.

for the above I would get this final output:

```<code>Id1, Id2, Count
1,   2,   1
1,   3,   2
</code>```

What sql query would that be?

The use case would be to find all those records who never made it to a later stage than type = "test"

答:
There might be various dates for similar (Id1, Id2) records.
So If all you need is a count of the records with this (Id1, Id2) pair irrespective of Date field then this will work for you.

```<code>SELECT T.Id1,T.Id2,COUNT(*) AS Count
FROM
   (SELECT Id1, Id2, Date
    FROM TABLENAME
    WHERE TYPE = 'test') AS T
GROUP BY
T.Id1, T.Id2
</code>```

Otherwise, you need to add the Date field in GROUP BY clause.

Body:
That would be the intermediary output I need:

Id1, Id2, Type,   Date
1,   2,    test,  2010-10-10
1,   3,    stage, 2010-05-05
1,   2,    stage, 2010-12-12
1,   3,    test,  2010-04-04
1,   3,    prod,  2010-12-31

From that point I want to know how many grouped (Id1,Id2) records do exist after the record with Type = 'test'.

for the above I would get this final output:

Id1, Id2, Count
1,   2,   1
1,   3,   2

What sql query would that be?

The use case would be to find all those records who never made it to a later stage than type = "test"

Body:
There might be various dates for similar (Id1, Id2) records.
So If all you need is a count of the records with this (Id1, Id2) pair irrespective of Date field then this will work for you.

SELECT T.Id1,T.Id2,COUNT(*) AS Count
FROM
   (SELECT Id1, Id2, Date
    FROM TABLENAME
    WHERE TYPE = 'test') AS T
GROUP BY
T.Id1, T.Id2

Otherwise, you need to add the Date field in GROUP BY clause.


问:
Why does Class AtomicBoolean be initialized not true but false by default constractor?
```<code>java source code:

static {
  try {
    valueOffset = unsafe.objectFieldOffset
        (AtomicBoolean.class.getDeclaredField("value"));
  } catch (Exception ex) { throw new Error(ex); }
}
</code>```

default constructor do nothing:

```<code>public AtomicBoolean() {
}
</code>```

The variable 'valueOffset' means the offset location in memory? I don't understand why it initialized to 'false' by default constructor.How can i understand this?

答:
As no value is set in the default constructor, the initial value is the initialized value of the value field - that's an int, with no explicit value, so it has the default value of zero.

Source code:

```<code>private volatile int value;

/**
 * Creates a new {@code AtomicBoolean} with the given initial value.
 *
 * @param initialValue the initial value
 */
public AtomicBoolean(boolean initialValue) {
    value = initialValue ? 1 : 0;
}

/**
 * Creates a new {@code AtomicBoolean} with initial value {@code false}.
 */
public AtomicBoolean() {
}
</code>```

Setting it to false is consistent with an uninitialized boolean field.

Body:
java source code:

static {
  try {
    valueOffset = unsafe.objectFieldOffset
        (AtomicBoolean.class.getDeclaredField("value"));
  } catch (Exception ex) { throw new Error(ex); }
}

default constructor do nothing:

public AtomicBoolean() {
}

The variable 'valueOffset' means the offset location in memory? I don't understand why it initialized to 'false' by default constructor.How can i understand this?

Body:
As no value is set in the default constructor, the initial value is the initialized value of the value field - that's an int, with no explicit value, so it has the default value of zero.

Source code:

private volatile int value;

/**
 * Creates a new {@code AtomicBoolean} with the given initial value.
 *
 * @param initialValue the initial value
 */
public AtomicBoolean(boolean initialValue) {
    value = initialValue ? 1 : 0;
}

/**
 * Creates a new {@code AtomicBoolean} with initial value {@code false}.
 */
public AtomicBoolean() {
}

Setting it to false is consistent with an uninitialized boolean field.


问:
SPRING WEB MVC ANNOTATIONS-Method for Partial Page Rendering
Hello Friends,

[Need some help regarding spring web mvc annotation based:]

How to use partial page rendering on spring web mvc annotations.

Master Page Name:  CreateEntity.jsp

Partial jsp page:  Account.jsp, Lead.jsp etc etc*

Now, this master page consists of drop down list where if Account is selected then partial page Account will get load into master page named CreateEntity. Else if Lead is Selected then Lead will get into the master page.

I have Created the Controller named CreateEntityController.java into which have written code as follows:

```<code>***CreateEntityController.java***
 @RequestMapping(value = { "/CreateEntity" }, method = RequestMethod.GET)
 public ModelAndView CreateEntity(Model model) {
 model.addAttribute("module", "Account");
 model.addAttribute("msg", "This is the partial view page!");
 return new ModelAndView("CreateEntity");
 }
</code>```

JSP Page Code:
  (CreateEntity.jsp)-Master Page

```<code><li><c:url value="/CreateEntity" var="CreateEntity"  />
                            <a data-params='{"module":"CreateLeadStatus"}'
                                href="<c:out value='${CreateEntity}'/>">Create Entity</a></li>

<div>
    <%@include file="CreateLeadStatus.jsp"%>
</div>
</code>```

JSP Page Code 2: *Partial Page Code: ***Account.jsp****

```<code> <spring:url value="CreateEntity" var="CreateEntity" />

<form class="form-Account" action="${CreateEntity}" method="POST"  role="form" >
<div class="crmBodyWin" style="">
    <div id="" class="p30 lbox set_mw">
        <div id="secDiv_Lead_Information" class="editParentSection pL30 pR30">
            <table style="width: 100%" cellspacing="0" cellpadding="0"
                id="secHead_Lead_Information">
                <tbody>
                    <tr>
                        <td class="contHeadInfo">Lead Status</td>
                    </tr>
                </tbody>
            </table>

            <div style="width: 100%" class="secContent" border="0"
                cellspacing="1" cellpadding="0" id="secContent_Lead_Information">
                <div class="contInfoTab floatL formViewCreate">
                    <div id="Leads_fldRow_COMPANY" class="textFld COMPANY tabDivCreate">
                        <div class="labelTabCreate pL5 pR newmandatory"
                            id="Crm_Leads_COMPANY_label">Status Name</div><div class="labelValCreate mL45">
                            <input
                                type="text" class="textField" style="width: 100%"
                                id="txtleadname" name="txtleadname" tabindex="5" maxlength="100"
                                data-maxlength="100" data-customfield="false"
                                data-decimal-length="2" data-label="leadname"
                                data-readonly="false" value="">
                        </div>
                        <div class="clearB"></div>
                    </div>
                    <br>
            <button class="btn btn-lg rest-btn-active btn-block" type="submit">Create Lead Status-TEST</button>
                </div>

                <div class="contInfoTab floatR formViewCreate"></div>

            </div>

        </div>
    </div>

</div>
</form>
</code>```

Please tell me that is there any solution for it such a manner:

- Example:

If{
(Account )-is selected then
Account.jsp  - partial view loads on that master page**(CreateEntity)**
}
else if (Lead)-is selected then
Lead.jsp -partial view loads on that master page**(CreateEntity)**
}

module can be the common method in controller:
For example on selected choice as Account. The URL lookes something like this:

For Account its should look something like this:

http://localhost:8080/projectname/CreateEntity?module=Account

For Lead its should look something like this:

http://localhost:8080/projectname/CreateEntity?module=Lead

Please kindly help me regarding this topic.

Thank You!

答:
As far as i understand your question. Your goal is to include a jsp page based on your URL param(module). To do that you have to change your controller to this

```<code>***CreateEntityController.java***
  @RequestMapping(value = { "/CreateEntity" }, method = RequestMethod.GET)
  public ModelAndView CreateEntity(String module,Model model) {
      model.addAttribute("module", module);
      model.addAttribute("msg", "This is the partial view page!");
      if(module.equals("Account"){
           //account related attributes
           // call your service or bo and send account related object
           model.addAttribute("account",yourAccountObject)
      }
      if(module.equals("Lead"){
          //lead related attributes
          // call your service or bo and send lead related object
           model.addAttribute("lead",yourLeadObject)
      }
      return new ModelAndView("CreateEntity");
  }
</code>```

CreateEntity.jsp

```<code> <%-- common code --%>
 <li>
        <a data-params='{"module":"CreateAccountStatus"}' href="<c:url value='CreateEntity?
              module=Account'/>">Create Account </a>
</li>
 <li>
        <a data-params='{"module":"CreateLeadStatus"}' href="<c:url value='CreateEntity?
              module=Lead'/>">Create Account </a>
 </li>

<div>
    <%-- Your partial condition --%>
    <c:choose>
      <c:when test="${module=='Account'}">
         <jsp:include page="Account.jsp" />
      </c:when>
       <c:when test="${module=='Lead'}">
         <jsp:include page="Lead.jsp" />
      </c:when>
    </c:choose>

</div>
</code>```

Body:
Hello Friends,

[Need some help regarding spring web mvc annotation based:]

How to use partial page rendering on spring web mvc annotations.

Master Page Name:  CreateEntity.jsp

Partial jsp page:  Account.jsp, Lead.jsp etc etc*

Now, this master page consists of drop down list where if Account is selected then partial page Account will get load into master page named CreateEntity. Else if Lead is Selected then Lead will get into the master page.

I have Created the Controller named CreateEntityController.java into which have written code as follows:

***CreateEntityController.java***
 @RequestMapping(value = { "/CreateEntity" }, method = RequestMethod.GET)
 public ModelAndView CreateEntity(Model model) {
 model.addAttribute("module", "Account");
 model.addAttribute("msg", "This is the partial view page!");
 return new ModelAndView("CreateEntity");
 }

JSP Page Code:
  (CreateEntity.jsp)-Master Page

<c:url value="/CreateEntity" var="CreateEntity"  />
                            <a data-params='{"module":"CreateLeadStatus"}'
                                href="<c:out value='${CreateEntity}'/>">Create Entity

    <%@include file="CreateLeadStatus.jsp"%>

JSP Page Code 2: *Partial Page Code: ***Account.jsp****

 <spring:url value="CreateEntity" var="CreateEntity" />

<form class="form-Account" action="${CreateEntity}" method="POST"  role="form" >

                        Lead Status

Status Name

                            <input
                                type="text" class="textField" style="width: 100%"
                                id="txtleadname" name="txtleadname" tabindex="5" maxlength="100"
                                data-maxlength="100" data-customfield="false"
                                data-decimal-length="2" data-label="leadname"
                                data-readonly="false" value="">

            <button class="btn btn-lg rest-btn-active btn-block" type="submit">Create Lead Status-TEST</button>

</form>

Please tell me that is there any solution for it such a manner:

- Example:

If{
(Account )-is selected then
Account.jsp  - partial view loads on that master page**(CreateEntity)**
}
else if (Lead)-is selected then
Lead.jsp -partial view loads on that master page**(CreateEntity)**
}

module can be the common method in controller:
For example on selected choice as Account. The URL lookes something like this:

For Account its should look something like this:

http://localhost:8080/projectname/CreateEntity?module=Account

For Lead its should look something like this:

http://localhost:8080/projectname/CreateEntity?module=Lead

Please kindly help me regarding this topic.

Thank You!

Body:
As far as i understand your question. Your goal is to include a jsp page based on your URL param(module). To do that you have to change your controller to this

***CreateEntityController.java***
  @RequestMapping(value = { "/CreateEntity" }, method = RequestMethod.GET)
  public ModelAndView CreateEntity(String module,Model model) {
      model.addAttribute("module", module);
      model.addAttribute("msg", "This is the partial view page!");
      if(module.equals("Account"){
           //account related attributes
           // call your service or bo and send account related object
           model.addAttribute("account",yourAccountObject)
      }
      if(module.equals("Lead"){
          //lead related attributes
          // call your service or bo and send lead related object
           model.addAttribute("lead",yourLeadObject)
      }
      return new ModelAndView("CreateEntity");
  }

CreateEntity.jsp

 <%-- common code --%>
 <li>
        <a data-params='{"module":"CreateAccountStatus"}' href="<c:url value='CreateEntity?
              module=Account'/>">Create Account </a>
</li>
 <li>
        <a data-params='{"module":"CreateLeadStatus"}' href="<c:url value='CreateEntity?
              module=Lead'/>">Create Account </a>
 </li>

<div>
    <%-- Your partial condition --%>
    <c:choose>
      <c:when test="${module=='Account'}">
         <jsp:include page="Account.jsp" />
      </c:when>
       <c:when test="${module=='Lead'}">
         <jsp:include page="Lead.jsp" />
      </c:when>
    </c:choose>

</div>


问:
Hide div while scrolling down
I just want to hide an image when scroll down and show another image. When scroll to top of the page, first image needs to show and other image needs to be hide.

I tried with this code.

```<code>//This is the image I just want to show at first
<img src="images/logo-wh.png" alt="" class="logo-white">

//This is the image I just want to show when scroll down
<img src="images/logo.png" alt="" class="logo-default">

.logo-default{
  display:none;
}

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
    } else {
        $('.logo-default').show();
    }
 });
</code>```

But it isn't working as I expected. Any suggestions?

答:
Modify a bit the show and hide inside the if...else statement:

$(window).scroll(function() {
  if ($(this).scrollTop() > 0) {
    $('.logo-white').hide();
    $('.logo-default').show();
  } else {
    $('.logo-white').show();
    $('.logo-default').hide();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.logo-default {
  display: none;
}
#wrapper{
  height: 1000px;
  background: #adadad;
}

img{
  width: 100px;
}</code>```

```

Title: Hide div while scrolling down

Body:
I just want to hide an image when scroll down and show another image. When scroll to top of the page, first image needs to show and other image needs to be hide.

I tried with this code.

//This is the image I just want to show at first

//This is the image I just want to show when scroll down

.logo-default{
  display:none;
}

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        $('.logo-white').hide();
    } else {
        $('.logo-default').show();
    }
 });

But it isn't working as I expected. Any suggestions?

Body:
Modify a bit the show and hide inside the if...else statement:

$(window).scroll(function() {
  if ($(this).scrollTop() > 0) {
    $('.logo-white').hide();
    $('.logo-default').show();
  } else {
    $('.logo-white').show();
    $('.logo-default').hide();
  }
});

.logo-default {
  display: none;
}
#wrapper{
  height: 1000px;
  background: #adadad;
}

img{
  width: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='wrapper'>
    <img src="http://www.alessandrobianchetti.com/uploads/1/8/5/3/18531856/1842659_orig.jpg" alt="" class="logo-white">
    <img src="http://www.pietrarosa.it/wp-content/uploads/2015/01/paesaggi-1.jpg" alt="" class="logo-default">
</div>


问:
How can we make SonarLint startup faster in Eclipse with lots of projects?
In our case we had a parent project (trunk) where all plug-ins where sub-projects and we want all the sub projects to have the same rules. In order to make maintenance easier we thought we could bind all plug-in projects in eclipse to trunk (so we can just batch update them etc.).
The problem here is that for some reason it always loads all sub projects for each project. 1) they are always the same 2) there is not more information in the call of the sub-project that the former call did not get.

If we bind each project to the real correct project in SonarLint that is a lot of effort. (we have hundreds of plug-ins.)
Still, for our 100+ plug-in projects that we have in Eclipse SonarLint takes some minutes to get all the info from the server.

How can we make SonarLint faster? Is there a recommended way? Can we help to improve the logic for this scenario?

答:
I think the title of your question is confusing. This is not about SonarLint startup, but about SonarLint "update all bindings" feature.

I have created a ticket that we will try to fix in the next version:
https://jira.sonarsource.com/browse/SLE-200

Note that not binding Eclipse project to the correct SonarQube project/module will prevent correct match between local and remote issues. It means issues flagged as "won't fix" or "false positive" on SonarQube side will not be muted in Eclipse.

You said mapping many projects is tedious. What about the auto-bind feature? If it is failing to correctly guess binding between local and remote projects, I encourage you to open a thread on the SonarLint Google group to so that we can investigate the reason.


问:
How to execute a java script with jshell?
Given that Java 9 is upon us and we can finally have a java REPL with jshell I was hoping there was a way to add a shebang to a script and have jshell interpret it.

I tried creating test.jsh:

```<code>#!/usr/bin/env jshell -s
System.out.println("Hello World")
/exit
</code>```

However that gives:

```<code>⚡ ./test.jsh
|  Error:
|  illegal character: '#'
|  #!/usr/bin/env jshell -s
|  ^
|  Error:
|  illegal start of expression
|  #!/usr/bin/env jshell -s
|    ^
Hello World
</code>```

It turns out there is an enhancement request for this in OpenJDK https://bugs.openjdk.java.net/browse/JDK-8167440.

Is there any other way to do this?

答:
Use

//usr/bin/env jshell --show-version --execution local "$0" "$@"; exit $?

as the first line of test.jsh. The test.jsh script could look like:

```<code>//usr/bin/env jshell --show-version "$0" "$@"; exit $?
System.out.println("Hello World")
/exit
</code>```

The command line option --show-version is optional, of course, but gives immediate feedback that the tool is running.

The extra command line option --execution local prevents jshell to spawn another VM. This speeds up launch time and if an exception is thrown by your script code, the local VM will exit.

Consult the output of jshell --help and jshell --help-extra for more options.

Update

Also take a look at https://github.com/jbangdev/jbang Having fun with Java scripting, which offers a neat wrapper around running .java files from the command line.

Body:
Given that Java 9 is upon us and we can finally have a java REPL with jshell I was hoping there was a way to add a shebang to a script and have jshell interpret it.

I tried creating test.jsh:

#!/usr/bin/env jshell -s
System.out.println("Hello World")
/exit

However that gives:

⚡ ./test.jsh
|  Error:
|  illegal character: '#'
|  #!/usr/bin/env jshell -s
|  ^
|  Error:
|  illegal start of expression
|  #!/usr/bin/env jshell -s
|    ^
Hello World

It turns out there is an enhancement request for this in OpenJDK https://bugs.openjdk.java.net/browse/JDK-8167440.

Is there any other way to do this?

Body:
Use

//usr/bin/env jshell --show-version --execution local "$0" "$@"; exit $?

as the first line of test.jsh. The test.jsh script could look like:

//usr/bin/env jshell --show-version "$0" "$@"; exit $?
System.out.println("Hello World")
/exit

The command line option --show-version is optional, of course, but gives immediate feedback that the tool is running.

The extra command line option --execution local prevents jshell to spawn another VM. This speeds up launch time and if an exception is thrown by your script code, the local VM will exit.

Consult the output of jshell --help and jshell --help-extra for more options.

Update

Also take a look at https://github.com/jbangdev/jbang Having fun with Java scripting, which offers a neat wrapper around running .java files from the command line.

ContentLicense: CC BY-SA 4.0


问:
camel rest dsl - any way to have GET with json body
I'm using camel rest java dsl with jetty component.
Camel version is 2.18.0

The route provides a rest service that consumes json formatted request and produces json response. Doing so using POST is no problem.

But since these routes don't change no data, it would be preferrable to use GET as verb.

Is there any way to accept a json body in the upstream together with GET?

Does it depend on the underlying consumer?

Are there any examples to do so or am I fundamentally wrong in trying so?

Thanx in advance
Henning

答:
I gather, what I came across so far. With the help of Panayiotis answer, CAMEL-9611 notes that it seems to be explicitly deactivated, also is swagger missing the possibility to express body in GET requests.

It comes to the point that although the HTTP spec is rather vague about the usage of a body in a GET request, the usage is only seldomly supported by frameworks.

I hoped it would be possible to define complex query input using GET with a json body, since it would be much easier to define more complex queries. But while reading on, I get the impression, that this handling is discouraged because of the lack of support.


问:
load data infile mysql how to ignore not valid records inserting
I have a text file and want to load it to my db table using load data infile, but this file contains invalid values, that contain empty strings, how to ignore this lines?</p>

答: edit your text file first to search-and-replace the invalid values.  Then load the data into mysql.


问:
Openpyxl: How to copy a row after checking if a cell contains specific value
I have a worksheet that is updated every week with thousands of rows and would need to transfer rows from this worksheet after filtering. I am using the current code to find the cells which has the value I need and then transfer the entire row to another sheet but after saving the file, I get the "IndexError: list index out of range" exception.

The code I use is as follows:

```<code>import openpyxl

wb1 = openpyxl.load_workbook('file1.xlsx')
wb2 = openpyxl.load_workbook('file2.xlsx')

ws1 = wb1.active
ws2 = wb2.active

for row in ws1.iter_rows():
    for cell in row:
        if cell.value == 'TrueValue':
            n = 'A' + str(cell.row) + ':' + ('GH' + str(cell.row))
            for row2 in ws1.iter_rows(n):
                ws2.append(row2)

wb2.save("file2.xlsx")
</code>```

The original code I used that used to work is below and has to be modified because of the large files which causes MS Excel not to open them (over 40mb).

```<code>n = 'A3' + ':' + ('GH'+ str(ws1.max_row))
for row in ws1.iter_rows(n):
    ws2.append(row)
</code>```

Thanks.

答:
I'm not entirely sure what you're trying to do but I suspect the problem is that you have nested your copy loop.

Try the following:

```<code>row_nr = 1
for row in ws1:
    for cell in row:
        if cell.value == "TrueValue":
            row_nr = cell.row
            break
    if row_nr > 1:
        break

for row in ws1.iter_rows(min_row=row_nr, max_col=190):
    ws2.append((cell.value for cell in row))
</code>```

Body:
I have a worksheet that is updated every week with thousands of rows and would need to transfer rows from this worksheet after filtering. I am using the current code to find the cells which has the value I need and then transfer the entire row to another sheet but after saving the file, I get the "IndexError: list index out of range" exception.

The code I use is as follows:

import openpyxl

wb1 = openpyxl.load_workbook('file1.xlsx')
wb2 = openpyxl.load_workbook('file2.xlsx')

ws1 = wb1.active
ws2 = wb2.active

for row in ws1.iter_rows():
    for cell in row:
        if cell.value == 'TrueValue':
            n = 'A' + str(cell.row) + ':' + ('GH' + str(cell.row))
            for row2 in ws1.iter_rows(n):
                ws2.append(row2)

wb2.save("file2.xlsx")

The original code I used that used to work is below and has to be modified because of the large files which causes MS Excel not to open them (over 40mb).

n = 'A3' + ':' + ('GH'+ str(ws1.max_row))
for row in ws1.iter_rows(n):
    ws2.append(row)

Thanks.

Body:
I'm not entirely sure what you're trying to do but I suspect the problem is that you have nested your copy loop.

Try the following:

row_nr = 1
for row in ws1:
    for cell in row:
        if cell.value == "TrueValue":
            row_nr = cell.row
            break
    if row_nr > 1:
        break

for row in ws1.iter_rows(min_row=row_nr, max_col=190):
    ws2.append((cell.value for cell in row))


问:
Laravel: Notify admin when user do something
I will explain my idea. When a default user does an action, I want the admin to be notified about this action. To do this, I use notifications in Laravel that are saved in the database (I don't know if this is the better way).

My problem is that i can't show the notifications with an admin user.

When a user does a specific action, I want all the admins to be notified:

```<code>$admins = Admin::all();<p>
foreach ($admins as $admin) {
    <p>$admin->notify(new RepliedToThread($acao));<p>
}
</code>```

Next, I want to show the notifications on a navbar in my dashboard (only admins have access).

I did that with:

```<code><li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
        Notificações <span class="badge"> {{Auth::admin()->unreadNotifications() }}</span>
    </a>

    <ul class="dropdown-menu" role="menu"><p>
        <li>
            @foreach (Auth::admin()->unreadNotifications as $notification)
                {{$notification->type}}
            @endforeach
        </li>
    </ul>
</li>
</code>```

I don't know if I did this in the best way or if it will work. For now I have this error:

Method admin does not exist

But I want help with the entire process, not just this error because I don't know if I'm doing it the right way.

答:
If you have set up an admin guard, you may use:

```<code>Auth::guard('admin')->user()->unreadNotifications())
</code>```

But if you're using the default web guard, then you should access unread notifications like this:

```<code>$user->unreadNotifications()
</code>```

But then again, it depends on how you've set up your admins.

Body:
I will explain my idea. When a default user does an action, I want the admin to be notified about this action. To do this, I use notifications in Laravel that are saved in the database (I don't know if this is the better way).

My problem is that i can't show the notifications with an admin user.

When a user does a specific action, I want all the admins to be notified:

$admins = Admin::all();

foreach ($admins as $admin) {

$admin->notify(new RepliedToThread($acao));

}

Next, I want to show the notifications on a navbar in my dashboard (only admins have access).

I did that with:

        Notificações  {{Auth::admin()->unreadNotifications() }}

            @foreach (Auth::admin()->unreadNotifications as $notification)
                {{$notification->type}}
            @endforeach

I don't know if I did this in the best way or if it will work. For now I have this error:

Method admin does not exist

But I want help with the entire process, not just this error because I don't know if I'm doing it the right way.

Body:
If you have set up an admin guard, you may use:

Auth::guard('admin')->user()->unreadNotifications())

But if you're using the default web guard, then you should access unread notifications like this:

$user->unreadNotifications()

But then again, it depends on how you've set up your admins.


问:
Leaflet Change Icon in Angular Script
How to change icon in Leaflet in Angular JS

Icon to be change in $scope.map.markers.push

Code i tried so far:

```<code>$cordovaGeolocation
        .getCurrentPosition()
        .then(function (position) {
          $scope.loading = false;
          $scope.map.center.lat  = position.coords.latitude;
          $scope.map.center.lng = position.coords.longitude;
          $scope.map.center.zoom = 18;
          $scope.map.markers.now = {
            lat:position.coords.latitude,
            lng:position.coords.longitude,
            focus: true,
            draggable: false,
            message: 'You are here'
          };

          $scope.map.markers.push = {
            lat:19.0310968,
            lng:73.030836,
            focus: false,
            draggable: false,
            //url: "http://localhost/uxo_data/img/covered.png",
            styles: [{
                url: "http://localhost/uxo_data/img/covered.png",
                width:60,
                height:60,
                textColor: 'white',
                textSize: 14,
                fontFamily: 'Open Sans'
            }],
            //message: ''
          };

        },
        function(err) {
          // error
          console.log("Location error!");
          console.log(err);

        });
</code>```

No Console Errors in above code!

答: Are you using angular leaflet directive or some other angular+leaflet? If the former, see: https://github.com/tombatossals/angular-leaflet-directive/blob/master/doc/markers-attribute.md where it shows that you may not need the styles attribute but just to set iconUrl</p>

Title: Leaflet Change Icon in Angular Script

Body:
How to change icon in Leaflet in Angular JS

Icon to be change in $scope.map.markers.push

Code i tried so far:

$cordovaGeolocation
        .getCurrentPosition()
        .then(function (position) {
          $scope.loading = false;
          $scope.map.center.lat  = position.coords.latitude;
          $scope.map.center.lng = position.coords.longitude;
          $scope.map.center.zoom = 18;
          $scope.map.markers.now = {
            lat:position.coords.latitude,
            lng:position.coords.longitude,
            focus: true,
            draggable: false,
            message: 'You are here'
          };

          $scope.map.markers.push = {
            lat:19.0310968,
            lng:73.030836,
            focus: false,
            draggable: false,
            //url: "http://localhost/uxo_data/img/covered.png",
            styles: [{
                url: "http://localhost/uxo_data/img/covered.png",
                width:60,
                height:60,
                textColor: 'white',
                textSize: 14,
                fontFamily: 'Open Sans'
            }],
            //message: ''
          };

        },
        function(err) {
          // error
          console.log("Location error!");
          console.log(err);

        });

No Console Errors in above code!


问:
yii2 dataprovider get all filtered data
I have grid view of student table when I filter table, for that instant I can get filter data by giving following

```<code>$allData=$dataProvider->getModels();
</code>```

This $allData contains filtered data.
If I have 50 records, when I filter them I get 30 records, but this $allData shows only 20 records due to pagination limit 20.
so How do I get all my 30 filtered records into a variable as well as pagination?
if I set pagination size =0, then I will get all data, but I want pagination too.

So, how do I solve this?

答:
If youre using DataProvider, you have $query as well. So using:

```<code>$models = $query->all();
</code>```

will return all filtered models, and DataProvider will still have pagination.

Title: yii2 dataprovider get all filtered data

Body:
I have grid view of student table when I filter table, for that instant I can get filter data by giving following

$allData=$dataProvider->getModels();

This $allData contains filtered data.
If I have 50 records, when I filter them I get 30 records, but this $allData shows only 20 records due to pagination limit 20.
so How do I get all my 30 filtered records into a variable as well as pagination?
if I set pagination size =0, then I will get all data, but I want pagination too.

So, how do I solve this?

Body:
If youre using DataProvider, you have $query as well. So using:

$models = $query->all();

will return all filtered models, and DataProvider will still have pagination.


问:
Charset encoding problem in webservices called from Biztalk
I have a problem occurring when Biztalk calls SOAP web services. The web services from one specific system seems to not always include a "charset" attribute in the Content-Type response header. In the cases where this is missing, the charset is interpreted as Windows-1252 encoding instead of UTF-8.

The response from the web servcie is actually UTF-8 encoded even when the "charset" attribute is missing. So my question is if it's somehow possible to tell Biztalk that UTF-8 should be used as default charset when no charset is specified in the HTTP response headers from the service.

Just to specify further:
If the following header is returned from the web service, Biztalk interprets the charset correctly:

```<code>Content-Type: text/xml; charset=UTF-8
</code>```

However when the charset part is missing, Biztalk falls back on Windows-1252 encoding and some international characters are garbled:

```<code>Content-Type: text/xml
</code>```

I know that the simplest solution would be to fix the web service to always return the UTF-8 charset attribute, but sadly we have no control over the services and the vendor will not release a fix for this anytime soon.

Another fix we have attempted is to use rewriting in IIS to rewrite the response header. This works fine unless when the services returns a large amount of data. In that case IIS will used chunked encoding, and the rewrite engine seems to double chunk-encode the output from the web service, rendering the resulting output broken.

The only solution I had working so far is to use an Apache web server as a proxy, and rewrite the header with Apache. This works, but since it introduces extra overhead and is quite hackish we would rather prefer to fix the problem at an existing end-point. Currently the Biztalk end is the only one we have access to make changes on.

I hope anyone can help me on this.

答:
An easy solution would be to use an Encoding Transcoder Custom Pipeline Component in the receive pipeline. This is, IMHO, better than hosting a separate proxy in a third-party server. But you are right, solving the problem at its root would be better if you can have a hand on the external web service.

Such a composent can be found there:
http://maximelabelle.wordpress.com/category/pipeline-components/

Body:
I have a problem occurring when Biztalk calls SOAP web services. The web services from one specific system seems to not always include a "charset" attribute in the Content-Type response header. In the cases where this is missing, the charset is interpreted as Windows-1252 encoding instead of UTF-8.

The response from the web servcie is actually UTF-8 encoded even when the "charset" attribute is missing. So my question is if it's somehow possible to tell Biztalk that UTF-8 should be used as default charset when no charset is specified in the HTTP response headers from the service.

Just to specify further:
If the following header is returned from the web service, Biztalk interprets the charset correctly:

Content-Type: text/xml; charset=UTF-8

However when the charset part is missing, Biztalk falls back on Windows-1252 encoding and some international characters are garbled:

Content-Type: text/xml

I know that the simplest solution would be to fix the web service to always return the UTF-8 charset attribute, but sadly we have no control over the services and the vendor will not release a fix for this anytime soon.

Another fix we have attempted is to use rewriting in IIS to rewrite the response header. This works fine unless when the services returns a large amount of data. In that case IIS will used chunked encoding, and the rewrite engine seems to double chunk-encode the output from the web service, rendering the resulting output broken.

The only solution I had working so far is to use an Apache web server as a proxy, and rewrite the header with Apache. This works, but since it introduces extra overhead and is quite hackish we would rather prefer to fix the problem at an existing end-point. Currently the Biztalk end is the only one we have access to make changes on.

I hope anyone can help me on this.


问:
Python PIL For Loop to work with Multi-image TIFF
Each tiff file has 4 images in it. I do not wish to extract and save them if possible, I would just like to use a for loop to look at each of them. (Like look at the pixel [0,0] )and depending on what color it is in all 4 I will do something accordingly.

Is this possible using PIL?
If not what should I use.

答:
Here's a method that reads a multipage tiff and returns the images as a numpy array</p>

```<code>from PIL import Image
import numpy as np

def read_tiff(path, n_images):
    """
    path - Path to the multipage-tiff file
    n_images - Number of pages in the tiff file
    """
    img = Image.open(path)
    images = []
    for i in range(n_images):
        try:
            img.seek(i)
            slice_ = np.zeros((img.height, img.width))
            for j in range(slice_.shape[0]):
                for k in range(slice_.shape[1]):
                    slice_[j,k] = img.getpixel((j, k))

            images.append(slice_)

        except EOFError:
            # Not enough frames in img
            break

    return np.array(images)
</code>```

Body:
Here's a method that reads a multipage tiff and returns the images as a numpy array

from PIL import Image
import numpy as np

def read_tiff(path, n_images):
    """
    path - Path to the multipage-tiff file
    n_images - Number of pages in the tiff file
    """
    img = Image.open(path)
    images = []
    for i in range(n_images):
        try:
            img.seek(i)
            slice_ = np.zeros((img.height, img.width))
            for j in range(slice_.shape[0]):
                for k in range(slice_.shape[1]):
                    slice_[j,k] = img.getpixel((j, k))

            images.append(slice_)

        except EOFError:
            # Not enough frames in img
            break

    return np.array(images)


问:
T-SQL set trailing numbers to zeros
I'm working on a stored procedure on SQL Server 2014.

I have a variable:

```<code>DECLARE @VersionNumber DECIMAL(18,1);
</code>```

This VersionNumber can have values such as 1.0 or 1.4.

In my logic, I increase the number +0.1 if there is a minor change and +1 if there is a major change.

If there is a major change though, I want to reset the trailing numbers to 0.

Example: Version 1.4 should become 2.0 after a major change

My current query looks like this:

```<code>IF @IsMajor = 'true'
BEGIN
    SELECT @VersionNumber = COALESCE(1 + MAX([VersionNumber]), 1)
    FROM [MySchema].[Project]
END
IF @IsMajor = 'false'
BEGIN
    SELECT @VersionNumber = COALESCE(0.1 + MAX([VersionNumber]), 1)
    FROM [MySchema].[Project]
END
</code>```

Do you know how to reset the trailing number to 0 on a decimal number?

Thank you!

答:
You can first cast MAX(VersionNumber) to an int. This will cut off the decimal digits. If you convert it back to a decimal(18,1) you can add 1:

```<code>SELECT COALESCE(1 + CONVERT(DECIMAL(18, 1), CONVERT(INT, MAX([VersionNumber]))), 1)
</code>```

Title: T-SQL set trailing numbers to zeros

Body:
I'm working on a stored procedure on SQL Server 2014.

I have a variable:

DECLARE @VersionNumber DECIMAL(18,1);

This VersionNumber can have values such as 1.0 or 1.4.

In my logic, I increase the number +0.1 if there is a minor change and +1 if there is a major change.

If there is a major change though, I want to reset the trailing numbers to 0.

Example: Version 1.4 should become 2.0 after a major change

My current query looks like this:

IF @IsMajor = 'true'
BEGIN
    SELECT @VersionNumber = COALESCE(1 + MAX([VersionNumber]), 1)
    FROM [MySchema].[Project]
END
IF @IsMajor = 'false'
BEGIN
    SELECT @VersionNumber = COALESCE(0.1 + MAX([VersionNumber]), 1)
    FROM [MySchema].[Project]
END

Do you know how to reset the trailing number to 0 on a decimal number?

Thank you!

Body:
You can first cast MAX(VersionNumber) to an int. This will cut off the decimal digits. If you convert it back to a decimal(18,1) you can add 1:

SELECT COALESCE(1 + CONVERT(DECIMAL(18, 1), CONVERT(INT, MAX([VersionNumber]))), 1)


问:
Rust behind proxy, "error: no default toolchain configured"
I installed Rust at home with no issues. Behind a company proxy I couldn't run rustup-init, so I installed 1.18 stable with an installer.

On every Rust command (e.g. cargo). I get the notification "error: no default toolchain configured". The only related question I found was this one, but the answer isn't very helpful. Knowing it is a proxy issue is useful, but I can't find an answer how to configure the proxy so that this works.

答:
I found an answer to why I'm getting this error message:

The Rust installer put two locations on my path:

C:\Users\<USERNAME>\.cargo\bin

C:\Users\<USERNAME>\AppData\Local\Programs\Rust\bin

The first one seems to have dummy .exes (which for some reason are 4.62MB) and the second one contains cargo and rustc.

I don't know why these dummy .exes exist, but if I take them off the path I can compile simple Rust programs.


问:
DateTimeFormatter doesn't parse custom date format
I have an issue with java DataTimeFormmater.
I feel that I missed something but cannot figure out what exactly.

```<code>String format = "yyyy-MM-dd'T'HH:mm:ss[.S]'T'zxxx";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);

String date = "2017-07-05T12:28:36.4TGMT+03:00";

System.out.println(formatter.format(ZonedDateTime.now()));
System.out.println(formatter.parse(date));
</code>```

The code above produces string of the current ZonedDateTime and attempts to parse date time string with the same date formatter.
Result that it successfully produces 2017-07-05T06:07:51.0TCDT-05:00 but fails to parse 2017-07-05T12:28:36.4TGMT+03:00

My goal is to parse 2017-07-05T12:28:36.4TGMT+03:00 and come up with appropriate DateTimeFormatter.

答:
You must change the format to:

```<code>String format = "yyyy-MM-dd'T'HH:mm:ss[.S]'T'[zzz][xxx]";
</code>```

Both [zzz] and [xxx] are in optional sections because zzz can parse either the whole GMT+03:00 part or just the zone short name (such as CDT), and xxx parses only the offset part (such as -05:00 - so it's not needed if a GMT+03:00 is found).

Just reminding that formatter.parse(date) returns a TemporalAccessor object. If you want to create a specific type, it's better to use the class's respective parse method:

```<code>System.out.println(ZonedDateTime.parse(date, formatter)); // 2017-07-05T12:28:36.400+03:00[GMT+03:00]
</code>```

PS: the only problem with this formatter is that, when formatting, it prints all the optional sections. So, if you do something like this:

```<code>String date = "2017-07-05T12:28:36.4TGMT+03:00";
ZonedDateTime z  = ZonedDateTime.parse(date, formatter);
System.out.println(formatter.format(z));
</code>```

The output will be:

2017-07-05T12:28:36.4TGMT+03:00+03:00

That's because the GMT+03:00 is the result of zzz and the second +03:00 is the result of xxx. If you don't want this, I recomment using 2 different DateTimeFormatter's (one for parsing, another for formatting).

Or (an "uglier" approach), use 2 different formatters:

```<code>DateTimeFormatter noGMT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.S]'T'zzzxxx");
DateTimeFormatter gmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.S]'TGMT'xxx");
</code>```

Then, you try to parse with the first - if you get an exception, try with the second (or you check if your input contains GMT to know which one to use).

I personally don't like this because GMT is part of the zone name and should't be treated as a literal. But in the end, you get a ZonedDateTime with the correct offset, so I'm not sure of how wrong this approach is.

Timezone abbreviations

Please be aware that you should avoid (as possible) using the 3-letter abbreviations (like CDT or PST) because they are ambiguous and not standard. CDT can be both Central Daylight Time (UTC-05:00), Cuba Daylight Time (UTC-04:00) or even China Daylight Time (UTC+09:00).

Prefer, if possible, to use IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin). Based on that list, there are more than 40 timezones that uses (or had used somewhere in the past) the CDT abbreviation.

CDT works for this case because some abbreviations have default values configured, probably due to retro-compatibility reasons, but you shouldn't rely on them for all cases.

To make sure your timezone abbreviations always work (in case you can't avoid using them), you can create a formatter that uses a set of prefered zones. In this case, I'm using America/Chicago (so, CST or CDT will be parsed as Chicago's timezone):

```<code>Set<ZoneId> preferedZones = new HashSet<>();
preferedZones.add(ZoneId.of("America/Chicago"));
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // append first part of pattern (before timezone)
    .appendPattern("yyyy-MM-dd'T'HH:mm:ss[.S]'T'")
    // append zone name, use prefered zones (optional)
    .optionalStart().appendZoneText(TextStyle.SHORT, preferedZones).optionalEnd()
    // offset (optional)
    .appendPattern("[xxx]")
    // create formatter
    .toFormatter();
</code>```

This formatter works the same way as above, for both your inputs (with and without GMT), and uses America/Chicago as default timezone when CDT is in the input. You can add as many zones you want in the set, according to your use cases.

Just reminding that this formatter has the same issues regarding the output (it prints all optional sections), as already stated above.

Body:
I have an issue with java DataTimeFormmater.
I feel that I missed something but cannot figure out what exactly.

String format = "yyyy-MM-dd'T'HH:mm:ss[.S]'T'zxxx";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);

String date = "2017-07-05T12:28:36.4TGMT+03:00";

System.out.println(formatter.format(ZonedDateTime.now()));
System.out.println(formatter.parse(date));

The code above produces string of the current ZonedDateTime and attempts to parse date time string with the same date formatter.
Result that it successfully produces 2017-07-05T06:07:51.0TCDT-05:00 but fails to parse 2017-07-05T12:28:36.4TGMT+03:00

My goal is to parse 2017-07-05T12:28:36.4TGMT+03:00 and come up with appropriate DateTimeFormatter.

Body:
You must change the format to:

String format = "yyyy-MM-dd'T'HH:mm:ss[.S]'T'[zzz][xxx]";

Both [zzz] and [xxx] are in optional sections because zzz can parse either the whole GMT+03:00 part or just the zone short name (such as CDT), and xxx parses only the offset part (such as -05:00 - so it's not needed if a GMT+03:00 is found).

Just reminding that formatter.parse(date) returns a TemporalAccessor object. If you want to create a specific type, it's better to use the class's respective parse method:

System.out.println(ZonedDateTime.parse(date, formatter)); // 2017-07-05T12:28:36.400+03:00[GMT+03:00]

PS: the only problem with this formatter is that, when formatting, it prints all the optional sections. So, if you do something like this:

String date = "2017-07-05T12:28:36.4TGMT+03:00";
ZonedDateTime z  = ZonedDateTime.parse(date, formatter);
System.out.println(formatter.format(z));

The output will be:

2017-07-05T12:28:36.4TGMT+03:00+03:00

That's because the GMT+03:00 is the result of zzz and the second +03:00 is the result of xxx. If you don't want this, I recomment using 2 different DateTimeFormatter's (one for parsing, another for formatting).

Or (an "uglier" approach), use 2 different formatters:

DateTimeFormatter noGMT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.S]'T'zzzxxx");
DateTimeFormatter gmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.S]'TGMT'xxx");

Then, you try to parse with the first - if you get an exception, try with the second (or you check if your input contains GMT to know which one to use).

I personally don't like this because GMT is part of the zone name and should't be treated as a literal. But in the end, you get a ZonedDateTime with the correct offset, so I'm not sure of how wrong this approach is.

Timezone abbreviations

Please be aware that you should avoid (as possible) using the 3-letter abbreviations (like CDT or PST) because they are ambiguous and not standard. CDT can be both Central Daylight Time (UTC-05:00), Cuba Daylight Time (UTC-04:00) or even China Daylight Time (UTC+09:00).

Prefer, if possible, to use IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin). Based on that list, there are more than 40 timezones that uses (or had used somewhere in the past) the CDT abbreviation.

CDT works for this case because some abbreviations have default values configured, probably due to retro-compatibility reasons, but you shouldn't rely on them for all cases.

To make sure your timezone abbreviations always work (in case you can't avoid using them), you can create a formatter that uses a set of prefered zones. In this case, I'm using America/Chicago (so, CST or CDT will be parsed as Chicago's timezone):

Set<ZoneId> preferedZones = new HashSet<>();
preferedZones.add(ZoneId.of("America/Chicago"));
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // append first part of pattern (before timezone)
    .appendPattern("yyyy-MM-dd'T'HH:mm:ss[.S]'T'")
    // append zone name, use prefered zones (optional)
    .optionalStart().appendZoneText(TextStyle.SHORT, preferedZones).optionalEnd()
    // offset (optional)
    .appendPattern("[xxx]")
    // create formatter
    .toFormatter();

This formatter works the same way as above, for both your inputs (with and without GMT), and uses America/Chicago as default timezone when CDT is in the input. You can add as many zones you want in the set, according to your use cases.

Just reminding that this formatter has the same issues regarding the output (it prints all optional sections), as already stated above.


问:
Using Oracle.DataAccess.DLL already on PC, not providing it
I am looking to make my program more dynamic. I would like it to be able to support an Oracle 10g and an Oracle 11g database with the same program. If I build the program using the .DLL reference for one version then the other fails. Is there a way to use the Oracle.DataAccess.DLL that is already on the computer being installed upon, instead of providing the DLL in my installer?

Thanks in advance.

答:
If you select the reference in Visual Studio and go to the Properties window (F4 by default), you'll see an option labeled "Specific Version".  If you set this to false, the project will accept different versions of the DLL.

Now this doesn't necessarily mean that the project will find the version of the DLL.  If it isn't near the .exe (i.e. in the folder, or subfolder) or in the GAC, then you'll have to do some work on your own to load it.


问:
Error in Python when dealing with lists read from a text file
Here is my code. I am newbie to Python:

```<code>    f=open('dt2.txt','r').read().split('\n')
    for i in range (len(f)):
        a=f[i].split('\t')
        print type(a)
        print str(a[1])," with roll no: ",str(a[0])," ",
        c=0
        d=0
        for j in range (0,100):
            try:
                if str(a[j])=="HU101":
                    c+=1
                if str(a[j])=="HU301":
                    c+=1
                if str(a[j])=="HU481":
                    c+=1
                if str(a[j])=="HU501":
                    c+=1
                if str(a[j])=="HU601":
                    c+=1
                if str(a[j])=="HU781":
                    c+=1
                if str(a[j])=="HU801A":
                    c+=1
                if str(a[j])=="HU801B":
                    c+=1
                if str(a[j])=="M101":
                    d+=1
            except IndexError:
                continue
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"
</code>```

I am getting this error:

enter image description here

答:
Frankly, this code is terrible. If I understand correctly what you're trying to achieve, this is a much cleaner way of doing the same:</p>

```<code>f = open('dt2.txt','r')
for line in f:
    a = line.split('\t')
    print "{} with roll no: {} ".format(a[1],a[0]),
    c = sum(1 for j in a if j in set("HU101", "HU301", "HU481", "HU501", "HU601", "HU781", "HU801A", "HU801B"))
    d = 1 if "M101" in a else 0
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"
f.close()
</code>```

Body:
Here is my code. I am newbie to Python:

    f=open('dt2.txt','r').read().split('\n')
    for i in range (len(f)):
        a=f[i].split('\t')
        print type(a)
        print str(a[1])," with roll no: ",str(a[0])," ",
        c=0
        d=0
        for j in range (0,100):
            try:
                if str(a[j])=="HU101":
                    c+=1
                if str(a[j])=="HU301":
                    c+=1
                if str(a[j])=="HU481":
                    c+=1
                if str(a[j])=="HU501":
                    c+=1
                if str(a[j])=="HU601":
                    c+=1
                if str(a[j])=="HU781":
                    c+=1
                if str(a[j])=="HU801A":
                    c+=1
                if str(a[j])=="HU801B":
                    c+=1
                if str(a[j])=="M101":
                    d+=1
            except IndexError:
                continue
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"

I am getting this error:

enter image description here

Body:
Frankly, this code is terrible. If I understand correctly what you're trying to achieve, this is a much cleaner way of doing the same:

f = open('dt2.txt','r')
for line in f:
    a = line.split('\t')
    print "{} with roll no: {} ".format(a[1],a[0]),
    c = sum(1 for j in a if j in set("HU101", "HU301", "HU481", "HU501", "HU601", "HU781", "HU801A", "HU801B"))
    d = 1 if "M101" in a else 0
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"
f.close()


问:
javascript: Loop Function on Array With Holes
If I create a sparse array (which has some holes in it), the array functions, like .map(), .reduce(), .forEach() will skip these holes.

```<code>[, , 1, , 2].forEach((item) => console.log(item))
// 1
// 2
</code>```

what I'm looking for is an array function which does not skip the holes, and works like this:

```<code>[, , 1, , 2].fullForEach((item) => console.log(item))
// undefined
// undefined
// 1
// undefined
// 2
</code>```

I would like to loop on the original array, and NOT to convert the holes in the array to actual undefined values, i.e. none of the following is what I'm looking for:

```<code>Array.from([, , 1, , 2]).forEach();
[...[, , 1, , 2]].forEach();
</code>```

I'm looking for a functional solution for this, which means I'd like to get a solution without any for / while loop.

答:
It will work.</p>

```<code>[,,1,4,,,,1].find((item) => console.log(item));
</code>```

Body:
If I create a sparse array (which has some holes in it), the array functions, like .map(), .reduce(), .forEach() will skip these holes.

[, , 1, , 2].forEach((item) => console.log(item))
// 1
// 2

what I'm looking for is an array function which does not skip the holes, and works like this:

[, , 1, , 2].fullForEach((item) => console.log(item))
// undefined
// undefined
// 1
// undefined
// 2

I would like to loop on the original array, and NOT to convert the holes in the array to actual undefined values, i.e. none of the following is what I'm looking for:

Array.from([, , 1, , 2]).forEach();
[...[, , 1, , 2]].forEach();

I'm looking for a functional solution for this, which means I'd like to get a solution without any for / while loop.

Body:
It will work.

[,,1,4,,,,1].find((item) => console.log(item));