问:
count function mechanism in laravel
suppose we have this code

result of count() function is about each query or after queries
executes then count function return result ?

```<code>$model=Model::query()

foreach ($Entities as $entity) {
               $model->orWhereBetween("id",$entity->first_id,$entity->last_id])
         }
$model->count()
</code>```

答:
Salam ,

Answer : It depends on when you call count method !

In your code :

```<code>$model=Model::query();
$model2 = $model;

foreach ($Entities as $entity) {
//you should save your where between in self $model varriable
    $model = $model->orWhereBetween("id",$entity->first_id,$entity->last_id])
}

//$model - object of query builder
$model->count();//After operations and filtering
$model2->count();//Before operations and filtering (  It is equal or more than $model->count()  )
</code>```

I hope this helps you :)

Title: count function mechanism in laravel

Body:
suppose we have this code

result of count() function is about each query or after queries
executes then count function return result ?

$model=Model::query()

foreach ($Entities as $entity) {
               $model->orWhereBetween("id",$entity->first_id,$entity->last_id])
         }
$model->count()

Body:
Salam ,

Answer : It depends on when you call count method !

In your code :

$model=Model::query();
$model2 = $model;

foreach ($Entities as $entity) {
//you should save your where between in self $model varriable
    $model = $model->orWhereBetween("id",$entity->first_id,$entity->last_id])
}

//$model - object of query builder
$model->count();//After operations and filtering
$model2->count();//Before operations and filtering (  It is equal or more than $model->count()  )

I hope this helps you :)


来源: stackexchange

问:
How to create unique batch number for the day
I want create unique batch number for the day,tomorrow batch number should be max(batchno)+1 . and serial number should be maintain as follows

record set should be as follows

```<code>ID    | invoice date   | Batchno     |  seqno
1     | 2019-05-24     |201905000001 | 1
2     | 2019-05-24     |201905000001 | 2
3     | 2019-05-25     |201905000002 | 1
4     | 2019-05-25     |201905000002 | 2

   ON  [dbo].[EBSIEMSTransfernew]
   AFTER INSERT

AS

 declare @year varchar(4)
 declare @month varchar(2)
 declare @serialNo varchar(10)

 select @year = year(getdate())
 select @month = REPLICATE('0', 2-len( month(getdate())))+ cast(month(getdate()) as varchar)
 select @serialNo = Max(right(BatchNo,5)) FROM  [Onaccount].[dbo].[EBSIEMSTransfernew] where InvoiceDate >= dateadd(day,datediff(day,1,GETDATE()),0)
 AND InvoiceDate < dateadd(day,datediff(day,0,GETDATE()),0)

BEGIN

UPDATE    [Onaccount].[dbo].[EBSIEMSTransfernew]
SET              BatchNo = @year + @month + REPLICATE('0', 5 - LEN(@serialNo + 1)) + CAST(@serialNo + 1 AS varchar)
FROM         [Onaccount].[dbo].[EBSIEMSTransfernew] INNER JOIN
                      inserted AS i ON EBSIEMSTransfernew.InvoiceDate = i.InvoiceDate
WHERE     (EBSIEMSTransfernew.InvoiceDate = i.InvoiceDate)

SET NOCOUNT ON;

END

GO
</code>```

答:
A trigger seems silly.  Why not just use a computed column?

```<code>alter table EBSIEMSTransfernew
    add batchnumber = datediff(day, '2019-05-04', invoice_date);
</code>```

Admittedly, this will skip days when there are no batches.  If that is an issue, you could generate the value in a view:

```<code>create view v_EBSIEMSTransfernew as
    select t.*,
           dense_rank() over (order by invoice_date)
    from EBSIEMSTransfernew t;
</code>```

Your description of your issue only mentions a number.  I'm not sure where the rest of the number comes from, but you can modify either of these approaches to add a prefix.

ContentLicense: CC BY-SA 4.0

Body:
I want create unique batch number for the day,tomorrow batch number should be max(batchno)+1 . and serial number should be maintain as follows

record set should be as follows

ID    | invoice date   | Batchno     |  seqno
1     | 2019-05-24     |201905000001 | 1
2     | 2019-05-24     |201905000001 | 2
3     | 2019-05-25     |201905000002 | 1
4     | 2019-05-25     |201905000002 | 2

   ON  [dbo].[EBSIEMSTransfernew]
   AFTER INSERT

AS

 declare @year varchar(4)
 declare @month varchar(2)
 declare @serialNo varchar(10)

 select @year = year(getdate())
 select @month = REPLICATE('0', 2-len( month(getdate())))+ cast(month(getdate()) as varchar)
 select @serialNo = Max(right(BatchNo,5)) FROM  [Onaccount].[dbo].[EBSIEMSTransfernew] where InvoiceDate >= dateadd(day,datediff(day,1,GETDATE()),0)
 AND InvoiceDate < dateadd(day,datediff(day,0,GETDATE()),0)

BEGIN

UPDATE    [Onaccount].[dbo].[EBSIEMSTransfernew]
SET              BatchNo = @year + @month + REPLICATE('0', 5 - LEN(@serialNo + 1)) + CAST(@serialNo + 1 AS varchar)
FROM         [Onaccount].[dbo].[EBSIEMSTransfernew] INNER JOIN
                      inserted AS i ON EBSIEMSTransfernew.InvoiceDate = i.InvoiceDate
WHERE     (EBSIEMSTransfernew.InvoiceDate = i.InvoiceDate)

SET NOCOUNT ON;

END

GO

Body:
A trigger seems silly.  Why not just use a computed column?

alter table EBSIEMSTransfernew
    add batchnumber = datediff(day, '2019-05-04', invoice_date);

Admittedly, this will skip days when there are no batches.  If that is an issue, you could generate the value in a view:

create view v_EBSIEMSTransfernew as
    select t.*,
           dense_rank() over (order by invoice_date)
    from EBSIEMSTransfernew t;

Your description of your issue only mentions a number.  I'm not sure where the rest of the number comes from, but you can modify either of these approaches to add a prefix.


问:
What is the significance of class data type in java?
Noob question.

I have been programming at basic level for quite a while but I have trouble understanding class data type.

when we say int a = 9;
it means a is of data type int meaning it can contain only integers.

like wise for String, boolean, double, float etc.

But consider the following code:

```<code>Class Node {

Node next = null;
int data;

public Node(int d){ data = d; }

void append(int d)
    {
        blah blah blah
        ..............
    }
}
</code>```

What does Node next = null; mean? I can understand the effort to create an object with

```<code>Node next = new Node();
</code>```

and then try to manipulate the next object.

答:
Node next = null means that this variable is initialized with null value, and doesn't point to any memory location.

So there isn't yest added the next "neighbor" node.

ContentLicense: CC BY-SA 3.0

Body:
Noob question.

I have been programming at basic level for quite a while but I have trouble understanding class data type.

when we say int a = 9;
it means a is of data type int meaning it can contain only integers.

like wise for String, boolean, double, float etc.

But consider the following code:

Class Node {

Node next = null;
int data;

public Node(int d){ data = d; }

void append(int d)
    {
        blah blah blah
        ..............
    }
}

What does Node next = null; mean? I can understand the effort to create an object with

Node next = new Node();

and then try to manipulate the next object.


问:
Scroll behaviour of AndroidX RecyclerView view with NestedScrollView
I'm migrating my application from appcompat to AndroidX. Everything works except that I am not able to set one scroll for both androidx.core.widget.NestedScrollView and
 androidx.recyclerview.widget.RecyclerView.

I have tried adding

setHasFixedSize(true)
setNestedScrollingEnabled(false)
```

<p>but it's not working. My XML now looks this way: </p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView
    android:clipToPadding="false"
    android:id="@+id/scroll"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:paddingBottom="5dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:background="@color/white"
        android:id="@+id/itenarydays"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="horizontal">

        <FrameLayout
            android:background="@drawable/roundshape"
            android:layout_gravity="center"
            android:layout_height="56dp"
            android:layout_margin="3dp"
            android:layout_width="56dp"
            android:padding="@dimen/textsise10">

            <ImageView
                android:layout_gravity="center"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:tint="@color/white"
                app:srcCompat="@drawable/ic_sketch" />
        </FrameLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:animationCache="true"
            android:clipToPadding="false"
            android:id="@+id/list_daycount"
            android:layout_gravity="center"
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:nestedScrollingEnabled="false"
            android:orientation="horizontal"
            android:scrollbars="none"

            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"></androidx.recyclerview.widget.RecyclerView>

        <FrameLayout
            android:background="@drawable/shape_redround"
            android:id="@+id/framelyt_add"
            android:layout_gravity="center"
            android:layout_height="56dp"
            android:layout_margin="3dp"
            android:layout_width="56dp"
            android:padding="@dimen/textsise10">

            <ImageView
                android:layout_gravity="center"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:tint="@color/white"
                app:srcCompat="@drawable/ic_plus" />
        </FrameLayout>
    </LinearLayout>

</androidx.core.widget.NestedScrollView>
</code>```

答:
use this:

```<code>app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
</code>```

instead of this:

```<code>app:layout_behavior="@string/appbar_scrolling_view_behavior"
</code>```

Body:
I'm migrating my application from appcompat to AndroidX. Everything works except that I am not able to set one scroll for both androidx.core.widget.NestedScrollView and
 androidx.recyclerview.widget.RecyclerView.

I have tried adding

setHasFixedSize(true)
setNestedScrollingEnabled(false)

but it's not working. My XML now looks this way:

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView
    android:clipToPadding="false"
    android:id="@+id/scroll"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:paddingBottom="5dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:background="@color/white"
        android:id="@+id/itenarydays"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="horizontal">

        <FrameLayout
            android:background="@drawable/roundshape"
            android:layout_gravity="center"
            android:layout_height="56dp"
            android:layout_margin="3dp"
            android:layout_width="56dp"
            android:padding="@dimen/textsise10">

            <ImageView
                android:layout_gravity="center"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:tint="@color/white"
                app:srcCompat="@drawable/ic_sketch" />
        </FrameLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:animationCache="true"
            android:clipToPadding="false"
            android:id="@+id/list_daycount"
            android:layout_gravity="center"
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:nestedScrollingEnabled="false"
            android:orientation="horizontal"
            android:scrollbars="none"

            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"></androidx.recyclerview.widget.RecyclerView>

        <FrameLayout
            android:background="@drawable/shape_redround"
            android:id="@+id/framelyt_add"
            android:layout_gravity="center"
            android:layout_height="56dp"
            android:layout_margin="3dp"
            android:layout_width="56dp"
            android:padding="@dimen/textsise10">

            <ImageView
                android:layout_gravity="center"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:tint="@color/white"
                app:srcCompat="@drawable/ic_plus" />
        </FrameLayout>
    </LinearLayout>

