问:
Problem overlaying additional percentile markers on seaborn boxplot
I want to plot additional markers on a boxplot to show 95th and 5th percentiles. I want the whiskers to show 90th and 10th percentiles which I believe I can do with whis = [10,95]

To test this is working correctly I set both my markers and my whiskers to 5 and 95.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

assay=pd.read_csv('df.csv')

#obtain percentiles of interest
pcntls=assay.groupby(['STRAT']).describe(percentiles=[0.05,0.95])
sumry= pcntls['Total'].T

#plot boxplot (with whiskers set to 5 and 95 as well to check)
ax=sns.boxplot(x=assay['STRAT'],y=assay["Total"], whis=[5,95],data=assay, showfliers=False,color='lightblue',
            showmeans=True,meanprops={"marker":"s","markersize":10,"markerfacecolor":"white", "markeredgecolor":"grey"})
plt.axhline(0.30, color='green',linestyle='dashed', label="0.3% S")
#ax.set_yscale('log')
leg= plt.legend()
plt.title("Assay data")

#overlay additional percentile points ( same as whiskers to check)
ax.scatter(x=list(sumry.columns.values),y=sumry.loc['5%'])
ax.scatter(x=list(sumry.columns.values),y=sumry.loc['95%'])
```

<p>Which gives me:</p>

<p><img src="https://i.stack.imgur.com/eZeRb.png" alt=""></p>

<p>The two plots furthest to the right have the markers applied incorrectly (the markers should be at the same y values as the ends of the whiskers), the order of the data series seems to have these reversed; but also, the percentiles seem off, the whiskers and markers will not match up even if the correct sequence is applied. Any ideas whats wrong and how to fix this? </p>

<p>Data below.</p>

```From    To  Interval (m)    Class   STRAT   Total
308 309 1   PAF CBC 4.15
309 310 1   PAF CBC 3.76
320 321 1   PAF-LC  CBC 0.85
330 331 1   PAF-LC  CBC 0.698
342 343 1   NAF LBB 0.259
376 377 1   NAF LBB 0.395
412 413 1   PAF-LC  LBB 1.19
51  52  1   PAF UBB 0.1
420 420.5   0.5 PAF-LC  UAB 1
189 190 1   PAF LBB 1.52
520 521 1   NAF UAB 3
632 633 1   NAF UAB 0.0615
644 645 1   NAF-AC  UAB 0.178
308 309 1   PAF CBC 4.15
309 310 1   PAF CBC 3.76
320 321 1   PAF-LC  CBC 0.85
330 331 1   PAF-LC  CBC 0.698
342 343 1   NAF-AC  LBB 0.259
376 377 1   NAF-AC  LBB 0.395
412 413 1   PAF-LC  LBB 1.19
51  52  1   PAF UBB 2.27
420 420.5   0.5 PAF-LC  UAB 1
189 190 1   PAF LBB 1.52
520 521 1   NAF-AC  UAB 1
632 633 1   NAF-AC  UAB 0.0615
644 645 1   NAF-AC  UAB 0.178
308 309 1   PAF CBC 4.15
309 310 1   PAF CBC 3.76
320 321 1   PAF-LC  CBC 0.85
330 331 1   PAF-LC  CBC 0.698
342 343 1   NAF-AC  LBB 0.259
376 377 1   NAF-AC  LBB 0.395
412 413 1   PAF-LC  LBB 1.19
51  52  1   PAF UBB 2.27
420 420.5   0.5 PAF-LC  UAB 0.002
189 190 1   PAF LBB 1.52
520 521 1   NAF-HS  UAB 1.45
632 633 1   NAF-HS  UAB 0.0615
644 645 1   NAF-HS  UAB 0.178
308 309 1   PAF CBC 4.15
309 310 1   PAF CBC 3.76
320 321 1   PAF-LC  CBC 0.85
330 331 1   PAF-LC  CBC 0.698
342 343 1   NAF-HS  LBB 0.259
376 377 1   NAF-HS  LBB 0.395
412 413 1   PAF-LC  LBB 1.19
51  52  1   PAF UBB 3
420 420.5   0.5 PAF-LC  UAB 1
189 190 1   PAF LBB 1.52
520 521 1   NAF-HS  UAB 1.45
632 633 1   NAF-HS  UAB 0.0615
644 645 1   NAF-HS  UAB 0.178
51  52  1   PAF UBB 0.1
51  52  1   PAF UBB 0.2
51  52  1   PAF UBB 2.27
51  52  1   PAF UBB 3
```

答:
Simply sort the boxplot data using:

ordered=sorted(assay['STRAT'].unique())
```

<p>and do the same for the percentile data:</p>

<pre class="lang-py prettyprint-override"><code>ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'])
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['95%'])
</code>```

plus some gridlines, giving:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

assay=pd.read_csv('df.csv')

#obtain percentiles of interest
pcntls=assay.groupby(['STRAT']).describe(percentiles=[0.05,0.95])
sumry= pcntls['Total'].T

ordered=sorted(assay['STRAT'].unique())

#plot boxplot (with whiskers set to 5 and 95 as well to check)
ax=sns.boxplot(x=assay['STRAT'],y=assay["Total"], order=ordered,whis=[5,95],data=assay, showfliers=False,color='lightblue',
            showmeans=True,meanprops={"marker":"s","markersize":10,"markerfacecolor":"white", "markeredgecolor":"grey"})
plt.axhline(0.30, color='green',linestyle='dashed', label="0.3% S")
#ax.set_yscale('log')
leg= plt.legend()
plt.title("Assay data")

plt.grid(True, which='both')

#overlay additional percentile points ( same as whiskers to check)
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'])
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['95%'])
```

results in correct output order, but there is a discrepency with the calculation of the 95th percentile for UAB, likely due to multiple methods and the small dataset. e.g. here

Body:
I want to plot additional markers on a boxplot to show 95th and 5th percentiles. I want the whiskers to show 90th and 10th percentiles which I believe I can do with whis = [10,95]

To test this is working correctly I set both my markers and my whiskers to 5 and 95.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

assay=pd.read_csv('df.csv')

#obtain percentiles of interest
pcntls=assay.groupby(['STRAT']).describe(percentiles=[0.05,0.95])
sumry= pcntls['Total'].T

#plot boxplot (with whiskers set to 5 and 95 as well to check)
ax=sns.boxplot(x=assay['STRAT'],y=assay["Total"], whis=[5,95],data=assay, showfliers=False,color='lightblue',
            showmeans=True,meanprops={"marker":"s","markersize":10,"markerfacecolor":"white", "markeredgecolor":"grey"})
plt.axhline(0.30, color='green',linestyle='dashed', label="0.3% S")
#ax.set_yscale('log')
leg= plt.legend()
plt.title("Assay data")

#overlay additional percentile points ( same as whiskers to check)
ax.scatter(x=list(sumry.columns.values),y=sumry.loc['5%'])
ax.scatter(x=list(sumry.columns.values),y=sumry.loc['95%'])

Which gives me:

The two plots furthest to the right have the markers applied incorrectly (the markers should be at the same y values as the ends of the whiskers), the order of the data series seems to have these reversed; but also, the percentiles seem off, the whiskers and markers will not match up even if the correct sequence is applied. Any ideas whats wrong and how to fix this?

Data below.

From    To  Interval (m)    Class   STRAT   Total
308 309 1   PAF CBC 4.15
309 310 1   PAF CBC 3.76
320 321 1   PAF-LC  CBC 0.85
330 331 1   PAF-LC  CBC 0.698
342 343 1   NAF LBB 0.259
376 377 1   NAF LBB 0.395
412 413 1   PAF-LC  LBB 1.19
51  52  1   PAF UBB 0.1
420 420.5   0.5 PAF-LC  UAB 1
189 190 1   PAF LBB 1.52
520 521 1   NAF UAB 3
632 633 1   NAF UAB 0.0615
644 645 1   NAF-AC  UAB 0.178
308 309 1   PAF CBC 4.15
309 310 1   PAF CBC 3.76
320 321 1   PAF-LC  CBC 0.85
330 331 1   PAF-LC  CBC 0.698
342 343 1   NAF-AC  LBB 0.259
376 377 1   NAF-AC  LBB 0.395
412 413 1   PAF-LC  LBB 1.19
51  52  1   PAF UBB 2.27
420 420.5   0.5 PAF-LC  UAB 1
189 190 1   PAF LBB 1.52
520 521 1   NAF-AC  UAB 1
632 633 1   NAF-AC  UAB 0.0615
644 645 1   NAF-AC  UAB 0.178
308 309 1   PAF CBC 4.15
309 310 1   PAF CBC 3.76
320 321 1   PAF-LC  CBC 0.85
330 331 1   PAF-LC  CBC 0.698
342 343 1   NAF-AC  LBB 0.259
376 377 1   NAF-AC  LBB 0.395
412 413 1   PAF-LC  LBB 1.19
51  52  1   PAF UBB 2.27
420 420.5   0.5 PAF-LC  UAB 0.002
189 190 1   PAF LBB 1.52
520 521 1   NAF-HS  UAB 1.45
632 633 1   NAF-HS  UAB 0.0615
644 645 1   NAF-HS  UAB 0.178
308 309 1   PAF CBC 4.15
309 310 1   PAF CBC 3.76
320 321 1   PAF-LC  CBC 0.85
330 331 1   PAF-LC  CBC 0.698
342 343 1   NAF-HS  LBB 0.259
376 377 1   NAF-HS  LBB 0.395
412 413 1   PAF-LC  LBB 1.19
51  52  1   PAF UBB 3
420 420.5   0.5 PAF-LC  UAB 1
189 190 1   PAF LBB 1.52
520 521 1   NAF-HS  UAB 1.45
632 633 1   NAF-HS  UAB 0.0615
644 645 1   NAF-HS  UAB 0.178
51  52  1   PAF UBB 0.1
51  52  1   PAF UBB 0.2
51  52  1   PAF UBB 2.27
51  52  1   PAF UBB 3

