问:
what is visual state in wpf? and anyone knows how to start understand and use that?
what is visual state in wpf? and anyone knows how to start understand and use that?

maybe like a complete tutorial, because i never touch visual state before. or just a simple example code

thx yeah

答:
Visual state is used to change the appearance of wpf control in different states of the control , for example take the case of a radio button, it may appear differently while focused , while clicked or while disabled ,

visual states falls under different visual state groups like

CommonStates

CheckStates

FocusStates

mostly used visual states are :

MouseOver

Pressed

Disabled

Checked

Unchecked

Indeterminate

Focused

Unfocused

PointerFocused

An example of visualstate used in a radio button style is given

```<code><Style TargetType="RadioButton">
    <Setter Property="Background"
            Value="Transparent" />
    <Setter Property="Foreground"
            Value="{DynamicResource BlackBrush}" />
    <Setter Property="Padding"
            Value="1,4,0,0" />
    <Setter Property="HorizontalAlignment"
            Value="Stretch" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="RadioButton">
                <Border Background="{TemplateBinding Background}">
                    <vsm:VisualStateManager.VisualStateGroups>
                        <vsm:VisualStateGroup x:Name="CommonStates">
                            <vsm:VisualState x:Name="Normal" >
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundEllipse"
                                                                   Storyboard.TargetProperty="Stroke">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{DynamicResource HpGray13Brush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="MouseOver">
                                <Storyboard>

                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundEllipse"
                                                                   Storyboard.TargetProperty="Stroke">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{DynamicResource HpGray15Brush}" />
                                    </ObjectAnimationUsingKeyFrames>

                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="Pressed">
                                <Storyboard>

                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundEllipse"
                                                                   Storyboard.TargetProperty="Stroke">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{DynamicResource GreenBrush}" />
                                    </ObjectAnimationUsingKeyFrames>

                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="Disabled">
                                <Storyboard>

                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundEllipse"
                                                                   Storyboard.TargetProperty="Stroke">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{DynamicResource HpGray1Brush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="CheckGlyph"
                                                                   Storyboard.TargetProperty="Fill">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{DynamicResource Gray1Brush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </vsm:VisualState>
                        </vsm:VisualStateGroup>
</code>```

Body:
Visual state is used to change the appearance of wpf control in different states of the control , for example take the case of a radio button, it may appear differently while focused , while clicked or while disabled ,

visual states falls under different visual state groups like

CommonStates

CheckStates

FocusStates

mostly used visual states are :

MouseOver

Pressed

Disabled

Checked

Unchecked

Indeterminate

Focused

Unfocused

PointerFocused

An example of visualstate used in a radio button style is given

