问:
SendKeys is messing with my NumLock key via VBA code in Access form
I have the following code for an Access form. It appears as if the SendKeys is messing with my NumLock key by toggling it on and off as I open and close the form.

For perfectly valid reasons which I don't want to get into, I really do not want to completely hide the ribbon (I want the pull down menus still accessible) so the DoCmd.ShowToolbar command is not my preferred way of doing it.

Does anyone have any suggestions as to how I can modify the code below to accomplish what I want using the SendKeys command?

Using Access 2007 so the command

```<code>CommandBars.ExecuteMso "MinimizeRibbon"
</code>```

is not available to me.

By the way, database will be distributed so solution must be contained within database.

```<code>Private Sub Form_Close()

' Unhide navigation pane
    DoCmd.NavigateTo "acNavigationCategoryObjectType"
    DoCmd.Maximize

' Maximize the ribbon
RibbonState = (CommandBars("Ribbon").Controls(1).Height < 75)

Select Case RibbonState
    Case True
        SendKeys "^{F1}", True
    Case False
        'Do nothing, already maximized
End Select
End Sub

Private Sub Form_Load()
' Hide navigation pane
    DoCmd.NavigateTo "acNavigationCategoryObjectType"
    DoCmd.Minimize
Debug.Print Application.CommandBars.Item("Ribbon").Height
' Minimize ribbon
RibbonState = (CommandBars("Ribbon").Controls(1).Height < 100)

Select Case RibbonState
    Case True
        'Do nothing, already minimized
    Case False
            SendKeys "^{F1}", False
End Select
End Sub
</code>```

答:
When you do a final sendKeys command in your code, adding in {NUMLOCK} to the statement may do the trick, as noted by RodB and iceBird76. But this is not a good coding practice, and here is why: if anything is different from one time to the next when you run the macro, it may or may not work.  I know this because I was experiencing a similar issue myself. When I would do a sendKeys command at the end of my program, sometimes the Num Lock would stay on, but other times it would stay off, just depending on certain variables in my spreadsheet (regardless of whether or not I included {NUMLOCK} in my last SendKeys statement).

I won't get into the details of my own variables, but the point is that to build a program/macro that will keep your Num Lock on consistently, you need to FIRST TEST TO SEE IF THE NUM LOCK IS ON OR OFF, then execute code based upon the present condition.

```<code>Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
Private Const kNumlock = 144

Public Function NumLock() As Boolean
    NumLock = KeyState(kNumlock)
    If (NumLock = True) Then
        MsgBox ("Num lock was off. Will turn back on now...")
        SendKeys "{NUMLOCK}", True
    Else: MsgBox ("Num Lock stayed on")
    End If
End Function

Private Function KeyState(lKey As Long) As Boolean
    KeyState = CBool(GetKeyState(lKey))
End Function

Sub myMainMethod()
    'do a function here that includes .SendKeys
    Call NumLock
End Sub
</code>```

This sample program will give you a confirmation message as to whether the Num Lock is on or off, and turn it on if it is off.

Body:
I have the following code for an Access form. It appears as if the SendKeys is messing with my NumLock key by toggling it on and off as I open and close the form.

For perfectly valid reasons which I don't want to get into, I really do not want to completely hide the ribbon (I want the pull down menus still accessible) so the DoCmd.ShowToolbar command is not my preferred way of doing it.

Does anyone have any suggestions as to how I can modify the code below to accomplish what I want using the SendKeys command?

Using Access 2007 so the command

CommandBars.ExecuteMso "MinimizeRibbon"

is not available to me.

By the way, database will be distributed so solution must be contained within database.

Private Sub Form_Close()

' Unhide navigation pane
    DoCmd.NavigateTo "acNavigationCategoryObjectType"
    DoCmd.Maximize

' Maximize the ribbon
RibbonState = (CommandBars("Ribbon").Controls(1).Height < 75)

Select Case RibbonState
    Case True
        SendKeys "^{F1}", True
    Case False
        'Do nothing, already maximized
End Select
End Sub

Private Sub Form_Load()
' Hide navigation pane
    DoCmd.NavigateTo "acNavigationCategoryObjectType"
    DoCmd.Minimize
Debug.Print Application.CommandBars.Item("Ribbon").Height
' Minimize ribbon
RibbonState = (CommandBars("Ribbon").Controls(1).Height < 100)

Select Case RibbonState
    Case True
        'Do nothing, already minimized
    Case False
            SendKeys "^{F1}", False
End Select
End Sub

Body:
When you do a final sendKeys command in your code, adding in {NUMLOCK} to the statement may do the trick, as noted by RodB and iceBird76. But this is not a good coding practice, and here is why: if anything is different from one time to the next when you run the macro, it may or may not work.  I know this because I was experiencing a similar issue myself. When I would do a sendKeys command at the end of my program, sometimes the Num Lock would stay on, but other times it would stay off, just depending on certain variables in my spreadsheet (regardless of whether or not I included {NUMLOCK} in my last SendKeys statement).

I won't get into the details of my own variables, but the point is that to build a program/macro that will keep your Num Lock on consistently, you need to FIRST TEST TO SEE IF THE NUM LOCK IS ON OR OFF, then execute code based upon the present condition.

Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
Private Const kNumlock = 144

Public Function NumLock() As Boolean
    NumLock = KeyState(kNumlock)
    If (NumLock = True) Then
        MsgBox ("Num lock was off. Will turn back on now...")
        SendKeys "{NUMLOCK}", True
    Else: MsgBox ("Num Lock stayed on")
    End If
End Function

Private Function KeyState(lKey As Long) As Boolean
    KeyState = CBool(GetKeyState(lKey))
End Function

Sub myMainMethod()
    'do a function here that includes .SendKeys
    Call NumLock
End Sub

This sample program will give you a confirmation message as to whether the Num Lock is on or off, and turn it on if it is off.


来源: stackexchange

问:
Transition from sentence to one word
What I am trying to achieve is to animate an element width few words in the way that hovered word leaves in the center of the element and the rest smoothly goes out of the bounds. I would also keep it as clear as possible in HTML and not to use fixed pixel amount of margins/widths to position elements.

The very lousy sketch of what I have on my mind is here:

* {
  transition: all 1.5s;
}

div {
  min-width: 150px;
  width: 30%;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
}

div:hover {
  background: white;
  word-spacing: 300px;
}