Body:
Simply sort the boxplot data using:

ordered=sorted(assay['STRAT'].unique())

and do the same for the percentile data:

ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'])
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['95%'])

plus some gridlines, giving:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

assay=pd.read_csv('df.csv')

#obtain percentiles of interest
pcntls=assay.groupby(['STRAT']).describe(percentiles=[0.05,0.95])
sumry= pcntls['Total'].T

ordered=sorted(assay['STRAT'].unique())

#plot boxplot (with whiskers set to 5 and 95 as well to check)
ax=sns.boxplot(x=assay['STRAT'],y=assay["Total"], order=ordered,whis=[5,95],data=assay, showfliers=False,color='lightblue',
            showmeans=True,meanprops={"marker":"s","markersize":10,"markerfacecolor":"white", "markeredgecolor":"grey"})
plt.axhline(0.30, color='green',linestyle='dashed', label="0.3% S")
#ax.set_yscale('log')
leg= plt.legend()
plt.title("Assay data")

plt.grid(True, which='both')

#overlay additional percentile points ( same as whiskers to check)
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'])
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['95%'])

results in correct output order, but there is a discrepency with the calculation of the 95th percentile for UAB, likely due to multiple methods and the small dataset. e.g. here


来源: stackexchange

问:
Generic Interface with composed interfaces and multiple concrete implementations
I want to use a generic interface, that can take other interfaces as properties, that use a concrete implementation. How do I create the pattern, if possible, and how do I resolve the implementation in the service collection. This is going to be used alongside a unit of work and the repository pattern.

I've been trying different techniques and implementations through code. Some have been able to compile, but at runtime they have not been able to get resolved. Part of the question is - can the approach be done, the other have I not resolved this correctly.

```<code>public class GenericInterface<T, U> : IGenericInterface<T, U>
{
    public T InterfaceOne { get; set; }     // IInterfaceOne
    public U InterfaceTwo { get; set; }     // IInterfaceTwo
}

public interface IInterfaceOne
{
    void DoOne();
    void DoTwo();
}

public interface IInterfaceTwo
{
    void DoThree();
    void DoFour();
}

public class ConcreteImplementation : IInterfaceOne, IInterfaceTwo
{
    public void DoOne()
    {
        throw new System.NotImplementedException();
    }

    public void DoTwo()
    {
        throw new System.NotImplementedException();
    }

    public void DoThree()
    {
        throw new System.NotImplementedException();
    }

    public void DoFour()
    {
        throw new System.NotImplementedException();
    }
}

public class Resolver {

    public void Resolve() {

        // Should be able to use the interfaces and reference the ConcreteImplementation....!?
        // How to resolve in a service collection?
        var genericComposedInterfaces = new GenericInterface<IInterfaceOne, IInterfaceTwo>();
    }
}
</code>```

The desired result is that it should first serve the purpose and secondly get resolved within the service collection / when it is called.

Update

Thanks for the help. So I think I was caught between two minds of what I was trying to achieve. All I really wanted was one backing class that was exposed via two interfaces that could be combined into one generic interface. I think the following works.

Generic Interface takes two or several interfaces.

```<code>public interface ITestGenericInterface<T, U>
{
    T InterfaceOne { get; }
    U InterfaceTwo { get; }
}

public class TestGenericInterface<T, U> : ITestGenericInterface<T, U>
{
    public TestGenericInterface(T interfaceOne, U interfaceTwo)
    {
        InterfaceOne = interfaceOne;
        InterfaceTwo = interfaceTwo;
    }

    public T InterfaceOne { get; }
    public U InterfaceTwo { get; }
}
</code>```

The interfaces with a class that might be used with the above interface.

```<code>public interface IInterfaceOne
{
    void DoOne();
    void DoTwo();
}

public interface IInterfaceTwo
{
    void DoThree();
    void DoFour();
}

public class ConcreteClass : IInterfaceOne, IInterfaceTwo
{
    public void DoOne()
    {
        Console.WriteLine("DoOne()");
    }
    public void DoTwo()
    {
        Console.WriteLine("DoTwo()");
    }

    public void DoThree()
    {
        Console.WriteLine("DoDoThreeOne()");
    }

    public void DoFour()
    {
        Console.WriteLine("DoFour()");
    }
}
</code>```

Registering in the service collection. I don't think I was registering the interface / implementation correctly before which could have been an issue.

```<code>  services.AddScoped<IInterfaceOne, ConcreteClass>();
  services.AddScoped<IInterfaceTwo, ConcreteClass>();
  services.AddScoped(typeof(ITestGenericInterface<,>), typeof(TestGenericInterface<,>));
</code>```

Trying it out

```<code>public interface ITestRunner
{
    void Start();
}

public class TestRunner : ITestRunner
{
    private readonly ITestGenericInterface<IInterfaceOne, IInterfaceTwo> _genericTest;

    public TestRunner(
        ITestGenericInterface<IInterfaceOne, IInterfaceTwo> genericTest
        )
    {
        _genericTest = genericTest;
    }

    public void Start()
    {
        // Interface One
        _genericTest.InterfaceOne.DoOne();
        _genericTest.InterfaceOne.DoTwo();

        // Interface Two
        _genericTest.InterfaceTwo.DoThree();
        _genericTest.InterfaceTwo.DoFour();
    }
}
</code>```

I appreciate that this was probably simpler than it sounded in my initial question. As Flavio Francisco put me on the right track with his first answer, I will up vote it and mark as the answer. Hopefully this will help someone else. Many thanks.

答:
If you want an instance of a class that implements two interfaces you could do it also:

```<code>public interface IInterfaceOneAndTwo : IInterfaceOne, IInterfaceTwo
{

}

public interface IInterfaceOne
{
    void DoOne();
    void DoTwo();
}

public interface IInterfaceTwo
{
    void DoThree();
    void DoFour();
}
</code>```

Your concrete class:

```<code>public class ConcreteClass : IInterfaceOneAndTwo
{
    public void DoFour()
    {
        throw new NotImplementedException();
    }

    public void DoOne()
    {
        throw new NotImplementedException();
    }

    public void DoThree()
    {
        throw new NotImplementedException();
    }

    public void DoTwo()
    {
        throw new NotImplementedException();
    }
}
</code>```

and your resolver:

```<code>IInterfaceOneAndTwo concreteClass = new ConcreteClass();

concreteClass.DoOne();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to use a generic interface, that can take other interfaces as properties, that use a concrete implementation. How do I create the pattern, if possible, and how do I resolve the implementation in the service collection. This is going to be used alongside a unit of work and the repository pattern.

I've been trying different techniques and implementations through code. Some have been able to compile, but at runtime they have not been able to get resolved. Part of the question is - can the approach be done, the other have I not resolved this correctly.

public class GenericInterface<T, U> : IGenericInterface<T, U>
{
    public T InterfaceOne { get; set; }     // IInterfaceOne
    public U InterfaceTwo { get; set; }     // IInterfaceTwo
}

public interface IInterfaceOne
{
    void DoOne();
    void DoTwo();
}

public interface IInterfaceTwo
{
    void DoThree();
    void DoFour();
}

public class ConcreteImplementation : IInterfaceOne, IInterfaceTwo
{
    public void DoOne()
    {
        throw new System.NotImplementedException();
    }

    public void DoTwo()
    {
        throw new System.NotImplementedException();
    }

    public void DoThree()
    {
        throw new System.NotImplementedException();
    }

    public void DoFour()
    {
        throw new System.NotImplementedException();
    }
}

public class Resolver {

    public void Resolve() {

        // Should be able to use the interfaces and reference the ConcreteImplementation....!?
        // How to resolve in a service collection?
        var genericComposedInterfaces = new GenericInterface<IInterfaceOne, IInterfaceTwo>();
    }
}

The desired result is that it should first serve the purpose and secondly get resolved within the service collection / when it is called.

Update

Thanks for the help. So I think I was caught between two minds of what I was trying to achieve. All I really wanted was one backing class that was exposed via two interfaces that could be combined into one generic interface. I think the following works.

Generic Interface takes two or several interfaces.

public interface ITestGenericInterface<T, U>
{
    T InterfaceOne { get; }
    U InterfaceTwo { get; }
}

public class TestGenericInterface<T, U> : ITestGenericInterface<T, U>
{
    public TestGenericInterface(T interfaceOne, U interfaceTwo)
    {
        InterfaceOne = interfaceOne;
        InterfaceTwo = interfaceTwo;
    }

    public T InterfaceOne { get; }
    public U InterfaceTwo { get; }
}

The interfaces with a class that might be used with the above interface.

public interface IInterfaceOne
{
    void DoOne();
    void DoTwo();
}

public interface IInterfaceTwo
{
    void DoThree();
    void DoFour();
}

public class ConcreteClass : IInterfaceOne, IInterfaceTwo
{
    public void DoOne()
    {
        Console.WriteLine("DoOne()");
    }
    public void DoTwo()
    {
        Console.WriteLine("DoTwo()");
    }

    public void DoThree()
    {
        Console.WriteLine("DoDoThreeOne()");
    }

    public void DoFour()
    {
        Console.WriteLine("DoFour()");
    }
}

Registering in the service collection. I don't think I was registering the interface / implementation correctly before which could have been an issue.

  services.AddScoped<IInterfaceOne, ConcreteClass>();
  services.AddScoped<IInterfaceTwo, ConcreteClass>();
  services.AddScoped(typeof(ITestGenericInterface<,>), typeof(TestGenericInterface<,>));

Trying it out

public interface ITestRunner
{
    void Start();
}

public class TestRunner : ITestRunner
{
    private readonly ITestGenericInterface<IInterfaceOne, IInterfaceTwo> _genericTest;

    public TestRunner(
        ITestGenericInterface<IInterfaceOne, IInterfaceTwo> genericTest
        )
    {
        _genericTest = genericTest;
    }

    public void Start()
    {
        // Interface One
        _genericTest.InterfaceOne.DoOne();
        _genericTest.InterfaceOne.DoTwo();

        // Interface Two
        _genericTest.InterfaceTwo.DoThree();
        _genericTest.InterfaceTwo.DoFour();
    }
}

I appreciate that this was probably simpler than it sounded in my initial question. As Flavio Francisco put me on the right track with his first answer, I will up vote it and mark as the answer. Hopefully this will help someone else. Many thanks.

Body:
If you want an instance of a class that implements two interfaces you could do it also:

public interface IInterfaceOneAndTwo : IInterfaceOne, IInterfaceTwo
{

}

public interface IInterfaceOne
{
    void DoOne();
    void DoTwo();
}

public interface IInterfaceTwo
{
    void DoThree();
    void DoFour();
}

Your concrete class:

public class ConcreteClass : IInterfaceOneAndTwo
{
    public void DoFour()
    {
        throw new NotImplementedException();
    }

    public void DoOne()
    {
        throw new NotImplementedException();
    }

    public void DoThree()
    {
        throw new NotImplementedException();
    }

    public void DoTwo()
    {
        throw new NotImplementedException();
    }
}

and your resolver:

IInterfaceOneAndTwo concreteClass = new ConcreteClass();

concreteClass.DoOne();


问:
Add congratulation message pong gosu
I just started learning ruby and gosu. The code I am using right now is a reference from someone else code.

This is a 2 player Pong ruby game. The game is working and is able to play. I am trying to set it so that any player reach to the score of 10, the game will stopped and show the message "Player 1/2 wins" and prompt the players whether they want to continue playing.

My problem now is to show the message when one of the player score reach 10 followed by prompting the user if they want to continue.

(Disclaimer this is not my original code, i only use it to learn.)

```<code>if @player_1.score == 2
  @state = :stopped
  @message.draw_text('WIN',100,100,2)