<Style TargetType="RadioButton">
    <Setter Property="Background"
            Value="Transparent" />
    <Setter Property="Foreground"
            Value="{DynamicResource BlackBrush}" />
    <Setter Property="Padding"
            Value="1,4,0,0" />
    <Setter Property="HorizontalAlignment"
            Value="Stretch" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="RadioButton">
                <Border Background="{TemplateBinding Background}">
                    <vsm:VisualStateManager.VisualStateGroups>
                        <vsm:VisualStateGroup x:Name="CommonStates">
                            <vsm:VisualState x:Name="Normal" >
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundEllipse"
                                                                   Storyboard.TargetProperty="Stroke">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{DynamicResource HpGray13Brush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="MouseOver">
                                <Storyboard>

                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundEllipse"
                                                                   Storyboard.TargetProperty="Stroke">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{DynamicResource HpGray15Brush}" />
                                    </ObjectAnimationUsingKeyFrames>

                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="Pressed">
                                <Storyboard>

                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundEllipse"
                                                                   Storyboard.TargetProperty="Stroke">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{DynamicResource GreenBrush}" />
                                    </ObjectAnimationUsingKeyFrames>

                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="Disabled">
                                <Storyboard>

                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundEllipse"
                                                                   Storyboard.TargetProperty="Stroke">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{DynamicResource HpGray1Brush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="CheckGlyph"
                                                                   Storyboard.TargetProperty="Fill">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{DynamicResource Gray1Brush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </vsm:VisualState>
                        </vsm:VisualStateGroup>


来源: stackexchange

问:
How to keep fps rate constant in cocos2d
I have 3 question.

How to keep fps rate constant(almost) in cocos2d.When lots of CCSprite created and removed within a small interval like (5-8) per second is it possible to keep frame rate lmost constant??

Is [self removeChild:sprite cleanup:YES] is enough or I should also use

```<code>  CCTexture2D *texture = [sprite texture]; [[CCTextureCache sharedTextureCache] removeTexture: texture];
</code>```

The following Part of code is responsible for my frame drop.How to accomplish same task in better way?

```<code>id fadeout = [CCFadeOut actionWithDuration:1.4f];

id call = [CCCallFunc actionWithTarget:self
selector:@selector(RemoveSmashedSprite:)];

CCSequence* sequence= [CCSequence
actions:fadeout, call, nil];

[smash runAction:sequence];
</code>```

... and...

```<code>> -(void)RemoveSmashedSprite:(id)sender
{

    CCSprite *sp = (CCSprite *)sender;

    [self removeChild:sp cleanup:YES];

}
</code>```

This is called 5-8 times per second. So the frame rate goes down. Can any one help me?

答:
You shouldn't remove textures if you're going to reuse them in the short term. It would only benefit memory while having a great drawback in performance.

To maintain a constant frame rate you could try reusing the sprites instead of creating and removing them. Instead of calling removeChild you could set visible = NO and add it to an array of unused sprites. Then when you need a new of these sprites you check if there is any in that unused array and only create a new one if it's empty. This way you would minimize the amount of sprites created and destroyed.

ContentLicense: CC BY-SA 3.0

Body:
I have 3 question.

How to keep fps rate constant(almost) in cocos2d.When lots of CCSprite created and removed within a small interval like (5-8) per second is it possible to keep frame rate lmost constant??

Is [self removeChild:sprite cleanup:YES] is enough or I should also use

  CCTexture2D *texture = [sprite texture]; [[CCTextureCache sharedTextureCache] removeTexture: texture];

The following Part of code is responsible for my frame drop.How to accomplish same task in better way?

id fadeout = [CCFadeOut actionWithDuration:1.4f];

id call = [CCCallFunc actionWithTarget:self
selector:@selector(RemoveSmashedSprite:)];

CCSequence* sequence= [CCSequence
actions:fadeout, call, nil];

[smash runAction:sequence];

... and...

> -(void)RemoveSmashedSprite:(id)sender
{

    CCSprite *sp = (CCSprite *)sender;

    [self removeChild:sp cleanup:YES];

}

This is called 5-8 times per second. So the frame rate goes down. Can any one help me?

ContentLicense: CC BY-SA 2.5


问:
Drawing Beans from a bag
I have a program that draws beans from a bag and removes them on the following conditions. However my results don't seem to correlate at all, it seems as if the beans are not being remembered.

```<code>public class Prog477h {

public static void main(String[] args) {
    ArrayList<Integer> beans = new ArrayList<Integer>(); //make arrayList and add first 10 random beans
    Random addrand = new Random();
    for (int i = 0; i < 10; i++) {
        int bean = addrand.nextInt(2);
        beans.add(bean);
    }
    //print title
    System.out.println("Beans\tBlack\tWhite\tLast");
    for (int i = 0; i <= 50; i++) { //start for loop for 50 iterations
        int whites = countWhite(beans); //count the initial white
        int blacks = countBlack(beans); //count the initial black
        String last = getLast(beans); //get the last
        System.out.println(beans.size() + "\t" + blacks + "\t" + whites + "\t" + last + "\t"); //print row

        //draw two beans and remove them
        Random drawRand = new Random();
        int draw1 = drawRand.nextInt(beans.size());
        int beanDrawn1 = beans.get(draw1);
        beans.remove(beanDrawn1);
        int draw2 = drawRand.nextInt(beans.size());
        int beanDrawn2 = beans.get(draw2);
        beans.remove(beanDrawn2);

        //check the beans if they are 0 then they are white and if they are 1 they are black
        if (beanDrawn1 == 0 && beanDrawn2 == 0) {
            beans.add(1); //both white, add a black
        } else if (beanDrawn1 == 1 && beanDrawn2 == 1) {
            beans.add(beanDrawn1); //both black add one back
        } else if (beanDrawn1 == 1 && beanDrawn2 == 0) {
            beans.add(beanDrawn2); //one black one white, add white back
        } else if (beanDrawn1 == 0 && beanDrawn2 == 1) {
            beans.add(beanDrawn1); //same as above
        }

        //add two random beans to offset for a +1 bean increase
        int bean = addrand.nextInt(2);
        beans.add(bean);
        bean = addrand.nextInt(2);
        beans.add(bean);
    }

}

//get the last
static String getLast(ArrayList<Integer> a) {
    String display = "";
    int last = a.get(a.size() - 1);
    if (last == 0) {
        display += "White";
    } else {
        display += "Black";
    }
    return display;
}

//get the white
static int countWhite(ArrayList<Integer> a) {
    int whites = 0;
    for (int i : a) { //go through loop and increase at 0s
        if (a.get(i) == 0) {
            whites++;
        }
    }
    return whites;
}

//get the black
static int countBlack(ArrayList<Integer> a) {
    int blacks = 0;
    for (int i : a) { //go through loop and increase at 1s
        if (a.get(i) == 1) {
            blacks++;
        }
    }
    return blacks;
}
</code>```

}

The output I get is.

Beans   Black   White   Last
10  6   4   Black

11  5   6   Black

12  0   12  White

13  13  0   White

14  14  0   White

15  11  4   White

16  12  4   White

17  0   17  White

18  13  5   White

19  0   19  White

20  0   20  White

21  8   13  White

22  7   15  White

23  15  8   White

24  14  10  Black

25  25  0   Black

26  0   26  Black

27  0   27  Black

28  14  14  White

29  15  14  White

30  14  16  Black

31  0   31  Black

32  0   32  Black

33  19  14  White

34  34  0   Black

35  35  0   White

36  36  0   Black

37  19  18  White

38  19  19  Black

39  0   39  White

40  40  0   White

41  20  21  Black

42  23  19  Black

43  43  0   White

44  44  0   White

45  0   45  White

46  21  25  White

47  22  25  Black

48  48  0   Black

49  0   49  Black

50  24  26  White

51  27  24  White

52  0   52  White

53  27  26  Black

54  28  26  Black

55  0   55  White

56  29  27  White

57  57  0   White

58  58  0   Black

59  32  27  Black

60  0   60  White

For example you can't change all the white beans to white on the last trial. Wtf is wrong please help.

答:
I think the problem might be with the way that you remove your beans.

```<code>int draw1 = drawRand.nextInt(beans.size());
int beanDrawn1 = beans.get(draw1);
beans.remove(beanDrawn1);
int draw2 = drawRand.nextInt(beans.size());
int beanDrawn2 = beans.get(draw2);
beans.remove(beanDrawn2);
</code>```

Basically, what you are doing is getting a random index from the beans ArrayList and getting the result at that index, which is either 0 or 1.

The way that the beans.remove method works is that it removes the element at the INDEX that you put in to the method.

Therefore,

```<code>beans.remove(beanDrawn1);
</code>```

will remove the first or second element of the array depending on if its white or black. Instead of removing a random index.

If you want to delete a random index, you would just skip the middle part and do

```<code>beans.remove(draw1);
</code>```

I think this is how some beans are "not being remembered" as you mentioned. I haven't tested this, however, so try that change and see if it works.

Title: Drawing Beans from a bag

Body:
I have a program that draws beans from a bag and removes them on the following conditions. However my results don't seem to correlate at all, it seems as if the beans are not being remembered.

public class Prog477h {

public static void main(String[] args) {
    ArrayList<Integer> beans = new ArrayList<Integer>(); //make arrayList and add first 10 random beans
    Random addrand = new Random();
    for (int i = 0; i < 10; i++) {
        int bean = addrand.nextInt(2);
        beans.add(bean);
    }
    //print title
    System.out.println("Beans\tBlack\tWhite\tLast");
    for (int i = 0; i <= 50; i++) { //start for loop for 50 iterations
        int whites = countWhite(beans); //count the initial white
        int blacks = countBlack(beans); //count the initial black
        String last = getLast(beans); //get the last
        System.out.println(beans.size() + "\t" + blacks + "\t" + whites + "\t" + last + "\t"); //print row

        //draw two beans and remove them
        Random drawRand = new Random();
        int draw1 = drawRand.nextInt(beans.size());
        int beanDrawn1 = beans.get(draw1);
        beans.remove(beanDrawn1);
        int draw2 = drawRand.nextInt(beans.size());
        int beanDrawn2 = beans.get(draw2);
        beans.remove(beanDrawn2);

        //check the beans if they are 0 then they are white and if they are 1 they are black
        if (beanDrawn1 == 0 && beanDrawn2 == 0) {
            beans.add(1); //both white, add a black
        } else if (beanDrawn1 == 1 && beanDrawn2 == 1) {
            beans.add(beanDrawn1); //both black add one back
        } else if (beanDrawn1 == 1 && beanDrawn2 == 0) {
            beans.add(beanDrawn2); //one black one white, add white back
        } else if (beanDrawn1 == 0 && beanDrawn2 == 1) {
            beans.add(beanDrawn1); //same as above
        }

        //add two random beans to offset for a +1 bean increase
        int bean = addrand.nextInt(2);
        beans.add(bean);
        bean = addrand.nextInt(2);
        beans.add(bean);
    }

}

//get the last
static String getLast(ArrayList<Integer> a) {
    String display = "";
    int last = a.get(a.size() - 1);
    if (last == 0) {
        display += "White";
    } else {
        display += "Black";
    }
    return display;
}

//get the white
static int countWhite(ArrayList<Integer> a) {
    int whites = 0;
    for (int i : a) { //go through loop and increase at 0s
        if (a.get(i) == 0) {
            whites++;
        }
    }
    return whites;
}

//get the black
static int countBlack(ArrayList<Integer> a) {
    int blacks = 0;
    for (int i : a) { //go through loop and increase at 1s
        if (a.get(i) == 1) {
            blacks++;
        }
    }
    return blacks;
}

}

The output I get is.

Beans   Black   White   Last
10  6   4   Black

11  5   6   Black

12  0   12  White

13  13  0   White

14  14  0   White

15  11  4   White

16  12  4   White

17  0   17  White

18  13  5   White

19  0   19  White

20  0   20  White

21  8   13  White

22  7   15  White

23  15  8   White

24  14  10  Black

25  25  0   Black

26  0   26  Black

27  0   27  Black

28  14  14  White

29  15  14  White

30  14  16  Black

31  0   31  Black

32  0   32  Black

33  19  14  White

34  34  0   Black

35  35  0   White

36  36  0   Black

37  19  18  White

38  19  19  Black

39  0   39  White

40  40  0   White

41  20  21  Black

42  23  19  Black

43  43  0   White

44  44  0   White

45  0   45  White

46  21  25  White

47  22  25  Black

48  48  0   Black

49  0   49  Black

50  24  26  White

51  27  24  White

52  0   52  White

53  27  26  Black

54  28  26  Black

55  0   55  White

56  29  27  White

57  57  0   White

58  58  0   Black

59  32  27  Black

60  0   60  White

For example you can't change all the white beans to white on the last trial. Wtf is wrong please help.

Body:
I think the problem might be with the way that you remove your beans.

int draw1 = drawRand.nextInt(beans.size());
int beanDrawn1 = beans.get(draw1);
beans.remove(beanDrawn1);
int draw2 = drawRand.nextInt(beans.size());
int beanDrawn2 = beans.get(draw2);
beans.remove(beanDrawn2);

Basically, what you are doing is getting a random index from the beans ArrayList and getting the result at that index, which is either 0 or 1.

The way that the beans.remove method works is that it removes the element at the INDEX that you put in to the method.

Therefore,

beans.remove(beanDrawn1);

will remove the first or second element of the array depending on if its white or black. Instead of removing a random index.

If you want to delete a random index, you would just skip the middle part and do

beans.remove(draw1);

I think this is how some beans are "not being remembered" as you mentioned. I haven't tested this, however, so try that change and see if it works.


问:
python xtick for bar graph
I want to plot the bar graph for this data :

```<code>(0, 68.41780598958333)
(1, 9.018391927083334)
(2, 0.4236653645833333)
(3, 0.5224609375)
(4, 0.4427083333333333)
(5, 0.6256510416666666)
(6, 1.248046875)
(7, 1.0188802083333333)
(8, 1.1717122395833333)
(9, 1.8673502604166667)
(10, 0.8668619791666666)
(11, 1.7233072916666667)
(12, 0.12353515625)
(13, 0.19661458333333334)
(14, 0.17513020833333334)
(15, 0.0006510416666666666)
(16, 12.1572265625)
</code>```

The code works perfectly but the problem with the xticks the graph I get is like:

I want to have the x-tick in the center of each corresponding bars and shows all numbers not only even. I tried the the len(k) but the k is not in a single row its a column. May be I am doing some mistake seems like solution should be easy but I get stuck.

```<code>with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))

    s=sum(d.values())

    for k, v in d.items():

     pct = float(v * 100.0 / s)
     data = (k,pct)
     print data
     width=0.15
     plt.bar(k,pct)
    #plt.xticks(k)

    pl.ylim(0, 80)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures(%)")
    plt.title("Adder@1")
    pl.show()
</code>```

答:
This line did the trick. Problem solved. Please someone make it tick

fig = pl.bar(k,pct,align='center',width=0.25)

Title: python xtick for bar graph

Body:
I want to plot the bar graph for this data :

(0, 68.41780598958333)
(1, 9.018391927083334)
(2, 0.4236653645833333)
(3, 0.5224609375)
(4, 0.4427083333333333)
(5, 0.6256510416666666)
(6, 1.248046875)
(7, 1.0188802083333333)
(8, 1.1717122395833333)
(9, 1.8673502604166667)
(10, 0.8668619791666666)
(11, 1.7233072916666667)
(12, 0.12353515625)
(13, 0.19661458333333334)
(14, 0.17513020833333334)
(15, 0.0006510416666666666)
(16, 12.1572265625)

The code works perfectly but the problem with the xticks the graph I get is like:

I want to have the x-tick in the center of each corresponding bars and shows all numbers not only even. I tried the the len(k) but the k is not in a single row its a column. May be I am doing some mistake seems like solution should be easy but I get stuck.

with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))

    s=sum(d.values())

    for k, v in d.items():

     pct = float(v * 100.0 / s)
     data = (k,pct)
     print data
     width=0.15
     plt.bar(k,pct)
    #plt.xticks(k)

    pl.ylim(0, 80)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures(%)")
    plt.title("Adder@1")
    pl.show()


