问:
Return parent row then child rows in Oracle SQL query
I'm trying to return data from family in the following structure:

Parent A row

A's child 1 row

A's child 2 row

A's child 3 row

Parent B row

B's child 1 row

B's child 2 row

B's child 3 row

Family returns parent and child data all together, like:

1 parent A columns, A's child 1 columns

2 parents A columns, A's child 2 columns

3 parents A columns, A's child 3 columns

My attempts so far with connect by prior results in the error:

ORA-01436: CONNECT BY loop in user data

I suspect, but I'm not certain, that should be using connect by level instead, but each of my attempts with that fails.

What am I doing wrong? How can I achieve my desired format?

```<code>with parents
as (
    select *
    from view_sot sot
    where sot.tree = 'parent'
        and sot.xmode = 'E'
    ),
children
as (
    select *
    from view_sot sot
    where sot.tree = 'child'
        and sot.xmode != 'E'
    ),
family
as (
    select parents.srn psrn,
        parents.cand pcand,
        parents.ayrc payrc,
        parents.mod_code pmod_code,
        parents.mark pmark,
        parents.grade pgrade,
        parents.xmode pxmode,
        parents.mavo pmavo,
        parents.mod_name pmod_name,
        parents.prg_code pprg_code,
        parents.tree ptree,
        children.srn csrn,
        children.cand ccand,
        children.ayrc cayrc,
        children.mod_code cmod_code,
        children.mark cmark,
        children.grade cgrade,
        children.xmode cxmode,
        children.mavo cmavo,
        children.mod_name cmod_name,
        children.prg_code cprg_code,
        children.tree ctree
    from parents
    inner join children on parents.srn = children.srn
        and parents.mod_code = children.mod_code
        and parents.ayrc = children.ayrc
        and parents.cand = children.cand
        and parents.mavo = children.mavo
    where parents.srn = 'A012345678'
    )
select psrn,
    pxmode,
    pmod_code,
    cmod_code,
    cxmode,
    level
from family connect by prior cmod_code = pmod_code
</code>```

Many thanks

答:
Without any context or data in your question, I just built a silly example - is this what you want?

```<code>with family as
  (select 1 as id_num, 'Jay-Z' as the_name, 'parent' as who, 2 as family, 0 as parent_id from dual
    union all
   select 2 as id_num, 'Beyonce' as the_name, 'parent' as who, 2 as family,     0 as parent_id from dual
     union all
   select 11 as id_num, 'Blue Ivy' as the_name, 'child' as who, 2 as family,     1 as parent_id from dual
      union all
   select 11 as id_num, 'Blue Ivy' as the_name, 'child' as who, 2 as family,     2 as parent_id from dual
   union all
    select 22 as id_num, 'Upcoming Twin #1' as the_name, 'child' as who, 2     as family, 1 as parent_id from dual
   union all
    select 22 as id_num, 'Upcoming Twin #1' as the_name, 'child' as who, 2     as family, 2 as parent_id from dual
       union all
     select 33 as id_num, 'Upcoming Twin #2' as the_name, 'child' as who, 2     as family, 1 as parent_id from dual
   union all
    select 33 as id_num, 'Upcoming Twin #2' as the_name, 'child' as who, 2     as family, 2 as parent_id from dual)

select lpad('.',level*3-3,'.')||the_name
from family
where ((level = 1 and who = 'parent') or (level = 2))
connect by prior id_num = parent_id
order siblings by the_name;

OUTPUT >>>>
Beyonce
...Blue Ivy
...Upcoming Twin #1
...Upcoming Twin #2
Jay-Z
...Blue Ivy
...Upcoming Twin #1
...Upcoming Twin #2
</code>```

I'm unclear as to if you have multiple rows per child (one row per child per parent).... but hopefully this syntax will at least guide you.

Body:
I'm trying to return data from family in the following structure:

Parent A row

A's child 1 row

A's child 2 row

A's child 3 row

Parent B row

B's child 1 row

B's child 2 row

B's child 3 row

Family returns parent and child data all together, like:

1 parent A columns, A's child 1 columns

2 parents A columns, A's child 2 columns

3 parents A columns, A's child 3 columns

My attempts so far with connect by prior results in the error:

ORA-01436: CONNECT BY loop in user data

I suspect, but I'm not certain, that should be using connect by level instead, but each of my attempts with that fails.

What am I doing wrong? How can I achieve my desired format?

with parents
as (
    select *
    from view_sot sot
    where sot.tree = 'parent'
        and sot.xmode = 'E'
    ),
children
as (
    select *
    from view_sot sot
    where sot.tree = 'child'
        and sot.xmode != 'E'
    ),
family
as (
    select parents.srn psrn,
        parents.cand pcand,
        parents.ayrc payrc,
        parents.mod_code pmod_code,
        parents.mark pmark,
        parents.grade pgrade,
        parents.xmode pxmode,
        parents.mavo pmavo,
        parents.mod_name pmod_name,
        parents.prg_code pprg_code,
        parents.tree ptree,
        children.srn csrn,
        children.cand ccand,
        children.ayrc cayrc,
        children.mod_code cmod_code,
        children.mark cmark,
        children.grade cgrade,
        children.xmode cxmode,
        children.mavo cmavo,
        children.mod_name cmod_name,
        children.prg_code cprg_code,
        children.tree ctree
    from parents
    inner join children on parents.srn = children.srn
        and parents.mod_code = children.mod_code
        and parents.ayrc = children.ayrc
        and parents.cand = children.cand
        and parents.mavo = children.mavo
    where parents.srn = 'A012345678'
    )
select psrn,
    pxmode,
    pmod_code,
    cmod_code,
    cxmode,
    level
from family connect by prior cmod_code = pmod_code

Many thanks

Body:
Without any context or data in your question, I just built a silly example - is this what you want?

with family as
  (select 1 as id_num, 'Jay-Z' as the_name, 'parent' as who, 2 as family, 0 as parent_id from dual
    union all
   select 2 as id_num, 'Beyonce' as the_name, 'parent' as who, 2 as family,     0 as parent_id from dual
     union all
   select 11 as id_num, 'Blue Ivy' as the_name, 'child' as who, 2 as family,     1 as parent_id from dual
      union all
   select 11 as id_num, 'Blue Ivy' as the_name, 'child' as who, 2 as family,     2 as parent_id from dual
   union all
    select 22 as id_num, 'Upcoming Twin #1' as the_name, 'child' as who, 2     as family, 1 as parent_id from dual
   union all
    select 22 as id_num, 'Upcoming Twin #1' as the_name, 'child' as who, 2     as family, 2 as parent_id from dual
       union all
     select 33 as id_num, 'Upcoming Twin #2' as the_name, 'child' as who, 2     as family, 1 as parent_id from dual
   union all
    select 33 as id_num, 'Upcoming Twin #2' as the_name, 'child' as who, 2     as family, 2 as parent_id from dual)

select lpad('.',level*3-3,'.')||the_name
from family
where ((level = 1 and who = 'parent') or (level = 2))
connect by prior id_num = parent_id
order siblings by the_name;

OUTPUT >>>>
Beyonce
...Blue Ivy
...Upcoming Twin #1
...Upcoming Twin #2
Jay-Z
...Blue Ivy
...Upcoming Twin #1
...Upcoming Twin #2

I'm unclear as to if you have multiple rows per child (one row per child per parent).... but hopefully this syntax will at least guide you.


来源: stackexchange

问:
How to print variable multiple times with one printf statement in C
After searching stack overflow and going through several tutorials I still can't find out how to print a variable multiple time with one printf statement.

This is what I want to get as a result:

1111111111

2222222222

3333333333

by using something like this:

```<code>for(int i=1; i<4; i++)

{
    printf("%d", i);   //it would be great to add something here
}
</code>```

But without another for loop!

Or it can be easily asked like this, I want printf to print variable int i=1; multiple times in a row without loops. So output would be 1111111111

答:
So the answer is...it is not possible to do what I wanted on the way I wanted. The best way is to use another for loop inside existing one.

Thank you all for your answers.

ContentLicense: CC BY-SA 3.0

Body:
After searching stack overflow and going through several tutorials I still can't find out how to print a variable multiple time with one printf statement.

This is what I want to get as a result:

1111111111

2222222222

3333333333

by using something like this:

for(int i=1; i<4; i++)

{
    printf("%d", i);   //it would be great to add something here
}

But without another for loop!

Or it can be easily asked like this, I want printf to print variable int i=1; multiple times in a row without loops. So output would be 1111111111


问:
Vertical-align: middle not working?
Why isn't the vertical-align: middle; not working on my h1? The ul isn't aligning with the h1 and it should.

#logo {
 color: white;
 display: inline;
 vertical-align: middle;
}

ul {
 padding: 20px;
 background: rgba(0,0,0,.5);
}

#title {
 position: absolute;
 text-align: center;
 color: white;
 font-size: 50px;
 top: 100px;

}

#navbar {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-image: url('../img/bg.jpg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    height: 600px;
}

li {
 float: right;
 display: inline;
}

li a {
 display: inline;
 padding: 10px 10px 10px 20px;
 text-decoration: none;
 color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navbar">
  <ul>
   <h1 id="logo">Jordan Baron</h1>
   <li>About Me</li>
   <li>Contact</li>
   <li>Projects</li>
  </ul>

  <h1 id="title">Freelance Web Developer</h1>
 </div></code>```

答:
Ready for a bit of a mind flip?

Here comes FLEXBOX! This could be done "better" but I didn't want to change your html structure: https://jsfiddle.net/ohbffjjm/

#navbar {
  background-color: pink;
}

#logo {
  margin-right: 150px;
  align-self: flex-start;
}

ul {
  display: flex;
  align-items: center;
  list-style-type: none;
}

li a {
  padding: 10px 10px 10px 20px;
  text-decoration: none;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navbar">

  <ul>
    <h1 id="logo">Jordan Baron</h1>
    <li>About Me</li>
    <li>Contact</li>
    <li>Projects</li>
  </ul>

</div></code>```

Title: Vertical-align: middle not working?

Body:
Why isn't the vertical-align: middle; not working on my h1? The ul isn't aligning with the h1 and it should.

#logo {
 color: white;
 display: inline;
 vertical-align: middle;
}

ul {
 padding: 20px;
 background: rgba(0,0,0,.5);
}

#title {
 position: absolute;
 text-align: center;
 color: white;
 font-size: 50px;
 top: 100px;

}

#navbar {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-image: url('../img/bg.jpg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    height: 600px;
}

li {
 float: right;
 display: inline;
}

li a {
 display: inline;
 padding: 10px 10px 10px 20px;
 text-decoration: none;
 color: white;
}

Jordan Baron

About Me

Contact

Projects

Freelance Web Developer

Body:
Ready for a bit of a mind flip?

Here comes FLEXBOX! This could be done "better" but I didn't want to change your html structure: https://jsfiddle.net/ohbffjjm/

#navbar {
  background-color: pink;
}

#logo {
  margin-right: 150px;
  align-self: flex-start;
}

ul {
  display: flex;
  align-items: center;
  list-style-type: none;
}

li a {
  padding: 10px 10px 10px 20px;
  text-decoration: none;
  color: white;
}

<div id="navbar">

  <ul>
    <h1 id="logo">Jordan Baron</h1>
    <li><a href="#">About Me</a></li>
    <li><a href="#">Contact</a></li>
    <li><a href="#">Projects</a></li>
  </ul>