a:hover::after,
a:hover::before {
  content: ' ';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  First & Second
</div></code>```

Each word on hover should go to center (possibly not with those 'jumps' visible now when other words disapear). Do you have any ideas? I'm pretty sure that the way I try to follow with word-spacing is wrong.

答:
This isn't perfect, but I think it comes pretty close to achieving what you were looking for. Using a little bit of jQuery was necessary for math (but not the animations themselves).

Hope this gets you further!

function reset() {
  // reset all spans
  $('.animate span').css('transform', '');
  $('.animate span.active').removeClass('active');
}

$('.animate').on('mouseover', 'span:not(.active)', function() {
  reset();

  // set current hovered word to active
  $(this).addClass('active');

  // slide over previous/next words
  $(this).prevAll().css('transform', 'translateX(-100vw)');
  $(this).nextAll().css('transform', 'translateX(100vw)');

  // determine offset for center of hovered word
  var center = (window.innerWidth / 2) - ($(this).offset().left + ($(this).width() / 2));
  // slide current word to center
  $(this).css('transform', 'translateX(' + center + 'px)');
});

// when leaving animate section, reset
$('.animate').mouseleave(reset);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.animate {
  background-color: orange;
  color: white;
  font-family: sans-serif;
  text-align: center;
  transition: .5s background-color, .5s color;
}

.animate:hover {
  background-color: white;
  color: orange;
}

span {
  display: inline-block;
  transition: 3s transform;
}

a {
  color: inherit;
}</code>```

  First & Second & Third and Fourth

```

ContentLicense: CC BY-SA 3.0

Title: Transition from sentence to one word

Body:
What I am trying to achieve is to animate an element width few words in the way that hovered word leaves in the center of the element and the rest smoothly goes out of the bounds. I would also keep it as clear as possible in HTML and not to use fixed pixel amount of margins/widths to position elements.

The very lousy sketch of what I have on my mind is here:

* {
  transition: all 1.5s;
}

div {
  min-width: 150px;
  width: 30%;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
}

div:hover {
  background: white;
  word-spacing: 300px;
}

a:hover::after,
a:hover::before {
  content: ' ';
}

  First & Second

Each word on hover should go to center (possibly not with those 'jumps' visible now when other words disapear). Do you have any ideas? I'm pretty sure that the way I try to follow with word-spacing is wrong.

Body:
This isn't perfect, but I think it comes pretty close to achieving what you were looking for. Using a little bit of jQuery was necessary for math (but not the animations themselves).

Hope this gets you further!

function reset() {
  // reset all spans
  $('.animate span').css('transform', '');
  $('.animate span.active').removeClass('active');
}

$('.animate').on('mouseover', 'span:not(.active)', function() {
  reset();

  // set current hovered word to active
  $(this).addClass('active');

  // slide over previous/next words
  $(this).prevAll().css('transform', 'translateX(-100vw)');
  $(this).nextAll().css('transform', 'translateX(100vw)');

  // determine offset for center of hovered word
  var center = (window.innerWidth / 2) - ($(this).offset().left + ($(this).width() / 2));
  // slide current word to center
  $(this).css('transform', 'translateX(' + center + 'px)');
});

// when leaving animate section, reset
$('.animate').mouseleave(reset);

.animate {
  background-color: orange;
  color: white;
  font-family: sans-serif;
  text-align: center;
  transition: .5s background-color, .5s color;
}

.animate:hover {
  background-color: white;
  color: orange;
}

span {
  display: inline-block;
  transition: 3s transform;
}

a {
  color: inherit;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="animate">
  <span><a href="#">First</a></span> <span>&amp;</span> <span><a href="#">Second</a></span> <span>&amp;</span> <span><a href="#">Third</a></span> <span>and</span> <span><a href="#">Fourth</a></span>
</div>


问:
Can't send data to firebase
Trying to send some data to firebase but showing nothing

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

    private static final String TAG = MainActivity.class.getSimpleName();
    private TextView txtDetails;
    private EditText name,age,gender,mobile,address,blood,bp,date;
    private Button submit;
    private FirebaseDatabase firebaseInstance;
    private DatabaseReference firebaseDatabase;
    private String patientId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtDetails = findViewById(R.id.txtheading);
        name = findViewById(R.id.edname);
        age = findViewById(R.id.edage);
        gender = findViewById(R.id.edgender);
        mobile = findViewById(R.id.edmobile);
        blood = findViewById(R.id.edblood);
        bp = findViewById(R.id.edbp);
        date = findViewById(R.id.eddate);
        submit = findViewById(R.id.btnsubmit);

        firebaseInstance = FirebaseDatabase.getInstance();
        firebaseDatabase = firebaseInstance.getReference("Doctor");

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String Name = name.getText().toString();
                String Age = age.getText().toString();
                String Gender = gender.getText().toString();
                String Mobile = mobile.getText().toString();
                String Blood = blood.getText().toString();
                String BP = bp.getText().toString();
                String Date = date.getText().toString();

             if(TextUtils.isEmpty(patientId)) {
                 createPatient(Name,Age,Gender,Mobile,Blood,BP,Date);
             }
             else {

                 updatePatient(Name,Age,Gender,Mobile,Blood,BP,Date);
             }
            }
        });

    }

    private void updatePatient(String name, String age, String gender,
                               String mobile, String blood,
                               String bp, String date) {

    }
    private void createPatient(String name, String age, String gender,
                               String mobile, String blood, String bp, String date) {

        if(TextUtils.isEmpty(patientId)) {

            patientId = firebaseDatabase.push().getKey();
        }

        Patient patient = new Patient(name,age,gender,mobile,blood,bp,date);
        firebaseDatabase.child(patientId).setValue(patient);
        addUserChangeListener();

    }

    private void addUserChangeListener() {

           firebaseDatabase.child(patientId).addValueEventListener(new ValueEventListener() {
               @Override
               public void onDataChange(DataSnapshot dataSnapshot) {

                   Patient patient = dataSnapshot.getValue(Patient.class);
                   if(patient==null) {

                       Log.e(TAG, "User data is changed !" );
                       return;
                   }

                   Log.e(TAG, "User data is changed!" + patient.Names + ", " + patient.Address +", "+patient.Age +
                   "," +patient.Blood +"," +patient.BP+ "," +patient.Gender +
                   "," +patient.Mobile + "," +patient.Date);

               }

               @Override
               public void onCancelled(DatabaseError databaseError) {
                   Log.e(TAG, "Failed to read user", databaseError.toException());
               }
           });

    }

   }
</code>```

Here is my Patient Class :

```<code>    public class Patient {

    public String Names;
    public String Age;
    public String Gender;
    public String Mobile;
    public String Address;
    public String Blood;
    public String BP;
    public String Date;

   public Patient(String name, String age, String gender, String mobile, String blood, String bp, String date) {
   }

    public Patient(String names, String age, String gender,
                   String mobile, String address, String blood,
                   String BP, String date) {
        Names = names;
        Age = age;
        Gender = gender;
        Mobile = mobile;
        Address = address;
        Blood = blood;
        this.BP = BP;
        Date = date;
    }

    public Patient(String name, String age, String gender, String mobile, String blood, String bp, String date) {
    }
}
</code>```

答:
First remove this:

```<code>       if(TextUtils.isEmpty(patientId)) {

         }
</code>```

from this:

```<code>        createPatient(Name,Age,Gender,Mobile,Blood,BP,Date);
</code>```

and this:

```<code>        patientId = firebaseDatabase.push().getKey();
</code>```

then use a map instead of class to store the info.

So delete this

```<code>  Patient patient = new Patient(name,age,gender,mobile,blood,bp,date);
</code>```

and createPatient method will look like this

```<code>    private void createPatient(String name, String age, String gender,
                           String mobile, String blood, String bp, String date) {

     //create a push id like that
     patientId = firebaseDatabase.push().getKey();

     //make a map called patientmap

     Map patientmap=new HashMap();

     //add your values like this to the map

      patientmap.put("Name",name);
      patientmap.put("Age",age);
      patientmap.put("Gender",gender);
      patientmap.put("Mobile",mobile);
      patientmap.put("Blood",blood);
      patientmap.put("BP",bp);
      patientmap.put("Date",date);

    firebaseDatabase.child(patientId).setValue(patientmap);
    addUserChangeListener();

}
</code>```

Title: Can't send data to firebase

Body:
Trying to send some data to firebase but showing nothing

    public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private TextView txtDetails;
    private EditText name,age,gender,mobile,address,blood,bp,date;
    private Button submit;
    private FirebaseDatabase firebaseInstance;
    private DatabaseReference firebaseDatabase;
    private String patientId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtDetails = findViewById(R.id.txtheading);
        name = findViewById(R.id.edname);
        age = findViewById(R.id.edage);
        gender = findViewById(R.id.edgender);
        mobile = findViewById(R.id.edmobile);
        blood = findViewById(R.id.edblood);
        bp = findViewById(R.id.edbp);
        date = findViewById(R.id.eddate);
        submit = findViewById(R.id.btnsubmit);

        firebaseInstance = FirebaseDatabase.getInstance();
        firebaseDatabase = firebaseInstance.getReference("Doctor");

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String Name = name.getText().toString();
                String Age = age.getText().toString();
                String Gender = gender.getText().toString();
                String Mobile = mobile.getText().toString();
                String Blood = blood.getText().toString();
                String BP = bp.getText().toString();
                String Date = date.getText().toString();

             if(TextUtils.isEmpty(patientId)) {
                 createPatient(Name,Age,Gender,Mobile,Blood,BP,Date);
             }
             else {

                 updatePatient(Name,Age,Gender,Mobile,Blood,BP,Date);
             }
            }
        });

    }

    private void updatePatient(String name, String age, String gender,
                               String mobile, String blood,
                               String bp, String date) {

    }
    private void createPatient(String name, String age, String gender,
                               String mobile, String blood, String bp, String date) {

        if(TextUtils.isEmpty(patientId)) {

            patientId = firebaseDatabase.push().getKey();
        }

        Patient patient = new Patient(name,age,gender,mobile,blood,bp,date);
        firebaseDatabase.child(patientId).setValue(patient);
        addUserChangeListener();

    }

    private void addUserChangeListener() {

           firebaseDatabase.child(patientId).addValueEventListener(new ValueEventListener() {
               @Override
               public void onDataChange(DataSnapshot dataSnapshot) {

                   Patient patient = dataSnapshot.getValue(Patient.class);
                   if(patient==null) {

                       Log.e(TAG, "User data is changed !" );
                       return;
                   }

                   Log.e(TAG, "User data is changed!" + patient.Names + ", " + patient.Address +", "+patient.Age +
                   "," +patient.Blood +"," +patient.BP+ "," +patient.Gender +
                   "," +patient.Mobile + "," +patient.Date);

               }

               @Override
               public void onCancelled(DatabaseError databaseError) {
                   Log.e(TAG, "Failed to read user", databaseError.toException());
               }
           });

    }

   }

Here is my Patient Class :

    public class Patient {

    public String Names;
    public String Age;
    public String Gender;
    public String Mobile;
    public String Address;
    public String Blood;
    public String BP;
    public String Date;

   public Patient(String name, String age, String gender, String mobile, String blood, String bp, String date) {
   }

    public Patient(String names, String age, String gender,
                   String mobile, String address, String blood,
                   String BP, String date) {
        Names = names;
        Age = age;
        Gender = gender;
        Mobile = mobile;
        Address = address;
        Blood = blood;
        this.BP = BP;
        Date = date;
    }

    public Patient(String name, String age, String gender, String mobile, String blood, String bp, String date) {
    }
}

Body:
First remove this:

       if(TextUtils.isEmpty(patientId)) {

         }

from this:

        createPatient(Name,Age,Gender,Mobile,Blood,BP,Date);

and this:

        patientId = firebaseDatabase.push().getKey();

then use a map instead of class to store the info.

So delete this

  Patient patient = new Patient(name,age,gender,mobile,blood,bp,date);

and createPatient method will look like this

    private void createPatient(String name, String age, String gender,
                           String mobile, String blood, String bp, String date) {

     //create a push id like that
     patientId = firebaseDatabase.push().getKey();

     //make a map called patientmap

     Map patientmap=new HashMap();

     //add your values like this to the map

      patientmap.put("Name",name);
      patientmap.put("Age",age);
      patientmap.put("Gender",gender);
      patientmap.put("Mobile",mobile);
      patientmap.put("Blood",blood);
      patientmap.put("BP",bp);
      patientmap.put("Date",date);

    firebaseDatabase.child(patientId).setValue(patientmap);
    addUserChangeListener();

}


问:
Comment a statement in shell script file using sed command at run time?
I am trying to comment a if statement in a shell script file using sed command.

Code snippet:

```<code>if[$z='LZ'||$x='LW']
then
        echo "This my test for sed and I am successful"
else
        echo "This my test for sed and my try failed"
fi
</code>```

I used

```<code>**sed -i -e 's\if\#if\g' test.sh**
</code>```

it works but if I give below command:

```<code>**sed -i -e "s\if[$z='LZ'||$x='LW']\#if[$z='LZ'||$x='LW']\g" test.sh**
</code>```

it doesn't work

Let me know if you need some more data.
Thanks in advance.

答:
When you want to match the if statement (which is missing some spaces, fix that), just replace the difficult characters by dots.</p>

```<code>sed -i -e 's/if.$z=.LZ.||$x=.LW.]/#&/' test.sh
</code>```

Body:
I am trying to comment a if statement in a shell script file using sed command.

Code snippet:

if[$z='LZ'||$x='LW']
then
        echo "This my test for sed and I am successful"
else
        echo "This my test for sed and my try failed"
fi

I used

**sed -i -e 's\if\#if\g' test.sh**

it works but if I give below command:

**sed -i -e "s\if[$z='LZ'||$x='LW']\#if[$z='LZ'||$x='LW']\g" test.sh**

it doesn't work

Let me know if you need some more data.
Thanks in advance.

Body:
When you want to match the if statement (which is missing some spaces, fix that), just replace the difficult characters by dots.

sed -i -e 's/if.$z=.LZ.||$x=.LW.]/#&/' test.sh


问:
Extract h264 stream from USB webcam (logitech C920)
So, I'm starting to play around with gstreamer and I'm able to do very simple pipes such as

```<code>gst-launch-1.0 -v v4l2src device=/dev/video1 ! video/x-raw,format=YUY2,width=640,height=480,framerate=10/1 ! videoconvert ! autovideosink
</code>```