问:
Execute multiple functions at once
I need to make a simple calculator for a school project using only functions.

One of the functions is:

```<code>double addition(double a, double b)
{
    return a + b;
}
</code>```

And I call it and show the results doing this:

```<code>printf( "Addition: %.2lf\n", addition(x,y));
</code>```

I have other functions for substraction, multiplication, and division.

I need to perform each one of those separately, and then, perform them all at once.

How can I integrate all of these functions in just one function, like this:

```<code>printf( "All of the results %.2lf\n", allfunctions(x,y));
</code>```

Is it possible?

I'm trying to avoid doing something like this:

```<code>printf( "Addition: %.2lf\n", addition(x,y));
printf( "Substraction: %.2lf\n", substraction(x,y));
</code>```

Thanks.

答:
One thing you could do would be to declare an array of pointers to functions:

```<code>double (*arith_op[4])(double, double) = {addition, subtraction, multiplication, division};
const char *strings[4] = {"addition", "subtraction", "multiplication", "division"};

for (i = 0; i < 4; i++)
{
    printf("Result of %s is %.2lf\n", strings[i], arith_op[i](x,y));
}
</code>```

This is one way of handling your problem.

Title: Execute multiple functions at once

Body:
I need to make a simple calculator for a school project using only functions.

One of the functions is:

double addition(double a, double b)
{
    return a + b;
}

And I call it and show the results doing this:

printf( "Addition: %.2lf\n", addition(x,y));

I have other functions for substraction, multiplication, and division.

I need to perform each one of those separately, and then, perform them all at once.

How can I integrate all of these functions in just one function, like this:

printf( "All of the results %.2lf\n", allfunctions(x,y));

Is it possible?

I'm trying to avoid doing something like this:

printf( "Addition: %.2lf\n", addition(x,y));
printf( "Substraction: %.2lf\n", substraction(x,y));

Thanks.

Body:
One thing you could do would be to declare an array of pointers to functions:

double (*arith_op[4])(double, double) = {addition, subtraction, multiplication, division};
const char *strings[4] = {"addition", "subtraction", "multiplication", "division"};

for (i = 0; i < 4; i++)
{
    printf("Result of %s is %.2lf\n", strings[i], arith_op[i](x,y));
}

This is one way of handling your problem.


问:
How to change state of nested formly form to readonly on click of a button
My problem is pretty straight forward.

Things that I have.

-- A form (formly) which I made using the data (JSON) received form the backend.

-- The form is going to be Multilevel Nested (currently its two level nested).

-- There is a repeater associated to every nested form element that will add another element to the form on click of a button.

-- There is going to be a button on the top of the page that will toggle the state of the form elements to readOnly.