</div>


问:
how to automate non Java Script form for login into a mobile app?
I am trying to automate our mobile application(It is an angular app). We have recently implemented token server into all of our apps. The login form (spoof page) for our app is not a Java Script form. I am not sure how to automate that or may be skip that and write the code to go directly into the app. Kindly help.</p>

答:
You need to automate your login or ataff like that? You can embed your Angular App in a native mobile app? becouse is possible save de credential in a mobile and then pass that for your app in a webview. I use this thinks in Android.
Regards</p>


问:
Query database in select onchange
I'd like to know how can I approach this better and what are my options. I cannot use AJAX requests for this.

I have a dropdown select populated through a SELECT query from the Database. The dropdown displays the user's display_name as the label and their IDs as the value. So:

$('select').val() retrieves an ID.

My problem is I'd like to display the selected user's username (another column from the same database table) in the onchange event of the Dropdown select.

Am I approaching this incorrectly?

EDIT:

I'm usiing Advanced Custom Functions for Wordpress, so this is how I'm retrieving my select and populating it:

```<code>function acf_load_color_field_choices( $field ) {
    $field['choices'] = array();

    foreach ($query as $row) {
        $field['choices'][$row[ID]] = $row[display_name];
    }

    return $field;
}
add_filter('acf/load_field/name=select_name', 'acf_load_color_field_choices');
</code>```

Any idea if there's a way to add a data- attribute to this?

答:
Since it was faster than figuring out if the plugin provided the data-name attribute, I managed to resolve my problem by changing my logic around.

Instead of passing the ID as a value, I've passed the username as a value. Then on the receiving end, I did a query to get the ID based on the username (since username is unique).

Title: Query database in select onchange

Body:
I'd like to know how can I approach this better and what are my options. I cannot use AJAX requests for this.

I have a dropdown select populated through a SELECT query from the Database. The dropdown displays the user's display_name as the label and their IDs as the value. So:

$('select').val() retrieves an ID.

My problem is I'd like to display the selected user's username (another column from the same database table) in the onchange event of the Dropdown select.

Am I approaching this incorrectly?

EDIT:

I'm usiing Advanced Custom Functions for Wordpress, so this is how I'm retrieving my select and populating it:

function acf_load_color_field_choices( $field ) {
    $field['choices'] = array();

    foreach ($query as $row) {
        $field['choices'][$row[ID]] = $row[display_name];
    }

    return $field;
}
add_filter('acf/load_field/name=select_name', 'acf_load_color_field_choices');

Any idea if there's a way to add a data- attribute to this?


问:
Implicit typeconversion and polymorphy
I'm currently building a small library for state machines (yeah, there are lots of those, but I'm in it for the fun). Now, I've encountered an interesting problem.

Assume, that a given statemachine accepts events of a certain type. If we were to parse a protocol this might, e.g. be characters. So in a certain state the character 'a' might lead to a new state, while all other characters (or a group of characters) remain in that state (e.g. Receive the payload of a packet, while no ETX was received).

My statemachine is defined similar to how Boost::MSM does it, i.e: a list of transitions with the events that trigger them:

```<code>        var S1 = new BasicTState<char>("S1");
        var S2 = new BasicTState<char>("S2");

        var transitions = new[]
        {
            new TTransition<char>{from = S1, to = S2, evt = 'b', guard = null },
            new TTransition<char>{from = S2, to = S1, evt = 'a', guard = null },
        };

        // The type parameter denotes the type of event, that is to be accepted.
        // the second parameter is the initial state!
        var sm = new TStateMachine<char>(transitions, S1);

        sm.Event('b');

        Assert.AreEqual(sm.ActiveState, S2);
</code>```

So far so good - now. Given the situation, where I want several e.g. characters, to match to the same statetransition I'm a bit stuck. The naive way would be to define a statetransition for each and every character to accept - which is tedious and errorprone. What I would like to do is use "Matcher" objects that will do that job, e.g.:

```<code>            var transitions = new[]
        {
            new TTransition<Matcher<char>>{from = S1, to = S2, evt = new Matcher<char>(new[] {'c', 'd'}), guard = null },
            new TTransition<Matcher<char>>{from = S2, to = S1, evt = new Matcher<char>(new[] {'e', 'f'}), guard = null },

        };
</code>```

To get this to work I've defined implicit conversions for the matcher, so that I can still generate events like in the above example, i.e. "sm.Event('c')". This works just fine. However now I'm in a situation where my statemachine object must be of the type TStateMachine<Matcher<char>> which is obviously annoying since I now cannot use a simple notation for cases, where only one eventtype needs to be matched and I can only ever use a single type of matcher and the implicit typeconversion will always force me into this one type. Worse, I cannot hide the matcher behind an interface because the typeconversion won't play with that at all.

I'm aware, that I could solve the problem of matching single and multiple eventtypes easily using interfaces, but that would compromise the readability quite a bit (and, quite frankly, it's no fun to solve it that way). What I'm really interested in is, if there is any way to get polymorphy to play nicely with implicit typeconversion. I'd imagine ending up with something like:

```<code>    var transitions = new[]
    {
        new TTransition<char>{from = S1, to = S2, evt = 'b', guard = null },
        new TTransition<char>{from = S2, to = S1, evt = new Matcher<char>(new[] {'e', 'f'}), guard = null },
        new TTransition<char>{from = S2, to = S1, evt = new YetAnotherMatcherTypeIDontKnowAboutYet<char>(new YadaYadaObject()), guard = null }
    };
</code>```

答:
Does the state itself need the generic type parameter? Why should the state need to know how it was triggered?

I would declare the transition type like this

```<code>public class Transition<TEvent>
{
    public BasicState From { get; set; }
    public BasicState To { get; set; }
    public Func<TEvent, bool> EventMatcher { get; set; }
    ...
}
</code>```

and the state machine like this

```<code>public class StateMachine<TEvent>
{
    public StateMachine(Transition<TEvent>[] transitions, BasicState initialState)
    {
        ...
    }

    ...
}
</code>```

and the transitions would always declare a matcher, even in the simple case where a single character is used

```<code>var transitions = new[]
{
    new Transition<char>{From = S1, To = S2, EventMatcher = c => c == 'b', Guard = null },
    new Transition<char>{From = S2, To = S1, EventMatcher = c => c == 'a', Guard = null },
};
</code>```

If you need to match several characters you can write

```<code>new Transition<char>{From = S2, To = S1, EventMatcher = c => "ef".Contains(c), Guard = null }
</code>```

Note, I've used Lambda Expressions (with the => syntax).

I've omitted the "T" prefix from the type names, as this is not usual in C# (it's usual in Pascal). Also, properties should be in PascalCase, even in C# :-). See Naming Guidelines on MSDN.

Alternatively, you could declare different types of transitions. They would be responsible for the matching themselves

```<code>public abstract class TransitionBase<TEvent>
    where TEvent : IEquatable<TEvent>
{
    public BasicState From { get; set; }
    public BasicState To { get; set; }
    public abstract bool DoesMatchEvent(TEvent event);
}

public class SingleEventTransition<TEvent> : TransitionBase<TEvent>
    where TEvent : IEquatable<TEvent>
{
    TEvent Event { get; set; }
    public override bool DoesMatchEvent(TEvent event)
    {
        return Event.Equals(event);
    }
}

public class MultiEventTransition<TEvent> : TransitionBase<TEvent>
    where TEvent : IEquatable<TEvent>
{
    TEvent[] Events { get; set; }
    public override bool DoesMatchEvent(TEvent event)
    {
        foreach (TEvent e in Events) {
            if (e.Equals(event)) {
                return true;
            }
        }
        return false;
    }
}
</code>```

Note that since you don't know the real type of TEvent in advance, you cannot work with it as if it was a char; however, you can specify a generic type constraint requiring the type to be equatable, i.e. to provide an Equals method. The basic types like char, int, string do. If you implement your own event type, you can implement the IEquatable<T> interface yourself.

```<code>TransitionBase<char>[] transitions = new[]
{
    new SingleEventTransition<char>{From = S1, To = S2, Event = 'b', Guard = null },
    new MultiEventTransition<char>{From = S2, To = S1, Events = new TEvent[]{ 'e', 'f'},
                                   Guard = null },
};
</code>```

Title: Implicit typeconversion and polymorphy

Body:
I'm currently building a small library for state machines (yeah, there are lots of those, but I'm in it for the fun). Now, I've encountered an interesting problem.

Assume, that a given statemachine accepts events of a certain type. If we were to parse a protocol this might, e.g. be characters. So in a certain state the character 'a' might lead to a new state, while all other characters (or a group of characters) remain in that state (e.g. Receive the payload of a packet, while no ETX was received).

My statemachine is defined similar to how Boost::MSM does it, i.e: a list of transitions with the events that trigger them:

        var S1 = new BasicTState<char>("S1");
        var S2 = new BasicTState<char>("S2");

        var transitions = new[]
        {
            new TTransition<char>{from = S1, to = S2, evt = 'b', guard = null },
            new TTransition<char>{from = S2, to = S1, evt = 'a', guard = null },
        };

        // The type parameter denotes the type of event, that is to be accepted.
        // the second parameter is the initial state!
        var sm = new TStateMachine<char>(transitions, S1);

        sm.Event('b');

        Assert.AreEqual(sm.ActiveState, S2);

So far so good - now. Given the situation, where I want several e.g. characters, to match to the same statetransition I'm a bit stuck. The naive way would be to define a statetransition for each and every character to accept - which is tedious and errorprone. What I would like to do is use "Matcher" objects that will do that job, e.g.:

            var transitions = new[]
        {
            new TTransition<Matcher<char>>{from = S1, to = S2, evt = new Matcher<char>(new[] {'c', 'd'}), guard = null },
            new TTransition<Matcher<char>>{from = S2, to = S1, evt = new Matcher<char>(new[] {'e', 'f'}), guard = null },

        };

To get this to work I've defined implicit conversions for the matcher, so that I can still generate events like in the above example, i.e. "sm.Event('c')". This works just fine. However now I'm in a situation where my statemachine object must be of the type TStateMachine<Matcher<char>> which is obviously annoying since I now cannot use a simple notation for cases, where only one eventtype needs to be matched and I can only ever use a single type of matcher and the implicit typeconversion will always force me into this one type. Worse, I cannot hide the matcher behind an interface because the typeconversion won't play with that at all.

I'm aware, that I could solve the problem of matching single and multiple eventtypes easily using interfaces, but that would compromise the readability quite a bit (and, quite frankly, it's no fun to solve it that way). What I'm really interested in is, if there is any way to get polymorphy to play nicely with implicit typeconversion. I'd imagine ending up with something like:

    var transitions = new[]
    {
        new TTransition<char>{from = S1, to = S2, evt = 'b', guard = null },
        new TTransition<char>{from = S2, to = S1, evt = new Matcher<char>(new[] {'e', 'f'}), guard = null },
        new TTransition<char>{from = S2, to = S1, evt = new YetAnotherMatcherTypeIDontKnowAboutYet<char>(new YadaYadaObject()), guard = null }
    };

Body:
Does the state itself need the generic type parameter? Why should the state need to know how it was triggered?

I would declare the transition type like this