Now, as my USB webcam (which is video1, video0 being the computer's built in camera) supports h264 (I have checked using lsusb), I would like to try to get the h264 feed directly. I understand that this feed is muxed in the mjpeg one, but looking around on the web it seems that gstreamer is able to get it nonetheless.

Since my end goal is to stream it from a Beaglebone, I made an attempt using the solution given to this post (adding a listener from a different terminal):

```<code>#sender
gst-launch-1.0 v4l2src device=/dev/video1 ! video/x-264,width=320,height=90,framerate=10/1 ! tcpserversink host=192.168.148.112 port=9999
</code>```

But this yields the following error :

```<code>WARNING: erroneous pipeline: could not link v4l2src0 to tcpserversink0
</code>```

I also tried something similar to my first command, changing the source from raw to h264 (based on that post , trying the full command given there gives the same error message)

```<code>gst-launch-1.0 -v v4l2src device=/dev/video1 ! video/x-h264,width=640,height=480,framerate=10/1 ! h264parse ! avdec_h264 ! autovideosink
</code>```

But again, this did not work either:

```<code>Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
ERROR: from element /GstPipeline:pipeline0/GstV4l2Src:v4l2src0: Internal data flow error.
Additional debug info:
gstbasesrc.c(2948): gst_base_src_loop (): /GstPipeline:pipeline0/GstV4l2Src:v4l2src0:
streaming task paused, reason not-negotiated (-4)
Execution ended after 0:00:00.036309961
Setting pipeline to PAUSED ...
Setting pipeline to READY ...
Setting pipeline to NULL ...
Freeing pipeline ...
</code>```

I admit this is driving me pretty crazy: looking on SO or elsewhere on the web, there seems to be a lot of people who made it work with exactly the same webcam as the one I have (Logitech C920), but I keep running into issues one after the other.

What would be an example of correct pipe to extract the h264 from that webcam?

答:
You definitely need to use a payloader before it hits the wire.  For example rtph264pay.  Here is an example that cannot test as I don't have your hardware available.  I have working udp examples from alternates sources if this doesn't steer you in the right direction.

server

```<code>gst-launch v4l2src device=/dev/video1 \
! video/x-264,width=320,height=90,framerate=10/1 \
! x264enc \
! queue \
! rtph264pay, config-interval=3, pt=96, mtu=1500 \
! queue \
! tcpserversink host=127.0.0.1 port=9002
</code>```

client

```<code>gst-launch tcpserversrc host=127.0.0.1 port=9002 \
! application/x-rtp, media=video, clock-rate=90000, encoding-name=H264, payload=96 \
! rtph264depay \
! video/x-h264 \
! queue \
! ffdec_h264 \
! queue \
! xvimagesink
</code>```

Body:
So, I'm starting to play around with gstreamer and I'm able to do very simple pipes such as

gst-launch-1.0 -v v4l2src device=/dev/video1 ! video/x-raw,format=YUY2,width=640,height=480,framerate=10/1 ! videoconvert ! autovideosink

Now, as my USB webcam (which is video1, video0 being the computer's built in camera) supports h264 (I have checked using lsusb), I would like to try to get the h264 feed directly. I understand that this feed is muxed in the mjpeg one, but looking around on the web it seems that gstreamer is able to get it nonetheless.

Since my end goal is to stream it from a Beaglebone, I made an attempt using the solution given to this post (adding a listener from a different terminal):

#sender
gst-launch-1.0 v4l2src device=/dev/video1 ! video/x-264,width=320,height=90,framerate=10/1 ! tcpserversink host=192.168.148.112 port=9999

But this yields the following error :

WARNING: erroneous pipeline: could not link v4l2src0 to tcpserversink0

I also tried something similar to my first command, changing the source from raw to h264 (based on that post , trying the full command given there gives the same error message)

gst-launch-1.0 -v v4l2src device=/dev/video1 ! video/x-h264,width=640,height=480,framerate=10/1 ! h264parse ! avdec_h264 ! autovideosink

But again, this did not work either:

Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
ERROR: from element /GstPipeline:pipeline0/GstV4l2Src:v4l2src0: Internal data flow error.
Additional debug info:
gstbasesrc.c(2948): gst_base_src_loop (): /GstPipeline:pipeline0/GstV4l2Src:v4l2src0:
streaming task paused, reason not-negotiated (-4)
Execution ended after 0:00:00.036309961
Setting pipeline to PAUSED ...
Setting pipeline to READY ...
Setting pipeline to NULL ...
Freeing pipeline ...

I admit this is driving me pretty crazy: looking on SO or elsewhere on the web, there seems to be a lot of people who made it work with exactly the same webcam as the one I have (Logitech C920), but I keep running into issues one after the other.

What would be an example of correct pipe to extract the h264 from that webcam?

Body:
You definitely need to use a payloader before it hits the wire.  For example rtph264pay.  Here is an example that cannot test as I don't have your hardware available.  I have working udp examples from alternates sources if this doesn't steer you in the right direction.

server

gst-launch v4l2src device=/dev/video1 \
! video/x-264,width=320,height=90,framerate=10/1 \
! x264enc \
! queue \
! rtph264pay, config-interval=3, pt=96, mtu=1500 \
! queue \
! tcpserversink host=127.0.0.1 port=9002

client

gst-launch tcpserversrc host=127.0.0.1 port=9002 \
! application/x-rtp, media=video, clock-rate=90000, encoding-name=H264, payload=96 \
! rtph264depay \
! video/x-h264 \
! queue \
! ffdec_h264 \
! queue \
! xvimagesink


问:
WebElement getText() doesn't work on Winium-Desktop
I'm trying to execute getText() on a WebElement instance but for some reason it doesn't work: pcresultsList.get(0).getText()

Maybe Winium doesn't support this method?

My code is:

```<code>public void monitorBasic() throws InterruptedException {
    monitorFrame = driver.findElement(By.name("BEAM Monitor"));
    WebElement resultsFrame = monitorFrame.findElement(By.id("ReportListBox"));
    List<WebElement> pcresultsList = resultsFrame.findElements(By.className("TextBlock"));
    System.out.println(pcresultsList.get(0).getText());
}
</code>```

sorry for not posting the error I'm getting - the site tells me that my code is not indent and when i'm trying to present it as code the site tells i have too much code. :)

答:
Have you tried using:

```<code>System.out.println(pcresultsList.get(0).getAttribute("Value"));
</code>```

Also try to get other properties of the element to confirm you can get info.

The code below works for me:

```<code>element = Window.findElement(By.xpath("//*[contains(@ControlType,'ControlType.DataItem') and contains(@Name,'G15')]"));
    System.out.println("Cell text: " + element.getText()); //writes Shipments
</code>```

Let us know if this helps.

Body:
I'm trying to execute getText() on a WebElement instance but for some reason it doesn't work: pcresultsList.get(0).getText()

Maybe Winium doesn't support this method?

My code is:

public void monitorBasic() throws InterruptedException {
    monitorFrame = driver.findElement(By.name("BEAM Monitor"));
    WebElement resultsFrame = monitorFrame.findElement(By.id("ReportListBox"));
    List<WebElement> pcresultsList = resultsFrame.findElements(By.className("TextBlock"));
    System.out.println(pcresultsList.get(0).getText());
}

sorry for not posting the error I'm getting - the site tells me that my code is not indent and when i'm trying to present it as code the site tells i have too much code. :)

Body:
Have you tried using:

System.out.println(pcresultsList.get(0).getAttribute("Value"));

Also try to get other properties of the element to confirm you can get info.

The code below works for me:

element = Window.findElement(By.xpath("//*[contains(@ControlType,'ControlType.DataItem') and contains(@Name,'G15')]"));
    System.out.println("Cell text: " + element.getText()); //writes Shipments

Let us know if this helps.


问:
mainframe - FOLLOWING RESERVED DATA SET NAMES UNAVAILABLE TO userid
I'm trying to create a report from a VSAM KSDS. I got this error when run the job

```<code> IEF861I FOLLOWING RESERVED DATA SET NAMES UNAVAILABLE TO SHE02
 IEF863I DSN = SHECICS.ZEUSBANK.BRANCHES SHE00081 RC = 04 RSN 2
 IEF099I JOB SHE00081 WAITING FOR DATA SETS
</code>```

Here's my code

```<code> //SHE0008  JOB A492,PROGRAMMER
 //STEP01   EXEC PGM=ICETOOL
 //SYSPRINT DD SYSOUT=*
 //SYSOUT   DD SYSOUT=*
 //INPUT1   DD DSN=SHECICS.ZEUSBANK.BRANCHES,DISP=SHR
 //SORTOUT  DD SYSOUT=*
 //SYSIN    DD *
      DISPLAY FROM(INPUT1) LIST(REPORT)
      TITLE('LIST OF ZEUSBANK BRANCH')
      HEADER('SORTCODE') ON (1,4,ZD)
      HEADER('FLAG') ON (10,1,CH)
      HEADER('BRANCH NAME') ON (20,32,CH)
 /*
</code>```

Can anyone help? Thanks.

答:
The dastaset is in use by another address space/job/task and has an enque on it.

Considering the dataset name it could well be in use by CICS.

You can try again later, it may have been released.

You could talk to you local friendly system's programmers who may tell you what has the enque.

You could try issuing the D GRS,RES=(SYSDSN,'SHECICS.ZEUSBANK.BRANCHES') command.

You may find IEF863I of interest.

Body:
I'm trying to create a report from a VSAM KSDS. I got this error when run the job

 IEF861I FOLLOWING RESERVED DATA SET NAMES UNAVAILABLE TO SHE02
 IEF863I DSN = SHECICS.ZEUSBANK.BRANCHES SHE00081 RC = 04 RSN 2
 IEF099I JOB SHE00081 WAITING FOR DATA SETS