Problem that I am facing

-- When I click the button, the state of the form elements change to readOnly, except the ones that are nested.

What I want

--When I click the button, every single element of my form should change its state to readOnly, nested or not.

Here is the controller...Followed by JS-Bin link.

app.controller('MainCtrl', function MainCtrl(formlyVersion) {
  var vm = this;

  vm.onSubmit = onSubmit;
  vm.exampleTitle = 'Nested Repeating Section';
  vm.options = {
    formState: {
      readOnly: true
    }
  };

  init();

  vm.originalFields = angular.copy(vm.fields);

  function onSubmit() {
    alert(JSON.stringify(vm.model), null, 2);
  }

  function init() {
    vm.fields = [{
      key: 'name',
      type: 'input',

      templateOptions: {
        label: 'Name',
        required: true,
        minlength: 5,
        maxlength: 25
      }
    }, {
      key: 'description',
      type: 'textarea',

      templateOptions: {
        label: 'Description',
        rows: 5,
        maxlength: 100
      }
    }, {
      wrapper: 'panel',
      templateOptions: {
        label: 'Cars'
      },
      fieldGroup: [{
        type: 'repeatSection',
        key: 'cars',
        templateOptions: {
          btnText: '+',
          fields: [{

            wrapper: 'panel',
            templateOptions: {
              label: 'New car'
            },
            fieldGroup: [{
              key: 'carname',
              type: 'input',
              templateOptions: {
                label: 'Name',
                required: true,
                maxlength: 25
              }
            }, {
              key: 'cardesc',
              type: 'input',
              templateOptions: {
                label: 'Description',
                maxlength: 50
              }
            }]
          }]
        }
      }]
    }];
  }
});```

http://jsbin.com/sunocaf/edit?html,js,output

Thanks in advance

P.S. - I took the example from the official angular formly website.

答:
This will only make inputs readOnly, and will not affect radio buttons or checkboxes.  Buttons either for that matter.

To do what you want, set the ng-click event in the button to:

```<code>ng-click="readOnly()"
</code>```

then in the controller:

```<code>   $scope.readOnly = function() {
       $(document).ready(function () {
            $('input').click(function (e) {
                e.preventDefault();
            });
        });
   };
</code>```

This will prevent any input from occurring.  If you need to hide/disable buttons you can set a readOnly flag to true and have an ng-show or an ng-disabled on the button set to !model.readOnly.

If you want to pretend you are using angular instead of jQuery, even though angular.element is an ALIAS for jQuery(straight out of the angular docs), then  you could do:

```<code> $scope.readOnly = function() {
     angular.element(function() {
            angular.element('input').trigger('click')(function(e) {
                e.preventDefault();
            };
       });
 };
</code>```

Body:
My problem is pretty straight forward.

Things that I have.

-- A form (formly) which I made using the data (JSON) received form the backend.

-- The form is going to be Multilevel Nested (currently its two level nested).

-- There is a repeater associated to every nested form element that will add another element to the form on click of a button.

-- There is going to be a button on the top of the page that will toggle the state of the form elements to readOnly.

Problem that I am facing

-- When I click the button, the state of the form elements change to readOnly, except the ones that are nested.

What I want

--When I click the button, every single element of my form should change its state to readOnly, nested or not.

Here is the controller...Followed by JS-Bin link.

app.controller('MainCtrl', function MainCtrl(formlyVersion) {
  var vm = this;

  vm.onSubmit = onSubmit;
  vm.exampleTitle = 'Nested Repeating Section';
  vm.options = {
    formState: {
      readOnly: true
    }
  };

  init();

  vm.originalFields = angular.copy(vm.fields);

  function onSubmit() {
    alert(JSON.stringify(vm.model), null, 2);
  }

  function init() {
    vm.fields = [{
      key: 'name',
      type: 'input',

      templateOptions: {
        label: 'Name',
        required: true,
        minlength: 5,
        maxlength: 25
      }
    }, {
      key: 'description',
      type: 'textarea',

      templateOptions: {
        label: 'Description',
        rows: 5,
        maxlength: 100
      }
    }, {
      wrapper: 'panel',
      templateOptions: {
        label: 'Cars'
      },
      fieldGroup: [{
        type: 'repeatSection',
        key: 'cars',
        templateOptions: {
          btnText: '+',
          fields: [{

            wrapper: 'panel',
            templateOptions: {
              label: 'New car'
            },
            fieldGroup: [{
              key: 'carname',
              type: 'input',
              templateOptions: {
                label: 'Name',
                required: true,
                maxlength: 25
              }
            }, {
              key: 'cardesc',
              type: 'input',
              templateOptions: {
                label: 'Description',
                maxlength: 50
              }
            }]
          }]
        }
      }]
    }];
  }
});

http://jsbin.com/sunocaf/edit?html,js,output

Thanks in advance

P.S. - I took the example from the official angular formly website.

Body:
This will only make inputs readOnly, and will not affect radio buttons or checkboxes.  Buttons either for that matter.

To do what you want, set the ng-click event in the button to:

ng-click="readOnly()"

then in the controller:

   $scope.readOnly = function() {
       $(document).ready(function () {
            $('input').click(function (e) {
                e.preventDefault();
            });
        });
   };

This will prevent any input from occurring.  If you need to hide/disable buttons you can set a readOnly flag to true and have an ng-show or an ng-disabled on the button set to !model.readOnly.

If you want to pretend you are using angular instead of jQuery, even though angular.element is an ALIAS for jQuery(straight out of the angular docs), then  you could do:

 $scope.readOnly = function() {
     angular.element(function() {
            angular.element('input').trigger('click')(function(e) {
                e.preventDefault();
            };
       });
 };


问:
How to get the body of a push notification sent from Firebase console in iOS 10 and Swift 3?
I'm developing an iOS app that should receive push notifications sent from the Firebase console. I'm using Swift 3 and iOS 10.

As recommended by the Firebase documentation, we must assign our delegate object to the UNUserNotificationCenter object to receive and display notifications, and the FIRMessaging object to receive data messages, before our app finishes launching.

This has been done in the didFinishLaunchingWithOptions method. I followed all the steps in order to configure Firmessaging as well as APNs.

Now, when I send a message from the Firebase console, I receive it through applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) method.

The problem is that I could not extract the body of the message from the remoteMessage.appData dictionary. Knowing that the body is within remoteMessage.appData["notification"]. Indeed, the instruction

```<code>print(remoteMessage.appData)
</code>```

prints

```<code>[AnyHashable("notification"): {
   body = Hello Notifications;
   e = 1;
}, AnyHashable("from"): 49679924394, AnyHashable("collapse_key"): com.company.app]
</code>```

Printing

```<code> remoteMessage.appData["notification"]
</code>```

shows

```<code>{
   body = Hello Notifications;
   e = 1;
}
</code>```

I tried

```<code>remoteMessage.appData["notification"]["body"]
</code>```

and

```<code> remoteMessage.appData["notification"].body
</code>```

but it results in syntax error. I could not extract the body in order to show it in an alert controller. The code of the appDelegate is given below.

```<code>class AppDelegate: UIResponder, UIApplicationDelegate, FIRMessagingDelegate, UNUserNotificationCenterDelegate{
......

func application(_ application: UIApplication, didFinishLaunchingWithOptions, launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    application.isStatusBarHidden = true
    FIRApp.configure()
    FIRDatabase.database().persistenceEnabled = true
    if #available(iOS 10.0, *) {
       let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
       let center = UNUserNotificationCenter.current()
       center.requestAuthorization(options: authOptions, completionHandler: {_ ,_ in })
       application.registerForRemoteNotifications()
// For iOS 10 display notification (sent via APNS)
       UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
       FIRMessaging.messaging().remoteMessageDelegate = self
    } else {
       let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
       application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
     return true
}
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print(remoteMessage.appData)
    print(remoteMessage.appData["notification"]!)
    let alertController = UIAlertController(title: "Message from IOBird Developer Team", message: "?????? Body of the message ?????", preferredStyle: .alert)
    let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
    }
    alertController.addAction(OKAction)
    self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
}
</code>```

答:
You should be able to print any line from the response with this :

```<code>let response = remoteMessage.appData