</androidx.core.widget.NestedScrollView>

Body:
use this:

app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"

instead of this:

app:layout_behavior="@string/appbar_scrolling_view_behavior"


问:
Find same position in two strings that are slightly different
I have two strings where the first is a master string and the second is a slave string. They both contain similar values except that the slave will have characters added or removed.

I need to find the character offset from the master string in the slave string for each character of the master string.

I'm currently using a percentage as the algorithm for finding the similar offset in the slave string.

For example;

```<code>const master = 'The chicken is blue, but not really a chicken';
const slave = 'This large bird is blue, but is really a dog';

function slaveOffset(m, offset, s): number {
    return Math.floor(s.length * (offset / m.length));
}

console.log(slaveOffset(master, 15, slave)); // prints 12
</code>```

When translating the position 15 from the master (which reads "The chicken is ") the slave position is calculated as 12. Which reads as "This large b" because using percentage is not at all accurate (doesn't take into account added or removed characters).

The correct value should have been 18 (which reads as "The large bird is"), because the master offset ends at "is".

I need an algorithm for slaveOffset() that can handle added and removed characters and find the most likely slave offset. It does not need to be overly accurate but should solve the problem of large deviations caused by character changes.

答:
This is a classic problem in computer science, typically called "data comparison" or simply "diff". The most common algorithms apply Longest Common Subsequence techniques, but in the general case this is a NP-hard problem so various heuristics are applied to get a "good enough" outcome, often tuned by a human in the loop.

Look up some diff algorithms to get some ideas.

In your case you probably want to start with the heuristic of "where does the slave string start to differ from the master and where does it become the same again". The strings match for the first two characters, but the next time you get a sequence of more than 3 characters matching is at the characters , i and s. The points become markers that you can use in your slaveOffset function.

Body:
I have two strings where the first is a master string and the second is a slave string. They both contain similar values except that the slave will have characters added or removed.

I need to find the character offset from the master string in the slave string for each character of the master string.

I'm currently using a percentage as the algorithm for finding the similar offset in the slave string.

For example;

const master = 'The chicken is blue, but not really a chicken';
const slave = 'This large bird is blue, but is really a dog';

function slaveOffset(m, offset, s): number {
    return Math.floor(s.length * (offset / m.length));
}

console.log(slaveOffset(master, 15, slave)); // prints 12

When translating the position 15 from the master (which reads "The chicken is ") the slave position is calculated as 12. Which reads as "This large b" because using percentage is not at all accurate (doesn't take into account added or removed characters).

The correct value should have been 18 (which reads as "The large bird is"), because the master offset ends at "is".

I need an algorithm for slaveOffset() that can handle added and removed characters and find the most likely slave offset. It does not need to be overly accurate but should solve the problem of large deviations caused by character changes.


问:
DirectShow filter that scales up the framerate of a video
I'm currently working on a software that is simultanously recording two videos. The first one has a framerate of 25fps, the second has a framerate of 10fps (or maybe 15fps in the future). Later, these two videos are put together into one video with a picture in picture. The problem is, that the DirectShow Filter for picture in picture doesn't support videos with different framerates. Now I'm looking for a DirectShow filter that can produce "dummy frames" to scale up the framerate of the second video to 25fps. Does anyone know such a DirectShow filter?

Thanks in advance, David

答:
The answer given by Appleton is correct.  I am expanding on that answer, providing some sample code (in C++/CLI) showing how to instantiate the filter for a manually-built DirectShow graph (picking up the pieces from the available sparse documentation can be time-consuming).   The relevant code is inside the REDUCE_FRAME_RATE conditionally-compiled code. COM_CALL() is my custom HRESULT checking macro.

```<code>// Additional include files required for DMO support

#include <ParserUIDs.h>
#include <dmodshow.h>
#include <propsys.h>
    …

static void AddDecodedVideoSampleGrabber(
      AVStreamSourceBox^ sourceBox,
      IGraphBuilder* pGraph,
      CComPtr<IBaseFilter>& pDecodedVideoSampleGrabber,
      IPin* pSourcePin,
      CComPtr<IPin>& pDecodedVideoSampleGrabberOutPin
   ) {
      HRESULT hRes;

      COM_CALL(pDecodedVideoSampleGrabber.CoCreateInstance(CLSID_SampleGrabber));
      COM_CALL(pGraph->AddFilter(pDecodedVideoSampleGrabber, L"DecodedVideoSampleGrabber"));
      CComPtr<IPin> pDecodedVideoSampleGrabberInPin(FilterTools::GetPin(pDecodedVideoSampleGrabber, "Input"));
      COM_CALL(pGraph->ConnectDirect(pSourcePin, pDecodedVideoSampleGrabberInPin, NULL));
      pDecodedVideoSampleGrabberOutPin = FilterTools::GetPin(pDecodedVideoSampleGrabber, "Output");

      auto pFrameCallbackSink = (SampleGrabberCBSink*)sourceBox->SetupSampleGrabberCallback(
         FRAME_SAMPLE_GRABBER,
         IntPtr(pDecodedVideoSampleGrabber)
      ).ToPointer();
      sourceBox->SetDecodedVideoSampleGrabber(IntPtr(pFrameCallbackSink));

   #ifdef REDUCE_FRAME_RATE
      // insert frame-reduction filter before x264 encoding
      CComPtr<IBaseFilter> pFrameReducer;
      COM_CALL(pFrameReducer.CoCreateInstance(CLSID_DMOWrapperFilter));
      COM_CALL(pGraph->AddFilter(pFrameReducer, L"FrameReducer"));

      CComPtr<IDMOWrapperFilter> pDmoWrapper;
      COM_CALL(pFrameReducer->QueryInterface(__uuidof(IDMOWrapperFilter), (void**)&pDmoWrapper));
      COM_CALL(pDmoWrapper->Init(__uuidof(CFrameRateConvertDmo), DMOCATEGORY_VIDEO_EFFECT));
      CComPtr<IPropertyStore> pPropStore;
      COM_CALL(pFrameReducer->QueryInterface(IID_PPV_ARGS(&pPropStore)));

      PROPVARIANT var;
      PropVariantInit(&var);
      var.vt = VT_UI8;
      var.uhVal.HighPart = OUTPUT_FPS;    // Desired frame rate
      var.uhVal.LowPart = 1;
      pPropStore->SetValue(MFPKEY_CONV_OUTPUTFRAMERATE, var);
      PropVariantClear(&var);
      CComPtr<IPin>&pDmoInPin(FilterTools::GetPin(pFrameReducer, "in0"));
      COM_CALL(pGraph->ConnectDirect(pDecodedVideoSampleGrabberOutPin, pDmoInPin, NULL));
      CComPtr<IPin>&pDmoOutPin(FilterTools::GetPin(pFrameReducer, "out0"));
      pDecodedVideoSampleGrabberOutPin = pDmoOutPin;
   #endif

   }
</code>```

Body:
The answer given by Appleton is correct.  I am expanding on that answer, providing some sample code (in C++/CLI) showing how to instantiate the filter for a manually-built DirectShow graph (picking up the pieces from the available sparse documentation can be time-consuming).   The relevant code is inside the REDUCE_FRAME_RATE conditionally-compiled code. COM_CALL() is my custom HRESULT checking macro.

// Additional include files required for DMO support

#include <ParserUIDs.h>
#include <dmodshow.h>
#include <propsys.h>
    …

static void AddDecodedVideoSampleGrabber(
      AVStreamSourceBox^ sourceBox,
      IGraphBuilder* pGraph,
      CComPtr<IBaseFilter>& pDecodedVideoSampleGrabber,
      IPin* pSourcePin,
      CComPtr<IPin>& pDecodedVideoSampleGrabberOutPin
   ) {
      HRESULT hRes;

      COM_CALL(pDecodedVideoSampleGrabber.CoCreateInstance(CLSID_SampleGrabber));
      COM_CALL(pGraph->AddFilter(pDecodedVideoSampleGrabber, L"DecodedVideoSampleGrabber"));
      CComPtr<IPin> pDecodedVideoSampleGrabberInPin(FilterTools::GetPin(pDecodedVideoSampleGrabber, "Input"));
      COM_CALL(pGraph->ConnectDirect(pSourcePin, pDecodedVideoSampleGrabberInPin, NULL));
      pDecodedVideoSampleGrabberOutPin = FilterTools::GetPin(pDecodedVideoSampleGrabber, "Output");

      auto pFrameCallbackSink = (SampleGrabberCBSink*)sourceBox->SetupSampleGrabberCallback(
         FRAME_SAMPLE_GRABBER,
         IntPtr(pDecodedVideoSampleGrabber)
      ).ToPointer();
      sourceBox->SetDecodedVideoSampleGrabber(IntPtr(pFrameCallbackSink));

   #ifdef REDUCE_FRAME_RATE
      // insert frame-reduction filter before x264 encoding
      CComPtr<IBaseFilter> pFrameReducer;
      COM_CALL(pFrameReducer.CoCreateInstance(CLSID_DMOWrapperFilter));
      COM_CALL(pGraph->AddFilter(pFrameReducer, L"FrameReducer"));

      CComPtr<IDMOWrapperFilter> pDmoWrapper;
      COM_CALL(pFrameReducer->QueryInterface(__uuidof(IDMOWrapperFilter), (void**)&pDmoWrapper));
      COM_CALL(pDmoWrapper->Init(__uuidof(CFrameRateConvertDmo), DMOCATEGORY_VIDEO_EFFECT));
      CComPtr<IPropertyStore> pPropStore;
      COM_CALL(pFrameReducer->QueryInterface(IID_PPV_ARGS(&pPropStore)));

      PROPVARIANT var;
      PropVariantInit(&var);
      var.vt = VT_UI8;
      var.uhVal.HighPart = OUTPUT_FPS;    // Desired frame rate
      var.uhVal.LowPart = 1;
      pPropStore->SetValue(MFPKEY_CONV_OUTPUTFRAMERATE, var);
      PropVariantClear(&var);
      CComPtr<IPin>&pDmoInPin(FilterTools::GetPin(pFrameReducer, "in0"));
      COM_CALL(pGraph->ConnectDirect(pDecodedVideoSampleGrabberOutPin, pDmoInPin, NULL));
      CComPtr<IPin>&pDmoOutPin(FilterTools::GetPin(pFrameReducer, "out0"));
      pDecodedVideoSampleGrabberOutPin = pDmoOutPin;
   #endif

   }


问:
setText function does not change the TextView
the app runs the way I want I can see that in the Logcat
but the text view is not changing and keeps the default value
i also tried to change button enable status programmatically but stayed in the same , nothing get changed !!

I tried in the setText method both
String.valueof(int)
and
Integer.toString(int)

java

```<code> @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         play =(Button) findViewById(R.id.button4);
         Pause =(Button) findViewById(R.id.button5);
        hourstext =(TextView) findViewById(R.id.textView1);
        mintext =(TextView) findViewById(R.id.textView2);
        sectext =(TextView) findViewById(R.id.textView3);

    }

    void playb(View v)  {

        while (!ispause) {
            sec = 0 ;
            while (sec < 60) {
                SystemClock.sleep(1000);
                sec++;
               sectext.setText(Integer.toString(sec));
                Log.d("this", "sec value=" + sec);
            }
            sec = 0;
            min++;
            Log.d("this","min value ="+min);

           mintext.setText(String.valueOf(min));

        }

    }
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="114dp"
        android:layout_height="94dp"
        android:layout_marginTop="159dp"
        android:layout_marginEnd="16dp"
        android:layout_x="274dp"
        android:layout_y="120dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/pauseButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="72dp"
        android:layout_marginTop="116dp"
        android:layout_marginEnd="93dp"
        android:layout_x="217dp"
        android:layout_y="296dp"
        android:enabled="false"
        android:onClick="playb"
        android:text="Pause"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/playbutton"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

    <Button
        android:id="@+id/playbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="70dp"
        android:layout_marginTop="116dp"
        android:layout_x="63dp"
        android:layout_y="293dp"
        android:onClick="playb"
        android:text="playb"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="120dp"
        android:layout_height="97dp"
        android:layout_marginTop="156dp"
        android:layout_marginEnd="17dp"
        android:layout_x="139dp"
        android:layout_y="117dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="103dp"
        android:layout_height="94dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="159dp"
        android:layout_x="11dp"
        android:layout_y="117dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</code>```

i get no error message ! the app keeps working but no updated textView

i've included my XML Code

答:
If you want make counter up for 60 sec you can use this code</p>

```<code>long time=60;
        new CountDownTimer(time*1000, 1000)
         {
    public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds : " + (time-millisUntilFinished /1000));
     }
        public void onFinish() {
     mTextField.setText("done!");
    }
        }.start();
</code>```

Body:
the app runs the way I want I can see that in the Logcat
but the text view is not changing and keeps the default value
i also tried to change button enable status programmatically but stayed in the same , nothing get changed !!

I tried in the setText method both
String.valueof(int)
and
Integer.toString(int)

java

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         play =(Button) findViewById(R.id.button4);
         Pause =(Button) findViewById(R.id.button5);
        hourstext =(TextView) findViewById(R.id.textView1);
        mintext =(TextView) findViewById(R.id.textView2);
        sectext =(TextView) findViewById(R.id.textView3);

    }

    void playb(View v)  {

        while (!ispause) {
            sec = 0 ;
            while (sec < 60) {
                SystemClock.sleep(1000);
                sec++;
               sectext.setText(Integer.toString(sec));
                Log.d("this", "sec value=" + sec);
            }
            sec = 0;
            min++;
            Log.d("this","min value ="+min);

           mintext.setText(String.valueOf(min));

        }

    }

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="114dp"
        android:layout_height="94dp"
        android:layout_marginTop="159dp"
        android:layout_marginEnd="16dp"
        android:layout_x="274dp"
        android:layout_y="120dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/pauseButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="72dp"
        android:layout_marginTop="116dp"
        android:layout_marginEnd="93dp"
        android:layout_x="217dp"
        android:layout_y="296dp"
        android:enabled="false"
        android:onClick="playb"
        android:text="Pause"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/playbutton"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

    <Button
        android:id="@+id/playbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="70dp"
        android:layout_marginTop="116dp"
        android:layout_x="63dp"
        android:layout_y="293dp"
        android:onClick="playb"
        android:text="playb"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="120dp"
        android:layout_height="97dp"
        android:layout_marginTop="156dp"
        android:layout_marginEnd="17dp"
        android:layout_x="139dp"
        android:layout_y="117dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="103dp"
        android:layout_height="94dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="159dp"
        android:layout_x="11dp"
        android:layout_y="117dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

i get no error message ! the app keeps working but no updated textView

i've included my XML Code

Body:
If you want make counter up for 60 sec you can use this code

long time=60;
        new CountDownTimer(time*1000, 1000)
         {
    public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds : " + (time-millisUntilFinished /1000));
     }
        public void onFinish() {
     mTextField.setText("done!");
    }
        }.start();