public class Transition<TEvent>
{
    public BasicState From { get; set; }
    public BasicState To { get; set; }
    public Func<TEvent, bool> EventMatcher { get; set; }
    ...
}

and the state machine like this

public class StateMachine<TEvent>
{
    public StateMachine(Transition<TEvent>[] transitions, BasicState initialState)
    {
        ...
    }

    ...
}

and the transitions would always declare a matcher, even in the simple case where a single character is used

var transitions = new[]
{
    new Transition<char>{From = S1, To = S2, EventMatcher = c => c == 'b', Guard = null },
    new Transition<char>{From = S2, To = S1, EventMatcher = c => c == 'a', Guard = null },
};

If you need to match several characters you can write

new Transition<char>{From = S2, To = S1, EventMatcher = c => "ef".Contains(c), Guard = null }

Note, I've used Lambda Expressions (with the => syntax).

I've omitted the "T" prefix from the type names, as this is not usual in C# (it's usual in Pascal). Also, properties should be in PascalCase, even in C# :-). See Naming Guidelines on MSDN.

Alternatively, you could declare different types of transitions. They would be responsible for the matching themselves

public abstract class TransitionBase<TEvent>
    where TEvent : IEquatable<TEvent>
{
    public BasicState From { get; set; }
    public BasicState To { get; set; }
    public abstract bool DoesMatchEvent(TEvent event);
}

public class SingleEventTransition<TEvent> : TransitionBase<TEvent>
    where TEvent : IEquatable<TEvent>
{
    TEvent Event { get; set; }
    public override bool DoesMatchEvent(TEvent event)
    {
        return Event.Equals(event);
    }
}

public class MultiEventTransition<TEvent> : TransitionBase<TEvent>
    where TEvent : IEquatable<TEvent>
{
    TEvent[] Events { get; set; }
    public override bool DoesMatchEvent(TEvent event)
    {
        foreach (TEvent e in Events) {
            if (e.Equals(event)) {
                return true;
            }
        }
        return false;
    }
}

Note that since you don't know the real type of TEvent in advance, you cannot work with it as if it was a char; however, you can specify a generic type constraint requiring the type to be equatable, i.e. to provide an Equals method. The basic types like char, int, string do. If you implement your own event type, you can implement the IEquatable<T> interface yourself.

TransitionBase<char>[] transitions = new[]
{
    new SingleEventTransition<char>{From = S1, To = S2, Event = 'b', Guard = null },
    new MultiEventTransition<char>{From = S2, To = S1, Events = new TEvent[]{ 'e', 'f'},
                                   Guard = null },
};


问:
Android App button press not functioning correctly
Being brand new to Java I'm not sure why this when called with android:onClick="changeInfo" isn't changing the text view back to the original value.

```<code>public class JavaTest extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_java_test);
}
public void changeInfo(View view){
    setContentView(R.layout.activity_java_test);
    TextView t = (TextView)findViewById(R.id.textSpace1);
    if (t.getText()==getResources().getString(R.string.lorem_ipsum)){
        t.setText("[Email Here]");
    }
    else{
        t.setText(getResources().getString(R.string.lorem_ipsum));
    }
}
</code>```

Could anyone help, thank you.

答:
setContentView(R.layout.activity_java_test);

You don't have to call setContentView inside changeInfo method

t.getText()==getResources().getString(R.string.lorem_ipsum)

it should be t.getText().toString().equeals(getResources().getString(R.string.lorem_ipsum))

Try this

```<code>  public class JavaTest extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_java_test);
}
public void changeInfo(View view){

    TextView t = (TextView)findViewById(R.id.textSpace1);
    if (t.getText().toString().equeals(getResources().getString(R.string.lorem_ipsum))){
        t.setText("[Email Here]");
    }
    else{
        t.setText(getResources().getString(R.string.lorem_ipsum));
    }
}
</code>```

Body:
Being brand new to Java I'm not sure why this when called with android:onClick="changeInfo" isn't changing the text view back to the original value.

public class JavaTest extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_java_test);
}
public void changeInfo(View view){
    setContentView(R.layout.activity_java_test);
    TextView t = (TextView)findViewById(R.id.textSpace1);
    if (t.getText()==getResources().getString(R.string.lorem_ipsum)){
        t.setText("[Email Here]");
    }
    else{
        t.setText(getResources().getString(R.string.lorem_ipsum));
    }
}

Could anyone help, thank you.

Body:
setContentView(R.layout.activity_java_test);

You don't have to call setContentView inside changeInfo method

t.getText()==getResources().getString(R.string.lorem_ipsum)

it should be t.getText().toString().equeals(getResources().getString(R.string.lorem_ipsum))

Try this

  public class JavaTest extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_java_test);
}
public void changeInfo(View view){

    TextView t = (TextView)findViewById(R.id.textSpace1);
    if (t.getText().toString().equeals(getResources().getString(R.string.lorem_ipsum))){
        t.setText("[Email Here]");
    }
    else{
        t.setText(getResources().getString(R.string.lorem_ipsum));
    }
}


问:
Input type=password, don't let browser remember the password
I remember seeing a way to have an <input type="password" /> such that the browser will not prompt the user to save the password. But I'm drawing a blank. Is there an HTML attribute or some JavaScript trick that will do this?

答:
I've found the following works on Firefox and Chrome.

```<code><form ... > <!-- more stuff -->
<input name="person" type="text" size=30 value="">
<input name="mypswd" type="password" size=6 value="" autocomplete="off">
<input name="userid" type="text" value="security" style="display:none">
<input name="passwd" type="password" value="faker" style="display:none">
<!-- more stuff --> </form>
</code>```

All of these are within the forms section. "person" and "mypswd" are what you want, but the browser will save "userid" and "passwd" once, and never again since they don't change. You could eliminate the "person" field if you don't really need it. In that case, all you want is the "mypswd" field, which could change in some way known to the user of your web-page.

OwnerDisplayName: David Thomas Garcia

Body:
I've found the following works on Firefox and Chrome.

<form ... > <!-- more stuff -->
<input name="person" type="text" size=30 value="">
<input name="mypswd" type="password" size=6 value="" autocomplete="off">
<input name="userid" type="text" value="security" style="display:none">
<input name="passwd" type="password" value="faker" style="display:none">
<!-- more stuff --> </form>

All of these are within the forms section. "person" and "mypswd" are what you want, but the browser will save "userid" and "passwd" once, and never again since they don't change. You could eliminate the "person" field if you don't really need it. In that case, all you want is the "mypswd" field, which could change in some way known to the user of your web-page.


问:
Android manage multi request rxJava on rotation device
I'm using MVVM on android application and i want to manage requests and rxJava on device rotation, how can i disable request after rotation device and countinue from last request?

this is my simple code to know how can i doing that, but i can't find any document and sample code about it

```<code>@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_register);
    ...
    Observer<String> myObserver = new Observer<String>() {
        @Override
        public void onError(Throwable e) {
            // Called when the observable encounters an error
        }

        @Override
        public void onComplete() {

        }

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String s) {
            // Called each time the observable emits data
            Log.e("MY OBSERVER", s);
        }
    };

    Observable.just("Hello").subscribe(myObserver);
}
</code>```

I'm using latest version of rxJava

答:
How I'm doing this is to have a singleton class (or any long living Object as explained by savepopulation earlier, but - the trick is to store the loaded data in a BehaviorSubject, and subscribe to that subject in the Activity instead of the original network request.

This way:

```<code>public class MyNetworkSingleton {
  // This static service survives orientation changes
  public static MyNetworkSingleton INSTANCE = new MyNetworkSingleton();

  private final BehaviorSubject<String> dataSubject = BehaviorSubject.create();

  public Observable<String> getData() {
     if (!dataSubject.hasValue()) {
        refreshData(); // No data is loaded yet, load initial data from network
     }

     return dataSubject;
  }

  public void refreshData() {
     someDataSourceCall().subscribe(new Observer<String>() {
       @Override
       public void onError(Throwable e) {
           // Remember, this point also needs error handling of some form,
           // e.g. propagating the error to the UI as a Toast
       }

       @Override
       public void onComplete() {

       }

       @Override
       public void onSubscribe(Disposable d) {

       }

       @Override
       public void onNext(String data) {
          dataSubject.onNext(data); // this refreshes the internally stored data
       }
     });
  }

  private Observable<String> someDataSourceCall() {
     return // some network request here etc. where you get your data from
  }
}
</code>```

and then:

```<code>@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    Observer<String> myObserver = new Observer<String>() {
        @Override
        public void onError(Throwable e) {
            // Called when the observable encounters an error
        }

        @Override
        public void onComplete() {

        }

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String s) {
            // Called each time the observable emits data
            Log.e("MY OBSERVER", s);
        }
    };

    MyNetworkSingleton.INSTANCE.getData().subscribe(myObserver);

    myRefreshButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            // refresh data from network only when button is pressed
            MyNetworkSingleton.INSTANCE.refreshData();
        }
    });
}
</code>```

This way only first time you need the data from network it will be loaded, or when the user clicks a refresh button (myRefreshButton).

Body:
I'm using MVVM on android application and i want to manage requests and rxJava on device rotation, how can i disable request after rotation device and countinue from last request?

this is my simple code to know how can i doing that, but i can't find any document and sample code about it

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_register);
    ...
    Observer<String> myObserver = new Observer<String>() {
        @Override
        public void onError(Throwable e) {
            // Called when the observable encounters an error
        }

        @Override
        public void onComplete() {

        }

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String s) {
            // Called each time the observable emits data
            Log.e("MY OBSERVER", s);
        }
    };

    Observable.just("Hello").subscribe(myObserver);
}

I'm using latest version of rxJava

Body:
How I'm doing this is to have a singleton class (or any long living Object as explained by savepopulation earlier, but - the trick is to store the loaded data in a BehaviorSubject, and subscribe to that subject in the Activity instead of the original network request.

This way:

public class MyNetworkSingleton {
  // This static service survives orientation changes
  public static MyNetworkSingleton INSTANCE = new MyNetworkSingleton();

  private final BehaviorSubject<String> dataSubject = BehaviorSubject.create();

  public Observable<String> getData() {
     if (!dataSubject.hasValue()) {
        refreshData(); // No data is loaded yet, load initial data from network
     }

     return dataSubject;
  }

  public void refreshData() {
     someDataSourceCall().subscribe(new Observer<String>() {
       @Override
       public void onError(Throwable e) {
           // Remember, this point also needs error handling of some form,
           // e.g. propagating the error to the UI as a Toast
       }

       @Override
       public void onComplete() {

       }

       @Override
       public void onSubscribe(Disposable d) {

       }

       @Override
       public void onNext(String data) {
          dataSubject.onNext(data); // this refreshes the internally stored data
       }
     });
  }

  private Observable<String> someDataSourceCall() {
     return // some network request here etc. where you get your data from
  }
}

and then:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    Observer<String> myObserver = new Observer<String>() {
        @Override
        public void onError(Throwable e) {
            // Called when the observable encounters an error
        }

        @Override
        public void onComplete() {

        }

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String s) {
            // Called each time the observable emits data
            Log.e("MY OBSERVER", s);
        }
    };

    MyNetworkSingleton.INSTANCE.getData().subscribe(myObserver);

    myRefreshButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            // refresh data from network only when button is pressed
            MyNetworkSingleton.INSTANCE.refreshData();
        }
    });
}