print(response[AnyHashable("notification")] as Any)
</code>```

Apple documentation on AnyHashable : https://developer.apple.com/reference/swift/anyhashable

Body:
I'm developing an iOS app that should receive push notifications sent from the Firebase console. I'm using Swift 3 and iOS 10.

As recommended by the Firebase documentation, we must assign our delegate object to the UNUserNotificationCenter object to receive and display notifications, and the FIRMessaging object to receive data messages, before our app finishes launching.

This has been done in the didFinishLaunchingWithOptions method. I followed all the steps in order to configure Firmessaging as well as APNs.

Now, when I send a message from the Firebase console, I receive it through applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) method.

The problem is that I could not extract the body of the message from the remoteMessage.appData dictionary. Knowing that the body is within remoteMessage.appData["notification"]. Indeed, the instruction

print(remoteMessage.appData)

prints

[AnyHashable("notification"): {
   body = Hello Notifications;
   e = 1;
}, AnyHashable("from"): 49679924394, AnyHashable("collapse_key"): com.company.app]

Printing

 remoteMessage.appData["notification"]

shows

{
   body = Hello Notifications;
   e = 1;
}

I tried

remoteMessage.appData["notification"]["body"]

and

 remoteMessage.appData["notification"].body

but it results in syntax error. I could not extract the body in order to show it in an alert controller. The code of the appDelegate is given below.

class AppDelegate: UIResponder, UIApplicationDelegate, FIRMessagingDelegate, UNUserNotificationCenterDelegate{
......

func application(_ application: UIApplication, didFinishLaunchingWithOptions, launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    application.isStatusBarHidden = true
    FIRApp.configure()
    FIRDatabase.database().persistenceEnabled = true
    if #available(iOS 10.0, *) {
       let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
       let center = UNUserNotificationCenter.current()
       center.requestAuthorization(options: authOptions, completionHandler: {_ ,_ in })
       application.registerForRemoteNotifications()
// For iOS 10 display notification (sent via APNS)
       UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
       FIRMessaging.messaging().remoteMessageDelegate = self
    } else {
       let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
       application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
     return true
}
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print(remoteMessage.appData)
    print(remoteMessage.appData["notification"]!)
    let alertController = UIAlertController(title: "Message from IOBird Developer Team", message: "?????? Body of the message ?????", preferredStyle: .alert)
    let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
    }
    alertController.addAction(OKAction)
    self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
}

Body:
You should be able to print any line from the response with this :

let response = remoteMessage.appData

print(response[AnyHashable("notification")] as Any)

Apple documentation on AnyHashable : https://developer.apple.com/reference/swift/anyhashable


问:
How does a json formatted response from a SQL Server work?
I have a stored procedure that returns query results as json and I want to understand how this query will get to my code behind in an ASP.NET app.

Stored procedure:

```<code>Select
       SUBJECT AS [subject],
       STARTDATE AS [start]
       ENDDATE AS [end],
       ID AS [id]
FROM
       SOME_TABLE
FOR JSON PATH
</code>```

Json format from stored procedure:

```<code>[
 {
  "subject": _,
  "start": _,
  "end":_,
  "id":_
 },
 ...]
</code>```

aspx.cs codebehind

(snippet from a function)

```<code>  try
        {
            if (sqlcon.State == ConnectionState.Closed)
            {
                sqlcon.Open();
            }

            SqlCommand sccmd = new SqlCommand("MY_STORED_PROCEDURE", sqlcon);
            sccmd.CommandType = CommandType.StoredProcedure;
            sccmd.Parameters.AddWithValue("@value1", valueID);
            sccmd.Parameters.AddWithValue("@value2", valueID);
            SqlDataReader sdrreader = sccmd.ExecuteReader();

            while (sdrreader.Read())
            {
                // lost on what to do here
            }

            sdrreader.Close();
        }
        catch (Exception ex){}
        finally { sqlcon.Close(); }
</code>```

I want to store this json response in my code behind, but I don't know how. Before making the response json I was using SqlDataReader with Read() to walk through each record, but how would this work if the response is now json; is there another class that will specifically handle a json response?

Clarification please!

答:
After read the SQL query return result, you can store the result into an array. Then, using json_encode function to output the result in json format.

For example,

```<code>int [] marks = new int[]  { 99,  98, 92, 97, 95};
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = jsonSerializer.Serialize(marks);
</code>```

Body:
I have a stored procedure that returns query results as json and I want to understand how this query will get to my code behind in an ASP.NET app.

Stored procedure:

Select
       SUBJECT AS [subject],
       STARTDATE AS [start]
       ENDDATE AS [end],
       ID AS [id]
FROM
       SOME_TABLE
FOR JSON PATH

Json format from stored procedure:

[
 {
  "subject": _,
  "start": _,
  "end":_,
  "id":_
 },
 ...]

aspx.cs codebehind

(snippet from a function)

  try
        {
            if (sqlcon.State == ConnectionState.Closed)
            {
                sqlcon.Open();
            }

            SqlCommand sccmd = new SqlCommand("MY_STORED_PROCEDURE", sqlcon);
            sccmd.CommandType = CommandType.StoredProcedure;
            sccmd.Parameters.AddWithValue("@value1", valueID);
            sccmd.Parameters.AddWithValue("@value2", valueID);
            SqlDataReader sdrreader = sccmd.ExecuteReader();

            while (sdrreader.Read())
            {
                // lost on what to do here
            }

            sdrreader.Close();
        }
        catch (Exception ex){}
        finally { sqlcon.Close(); }

I want to store this json response in my code behind, but I don't know how. Before making the response json I was using SqlDataReader with Read() to walk through each record, but how would this work if the response is now json; is there another class that will specifically handle a json response?

Clarification please!

Body:
After read the SQL query return result, you can store the result into an array. Then, using json_encode function to output the result in json format.

For example,

int [] marks = new int[]  { 99,  98, 92, 97, 95};
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = jsonSerializer.Serialize(marks);


问:
Server software for handling multiple mp3/ogg streams
I'm looking for advice regarding an aspect of a project I'm working on.

I'm developing a demo android app for a not-for-profit that specialises in services for the vision impaired. The plan is, among other things, the app will enable users to stream this organization's specialised audiobooks.

For the sake of demo'ing/development I need to establish some sort of server which will, pending a request from a device running the app:

directly transfer certain xml/html index files to the android phone (no streaming necessary)

stream .ogg and .mp3 audio files to the device

serve more than one client device at a time

start a stream from a specific point within an mp3/ogg file, pending a request from the phone app

I've had a look at Icecast as an mp3/ogg streaming solution, but my knowledge of servers is a bit limited (I've only ever done some basic work in Flask). Would I need to run this in tandem with something that can generically serve files / handle requests?

I'm basically just looking for a good solution/tool to implement this is. The server side doesn't need to be completely fleshed out, just fit the bill above, as my focus is developing the phone app side for now. For the sake of a demo, something straightforward / well documented would suit best.

答:
You don't need a special server for this.  Any HTTP server that supports range requests will be fine.  This includes Nginx, Apache, etc.  There is no need to spoon-feed clients media data from the server.  This streaming and buffering aspect is handled automatically on the client, through TCP window size and outright closing the connection and connecting again later as-needed.

Icecast is meant for radio-style streams where everyone listening hears the same thing at roughly the same time.  Since that's not an aspect you want, stick to any normal HTTP server.


问:
Warning in StringBuffer and StringBuilder
I have a StringBuffer initialized outside for loop and inside for loop I am concatenating some strings.

I am getting the warning

'StringBuffer stringBuffer' may be declared as 'StringBuilder'

and

string concatenation as argument to 'stringbuilder.append()' call

Then I changed that StringBuffer to StringBuilder, since it is comparatively faster than StringBuffer. Now I am getting the warning as

string concatenation as argument to 'stringbuilder.append()' call

Sample code:

```<code>public static String stringConcat(String[] words) {
    StringBuffer stringBuffer = new StringBuffer();
    for (String word : words) {
        stringBuffer.append(word).append(" ");
    }
    return stringBuffer.toString();
}
</code>```

Why I am getting these warnings.

Edit Actual code:

```<code>stringBuffer.append(word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()).append(" ");
</code>```

答:
Use  StringBuilder instead of StringBuffer

```<code> public static String stringConcat(String[] words) {
    StringBuilder stringBuilder = new StringBuilder();

    for (String word : words) {
        stringBuilder.append(word).append(" ");
    }
    return stringBuilder.toString();
  }