Here's my code

 //SHE0008  JOB A492,PROGRAMMER
 //STEP01   EXEC PGM=ICETOOL
 //SYSPRINT DD SYSOUT=*
 //SYSOUT   DD SYSOUT=*
 //INPUT1   DD DSN=SHECICS.ZEUSBANK.BRANCHES,DISP=SHR
 //SORTOUT  DD SYSOUT=*
 //SYSIN    DD *
      DISPLAY FROM(INPUT1) LIST(REPORT)
      TITLE('LIST OF ZEUSBANK BRANCH')
      HEADER('SORTCODE') ON (1,4,ZD)
      HEADER('FLAG') ON (10,1,CH)
      HEADER('BRANCH NAME') ON (20,32,CH)
 /*

Can anyone help? Thanks.


问:
Playing multi-sampled Instruments using AudioKit, controlling ADSR envelope
I'm trying to play instrument of several .wav samples using AudioKit.

I've tried so far:

Using AKSampler (with underlying AVAudioUnitSampler) – it worked fine, but I can't figure out how to control ADSR envelope here – calling stop will stop note immediately.

Another way is to use AKSamplePlayer for each sample and play it, manually setting rate so it play the right note. I can (possibly?) then connect AKAmplitudeEnvelope to each sample player. But if I want to play 5 notes of the same sample simultaneously, I would need 5 instances of AKSamplePlayer, which seems like wasting resources.

I also tried to find a way to just push raw audio samples to the AudioKit output buffer, making mixing and sample interpolation by myself (in C, probably?). But didn't find how to do it :(

What is the right way to make a multi-sampled instrument using AudioKit? I feel like it must be a fairly simple task.

答: Probably the best way would be to embed your wav files into an EXS or Soundfont format, making use of tools in that realm to accomplish the ADSR for instance. Otherwise you'll kind of have to have an instrument for each sample.</p>


答:
Here is the sample code to achieve this, by filtering for the distinct values of Employee:
</p>

```<code>//Getting the distinct columns
List<Row> distinctColumns = df.select("Employee").distinct().collectAsList();

//Initializing empty list for the new DataFrames
ArrayList<Dataset<Row>> newDFs = new ArrayList<>();

WindowSpec ws = Window.orderBy("date");

//Filtering by the distinct column values and adding to the list.
for (Row distinctColumn : distinctColumns) {
    String colName = distinctColumn.getString(0);

    newDFs.add(
            df.filter(col("Employee").$eq$eq$eq(colName))
                    .withColumn("rank", rank().over(ws))
    );
}

// show all the new DFs
for (Dataset<Row> aDF : newDFs) {
    aDF.show();
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: separate the dataset as per rank in spark

Body:
I have a dataset which includes name of employees, balance, date and employees has separate rank number.

df.show();
+------------+----------+-------+----+
|    Employee|      date|balance|rank|
+------------+----------+-------+----+
|      A     |2016-02-05|   2143|   1|
|      A     |2016-07-05|    231|   2|
|      A     |2016-08-05|    447|   3|
|      A     |2017-10-05|    779|   4|
|      A     |2018-03-05|    255|   5|
|      A     |2018-05-05|    246|   6|
|      A     |2018-08-05|    378|   7|
|      A     |2018-11-05|  10635|   8|
|      A     |2019-06-05|     49|   9|
|      A     |2020-02-05|      0|  10|
|      A     |2020-04-05|    244|  11|
|      A     |2020-05-05|      0|  12|
|      A     |2020-09-05|    424|  13|
|      C     |2016-05-05|   1506|   1|
|      C     |2017-06-05|     52|   2|
|      C     |2017-09-05|    723|   3|
|      C     |2017-11-05|     23|   4|
+------------+----------+-------+----+

I have to separate this dataset as per rank. so my expected output is

table1
+------------+----------+-------+----+
|    Employee|      date|balance|rank|
+------------+----------+-------+----+
|      A     |2016-02-05|   2143|   1|
|      A     |2016-07-05|    231|   2|
|      A     |2016-08-05|    447|   3|
|      A     |2017-10-05|    779|   4|
|      A     |2018-03-05|    255|   5|
|      A     |2018-05-05|    246|   6|
|      A     |2018-08-05|    378|   7|
|      A     |2018-11-05|  10635|   8|
|      A     |2019-06-05|     49|   9|
|      A     |2020-02-05|      0|  10|
|      A     |2020-04-05|    244|  11|
|      A     |2020-05-05|      0|  12|
|      A     |2020-09-05|    424|  13|
+------------+----------+-------+----+

table2

+------------+----------+-------+----+
|    Employee|      date|balance|rank|
+------------+----------+-------+----+
|      C     |2016-05-05|   1506|   1|
|      C     |2017-06-05|     52|   2|
|      C     |2017-09-05|    723|   3|
|      C     |2017-11-05|     23|   4|
+------------+----------+-------+----+

I used window function for getting this rank but I didn't get how can I get separate tables like this. I am using spark 2.0.0 and java.

     WindowSpec ws = Window.partitionBy(Employee).orderBy(date);
     data.withColumn( "rank", rank().over(ws) )

Body:
Here is the sample code to achieve this, by filtering for the distinct values of Employee:

//Getting the distinct columns
List<Row> distinctColumns = df.select("Employee").distinct().collectAsList();

//Initializing empty list for the new DataFrames
ArrayList<Dataset<Row>> newDFs = new ArrayList<>();

WindowSpec ws = Window.orderBy("date");

//Filtering by the distinct column values and adding to the list.
for (Row distinctColumn : distinctColumns) {
    String colName = distinctColumn.getString(0);

    newDFs.add(
            df.filter(col("Employee").$eq$eq$eq(colName))
                    .withColumn("rank", rank().over(ws))
    );
}

// show all the new DFs
for (Dataset<Row> aDF : newDFs) {
    aDF.show();
}


问:
Showing images into a list view
I am writing a code in C# to show the unknown number of images from a specified folder into a "listview" I don't know how to get all the files present in that specific folder.
I know I have to use a loop and array but I don't know how.
Here is the code which I use to access files with the "known name of file".
It's a windows form app.</p>

```<code>private void btnZoom_Click(object sender, EventArgs e)
{
    ImageList imgs = new ImageList();
    imgs.ImageSize = new Size(100, 100);

    string[] paths = { };
    paths = Directory.GetFiles("TestFolder");

    try
    {
        foreach (string path in paths)
        {
            imgs.Images.Add(Image.FromFile(path));
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    listView1.SmallImageList = imgs;
    listView1.Items.Add("2",0);
}
</code>```

答:
Here is the working code:

and the code is :

```<code>   private void button1_Click(object sender, EventArgs e)
    {
        listView1.Items.Clear();
        imageList1.Images.Clear();

        string[] pics = System.IO.Directory.GetFiles( "pics//");
        listView1.View = View.SmallIcon;
        listView1.SmallImageList = imageList1;

        imageList1.ImageSize = new Size(64, 64);
        foreach (string pic in pics)
        {
            imageList1.Images.Add(Image.FromFile(pic));
        }

        for (int j = 0; j < imageList1.Images.Count; j++)
        {

            ListViewItem item = new ListViewItem();

            item.ImageIndex = j;

            listView1.Items.Add(item);

        }

    }
</code>```

and at designer set this:

Title: Showing images into a list view

Body:
I am writing a code in C# to show the unknown number of images from a specified folder into a "listview" I don't know how to get all the files present in that specific folder.
I know I have to use a loop and array but I don't know how.
Here is the code which I use to access files with the "known name of file".
It's a windows form app.

private void btnZoom_Click(object sender, EventArgs e)
{
    ImageList imgs = new ImageList();
    imgs.ImageSize = new Size(100, 100);

    string[] paths = { };
    paths = Directory.GetFiles("TestFolder");

    try
    {
        foreach (string path in paths)
        {
            imgs.Images.Add(Image.FromFile(path));
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    listView1.SmallImageList = imgs;
    listView1.Items.Add("2",0);
}

Body:
Here is the working code:

and the code is :

   private void button1_Click(object sender, EventArgs e)
    {
        listView1.Items.Clear();
        imageList1.Images.Clear();

        string[] pics = System.IO.Directory.GetFiles( "pics//");
        listView1.View = View.SmallIcon;
        listView1.SmallImageList = imageList1;

        imageList1.ImageSize = new Size(64, 64);
        foreach (string pic in pics)
        {
            imageList1.Images.Add(Image.FromFile(pic));
        }

        for (int j = 0; j < imageList1.Images.Count; j++)
        {

            ListViewItem item = new ListViewItem();

            item.ImageIndex = j;

            listView1.Items.Add(item);

        }

    }

and at designer set this:


问:
Failed to install  "gem install eventmachine". I need starling in my project, for starling i need to install eventmachine
I am getting the following error on my console

```<code>root@comp09:~# gem install eventmachine
Building native extensions.  This could take a while...
ERROR:  Error installing eventmachine:
 ERROR: Failed to build gem native extension.

/usr/local/bin/ruby extconf.rb
checking for rb_trap_immediate in ruby.h,rubysig.h... yes
checking for rb_thread_blocking_region()... no
checking for inotify_init() in sys/inotify.h... yes
checking for writev() in sys/uio.h... yes
checking for rb_thread_check_ints()... no
checking for rb_time_new()... yes
checking for sys/event.h... no
checking for epoll_create() in sys/epoll.h... yes
creating Makefile

make
I. -I/usr/local/lib/ruby/1.8/x86_64-linux -I/usr/local/lib/ruby/1.8/x86_64-linux -I. -DBUILD_FOR_RUBY -DHAVE_RB_TRAP_IMMEDIATE -DHAVE_RBTRAP -DHAVE_INOTIFY_INIT -DHAVE_INOTIFY -DHAVE_WRITEV -DHAVE_WRITEV -DHAVE_RB_TIME_NEW -DOS_UNIX -DHAVE_EPOLL_CREATE -DHAVE_EPOLL -DWITH_SSL    -fPIC -O2 -g -Wall -Wno-parentheses -Wno-long-long     -o rubymain.o -c rubymain.cpp
make: I.: Command not found
make: [rubymain.o] Error 127 (ignored)
I. -I/usr/local/lib/ruby/1.8/x86_64-linux -I/usr/local/lib/ruby/1.8/x86_64-linux -I. -DBUILD_FOR_RUBY -DHAVE_RB_TRAP_IMMEDIATE -DHAVE_RBTRAP -DHAVE_INOTIFY_INIT -DHAVE_INOTIFY -DHAVE_WRITEV -DHAVE_WRITEV -DHAVE_RB_TIME_NEW -DOS_UNIX -DHAVE_EPOLL_CREATE -DHAVE_EPOLL -DWITH_SSL    -fPIC -O2 -g -Wall -Wno-parentheses -Wno-long-long     -o em.o -c em.cpp
make: I.: Command not found
</code>```

For any help and suggestion it would be greatly appreciated.

答:
from docs .

EventMachine may require the following
  dependencies, depending on your
  specific usage:

```<code>* OpenSSL
* libstd++ (some systems, such as debian, may require an explicit
</code>```

install in order for the compiler to
  support this)

Try to install it , if you are using debian

```<code>sudo apt-get install libstdc++6
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am getting the following error on my console

root@comp09:~# gem install eventmachine
Building native extensions.  This could take a while...
ERROR:  Error installing eventmachine:
 ERROR: Failed to build gem native extension.

/usr/local/bin/ruby extconf.rb
checking for rb_trap_immediate in ruby.h,rubysig.h... yes
checking for rb_thread_blocking_region()... no
checking for inotify_init() in sys/inotify.h... yes
checking for writev() in sys/uio.h... yes
checking for rb_thread_check_ints()... no
checking for rb_time_new()... yes
checking for sys/event.h... no
checking for epoll_create() in sys/epoll.h... yes
creating Makefile

make
I. -I/usr/local/lib/ruby/1.8/x86_64-linux -I/usr/local/lib/ruby/1.8/x86_64-linux -I. -DBUILD_FOR_RUBY -DHAVE_RB_TRAP_IMMEDIATE -DHAVE_RBTRAP -DHAVE_INOTIFY_INIT -DHAVE_INOTIFY -DHAVE_WRITEV -DHAVE_WRITEV -DHAVE_RB_TIME_NEW -DOS_UNIX -DHAVE_EPOLL_CREATE -DHAVE_EPOLL -DWITH_SSL    -fPIC -O2 -g -Wall -Wno-parentheses -Wno-long-long     -o rubymain.o -c rubymain.cpp
make: I.: Command not found
make: [rubymain.o] Error 127 (ignored)
I. -I/usr/local/lib/ruby/1.8/x86_64-linux -I/usr/local/lib/ruby/1.8/x86_64-linux -I. -DBUILD_FOR_RUBY -DHAVE_RB_TRAP_IMMEDIATE -DHAVE_RBTRAP -DHAVE_INOTIFY_INIT -DHAVE_INOTIFY -DHAVE_WRITEV -DHAVE_WRITEV -DHAVE_RB_TIME_NEW -DOS_UNIX -DHAVE_EPOLL_CREATE -DHAVE_EPOLL -DWITH_SSL    -fPIC -O2 -g -Wall -Wno-parentheses -Wno-long-long     -o em.o -c em.cpp
make: I.: Command not found

For any help and suggestion it would be greatly appreciated.

Body:
from docs .

EventMachine may require the following
  dependencies, depending on your
  specific usage:

* OpenSSL
* libstd++ (some systems, such as debian, may require an explicit

install in order for the compiler to
  support this)

Try to install it , if you are using debian

sudo apt-get install libstdc++6


问:
How to create an Admin page for a website developed in React + Node?
I want to create an Admin page in order to manage users, groups, passwords and to publish content in a website. That website is made using React.

What is the right way to make it? Using a library for React that provides such Admin?

My workmate told me he uses Material UI, but I don't see how that library could be used for that purpose.

答:
Material UI is used only for styling stuff, not for actual logic. If you have a REST backend, take a look at admin on rest project.

What is your backed written in?


问:
Where can I find UX documentation for Xamarin's TableView Intent?
The Xamarin TableView has an Intent property that allows me to define between

Data

Form

Menu

Settings

However it's not clear what the UX difference will be on each platform.

Is there any elaboration for this enumeration?

答:
Currently (9c48284d) the only platform specific renderer that uses that TableIntent enum is on iOS.

If you set the TableView to be "Data" orientated the section headers & footers do not float in the view.

Xamarin.Forms.Platform.iOS/Renderers/TableViewRenderer.cs

```<code>~~~
if (e.NewElement.Intent != TableIntent.Data)
   style = UITableViewStyle.Grouped;
~~~
</code>```

Body:
Currently (9c48284d) the only platform specific renderer that uses that TableIntent enum is on iOS.

If you set the TableView to be "Data" orientated the section headers & footers do not float in the view.

Xamarin.Forms.Platform.iOS/Renderers/TableViewRenderer.cs

~~~
if (e.NewElement.Intent != TableIntent.Data)
   style = UITableViewStyle.Grouped;
~~~


问:
How to get value of other table like a movies data was conected by ID in php, sql group_concat / inner join or any
If i have table like this

```<code>anime(ID,anime_name,genres,studio,series)
anime_genres(ID,anime_id,genres_id)
anime_studio(ID,anime_id,studio_id)
anime_series(ID,anime_id,series_id)
</code>```

and

```<code>genres(ID,genres_name)
studio(ID,studio_name)
series(ID,series_name)
</code>```

Problem :
How to get data like this.

```<code>ID | anime_name |        genres                  |      studio                | series
1  | Uq holder  | (1)action,(2)fantasy,(3)isekai |(1)A-1,(2)pierot,(3)tvtokyo | neginegima
</code>```

i try like this

```<code>    SELECT anime.ID ,anime_name
     FROM anime
    INNER JOIN (SELECT genres_id FROM anime_genres WHERE anime_id = genres ) as genre_selector
    ON genre_selector.genres = anime.genres
     INNER JOIN (SELECT genres_name FROM genres WHERE ID = genres_id) as genre_data
 ON genre_data.genres_id = anime_genres.genres_id
   ORDER BY anime.ID
</code>```

i use this to run the query

```<code>$stmt = $reg_anime->animeQuery(sql statement); $stmt->execute(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo $row['ID']. ' : '. $row['anime_name']. ' '. $row['genres_name']. ' - '. $row['genres']. '<br />'; }
</code>```

答:
You could do this all in sql, though I will admit it is a bit ugly.</p>

```<code>SELECT
a.Id,
a.anime_name,
(
    STUFF((
    SELECT TOP 3 ',' + g.genres_name
    FROM
    anime_genres ag INNER JOIN genres g
    ON ag.genres_id = g.id
    WHERE ag.anime_id = 1
    FOR XML PATH('')
    ), 1, 1, '')
) AS genres,
(
    STUFF((
    SELECT TOP 3 ',' + s.studio_name
    FROM
    anime_studio as INNER JOIN studio s
    ON as.studio_id = g.id
    WHERE ag.anime_id = 1
    FOR XML PATH('')
    ), 1, 1, '')
) AS studio,
anime.series
FROM anime a
WHERE
a.ID = 1
</code>```

Body:
If i have table like this

anime(ID,anime_name,genres,studio,series)
anime_genres(ID,anime_id,genres_id)
anime_studio(ID,anime_id,studio_id)
anime_series(ID,anime_id,series_id)

and

genres(ID,genres_name)
studio(ID,studio_name)
series(ID,series_name)

Problem :
How to get data like this.

ID | anime_name |        genres                  |      studio                | series
1  | Uq holder  | (1)action,(2)fantasy,(3)isekai |(1)A-1,(2)pierot,(3)tvtokyo | neginegima

i try like this

    SELECT anime.ID ,anime_name
     FROM anime
    INNER JOIN (SELECT genres_id FROM anime_genres WHERE anime_id = genres ) as genre_selector
    ON genre_selector.genres = anime.genres
     INNER JOIN (SELECT genres_name FROM genres WHERE ID = genres_id) as genre_data
 ON genre_data.genres_id = anime_genres.genres_id
   ORDER BY anime.ID

i use this to run the query

$stmt = $reg_anime->animeQuery(sql statement); $stmt->execute(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo $row['ID']. ' : '. $row['anime_name']. ' '. $row['genres_name']. ' - '. $row['genres']. '
'; }

Body:
You could do this all in sql, though I will admit it is a bit ugly.

SELECT
a.Id,
a.anime_name,
(
    STUFF((
    SELECT TOP 3 ',' + g.genres_name
    FROM
    anime_genres ag INNER JOIN genres g
    ON ag.genres_id = g.id
    WHERE ag.anime_id = 1
    FOR XML PATH('')
    ), 1, 1, '')
) AS genres,
(
    STUFF((
    SELECT TOP 3 ',' + s.studio_name
    FROM
    anime_studio as INNER JOIN studio s
    ON as.studio_id = g.id
    WHERE ag.anime_id = 1
    FOR XML PATH('')
    ), 1, 1, '')
) AS studio,
anime.series
FROM anime a
WHERE
a.ID = 1


问:
How to work with 2 FireFoxDrivers simultaneously? Does Selenium support multithreading?
How to work with 2 FireFoxDrivers simultaneously? Does Selenium support multithreading?

I have the below test which opens 2 firefox browsers but both navigations happen only on the first browser instance!

```<code>  [Test]
    public void TestMultithreading()
    {
        var tasks = new List<Task>
                        {
                            new Task(goToBbc),
                            new Task(goToGoogle)
                        };

        tasks.ForEach(task => task.Start());

        Task.WaitAll(tasks.ToArray());
    }

    private void goToBbc()
    {
        openBrowserAndGoTo("http://www.bbc.com");
    }

    private void goToGoogle()
    {
        openBrowserAndGoTo("http://www.google.com");
    }

    private void openBrowserAndGoTo(string url)
    {
        var webDriver = new FirefoxDriver();
        webDriver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 1, 0));
        webDriver.Navigate().GoToUrl(url);
        Thread.Sleep(5000);
        webDriver.Quit();
    }
</code>```

Hope the question is clear.

Thanks,

答:
Since others haven't mentioned this yet, I'll give a shout out to Maven and its plugins for selenium in Java.

Maven's Surefire and Failsafe plugins manage the test lifecycle of a build (or suite in this case). I've used these plugins with JUnit to run multi-threaded selenium tests. I'm sure TestNG is just as capable.

With this type of project, you can run mvn test or mvn verify from the command-line to kick off the tests and report the results. If your IDE supports maven builds, you can right-click on your test package and execute the tests from there.

You can run the tests locally (it will pop up a lot of browsers), or point your suite to a remote hub to execute them remotely.

I should also note, you'll want to focus on writing tests that are atomic in nature, to where they can run individually, and then let the build system execute them all as a suite.

Body:
How to work with 2 FireFoxDrivers simultaneously? Does Selenium support multithreading?

I have the below test which opens 2 firefox browsers but both navigations happen only on the first browser instance!

  [Test]
    public void TestMultithreading()
    {
        var tasks = new List<Task>
                        {
                            new Task(goToBbc),
                            new Task(goToGoogle)
                        };

        tasks.ForEach(task => task.Start());

        Task.WaitAll(tasks.ToArray());
    }

    private void goToBbc()
    {
        openBrowserAndGoTo("http://www.bbc.com");
    }

    private void goToGoogle()
    {
        openBrowserAndGoTo("http://www.google.com");
    }

    private void openBrowserAndGoTo(string url)
    {
        var webDriver = new FirefoxDriver();
        webDriver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 1, 0));
        webDriver.Navigate().GoToUrl(url);
        Thread.Sleep(5000);
        webDriver.Quit();
    }

Hope the question is clear.

Thanks,


问:
Scale and center image in each div in this container
I have this in HTML and i need the pictures inside the containers to be centered and to scale even if i resize the parent div

```<code><div class="art-cont" id="art">
<div class="art-1">
<img src="https://cdn.stocksnap.io/img-thumbs/960w/2SQMYBPQGK.jpg">
</div>
<div class="art-2">
<img src="https://cdn.stocksnap.io/img-thumbs/960w/2SQMYBPQGK.jpg">
</div>
<div class="art-3">
<img src="https://cdn.stocksnap.io/img-thumbs/960w/2SQMYBPQGK.jpg">
</div>
</div>
</code>```

CSS:

```<code>.art-cont{
    width:100%;
    height:400px;
}
.art-1{
    width:70%;
    height:50%;
    float:left;
    position:relative;
    overflow:hidden;
    border:2px solid #fff;
}
.art-2{
    width:30%;
    height:50%;
    float:left;
    position:relative;
    overflow:hidden;
    border:2px solid #fff;
}
.art-3{
    width:100%;
    height:50%;
    clear:both;
    position:relative;
    overflow:hidden;
    border:2px solid #fff;
}
</code>```

Here's a fiddle: https://jsfiddle.net/0r7rhe77/

答:
The following rule will do it

```<code>.art-cont img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
</code>```

as long as you're okay with the browser compatibility of object-fit (roughly 90% of users - most everybody except IE 11 or lower). Also check out the other options for object-fit.

Fiddle

Another option is refactoring your code to display the images using background-image, as all modern browsers support background-size. Remove the  elements and instead do:

```<code>.art-1, .art-2, .art-3 {
    background-image: url(https://cdn.stocksnap.io/img-thumbs/960w/2SQMYBPQGK.jpg);
    background-size: cover;
    background-position: center center;
}
</code>```

Fiddle using this approach

Body:
I have this in HTML and i need the pictures inside the containers to be centered and to scale even if i resize the parent div

CSS:

.art-cont{
    width:100%;
    height:400px;
}
.art-1{
    width:70%;
    height:50%;
    float:left;
    position:relative;
    overflow:hidden;
    border:2px solid #fff;
}
.art-2{
    width:30%;
    height:50%;
    float:left;
    position:relative;
    overflow:hidden;
    border:2px solid #fff;
}
.art-3{
    width:100%;
    height:50%;
    clear:both;
    position:relative;
    overflow:hidden;
    border:2px solid #fff;
}

Here's a fiddle: https://jsfiddle.net/0r7rhe77/

Body:
The following rule will do it

.art-cont img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

as long as you're okay with the browser compatibility of object-fit (roughly 90% of users - most everybody except IE 11 or lower). Also check out the other options for object-fit.

Fiddle

Another option is refactoring your code to display the images using background-image, as all modern browsers support background-size. Remove the <img> elements and instead do:

.art-1, .art-2, .art-3 {
    background-image: url(https://cdn.stocksnap.io/img-thumbs/960w/2SQMYBPQGK.jpg);
    background-size: cover;
    background-position: center center;
}

Fiddle using this approach


问:
Why is my list of Tuples vertical?
I believe I've made an error in my coding in where my list of tuples prints out vertically instead of the correct way. May someone please tell me what's up?

This is the question being asked:
Enumerate It!
Write a function called enum that takes a sequence and returns a list of 2-tuples with each tuple holding the index and its associated item.

This is the example given:

```<code>>>> enum([45,67,23,34,88,12,90])
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

>> enum('hello')
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
</code>```

This is my code:

```<code>def enum(aSequence):
    for i in range(7):
        b=aSequence[i]
        a= [i]
        list1 = [a,b]
       print (list1)

If following the example input is used this is the result:
[[0], 45]
[[1], 67]
[[2], 23]
[[3], 34]
[[4], 88]
[[5], 12]
[[6], 90]
</code>```

The result I would desire is:
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

When I take away print(list1) and use return list1 instead this is the result.

```<code>[[0], 13]
</code>```

Why is this the case?

When I put this into the website in which I'm being tutored on, the word "Jack and Jane" is displayed and random numbers are shown if a different test. My second question is how do I get the range loop to fit based on the parameter input. I tried to import math and import random. While both are short term solutions they aren't long term solutions.

I feel like I'm overthinking the problem as the code is there just the basic fundamentals might be missing.

答:
This is what you need to print everything in the same line

```<code> for i in range(len(aSequence)):
     b=aSequence[i]
     a= i
    list1 = [a,b]
    print (list1,end=' ')
</code>```

Since you wanted the result

[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

Title: Why is my list of Tuples vertical?

Body:
I believe I've made an error in my coding in where my list of tuples prints out vertically instead of the correct way. May someone please tell me what's up?

This is the question being asked:
Enumerate It!
Write a function called enum that takes a sequence and returns a list of 2-tuples with each tuple holding the index and its associated item.

This is the example given:

>>> enum([45,67,23,34,88,12,90])
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

>> enum('hello')
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]

This is my code:

def enum(aSequence):
    for i in range(7):
        b=aSequence[i]
        a= [i]
        list1 = [a,b]
       print (list1)

If following the example input is used this is the result:
[[0], 45]
[[1], 67]
[[2], 23]
[[3], 34]
[[4], 88]
[[5], 12]
[[6], 90]

The result I would desire is:
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]

When I take away print(list1) and use return list1 instead this is the result.

[[0], 13]

Why is this the case?

When I put this into the website in which I'm being tutored on, the word "Jack and Jane" is displayed and random numbers are shown if a different test. My second question is how do I get the range loop to fit based on the parameter input. I tried to import math and import random. While both are short term solutions they aren't long term solutions.

I feel like I'm overthinking the problem as the code is there just the basic fundamentals might be missing.

Body:
This is what you need to print everything in the same line

 for i in range(len(aSequence)):
     b=aSequence[i]
     a= i
    list1 = [a,b]
    print (list1,end=' ')

Since you wanted the result

[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]


问:
Selecting multiple tables for a Query MySQLi PHP
I am trying to create a query, but I don't know how to select multiple tables with the way I have my database set up.

In my query I am trying to display what movies have what actor, but each movie has multiple actors so I have to select from three tables.
This is my movies table:

This is my actor_information table

My last table is the actor_movie table. This table correlates the movie_id with and actor_id

I have the following php to connect to the database, but I am not sure how to write the query portion.

```<code><?php
$databaseName = 'movie_database';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';

$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully <br>";

// this code is wrong, but i get the general idea of how to select from my db.
$sql = "SELECT actor_movie, movies, actor_information FROM actor_movie INNER
JOIN movies ON actor_movie.movie_id = movies.movie_id
INNER JOIN actor_information ON actor_movie.actor_id =
actor_information.actor_id"
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo " Title " . $row["title"]. "". $row["actor_id"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>
</code>```

Here is my uml if it helps:

答:
As you have three tables and want to fetch relevant data, use the below SQL Query.

```<code>SELECT actor_movie.*, movies.*, actor_information.* FROM actor_movie INNER JOIN movies ON actor_movie.movie_id = movies.movie_id INNER JOIN actor_information ON actor_movie.actor_id = actor_information.actor_id"
</code>```

Consider using an Auto Increment value (which will be PRIMARY KEY) in your DB with all the tables. This should be your ID.

Hope this helps.

Body:
I am trying to create a query, but I don't know how to select multiple tables with the way I have my database set up.

In my query I am trying to display what movies have what actor, but each movie has multiple actors so I have to select from three tables.
This is my movies table:

This is my actor_information table

My last table is the actor_movie table. This table correlates the movie_id with and actor_id

I have the following php to connect to the database, but I am not sure how to write the query portion.

<?php
$databaseName = 'movie_database';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';

$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully
";

// this code is wrong, but i get the general idea of how to select from my db.
$sql = "SELECT actor_movie, movies, actor_information FROM actor_movie INNER
JOIN movies ON actor_movie.movie_id = movies.movie_id
INNER JOIN actor_information ON actor_movie.actor_id =
actor_information.actor_id"
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo " Title " . $row["title"]. "". $row["actor_id"]. "
";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>

Here is my uml if it helps:

Body:
As you have three tables and want to fetch relevant data, use the below SQL Query.

SELECT actor_movie.*, movies.*, actor_information.* FROM actor_movie INNER JOIN movies ON actor_movie.movie_id = movies.movie_id INNER JOIN actor_information ON actor_movie.actor_id = actor_information.actor_id"

Consider using an Auto Increment value (which will be PRIMARY KEY) in your DB with all the tables. This should be your ID.

Hope this helps.


问:
Event Handler on component in Reactjs
This is not firing on the component but when I attach my event handler to a div it works. Do I need to pass a prop types function in my child component?</p>

```<code>const buttonStyle = {
  color: 'red'
};

class Button extends React.Component {
    render() {
        return (
          <a className="social-button twitter">
            <i href="#" className="fa fa-twitter"></i>
          </a>
        )};
}

class PanelButtons extends React.Component {
  constructor(props){
    super(props);
    }

  handleClick() {
    console.log('this is:');
  }

    render() {
        return (
          <div>
          <div onClick={(e) => this.handleClick(e)}> {/*this works attaching it to a div*/}
            CLick me
            </div>
            <div className="social-buttons">
                <Button onClick={(e) => this.handleClick(e)} />{/*does now work attaching it to a component*/}
            </div>
           </div>
        )
    }
}