end

if @player_2.score == 2
  @state = :stopped
end
</code>```

This code is inside class Gosu::Window (I can't quite figure out how to put the whole code here since this is my first time)

screenshot 2

screenshot 1

答:
To show your "WINNER SCREEN" you must manage status also in DRAW method.

This is an example of my code in an RPG Game...

```<code>  def draw
    case @state
    when ZOrdinals::GAME
      main_draw
    when ZOrdinals::MENU
      @main_menu.draw
    when ZOrdinals::BATTLE
      @battle.draw
    when ZOrdinals::DEAD
      @dead = Dead.new(self) if @dead.nil?
      @dead.draw
    end
  end
</code>```

And this is the DEAD SCREEN code:

```<code>require_relative 'zordinals'

# Death screen

    class Dead
      def initialize(window)
        @window = window
        @image = Gosu::Image.new(File.dirname(__FILE__) + '../../images/die.png',
                                 tileable: false)
      end

      def update; end

      def draw
        @image.draw((ZOrdinals::SCREEN_WIDTH / 2) - (@image.width / 2),
                    (ZOrdinals::SCREEN_HEIGHT / 2) - (@image.height / 2),
                    ZOrdinals::BACKGROUND)
      end
    end
</code>```

You can do something like this for your problem...

Title: Add congratulation message pong gosu

Body:
I just started learning ruby and gosu. The code I am using right now is a reference from someone else code.

This is a 2 player Pong ruby game. The game is working and is able to play. I am trying to set it so that any player reach to the score of 10, the game will stopped and show the message "Player 1/2 wins" and prompt the players whether they want to continue playing.

My problem now is to show the message when one of the player score reach 10 followed by prompting the user if they want to continue.

(Disclaimer this is not my original code, i only use it to learn.)

if @player_1.score == 2
  @state = :stopped
  @message.draw_text('WIN',100,100,2)
end

if @player_2.score == 2
  @state = :stopped
end

This code is inside class Gosu::Window (I can't quite figure out how to put the whole code here since this is my first time)

screenshot 2

screenshot 1

Body:
To show your "WINNER SCREEN" you must manage status also in DRAW method.

This is an example of my code in an RPG Game...

  def draw
    case @state
    when ZOrdinals::GAME
      main_draw
    when ZOrdinals::MENU
      @main_menu.draw
    when ZOrdinals::BATTLE
      @battle.draw
    when ZOrdinals::DEAD
      @dead = Dead.new(self) if @dead.nil?
      @dead.draw
    end
  end

And this is the DEAD SCREEN code:

require_relative 'zordinals'

# Death screen

    class Dead
      def initialize(window)
        @window = window
        @image = Gosu::Image.new(File.dirname(__FILE__) + '../../images/die.png',
                                 tileable: false)
      end

      def update; end

      def draw
        @image.draw((ZOrdinals::SCREEN_WIDTH / 2) - (@image.width / 2),
                    (ZOrdinals::SCREEN_HEIGHT / 2) - (@image.height / 2),
                    ZOrdinals::BACKGROUND)
      end
    end

You can do something like this for your problem...


问:
return the value if its in within the range?
n this project i have to check column's A value between Column B and Column C. If columnA's values>= Columns B value or Columns A value<= Columns C value then i need to copy column d and e values and need to put into sheet1 column G and H. Column A is in sheet1 and Column B, C, D and E in sheet2.

```<code>   A       B    C   D     E
   1       1    9   Dog   Naruto
  11      10   19   Cat   one piece
  21      20   30   Duck  lo
  1
  31
  12
  and so on
</code>```

I want the outcome like this

```<code>   A    G       H
   1    Dog     Naruto
   11   cat     One piece
   21   duck     o
   1    Dog     Naruto
   31
   12   cat     One piece
   and so on
</code>```

This is the code I got with the help of someone but its limited. I want it to return value no matter how many rows A column has.

```<code>Dim i As Long
Dim lRow As Long
Dim colA As Double, colB As Double, colC As Double

lRow = Sheets("Sheet1").Range("A" &
         Sheets("Sheet1").Rows.Count).End(xlUp).Row
For i = 2 To lRow
    colA = Sheets("Sheet1").Range("A" & i).Value
    colB = Sheets("Sheet2").Range("B" & i).Value
    colC = Sheets("Sheet2").Range("C" & i).Value

    If colA >= colB Or colA <= colC Then
        Sheets("Sheet1").Range("G" & i).Value = Sheets("Sheet2").Range("D" &
   i).Value
        Sheets("Sheet1").Range("H" & i).Value = Sheets("Sheet2").Range("E" &
  i).Value
    End If
Next i
</code>```

答:
If column B in Sheet2 is in a ascending order …

… you can easily do that with a formula. In B2 add the following formula and pull it down and right.

```<code>=INDEX(Sheet2!D:D,MATCH($A:$A,Sheet2!$B:$B,1))
</code>```

And you will get this output in Sheet1:

The same approach would be possible with VBA using Application.WorksheetFunction but I recommend to use the formula.

VBA Solution

```<code>Option Explicit

Public Sub FindAndFillData()
    Dim wsDest As Worksheet
    Set wsDest = ThisWorkbook.Worksheets("Sheet1")

    Dim wsLookup As Worksheet
    Set wsLookup = ThisWorkbook.Worksheets("Sheet2")

    Dim LastRow As Long
    LastRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Row

    Dim MatchedRow As Double

    Dim iRow As Long
    For iRow = 2 To LastRow
        MatchedRow = 0 'initialize!
        On Error Resume Next
        MatchedRow = Application.WorksheetFunction.Match(wsDest.Cells(iRow, "A").Value, wsLookup.Columns("B"), 1)
        On Error GoTo 0

        If MatchedRow <> 0 Then
            If wsDest.Cells(iRow, "A").Value <= wsLookup.Cells(MatchedRow, "C").Value Then
                wsDest.Cells(iRow, "B").Value = wsLookup.Cells(MatchedRow, "D").Value
                wsDest.Cells(iRow, "C").Value = wsLookup.Cells(MatchedRow, "E").Value
            End If
        End If
    Next iRow