</code>```

Body:
I have a StringBuffer initialized outside for loop and inside for loop I am concatenating some strings.

I am getting the warning

'StringBuffer stringBuffer' may be declared as 'StringBuilder'

and

string concatenation as argument to 'stringbuilder.append()' call

Then I changed that StringBuffer to StringBuilder, since it is comparatively faster than StringBuffer. Now I am getting the warning as

string concatenation as argument to 'stringbuilder.append()' call

Sample code:

public static String stringConcat(String[] words) {
    StringBuffer stringBuffer = new StringBuffer();
    for (String word : words) {
        stringBuffer.append(word).append(" ");
    }
    return stringBuffer.toString();
}

Why I am getting these warnings.

Edit Actual code:

stringBuffer.append(word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()).append(" ");

Body:
Use  StringBuilder instead of StringBuffer

 public static String stringConcat(String[] words) {
    StringBuilder stringBuilder = new StringBuilder();

    for (String word : words) {
        stringBuilder.append(word).append(" ");
    }
    return stringBuilder.toString();
  }


问:
Fragment won't launch
I have onclicklistener that works. I am trying to launch a new fragment from the button click on the list view. Right now, the fragment does not launch. However, the emulator we are using does not crash, so if we're understanding this correctly, it isn't connecting to the new fragment/XML page.

```<code>  public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    myBadData.setId(i);
    Fragment fr = new event_description();
    //fr.setArguments(bundle);
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    //int contId = v.getId();
    fragmentTransaction.add(R.id.page, fr);
   // fragmentTransaction.add(view.getId(), fr);
   // fragmentTransaction.commit();

    Intent intent =new Intent(eventList.this, fr.getClass());

}
</code>```

Here is our XML code for the view that we are trying to add the fragment over top of.

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/page"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.example.alex.qtapandroid.ui.fragments.DayFragment">

<!-- TODO: Update blank fragment layout -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />

    <ListView
        android:id="@+id/dayList"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

 </FrameLayout>
</code>```

答:
change this line

```<code>Intent intent =new Intent(eventList.this, fr.getClass());
</code>```

to:

```<code>fragmentTransaction.commit;
</code>```

and better replace fragment in container ,

```<code>fragmentTransaction.replace(R.id.page, fr);
</code>```

Title: Fragment won't launch

Body:
I have onclicklistener that works. I am trying to launch a new fragment from the button click on the list view. Right now, the fragment does not launch. However, the emulator we are using does not crash, so if we're understanding this correctly, it isn't connecting to the new fragment/XML page.

  public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    myBadData.setId(i);
    Fragment fr = new event_description();
    //fr.setArguments(bundle);
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    //int contId = v.getId();
    fragmentTransaction.add(R.id.page, fr);
   // fragmentTransaction.add(view.getId(), fr);
   // fragmentTransaction.commit();

    Intent intent =new Intent(eventList.this, fr.getClass());

}

Here is our XML code for the view that we are trying to add the fragment over top of.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/page"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.example.alex.qtapandroid.ui.fragments.DayFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />

    <ListView
        android:id="@+id/dayList"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

 </FrameLayout>

Body:
change this line

Intent intent =new Intent(eventList.this, fr.getClass());

to:

fragmentTransaction.commit;

and better replace fragment in container ,

fragmentTransaction.replace(R.id.page, fr);


问:
Order by date desc, but within day order by time asc
I have a table in which there is a Date (smalldatetime) column. I need to order by Date DESC, but within each day to order by Date ASC.  The output should be like:

```<code>Date
2017-01-31T09:00:00Z
2017-01-31T17:00:00Z
2017-01-28T09:00:00Z
2017-01-28T17:00:00Z
2017-01-25T09:00:00Z
2017-01-25T17:00:00Z
...
</code>```

Is such a query possible?

If it's of any help, the data contains a maximum of two rows for the same Date.

答:
Cast to dateand then to time

```<code>ORDER BY
    CAST([Date] AS date) DESC
    ,CAST([Date] AS time) ASC
</code>```

Body:
I have a table in which there is a Date (smalldatetime) column. I need to order by Date DESC, but within each day to order by Date ASC.  The output should be like:

Date
2017-01-31T09:00:00Z
2017-01-31T17:00:00Z
2017-01-28T09:00:00Z
2017-01-28T17:00:00Z
2017-01-25T09:00:00Z
2017-01-25T17:00:00Z
...

Is such a query possible?

If it's of any help, the data contains a maximum of two rows for the same Date.

Body:
Cast to dateand then to time

ORDER BY
    CAST([Date] AS date) DESC
    ,CAST([Date] AS time) ASC


问:
How to get RxJS Observable events in zero time?
I'm collecting all the events of an Observable to a data array:

const obs$ = Rx.Observable
  .interval(500)
  .take(4);

let data = [];
const start = performance.now();