问:
Printing last 3 lines of a .csv file
Need to get this section of python to print out individual lines found at the end of a .csv file in a human readable format. The information of a whole line needs to be printed on its own line.

I have tried using "deque" and it produces tons of useless characters brackets, and information not needed. It is difficult to read whenever I used the deque.
I have gotten it to print the very last line, but I can not get the 2 more from before it.

```<code>#This section is intented to test the code that would print the last 3 entries to the INV.csv.
#Code currently not working.
def EX1():
    #Tells the user what they are seeing.
    print("====-----EXPERIMENTAL SECTION-----====")
    print("This section tests the call back method for last 3 vehichles added to inventory.")
    print("")

    with open('INV.csv','r') as INQB: #Opens INV.csv as read only.
        lineA = INQB.readline()[-1] #Works just fine, as intended.
        lineB = INQB.readline()[-2] #Does not work.
        #lineC = INQB.readline()[-3] #Still doesn't work.

        print("Previously listed entries to the Inventory List are as follows:") #To tell user what they are reading.

        #Need these print commands to print 3rd 2nd and last entry line made to INV.csv.
        #These entries are msade by another defined area not shown here.
        #print(lineC)
        print(lineB)
        print(lineA)

        #This is to tell me that this area was reached when tested and didnt fail.
        print("Stuff was supposed to be there /\.")
        print("") #Spacing for readability.

        INQB.close() #Closes it (If its not closed it gets crashy)
        starter() #Exits to other portions of the program.
</code>```

I need this patch of the code to produce the last 3 lines of the .csv in a human readable format.

Third to last line in the .csv

Second to last line in the .csv

Very last line in the .csv

答:
Read all the lines, then print the last three:

```<code>with open('INV.csv') as INQB:
    lines = INQB.readlines()  # Reads all lines into a list.

for line in lines[-3:]:  # slices the list for the last three entries.
    print(line,end='') # end='' because the lines already have newlines in them.
</code>```

If the file is too huge to read all lines, you can seek back from the end an amount larger than 3 maximum length lines.  For example:

```<code># Create a file with 100 lines in it to use for demonstration.
with open('INV.csv','w') as f:
    for line in range(100):
        f.write(f'line {line}\n')

# Now open the file and read three lines efficiently.
with open('INV.csv','rb') as f: # open in binary for seek operations
    # Lines created above were 10 bytes long max, go back more than 3x that
    f.seek(-50,2) # 2 means end-of-file
    lines = f.readlines()  # read only the last few lines of the file

for line in lines[-3:]:  # slice only the last three lines and display.
    print(line.decode(),end='') # decode the line to text since file was opened in binary.
</code>```

Output:

```<code>line 97
line 98
line 99
</code>```

Title: Printing last 3 lines of a .csv file

Body:
Need to get this section of python to print out individual lines found at the end of a .csv file in a human readable format. The information of a whole line needs to be printed on its own line.

I have tried using "deque" and it produces tons of useless characters brackets, and information not needed. It is difficult to read whenever I used the deque.
I have gotten it to print the very last line, but I can not get the 2 more from before it.

#This section is intented to test the code that would print the last 3 entries to the INV.csv.
#Code currently not working.
def EX1():
    #Tells the user what they are seeing.
    print("====-----EXPERIMENTAL SECTION-----====")
    print("This section tests the call back method for last 3 vehichles added to inventory.")
    print("")

    with open('INV.csv','r') as INQB: #Opens INV.csv as read only.
        lineA = INQB.readline()[-1] #Works just fine, as intended.
        lineB = INQB.readline()[-2] #Does not work.
        #lineC = INQB.readline()[-3] #Still doesn't work.

        print("Previously listed entries to the Inventory List are as follows:") #To tell user what they are reading.

        #Need these print commands to print 3rd 2nd and last entry line made to INV.csv.
        #These entries are msade by another defined area not shown here.
        #print(lineC)
        print(lineB)
        print(lineA)

        #This is to tell me that this area was reached when tested and didnt fail.
        print("Stuff was supposed to be there /\.")
        print("") #Spacing for readability.

        INQB.close() #Closes it (If its not closed it gets crashy)
        starter() #Exits to other portions of the program.

I need this patch of the code to produce the last 3 lines of the .csv in a human readable format.

Third to last line in the .csv

Second to last line in the .csv

Very last line in the .csv

Body:
Read all the lines, then print the last three:

with open('INV.csv') as INQB:
    lines = INQB.readlines()  # Reads all lines into a list.

for line in lines[-3:]:  # slices the list for the last three entries.
    print(line,end='') # end='' because the lines already have newlines in them.

If the file is too huge to read all lines, you can seek back from the end an amount larger than 3 maximum length lines.  For example:

# Create a file with 100 lines in it to use for demonstration.
with open('INV.csv','w') as f:
    for line in range(100):
        f.write(f'line {line}\n')

# Now open the file and read three lines efficiently.
with open('INV.csv','rb') as f: # open in binary for seek operations
    # Lines created above were 10 bytes long max, go back more than 3x that
    f.seek(-50,2) # 2 means end-of-file
    lines = f.readlines()  # read only the last few lines of the file

for line in lines[-3:]:  # slice only the last three lines and display.
    print(line.decode(),end='') # decode the line to text since file was opened in binary.

Output:

line 97
line 98
line 99


问:
PowerShell How to use -and in Where-Object
I want to filter a command result using two conditions. Here are my commands

```<code> $list=Get-PnpDevice | Sort-Object -Property Name | Where-Object -Property ConfigurationFlags -NotLike '*DISABLED*' | ft Name, InstanceId -AutoSize
</code>```

and the next filter is

```<code> $list=Get-PnpDevice | Sort-Object -Property Name | Where-Object -Property FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize
</code>```

both of them works separately but I want to join them using and command. I tried to use -AND as following command but it keeps raising errors

```<code>
 Get-PnpDevice | Sort-Object -Property Name | Where-Object{
      ( ConfigurationFlags -NotLike '*DISABLED*') -and
      ( FriendlyName -like '*touch screen*' ) }| ft Name, InstanceId -AutoSize

</code>```

答:
You can pipe 'Where' clauses together... it's simpler syntax and easier to read</p>