ReactDOM.render(<PanelButtons />,  document.querySelector('body'));
</code>```

答:
What you did basically, is passing a callback called onClick to the Button component. It will be accessible to you through the component's props.

```<code>class Button extends React.Component {
    render() {
        return (
          <a className="social-button twitter" onClick={this.props.onClick}>
            <i href="#" className="fa fa-twitter"></i>
          </a>
        )};
}
</code>```

once the Button component's a element is clicked, the callback that you passed will be triggered (and handleClick will be called).

Title: Event Handler on component in Reactjs

Body:
This is not firing on the component but when I attach my event handler to a div it works. Do I need to pass a prop types function in my child component?

const buttonStyle = {
  color: 'red'
};

class Button extends React.Component {
    render() {
        return (

        )};
}

class PanelButtons extends React.Component {
  constructor(props){
    super(props);
    }

  handleClick() {
    console.log('this is:');
  }

    render() {
        return (

 this.handleClick(e)}> {/*this works attaching it to a div*/}
            CLick me

                <Button onClick={(e) => this.handleClick(e)} />{/*does now work attaching it to a component*/}

        )
    }
}

ReactDOM.render(<PanelButtons />,  document.querySelector('body'));

Body:
What you did basically, is passing a callback called onClick to the Button component. It will be accessible to you through the component's props.

class Button extends React.Component {
    render() {
        return (
          <a className="social-button twitter" onClick={this.props.onClick}>
            <i href="#" className="fa fa-twitter"></i>
          </a>
        )};
}

once the Button component's a element is clicked, the callback that you passed will be triggered (and handleClick will be called).


问:
Regex not always working with angle brackets
So, in the process of writing a Brainfuck translator in Java I need to split the string following next rules: any of the [ ] , . characters or any sequence of the + - < > should be followed by newline. Here's the input string:

```<code>..-<[-]>..[[<<[+[-<-->>+,>-.++]-,>,<[.],][<.,<-]+[-,<->,-]<<[>->-.<-[.<++,>++,].-]]]
</code>```

And my code:

```<code>s = s.replaceAll("(\\+|-|<|>)+", "$0\n")
.replaceAll("\\.|\\,|\\[|\\]", "$0\n");
</code>```

And the result (SO won't allow this here): https://pastebin.com/ZaT8d5ve
What was expected: https://pastebin.com/gNxcgTSP
It seems that connections of brackets with plus-minus signs are faulty, while angle brackets with square brackets and dot/comma are fine. I can't really get, what's wrong with my solution?

答:
Your output does exactly what you described, sequence of the + - < > is followed by \n so -< becomes -<\n not -\n<\n.

If I understand you correctly you want to split of sequence of same characters which is either + - < > to have \n after it. If that is the case then instead of

```<code>s.replaceAll("(\\+|-|<|>)+", "$0\n")
</code>```

you can use

```<code>s.replaceAll("(\\+|-|<|>)\\1*", "$0\n")
</code>```

\1 is backreference to match from group 1 (here (\\+|-|<|>)), so it matches one of those characters and its optional following repetitions.

Body:
So, in the process of writing a Brainfuck translator in Java I need to split the string following next rules: any of the [ ] , . characters or any sequence of the + - < > should be followed by newline. Here's the input string:

..-<[-]>..[[<<[+[-<-->>+,>-.++]-,>,<[.],][<.,<-]+[-,<->,-]<<[>->-.<-[.<++,>++,].-]]]

And my code:

s = s.replaceAll("(\\+|-|<|>)+", "$0\n")
.replaceAll("\\.|\\,|\\[|\\]", "$0\n");

And the result (SO won't allow this here): https://pastebin.com/ZaT8d5ve
What was expected: https://pastebin.com/gNxcgTSP
It seems that connections of brackets with plus-minus signs are faulty, while angle brackets with square brackets and dot/comma are fine. I can't really get, what's wrong with my solution?

Body:
Your output does exactly what you described, sequence of the + - < > is followed by \n so -< becomes -<\n not -\n<\n.

If I understand you correctly you want to split of sequence of same characters which is either + - < > to have \n after it. If that is the case then instead of

s.replaceAll("(\\+|-|<|>)+", "$0\n")

you can use

s.replaceAll("(\\+|-|<|>)\\1*", "$0\n")

\1 is backreference to match from group 1 (here (\\+|-|<|>)), so it matches one of those characters and its optional following repetitions.


答:
You are almost correct. The problem is with your a=[i]. By using [] brackets you are creating a list, so a is a list, instead of an int.
Change a=i and it will be fine. Also hardcoded range(7) should be changed to range(len(aSequence)). The ideal solution for you would be something like:

```<code>def enum(aSequence):
    result = []
    for i in range(len(aSequence)):
        result.append((i, aSequence[i]))
    return result