End Sub
</code>```

Body:
n this project i have to check column's A value between Column B and Column C. If columnA's values>= Columns B value or Columns A value<= Columns C value then i need to copy column d and e values and need to put into sheet1 column G and H. Column A is in sheet1 and Column B, C, D and E in sheet2.

   A       B    C   D     E
   1       1    9   Dog   Naruto
  11      10   19   Cat   one piece
  21      20   30   Duck  lo
  1
  31
  12
  and so on

I want the outcome like this

   A    G       H
   1    Dog     Naruto
   11   cat     One piece
   21   duck     o
   1    Dog     Naruto
   31
   12   cat     One piece
   and so on

This is the code I got with the help of someone but its limited. I want it to return value no matter how many rows A column has.

Dim i As Long
Dim lRow As Long
Dim colA As Double, colB As Double, colC As Double

lRow = Sheets("Sheet1").Range("A" &
         Sheets("Sheet1").Rows.Count).End(xlUp).Row
For i = 2 To lRow
    colA = Sheets("Sheet1").Range("A" & i).Value
    colB = Sheets("Sheet2").Range("B" & i).Value
    colC = Sheets("Sheet2").Range("C" & i).Value

    If colA >= colB Or colA <= colC Then
        Sheets("Sheet1").Range("G" & i).Value = Sheets("Sheet2").Range("D" &
   i).Value
        Sheets("Sheet1").Range("H" & i).Value = Sheets("Sheet2").Range("E" &
  i).Value
    End If
Next i

Body:
If column B in Sheet2 is in a ascending order …

… you can easily do that with a formula. In B2 add the following formula and pull it down and right.

=INDEX(Sheet2!D:D,MATCH($A:$A,Sheet2!$B:$B,1))

And you will get this output in Sheet1:

The same approach would be possible with VBA using Application.WorksheetFunction but I recommend to use the formula.

VBA Solution

Option Explicit

Public Sub FindAndFillData()
    Dim wsDest As Worksheet
    Set wsDest = ThisWorkbook.Worksheets("Sheet1")

    Dim wsLookup As Worksheet
    Set wsLookup = ThisWorkbook.Worksheets("Sheet2")

    Dim LastRow As Long
    LastRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Row

    Dim MatchedRow As Double

    Dim iRow As Long
    For iRow = 2 To LastRow
        MatchedRow = 0 'initialize!
        On Error Resume Next
        MatchedRow = Application.WorksheetFunction.Match(wsDest.Cells(iRow, "A").Value, wsLookup.Columns("B"), 1)
        On Error GoTo 0

        If MatchedRow <> 0 Then
            If wsDest.Cells(iRow, "A").Value <= wsLookup.Cells(MatchedRow, "C").Value Then
                wsDest.Cells(iRow, "B").Value = wsLookup.Cells(MatchedRow, "D").Value
                wsDest.Cells(iRow, "C").Value = wsLookup.Cells(MatchedRow, "E").Value
            End If
        End If
    Next iRow
End Sub


问:
Sending POJO containing XML Document via Spring MVC
i try to post a POJO from one Spring Boot&MVC app to another.
This all works fine except for one case, in which the POJO contains a w3c.dom.Document XML attribute.

The POJO is quite simple, all getters and setters are managed by project lombok:

@Data
public class SmartContractFile {
    private final UUID id;
    private Document file;
    private int copies;

    public SmartContractFile(UUID id, Document scFile, int copies) {
        this.id = id;
        this.file = scFile;
        this.copies = copies;
    }
}
```

<p>The POSTing happens via Spring RestTemplate and contains only the POJO.
I expect a simple true or false response.</p>

<pre class="lang-java prettyprint-override"><code>    public boolean saveFile(SmartContractFile smartContract) {
        RestTemplate template = new RestTemplate();
        URI methodURI;
        try {
            methodURI = new URI(this.address + DNWebConstants.REST_ADDSC);
            ResponseEntity<Boolean> response = template.postForEntity(methodURI, smartContract, Boolean.class);

            return (response.hasBody() && response.getBody());
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }
</code>```

The server-side webservice is bound via @RequestMapping and a constant to the target address. I already tried @PostMapping, but the behavior did not change. The POJO should be extracted by Spring via @RequestBody.

@RequestMapping(DNWebConstants.REST_ADDSC)
    public ResponseEntity<Boolean> addSmartContract(@RequestBody SmartContractFile smartContract) {
        try {
            smartContractHandler.validateScDocument(smartContract.getFile());
        } catch (ContractException | IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(false);
        }
        if (this.thisNode.saveRequestedScStorage(smartContract))
            return ResponseEntity.ok(true);
        else
            System.out.println("Wrong storage location.");
        return ResponseEntity.badRequest().body(false);
    }
```

<p>In case of any error in my application, i would always expect a 400 bad request with "false" in the response body, as well as an output on the servers console (either via printStackTrace() or System.out.println()).</p>

<p>However, all i get is a 400 with empty body:</p>

```org.springframework.web.client.HttpClientErrorException: 400 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:766) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:724) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:698) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:484) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at model.Node.saveFile(Node.java:80) ~[classes/:na]
    at model.Topology.saveFile(Topology.java:50) ~[classes/:na]
    at mgmt.web.DNWebservice.saveSmartContract(DNWebservice.java:111) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_201]
```

<p>With this being my application:</p>

```at model.Node.saveFile(Node.java:80) ~[classes/:na]
    at model.Topology.saveFile(Topology.java:50) ~[classes/:na]
    at mgmt.web.DNWebservice.saveSmartContract(DNWebservice.java:111) ~[classes/:na]
```

Where model.Node.saveFile(Node.java:80) is the client method shown above.

I basically tried every way i know to pack that request and switched wildly through al Spring Annotations, but nothing worked.
So i hope there's somebody here to help me.

Thanks in advance!

答:
I now found my error, it had nothing to do with the resttemplate.
The bootstrap had an error which caused the app to send the request to itself.
The client denied its' own request and Spring did all the errorhandling automatically, so it did not show in the console output as logged by my application, which is why i overlooked it.

After fixing this, the request in the OP worked just fine.
Sorry.

Body:
i try to post a POJO from one Spring Boot&MVC app to another.
This all works fine except for one case, in which the POJO contains a w3c.dom.Document XML attribute.

The POJO is quite simple, all getters and setters are managed by project lombok:

@Data
public class SmartContractFile {
    private final UUID id;
    private Document file;
    private int copies;

    public SmartContractFile(UUID id, Document scFile, int copies) {
        this.id = id;
        this.file = scFile;
        this.copies = copies;
    }
}

The POSTing happens via Spring RestTemplate and contains only the POJO.
I expect a simple true or false response.

    public boolean saveFile(SmartContractFile smartContract) {
        RestTemplate template = new RestTemplate();
        URI methodURI;
        try {
            methodURI = new URI(this.address + DNWebConstants.REST_ADDSC);
            ResponseEntity<Boolean> response = template.postForEntity(methodURI, smartContract, Boolean.class);

            return (response.hasBody() && response.getBody());
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

The server-side webservice is bound via @RequestMapping and a constant to the target address. I already tried @PostMapping, but the behavior did not change. The POJO should be extracted by Spring via @RequestBody.

@RequestMapping(DNWebConstants.REST_ADDSC)
    public ResponseEntity<Boolean> addSmartContract(@RequestBody SmartContractFile smartContract) {
        try {
            smartContractHandler.validateScDocument(smartContract.getFile());
        } catch (ContractException | IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(false);
        }
        if (this.thisNode.saveRequestedScStorage(smartContract))
            return ResponseEntity.ok(true);
        else
            System.out.println("Wrong storage location.");
        return ResponseEntity.badRequest().body(false);
    }

In case of any error in my application, i would always expect a 400 bad request with "false" in the response body, as well as an output on the servers console (either via printStackTrace() or System.out.println()).

However, all i get is a 400 with empty body:

org.springframework.web.client.HttpClientErrorException: 400 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:766) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:724) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:698) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:484) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at model.Node.saveFile(Node.java:80) ~[classes/:na]
    at model.Topology.saveFile(Topology.java:50) ~[classes/:na]
    at mgmt.web.DNWebservice.saveSmartContract(DNWebservice.java:111) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_201]

With this being my application:

at model.Node.saveFile(Node.java:80) ~[classes/:na]
    at model.Topology.saveFile(Topology.java:50) ~[classes/:na]
    at mgmt.web.DNWebservice.saveSmartContract(DNWebservice.java:111) ~[classes/:na]

Where model.Node.saveFile(Node.java:80) is the client method shown above.

I basically tried every way i know to pack that request and switched wildly through al Spring Annotations, but nothing worked.
So i hope there's somebody here to help me.

Thanks in advance!


问:
How to fix invalid prop 'color' suplied to 'icon'?
I’m setting up a new component with an icon from the "react-native-vector-icons" and I got a yellow warning.

This is for a new feature of the icon

```<code>Dashboard: {
        screen: DashboardStack,
        navigationOptions: {
            title: 'HOME',
            tabBarOnPress: ({ navigation, defaultHandler }) => handleTabPress(navigation, defaultHandler),
            tabBarIcon: ({ focused, tintColor }) => {
                // HERE IS THE PROBLEM //
            return <SSIcon name={'home'} size={20} color={focused ? GStyle.GREEN : Color(GStyle.BLACK).alpha(.45)} />

            },

        }
    },
</code>```

I expect for no yellow warning

答:
You could try this code</p>

```<code> <SSIcon name={'home'} size={20} color={focused ? "green" : "black"} />
</code>```

Body:
I’m setting up a new component with an icon from the "react-native-vector-icons" and I got a yellow warning.

This is for a new feature of the icon

Dashboard: {
        screen: DashboardStack,
        navigationOptions: {
            title: 'HOME',
            tabBarOnPress: ({ navigation, defaultHandler }) => handleTabPress(navigation, defaultHandler),
            tabBarIcon: ({ focused, tintColor }) => {
                // HERE IS THE PROBLEM //
            return <SSIcon name={'home'} size={20} color={focused ? GStyle.GREEN : Color(GStyle.BLACK).alpha(.45)} />

            },

        }
    },

I expect for no yellow warning

Body:
You could try this code

 <SSIcon name={'home'} size={20} color={focused ? "green" : "black"} />