This way only first time you need the data from network it will be loaded, or when the user clicks a refresh button (myRefreshButton).


问:
findAll throwing error
I am using a simple findAll query in my ember application ( ember-version: 2.12.0, ember-data-version: 2.12.1 ) and I get the following error:

Assertion Failed: You can no longer pass a modelClass as the first argument to store.buildInternalModel. Pass modelName instead.

I am using the RESTAdapter and RESTSerializer.

Here is my team model:

```<code>import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),

  projects: DS.hasMany('project'),
  users: DS.hasMany('user'),
  members: Ember.computed('users', function() {
    return this.get('users.content.length');
  }),
  leader: DS.belongsTo('user', {
    inverse: 'team'
  })
});
</code>```

and my team serializer:

```<code>import ApplicationSerializer from './application';
import DS from 'ember-data';

export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin,{
  attrs: {
    users: { async: true },
    projects: { async: true }
  }
});
</code>```

Despite the error, the team objects I requested are in the store. I had no luck in solving this so far.

答: Actually the problem was in the serializer and the payload from the server. I should have attrs: {users: {embedded: 'always'}} as users where in the payload from the server. </p>

Title: findAll throwing error

Body:
I am using a simple findAll query in my ember application ( ember-version: 2.12.0, ember-data-version: 2.12.1 ) and I get the following error:

Assertion Failed: You can no longer pass a modelClass as the first argument to store.buildInternalModel. Pass modelName instead.

I am using the RESTAdapter and RESTSerializer.

Here is my team model:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),

  projects: DS.hasMany('project'),
  users: DS.hasMany('user'),
  members: Ember.computed('users', function() {
    return this.get('users.content.length');
  }),
  leader: DS.belongsTo('user', {
    inverse: 'team'
  })
});

and my team serializer:

import ApplicationSerializer from './application';
import DS from 'ember-data';

export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin,{
  attrs: {
    users: { async: true },
    projects: { async: true }
  }
});

Despite the error, the team objects I requested are in the store. I had no luck in solving this so far.


问:
RxAndroid - retry observable on click
I'm using rxAndroid and rxKotlin in my Android app to handle network requests asynchronously. Now I would like to retry a failed network request only after click on Snackbar button.

My code now:

```<code>val citiesService = ApiFactory.citiesService

citiesService.cities()
    .subscribeOn(Schedulers.newThread()) // fetch List<String>
    .flatMap { Observable.from(it) }     // convert to sequence of String
    .flatMap { city ->
        citiesService.coordinates(city)  // fetch DoubleArray
            .map { City(city, it) }      // convert to City(String, DoubleArray)
        }
    .toList()
    .observeOn(AndroidSchedulers.mainThread())
    .doOnNext {
        listView.setOnItemClickListener { adapterView, view, position, id ->
            onItemClick(it[position])
        }
    }
    .map { it.map { it.getName(activity) } }
    .subscribe(
        { listAdapter = setupAdapter(it) },
        { showErrorSnackbar() }  // handle error
    )

fun showErrorSnackbar() {
        Snackbar.make(listView, getString(R.string.not_available_msg), Snackbar.LENGTH_INDEFINITE)
                .setAction(getString(R.string.snack_retry_btn), {
                    // retry observable
                })
                .show()
    }
</code>```

Cities interface for retrofit:

```<code>interface CitiesService {

    @GET("api/v1/cities")
    fun cities(): Observable<List<String>>

    @GET("api/v1/cities/{city}/coordinates")
    fun coordinates(@Path("city") city: String): Observable<DoubleArray>
}
</code>```

Api factory:

```<code>object ApiFactory {

    val citiesService: CitiesService
        get() = retrofit.create(CitiesService::class.java)

    private val retrofit: Retrofit
        get() = Retrofit
            .Builder()
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASE_URL)
            .build()
}
</code>```

How can I restart the observable in such way?

答:
I can suggest you truly reactive way instead of imperative way.

Insert this code right after subscribe() method:

```<code>.retryWhen(retryHandler ->
           retryHandler.flatMap(nothing -> retrySubject.asObservable()))
.subscribe()
</code>```

Where update subject is just:

```<code>@NonNull
private final PublishSubject<Void> retrySubject = PublishSubject.create();
</code>```

And on snackbar click call this method:

```<code>public void update() {
    retrySubject.onNext(null);
}
</code>```

Everything above the retryWhen method will be literally redone.

Though with this approach error will never go down to the subscriber, you can add error conditioning to the retryHandler flat map, but this is another story.

P.S. sorry, this was Java code with retrolambdas, but you'll easily convert this to Kotlin.

Title: RxAndroid - retry observable on click

Body:
I'm using rxAndroid and rxKotlin in my Android app to handle network requests asynchronously. Now I would like to retry a failed network request only after click on Snackbar button.

My code now:

val citiesService = ApiFactory.citiesService

citiesService.cities()
    .subscribeOn(Schedulers.newThread()) // fetch List<String>
    .flatMap { Observable.from(it) }     // convert to sequence of String
    .flatMap { city ->
        citiesService.coordinates(city)  // fetch DoubleArray
            .map { City(city, it) }      // convert to City(String, DoubleArray)
        }
    .toList()
    .observeOn(AndroidSchedulers.mainThread())
    .doOnNext {
        listView.setOnItemClickListener { adapterView, view, position, id ->
            onItemClick(it[position])
        }
    }
    .map { it.map { it.getName(activity) } }
    .subscribe(
        { listAdapter = setupAdapter(it) },
        { showErrorSnackbar() }  // handle error
    )

fun showErrorSnackbar() {
        Snackbar.make(listView, getString(R.string.not_available_msg), Snackbar.LENGTH_INDEFINITE)
                .setAction(getString(R.string.snack_retry_btn), {
                    // retry observable
                })
                .show()
    }

Cities interface for retrofit:

interface CitiesService {

    @GET("api/v1/cities")
    fun cities(): Observable<List<String>>

    @GET("api/v1/cities/{city}/coordinates")
    fun coordinates(@Path("city") city: String): Observable<DoubleArray>
}

Api factory:

object ApiFactory {

    val citiesService: CitiesService
        get() = retrofit.create(CitiesService::class.java)

    private val retrofit: Retrofit
        get() = Retrofit
            .Builder()
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASE_URL)
            .build()
}

How can I restart the observable in such way?

Body:
I can suggest you truly reactive way instead of imperative way.

Insert this code right after subscribe() method:

.retryWhen(retryHandler ->
           retryHandler.flatMap(nothing -> retrySubject.asObservable()))
.subscribe()

Where update subject is just:

@NonNull
private final PublishSubject<Void> retrySubject = PublishSubject.create();

And on snackbar click call this method:

public void update() {
    retrySubject.onNext(null);
}

Everything above the retryWhen method will be literally redone.

Though with this approach error will never go down to the subscriber, you can add error conditioning to the retryHandler flat map, but this is another story.

P.S. sorry, this was Java code with retrolambdas, but you'll easily convert this to Kotlin.


问:
How to execute laravel artisan commands in linux server
I have uploaded my project on a Linux server, but I don't know how to execute Laravel commands on the server.

Commands:

```<code>php artisan migrate
php artisan migrate:rollback
php artisan migrate:reset
php artisan migrate:refresh
php artisan db:seed
</code>```

答:
If the lemp stack is installed along with composer. Run composer install Then the command should be available.

https://www.digitalocean.com/community/tutorials/how-to-install-laravel-with-an-nginx-web-server-on-ubuntu-14-04

Body:
I have uploaded my project on a Linux server, but I don't know how to execute Laravel commands on the server.

Commands:

php artisan migrate
php artisan migrate:rollback
php artisan migrate:reset
php artisan migrate:refresh
php artisan db:seed


问:
Is there a plugin that allows me to automatically unminify the Javascript included on a site?
Is there a plugin, add-on, Greasemonkey script or something similar (at worst, an easy to use proxy?) that automatically unminifies the Javascript files included on a site?

I know about e.g. jsbeautifier.org but doing this externally doesn't allow me to set breakpoints in the unminified code, for example.

Typical use cases for me:

Analysing and learning from complex web frontends.

Debugging Greasemonkey scripts which interact with the existing code.

I'm primarily interested in a solution that works with Firebug, but if there's something for the dev tools of Chrome or Opera, I'd like to hear about it as well.

答:
Venkman JavaScript debugger has a pretty-printer.

There is also an extension for Fiddler proxy.

IE9 developer tools also have a "format javascript" option (see "F12 Developer Tools and Formatting Minified Script" here)

ContentLicense: CC BY-SA 2.5


问:
Adding multiple reactive plots and tables to Shiny app
I am working on a Shiny app and as I go I have been adding figures and tables in a haphazard way. I would like to have a better framework so that I can flexibly add reactive figures and tables to the output as it develops further.

At the moment I have been using tabPanel and fluidrow to add additional a summary table and a second plot. However I have had trouble adapting this. For example I currently generate 3 plots but have only able to plot 2 at a time. Could anyone show me a way to modify the code to display all three plots (distPlot1, distPlot2, distPlot3) and the summary table on the same page? Ideally in a way that it would be simple to add additional tables and plots in the future.

Thank you in advance.

My current code is below.

ui.R

```<code>library(reshape2)
library(shiny)
library(ggplot2)
# Define UI for application that draws a histogram
fluidPage(

  # Application title
  titlePanel("Mutation Probability"),

  # Sidebar with a slider input for the number of bins
  sidebarLayout(
    sidebarPanel(
      sliderInput("x", "Probability of mutation (per bp):",
                  min=1/1000000000000, max=1/1000, value=1/10000000),

      sliderInput("y", "Size of region (bp):",
                  min = 10, max = 10000, value = 1000, step= 100),

      sliderInput("z", "Number of samples:",
                  min = 1, max = 100000, value = 1000, step= 10)

    ),

    # Show a plot of the generated distribution
    mainPanel(
      tabsetPanel(
        tabPanel("Plot",
          fluidRow(
            splitLayout(cellWidths = c("50%", "50%"), plotOutput("distPlot1"), plotOutput("distPlot3"), plotOutput("distPlot3)"))
          )),
        tabPanel("Summary",  verbatimTextOutput("summary"))
      )
    )
  )
)
</code>```

server.R

```<code>server <- function(input, output) {

  mydata <- reactive({
    x <- input$x
    y <- input$y
    z <- input$z
    Muts <- as.data.frame(rpois(100,(x*y*z)))
    Muts
  })

  output$distPlot1 <- renderPlot({
    Muts <- mydata()
    ggplot(Muts, aes(Muts)) + geom_density() +xlab("Observed variants")
  })

  output$distPlot2 <-renderPlot({
    Muts <- mydata()
    ggplot(Muts, aes(Muts)) + geom_histogram() + xlab("Observed variants")
  })
  #get a boxplot working
  output$distPlot3 <-renderPlot({
    Muts <- mydata()
    ggplot(data= melt(Muts), aes(variable, value)) + geom_boxplot() + xlab("Observed variants")
  })

  output$summary <- renderPrint({
    Muts <- mydata()
    summary(Muts)
  })

}
</code>```

答:
I like laying out the graphics in the server using tools like grid.arrange from the package gridExtra or the package cowplot - they offer a lot of layout flexiblity. This for example:

```<code>library(reshape2)
library(shiny)
library(ggplot2)
library(gridExtra)
# Define UI for application that draws a histogram

u <- fluidPage(

  # Application title
  titlePanel("Mutation Probability"),

  # Sidebar with a slider input for the number of bins
  sidebarLayout(
    sidebarPanel(
      sliderInput("x", "Probability of mutation (per bp):",
                  min=1/1000000000000, max=1/1000, value=1/10000000),

      sliderInput("y", "Size of region (bp):",
                  min = 10, max = 10000, value = 1000, step= 100),

      sliderInput("z", "Number of samples:",
                  min = 1, max = 100000, value = 1000, step= 10)

    ),

    # Show a plot of the generated distribution
    mainPanel(
      tabsetPanel(
        tabPanel("Plot",
                 fluidRow(
                   plotOutput("distPlot4"),
                   verbatimTextOutput("summary"))
                 )),
        tabPanel("Summary",  verbatimTextOutput("summary1"))
      )
    )
  )
)
s <- function(input, output) {

  mydata <- reactive({
    x <- input$x
    y <- input$y
    z <- input$z
    Muts <- as.data.frame(rpois(100,(x*y*z)))
    Muts
  })
  output$distPlot4 <- renderPlot({
    Muts <- mydata()
    p1 <- ggplot(Muts, aes(Muts)) + geom_density() +xlab("Observed variants")
    p2 <- ggplot(Muts, aes(Muts)) + geom_histogram() + xlab("Observed variants")
    p3 <- ggplot(data= melt(Muts), aes(variable, value)) + geom_boxplot() + xlab("Observed variants")
    grid.arrange(p1,p2,p3, ncol=3,widths = c(2,1,1))
  })
  output$summary <- renderPrint({
    Muts <- mydata()
    summary(Muts)
  })
}
shinyApp(u,s)
</code>```

which yields:

For summary tables, I just add them to the bottom, one after the other, not much else you can do there I think.

Body:
I am working on a Shiny app and as I go I have been adding figures and tables in a haphazard way. I would like to have a better framework so that I can flexibly add reactive figures and tables to the output as it develops further.

At the moment I have been using tabPanel and fluidrow to add additional a summary table and a second plot. However I have had trouble adapting this. For example I currently generate 3 plots but have only able to plot 2 at a time. Could anyone show me a way to modify the code to display all three plots (distPlot1, distPlot2, distPlot3) and the summary table on the same page? Ideally in a way that it would be simple to add additional tables and plots in the future.

Thank you in advance.

My current code is below.

ui.R

library(reshape2)
library(shiny)
library(ggplot2)
# Define UI for application that draws a histogram
fluidPage(

  # Application title
  titlePanel("Mutation Probability"),

  # Sidebar with a slider input for the number of bins
  sidebarLayout(
    sidebarPanel(
      sliderInput("x", "Probability of mutation (per bp):",
                  min=1/1000000000000, max=1/1000, value=1/10000000),

      sliderInput("y", "Size of region (bp):",
                  min = 10, max = 10000, value = 1000, step= 100),

      sliderInput("z", "Number of samples:",
                  min = 1, max = 100000, value = 1000, step= 10)

    ),

    # Show a plot of the generated distribution
    mainPanel(
      tabsetPanel(
        tabPanel("Plot",
          fluidRow(
            splitLayout(cellWidths = c("50%", "50%"), plotOutput("distPlot1"), plotOutput("distPlot3"), plotOutput("distPlot3)"))
          )),
        tabPanel("Summary",  verbatimTextOutput("summary"))
      )
    )
  )
)

server.R

server <- function(input, output) {

  mydata <- reactive({
    x <- input$x
    y <- input$y
    z <- input$z
    Muts <- as.data.frame(rpois(100,(x*y*z)))
    Muts
  })

  output$distPlot1 <- renderPlot({
    Muts <- mydata()
    ggplot(Muts, aes(Muts)) + geom_density() +xlab("Observed variants")
  })

  output$distPlot2 <-renderPlot({
    Muts <- mydata()
    ggplot(Muts, aes(Muts)) + geom_histogram() + xlab("Observed variants")
  })
  #get a boxplot working
  output$distPlot3 <-renderPlot({
    Muts <- mydata()
    ggplot(data= melt(Muts), aes(variable, value)) + geom_boxplot() + xlab("Observed variants")
  })

  output$summary <- renderPrint({
    Muts <- mydata()
    summary(Muts)
  })

}

Body:
I like laying out the graphics in the server using tools like grid.arrange from the package gridExtra or the package cowplot - they offer a lot of layout flexiblity. This for example:

library(reshape2)
library(shiny)
library(ggplot2)
library(gridExtra)
# Define UI for application that draws a histogram

u <- fluidPage(

  # Application title
  titlePanel("Mutation Probability"),

  # Sidebar with a slider input for the number of bins
  sidebarLayout(
    sidebarPanel(
      sliderInput("x", "Probability of mutation (per bp):",
                  min=1/1000000000000, max=1/1000, value=1/10000000),

      sliderInput("y", "Size of region (bp):",
                  min = 10, max = 10000, value = 1000, step= 100),

      sliderInput("z", "Number of samples:",
                  min = 1, max = 100000, value = 1000, step= 10)

    ),

    # Show a plot of the generated distribution
    mainPanel(
      tabsetPanel(
        tabPanel("Plot",
                 fluidRow(
                   plotOutput("distPlot4"),
                   verbatimTextOutput("summary"))
                 )),
        tabPanel("Summary",  verbatimTextOutput("summary1"))
      )
    )
  )
)
s <- function(input, output) {

  mydata <- reactive({
    x <- input$x
    y <- input$y
    z <- input$z
    Muts <- as.data.frame(rpois(100,(x*y*z)))
    Muts
  })
  output$distPlot4 <- renderPlot({
    Muts <- mydata()
    p1 <- ggplot(Muts, aes(Muts)) + geom_density() +xlab("Observed variants")
    p2 <- ggplot(Muts, aes(Muts)) + geom_histogram() + xlab("Observed variants")
    p3 <- ggplot(data= melt(Muts), aes(variable, value)) + geom_boxplot() + xlab("Observed variants")
    grid.arrange(p1,p2,p3, ncol=3,widths = c(2,1,1))
  })
  output$summary <- renderPrint({
    Muts <- mydata()
    summary(Muts)
  })
}
shinyApp(u,s)

which yields:

For summary tables, I just add them to the bottom, one after the other, not much else you can do there I think.


问:
PHP-generated XML Feed Displaying as Text
EDIT: HOW IS THIS TOO BROAD? My question was put on hold for being too broad, but I asked one question and provided screenshots and sourcecode. What more do I need? I feel this was flagged for closure before the people that flagged it read everything here. I provided the full source code of my file. HELP! I don't feel very welcome. :-(

I followed the answer in this question to take an existing XML feed, change some tag names, and then spit out a new feed:

How do I change XML tag names with PHP?

The issue I am having is that when the feed is displayed in any browser, it displays as text, instead of being nicely formatted like other 'normal' XML feeds. I assume that since I have not told PHP to render the page as XML, it assumes text/html by default, and that is why it is happening. HOWEVER, when I specify in the header that it's XML, it generates with some XML formatting, but all of my feed shows up bold between the 'pre' tags that are in that answer linked above. When removing the 'pre' tag from the source, it generates nothing.

Without Header Specifying XML:

Rendering as Text

With Header Specifying XML:

Rendering Improperly as XML

Does anyone have any hints to guide me to get this to render properly in a browser?

Thanks in Advance!

Source linked in comments below. StackOverflow would not let me add a third link.

答:
Have you run the resulting code through an xml validator to make sure your rename function is returning valid xml syntax?

If your only problem is having it render in a browser you might look into simple_xml_load_string or SimpleXMLElement to parse your xml into workable objects.

```<code>simplexml_load_string
$showme = simplexml_load_string($xml);
print_r($showme);
</code>```

SimpleXMLElement

```<code>$showme = new SimpleXMLElement($xml);
echo $showme->asXML();
</code>```

Body:
Have you run the resulting code through an xml validator to make sure your rename function is returning valid xml syntax?

If your only problem is having it render in a browser you might look into simple_xml_load_string or SimpleXMLElement to parse your xml into workable objects.

simplexml_load_string
$showme = simplexml_load_string($xml);
print_r($showme);

SimpleXMLElement

$showme = new SimpleXMLElement($xml);
echo $showme->asXML();


问:
Angular2 reactive forms select multiple attribute?
I use the following code in my app with reactive forms.

If I uncomment the [multiple] line, the Choose ... option does not set the dformControl form control object back to status INVALID.

dformControl.multiple by the way returns false. Even if I change the commented line to [multiple]="false", still switching back to the Choose ... option does NOT set the form control status to INVALID.

```<code><select class="form-control"
        [id]="dformControl.key"
        [formControlName]="dformControl.key"
        /*[multiple]="dformControl.multiple"*/>

  <option *ngIf="!dformControl.value"
          value="">
    Choose ...
  </option>

  <option *ngFor="let opt of dformControl.options"
          [value]="opt.value"
          [selected]="dformControl.value == opt.value">
    {{opt.label}}
  </option>

</select>
</code>```

答:
Bind to the multiple property at the select level to a boolean isMultiple. Then you can change it and the select will change as well. Take a look at the this, I change it using a button. plnkr

```<code>  <select formControlName="cars" [multiple]="isMultiple">
      <option></option>
      <option *ngFor="let car of cars" >{{car}}</option>
  </select>
</code>```

It seems when adding the multiple property it is affecting the required validator. I was able to just add an extra validator and it worked as expected.

```<code>Validators.compose([Validators.required,Validators.pattern('.+')]
</code>```

Body:
I use the following code in my app with reactive forms.

If I uncomment the [multiple] line, the Choose ... option does not set the dformControl form control object back to status INVALID.

dformControl.multiple by the way returns false. Even if I change the commented line to [multiple]="false", still switching back to the Choose ... option does NOT set the form control status to INVALID.

<select class="form-control"
        [id]="dformControl.key"
        [formControlName]="dformControl.key"
        /*[multiple]="dformControl.multiple"*/>

  <option *ngIf="!dformControl.value"
          value="">
    Choose ...
  </option>

  <option *ngFor="let opt of dformControl.options"
          [value]="opt.value"
          [selected]="dformControl.value == opt.value">
    {{opt.label}}
  </option>

</select>

Body:
Bind to the multiple property at the select level to a boolean isMultiple. Then you can change it and the select will change as well. Take a look at the this, I change it using a button. plnkr

  <select formControlName="cars" [multiple]="isMultiple">
      <option></option>
      <option *ngFor="let car of cars" >{{car}}</option>
  </select>

It seems when adding the multiple property it is affecting the required validator. I was able to just add an extra validator and it worked as expected.