</code>```

What you need to remember is the fact, that print is not a return.

Title: Why is my list of Tuples vertical?

Body:
You are almost correct. The problem is with your a=[i]. By using [] brackets you are creating a list, so a is a list, instead of an int.
Change a=i and it will be fine. Also hardcoded range(7) should be changed to range(len(aSequence)). The ideal solution for you would be something like:

def enum(aSequence):
    result = []
    for i in range(len(aSequence)):
        result.append((i, aSequence[i]))
    return result

What you need to remember is the fact, that print is not a return.


问:
access array inside array in angular 4
I'm using angular to create a web project that uses google's custom search engine to populate the web pages with the first ten results returned. The data I get back from the API is in JSON format which I can assess and display using an interface. I'm able access the array "items", my problem is I don't know how to access the array inside the items array. Any help is welcome. Ps. i'm new to angular.

```<code>  interface ISite{
    kind: string;
    title: string;
    htmlTitle: string;
    link: string;
    displayLink: string;
    srcImage: string;
    snippet: string;
}

  //Second interface to deal the api
  interface ISearchResponse {
  kind: string;
  context: string;
  items: ISite[];
  cse_images: string;
  company: string;
  snippet: string;
}

//and my service
  constructor(private _http: HttpClient) { }

   getSites(): Observable<ISearchResponse> {
    return this._http.get<ISearchResponse>(this._siteURL)
      .do(data => console.log('All: ' + JSON.stringify(data)))
      .catch(this.handleError);

  }
  private handleError(err: HttpErrorResponse) {
    console.log('SearchEngineService: ' + err.message);
    return Observable.throw(err.message);
  }
}

    //My html
    <h2>Search Results</h2>