```<code>Get-PnpDevice | Sort-Object -Property Name | Where ConfigurationFlags -NotLike '*DISABLED*' | Where FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize
</code>```

Body:
I want to filter a command result using two conditions. Here are my commands

 $list=Get-PnpDevice | Sort-Object -Property Name | Where-Object -Property ConfigurationFlags -NotLike '*DISABLED*' | ft Name, InstanceId -AutoSize

and the next filter is

 $list=Get-PnpDevice | Sort-Object -Property Name | Where-Object -Property FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize

both of them works separately but I want to join them using and command. I tried to use -AND as following command but it keeps raising errors

 Get-PnpDevice | Sort-Object -Property Name | Where-Object{
      ( ConfigurationFlags -NotLike '*DISABLED*') -and
      ( FriendlyName -like '*touch screen*' ) }| ft Name, InstanceId -AutoSize

Body:
You can pipe 'Where' clauses together... it's simpler syntax and easier to read

Get-PnpDevice | Sort-Object -Property Name | Where ConfigurationFlags -NotLike '*DISABLED*' | Where FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize


问:
Finding ordered array in an ordered array
```<code>c = [-1, 0, 1, 2, 3, 4]
d = [-1,0,2,3,4,5,6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
</code>```

desired output:

```<code>fc = [-1,0,1,2,3],[0,1,2,3,4]
fd = [2,3,4,5,6]
fa = []
</code>```

I want to find how many times the ordered set is in the larger set given an interval. In my case, I choose 5 since this is for my poker game. Set's won't work since they need to be in order so I don't know what to use.

In my program, I tried using for loops but I'm not getting it.

```<code>ns = len(c)-5
nt = range(0,ns)
if ns >= 0:
    for n in nt:
        templist = c[n:n+5]
</code>```

I just need a function to compare both lists.

答:
Compare the small lists to slices of main.

```<code>c = [-1, 0, 1, 2, 3, 4]
d = [-1,0,2,3,4,5,6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

for sublist in [c, d, a]:
    l = len(sublist)
    i = 0
    while i + l <= len(main):
        if sublist == main[i:i+l]:
            print 'sublist %s matches' % sublist
        i = i + 1
</code>```

Body:
c = [-1, 0, 1, 2, 3, 4]
d = [-1,0,2,3,4,5,6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

desired output:

fc = [-1,0,1,2,3],[0,1,2,3,4]
fd = [2,3,4,5,6]
fa = []

I want to find how many times the ordered set is in the larger set given an interval. In my case, I choose 5 since this is for my poker game. Set's won't work since they need to be in order so I don't know what to use.

In my program, I tried using for loops but I'm not getting it.

ns = len(c)-5
nt = range(0,ns)
if ns >= 0:
    for n in nt:
        templist = c[n:n+5]

I just need a function to compare both lists.

Body:
Compare the small lists to slices of main.

c = [-1, 0, 1, 2, 3, 4]
d = [-1,0,2,3,4,5,6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

for sublist in [c, d, a]:
    l = len(sublist)
    i = 0
    while i + l <= len(main):
        if sublist == main[i:i+l]:
            print 'sublist %s matches' % sublist
        i = i + 1


问:
IndProp: ev_plus_plus
```<code>(** **** Exercise: 3 stars, standard, optional (ev_plus_plus)

    This exercise just requires applying existing lemmas.  No
    induction or even case analysis is needed, though some of the
    rewriting may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  even (n+m) -> even (n+p) -> even (m+p).
Proof.
  intros n m p H1 H2.
</code>```

Here is what I got:

```<code>1 subgoal (ID 89)

n, m, p : nat
H1 : even (n + m)
H2 : even (n + p)
============================
even (m + p)
</code>```

I have proven the previous theorem:

```<code>Theorem ev_ev__ev : forall n m,
  even (n+m) -> even n -> even m.
</code>```

And wanted to apply it to H1, but

```<code>apply ev_ev__ev in H1.
</code>```

gives an error:

```<code>Error: Unable to find an instance for the variable m.
</code>```

Why can't it find "m" in the expression even (n + m)? How to fix?

Update

```<code>apply ev_ev__ev with (m:=m) in H1.
</code>```

gives a very strange result:

```<code>2 subgoals (ID 90)

n, m, p : nat
H1 : even m
H2 : even (n + p)
============================
even (m + p)

subgoal 2 (ID 92) is:
 even (n + m + m)
</code>```

I thought that it will transform H1 to 2 hypothesis:

```<code>H11 : even n
H12 : even m
</code>```

But instead it gave 2 subgoals, the second that we need to prove is more complicated than the initial one:

```<code>even (n + m + m)
</code>```

What's happening here?

答:
Because Coq can't figure out what value it should give for m. You can apply the tactic  eapply ev_ev__ev in H1. and see the goals

```<code>  n, m, p : nat
  H2 : even (n + p)
  H1 : even ?m
  ============================
  even (m + p)

subgoal 2 (ID 17) is:
 even (n + m + ?m)
</code>```

Coq has instantiated the m with a meta variable ?m, and you need to give a witness for this meta variable in the end to finish the proof.

Second approach is just apply the tactic with instantiating the value of m apply ev_ev__ev with (m := m) in H1.

You can see more on apply with tactics in software-foundations https://softwarefoundations.cis.upenn.edu/lf-current/Tactics.html

Title: IndProp: ev_plus_plus

Body:
(** **** Exercise: 3 stars, standard, optional (ev_plus_plus)

    This exercise just requires applying existing lemmas.  No
    induction or even case analysis is needed, though some of the
    rewriting may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  even (n+m) -> even (n+p) -> even (m+p).
Proof.
  intros n m p H1 H2.

Here is what I got:

1 subgoal (ID 89)

n, m, p : nat
H1 : even (n + m)
H2 : even (n + p)
============================
even (m + p)

I have proven the previous theorem:

Theorem ev_ev__ev : forall n m,
  even (n+m) -> even n -> even m.

And wanted to apply it to H1, but

apply ev_ev__ev in H1.

gives an error:

Error: Unable to find an instance for the variable m.

Why can't it find "m" in the expression even (n + m)? How to fix?

Update

apply ev_ev__ev with (m:=m) in H1.

gives a very strange result:

2 subgoals (ID 90)

n, m, p : nat
H1 : even m
H2 : even (n + p)
============================
even (m + p)

subgoal 2 (ID 92) is:
 even (n + m + m)

I thought that it will transform H1 to 2 hypothesis:

H11 : even n
H12 : even m

But instead it gave 2 subgoals, the second that we need to prove is more complicated than the initial one:

even (n + m + m)

What's happening here?

Body:
Because Coq can't figure out what value it should give for m. You can apply the tactic  eapply ev_ev__ev in H1. and see the goals

  n, m, p : nat
  H2 : even (n + p)
  H1 : even ?m
  ============================
  even (m + p)

subgoal 2 (ID 17) is:
 even (n + m + ?m)

Coq has instantiated the m with a meta variable ?m, and you need to give a witness for this meta variable in the end to finish the proof.

Second approach is just apply the tactic with instantiating the value of m apply ev_ev__ev with (m := m) in H1.

You can see more on apply with tactics in software-foundations https://softwarefoundations.cis.upenn.edu/lf-current/Tactics.html


问:
Unable to inject IRepository<TEntity> due to "no implicit reference conversion"
Started off and trying to get familiar with the ASP.NET Boilerplate template for .NET Core.

Everything was going smoothly until I needed to inject an IRepository with a generic Entity into a class constructor.

In the DepartmentManager class, when I tried to create a private read-only field to inject into the constructor, I get the IntelliSense error that:

There is no implicit reference conversion from Department to
  Abp.Domain.Entities.IEntity The Type Department cannot be used
  as type parameter TEntity in the generic type or method
  'IRepository, primary key'

I have tried to research to see if I could find similar problems online with some solutions, but to no avail.

Below is a simple code to illustrate the challenge.

```<code>// Class
public class Department
{
    public long Id { get; set; }

    public string DepartmentName { get; set; }
}

// IDepartment Manager
public interface IDepartmentManager
{
    Task<Department> CreateDepartment(Department entity);
    Task Update(Department entity);
    Task Delete(long id);
    Task<IEnumerable<Department>> GetAll();
}

// Department Manager
private readonly IRepository<Department, long> _departmentRepo;
public DepartmentManager(IRepository<Department, long> departmentRepo)
{
    _departmentRepo = departmentRepo
}
</code>```

Any help is well appreciated on what I am not doing right.

答:
Make Department implement Entity<long> or IEntity<long> to use its repository.

public class Department : Entity<long>
{
    public string DepartmentName { get; set; }
}
```

References

Entities: https://aspnetboilerplate.com/Pages/Documents/Entities

Repositories: https://aspnetboilerplate.com/Pages/Documents/Repositories

Body:
Started off and trying to get familiar with the ASP.NET Boilerplate template for .NET Core.

Everything was going smoothly until I needed to inject an IRepository with a generic Entity into a class constructor.

In the DepartmentManager class, when I tried to create a private read-only field to inject into the constructor, I get the IntelliSense error that:

There is no implicit reference conversion from Department to
  Abp.Domain.Entities.IEntity The Type Department cannot be used
  as type parameter TEntity in the generic type or method
  'IRepository, primary key'

I have tried to research to see if I could find similar problems online with some solutions, but to no avail.

Below is a simple code to illustrate the challenge.

// Class
public class Department
{
    public long Id { get; set; }

    public string DepartmentName { get; set; }
}

// IDepartment Manager
public interface IDepartmentManager
{
    Task<Department> CreateDepartment(Department entity);
    Task Update(Department entity);
    Task Delete(long id);
    Task<IEnumerable<Department>> GetAll();
}

// Department Manager
private readonly IRepository<Department, long> _departmentRepo;
public DepartmentManager(IRepository<Department, long> departmentRepo)
{
    _departmentRepo = departmentRepo
}

Any help is well appreciated on what I am not doing right.

Body:
Make Department implement Entity<long> or IEntity<long> to use its repository.

public class Department : Entity<long>
{
    public string DepartmentName { get; set; }
}

References

Entities: https://aspnetboilerplate.com/Pages/Documents/Entities

Repositories: https://aspnetboilerplate.com/Pages/Documents/Repositories


问:
Applying models to data - Inheriting or accessing the attributes of a root class (data) from a sub-class (model)
I am fitting a number of models to several different datasets.  I would like to store the methods and attributes of the datasets (e.g. X, y, trainTestSplit(), etc.) in 'Dataset' objects, and store the the methods and attributes of the models (e.g. fit(), hyperparameters, scores, etc.) in 'Model' objects, and store the 'Models' in the 'Datasets' (several Models for each Dataset).

I have tried several different ways to make this work, including inheritance with the use of super(); indenting (nesting) the Model class inside the dataset class; and with functions in the Dataset class which can be called by the Model class.

This is about as close as I've come:

```<code>class Dataset :
    def __init__(self, X, y, attr) :
       self.X = X
       self.y = y
       self.attr = attr

    def trainTestSplit(self, **kwargs):
       self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.X, self.y, **kwargs)

class Model(Dataset) :
    def __init__(self, regressor):
        self.reg = regressor
        super().__init__(self)

    def fit(self):
        self.reg.fit(X=self.X_train, y=self.y_train)

    def predict(self):
        self.yPredict = self.reg.predict(X=self.X_test)
</code>```

In the above, the variables are not accessible to the Model class, and so it returns and error.

If this worked, I would expect to be executing the following function calls, as examples.

Creating an instance of a Dataset object:

```<code>dataset_1 = Dataset(X, y, 'string')
</code>```

Splitting data into training and test sets:

```<code>dataset_1.trainTestSplit(test_size=0.3))
</code>```

Creating an instance of a Model, and applying it to a dataset:

```<code>dataset_1.svr = Model(SVR(hyperParams))
</code>```

Fitting a model:

```<code>dataset_1.svr.fit()
</code>```

Actually, if I'm thinking about this in the right way, the fit() method of the Model class could be applied as part of the init, so that it is fit to the dataset on instantiation.

Reading a training score:

```<code>dataset_1.svr.training_score_
</code>```

Because I have so many datasets, and will be fitting numerous models to each, having the methods and attributes stored in this way seemed to make sense, but I'm not sure how to implement it.

Is there any way to instantiate a class (call it a sub-class), such that it inherits or has access to the attributes or objects contained in another class (say a root class), and so the sub-class is contained as an object within the root class?  Or am I thinking about this in the wrong way?

答:
So I might have been trying to use classes where a dictionary would be better suited.

The following seems to accomplish what I'm trying to do, which is to store a dataset and the results of models applied to it in the one object (other attributes such as training/CV/test scores etc. are still to be added in the answer below).

If anyone has any suggestions/comments on how this can be done better please comment.

Thanks.

```<code>from sklearn.model_selection import train_test_split

class Dataset(object):

def __init__(self, X, y):
    self.X = X
    self.y = y
    self.models = {}

def add_model(self, model, regressor):
    self.models[model] = {}
    self.models[model]['reg'] = regressor
    regressor.fit(self.X_train, self.y_train)
    yPredict = regressor.predict(self.X_test)
    self.models[model]['yPredict'] = yPredict

def trainTestSplit(self, **kwargs):
   self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.X, self.y, **kwargs)