问:
gets() problem in C
I wrote the following code:

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

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int const count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}
</code>```

The problem is that the gcc gives me an error for the 'int const count': " increment of read-only variable ‘count’".

What seems to be wrong ?

Thank !

答:
Try using fgets instead as:

```<code>fgets (string, SIZE, stdin);
</code>```

Why gets is unsafe, has been answered several times on SO. You can see this.

ContentLicense: CC BY-SA 3.0

Title: gets() problem in C

Body:
I wrote the following code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int const count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}

The problem is that the gcc gives me an error for the 'int const count': " increment of read-only variable ‘count’".

What seems to be wrong ?

Thank !

Body:
Try using fgets instead as:

fgets (string, SIZE, stdin);

Why gets is unsafe, has been answered several times on SO. You can see this.


问:
Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed
Context:

I've created what I called a softmodem-poetry machine, using two softmodems transmitters to transmit synchronously two different twitter streams at the same baud rate, creating an entanglement of quasi-gibberish/quasi-legible signals coming both from softmodem 1 and softmodem 2. These programs were running three months ago.

Problem:

When I try running these programs now, I have this Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed as soon as I connect to my socket.

Here's the relevant code I think:

```<code>twit.stream("statuses/filter", { track: randomTitle}, function(stream) {
      stream.on("data", function(data) {
        socket.emit("tweet", data.text);
        child.stdin.write(data.text);
      });
});`
</code>```

Here's the entire code: https://github.com/cyruslk/twitter_minimodem/blob/master/app.js

答: grant wrx access to log files, like chmod 777. </p>

Body:
Context:

I've created what I called a softmodem-poetry machine, using two softmodems transmitters to transmit synchronously two different twitter streams at the same baud rate, creating an entanglement of quasi-gibberish/quasi-legible signals coming both from softmodem 1 and softmodem 2. These programs were running three months ago.

Problem:

When I try running these programs now, I have this Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed as soon as I connect to my socket.

Here's the relevant code I think:

twit.stream("statuses/filter", { track: randomTitle}, function(stream) {
      stream.on("data", function(data) {
        socket.emit("tweet", data.text);
        child.stdin.write(data.text);
      });
});`

Here's the entire code: https://github.com/cyruslk/twitter_minimodem/blob/master/app.js


问:
Delete trailing newline in Atom for existing files
I have about 150 files that have an additional newline at the end which needs to be removed. I have set the 'Ensure trailing space' setting from the whitespace package in Atom, however it only works for new files. I need to apply it to existing files, since I cannot edit each file to delete the last line.
I have tried using a regex, but Atom selects all line breaks instead of just the last. \z doesn't seem to work, it simply selects all z characters.

Is there a regex that will help me select the very last newline in Atom? Or is there a way to apply the settings to existing files?

答:
You may use

```<code>(?:\r\n?|\n)(?![\s\S])
</code>```

Details

(?:\r\n?|\n) - a CRLF, CR or LF line break

(?![\s\S]) - not followed with any char.

Regex graph:

Body:
You may use

(?:\r\n?|\n)(?![\s\S])

Details

(?:\r\n?|\n) - a CRLF, CR or LF line break

(?![\s\S]) - not followed with any char.

Regex graph:


问:
Why does the Visual Studio editor show dots in blank spaces?
I have a strange bug in the Visual Studio text editor.
All my blank spaces are replaced by a "."

```<code>public class Person
{
  int age;
}
</code>```

looks like this

```<code>public..class..Person..........................
{..................
..int age;...................
}.....................
</code>```

I reset the settings to default. Didn't work.
I also re-installed VS2008. Still didn't work.
What's the error?

答: In Visual Studio 2019, this can also be configured in Tools -> Options -> General -> View whitespace

ContentLicense: CC BY-SA 2.5

Body:
I have a strange bug in the Visual Studio text editor.
All my blank spaces are replaced by a "."

public class Person
{
  int age;
}

looks like this

public..class..Person..........................
{..................
..int age;...................
}.....................

I reset the settings to default. Didn't work.
I also re-installed VS2008. Still didn't work.
What's the error?


问:
Stop Concatenating String to Dynamic Array when '#' is Entered by User in C
I am required to write a code where I constantly read a string input from the user and store it in the same variable. Each time an input is received the string will be concatenated onto a dynamic array (so the dynamic array grows bigger and bigger). It will stop reading the input from the user when the input contains '#'.

Expected inputs and outputs should be:

```<code>inputs              output
here I am #abc      hereIam
there you are #12   thereyouare
</code>```

Here's the code I've done:

```<code>#include<stdio.h>
#include<stdlib.h> // for malloc
#include<string.h> // for string funs

int main(void){
    char input1[256];
    char *combined = malloc(sizeof(char));
    int i = 0;

    while (input1[i]!= '#'){
    // read in the arrays
    printf("Enter a string (max 256 char) ");
    scanf("%256s",input1);

    // find out string lengths
    int len1;
    len1=strlen(input1);

     // allocate an array big enough for both
     combined=realloc(combined, sizeof(char)*(len1));

     //concatenate
     strcat(combined,input1);
    }

    // print
    printf("%s\n",combined);

    return 0;
}
</code>```

This code I have here have several problems:

I have no idea how to check if elements other than the first element of the user's input is '#' or not.

Even if the input contains '#', the output will still contain that input where '#' is in it.

Can anyone give me hints on how to solve this? Thank you!

答:
You may be making this harder on yourself that need be. While your heading a 2-column output adds a bit of formatting challenge, the easiest way to handle the input and classification (store-it/ignore-it) is with a character-oriented approach using getchar() or fgetc().

That way you simply continually read from the input and check if the character is a '#' or '\n', if so, stop storing characters in your buffer and just read and output the rest. After your loop completes, you simply need to nul-terminate your final buffer, compute the whitespace needed between the end of the original and the output of your buffer content, write the spaces and the final buffer and you are done. A short example would be:

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

#define MAXC 1024   /* if you need a constant, #define one (or more) */

int main (int argc, char **argv) {

    char buf[MAXC];
    int c, idx = 0, nc = 0, ws = 0;
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    puts ("inputs              output");    /* output headings */
    while ((c = fgetc(fp)) != EOF) {        /* read each char until EOF */
        if (c == '#' || c == '\n') {        /* if # or \n, end of storage */
            buf[idx] = 0;                   /* nul-terminate buffer at idx */
            putchar (c);                    /* output delim in orig string */
            nc++;                           /* increment no. of char  */
            while ((c = fgetc(fp)) != '\n' && c != EOF) {   /* print rest */
                putchar (c);
                nc++;
            }
            ws = 20 - nc;           /* compute amount of whitespace to col */
            while (ws--)            /* output that many spaces */
                putchar (' ');
            printf ("%s\n", buf);   /* print the stored buffer */
            idx = 0, nc = 0;        /* reset index and counter */
            continue;               /* go get next char */
        }
        else if (isalnum (c))       /* if alnum char add to buffer */
            buf[idx++] = c;
        putchar (c);        /* output all chars until # */
        nc++;               /* increment no. of chars */
    }
    buf[idx] = 0;           /* nul-terminate final line after loop */
    ws = 20 - nc;           /* set number of whitespace needed to 2nd col */
    while (ws--)            /* write that number of spaces */
        putchar (' ');
    printf ("%s\n", buf);   /* output string without whitespace in buf */

    if (fp != stdin)        /* close file if not reading stdin */
        fclose (fp);

    return 0;
}
</code>```

Example Input File

```<code>$ cat dat/pounddelim.txt
here I am #abc
there you are #12
</code>```

Example Use/Output

Running the program on your input produces the "Expected inputs and outputs":

```<code>$ ./bin/pounddelim <dat/pounddelim.txt
inputs              output
here I am #abc      hereIam
there you are #12   thereyouare
</code>```

Look things over and let me know if you have further questions.

Body:
I am required to write a code where I constantly read a string input from the user and store it in the same variable. Each time an input is received the string will be concatenated onto a dynamic array (so the dynamic array grows bigger and bigger). It will stop reading the input from the user when the input contains '#'.

Expected inputs and outputs should be:

inputs              output
here I am #abc      hereIam
there you are #12   thereyouare

Here's the code I've done:

#include<stdio.h>
#include<stdlib.h> // for malloc
#include<string.h> // for string funs

int main(void){
    char input1[256];
    char *combined = malloc(sizeof(char));
    int i = 0;

    while (input1[i]!= '#'){
    // read in the arrays
    printf("Enter a string (max 256 char) ");
    scanf("%256s",input1);

    // find out string lengths
    int len1;
    len1=strlen(input1);

     // allocate an array big enough for both
     combined=realloc(combined, sizeof(char)*(len1));

     //concatenate
     strcat(combined,input1);
    }

    // print
    printf("%s\n",combined);

    return 0;
}

This code I have here have several problems:

I have no idea how to check if elements other than the first element of the user's input is '#' or not.

Even if the input contains '#', the output will still contain that input where '#' is in it.

Can anyone give me hints on how to solve this? Thank you!

Body:
You may be making this harder on yourself that need be. While your heading a 2-column output adds a bit of formatting challenge, the easiest way to handle the input and classification (store-it/ignore-it) is with a character-oriented approach using getchar() or fgetc().

That way you simply continually read from the input and check if the character is a '#' or '\n', if so, stop storing characters in your buffer and just read and output the rest. After your loop completes, you simply need to nul-terminate your final buffer, compute the whitespace needed between the end of the original and the output of your buffer content, write the spaces and the final buffer and you are done. A short example would be:

#include <stdio.h>
#include <ctype.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */

int main (int argc, char **argv) {

    char buf[MAXC];
    int c, idx = 0, nc = 0, ws = 0;
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    puts ("inputs              output");    /* output headings */
    while ((c = fgetc(fp)) != EOF) {        /* read each char until EOF */
        if (c == '#' || c == '\n') {        /* if # or \n, end of storage */
            buf[idx] = 0;                   /* nul-terminate buffer at idx */
            putchar (c);                    /* output delim in orig string */
            nc++;                           /* increment no. of char  */
            while ((c = fgetc(fp)) != '\n' && c != EOF) {   /* print rest */
                putchar (c);
                nc++;
            }
            ws = 20 - nc;           /* compute amount of whitespace to col */
            while (ws--)            /* output that many spaces */
                putchar (' ');
            printf ("%s\n", buf);   /* print the stored buffer */
            idx = 0, nc = 0;        /* reset index and counter */
            continue;               /* go get next char */
        }
        else if (isalnum (c))       /* if alnum char add to buffer */
            buf[idx++] = c;
        putchar (c);        /* output all chars until # */
        nc++;               /* increment no. of chars */
    }
    buf[idx] = 0;           /* nul-terminate final line after loop */
    ws = 20 - nc;           /* set number of whitespace needed to 2nd col */
    while (ws--)            /* write that number of spaces */
        putchar (' ');
    printf ("%s\n", buf);   /* output string without whitespace in buf */

    if (fp != stdin)        /* close file if not reading stdin */
        fclose (fp);

    return 0;
}

Example Input File

$ cat dat/pounddelim.txt
here I am #abc
there you are #12

Example Use/Output

Running the program on your input produces the "Expected inputs and outputs":

$ ./bin/pounddelim <dat/pounddelim.txt
inputs              output
here I am #abc      hereIam
there you are #12   thereyouare

Look things over and let me know if you have further questions.


问:
How to select the rows of a dataframe where two variables have value
So I have a dataframe: df1. And I want to select the rows based on the value of two variables != NULL.

For example:

```<code>Variable1    Variable2

NULL         5

6            NULL

NULL         NULL

3            6

1            9
</code>```

Result:

```<code>Variable1   Variable2

3            6

1            9
</code>```

答:
```<code>df1 <- data.frame(Variable1 = c("NULL", 6, "NULL", 3, 1), Variable2 = c(5, "NULL", "NULL", 6, 9))
df1 <- df1[df1$Variable1 != "NULL" & df1$Variable2 != "NULL",]
</code>```

Body:
So I have a dataframe: df1. And I want to select the rows based on the value of two variables != NULL.

For example:

Variable1    Variable2

NULL         5

6            NULL

NULL         NULL

3            6

1            9

Result:

Variable1   Variable2

3            6

1            9


问:
Split (explode) pandas dataframe string entry to separate rows
I have a pandas dataframe in which one column of text strings contains comma-separated values. I want to split each CSV field and create a new row per entry (assume that CSV are clean and need only be split on ','). For example, a should become b:

```<code>In [7]: a
Out[7]:
    var1  var2
0  a,b,c     1
1  d,e,f     2

In [8]: b
Out[8]:
  var1  var2
0    a     1
1    b     1
2    c     1
3    d     2
4    e     2
5    f     2
</code>```

So far, I have tried various simple functions, but the .apply method seems to only accept one row as return value when it is used on an axis, and I can't get .transform to work. Any suggestions would be much appreciated!

Example data:

```<code>from pandas import DataFrame
import numpy as np
a = DataFrame([{'var1': 'a,b,c', 'var2': 1},
               {'var1': 'd,e,f', 'var2': 2}])
b = DataFrame([{'var1': 'a', 'var2': 1},
               {'var1': 'b', 'var2': 1},
               {'var1': 'c', 'var2': 1},
               {'var1': 'd', 'var2': 2},
               {'var1': 'e', 'var2': 2},
               {'var1': 'f', 'var2': 2}])
</code>```

I know this won't work because we lose DataFrame meta-data by going through numpy, but it should give you a sense of what I tried to do:

```<code>def fun(row):
    letters = row['var1']
    letters = letters.split(',')
    out = np.array([row] * len(letters))
    out['var1'] = letters
a['idx'] = range(a.shape[0])
z = a.groupby('idx')
z.transform(fun)
</code>```

答:
upgraded MaxU's answer with MultiIndex support</p>

```<code>def explode(df, lst_cols, fill_value='', preserve_index=False):
    """
    usage:
        In [134]: df
        Out[134]:
           aaa  myid        num          text
        0   10     1  [1, 2, 3]  [aa, bb, cc]
        1   11     2         []            []
        2   12     3     [1, 2]      [cc, dd]
        3   13     4         []            []

        In [135]: explode(df, ['num','text'], fill_value='')
        Out[135]:
           aaa  myid num text
        0   10     1   1   aa
        1   10     1   2   bb
        2   10     1   3   cc
        3   11     2
        4   12     3   1   cc
        5   12     3   2   dd
        6   13     4
    """
    # make sure `lst_cols` is list-alike
    if (lst_cols is not None
        and len(lst_cols) > 0
        and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))):
        lst_cols = [lst_cols]
    # all columns except `lst_cols`
    idx_cols = df.columns.difference(lst_cols)
    # calculate lengths of lists
    lens = df[lst_cols[0]].str.len()
    # preserve original index values
    idx = np.repeat(df.index.values, lens)
    res = (pd.DataFrame({
                col:np.repeat(df[col].values, lens)
                for col in idx_cols},
                index=idx)
             .assign(**{col:np.concatenate(df.loc[lens>0, col].values)
                            for col in lst_cols}))
    # append those rows that have empty lists
    if (lens == 0).any():
        # at least one list in cells is empty
        res = (res.append(df.loc[lens==0, idx_cols], sort=False)
                  .fillna(fill_value))
    # revert the original index order
    res = res.sort_index()
    # reset index if requested
    if not preserve_index:
        res = res.reset_index(drop=True)

    # if original index is MultiIndex build the dataframe from the multiindex
    # create "exploded" DF
    if isinstance(df.index, pd.MultiIndex):
        res = res.reindex(
            index=pd.MultiIndex.from_tuples(
                res.index,
                names=['number', 'color']
            )
    )
    return res
</code>```

Body:
I have a pandas dataframe in which one column of text strings contains comma-separated values. I want to split each CSV field and create a new row per entry (assume that CSV are clean and need only be split on ','). For example, a should become b:

In [7]: a
Out[7]:
    var1  var2
0  a,b,c     1
1  d,e,f     2

In [8]: b
Out[8]:
  var1  var2
0    a     1
1    b     1
2    c     1
3    d     2
4    e     2
5    f     2

So far, I have tried various simple functions, but the .apply method seems to only accept one row as return value when it is used on an axis, and I can't get .transform to work. Any suggestions would be much appreciated!

Example data:

from pandas import DataFrame
import numpy as np
a = DataFrame([{'var1': 'a,b,c', 'var2': 1},
               {'var1': 'd,e,f', 'var2': 2}])
b = DataFrame([{'var1': 'a', 'var2': 1},
               {'var1': 'b', 'var2': 1},
               {'var1': 'c', 'var2': 1},
               {'var1': 'd', 'var2': 2},
               {'var1': 'e', 'var2': 2},
               {'var1': 'f', 'var2': 2}])

I know this won't work because we lose DataFrame meta-data by going through numpy, but it should give you a sense of what I tried to do:

def fun(row):
    letters = row['var1']
    letters = letters.split(',')
    out = np.array([row] * len(letters))
    out['var1'] = letters
a['idx'] = range(a.shape[0])
z = a.groupby('idx')
z.transform(fun)

Body:
upgraded MaxU's answer with MultiIndex support

def explode(df, lst_cols, fill_value='', preserve_index=False):
    """
    usage:
        In [134]: df
        Out[134]:
           aaa  myid        num          text
        0   10     1  [1, 2, 3]  [aa, bb, cc]
        1   11     2         []            []
        2   12     3     [1, 2]      [cc, dd]
        3   13     4         []            []

        In [135]: explode(df, ['num','text'], fill_value='')
        Out[135]:
           aaa  myid num text
        0   10     1   1   aa
        1   10     1   2   bb
        2   10     1   3   cc
        3   11     2
        4   12     3   1   cc
        5   12     3   2   dd
        6   13     4
    """
    # make sure `lst_cols` is list-alike
    if (lst_cols is not None
        and len(lst_cols) > 0
        and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))):
        lst_cols = [lst_cols]
    # all columns except `lst_cols`
    idx_cols = df.columns.difference(lst_cols)
    # calculate lengths of lists
    lens = df[lst_cols[0]].str.len()
    # preserve original index values
    idx = np.repeat(df.index.values, lens)
    res = (pd.DataFrame({
                col:np.repeat(df[col].values, lens)
                for col in idx_cols},
                index=idx)
             .assign(**{col:np.concatenate(df.loc[lens>0, col].values)
                            for col in lst_cols}))
    # append those rows that have empty lists
    if (lens == 0).any():
        # at least one list in cells is empty
        res = (res.append(df.loc[lens==0, idx_cols], sort=False)
                  .fillna(fill_value))
    # revert the original index order
    res = res.sort_index()
    # reset index if requested
    if not preserve_index:
        res = res.reset_index(drop=True)

    # if original index is MultiIndex build the dataframe from the multiindex
    # create "exploded" DF
    if isinstance(df.index, pd.MultiIndex):
        res = res.reindex(
            index=pd.MultiIndex.from_tuples(
                res.index,
                names=['number', 'color']
            )
    )
    return res


问:
Airflow backfill stops if any task fails
I am using airflow cli's backfill command to manually run some backfill jobs.

```<code> airflow backfill mydag -i -s 2018-01-11T16-00-00 -e 2018-01-31T23-00-00 --reset_dagruns --rerun_failed_tasks
</code>```

The dag interval is hourly and it has around 40 tasks. Hence this kind of backfill job takes more than a day to finish. I need it to run without supervision. I noticed however, that even if one task fails at one of the runs in the backfill interval, the entire backfill job stops with the following exception and I have to restart it manually again.