<div class="list-group" *ngFor='let site of sites.items'>
  <a href="{{site.link}}" class="list-group-item list-group-item-action flex-column align-items-start active" >
    <div class="d-flex w-100 justify-content-between">
      <h4 class="mb-1">Title:  {{site.title}}</h4>
    </div>
    <h5>URL: {{site.link}}</h5>
    <p class="mb-1">Description: {{site.snippet}}</p>
  </a>
</div>
</code>```

sample of the data form google api, I want to access the image in
 cse_image

```<code> "items": [
        {
            "kind": "customsearch#result",
        "title": "Sports News,Scores,Schedules,Standings,Stats,Photos",
            "pagemap": {
                "cse_image": [
                    {
                        "src": image.jpg"
                    }
                ]
            }
        },
</code>```

答:
Try this:</p>

```<code><h2>Search Results</h2>
    <div class="list-group" *ngFor='let site of sites.items'>
      <a href="{{site.link}}" class="list-group-item list-group-item-action flex-column align-items-start active" >
        <div class="d-flex w-100 justify-content-between">
          <h4 class="mb-1">Title:  {{site.title}}</h4>
        </div>
        <h5>URL: {{site.link}}</h5>
        <p class="mb-1">Description: {{site.snippet}}</p>
    <img src={{site.pagemap.cse_image[0].src}}>
      </a>
    </div>
</code>```

Title: access array inside array in angular 4

Body:
I'm using angular to create a web project that uses google's custom search engine to populate the web pages with the first ten results returned. The data I get back from the API is in JSON format which I can assess and display using an interface. I'm able access the array "items", my problem is I don't know how to access the array inside the items array. Any help is welcome. Ps. i'm new to angular.

  interface ISite{
    kind: string;
    title: string;
    htmlTitle: string;
    link: string;
    displayLink: string;
    srcImage: string;
    snippet: string;
}

  //Second interface to deal the api
  interface ISearchResponse {
  kind: string;
  context: string;
  items: ISite[];
  cse_images: string;
  company: string;
  snippet: string;
}

//and my service
  constructor(private _http: HttpClient) { }

   getSites(): Observable<ISearchResponse> {
    return this._http.get<ISearchResponse>(this._siteURL)
      .do(data => console.log('All: ' + JSON.stringify(data)))
      .catch(this.handleError);

  }
  private handleError(err: HttpErrorResponse) {
    console.log('SearchEngineService: ' + err.message);
    return Observable.throw(err.message);
  }
}

    //My html

Search Results

Title:  {{site.title}}

URL: {{site.link}}

Description: {{site.snippet}}

sample of the data form google api, I want to access the image in
 cse_image

 "items": [
        {
            "kind": "customsearch#result",
        "title": "Sports News,Scores,Schedules,Standings,Stats,Photos",
            "pagemap": {
                "cse_image": [
                    {
                        "src": image.jpg"
                    }
                ]
            }
        },

Body:
Try this:

<h2>Search Results</h2>
    <div class="list-group" *ngFor='let site of sites.items'>
      <a href="{{site.link}}" class="list-group-item list-group-item-action flex-column align-items-start active" >
        <div class="d-flex w-100 justify-content-between">
          <h4 class="mb-1">Title:  {{site.title}}</h4>
        </div>
        <h5>URL: {{site.link}}</h5>
        <p class="mb-1">Description: {{site.snippet}}</p>
    <img src={{site.pagemap.cse_image[0].src}}>
      </a>
    </div>


问:
mvn install jar-with-dependencies
Is there a way to do an install on a jar-with-dependencies created using maven-assembly-plugin?</p>

答:
One way would be to create a project where you use the assembly-plugin. In the assembly-plugin configuration you can specify what output you want (jar, zip, ...)

In this projects pom you can put your dependencies and build it. Every time you execute the install command all your dependencies will be in your packaged file.

Title: mvn install jar-with-dependencies


问:
Titanium open url with a done button in browser window
In Titanium I know it is possible to open a URL in a browser like so:

```<code>Ti.Platform.openURL("http://example.com/foo");
</code>```

However this opens it up in a browser like this:

Compare that to other iOS apps like Slack and it looks like this:

As you can see at the top it has a done button and it is not possible to change the url. There is also an option to open it up on Safari.

Open it up on Facebook messenger iOS app and it looks like this:

How can I change the way Titanium opens URL's on iOS so that it uses a browser like the one used in Slack.

答:
What you're looking for is the native component for that, which is wrapper by Appcelerator in the module ti.safaridialog. You can see specs about it in the documentation

Add it to your app

```<code><module platform="iphone">ti.safaridialog</module>
</code>```

And then use it

```<code>var dialog = require('ti.safaridialog');
if (dialog.isSupported()) {
    dialog.open({
        url: 'http://appcelerator.com',
        title: 'Titanium rocks!',
        tintColor: 'red'
    });
}
</code>```

Body:
In Titanium I know it is possible to open a URL in a browser like so:

Ti.Platform.openURL("http://example.com/foo");

However this opens it up in a browser like this:

Compare that to other iOS apps like Slack and it looks like this:

As you can see at the top it has a done button and it is not possible to change the url. There is also an option to open it up on Safari.

Open it up on Facebook messenger iOS app and it looks like this:

How can I change the way Titanium opens URL's on iOS so that it uses a browser like the one used in Slack.

Body:
What you're looking for is the native component for that, which is wrapper by Appcelerator in the module ti.safaridialog. You can see specs about it in the documentation

Add it to your app

<module platform="iphone">ti.safaridialog</module>

And then use it

var dialog = require('ti.safaridialog');
if (dialog.isSupported()) {
    dialog.open({
        url: 'http://appcelerator.com',
        title: 'Titanium rocks!',
        tintColor: 'red'
    });
}


问:
Connecting to a telnet server in NodeJS
There is a particular equipment here that can only be controlled via telnet, which I have been doing (through PuTTy or Terminal) for a while now.

In NodeJS, I created a web interface that would make it easier to control the equipment. I did this by running different bash scripts for different commands sent through telnet. This is working fine, but it felt too unorganized, and not to mention the clutter of shell scripts for each command. I'm looking for a better way of doing this.

I thought of connecting to the telnet server directly from NodeJS. I have tried different packages (i.e. net, telnet-client, telnet-stream, another-telnet-client, etc) but it's either those aren't the tools I need or I'm just not implementing it correctly.

Here's a sample code I'm testing using the telnet-client package (others are just variations of this):

```<code>const telnet = require('telnet-client');
const server = new telnet();

// display server response
server.on("data", function(data){
    console.log(''+data);
});

// login when connected
server.on("connect", function(){
    server.write("login <user> <pass>");
});

// connect to server
server.connect({
    host: "172.16.0.1",
    port: 9600
});
</code>```

When done manually, after the "login" request, I should see a "login successful" message but I'm not getting anything back.

Is this code incorrect? I'm not familiar with telnet and would really appreciate any help.

答:
Just going to write the answer here in case anyone's having the same problem.

My problem was fixed simply by adding a carriage return and a line feed at the end of the string I'm sending to the server.

```<code>server.write("login <user> <pass>\r\n");
</code>```

Title: Connecting to a telnet server in NodeJS

Body:
There is a particular equipment here that can only be controlled via telnet, which I have been doing (through PuTTy or Terminal) for a while now.

In NodeJS, I created a web interface that would make it easier to control the equipment. I did this by running different bash scripts for different commands sent through telnet. This is working fine, but it felt too unorganized, and not to mention the clutter of shell scripts for each command. I'm looking for a better way of doing this.

I thought of connecting to the telnet server directly from NodeJS. I have tried different packages (i.e. net, telnet-client, telnet-stream, another-telnet-client, etc) but it's either those aren't the tools I need or I'm just not implementing it correctly.

Here's a sample code I'm testing using the telnet-client package (others are just variations of this):

const telnet = require('telnet-client');
const server = new telnet();

// display server response
server.on("data", function(data){
    console.log(''+data);
});

// login when connected
server.on("connect", function(){
    server.write("login <user> <pass>");
});

// connect to server
server.connect({
    host: "172.16.0.1",
    port: 9600
});

When done manually, after the "login" request, I should see a "login successful" message but I'm not getting anything back.

Is this code incorrect? I'm not familiar with telnet and would really appreciate any help.

Body:
Just going to write the answer here in case anyone's having the same problem.

My problem was fixed simply by adding a carriage return and a line feed at the end of the string I'm sending to the server.

server.write("login <user> <pass>\r\n");


答:
An onClick on a <button /> would have worked as you expected.

But this is <Button /> a component which you created, the onClick will be sent as props which you can invoke through an onClick on the Button component's a tag like below, whose handleClick will callback the actual onClick on your PanelButtons component.

```<code>const buttonStyle = {
  color: 'red'
};

class Button extends React.Component {

    handleClick = (e) => {
      this.props.onClick(e)
    }

    render() {
        return (
          <a className="social-button twitter" onClick={this.handleClick}>
            <i href="#" className="fa fa-twitter"></i>
          </a>
        )};
}

class PanelButtons extends React.Component {
  constructor(props){
    super(props);
    }

  handleClick() {
    console.log('this is:');
  }

    render() {
        return (
          <div>
          <div onClick={(e) => this.handleClick(e)}> {/*this works attaching it to a div*/}
            CLick me
            </div>
            <div className="social-buttons">
                <Button onClick={(e) => this.handleClick(e)} />{/*does now work attaching it to a component*/}
            </div>
           </div>
        )
    }
}

ReactDOM.render(<PanelButtons />,  document.querySelector('body'));
</code>```

If you just want to add an onClick in the PanelButtons for each button, just modify your render a little bit like this by adding event listener on the div tag.

```<code>render() {
    return (
      <div>
      <div onClick={(e) => this.handleClick(e)}> {/*this works attaching it to a div*/}
        CLick me
        </div>
        <div className="social-buttons" onClick={(e) => this.handleClick(e)}>
            <Button />{/*does now work attaching it to a component*/}
        </div>
       </div>
    )
}
</code>```

Title: Event Handler on component in Reactjs

Body:
An onClick on a <button /> would have worked as you expected.

But this is <Button /> a component which you created, the onClick will be sent as props which you can invoke through an onClick on the Button component's a tag like below, whose handleClick will callback the actual onClick on your PanelButtons component.

const buttonStyle = {
  color: 'red'
};

class Button extends React.Component {

    handleClick = (e) => {
      this.props.onClick(e)
    }

    render() {
        return (
          <a className="social-button twitter" onClick={this.handleClick}>
            <i href="#" className="fa fa-twitter"></i>
          </a>
        )};
}

class PanelButtons extends React.Component {
  constructor(props){
    super(props);
    }

  handleClick() {
    console.log('this is:');
  }

    render() {
        return (
          <div>
          <div onClick={(e) => this.handleClick(e)}> {/*this works attaching it to a div*/}
            CLick me
            </div>
            <div className="social-buttons">
                <Button onClick={(e) => this.handleClick(e)} />{/*does now work attaching it to a component*/}
            </div>
           </div>
        )
    }
}

ReactDOM.render(<PanelButtons />,  document.querySelector('body'));

If you just want to add an onClick in the PanelButtons for each button, just modify your render a little bit like this by adding event listener on the div tag.

render() {
    return (
      <div>
      <div onClick={(e) => this.handleClick(e)}> {/*this works attaching it to a div*/}
        CLick me
        </div>
        <div className="social-buttons" onClick={(e) => this.handleClick(e)}>
            <Button />{/*does now work attaching it to a component*/}
        </div>
       </div>
    )
}


问:
Load lottery drawings from file like this way in python?
I want to create a python script to analyze and generate lottery prediction numbers based on already done drawings.
For this I need first to load lottery drawings from a text file into some kind of python container (I don't know yet if a list is the best one).
The text file is like follow:

```<code>08-08-93 38 17 47 25 30 37
15-08-93 6 7 30 17 2 42
22-08-93 44 20 17 3 38 45
29-08-93 42 30 36 5 4 6
05-09-93 5 14 7 49 35 19
12-09-93 42 28 41 15 22 38
19-09-93 18 4 16 35 2 17
03-10-93 44 48 34 37 4 41
17-10-93 13 7 6 45 29 25
24-10-93 8 22 43 14 34 15
31-10-93 14 17 47 19 36 12
14-11-93 48 20 6 43 4 35
</code>```

First one is the date which can have different format (yy-mm-dd or dd-mm-yyyy etc.) and after that follow the numbers.
I want to analyze easily just the numbers to do e.g. average, sum, stdev etc. and based on this I want to generate other lottery combinations with the same specifications.
I would like to have/keep the date for each drawing in order to access it faster when I need e.g. print draw from 14-11-83 or the script itself should say to me something like: "general average is xx.xx and yy drawings fall out of this range, they are: "date: 14-11-93: num1, num2, num3 etc. and 23-09-14: num1, num2, num3 etc."
That's why I want to keep the date but also to use a container which is easy to loop through.
something like:

```<code>list a = ['date', int num1, int num2, int num3, int num4, int num5, int num6]
</code>```

but when looping it should skip the date (first element a[0]).
Other way I think is a dictionary but is it so easy to loop all of that ?

I tried a few other pieces of code from here but seems to not work:

```<code>with open('lotto.txt') as f:
    content = f.readlines()
    # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip('') for x in content]
    print content
</code>```

答:
Try this

```<code>with open('lotto.txt') as f:
     line = f.readline()
     a = line.split()
</code>```

a will now be the list as you requested.

Body:
I want to create a python script to analyze and generate lottery prediction numbers based on already done drawings.
For this I need first to load lottery drawings from a text file into some kind of python container (I don't know yet if a list is the best one).
The text file is like follow:

08-08-93 38 17 47 25 30 37
15-08-93 6 7 30 17 2 42
22-08-93 44 20 17 3 38 45
29-08-93 42 30 36 5 4 6
05-09-93 5 14 7 49 35 19
12-09-93 42 28 41 15 22 38
19-09-93 18 4 16 35 2 17
03-10-93 44 48 34 37 4 41
17-10-93 13 7 6 45 29 25
24-10-93 8 22 43 14 34 15
31-10-93 14 17 47 19 36 12
14-11-93 48 20 6 43 4 35

First one is the date which can have different format (yy-mm-dd or dd-mm-yyyy etc.) and after that follow the numbers.
I want to analyze easily just the numbers to do e.g. average, sum, stdev etc. and based on this I want to generate other lottery combinations with the same specifications.
I would like to have/keep the date for each drawing in order to access it faster when I need e.g. print draw from 14-11-83 or the script itself should say to me something like: "general average is xx.xx and yy drawings fall out of this range, they are: "date: 14-11-93: num1, num2, num3 etc. and 23-09-14: num1, num2, num3 etc."
That's why I want to keep the date but also to use a container which is easy to loop through.
something like:

list a = ['date', int num1, int num2, int num3, int num4, int num5, int num6]

but when looping it should skip the date (first element a[0]).
Other way I think is a dictionary but is it so easy to loop all of that ?

I tried a few other pieces of code from here but seems to not work:

with open('lotto.txt') as f:
    content = f.readlines()
    # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip('') for x in content]
    print content

Body:
Try this

with open('lotto.txt') as f:
     line = f.readline()
     a = line.split()

a will now be the list as you requested.


问:
Swift GeoFire Error Linker Error _OBJC_CLASS_$_GeoFire
I can compile and build the apps probably until I add this 2 line of geofire code, I get the linker error

```<code>  let geofireRef = Database.database().reference().child("USER")

override func viewDidLoad() {
    super.viewDidLoad()

  let geoFire = GeoFire(firebaseRef: geofireRef)
}
</code>```

I have been stuck in this error for couple hours. Still not sure what and how to solve.
It is my Podfile

```<code>   # Uncomment the next line to define a global platform for your project
 platform :ios, '11.0'

target 'App' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  pod 'Firebase'
  pod 'FirebaseCore’
  pod 'FirebaseAuth'
  pod 'FirebaseStorage'
  pod 'FirebaseDatabase'
  pod 'Material'
  pod 'Kingfisher', '~> 4.0'
  pod 'MapKitGoogleStyler'
  pod 'GeoFire', :git => 'https://github.com/firebase/geofire-objc.git'
  pod 'Mapbox-iOS-SDK', '~> 3.6'
  pod 'MapboxDirections.swift', '~> 0.12'

  #Pods for App

  target 'AppTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'AppUITests' do
    inherit! :search_paths
    # Pods for testing
  end
</code>```

And it is the Error I got from XCode

Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_GeoFire", referenced from:
      objc-class-ref in SecondMainViewController.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

答:
I am not sure why but I found out the answer by adding pod 'GeoFire', :git => 'https://github.com/firebase/geofire-objc.git', :branch => 'mpmcdonald-use-community' and it run prefectly.

Reference Link from Github

Body:
I can compile and build the apps probably until I add this 2 line of geofire code, I get the linker error

  let geofireRef = Database.database().reference().child("USER")

override func viewDidLoad() {
    super.viewDidLoad()

  let geoFire = GeoFire(firebaseRef: geofireRef)
}

I have been stuck in this error for couple hours. Still not sure what and how to solve.
It is my Podfile

   # Uncomment the next line to define a global platform for your project
 platform :ios, '11.0'

target 'App' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  pod 'Firebase'
  pod 'FirebaseCore’
  pod 'FirebaseAuth'
  pod 'FirebaseStorage'
  pod 'FirebaseDatabase'
  pod 'Material'
  pod 'Kingfisher', '~> 4.0'
  pod 'MapKitGoogleStyler'
  pod 'GeoFire', :git => 'https://github.com/firebase/geofire-objc.git'
  pod 'Mapbox-iOS-SDK', '~> 3.6'
  pod 'MapboxDirections.swift', '~> 0.12'

  #Pods for App

  target 'AppTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'AppUITests' do
    inherit! :search_paths
    # Pods for testing
  end

And it is the Error I got from XCode

Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_GeoFire", referenced from:
      objc-class-ref in SecondMainViewController.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)


问:
Different Result from SAS Proc univariate and R quantile function
I used function quantile in R to do the calculation of 90th, 75th, 50th, 25th percentile, but then my colleague used SAS proc univariate to do the same calculation, we got quite different results (for example, 90th percentile from R is 47.36, but 90th percentile from SAS is 50.64). I'm trying to figure out why. Could anybody give me some guidance on this?

R code:

quantile(c(43.55,41.30,39.40,40.93,38.74,39.97,45.38,41.48,45.01,42.03,44.71,43.42,45.83,43.44,37.84,50.64,53.16,45.95), prob=c(0.90, 0.10, 0.75, 0.50, 0.25))

SAS code:

```<code>    data x;
    input x;
    datalines;
    43.55
    41.30
    39.40
    40.93
    38.74
    39.97
    45.38
    41.48
    45.01
    42.03
    44.71
    43.42
    45.83
    43.44
    37.84
    50.64
    53.16
    45.95

    ;
    run;
    proc univariate data=x noprint ;
    var x;
    output out=new  p90=p90 p10=p10 q3=p75 median=p50 q1=p25 ;
    run;
</code>```

Body:
I used function quantile in R to do the calculation of 90th, 75th, 50th, 25th percentile, but then my colleague used SAS proc univariate to do the same calculation, we got quite different results (for example, 90th percentile from R is 47.36, but 90th percentile from SAS is 50.64). I'm trying to figure out why. Could anybody give me some guidance on this?

R code:

quantile(c(43.55,41.30,39.40,40.93,38.74,39.97,45.38,41.48,45.01,42.03,44.71,43.42,45.83,43.44,37.84,50.64,53.16,45.95), prob=c(0.90, 0.10, 0.75, 0.50, 0.25))

SAS code:

    data x;
    input x;
    datalines;
    43.55
    41.30
    39.40
    40.93
    38.74
    39.97
    45.38
    41.48
    45.01
    42.03
    44.71
    43.42
    45.83
    43.44
    37.84
    50.64
    53.16
    45.95

    ;
    run;
    proc univariate data=x noprint ;
    var x;
    output out=new  p90=p90 p10=p10 q3=p75 median=p50 q1=p25 ;
    run;

Body:
Default method in R is 7 while in SAS default is probably empirical distribution function with averaging .

If you use add option type = 1 in R you will get same result as in SAS.

quantile(c(43.55,41.30,39.40,40.93,38.74,39.97,45.38,41.48,45.01,
           42.03,44.71,43.42,45.83,43.44,37.84,50.64,53.16,45.95),
         prob=c(0.90, 0.10, 0.75, 0.50, 0.25),
         type = 1)
  90%   10%   75%   50%   25%
50.64 38.74 45.38 43.42 40.93


答:
You seem to think that

```<code>(\\+|-|<|>)+
</code>```

would match only sequences of identical characters like ++ whereas it also matches any sequence of these characters like -<-->>.

You also don't need two regexes in sequence. The following should do:

```<code>s = s.replaceAll("([+<>-])\\1*|[,.\\[\\]]", "$0\n");
</code>```

Title: Regex not always working with angle brackets

Body:
You seem to think that

(\\+|-|<|>)+

would match only sequences of identical characters like ++ whereas it also matches any sequence of these characters like -<-->>.

You also don't need two regexes in sequence. The following should do:

s = s.replaceAll("([+<>-])\\1*|[,.\\[\\]]", "$0\n");