</code>```

Body:
I am fitting a number of models to several different datasets.  I would like to store the methods and attributes of the datasets (e.g. X, y, trainTestSplit(), etc.) in 'Dataset' objects, and store the the methods and attributes of the models (e.g. fit(), hyperparameters, scores, etc.) in 'Model' objects, and store the 'Models' in the 'Datasets' (several Models for each Dataset).

I have tried several different ways to make this work, including inheritance with the use of super(); indenting (nesting) the Model class inside the dataset class; and with functions in the Dataset class which can be called by the Model class.

This is about as close as I've come:

class Dataset :
    def __init__(self, X, y, attr) :
       self.X = X
       self.y = y
       self.attr = attr

    def trainTestSplit(self, **kwargs):
       self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.X, self.y, **kwargs)

class Model(Dataset) :
    def __init__(self, regressor):
        self.reg = regressor
        super().__init__(self)

    def fit(self):
        self.reg.fit(X=self.X_train, y=self.y_train)

    def predict(self):
        self.yPredict = self.reg.predict(X=self.X_test)

In the above, the variables are not accessible to the Model class, and so it returns and error.

If this worked, I would expect to be executing the following function calls, as examples.

Creating an instance of a Dataset object:

dataset_1 = Dataset(X, y, 'string')

Splitting data into training and test sets:

dataset_1.trainTestSplit(test_size=0.3))

Creating an instance of a Model, and applying it to a dataset:

dataset_1.svr = Model(SVR(hyperParams))

Fitting a model:

dataset_1.svr.fit()

Actually, if I'm thinking about this in the right way, the fit() method of the Model class could be applied as part of the init, so that it is fit to the dataset on instantiation.

Reading a training score:

dataset_1.svr.training_score_

Because I have so many datasets, and will be fitting numerous models to each, having the methods and attributes stored in this way seemed to make sense, but I'm not sure how to implement it.

Is there any way to instantiate a class (call it a sub-class), such that it inherits or has access to the attributes or objects contained in another class (say a root class), and so the sub-class is contained as an object within the root class?  Or am I thinking about this in the wrong way?

Body:
So I might have been trying to use classes where a dictionary would be better suited.

The following seems to accomplish what I'm trying to do, which is to store a dataset and the results of models applied to it in the one object (other attributes such as training/CV/test scores etc. are still to be added in the answer below).

If anyone has any suggestions/comments on how this can be done better please comment.

Thanks.

from sklearn.model_selection import train_test_split

class Dataset(object):

def __init__(self, X, y):
    self.X = X
    self.y = y
    self.models = {}

def add_model(self, model, regressor):
    self.models[model] = {}
    self.models[model]['reg'] = regressor
    regressor.fit(self.X_train, self.y_train)
    yPredict = regressor.predict(self.X_test)
    self.models[model]['yPredict'] = yPredict

def trainTestSplit(self, **kwargs):
   self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.X, self.y, **kwargs)


问:
Having trouble understanding cmpsb in the following example
I am following a tutorial on operating systems and I came across the following block code which is checking filenames on a disk against my variable "ImageName".

My confusion arises from the push di line before rep cmpsb.

```<code>    mov       cx, WORD [bpbRootEntries]
    mov       di, 0x0200
.LOOP:
    push      cx
    mov       cx, 0x000B
    mov       si, ImageName
    push      di
    rep  cmpsb
    pop       di
    je        LOAD_FAT
    pop       cx
    add       di, 0x0020
    loop      .LOOP
    jmp       FAILURE
</code>```

The documentation I have found for cmpsb states "For legacy mode, compare byte at address DS:(E)SI with byte at address ES:(E)DI. The status flags are set accordingly." Wouldn't pushing di before this call mean that I am always comparing against an empty value? The code works so I am obviously misunderstanding something, but every piece of documentation I can find implies that this code shouldn't work.

答: The rep cmpsb instruction will leave di pointing after the location where the two strings differ.  Since this code does not care about that position (just if the two strings match), we throw out where the difference lies and just check the Z flag to see if we matched.  If we don't match, we advance di far enough to get to the next file name, which is a constant since we reset di back to where we started.

Body:
I am following a tutorial on operating systems and I came across the following block code which is checking filenames on a disk against my variable "ImageName".

My confusion arises from the push di line before rep cmpsb.

    mov       cx, WORD [bpbRootEntries]
    mov       di, 0x0200
.LOOP:
    push      cx
    mov       cx, 0x000B
    mov       si, ImageName
    push      di
    rep  cmpsb
    pop       di
    je        LOAD_FAT
    pop       cx
    add       di, 0x0020
    loop      .LOOP
    jmp       FAILURE

The documentation I have found for cmpsb states "For legacy mode, compare byte at address DS:(E)SI with byte at address ES:(E)DI. The status flags are set accordingly." Wouldn't pushing di before this call mean that I am always comparing against an empty value? The code works so I am obviously misunderstanding something, but every piece of documentation I can find implies that this code shouldn't work.


问:
Why is my variable not holding its value in bash?
I am horribly perplexed.

I've written a bash script to sort lines into categories based on substrings within that line.

Here's my example "lines.txt"

```<code>i am line1
i am line2
</code>```

If a line contains "line1", then it should be sorted into group "l1". If it contains "line2", then it should be sorted into group "l2"

The problem is that the variable which holds the category isn't retaining its value, and I have no clue why. Here's the script.

```<code>#!/bin/bash
categories="l1 l2"

l1="
    line1
"

l2="
    line2
"

# match line1
cat lines.txt | while read fline
do
    cate="no match"

    for c in $categories
    do
        echo "${!c}" | while read location
        do
            if [ ! -z "$location" ] && [[ "$fline" =~ "$location" ]]
            then
                echo "we are selecting category $c"
                cate="$c"
                break
            fi
        done

        if [ "$cate" != "no match" ]
        then
            echo "we found a match"
            break
        fi
    done

    echo "$cate:$fline"
done