```<code>    Traceback (most recent call last):
      File "/home/ubuntu/airflow/bin/airflow", line 4, in <module>
        __import__('pkg_resources').run_script('apache-airflow==1.10.0', 'airflow')
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/pkg_resources/__init__.py"
    , line 719, in run_script
        self.require(requires)[0].run_script(script_name, ns)
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/pkg_resources/__init__.py", line 1504, in run_script
        exec(code, namespace, namespace)
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.
    5.egg/EGG-INFO/scripts/airflow", line 32, in <module>
        args.func(args)
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.5.egg/airflow/utils/cli.py", line 74, in wrapper
        return f(*args, **kwargs)
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.
    5.egg/airflow/bin/cli.py", line 217, in backfill
        rerun_failed_tasks=args.rerun_failed_tasks,
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.5.egg/airflow/models.py", line 4105, in run
        job.run()
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.
    5.egg/airflow/jobs.py", line 202, in run
        self._execute()
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.5.egg/airflow/utils/db.py", line 74, in wrapper
        return func(*args, **kwargs)
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.
    5.egg/airflow/jobs.py", line 2533, in _execute

 airflow.exceptions.AirflowException:

Some task instances failed:
{('mydag', 'a_task', datetime.datetime(2018, 1, 30, 17, 5, tzinfo=psy
copg2.tz.FixedOffsetTimezone(offset=0, name=None)))}
</code>```

The task instances do not depend on their previous instances, therefore I don't mind if one or two tasks fail. I need the job to continue.

I could not find any option in the documentation of backfill which would allow me to specify this behaviour.

Is there a way to achieve what I am looking for?

答:
Have experienced the same problem with the backfill command.

Tried the --donot_pickle option and depends_on_past set to False without success.

Possible workaround: Set a start date and catchup=True for the DAG, and unpause it in the web gui. This worked like a backfill.

I could not get backfill CLI command to keep running if more than 1 DAG run was marked as failed.

Body:
I am using airflow cli's backfill command to manually run some backfill jobs.

 airflow backfill mydag -i -s 2018-01-11T16-00-00 -e 2018-01-31T23-00-00 --reset_dagruns --rerun_failed_tasks

The dag interval is hourly and it has around 40 tasks. Hence this kind of backfill job takes more than a day to finish. I need it to run without supervision. I noticed however, that even if one task fails at one of the runs in the backfill interval, the entire backfill job stops with the following exception and I have to restart it manually again.

    Traceback (most recent call last):
      File "/home/ubuntu/airflow/bin/airflow", line 4, in <module>
        __import__('pkg_resources').run_script('apache-airflow==1.10.0', 'airflow')
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/pkg_resources/__init__.py"
    , line 719, in run_script
        self.require(requires)[0].run_script(script_name, ns)
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/pkg_resources/__init__.py", line 1504, in run_script
        exec(code, namespace, namespace)
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.
    5.egg/EGG-INFO/scripts/airflow", line 32, in <module>
        args.func(args)
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.5.egg/airflow/utils/cli.py", line 74, in wrapper
        return f(*args, **kwargs)
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.
    5.egg/airflow/bin/cli.py", line 217, in backfill
        rerun_failed_tasks=args.rerun_failed_tasks,
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.5.egg/airflow/models.py", line 4105, in run
        job.run()
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.
    5.egg/airflow/jobs.py", line 202, in run
        self._execute()
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.5.egg/airflow/utils/db.py", line 74, in wrapper
        return func(*args, **kwargs)
      File "/home/ubuntu/airflow/lib/python3.5/site-packages/apache_airflow-1.10.0-py3.
    5.egg/airflow/jobs.py", line 2533, in _execute

 airflow.exceptions.AirflowException:

Some task instances failed:
{('mydag', 'a_task', datetime.datetime(2018, 1, 30, 17, 5, tzinfo=psy
copg2.tz.FixedOffsetTimezone(offset=0, name=None)))}

The task instances do not depend on their previous instances, therefore I don't mind if one or two tasks fail. I need the job to continue.

I could not find any option in the documentation of backfill which would allow me to specify this behaviour.

Is there a way to achieve what I am looking for?


问:
How could I implement image channel drop with the python lib of pillow
I need to randomly zero out 0, 1 or 2 channel of a pillow image. That means I need to randomly set 0, 1 or 2 channels of an image to 0.

How could I do that with pil?

答:
Here's an easy, native PIL way of doing it by multiplying by a transform. I set the default transform so the maths looks like this:

```<code>newRed   = 1*oldRed  +  0*oldGreen  +  0*oldBlue  + constant
newGreen = 0*oldRed  +  1*OldGreen  +  0*OldBlue  + constant
newBlue  = 0*oldRed  +  0*OldGreen  +  1*OldBlue  + constant
</code>```

Then I just change the 1 to 0 where I want a channel zeroed out.

```<code>#!/usr/bin/env python3

from PIL import Image

# Open image
im = Image.open('input.png').convert("RGB")

# Pre-set R, G and B multipliers to 1
Rmult, Gmult, Bmult = 1, 1, 1

# Select one (or more) channels to zero out, I choose B channel here
Bmult=0

# Make transform matrix
Matrix = ( Rmult, 0, 0, 0,
           0, Gmult, 0, 0,
           0, 0, Bmult, 0)

# Apply transform and save
im = im.convert("RGB", Matrix)
im.save('result.png')
</code>```

So, if you start with this:

and you set the Blue multiplier (Bmult) to zero, you'll get:

If you zero Red and Blue with:

```<code>Rmult = Bmult = 0
</code>```

you'll get:

Body:
Here's an easy, native PIL way of doing it by multiplying by a transform. I set the default transform so the maths looks like this:

newRed   = 1*oldRed  +  0*oldGreen  +  0*oldBlue  + constant
newGreen = 0*oldRed  +  1*OldGreen  +  0*OldBlue  + constant
newBlue  = 0*oldRed  +  0*OldGreen  +  1*OldBlue  + constant

Then I just change the 1 to 0 where I want a channel zeroed out.

#!/usr/bin/env python3

from PIL import Image

# Open image
im = Image.open('input.png').convert("RGB")

# Pre-set R, G and B multipliers to 1
Rmult, Gmult, Bmult = 1, 1, 1

# Select one (or more) channels to zero out, I choose B channel here
Bmult=0

# Make transform matrix
Matrix = ( Rmult, 0, 0, 0,
           0, Gmult, 0, 0,
           0, 0, Bmult, 0)

# Apply transform and save
im = im.convert("RGB", Matrix)
im.save('result.png')

So, if you start with this:

and you set the Blue multiplier (Bmult) to zero, you'll get:

If you zero Red and Blue with:

Rmult = Bmult = 0

you'll get:


问:
TreeMap put 100 elements(1MB each) and Heap have only 80 MB memory, behavior in this case?
Heap space have only 80 MB memory available. We need to put 100 elements(of 1MB each) in TreeMap.

What is the behavior in this case when 80th element is put into map?
How will garbage collection work in this scenario?
what is the effective way to handle such scenario?

答:
This is a bit un-clear, since you put Key and Value to a Map, not individual elements. I'll assume your Key + Value combined will give you 1MB.