Validators.compose([Validators.required,Validators.pattern('.+')]


问:
Swift3 Timer.scheduledTimer issue
```<code>@IBAction func attack(_ sender: UIButton) {

    Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.disableAttackBtn(btnTag:sender.tag)), userInfo: nil, repeats: false)

}

func disableAttackBtn(btnTag: Int) {
    if btnTag == attack1Btn.tag {
        attack2Btn.isEnabled = false
    } else {
        attack1Btn.isEnabled = false
    }

    }
</code>```

Trying to pass the sender.tag data to the function disableAttackBtn(btnTag:) within the Timer.scheduledTimer. But getting an error saying "Argument of #selector does not refer to an @objc method, property, or initializer"  Is there a way to pass this data to the function?  Any help would be appreciated.  Thanks

答:
It is impossible to pass a custom parameter through the timer action.

Supported is eiter no parameter

```<code>disableAttackBtn()
</code>```

or one parameter which must be the Timer instance

```<code>disableAttackBtn(_ timer: Timer)
</code>```

If you need to pass custom parameters use the userInfo dictionary:

```<code>Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(disableAttackBtn(_:)), userInfo: ["tag" : sender.tag], repeats: false)
</code>```

```<code>fun disableAttackBtn(_ timer: Timer) {
    let info = timer.userInfo as! [String:Int]
    let tag  = info["tag"]!
    ...
</code>```

Title: Swift3 Timer.scheduledTimer issue

Body:
@IBAction func attack(_ sender: UIButton) {

    Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.disableAttackBtn(btnTag:sender.tag)), userInfo: nil, repeats: false)

}

func disableAttackBtn(btnTag: Int) {
    if btnTag == attack1Btn.tag {
        attack2Btn.isEnabled = false
    } else {
        attack1Btn.isEnabled = false
    }

    }

Trying to pass the sender.tag data to the function disableAttackBtn(btnTag:) within the Timer.scheduledTimer. But getting an error saying "Argument of #selector does not refer to an @objc method, property, or initializer"  Is there a way to pass this data to the function?  Any help would be appreciated.  Thanks

Body:
It is impossible to pass a custom parameter through the timer action.

Supported is eiter no parameter

disableAttackBtn()

or one parameter which must be the Timer instance

disableAttackBtn(_ timer: Timer)

If you need to pass custom parameters use the userInfo dictionary:

Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(disableAttackBtn(_:)), userInfo: ["tag" : sender.tag], repeats: false)