exit 0
</code>```

And when I run it, I see the output

```<code>we are selecting category l1
no match:i am line1
we are selecting category l2
no match:i am line2
</code>```

This means that we are selecting the correct group, but we don't remember it when we exit the nested "while" loop.

Why is my variable not retaining its value, and how could I fix that?

答:
The while loop is executed in a subshell because of the pipe. That means that the name 'cate' really refers to two different variables. One outside the while loop and the other inside the loop inside the subshell. When the subshell exits that value is lost.

A way to get around this is to use a redirect like this

```<code>while read line; do
...
done < $myfile
</code>```

If the expression is more complicated and you need something executed in a subshell, then you can use process substitution (Thanks to David Rankin for reminding me about this one).

```<code>while read -r line; do
...
done < <(find . -iname "*sh")
</code>```

Body:
I am horribly perplexed.

I've written a bash script to sort lines into categories based on substrings within that line.

Here's my example "lines.txt"

i am line1
i am line2

If a line contains "line1", then it should be sorted into group "l1". If it contains "line2", then it should be sorted into group "l2"

The problem is that the variable which holds the category isn't retaining its value, and I have no clue why. Here's the script.

#!/bin/bash
categories="l1 l2"

l1="
    line1
"

l2="
    line2
"

# match line1
cat lines.txt | while read fline
do
    cate="no match"

    for c in $categories
    do
        echo "${!c}" | while read location
        do
            if [ ! -z "$location" ] && [[ "$fline" =~ "$location" ]]
            then
                echo "we are selecting category $c"
                cate="$c"
                break
            fi
        done

        if [ "$cate" != "no match" ]
        then
            echo "we found a match"
            break
        fi
    done

    echo "$cate:$fline"
done

exit 0

And when I run it, I see the output

we are selecting category l1
no match:i am line1
we are selecting category l2
no match:i am line2

This means that we are selecting the correct group, but we don't remember it when we exit the nested "while" loop.

Why is my variable not retaining its value, and how could I fix that?

Body:
The while loop is executed in a subshell because of the pipe. That means that the name 'cate' really refers to two different variables. One outside the while loop and the other inside the loop inside the subshell. When the subshell exits that value is lost.

A way to get around this is to use a redirect like this

while read line; do
...
done < $myfile

If the expression is more complicated and you need something executed in a subshell, then you can use process substitution (Thanks to David Rankin for reminding me about this one).

while read -r line; do
...
done < <(find . -iname "*sh")


问:
How to update state in child component using React Router params?
I'm trying to update my state based on a Link. It is dependent on the param.ID that is passed down through the Route.

Problem is I'm not sure how to get that info to the parent component.

The state has an array of objects. Clicking the Link changes one of the object's properties. But I need to know which link was clicked in order to know how to update the state. Ideally I'd have this function in the parent component:

```<code>updateState() {
    this.setState({
        data: ????
})
</code>```

But I'm not sure what to set the data as without knowing the param beforehand. If I pass an event handler to the onClick function in the Link I just get the html.

I've tried changing the child component into a class component and updating the state from there but that doesn't work. Even in componentDidMount. I get a massive error saying I'm updating the state too many times and it will result in an infinite loop.

答:
Compare the previous previous props in component did update to the current props.

```<code>componentDidUpdate(prevProps) {
     if(prevProps.value !== this.props.value){
         this.setState({value: this.props.value)}
}
</code>```

Untested... but this is the gist of it.

Body:
I'm trying to update my state based on a Link. It is dependent on the param.ID that is passed down through the Route.

Problem is I'm not sure how to get that info to the parent component.

The state has an array of objects. Clicking the Link changes one of the object's properties. But I need to know which link was clicked in order to know how to update the state. Ideally I'd have this function in the parent component:

updateState() {
    this.setState({
        data: ????
})

But I'm not sure what to set the data as without knowing the param beforehand. If I pass an event handler to the onClick function in the Link I just get the html.

I've tried changing the child component into a class component and updating the state from there but that doesn't work. Even in componentDidMount. I get a massive error saying I'm updating the state too many times and it will result in an infinite loop.

Body:
Compare the previous previous props in component did update to the current props.

componentDidUpdate(prevProps) {
     if(prevProps.value !== this.props.value){
         this.setState({value: this.props.value)}
}

Untested... but this is the gist of it.


问:
Part of PropTypes Shape
I have something that looks like this:

```<code>export const LocalesModel = PropTypes.shape({
  defaultLocale: PropTypes.string.isRequired,
  supportedLanguages: PropTypes.arrayOf(PropTypes.string).isRequired,
  messages: MessageModel,
});
</code>```

In a component I am getting that model like this:

```<code>import { LocalesModel } from '...';

const Component = () => ...

Component.propTypes = {
   supportedLanguages: ???
}
</code>```

I want to be able to do something like:

```<code>Component.propTypes = {
   supportedLanguages: LocalesModel.supportedLanguages
}
</code>```

but I know this doesn't work. Is there any way to get a property of a PropTypes shape - or do I just have to extract supportedLanguages out of LocalesModel?

答:
You can export the shape without PropTypes.shape:

```<code>export const LocalesModel = {
  defaultLocale: PropTypes.string.isRequired,
  supportedLanguages: PropTypes.arrayOf(PropTypes.string).isRequired,
  messages: MessageModel,
};
</code>```

And then add PropTypes.shape where you use it:

```<code>Component.propTypes = {
 supportedLanguages: PropTypes.shape(LocalesModel.supportedLanguages)
}
</code>```

Title: Part of PropTypes Shape

Body:
I have something that looks like this:

export const LocalesModel = PropTypes.shape({
  defaultLocale: PropTypes.string.isRequired,
  supportedLanguages: PropTypes.arrayOf(PropTypes.string).isRequired,
  messages: MessageModel,
});

In a component I am getting that model like this:

import { LocalesModel } from '...';

const Component = () => ...

Component.propTypes = {
   supportedLanguages: ???
}

I want to be able to do something like:

Component.propTypes = {
   supportedLanguages: LocalesModel.supportedLanguages
}

but I know this doesn't work. Is there any way to get a property of a PropTypes shape - or do I just have to extract supportedLanguages out of LocalesModel?

Body:
You can export the shape without PropTypes.shape:

export const LocalesModel = {
  defaultLocale: PropTypes.string.isRequired,
  supportedLanguages: PropTypes.arrayOf(PropTypes.string).isRequired,
  messages: MessageModel,
};

And then add PropTypes.shape where you use it:

Component.propTypes = {
 supportedLanguages: PropTypes.shape(LocalesModel.supportedLanguages)
}


问:
How to prevent TPUEstimator from using GPU or TPU
I need to force TPUEstimator to use the CPU. I have a rented google machine and the GPU is already running training. Since the CPUs are idle, I want to start a second Tensorflow session for evaluation but I want to force the evaluation cycle to use CPUs only so that it does not steal GPU time.

I am assuming there is a flag in the run_config or similar for doing this but am struggling to find one in the TF documentation.

```<code>run_config = tf.contrib.tpu.RunConfig(
    cluster=tpu_cluster_resolver,
    master=FLAGS.master,
    model_dir=FLAGS.output_dir,
    save_checkpoints_steps=FLAGS.save_checkpoints_steps,
    tpu_config=tf.contrib.tpu.TPUConfig(
        iterations_per_loop=FLAGS.iterations_per_loop,
        num_shards=FLAGS.num_tpu_cores,
        per_host_input_for_training=is_per_host))
</code>```

答:
You can run a TPUEstimator locally by including two arguments: (1) use_tpu should be set to False, and (2) tf.contrib.tpu.RunConfig should be passed as the config argument.

my_tpu_estimator = tf.contrib.tpu.TPUEstimator(
    model_fn=my_model_fn,
    config=tf.contrib.tpu.RunConfig()
    use_tpu=False)
```

<p>The majority of example TPU models can be run in local mode by setting the command line flags:</p>

```$> python mnist_tpu.py --use_tpu=false --master=''
```

More documentation can be found here.

Body:
I need to force TPUEstimator to use the CPU. I have a rented google machine and the GPU is already running training. Since the CPUs are idle, I want to start a second Tensorflow session for evaluation but I want to force the evaluation cycle to use CPUs only so that it does not steal GPU time.

I am assuming there is a flag in the run_config or similar for doing this but am struggling to find one in the TF documentation.

run_config = tf.contrib.tpu.RunConfig(
    cluster=tpu_cluster_resolver,
    master=FLAGS.master,
    model_dir=FLAGS.output_dir,
    save_checkpoints_steps=FLAGS.save_checkpoints_steps,
    tpu_config=tf.contrib.tpu.TPUConfig(
        iterations_per_loop=FLAGS.iterations_per_loop,
        num_shards=FLAGS.num_tpu_cores,
        per_host_input_for_training=is_per_host))

Body:
You can run a TPUEstimator locally by including two arguments: (1) use_tpu should be set to False, and (2) tf.contrib.tpu.RunConfig should be passed as the config argument.

my_tpu_estimator = tf.contrib.tpu.TPUEstimator(
    model_fn=my_model_fn,
    config=tf.contrib.tpu.RunConfig()
    use_tpu=False)

The majority of example TPU models can be run in local mode by setting the command line flags:

$> python mnist_tpu.py --use_tpu=false --master=''

More documentation can be found here.


问:
Calculating the BCC for the 3964r serial communications protocol
I am trying to write some code to communicate with an old device over serial that uses the Siemens 3964r protocol. This includes a checksum, or more accurately a BCC (block check character) at the end of the transmission. A single char after the ETX. The docs define the BCC as this:

With the 3964R transfer protocol, data security is enhanced by sending an additional block
check character (BCC = Block Check Character).
The block check character is the even longitudinal parity (EXOR logic operation of all data
bytes) of a sent or received block. Its calculation begins with the first byte of user data (first
byte of the frame) after the connection establishment, and ends after the DLE ETX character
at connection termination.

Here is some sample data in hex.
53 54 41 54 55 53 10 03 07

07 is the BCC in this one.

4d 45 41 53 4d 50 54 45 53 54 41 4e 41 50 52 47 30 30 30 55 78 30 31 31 2e 30 30 5a 30 31 31 31 30 10 03 61

61 is the BCC in this one.

I know in general how to do XOR operations, but I haven't been able to figure out any combination of things that gives me a proper BCC. I think I am interpreting the definition wrong.

My preferred language for this is javascript as it's for a node.js electron app. I can read the buffer and get the hex values. And I can construct propoer messages back. But it won't work correctly until I can include a proper BCC. So just looking for someone smarter than me that knows exactly how to produce a valid BCC.

thanks!

答:
The document that was posted as the first comment had the right structure to calculate the 3964r BCC. That document is here:

https://support.industry.siemens.com/cs/attachments/1117397/s7300_cp341_manual_en_en-US.pdf?download=true

Here is a simple javascript function. The hexarray would be passed in, not hardcoded like here, but this accurately calculates the BCC for this particular protocol. If anyone cares or needs it. I just wrote out the bcc as a hex string to the console in this, but you can make it a function and actually return something useable.

```<code>var hexarr = ['4d', 45, 41, 53, '4d', 50, 30, 30, 10, 03];
var bcc = 0;
var xor = 0;

for(var i= 0; i< hexarr.length; i++){
    var hexint = parseInt(hexarr[i],16);
    if(i==0){ xor = hexint; }
    else {
        bcc = xor ^ hexint;
        xor = bcc;
    }
}

console.log(bcc.toString(16));
</code>```

Body:
The document that was posted as the first comment had the right structure to calculate the 3964r BCC. That document is here:

https://support.industry.siemens.com/cs/attachments/1117397/s7300_cp341_manual_en_en-US.pdf?download=true

Here is a simple javascript function. The hexarray would be passed in, not hardcoded like here, but this accurately calculates the BCC for this particular protocol. If anyone cares or needs it. I just wrote out the bcc as a hex string to the console in this, but you can make it a function and actually return something useable.

var hexarr = ['4d', 45, 41, 53, '4d', 50, 30, 30, 10, 03];
var bcc = 0;
var xor = 0;

for(var i= 0; i< hexarr.length; i++){
    var hexint = parseInt(hexarr[i],16);
    if(i==0){ xor = hexint; }
    else {
        bcc = xor ^ hexint;
        xor = bcc;
    }
}

console.log(bcc.toString(16));


问:
How to disable radio input with certain values when choosing radio input with the same value
how can disable radio button with name "least1" if i checked radio with name "most1" with same value </p>

```<code> <form action="{{route('questionnaire.action')}}" name="QuestionnaireForm" method="post" id="questionnaireEnglishForm">
    <input type="radio" name="most1" value="Trusting & believing in others">

    <input type="radio" name="least1" value="Trusting & believing in others">

    <input type="radio" name="most1" value="Satisfied, easy to please">

    <input type="radio" name="least1" value="Satisfied, easy to please">

    <input type="radio" name="most1" value="Clear">

    <input type="radio" name="least1" value="Clear">

    <input type="radio" name="most1" value="Calm & Peaceful">

    <input type="radio" name="least1" value="Calm & Peaceful">

    </form>
</code>```

答:
In Jquery

[1] You can use change event for most1

[2] Use.filter() to filter least1 by value

[3] Use .prop('disabled' , true/false) to on/off the disabled property

[4] You may need .prop('checked' , false) to uncheck the least1 if it was checked

$('input[name="most1"]').on('change' , function(){
  var GetValue = $(this).val();
  $('[name="least1"]').prop('disabled' , false).filter(function(){
    return $(this).val() == GetValue;
  }).prop('disabled' , true).prop('checked' , false);
});

var i = 12;
console.log('[name="least' + i + '"]');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="{{route('questionnaire.action')}}" name="QuestionnaireForm" method="post" id="questionnaireEnglishForm">
  <input type="radio" name="most1" value="Trusting & believing in others">

  <input type="radio" name="least1" value="Trusting & believing in others">

  <input type="radio" name="most1" value="Satisfied, easy to please">

  <input type="radio" name="least1" value="Satisfied, easy to please">

  <input type="radio" name="most1" value="Clear">

  <input type="radio" name="least1" value="Clear">

  <input type="radio" name="most1" value="Calm & Peaceful">

  <input type="radio" name="least1" value="Calm & Peaceful">

</form></code>```

To concatenate the string in javascript  $('[name="least' +  i + '"]') .. You can see the snippet above

Body:
how can disable radio button with name "least1" if i checked radio with name "most1" with same value

 <form action="{{route('questionnaire.action')}}" name="QuestionnaireForm" method="post" id="questionnaireEnglishForm">
    <input type="radio" name="most1" value="Trusting & believing in others">

    <input type="radio" name="least1" value="Trusting & believing in others">

    <input type="radio" name="most1" value="Satisfied, easy to please">

    <input type="radio" name="least1" value="Satisfied, easy to please">

    <input type="radio" name="most1" value="Clear">

    <input type="radio" name="least1" value="Clear">

    <input type="radio" name="most1" value="Calm & Peaceful">

    <input type="radio" name="least1" value="Calm & Peaceful">

    </form>

Body:
In Jquery

[1] You can use change event for most1

[2] Use.filter() to filter least1 by value

[3] Use .prop('disabled' , true/false) to on/off the disabled property

[4] You may need .prop('checked' , false) to uncheck the least1 if it was checked

$('input[name="most1"]').on('change' , function(){
  var GetValue = $(this).val();
  $('[name="least1"]').prop('disabled' , false).filter(function(){
    return $(this).val() == GetValue;
  }).prop('disabled' , true).prop('checked' , false);
});

var i = 12;
console.log('[name="least' + i + '"]');

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="{{route('questionnaire.action')}}" name="QuestionnaireForm" method="post" id="questionnaireEnglishForm">
  <input type="radio" name="most1" value="Trusting & believing in others">

  <input type="radio" name="least1" value="Trusting & believing in others">

  <input type="radio" name="most1" value="Satisfied, easy to please">

  <input type="radio" name="least1" value="Satisfied, easy to please">

  <input type="radio" name="most1" value="Clear">

  <input type="radio" name="least1" value="Clear">

  <input type="radio" name="most1" value="Calm & Peaceful">

  <input type="radio" name="least1" value="Calm & Peaceful">

</form>

To concatenate the string in javascript  $('[name="least' +  i + '"]') .. You can see the snippet above


问:
Powershell: Copy all Subdirectory and Contents in Parent Folder to Another Folder Destination
I have some folders called

```<code>C:\Source
C:\Destination

C:\Source contains
  ---> FolderA (having few files)
  ---> FolderB (having few files)
  ... etc
</code>```

I want to copy all subdirectories into C:\Destination

How would I write Powershell program which takes all multiple variable subfolders and copies into Directory?

This does not work, as it is results in copying all of Source Folder into Destination resulting in

How to copy folder with subfolders?

```<code>C:\Destination\Source
</code>```

Would like to keep same subdirectory folder structure

答:
This seems to work</p>

```<code>Get-ChildItem -Path "C:\Source" |
Copy-Item -Force -Destination "C:\Destination" -Recurse -Container
</code>```

Body:
I have some folders called

C:\Source
C:\Destination

C:\Source contains
  ---> FolderA (having few files)
  ---> FolderB (having few files)
  ... etc

I want to copy all subdirectories into C:\Destination

How would I write Powershell program which takes all multiple variable subfolders and copies into Directory?

This does not work, as it is results in copying all of Source Folder into Destination resulting in

How to copy folder with subfolders?

C:\Destination\Source

Would like to keep same subdirectory folder structure

Body:
This seems to work

Get-ChildItem -Path "C:\Source" |
Copy-Item -Force -Destination "C:\Destination" -Recurse -Container


问:
CloudFormation templates for Global Aurora Database
I am trying to write Cloudformation template to get a aws Global Aurora Database. However I am not able to figure out where and how to add the Global database identifier. Can someone help Cloudformation snippet?

below is my code:

```<code>Description: RDS Aurora MySQL cluster.
Parameters:
    DatabaseName:
      Default: "testglobalaurora"
      Description: The database name
      Type: String

    DatabaseInstanceType:
        Default: db.r4.large
        AllowedValues:
            - db.r4.large
            - db.r4.xlarge
            - db.r4.2xlarge
            - db.r4.4xlarge
            - db.r4.8xlarge
            - db.r4.16xlarge
        Description: "The instance type to use for the database."
        Type: String

    DatabasePassword:
        Default: "testglobalaurora"
        AllowedPattern: "[a-zA-Z0-9]+"
        ConstraintDescription: must contain only alphanumeric characters. Must have length 8-41.
        Description: The database admin account password.
        MaxLength: '41'
        MinLength: '8'
        NoEcho: 'true'
        Type: String

    DatabaseUsername:
        Default: "testglobalaurora"
        AllowedPattern: "[a-zA-Z0-9]+"
        ConstraintDescription: must contain only alphanumeric characters. Must have length 1-16
        Description: The database admin account user name.
        MaxLength: '16'
        MinLength: '1'
        Type: String

Metadata:
    AWS::CloudFormation::Interface:
        ParameterGroups:
            - Label:
                default: Database Configuration
              Parameters:
                - DatabaseInstanceType
                - DatabaseName
                - DatabaseUsername
                - DatabasePassword
        ParameterLabels:
            DatabaseName:
              default: Database name
            DatabaseInstanceType:
                default: Database Instance Type
            DatabasePassword:
                default: Database Password
            DatabaseUsername:
                default: Database Username

Resources:
    ParameterGroup:
        Type: "AWS::RDS::DBParameterGroup"
        Properties:
            Description: testglobalaurora DB parameter group
            Family: aurora5.6
            Parameters:
                max_connections: 300

    DatabaseCluster:
        Type: AWS::RDS::DBCluster
        Properties:
            Engine: aurora
            EngineMode: global

            MasterUsername:
              Ref: DatabaseUsername
            MasterUserPassword:
              Ref: DatabasePassword
            BackupRetentionPeriod: 35
            PreferredBackupWindow: 02:00-03:00
            PreferredMaintenanceWindow: mon:03:00-mon:04:00
            VpcSecurityGroupIds:
              - Ref: DatabaseSecurityGroup

    DatabaseInstance:
        Type: AWS::RDS::DBInstance
        Properties:
            Engine: aurora
            EngineVersion : 5.6.10a
            DBClusterIdentifier:
                Ref: DatabaseCluster
            DBInstanceClass:
                Ref: DatabaseInstanceType
            DBParameterGroupName: !Ref ParameterGroup
            PubliclyAccessible: "true"
            DBInstanceIdentifier: !Ref DatabaseName

    DatabaseSecurityGroup:
        Type: AWS::EC2::SecurityGroup
        Properties:
            VpcId: vpc-55378f2f
            GroupDescription: Access to database
            SecurityGroupIngress:
                - CidrIp: 0.0.0.0/0
                  FromPort: 3306
                  ToPort: 3306
                  IpProtocol: tcp
            Tags:
                - Key: Name
                  Value: !Sub ${DatabaseName}-security-group

Outputs:
    DatabaseEndpoint:
        Description: The database endpoint
        Value: !GetAtt DatabaseCluster.Endpoint.Address

    DatabasePort:
        Description: The database port
        Value: !GetAtt DatabaseCluster.Endpoint.Port
</code>```

My output
"

global-database-1-cluster-1 Regional     Aurora MySQL   5.6.10a

global-database-1-instance-1    Writer       Aurora MySQL   5.6.10a
"

Actual ouput
"

test-it                         Global  Aurora MySQL    5.6.10a
global-database-1-cluster-1 Primary Aurora MySQL    5.6.10a

global-database-1-instance-1    Writer  Aurora MySQL    5.6.10a
"

答:
You need to create a Global Cluster with an identifier, and use that identifier in your DB Cluster. That portion is missing in your CFN template.

Something like:

```<code>GlobalCluster:
        Type: AWS::RDS::GlobalCluster
        Properties:
            Engine: aurora
            EngineVersion: 5.6.10a
            Region: us-east-1
</code>```

and then use it in your DatabaseCluster properties using GlobalClusterIdentifier: <id>

However, looking at the official docs for the CFN types [1] for RDS, it does not list GlobalCluster. So either its just not documented or this Resource type has not been registered with Cloudformation. If the latter is the case, then you may want to open a support case and put in a feature request.

[1] https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_RDS.html

Body:
I am trying to write Cloudformation template to get a aws Global Aurora Database. However I am not able to figure out where and how to add the Global database identifier. Can someone help Cloudformation snippet?

below is my code:

Description: RDS Aurora MySQL cluster.
Parameters:
    DatabaseName:
      Default: "testglobalaurora"
      Description: The database name
      Type: String

    DatabaseInstanceType:
        Default: db.r4.large
        AllowedValues:
            - db.r4.large
            - db.r4.xlarge
            - db.r4.2xlarge
            - db.r4.4xlarge
            - db.r4.8xlarge
            - db.r4.16xlarge
        Description: "The instance type to use for the database."
        Type: String

    DatabasePassword:
        Default: "testglobalaurora"
        AllowedPattern: "[a-zA-Z0-9]+"
        ConstraintDescription: must contain only alphanumeric characters. Must have length 8-41.
        Description: The database admin account password.
        MaxLength: '41'
        MinLength: '8'
        NoEcho: 'true'
        Type: String

    DatabaseUsername:
        Default: "testglobalaurora"
        AllowedPattern: "[a-zA-Z0-9]+"
        ConstraintDescription: must contain only alphanumeric characters. Must have length 1-16
        Description: The database admin account user name.
        MaxLength: '16'
        MinLength: '1'
        Type: String

Metadata:
    AWS::CloudFormation::Interface:
        ParameterGroups:
            - Label:
                default: Database Configuration
              Parameters:
                - DatabaseInstanceType
                - DatabaseName
                - DatabaseUsername
                - DatabasePassword
        ParameterLabels:
            DatabaseName:
              default: Database name
            DatabaseInstanceType:
                default: Database Instance Type
            DatabasePassword:
                default: Database Password
            DatabaseUsername:
                default: Database Username

Resources:
    ParameterGroup:
        Type: "AWS::RDS::DBParameterGroup"
        Properties:
            Description: testglobalaurora DB parameter group
            Family: aurora5.6
            Parameters:
                max_connections: 300

    DatabaseCluster:
        Type: AWS::RDS::DBCluster
        Properties:
            Engine: aurora
            EngineMode: global

            MasterUsername:
              Ref: DatabaseUsername
            MasterUserPassword:
              Ref: DatabasePassword
            BackupRetentionPeriod: 35
            PreferredBackupWindow: 02:00-03:00
            PreferredMaintenanceWindow: mon:03:00-mon:04:00
            VpcSecurityGroupIds:
              - Ref: DatabaseSecurityGroup

    DatabaseInstance:
        Type: AWS::RDS::DBInstance
        Properties:
            Engine: aurora
            EngineVersion : 5.6.10a
            DBClusterIdentifier:
                Ref: DatabaseCluster
            DBInstanceClass:
                Ref: DatabaseInstanceType
            DBParameterGroupName: !Ref ParameterGroup
            PubliclyAccessible: "true"
            DBInstanceIdentifier: !Ref DatabaseName

    DatabaseSecurityGroup:
        Type: AWS::EC2::SecurityGroup
        Properties:
            VpcId: vpc-55378f2f
            GroupDescription: Access to database
            SecurityGroupIngress:
                - CidrIp: 0.0.0.0/0
                  FromPort: 3306
                  ToPort: 3306
                  IpProtocol: tcp
            Tags:
                - Key: Name
                  Value: !Sub ${DatabaseName}-security-group

Outputs:
    DatabaseEndpoint:
        Description: The database endpoint
        Value: !GetAtt DatabaseCluster.Endpoint.Address

    DatabasePort:
        Description: The database port
        Value: !GetAtt DatabaseCluster.Endpoint.Port

My output
"

global-database-1-cluster-1 Regional     Aurora MySQL   5.6.10a

global-database-1-instance-1    Writer       Aurora MySQL   5.6.10a
"

Actual ouput
"

test-it                         Global  Aurora MySQL    5.6.10a
global-database-1-cluster-1 Primary Aurora MySQL    5.6.10a

global-database-1-instance-1    Writer  Aurora MySQL    5.6.10a
"

Body:
You need to create a Global Cluster with an identifier, and use that identifier in your DB Cluster. That portion is missing in your CFN template.

Something like:

GlobalCluster:
        Type: AWS::RDS::GlobalCluster
        Properties:
            Engine: aurora
            EngineVersion: 5.6.10a
            Region: us-east-1

and then use it in your DatabaseCluster properties using GlobalClusterIdentifier: <id>

However, looking at the official docs for the CFN types [1] for RDS, it does not list GlobalCluster. So either its just not documented or this Resource type has not been registered with Cloudformation. If the latter is the case, then you may want to open a support case and put in a feature request.

[1] https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_RDS.html


问:
JSONP works in jQuery but not in mootools
I'm trying to convert my code to Mootools (I like the coding paradigm better).

I am doing cross-domain AJAX where I own both domains (closed network).  I am just requesting simple JSON from my server.  I get these errors in Mootools (jQuery works):

Resource interpreted as Script but transferred with MIME type text/plain.
Uncaught SyntaxError: Unexpected token :

var url = http://localhost:3000/

Server:

```<code>var http = require('http'),
    json = {"hi" : false};

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(json));
}).listen(3000, function() {
    console.log("Server on " + 3000);
});
</code>```

jQuery:

```<code>$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    success: function (data) {
    }
});
</code>```

Mootools:

```<code>var myRequest = new Request.JSONP({
    url: url,
    onComplete: function (data) {
        alert(JSON.stringify(data));
    }
});
myRequest.send();
</code>```

I've tried adding these headers to no avail.:

```<code>'Accept': 'application/json',
'Content-Type': 'application/json'
</code>```

This seems to be a client-side thing and not a server-side thing since it works in jQuery.

答:
You had a syntax error in your code.

```<code>var myRequest = new Request.JSONP({
    url: url,
    method: 'get',
    onComplete: function(data){}
});
myRequest.send();
</code>```

Also, the response should be wrapped with callback function, example: http://jsfiddle.net/zalun/yVbYQ/

Body:
I'm trying to convert my code to Mootools (I like the coding paradigm better).

I am doing cross-domain AJAX where I own both domains (closed network).  I am just requesting simple JSON from my server.  I get these errors in Mootools (jQuery works):

Resource interpreted as Script but transferred with MIME type text/plain.
Uncaught SyntaxError: Unexpected token :

var url = http://localhost:3000/

Server:

var http = require('http'),
    json = {"hi" : false};

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(json));
}).listen(3000, function() {
    console.log("Server on " + 3000);
});

jQuery:

$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    success: function (data) {
    }
});

Mootools:

var myRequest = new Request.JSONP({
    url: url,
    onComplete: function (data) {
        alert(JSON.stringify(data));
    }
});
myRequest.send();

I've tried adding these headers to no avail.:

'Accept': 'application/json',
'Content-Type': 'application/json'

This seems to be a client-side thing and not a server-side thing since it works in jQuery.

Body:
You had a syntax error in your code.

var myRequest = new Request.JSONP({
    url: url,
    method: 'get',
    onComplete: function(data){}
});
myRequest.send();

Also, the response should be wrapped with callback function, example: http://jsfiddle.net/zalun/yVbYQ/


答:
Neither pretty nor optimal, but it does what seems to be asked:

c = [-1, 0, 1, 2, 3, 4]
d = [-1, 0, 2, 3, 4, 5, 6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

def find_in_order(to_find, to_search, num_to_find):
    solutions = []
    for bucket in to_find:
        bucket_solutions = []
        solutions.append(bucket_solutions)
        for thing in [bucket[x:x + num_to_find] for x in range(len(bucket) - num_to_find + 1)]:
            for section in [main[y:y + num_to_find] for y in range(len(to_search) - num_to_find + 1)]:
                if thing == section:
                    bucket_solutions.append(thing)
    return solutions

fc, fd, fa = find_in_order([c, d, a], main, 5)

# fc == [[-1, 0, 1, 2, 3], [0, 1, 2, 3, 4]]
# fd == [[2, 3, 4, 5, 6]]
# fa == []
```