If they indeed have 1MB each - your memory will blow up a lot faster then even 50 elements that you put into your TreeMap, since each object has 2 headers (12 bytes combined on typical VM's); there is padding involved + each Key + Value is wrapped into an Entry internally that add some overhead too.

GC is not going to be able to help you much, you have limited memory to begin with; your VM is blow up with an OutOfMemory. GC will be triggered when you are getting close to the limits (this heavily depends on the GC used and the input parameters), but since there will be not much to clean - it will basically not do much, if anything at all.


答:
If I get you right, you want to have all the integers in a numpy array padded with zeros. This is how I would do this.

```<code># open and read file
file = open(data, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
maze = np.zeros((rows, cols),dtype=str)

for index,line in enumerate(lines):
    for i in range(0,len(line)-1):
        maze[index][i]= line[i]

return maze
</code>```

this will produce this output:

```<code>[['*' '*' '*' ... '*' '*' '*']
 ['*' 'A' ' ' ... ' ' ' ' '*']
 ['*' '*' '*' ... '*' ' ' '*']
 ...
 ['*' ' ' '*' ... '*' ' ' '*']
 ['*' ' ' '*' ... ' ' 'B' '*']
 ['*' '*' '*' ... '*' '*' '']]
</code>```

Title: How to add line after line to a numpy 2d array in python?

Body:
I need to add line after line to a 2d array in python using numpy.

def read_file(file):
    # open and read file
    file = open(file, "r")
    lines = file.readlines()
    file.close()
    # row and col count
    rows = len(lines)
    cols = len(lines[0]) - 1
    maze = np.zeros((rows, cols), dtype=int)
    for line in lines:
        maze = np.append(maze, line)
    return maze

First I read a file and get the lines from that one. Then I am creating a 2d array using the count of lines and columns (-1 because of '\n' at the end). Then I want to append them to the array, but it looks really weird:

['0' '0' '0' ...
'* * * ******* *** * * * * *** ******* * * ***** *** * ***** *** *\n'
'* *           *   *     *     *       *       *       *        B*\n'
'*****************************************************************\n']
['0' '0' '0' ...
'* * * ******* *** * * * * *** ******* * * ***** *** * ***** *** *\n'
'* *           *   *     *     *       *       *       *        B*\n'
'*****************************************************************\n']

What am I doing wrong? Where is the error?

Expected output is a 2d array (17,65).
Something like:
[[0,0,0,0,0...0,0], [0,0,0,0...,0,0]...]
etc.

I want to generate an array from this file:

*****************************************************************
*A  *         *         *     *                   *             *
*** * ***** * ******* *** *** * *************** * *********** * *
*   *     * *       *       * * *     *   *     *   *       * * *
* ******* * ******* ******* * * * ***** * * ******* * ***** *** *
*       * *   *           * * *   *   * * * *   *   * *   *     *
* ***** * *** *********** * * * *** * * * * * *** *** *** ***** *
* *   * *   *     *       * *   *   *   *   *   * *     *   *   *
*** * * *** ***** ******* ******* *** ******* * * *** * * *** ***
*   *     *   * *   *   *   *   * *   *     * * *   * * *   *   *
* ***** ***** * *** * * *** * * * ***** *** * * *** * * *** *** *
*   *   *     *   * * *   *   *   *     *   * *   * * *   *   * *
* * ***** ***** * * * *** * ******* ********* * * * ***** * * * *
* * *     *     * * * * * * *       *   *     * * * *     * * * *
* * * ******* *** * * * * *** ******* * * ***** *** * ***** *** *
* *           *   *     *     *       *       *       *        B*
*****************************************************************

every line is in brackets [] and after a new line a new bracket beginns.

Body:
If I get you right, you want to have all the integers in a numpy array padded with zeros. This is how I would do this.

# open and read file
file = open(data, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
maze = np.zeros((rows, cols),dtype=str)

for index,line in enumerate(lines):
    for i in range(0,len(line)-1):
        maze[index][i]= line[i]

return maze

this will produce this output:

[['*' '*' '*' ... '*' '*' '*']
 ['*' 'A' ' ' ... ' ' ' ' '*']
 ['*' '*' '*' ... '*' ' ' '*']
 ...
 ['*' ' ' '*' ... '*' ' ' '*']
 ['*' ' ' '*' ... ' ' 'B' '*']
 ['*' '*' '*' ... '*' '*' '']]


问:
How can I order a dictionary list by one specified key with some values being None?
There is a list like

```<code>l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]
</code>```

And I want to order it by one specified key, n for example.
Besides, some value of the key may be None, and I want to leave them at behind

Here's my trial

```<code>l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]

from functools import partial
def order(key, item):
    if item[key]:
        return item[key]
    else:
        return 0
order_key = "n"
r = sorted(l, key=partial(order, order_key), reverse=True)
print(r)
</code>```

Is there a better way to make it happen?

答:
use a key function that returns a tuple for a double criteria:

```<code>l = [ {"n":1, "m":3}, {"n":None, "m":1}, {"n":3, "m":None}, {"n":None, "m":0}]

result = sorted(l,key = lambda d : (d["m"] is None,d["m"] or 0))
</code>```

result:

```<code>>>> result
[{'m': 0, 'n': None},
 {'m': 1, 'n': None},
 {'m': 3, 'n': 1},
 {'m': None, 'n': 3}]
</code>```

Let's clarify how and why it works:

(d["m"] is None,d["m"] or 0) is a tuple:

True if the value is None for the first element, which guarantees that None entries are last (negate for the reverse effect)

the other one is the tiebreaker, with the or trick to convert None to 0 so it's comparable with other integers without errors (although here it is not needed since first boolean stops the tuple comparison so we could write (d["m"] is None,d["m"]))

Body:
There is a list like

l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]

And I want to order it by one specified key, n for example.
Besides, some value of the key may be None, and I want to leave them at behind

Here's my trial

l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]

from functools import partial
def order(key, item):
    if item[key]:
        return item[key]
    else:
        return 0
order_key = "n"
r = sorted(l, key=partial(order, order_key), reverse=True)
print(r)

Is there a better way to make it happen?

Body:
use a key function that returns a tuple for a double criteria:

l = [ {"n":1, "m":3}, {"n":None, "m":1}, {"n":3, "m":None}, {"n":None, "m":0}]

result = sorted(l,key = lambda d : (d["m"] is None,d["m"] or 0))

result:

>>> result
[{'m': 0, 'n': None},
 {'m': 1, 'n': None},
 {'m': 3, 'n': 1},
 {'m': None, 'n': 3}]

Let's clarify how and why it works:

(d["m"] is None,d["m"] or 0) is a tuple:

True if the value is None for the first element, which guarantees that None entries are last (negate for the reverse effect)

the other one is the tiebreaker, with the or trick to convert None to 0 so it's comparable with other integers without errors (although here it is not needed since first boolean stops the tuple comparison so we could write (d["m"] is None,d["m"]))


问:
how to use session ids for authentication purpose
I am using just session variables $_SESSION['user_id'] and $_SESSION['passwd'] to store the id and password of user once when he logs in.

I am just checking these two variables with database each time the user moves to a new php page for authentication. Actually I didnt know about session_id() .

I dont think what i am doing for authentication is the right way. I feel that there is something to be done with session_id for security stuff.

and one more doubt- can these session variables be easily hacked when I use the session variables by the way i mentioned

What should I do?

答:
Sure.

$_SESSION['user_id'] is only variable you need.

```<code>if (empty($_SESSION['user_id'])) {
   die("access denied");
}
</code>```

to check if user is authenticated.

Body:
Sure.

$_SESSION['user_id'] is only variable you need.

if (empty($_SESSION['user_id'])) {
   die("access denied");
}

to check if user is authenticated.


问:
simple python port scanner
Can somebody give python 3 based port scanner for a particular ip. For example program will ask ip to be scanned and scan the particular range of open ports in that ip.</p>

答: Use nmap library which is already in python.</p>

Title: simple python port scanner


问:
Replacement for DirectPropertyAccessor?
I am upgrading a Spring 4.3.2 project to Spring 5.1.5.
One of my test cases started failing with the error.

ClassNotFoundException: org.hibernate.property.DirectPropertyAccessor

Which makes sense since it has been deprecated in Hibernate 5.x which is the lowest compatible Hibernate version for Spring 5.x. I am consuming it in my hbm.xml as below:

```<code><class name="Notification"
       table="T_NOTIFICATION"
       lazy="false">

    <id name="id"
        type="integer"
        column="ID"
        unsaved-value="null"
        access="property">
        <generator class="identity"/>
    </id>

    <!-- A versioned entity. -->
    <version name="version"
             column="VERSION"
             access="org.hibernate.property.DirectPropertyAccessor"/>
</code>```

What should I replace the access field with, to maintain the same behaviour?

答:
Using access=<class-name> you should only be using that if you have your own custom class you want to use. If you want to use direct field access instead of properties use access="field" instead of what you have now. See also the Hibernate Reference Guide.

Internally your current version will use the DirectPropertyAccessor when upgrading Hibernate it will automatically adapt to the newly introduced other class to use. Now that burden lies with hibernate instead of you having to know the internal API of hibernate.

Title: Replacement for DirectPropertyAccessor?

Body:
I am upgrading a Spring 4.3.2 project to Spring 5.1.5.
One of my test cases started failing with the error.

ClassNotFoundException: org.hibernate.property.DirectPropertyAccessor

Which makes sense since it has been deprecated in Hibernate 5.x which is the lowest compatible Hibernate version for Spring 5.x. I am consuming it in my hbm.xml as below:

<class name="Notification"
       table="T_NOTIFICATION"
       lazy="false">

    <id name="id"
        type="integer"
        column="ID"
        unsaved-value="null"
        access="property">
        <generator class="identity"/>
    </id>

    <version name="version"
             column="VERSION"
             access="org.hibernate.property.DirectPropertyAccessor"/>

What should I replace the access field with, to maintain the same behaviour?


问:
d3.js tree - How to set Y depth of a specific level?
In d3.js tree code, there is the following which sets the y depth for all child levels/nodes:

```<code>  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 220;
  });
</code>```

How can I set the Y depth of a specific level in the hierarchy, e.g. the 3rd level?

答:
I guess you refer to this code

Simple example for the third level.

```<code>nodes.forEach(function(d) {
 (d.depth === 1) ? d.y = d.depth * 100: d.y = d.depth * 300;
});
</code>```

It display this https://jsfiddle.net/0rv8z276/

You can use a switch to set for different level, or maybe use an array or a hashmap with the key associated to the level and depth as the value.

Body:
In d3.js tree code, there is the following which sets the y depth for all child levels/nodes:

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 220;
  });

How can I set the Y depth of a specific level in the hierarchy, e.g. the 3rd level?

Body:
I guess you refer to this code

Simple example for the third level.

nodes.forEach(function(d) {
 (d.depth === 1) ? d.y = d.depth * 100: d.y = d.depth * 300;
});

It display this https://jsfiddle.net/0rv8z276/

You can use a switch to set for different level, or maybe use an array or a hashmap with the key associated to the level and depth as the value.


问:
Build and Deploy pipelines with same version
I would like to specify the (SemVer) version number during a (not selfhosted) DevOps release, so that DLLs will have this version number embedded in them, and I can create a release to GitHub + NuGet with the same version.

However, I'm struggling with how to accomplish this with as much automation as possible.

I know I can use the /p:Version=x.y.z during build to set a specific version, but if I build one more time I shouldn't use the same version number again, which could be fixed by appending +buildnumber to the version. This build number is not something I neccessarilly would want in the actual release, though.

So, how should I best handle version numbers during build and deploy, without having to edit some variables every time?

答:
how should I best handle version numbers during build and deploy, without having to edit some variables every time?

If you want to increment the version in build/release automatically, the buildnumber should be a good choice.

In generally, we defined the major.minor.patch in Variables or some config file, and use it with BuildNumber in the Build number format option:

Then, we could use the option use the build number as nuget version when we pack the nuget package:

For the release, we could use the parameter $(Build.buildnumber) to get the build number and set it as release version:

Now, we could handle version numbers with same version during build and release, without having to edit some variables every time.

Hope this helps.