obs$.subscribe(
  value => {
    data.push({
      time: performance.now() - start,
      data: value
    });
  },
  () => {},
  () => {
    console.log(JSON.stringify(data, null, 2));
  }
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/rxjs@5.2.0/bundles/Rx.js"></script></code>```

Is it possible to "foresee the future" and get the same data array without waiting 2 seconds?

To clarify, I'm trying to find a way to wrap somehow a given Observable (obs$ in the example above) with a custom timer/scheduler so I could get the events immediately.

答:
You can create an instance of the VirtualTimeScheduler and can specify it in the call to interval.

If you then call flush on the scheduler after subscribing, the events will be emitted immediately:

const scheduler = new Rx.VirtualTimeScheduler();

const obs$ = Rx.Observable
  .interval(500, scheduler)
  .take(4);

let data = [];
const start = scheduler.now();

obs$.subscribe(
  value => {
    data.push({
      time: scheduler.now() - start,
      data: value
    });
  },
  () => {},
  () => {
    console.log(JSON.stringify(data, null, 2));
  }
);

scheduler.flush();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```

Body:
I'm collecting all the events of an Observable to a data array:

const obs$ = Rx.Observable
  .interval(500)
  .take(4);

let data = [];
const start = performance.now();

obs$.subscribe(
  value => {
    data.push({
      time: performance.now() - start,
      data: value
    });
  },
  () => {},
  () => {
    console.log(JSON.stringify(data, null, 2));
  }
);

Is it possible to "foresee the future" and get the same data array without waiting 2 seconds?

To clarify, I'm trying to find a way to wrap somehow a given Observable (obs$ in the example above) with a custom timer/scheduler so I could get the events immediately.

Body:
You can create an instance of the VirtualTimeScheduler and can specify it in the call to interval.

If you then call flush on the scheduler after subscribing, the events will be emitted immediately:

const scheduler = new Rx.VirtualTimeScheduler();

const obs$ = Rx.Observable
  .interval(500, scheduler)
  .take(4);

let data = [];
const start = scheduler.now();

obs$.subscribe(
  value => {
    data.push({
      time: scheduler.now() - start,
      data: value
    });
  },
  () => {},
  () => {
    console.log(JSON.stringify(data, null, 2));
  }
);

scheduler.flush();

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://unpkg.com/rxjs@5.2.0/bundles/Rx.js"></script>


问:
Downloading 'Yum groupinstall "development tools"'?
I've looked all over and build essentials are all I see that was replaced by Development tools. When I type the command I receive "no such command".

What is the alternative to this?

答:
apt-get build-dep package-i-want-to-build to get everything you need to build package - often the easiest way to get the dev tools is to pick a sufficiently complicated package like pidgin and run this

or

apt-get install build-essential to just get a compiler


问:
Multiple checkboxes to variable logic
I am looking to create a simple page using HTML and (probably) PHP or JQuery. The page should allow for multiple checkbox selection, and give a variable a value based on which boxes are checked. This can be on submit or can render live on the page.

i.e.

Checkbox 1

Checkbox 2

Checkbox 3

If checkbox 1 is checked, variable = X

If checkbox 1 & 2 are checked, variable = Y

If no checkboxes are checked, variable = Z

What is the best way to approach doing this?

答:
The best way would be using Javascript (because it'd be done live) but if you are doing this with PHP. The form would be something like

```<code><form action='phplogic.php' method='post>
<input type="checkbox" name="checkbox1" value="Yes" />
<input type="checkbox" name="checkbox2" value="Yes" />
<input type="checkbox" name="checkbox3" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
</code>```

phplogic would would look like this

```<code><?php
if(isset($_POST[checkbox1']) && (isset($_POST['checkbox2']))  {
$variable = 'Y';
} else (isset($_POST[checkbox1'])) {
$variable = 'X';
} else {
$variable = 'Z';
}
</code>```

Although this doesn't address if checkbox 2 alone is checked but you get the point. You can do something very similar with javascript. https://www.w3schools.com/jsref/prop_checkbox_value.asp

Title: Multiple checkboxes to variable logic

Body:
The best way would be using Javascript (because it'd be done live) but if you are doing this with PHP. The form would be something like

<form action='phplogic.php' method='post>
<input type="checkbox" name="checkbox1" value="Yes" />
<input type="checkbox" name="checkbox2" value="Yes" />
<input type="checkbox" name="checkbox3" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>

phplogic would would look like this

<?php
if(isset($_POST[checkbox1']) && (isset($_POST['checkbox2']))  {
$variable = 'Y';
} else (isset($_POST[checkbox1'])) {
$variable = 'X';
} else {
$variable = 'Z';
}

Although this doesn't address if checkbox 2 alone is checked but you get the point. You can do something very similar with javascript. https://www.w3schools.com/jsref/prop_checkbox_value.asp


答:
Ok, let's say, you have created a magic function that do all your operation. The name of the function is double allFunctions(double a, double b).

If problem is, the function have only 2 inputs. a and b, so the function know with which values it will be working. But what will it do with those a and b. Does this function have any clue? No, right? So, if you want to do all operation in one function than you need to set an extra parameter from which the function will be able to understand what to do with those a and b.

So, you magic function should be for example double allFuncations(double a, double b, int operation). Now inside this function you can set condition that if operation is 1 then return add result and if its 2 then return subtract result and so on. So, how will you call this new function?

```<code>printf( "Addition: %.2lf\n", allFuncations(x,y, 1));//for addition
printf( "Substraction: %.2lf\n", allFuncations(x,y, 2));//for subtraction
</code>```

By the way, you can even use char type data instead of int for the operation variable that will be more readable. for example:

new function?

```<code>printf( "Addition: %.2lf\n", allFuncations(x,y, '+'));//for addition
printf( "Substraction: %.2lf\n", allFuncations(x,y, '-'));//for subtraction
</code>```

When your function definition will be double allFunction(double a, double b, char operation)

Finally, this is how you can do all operation in a single function. But there is nothing wrong if you create separate function for every operation. Nothing to feel guilty there. Beside, getting all result in one line may create less control on your code.

Title: Execute multiple functions at once

Body:
I need to make a simple calculator for a school project using only functions.

One of the functions is:

double addition(double a, double b)
{
    return a + b;
}

And I call it and show the results doing this:

printf( "Addition: %.2lf\n", addition(x,y));

I have other functions for substraction, multiplication, and division.

I need to perform each one of those separately, and then, perform them all at once.

How can I integrate all of these functions in just one function, like this:

printf( "All of the results %.2lf\n", allfunctions(x,y));

Is it possible?

I'm trying to avoid doing something like this:

printf( "Addition: %.2lf\n", addition(x,y));
printf( "Substraction: %.2lf\n", substraction(x,y));

Thanks.

Body:
Ok, let's say, you have created a magic function that do all your operation. The name of the function is double allFunctions(double a, double b).

If problem is, the function have only 2 inputs. a and b, so the function know with which values it will be working. But what will it do with those a and b. Does this function have any clue? No, right? So, if you want to do all operation in one function than you need to set an extra parameter from which the function will be able to understand what to do with those a and b.

So, you magic function should be for example double allFuncations(double a, double b, int operation). Now inside this function you can set condition that if operation is 1 then return add result and if its 2 then return subtract result and so on. So, how will you call this new function?

printf( "Addition: %.2lf\n", allFuncations(x,y, 1));//for addition
printf( "Substraction: %.2lf\n", allFuncations(x,y, 2));//for subtraction

By the way, you can even use char type data instead of int for the operation variable that will be more readable. for example:

new function?

printf( "Addition: %.2lf\n", allFuncations(x,y, '+'));//for addition
printf( "Substraction: %.2lf\n", allFuncations(x,y, '-'));//for subtraction

When your function definition will be double allFunction(double a, double b, char operation)

Finally, this is how you can do all operation in a single function. But there is nothing wrong if you create separate function for every operation. Nothing to feel guilty there. Beside, getting all result in one line may create less control on your code.


问:
ASP.Net check if radiobuttons are checked doesn't work in backend
This is my frontend code

```<code><table width="50%">
    <tr>
       <td><asp:RadioButton ID="RadioButton1" runat="server" Text=" NL" GroupName="lang"/></td>
       <td><asp:RadioButton ID="RadioButton2" runat="server" Text=" FR" GroupName="lang"/></td>
       <td><asp:RadioButton ID="RadioButton3" runat="server" Text=" DE" GroupName="lang"/></td>
    </tr>
 </table>
</code>```

This is my backend (.vb) code

```<code>If RadioButton1.Checked = True Then
   .LanguageId = 1
ElseIf RadioButton2.Checked = True Then
   .LanguageId = 2
ElseIf RadioButton3.Checked = True Then
   .LanguageId = 3
Else
   .LanguageId = 4

End If
</code>```

Somehow it always gives languageId 4, so the if and elseif are not true (which is not the case there's definitely always one checked).

Any ideas what can be the problem?

答:
Since you're saying it is a big project with more code, maybe you're manipulating two objects where you think they're one.

For debugging purposes, write all the values to the console.
Console. WriteLine(radio button 1. Checked. To string)

The line has improper syntax but you should get the idea. Coding on a phone is impossible.

You should be able to understand what your code is doing this way and locate where the logic does not follow and ask a better question.

Body:
This is my frontend code

       <asp:RadioButton ID="RadioButton1" runat="server" Text=" NL" GroupName="lang"/>
       <asp:RadioButton ID="RadioButton2" runat="server" Text=" FR" GroupName="lang"/>
       <asp:RadioButton ID="RadioButton3" runat="server" Text=" DE" GroupName="lang"/>

This is my backend (.vb) code

If RadioButton1.Checked = True Then
   .LanguageId = 1
ElseIf RadioButton2.Checked = True Then
   .LanguageId = 2
ElseIf RadioButton3.Checked = True Then
   .LanguageId = 3
Else
   .LanguageId = 4

End If

Somehow it always gives languageId 4, so the if and elseif are not true (which is not the case there's definitely always one checked).

Any ideas what can be the problem?


问:
Hibernate 3 not auto creating tables
Here is my code:

hiberntae.cfg.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
  </session-factory>
</hibernate-configuration>
</code>```

pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.bc.eagleapps</groupId>
    <artifactId>mavenproject1</artifactId>
    <version>1.2-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>mavenproject1</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springframework.version>4.0.6.RELEASE</springframework.version>
        <hibernate.version>3.6.9.Final</hibernate.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.18.2-GA</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-base</artifactId>
            <version>2.6.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Model

```<code>package app.model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_MASTER")
public class UserMaster {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column
private String id;

  @Column(length = 50, nullable = false, unique = true)
private String userid;

  @Column(length = 50, nullable = false, unique = true)
private String password;

public UserMaster() {}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
</code>```

When I try to save user via controller, I get the following error:

```<code>org.hibernate.exception.SQLGrammarException: could not insert: [app.model.UserMaster]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at coolcook.dao.UserMasterDao.saveUser(UserMasterDao.java:23)
at coolcook.service.UserMasterServiceImpl.saveUser(UserMasterServiceImpl.java:16)
at coolcook.controller.UserController.registerUser(UserController.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
a

t java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'app.USER_MASTER' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
</code>```

the database "app" exists, but whenever I try to save user through controller, it gives me above error.

I search through several answers on SO and other sites but not successful. Any help will be appreciated!

Dao

```<code>   package coolcook.dao;

import coolcook.model.UserMaster;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserMasterDao {

    @Autowired
    private SessionFactory sessionFactory;

    public UserMaster saveUser(UserMaster user) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            session.save(user);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
            }
            return user;
        }

    }
</code>```

springmvc-servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="app" />
    <!--<mvc:resources mapping="/views/**" location="/views/" />-->
    <mvc:default-servlet-handler />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
          p:url="jdbc:mysql://localhost:3306/app" p:username="root"
          p:password="root" />

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>app.model</value>
            </list>
        </property>

        <property name="configLocation">
            <value>WEB-INF/hibernate.cfg.xml</value>
        </property>

    </bean>

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:annotation-config />

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name = "prefix" value = "/WEB-INF/views/" />
        <property name = "suffix" value = ".jsp" />
    </bean>

</beans>
</code>```

答:
your hibernate and spring config file add this property  <prop key="hibernate.hbm2ddl.auto">update</prop> ; for example：

```<code><bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
</code>```

Title: Hibernate 3 not auto creating tables

Body:
Here is my code:

hiberntae.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
  </session-factory>
</hibernate-configuration>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edu.bc.eagleapps</groupId>
    <artifactId>mavenproject1</artifactId>
    <version>1.2-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>mavenproject1</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springframework.version>4.0.6.RELEASE</springframework.version>
        <hibernate.version>3.6.9.Final</hibernate.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.18.2-GA</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-base</artifactId>
            <version>2.6.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Model

package app.model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_MASTER")
public class UserMaster {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column
private String id;

  @Column(length = 50, nullable = false, unique = true)
private String userid;

  @Column(length = 50, nullable = false, unique = true)
private String password;

public UserMaster() {}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }

When I try to save user via controller, I get the following error:

org.hibernate.exception.SQLGrammarException: could not insert: [app.model.UserMaster]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at coolcook.dao.UserMasterDao.saveUser(UserMasterDao.java:23)
at coolcook.service.UserMasterServiceImpl.saveUser(UserMasterServiceImpl.java:16)
at coolcook.controller.UserController.registerUser(UserController.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
a

t java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'app.USER_MASTER' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)

the database "app" exists, but whenever I try to save user through controller, it gives me above error.

I search through several answers on SO and other sites but not successful. Any help will be appreciated!

Dao

   package coolcook.dao;

import coolcook.model.UserMaster;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserMasterDao {

    @Autowired
    private SessionFactory sessionFactory;

    public UserMaster saveUser(UserMaster user) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            session.save(user);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
            }
            return user;
        }

    }

springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="app" />

    <mvc:default-servlet-handler />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
          p:url="jdbc:mysql://localhost:3306/app" p:username="root"
          p:password="root" />

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>app.model</value>
            </list>
        </property>

        <property name="configLocation">
            <value>WEB-INF/hibernate.cfg.xml</value>
        </property>

    </bean>

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:annotation-config />

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name = "prefix" value = "/WEB-INF/views/" />
        <property name = "suffix" value = ".jsp" />
    </bean>

</beans>

Body:
your hibernate and spring config file add this property  <prop key="hibernate.hbm2ddl.auto">update</prop> ; for example：

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>