<p>There's not bounds-checking in this, so it might be brittle. I also don't like how the additions of the magic number <code>1</code> are needed to get things to align. If you care about speed, string searches do things like keeping a rolling checksum and only doing comparisons when the checksums match. This is left as an exercise. Also, I'm on:</p>

<pre class="lang-py prettyprint-override"><code>sys.version
'3.6.8 |Anaconda, Inc.| (default, Dec 30 2018, 01:22:34) \n[GCC 7.3.0]'
</code>```

Title: Finding ordered array in an ordered array

Body:
c = [-1, 0, 1, 2, 3, 4]
d = [-1,0,2,3,4,5,6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

desired output:

fc = [-1,0,1,2,3],[0,1,2,3,4]
fd = [2,3,4,5,6]
fa = []

I want to find how many times the ordered set is in the larger set given an interval. In my case, I choose 5 since this is for my poker game. Set's won't work since they need to be in order so I don't know what to use.

In my program, I tried using for loops but I'm not getting it.

ns = len(c)-5
nt = range(0,ns)
if ns >= 0:
    for n in nt:
        templist = c[n:n+5]

I just need a function to compare both lists.

Body:
Neither pretty nor optimal, but it does what seems to be asked:

c = [-1, 0, 1, 2, 3, 4]
d = [-1, 0, 2, 3, 4, 5, 6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

def find_in_order(to_find, to_search, num_to_find):
    solutions = []
    for bucket in to_find:
        bucket_solutions = []
        solutions.append(bucket_solutions)
        for thing in [bucket[x:x + num_to_find] for x in range(len(bucket) - num_to_find + 1)]:
            for section in [main[y:y + num_to_find] for y in range(len(to_search) - num_to_find + 1)]:
                if thing == section:
                    bucket_solutions.append(thing)
    return solutions

fc, fd, fa = find_in_order([c, d, a], main, 5)

# fc == [[-1, 0, 1, 2, 3], [0, 1, 2, 3, 4]]
# fd == [[2, 3, 4, 5, 6]]
# fa == []

There's not bounds-checking in this, so it might be brittle. I also don't like how the additions of the magic number 1 are needed to get things to align. If you care about speed, string searches do things like keeping a rolling checksum and only doing comparisons when the checksums match. This is left as an exercise. Also, I'm on:

sys.version
'3.6.8 |Anaconda, Inc.| (default, Dec 30 2018, 01:22:34) \n[GCC 7.3.0]'


问:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema in Angular
I have encountered an issue when i tried to run "ng serve -o" to run the angular application an error messages appears "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema"

Before, the angular "ng serve -o" is working, but when i installed "npm install ngx-bootstrap --save" ,"ng add ngx-bootstrap  --component datepicker" and "npm install webpack --save-dev" this command "ng serve -o" is not working now.

Here is the screenshot of the error
https://imgur.com/J48f0ec

Anyone can help me to figure out this?

Thank you in advance!

答:
Your error was likely caused by installing Webpack:

```<code>npm install webpack --save-dev
</code>```

The Angular CLI already has it's own Webpack dependency, which is how it builds and serves the app. Adding Webpack to your project likely crosses wires with the internal configuration in the CLI.

Try uninstalling Webpack and see if you can serve the app again.

```<code>npm uninstall webpack

ng serve -o
</code>```

Body:
Your error was likely caused by installing Webpack:

npm install webpack --save-dev

The Angular CLI already has it's own Webpack dependency, which is how it builds and serves the app. Adding Webpack to your project likely crosses wires with the internal configuration in the CLI.

Try uninstalling Webpack and see if you can serve the app again.

npm uninstall webpack

ng serve -o