fun disableAttackBtn(_ timer: Timer) {
    let info = timer.userInfo as! [String:Int]
    let tag  = info["tag"]!
    ...


问:
Bash - How to check if command gave no output without printing it?
I am writing a testing script. It executes program with *.in files passed as input and compares its output with *.out files using diff command.

However, I don't want to print diff output, but to check if there is any and if so, then add *.in file name to the list of failed tests.

The problem is I have no idea how to check if command produces output without printing it.

My script now:

```<code>failed_tests=""

for filename in $directory/*.in; do

    command=< ${filename} ./${program} | diff - ${filename%.in}.out

    # Check if command produces output.
    if command; then
        # Add filename to failed tests list.
        failed_tests="${failed_tests} ${filename}"
    fi

done

echo $failed_tests
</code>```

Thank you in advance for all the answers.

答:
You can react on the output of diff -q with

```<code>if [ -n "$(diff -q file1 file2)" ]; then
   echo different
fi
</code>```

You want to compare the output of your prog, that is possible with process substitution:

```<code>if [ -n "$(diff -q $(command "${filename}") file2)" ]; then
   echo different
fi
</code>```

Body:
I am writing a testing script. It executes program with *.in files passed as input and compares its output with *.out files using diff command.

However, I don't want to print diff output, but to check if there is any and if so, then add *.in file name to the list of failed tests.

The problem is I have no idea how to check if command produces output without printing it.

My script now:

failed_tests=""

for filename in $directory/*.in; do

    command=< ${filename} ./${program} | diff - ${filename%.in}.out

    # Check if command produces output.
    if command; then
        # Add filename to failed tests list.
        failed_tests="${failed_tests} ${filename}"
    fi

done

echo $failed_tests

Thank you in advance for all the answers.

Body:
You can react on the output of diff -q with

if [ -n "$(diff -q file1 file2)" ]; then
   echo different
fi

You want to compare the output of your prog, that is possible with process substitution:

if [ -n "$(diff -q $(command "${filename}") file2)" ]; then
   echo different
fi


问:
Java - Annotation processor - method process not called
I am trying to implement AnnotationProcessor. I am following this tutorial.

I am able to debug the annotation processor, and the debugger goes to methods: init, getSupportedAnnotationTypes, getSupportedOptions ,getSupportedSourceVersion but it does not go to process method.

I was unable to find something useful on the internet. Could you please tell me why is this happening and how to fix it?

Thank you.

答: I just found out that in order to run the process method. At least one element must be annotated with an annotation that was set in getSupportedAnnotationTypes.

ContentLicense: CC BY-SA 4.0


问:
How to calculate the distance of a data point to a decision hyperplane created by svm using e1071
I used the e1071 package to create a linear model that predicts 2 classes. I now am able to predict classes, but I also want to know the distance of each prediction to the decision hyperplane.

This code subsets the iris data, creates a training set and a prediction set:

```<code># The data should have 2 factors, such that there is only 1 hyperplane
iris.subset <- subset(iris, iris$Species %in% c("versicolor", "virginica"))
iris.subset$Species <- as.factor(as.character(iris.subset$Species))
# Random sampling for training data
training.data <- iris.subset[sample(1:nrow(iris.subset), 50, replace=FALSE),]
# Remaining samples make up the prediction data
prediction.data <- iris.subset[!(rownames(iris.subset) %in% rownames(training.data)),]
</code>```

This code fits the model.:

```<code>require(e1071)
svmfit <- svm(Species~., data=training.data, kernel="linear")
</code>```

Predicting 5 samples from the prediction set:

```<code>predict(svmfit, prediction.data[sample(1:nrow(prediction.data), 5, replace=FALSE),])
</code>```

This gave me the classes. Now, I want to calculate the distance of these points to the hyperplane. How do I do that?

Here is an unanswered question of the same sort, but in Matlab.
Here is another page that might be of help, but again in Matlab.

答:
You can get the decision values from the predict with

```<code>dd <- prediction.data[sample(1:nrow(prediction.data), 5, replace=FALSE),]
pred <- predict(svmfit, dd, decision.value=T)
pred
#        112        139         87        108         70
#  virginica  virginica versicolor  virginica versicolor
# attr(,"decision.values")
#     virginica/versicolor
# 112            1.9830355
# 139            0.4160704
# 87            -1.2680673
# 108            2.7181950
# 70            -2.6954507
</code>```

These values are returned in an attribute. You can access the data more directly with

```<code>attr(pred, "decision.values")
</code>```

which returns a matrix of values.

For more information, you can read the help page for ?predict.svm

Body:
I used the e1071 package to create a linear model that predicts 2 classes. I now am able to predict classes, but I also want to know the distance of each prediction to the decision hyperplane.

This code subsets the iris data, creates a training set and a prediction set:

# The data should have 2 factors, such that there is only 1 hyperplane
iris.subset <- subset(iris, iris$Species %in% c("versicolor", "virginica"))
iris.subset$Species <- as.factor(as.character(iris.subset$Species))
# Random sampling for training data
training.data <- iris.subset[sample(1:nrow(iris.subset), 50, replace=FALSE),]
# Remaining samples make up the prediction data
prediction.data <- iris.subset[!(rownames(iris.subset) %in% rownames(training.data)),]

This code fits the model.:

require(e1071)
svmfit <- svm(Species~., data=training.data, kernel="linear")

Predicting 5 samples from the prediction set:

predict(svmfit, prediction.data[sample(1:nrow(prediction.data), 5, replace=FALSE),])

This gave me the classes. Now, I want to calculate the distance of these points to the hyperplane. How do I do that?

Here is an unanswered question of the same sort, but in Matlab.
Here is another page that might be of help, but again in Matlab.

Body:
You can get the decision values from the predict with

dd <- prediction.data[sample(1:nrow(prediction.data), 5, replace=FALSE),]
pred <- predict(svmfit, dd, decision.value=T)
pred
#        112        139         87        108         70
#  virginica  virginica versicolor  virginica versicolor
# attr(,"decision.values")
#     virginica/versicolor
# 112            1.9830355
# 139            0.4160704
# 87            -1.2680673
# 108            2.7181950
# 70            -2.6954507

These values are returned in an attribute. You can access the data more directly with

attr(pred, "decision.values")

which returns a matrix of values.

For more information, you can read the help page for ?predict.svm


问:
Vertical-align: middle not working?
Why isn't the vertical-align: middle; not working on my h1? The ul isn't aligning with the h1 and it should.

#logo {
 color: white;
 display: inline;
 vertical-align: middle;
}

ul {
 padding: 20px;
 background: rgba(0,0,0,.5);
}

#title {
 position: absolute;
 text-align: center;
 color: white;
 font-size: 50px;
 top: 100px;

}

#navbar {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-image: url('../img/bg.jpg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    height: 600px;
}

li {
 float: right;
 display: inline;
}

li a {
 display: inline;
 padding: 10px 10px 10px 20px;
 text-decoration: none;
 color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navbar">
  <ul>
   <h1 id="logo">Jordan Baron</h1>
   <li>About Me</li>
   <li>Contact</li>
   <li>Projects</li>
  </ul>

  <h1 id="title">Freelance Web Developer</h1>
 </div></code>```

答:
And a flexbox solution with a few html improvements and improvisations.

body {
  margin: 0;
}
header {
  color: white;
  background: rgba( 0, 0, 0, 0.5 );
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}

header,
ul {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

h1,
h2 {
  margin: 0.5rem 0;
}

h1 {
  padding: 0 20px;
}

h2 {
  text-align: center;
}

ul {
  padding: 0 10px;
}

li {
  padding: 10px;
}

li a {
  color: white;
  text-decoration: none;
  transition: color 350ms ease-in-out;
}
li a:hover {
  color: gold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>

      <h1 id="logo">Jordan Baron</h1>

      <ul>
        <li>About Me</li>
        <li>Contact</li>
        <li>Projects</li>
      </ul>

</header>
<main>
    <h2>Freelance Web Developer</h2>
</main></code>```

Title: Vertical-align: middle not working?

Body:
Why isn't the vertical-align: middle; not working on my h1? The ul isn't aligning with the h1 and it should.

#logo {
 color: white;
 display: inline;
 vertical-align: middle;
}

ul {
 padding: 20px;
 background: rgba(0,0,0,.5);
}

#title {
 position: absolute;
 text-align: center;
 color: white;
 font-size: 50px;
 top: 100px;

}

#navbar {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-image: url('../img/bg.jpg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    height: 600px;
}

li {
 float: right;
 display: inline;
}

li a {
 display: inline;
 padding: 10px 10px 10px 20px;
 text-decoration: none;
 color: white;
}

Jordan Baron

About Me

Contact

Projects

Freelance Web Developer

Body:
And a flexbox solution with a few html improvements and improvisations.

body {
  margin: 0;
}
header {
  color: white;
  background: rgba( 0, 0, 0, 0.5 );
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}

header,
ul {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

h1,
h2 {
  margin: 0.5rem 0;
}

h1 {
  padding: 0 20px;
}

h2 {
  text-align: center;
}

ul {
  padding: 0 10px;
}

li {
  padding: 10px;
}

li a {
  color: white;
  text-decoration: none;
  transition: color 350ms ease-in-out;
}
li a:hover {
  color: gold;
}

<header>

      <h1 id="logo">Jordan Baron</h1>

      <ul>
        <li><a href="#">About Me</a></li>
        <li><a href="#">Contact</a></li>
        <li><a href="#">Projects</a></li>
      </ul>

</header>
<main>
    <h2>Freelance Web Developer</h2>
</main>


问:
Does TinyMCE PowerPaste support pasting images from a browser as Base64
From the TinyMCE PowerPaste plugin documentation :

If you configure PowerPaste to allow local images (see the
  powerpaste_allow_local_images setting below) then images pasted from
  Microsoft Word and other sources will appear in TinyMCE as Base64
  encoded images.

It's not clear what and other sources means. Does it include things copied over from a browser?

From https://stackoverflow.com/a/39842881/329660 I assume that an image pasted as part of a chunk of HTML can't be pasted as binary data in TinyMCE.

But if the user right clicks the image and "copy image" from their browser, is PowerPaste supposed to paste the full Base64 data in the editor (granted that the browser put the data in the correct format in the clipboard in the first place, of course)?

答:
The "other sources" for this is typically just Excel.  Word and Excel are the two office products that consistently place image binaries into the clipboard in RTF format that PowerPaste can extract.

If another office product did the same PowerPaste would see that and grab it as well but at present I don't know of another office product that does exactly what Word and Excel do with images.


问:
How to find whether a given commit is on the first-parent chain of a branch
I'm trying to script a way to tell if a given commit is on the first-parent chain of a given branch.  So, for example, merge-base won't fly, as the commit might have been merged in.  I want to know whether the exact commit was ever the tip of the branch.

Note: The branch in question is subject to a no-fast-forward merge strategy.

答:
The fancy way

A simple "is ancestor" test obviously won't do, as commits down 2nd-or-later parent chains are also ancestors:

```<code>...o--o--A--o--o--o--T
    \            /
 ...-o--*--B----o
         \
          C
</code>```

Both A and B are ancestors of T, but you want to accept A while rejecting B and C.  (Assume --first-parent is the top line here.)

Using git merge-base, however, will actually do part of the job.  You don't need the --is-ancestor mode of git merge-base, though, and do need some additional processing.

Note that, regardless of the path between T and some ancestor, the merge base of T and that ancestor (such as A or B) is either the ancestor itself (A or B respectively here), or some ancestor of the ancestor, such as commit * if we look at T and C as a pair.  (This holds even in the case of multiple merge bases, although I leave constructing a proof of that to you.)

If the, or any arbitrarily chosen one of the set of all, merge base(s) of the test commit and the branch-tip is not already the test-commit, we have a case like C and can reject it out of hand.  (Or, we can use --is-ancestor to reject it, or ... well, see below.)  If not, we must enumerate the commits in the ancestry path between the commit in question and the branch tip.  For A this is:

```<code>         o--o--*--T
</code>```

and for B this is:

```<code>               *--T
              /
             o
</code>```

If any such commit is a merge commit, as is the one marked *, we need to make sure that the first parent includes one of the commit(s) listed along this path.  The toughest cases are those topologically similar to:

```<code>       o--o
      /    \
...--A      o--T
      \    /
       o--o
</code>```

since the --ancestry-path between these includes a merge and two ways to reach A, one of which is a first-parent path and one of which is not.  (This is true if T itself is a merge as well.)

We don't actually need to find the merge base in the first place, though.  We're only using the merge base in order to examine the ancestry path.  If the merge base is not the test commit itself, then the test commit is not an ancestor of the tip commit, and testcommit..tipcommit will not include testcommit itself.  Moreover, adding --ancestry-path—which discards all commits that are not themselves children of the left hand side here—will then discard all commits in the git rev-list output: a case like C has no descendants that are ancestors of T (if it did, C would be a merge base).

Hence, what we want is to examine the commits in git rev-list --ancestry-path testcommit..branchtip.  If this list is empty, the test commit is not an ancestor of the branch tip in the first place.  We have a case like commit C; so we have our answer.  If the list is non-empty, reduce it to its merge components (run again with --merges, or feed the list to git rev-list --stdin --merges, to produce the shrunken list).  If this list is non-empty, check each merge by finding its --first-parent ID and making sure the result is in the first list.

In actual (albeit untested) shell-script code:

```<code>TF=$(mktemp) || exit 1
trap "rm -f $TF" 0 1 2 3 15
git rev-list --ancestry-path $testcommit..$branch > $TF
test -s $TF || exit 1  # not ancestor
git rev-list --stdin --merges < $TF | while read hash; do
    parent1=$(git rev-parse ${hash}^1)
    grep "$parent1" $TF >/dev/null || exit 1 # on wrong path
done
exit 0 # on correct path
</code>```

The brute-force way

The above tests as few commits as possible, but it would be a lot more practical, in a sense, to just run:

```<code>git rev-list --first-parent ${testcommit}^@..$branch
</code>```

If the output includes $testcommit itself, then $testcommit is reachable, by first-parent only, from branch.  (We use ^@ to exclude all parents of $testcommit so that this works even for the root commit; for other commits, ${testcommit}^ suffices since we're using --first-parent.)  Moreover, if we make sure this is done in topological order, the last commit ID emitted from the git rev-list command will be $testcommit itself if and only if $testcommit is reachable from $branch.  Hence:

```<code>hash=$(git rev-parse "$testcommit") || exit 1
t=$(git rev-list --first-parent --topo-order $branch --not ${hash}^@ | tail -1)
test $hash = "$t"
</code>```

should do the trick.  The quotes around $t are in case it expands to the empty string.

Body:
The fancy way

A simple "is ancestor" test obviously won't do, as commits down 2nd-or-later parent chains are also ancestors:

...o--o--A--o--o--o--T
    \            /
 ...-o--*--B----o
         \
          C

Both A and B are ancestors of T, but you want to accept A while rejecting B and C.  (Assume --first-parent is the top line here.)

Using git merge-base, however, will actually do part of the job.  You don't need the --is-ancestor mode of git merge-base, though, and do need some additional processing.

Note that, regardless of the path between T and some ancestor, the merge base of T and that ancestor (such as A or B) is either the ancestor itself (A or B respectively here), or some ancestor of the ancestor, such as commit * if we look at T and C as a pair.  (This holds even in the case of multiple merge bases, although I leave constructing a proof of that to you.)

If the, or any arbitrarily chosen one of the set of all, merge base(s) of the test commit and the branch-tip is not already the test-commit, we have a case like C and can reject it out of hand.  (Or, we can use --is-ancestor to reject it, or ... well, see below.)  If not, we must enumerate the commits in the ancestry path between the commit in question and the branch tip.  For A this is:

         o--o--*--T

and for B this is:

               *--T
              /
             o

If any such commit is a merge commit, as is the one marked *, we need to make sure that the first parent includes one of the commit(s) listed along this path.  The toughest cases are those topologically similar to:

       o--o
      /    \
...--A      o--T
      \    /
       o--o

since the --ancestry-path between these includes a merge and two ways to reach A, one of which is a first-parent path and one of which is not.  (This is true if T itself is a merge as well.)

We don't actually need to find the merge base in the first place, though.  We're only using the merge base in order to examine the ancestry path.  If the merge base is not the test commit itself, then the test commit is not an ancestor of the tip commit, and testcommit..tipcommit will not include testcommit itself.  Moreover, adding --ancestry-path—which discards all commits that are not themselves children of the left hand side here—will then discard all commits in the git rev-list output: a case like C has no descendants that are ancestors of T (if it did, C would be a merge base).

Hence, what we want is to examine the commits in git rev-list --ancestry-path testcommit..branchtip.  If this list is empty, the test commit is not an ancestor of the branch tip in the first place.  We have a case like commit C; so we have our answer.  If the list is non-empty, reduce it to its merge components (run again with --merges, or feed the list to git rev-list --stdin --merges, to produce the shrunken list).  If this list is non-empty, check each merge by finding its --first-parent ID and making sure the result is in the first list.

In actual (albeit untested) shell-script code:

TF=$(mktemp) || exit 1
trap "rm -f $TF" 0 1 2 3 15
git rev-list --ancestry-path $testcommit..$branch > $TF
test -s $TF || exit 1  # not ancestor
git rev-list --stdin --merges < $TF | while read hash; do
    parent1=$(git rev-parse ${hash}^1)
    grep "$parent1" $TF >/dev/null || exit 1 # on wrong path
done
exit 0 # on correct path

The brute-force way

The above tests as few commits as possible, but it would be a lot more practical, in a sense, to just run:

git rev-list --first-parent ${testcommit}^@..$branch

If the output includes $testcommit itself, then $testcommit is reachable, by first-parent only, from branch.  (We use ^@ to exclude all parents of $testcommit so that this works even for the root commit; for other commits, ${testcommit}^ suffices since we're using --first-parent.)  Moreover, if we make sure this is done in topological order, the last commit ID emitted from the git rev-list command will be $testcommit itself if and only if $testcommit is reachable from $branch.  Hence:

hash=$(git rev-parse "$testcommit") || exit 1
t=$(git rev-list --first-parent --topo-order $branch --not ${hash}^@ | tail -1)
test $hash = "$t"

should do the trick.  The quotes around $t are in case it expands to the empty string.


问:
How to load csv file into python GUI to create a map without using pandas/numby or matplotlib
I have created a frame in Python GUI.I have a large csv data with this format:
"n",-x,y     where n is an integer counting from 1 onward,x is a coordinate with negative number and y having a positive number.I want to use create_polygon method in canvas to create a map by using  this csv data file .Any suggestion will be appreciated</p>

答:
python has a CSV module that makes it easy to parse csvs. I recommend using the namedtuple class factory in the collections module to make working with your csvs easier.

EX:

```<code>def read_csv(filepath):
    Row = collections.namedtuple('Row', ['n', 'x', 'y'])
    with open(filepath) as file:
        reader = csv.reader(file)
        for row in reader:
            yield Row(*row)

with open('testfile.csv', 'w') as file:
    print('"1", -5, -8', file = file)
    print('"2", -8, -20', file=file)
for row in read_csv('testfile.csv'):
    print(f'{row.n} = {row.x}, {row.y}')`
</code>```

OUTPUT:

1 =  -5,  -8

2 =  -8,  -20

Body:
python has a CSV module that makes it easy to parse csvs. I recommend using the namedtuple class factory in the collections module to make working with your csvs easier.

EX:

def read_csv(filepath):
    Row = collections.namedtuple('Row', ['n', 'x', 'y'])
    with open(filepath) as file:
        reader = csv.reader(file)
        for row in reader:
            yield Row(*row)

with open('testfile.csv', 'w') as file:
    print('"1", -5, -8', file = file)
    print('"2", -8, -20', file=file)
for row in read_csv('testfile.csv'):
    print(f'{row.n} = {row.x}, {row.y}')`

OUTPUT:

1 =  -5,  -8

2 =  -8,  -20


问:
How can write code in verilog shorter using case sentence
I am new in Verilog and I still have some problems with basics. The following code is one of the modules and works the way I want, but I wonder if it can be written more efficient and shorter and how could it be done.
Thank you for your help!</p>

```<code>`timescale 1ns / 1ps

module COUNTER
  (
    input A_i,
    input B_i,
    input ENABLE_i,
    input CLK,
    input RESET,
    input R_i,
    input UP_DOWN_i, // za realno stanje se UP_DOWN_o prepisuje v UP_DOWN_i
    output reg signed [7:0] VALUE_o,
    output reg UP_DOWN_o
  );

  reg A;
  reg B;
  reg signed [7:0] VALUE_cmp;
  wire [1:0] A_B={A,B};

  initial VALUE_o = 8'b00000000;
  initial VALUE_cmp = 8'b00000000;
  initial A = 1'b0;
  initial B = 1'b0;
  initial UP_DOWN_o = 1'b1;

  always@ (posedge CLK or posedge RESET)
  begin
    A <= A_i;
    B <= B_i;
    VALUE_cmp <= VALUE_o;

    if (RESET || R_i)
    begin
      VALUE_o<= 8'b0;
      VALUE_cmp <=8'b0;
    end

    else if (ENABLE_i)
    begin

//up or down
      if (UP_DOWN_i)
      begin
//up
        if ((A == 1'b0) && (A_i == 1'b0) && (B == 1'b0) && (B_i == 1'b1))
          VALUE_o <= VALUE_o+1;
        else if ((A == 1'b0) && (A_i == 1'b1) && (B == 1'b1) && (B_i == 1'b1))
          VALUE_o <= VALUE_o+1;
        else if ((A == 1'b1) && (A_i == 1'b1) && (B == 1'b1) && (B_i == 1'b0))
          VALUE_o <= VALUE_o+1;
        else if ((A == 1'b1) && (A_i == 1'b0) && (B == 1'b0) && (B_i == 1'b0))
          VALUE_o <= VALUE_o+1;
// change
        if ((A == 1'b0) && (A_i == 1'b1) && (B == 1'b0) && (B_i == 1'b0))
            VALUE_o <= VALUE_o+1;
        else if ((A == 1'b1) && (A_i == 1'b1) && (B == 1'b0) && (B_i == 1'b1))
            VALUE_o <= VALUE_o+1;
        else if ((A == 1'b1) && (A_i == 1'b0) && (B == 1'b1) && (B_i == 1'b1))
            VALUE_o <= VALUE_o+1;
        else if ((A == 1'b0) && (A_i == 1'b0) && (B == 1'b1) && (B_i == 1'b0))
            VALUE_o <= VALUE_o+1;
// after
        else if (A == A_i ==B == B_i )
            VALUE_o <= VALUE_o+1;
      end

      else
      begin
 //down
        if ((A == 1'b0) && (A_i == 1'b1) && (B == 1'b0) && (B_i == 1'b0))
            VALUE_o <= VALUE_o-1;
        else if ((A == 1'b1) && (A_i == 1'b1) && (B == 1'b0) && (B_i == 1'b1))
            VALUE_o <= VALUE_o-1;
        else if ((A == 1'b1) && (A_i == 1'b0) && (B == 1'b1) && (B_i == 1'b1))
            VALUE_o <= VALUE_o-1;
        else if ((A == 1'b0) && (A_i == 1'b0) && (B == 1'b1) && (B_i == 1'b0))
            VALUE_o <= VALUE_o-1;
//change
        else if ((A == 1'b1) && (A_i == 1'b1) && (B == 1'b1) && (B_i == 1'b0))
                VALUE_o <= VALUE_o-1;
        else if ((A == 1'b0) && (A_i == 1'b1) && (B == 1'b1) && (B_i == 1'b1))
                VALUE_o <= VALUE_o-1;
        else if ((A == 1'b0) && (A_i == 1'b0) && (B == 1'b0) && (B_i == 1'b1))
                        VALUE_o <= VALUE_o-1;
        else if ((A == 1'b1) && (A_i == 1'b0) && (B == 1'b0) && (B_i == 1'b0))
                                VALUE_o <= VALUE_o-1;
// after
        else if (A == A_i ==B == B_i )
            VALUE_o <= VALUE_o-1;
       end
      end
  end

  always@ (posedge CLK) // kasneje potrebo vezat za UP_DOWN_o
  begin
       //steje dol
      if (VALUE_cmp > VALUE_o)
        UP_DOWN_o <= 0;

      //steje gor
      else if (VALUE_cmp < VALUE_o)
          UP_DOWN_o <= 1;
  end
endmodule
</code>```

答:
It can be shortened by replacing the if-else chains with the a case as you suggest. Here is the dense implementation. Also in this kind of problems you can use Look up tables (LUT).

```<code>  always@ (posedge CLK or posedge RESET)
  begin
    A <= A_i;
    B <= B_i;
    VALUE_cmp <= VALUE_o;

    if (RESET || R_i)
    begin
      VALUE_o<= 8'b0;
      VALUE_cmp <=8'b0;
    end

    else if (ENABLE_i)
    begin

//up or down
      if (UP_DOWN_i)
      begin

        case({A,A_i,B,B_i})
            //up
            4'b0001, 4'b0111,
            4'b1110, 4'b1000,
            // change
            4'b0100, 4'b1101,
            4'b1011, 4'b0010:
                VALUE_o <= VALUE_o+1;
        endcase
        if (A == A_i ==B == B_i )
            VALUE_o <= VALUE_o+1;
        end

      else
      begin

        case({A,A_i,B,B_i})
        //down
        4'b0100, 4'b1101,
        4'b1011, 4'b0010,
        //change
        4'b1110, 4'b0111,
        4'b0001, 4'b1000:
            VALUE_o <= VALUE_o-1;
        endcase
// after
        else if (A == A_i ==B == B_i )
            VALUE_o <= VALUE_o-1;
       end
      end
  end
</code>```

Here is a reference for LUT implementations:
https://www.csee.umbc.edu/~tinoosh/cmpe415/slides/Rom-LUT-verilog.pdf

Body:
I am new in Verilog and I still have some problems with basics. The following code is one of the modules and works the way I want, but I wonder if it can be written more efficient and shorter and how could it be done.
Thank you for your help!

`timescale 1ns / 1ps

module COUNTER
  (
    input A_i,
    input B_i,
    input ENABLE_i,
    input CLK,
    input RESET,
    input R_i,
    input UP_DOWN_i, // za realno stanje se UP_DOWN_o prepisuje v UP_DOWN_i
    output reg signed [7:0] VALUE_o,
    output reg UP_DOWN_o
  );

  reg A;
  reg B;
  reg signed [7:0] VALUE_cmp;
  wire [1:0] A_B={A,B};

  initial VALUE_o = 8'b00000000;
  initial VALUE_cmp = 8'b00000000;
  initial A = 1'b0;
  initial B = 1'b0;
  initial UP_DOWN_o = 1'b1;

  always@ (posedge CLK or posedge RESET)
  begin
    A <= A_i;
    B <= B_i;
    VALUE_cmp <= VALUE_o;

    if (RESET || R_i)
    begin
      VALUE_o<= 8'b0;
      VALUE_cmp <=8'b0;
    end

    else if (ENABLE_i)
    begin

//up or down
      if (UP_DOWN_i)
      begin
//up
        if ((A == 1'b0) && (A_i == 1'b0) && (B == 1'b0) && (B_i == 1'b1))
          VALUE_o <= VALUE_o+1;
        else if ((A == 1'b0) && (A_i == 1'b1) && (B == 1'b1) && (B_i == 1'b1))
          VALUE_o <= VALUE_o+1;
        else if ((A == 1'b1) && (A_i == 1'b1) && (B == 1'b1) && (B_i == 1'b0))
          VALUE_o <= VALUE_o+1;
        else if ((A == 1'b1) && (A_i == 1'b0) && (B == 1'b0) && (B_i == 1'b0))
          VALUE_o <= VALUE_o+1;
// change
        if ((A == 1'b0) && (A_i == 1'b1) && (B == 1'b0) && (B_i == 1'b0))
            VALUE_o <= VALUE_o+1;
        else if ((A == 1'b1) && (A_i == 1'b1) && (B == 1'b0) && (B_i == 1'b1))
            VALUE_o <= VALUE_o+1;
        else if ((A == 1'b1) && (A_i == 1'b0) && (B == 1'b1) && (B_i == 1'b1))
            VALUE_o <= VALUE_o+1;
        else if ((A == 1'b0) && (A_i == 1'b0) && (B == 1'b1) && (B_i == 1'b0))
            VALUE_o <= VALUE_o+1;
// after
        else if (A == A_i ==B == B_i )
            VALUE_o <= VALUE_o+1;
      end

      else
      begin
 //down
        if ((A == 1'b0) && (A_i == 1'b1) && (B == 1'b0) && (B_i == 1'b0))
            VALUE_o <= VALUE_o-1;
        else if ((A == 1'b1) && (A_i == 1'b1) && (B == 1'b0) && (B_i == 1'b1))
            VALUE_o <= VALUE_o-1;
        else if ((A == 1'b1) && (A_i == 1'b0) && (B == 1'b1) && (B_i == 1'b1))
            VALUE_o <= VALUE_o-1;
        else if ((A == 1'b0) && (A_i == 1'b0) && (B == 1'b1) && (B_i == 1'b0))
            VALUE_o <= VALUE_o-1;
//change
        else if ((A == 1'b1) && (A_i == 1'b1) && (B == 1'b1) && (B_i == 1'b0))
                VALUE_o <= VALUE_o-1;
        else if ((A == 1'b0) && (A_i == 1'b1) && (B == 1'b1) && (B_i == 1'b1))
                VALUE_o <= VALUE_o-1;
        else if ((A == 1'b0) && (A_i == 1'b0) && (B == 1'b0) && (B_i == 1'b1))
                        VALUE_o <= VALUE_o-1;
        else if ((A == 1'b1) && (A_i == 1'b0) && (B == 1'b0) && (B_i == 1'b0))
                                VALUE_o <= VALUE_o-1;
// after
        else if (A == A_i ==B == B_i )
            VALUE_o <= VALUE_o-1;
       end
      end
  end

  always@ (posedge CLK) // kasneje potrebo vezat za UP_DOWN_o
  begin
       //steje dol
      if (VALUE_cmp > VALUE_o)
        UP_DOWN_o <= 0;

      //steje gor
      else if (VALUE_cmp < VALUE_o)
          UP_DOWN_o <= 1;
  end
endmodule

Body:
It can be shortened by replacing the if-else chains with the a case as you suggest. Here is the dense implementation. Also in this kind of problems you can use Look up tables (LUT).

  always@ (posedge CLK or posedge RESET)
  begin
    A <= A_i;
    B <= B_i;
    VALUE_cmp <= VALUE_o;

    if (RESET || R_i)
    begin
      VALUE_o<= 8'b0;
      VALUE_cmp <=8'b0;
    end

    else if (ENABLE_i)
    begin

//up or down
      if (UP_DOWN_i)
      begin

        case({A,A_i,B,B_i})
            //up
            4'b0001, 4'b0111,
            4'b1110, 4'b1000,
            // change
            4'b0100, 4'b1101,
            4'b1011, 4'b0010:
                VALUE_o <= VALUE_o+1;
        endcase
        if (A == A_i ==B == B_i )
            VALUE_o <= VALUE_o+1;
        end

      else
      begin

        case({A,A_i,B,B_i})
        //down
        4'b0100, 4'b1101,
        4'b1011, 4'b0010,
        //change
        4'b1110, 4'b0111,
        4'b0001, 4'b1000:
            VALUE_o <= VALUE_o-1;
        endcase
// after
        else if (A == A_i ==B == B_i )
            VALUE_o <= VALUE_o-1;
       end
      end
  end

Here is a reference for LUT implementations:
https://www.csee.umbc.edu/~tinoosh/cmpe415/slides/Rom-LUT-verilog.pdf