问:
How to adjust different height of cardview on tablet and android phone?
I am making an android app that has a cardview inside a recyclerview. Cardview looks good on tablet and takes 40% size of screen. When i run it on a 5" android device, cardview covers 80% of screen size. Please check the code below and suggest some solutions to correct layout that automatically fits itself according to the screen sizes.

MainLayout.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentBottom="false"
       android:layout_alignParentEnd="true"
       android:layout_below="@+id/empty_view"
       android:orientation="vertical">
    <SearchView
      android:id="@+id/searchbar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
    />
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:scrollbars="vertical"
        android:clipToPadding="false"
        android:layout_height="0dp"
        android:layout_weight="1"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load More"
        android:id="@+id/btnLoad"
        android:layout_gravity="center_horizontal"
        android:layout_below="@+id/recyclerview"
        android:background="#42a7f4" />
  </LinearLayout>
</LinearLayout>
</code>```

CardViewTemplate.xml

```<code><?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
  <android.support.v7.widget.CardView
      android:id="@+id/card_view"
      android:layout_gravity="start"
      android:layout_width="match_parent"
      card_view:cardUseCompatPadding="true"
      android:layout_height="500dp"
      android:layout_marginBottom="20dp"
      android:layout_marginLeft="20dp"
      android:layout_marginRight="20dp"
      android:layout_marginTop="10dp"
      card_view:contentPaddingLeft="5dp"
      card_view:contentPaddingRight="5dp"
      card_view:contentPaddingTop="5dp"
      card_view:cardCornerRadius="0dp">
    <RelativeLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent">
      <LinearLayout
          android:id="@+id/greenBoxView"
          android:background="#EBEFF2"
          android:layout_height="50dp"
          android:orientation="horizontal"
          android:layout_width="match_parent"
          android:layout_alignParentTop="true"
          >
         <ImageView
          android:layout_height="30dp"
          android:layout_width="30dp"
          android:layout_alignParentLeft="true"
                    android:layout_marginLeft="5dp"
          android:src="@drawable/lab"
          android:layout_gravity="center_vertical"
             />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Yay! This is a Sample Title Text"
            android:textColor="#002868"
            android:textStyle="bold"
            android:paddingRight="70dp"
            android:paddingLeft="60dp"

            android:textSize="25dp"
            android:layout_gravity="center_vertical" />
      <ImageView
          android:layout_height="30dp"
          android:layout_width="30dp"
          android:layout_alignParentRight="true"
          android:src="@drawable/lab"
          android:layout_marginRight="8dp"
          android:layout_gravity="center_vertical"
             />
      </LinearLayout>
      <LinearLayout
          android:layout_below="@id/greenBoxView"
          android:layout_above="@+id/footer"
          android:id="@+id/centeralPart"
          android:paddingTop="5dp"
          android:paddingLeft="5dp"
          android:paddingRight="5dp"
          android:layout_height="match_parent"
          android:layout_width="match_parent"
          android:gravity="center_horizontal"
          android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#000"
            android:textSize="20dp"
            android:id="@+id/txtMaintitle" />
        <TextView
            android:textColor="#0080ff"
            android:textSize="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/txtSecondTitle" />
        <ListView
            android:id="@+id/mainlist_view"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:divider="@null"
            android:dividerHeight="0dp"/>
      </LinearLayout>
      <LinearLayout
          android:id="@id/footer"
          android:layout_height="80dp"
          android:layout_width="match_parent"
          android:layout_alignParentBottom="true"
          android:gravity="center_horizontal"
          android:orientation="horizontal">
        <Button
          android:id="@+id/btnOrder"
            android:layout_gravity="center_vertical"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Order"
            android:background="#00AF50"
            android:textColor="#FFFFFF"
            android:layout_marginRight="10dp" />
        <Button
            android:id="@+id/btnCompare"
            android:layout_gravity="center_vertical"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Compare"
            android:textColor="#FFFFFF"
            android:background="#0071C1" />
      </LinearLayout>
    </RelativeLayout>
  </android.support.v7.widget.CardView>
</LinearLayout>
</code>```

答:
This is what CardViewTemplate.xml should look like:

```<code><?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:ignore="HardcodedText,ContentDescription" >

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        card_view:cardCornerRadius="0dp"
        card_view:cardUseCompatPadding="true"
        card_view:contentPaddingLeft="5dp"
        card_view:contentPaddingRight="5dp"
        card_view:contentPaddingTop="5dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/greenBoxView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#EBEFF2"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center_vertical"
                    android:layout_marginStart="5dp"
                    android:src="@drawable/lab"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:paddingEnd="70dp"
                    android:paddingStart="60dp"
                    android:text="Yay! This is a Sample Title Text"
                    android:textColor="#002868"
                    android:textSize="25sp"
                    android:textStyle="bold" />

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center_vertical"
                    android:layout_marginEnd="8dp"
                    android:src="@drawable/lab" />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/centeralPart"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/footer"
                android:layout_below="@id/greenBoxView"
                android:gravity="center_horizontal"
                android:orientation="vertical"
                android:paddingLeft="5dp"
                android:paddingRight="5dp"
                android:paddingTop="5dp">

                <TextView
                    android:id="@+id/txtMaintitle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#000"
                    android:textSize="20sp" />

                <TextView
                    android:id="@+id/txtSecondTitle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#0080ff"
                    android:textSize="20sp" />

                <ListView
                    android:id="@+id/mainlist_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:divider="@null"
                    android:dividerHeight="0dp" />
            </LinearLayout>

            <LinearLayout
                android:id="@id/footer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/btnOrder"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_marginEnd="10dp"
                    android:background="#00AF50"
                    android:text="Order"
                    android:textColor="#FFFFFF" />

                <Button
                    android:id="@+id/btnCompare"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:background="#0071C1"
                    android:text="Compare"
                    android:textColor="#FFFFFF" />
            </LinearLayout>
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>
</code>```

In case this does not fit with your idea, please provide a screenshot of an inflated item view or a drawing of the layout.

Body:
I am making an android app that has a cardview inside a recyclerview. Cardview looks good on tablet and takes 40% size of screen. When i run it on a 5" android device, cardview covers 80% of screen size. Please check the code below and suggest some solutions to correct layout that automatically fits itself according to the screen sizes.

MainLayout.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentBottom="false"
       android:layout_alignParentEnd="true"
       android:layout_below="@+id/empty_view"
       android:orientation="vertical">
    <SearchView
      android:id="@+id/searchbar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
    />
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:scrollbars="vertical"
        android:clipToPadding="false"
        android:layout_height="0dp"
        android:layout_weight="1"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load More"
        android:id="@+id/btnLoad"
        android:layout_gravity="center_horizontal"
        android:layout_below="@+id/recyclerview"
        android:background="#42a7f4" />
  </LinearLayout>
</LinearLayout>

CardViewTemplate.xml

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
  <android.support.v7.widget.CardView
      android:id="@+id/card_view"
      android:layout_gravity="start"
      android:layout_width="match_parent"
      card_view:cardUseCompatPadding="true"
      android:layout_height="500dp"
      android:layout_marginBottom="20dp"
      android:layout_marginLeft="20dp"
      android:layout_marginRight="20dp"
      android:layout_marginTop="10dp"
      card_view:contentPaddingLeft="5dp"
      card_view:contentPaddingRight="5dp"
      card_view:contentPaddingTop="5dp"
      card_view:cardCornerRadius="0dp">
    <RelativeLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent">
      <LinearLayout
          android:id="@+id/greenBoxView"
          android:background="#EBEFF2"
          android:layout_height="50dp"
          android:orientation="horizontal"
          android:layout_width="match_parent"
          android:layout_alignParentTop="true"
          >
         <ImageView
          android:layout_height="30dp"
          android:layout_width="30dp"
          android:layout_alignParentLeft="true"
                    android:layout_marginLeft="5dp"
          android:src="@drawable/lab"
          android:layout_gravity="center_vertical"
             />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Yay! This is a Sample Title Text"
            android:textColor="#002868"
            android:textStyle="bold"
            android:paddingRight="70dp"
            android:paddingLeft="60dp"

            android:textSize="25dp"
            android:layout_gravity="center_vertical" />
      <ImageView
          android:layout_height="30dp"
          android:layout_width="30dp"
          android:layout_alignParentRight="true"
          android:src="@drawable/lab"
          android:layout_marginRight="8dp"
          android:layout_gravity="center_vertical"
             />
      </LinearLayout>
      <LinearLayout
          android:layout_below="@id/greenBoxView"
          android:layout_above="@+id/footer"
          android:id="@+id/centeralPart"
          android:paddingTop="5dp"
          android:paddingLeft="5dp"
          android:paddingRight="5dp"
          android:layout_height="match_parent"
          android:layout_width="match_parent"
          android:gravity="center_horizontal"
          android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#000"
            android:textSize="20dp"
            android:id="@+id/txtMaintitle" />
        <TextView
            android:textColor="#0080ff"
            android:textSize="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/txtSecondTitle" />
        <ListView
            android:id="@+id/mainlist_view"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:divider="@null"
            android:dividerHeight="0dp"/>
      </LinearLayout>
      <LinearLayout
          android:id="@id/footer"
          android:layout_height="80dp"
          android:layout_width="match_parent"
          android:layout_alignParentBottom="true"
          android:gravity="center_horizontal"
          android:orientation="horizontal">
        <Button
          android:id="@+id/btnOrder"
            android:layout_gravity="center_vertical"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Order"
            android:background="#00AF50"
            android:textColor="#FFFFFF"
            android:layout_marginRight="10dp" />
        <Button
            android:id="@+id/btnCompare"
            android:layout_gravity="center_vertical"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Compare"
            android:textColor="#FFFFFF"
            android:background="#0071C1" />
      </LinearLayout>
    </RelativeLayout>
  </android.support.v7.widget.CardView>
</LinearLayout>

Body:
This is what CardViewTemplate.xml should look like:

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:ignore="HardcodedText,ContentDescription" >

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        card_view:cardCornerRadius="0dp"
        card_view:cardUseCompatPadding="true"
        card_view:contentPaddingLeft="5dp"
        card_view:contentPaddingRight="5dp"
        card_view:contentPaddingTop="5dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/greenBoxView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#EBEFF2"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center_vertical"
                    android:layout_marginStart="5dp"
                    android:src="@drawable/lab"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:paddingEnd="70dp"
                    android:paddingStart="60dp"
                    android:text="Yay! This is a Sample Title Text"
                    android:textColor="#002868"
                    android:textSize="25sp"
                    android:textStyle="bold" />

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center_vertical"
                    android:layout_marginEnd="8dp"
                    android:src="@drawable/lab" />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/centeralPart"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/footer"
                android:layout_below="@id/greenBoxView"
                android:gravity="center_horizontal"
                android:orientation="vertical"
                android:paddingLeft="5dp"
                android:paddingRight="5dp"
                android:paddingTop="5dp">

                <TextView
                    android:id="@+id/txtMaintitle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#000"
                    android:textSize="20sp" />

                <TextView
                    android:id="@+id/txtSecondTitle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#0080ff"
                    android:textSize="20sp" />

                <ListView
                    android:id="@+id/mainlist_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:divider="@null"
                    android:dividerHeight="0dp" />
            </LinearLayout>

            <LinearLayout
                android:id="@id/footer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:gravity="center_horizontal"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/btnOrder"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_marginEnd="10dp"
                    android:background="#00AF50"
                    android:text="Order"
                    android:textColor="#FFFFFF" />

                <Button
                    android:id="@+id/btnCompare"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:background="#0071C1"
                    android:text="Compare"
                    android:textColor="#FFFFFF" />
            </LinearLayout>
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

In case this does not fit with your idea, please provide a screenshot of an inflated item view or a drawing of the layout.


来源: stackexchange

问:
issue with multiplying sequences in Python
Can anyone tell me why my code is returning the error (in the Python IDLE)?:

TypeError: can't multiply sequence by non-int of type 'str' ".

here is the code that's been causing the errors:

```<code>def main():
    varone = input("Enter total number of episodes:  ")
    vartwo = input("enter approx. time of each episode (in minutes):  ")
    varthree = varone * vartwo
    print(varthree)
    print("minutes")
main()
</code>```

答:
input() returns strings... Convert to integers:

```<code>varthree = int(varone) * int(vartwo)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Can anyone tell me why my code is returning the error (in the Python IDLE)?:

TypeError: can't multiply sequence by non-int of type 'str' ".

here is the code that's been causing the errors:

def main():
    varone = input("Enter total number of episodes:  ")
    vartwo = input("enter approx. time of each episode (in minutes):  ")
    varthree = varone * vartwo
    print(varthree)
    print("minutes")
main()

Body:
input() returns strings... Convert to integers:

varthree = int(varone) * int(vartwo)


答:
depends on whether you are using python 2.x or 3.x

in 3.x input always gives you a string, so a quick fix is:

```<code>varthree = int(varone) * int(vartwo)
</code>```

Title: issue with multiplying sequences in Python

Body:
depends on whether you are using python 2.x or 3.x

in 3.x input always gives you a string, so a quick fix is:

varthree = int(varone) * int(vartwo)


问:
FirebaseRecycleAdapter adding onSwipe the right way
I have a FirebaseRecyclerAdapter where I try to add an onSwipe method that I created with the ItemTouchHelper.SimpleCallback. Below is my code where is try to delete a firebase entry upon swipe. The code below does indeed delete a firebase entry, except it always deletes the last entry in the list. I expect it has something to do with parsing the list_id the wrong way. Is it perhaps possible to call onSwipe inside the populateViewHolder?

```<code>private String other_id;

protected void onStart() {
    super.onStart();

final FirebaseRecyclerAdapter<Lists, ListAdapter.ListsViewHolder> listsRecycleViewAdapter = new FirebaseRecyclerAdapter<Lists, ListAdapter.ListsViewHolder>(
            Lists.class,
            R.layout.list_single_layout,
            ListAdapter.ListsViewHolder.class,
            mDoneListRef

    ) {
        @Override
        protected void populateViewHolder(final ListAdapter.ListsViewHolder viewHolder, Lists model, final int position) {

            final String list_id = getRef(viewHolder.getAdapterPosition()).getKey();

            other_id = list_id;

            mDoneListRef.child(list_id).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()) {

                    //do stuff

                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    };

    mListView.setAdapter(listsRecycleViewAdapter);

}

@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {

    mDoneListRef.child(other_id).removeValue();
}
</code>```

答:
You'll need to look up the item that was swiped by the position parameter that is passed into onSwiped. Something along these lines:

```<code>public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {
    listsRecycleViewAdapter.getRef(position).removeValue();
}
</code>```

Body:
I have a FirebaseRecyclerAdapter where I try to add an onSwipe method that I created with the ItemTouchHelper.SimpleCallback. Below is my code where is try to delete a firebase entry upon swipe. The code below does indeed delete a firebase entry, except it always deletes the last entry in the list. I expect it has something to do with parsing the list_id the wrong way. Is it perhaps possible to call onSwipe inside the populateViewHolder?

private String other_id;

protected void onStart() {
    super.onStart();

final FirebaseRecyclerAdapter<Lists, ListAdapter.ListsViewHolder> listsRecycleViewAdapter = new FirebaseRecyclerAdapter<Lists, ListAdapter.ListsViewHolder>(
            Lists.class,
            R.layout.list_single_layout,
            ListAdapter.ListsViewHolder.class,
            mDoneListRef

    ) {
        @Override
        protected void populateViewHolder(final ListAdapter.ListsViewHolder viewHolder, Lists model, final int position) {

            final String list_id = getRef(viewHolder.getAdapterPosition()).getKey();

            other_id = list_id;

            mDoneListRef.child(list_id).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()) {

                    //do stuff

                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    };

    mListView.setAdapter(listsRecycleViewAdapter);

}

@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {

    mDoneListRef.child(other_id).removeValue();
}

Body:
You'll need to look up the item that was swiped by the position parameter that is passed into onSwiped. Something along these lines:

public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {
    listsRecycleViewAdapter.getRef(position).removeValue();
}


问:
Get List Of Functions From Script
If I have a .ps1 file with the following functions

```<code>function SomeFunction {}

function AnotherFunction {}
</code>```

How can I get a list of all those functions and invoke them?

I'd like to do something like this:

```<code>$functionsFromFile = Get-ListOfFunctions -Path 'C:\someScript.ps1'
foreach($function in $functionsFromFile)
{
   $function.Run() #SomeFunction and AnotherFunction execute
}
</code>```

答:
I needed to get the name of the functions from a multi-function script.  This is what I came up with.  Based on this maybe someone can provide a shorter version.

```<code># Get text lines from file that contain 'function'
$functionList = Select-String -Path $scriptName -Pattern "function"

# Iterate through all of the returned lines
foreach ($functionDef in $functionList)
{
    # Get index into string where function definition is and skip the space
    $funcIndex = ([string]$functionDef).LastIndexOf(" ") + 1

    # Get the function name from the end of the string
    $FunctionExport = ([string]$functionDef).Substring($funcIndex)

    Write-Output $FunctionExport
}
</code>```

I came up with a shorter version to find and list the functions in a list of scripts.  It is not perfect and will have an issue because the pattern is just the word "Function" and if this method will assume it has found a function anywhere it finds the keyword.

To iterate through the files and get a list I used the 'Get-ChildItem' function and passed a path and file filter specification using the recursive option.

That gets passed into the 'Select-String' through the pipeline and looks for the 'Function' keyword.  It is not case-sensitive and will accept "Function" or "function".  there is a case sensitive option if needed by adding the "-CaseSensitive".

The output is then iterated over to get the actual function names.  The "Line" member is a string type and I used the "Substring" option starting at position 9, which is the length just passed the "function" identifier.

```<code>$scriptPath = "c:\\Project"
$scriptFilter = "*.ps1"

( Get-ChildItem -Path $scriptPath -Filter $scriptFilter -Recurse | Select-String -Pattern "function" ) | %{ $_.Line.Substring(9) }
</code>```

Title: Get List Of Functions From Script

Body:
If I have a .ps1 file with the following functions

function SomeFunction {}

function AnotherFunction {}

How can I get a list of all those functions and invoke them?

I'd like to do something like this:

$functionsFromFile = Get-ListOfFunctions -Path 'C:\someScript.ps1'
foreach($function in $functionsFromFile)
{
   $function.Run() #SomeFunction and AnotherFunction execute
}

Body:
I needed to get the name of the functions from a multi-function script.  This is what I came up with.  Based on this maybe someone can provide a shorter version.

# Get text lines from file that contain 'function'
$functionList = Select-String -Path $scriptName -Pattern "function"

# Iterate through all of the returned lines
foreach ($functionDef in $functionList)
{
    # Get index into string where function definition is and skip the space
    $funcIndex = ([string]$functionDef).LastIndexOf(" ") + 1

    # Get the function name from the end of the string
    $FunctionExport = ([string]$functionDef).Substring($funcIndex)

    Write-Output $FunctionExport
}

I came up with a shorter version to find and list the functions in a list of scripts.  It is not perfect and will have an issue because the pattern is just the word "Function" and if this method will assume it has found a function anywhere it finds the keyword.

To iterate through the files and get a list I used the 'Get-ChildItem' function and passed a path and file filter specification using the recursive option.

That gets passed into the 'Select-String' through the pipeline and looks for the 'Function' keyword.  It is not case-sensitive and will accept "Function" or "function".  there is a case sensitive option if needed by adding the "-CaseSensitive".

The output is then iterated over to get the actual function names.  The "Line" member is a string type and I used the "Substring" option starting at position 9, which is the length just passed the "function" identifier.

$scriptPath = "c:\\Project"
$scriptFilter = "*.ps1"

( Get-ChildItem -Path $scriptPath -Filter $scriptFilter -Recurse | Select-String -Pattern "function" ) | %{ $_.Line.Substring(9) }


问:
How to check if a Keyword exists in an Access Query
My question is quite simple but my access database have multiple queries and I want to write an automate process to check if certain keyword exists in any of the queries. This automate process can either be a query or a VBA. Can someone please give me an idea where to start?

Thanks in advance!

答:
@vivi Use @Don-George's answer, but if you just want the query's name(s), replace the middle part:</p>

```<code>If InStr(S, F_string) > 0 Then
    Debug.Print QD.Name
End If
</code>```

Body:
@vivi Use @Don-George's answer, but if you just want the query's name(s), replace the middle part:

If InStr(S, F_string) > 0 Then
    Debug.Print QD.Name
End If


问:
How can I get only 1 result to be printed to the console and not both of them?

My code here has a problem but I know what the problem is. There are 2 characters in grade, so 2 results are shown, each result is added by 0.3. That is a problem because only one result is supposed to be printed to the console.

```<code>keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3}
grade = input('Grade:')

def letter2number(letter):
    if len(grade) > 2:
        print('Too many characters')
        letter2number(grade)
    for char in grade:
        if char in keydict:
            if '+' in grade:
                print(keydict[char] + keydict['+'])
            elif '-' in grade:
                print(keydict[char] + keydict['-'])
            else:
                print(keydict[char])
        else:
            print(grade,'is an invalid input')
    return

letter2number(grade)
</code>```

This is what gets printed to the screen after the user inputs "A+"(or any grade with a '+' or '-') I realize the for loop is causing this problem because there are 2 characters in the input. But I don't think there is another way to do it without using a for loop. The 4.3 is expected, the 0.6 is not what I want.

```<code>Grade: A+ # <<< Thats a user input
4.3       # <<< YES
0.6       # <<< How can I get this to NOT print
</code>```

Other than the 0.6 being printed, I have no other issue with the code. In other words, I don't want the 0.6 there, but the 4.3 should stay.

答:
Your for loop is unnecessary here, and causing your issue. Remember that the for loop is going to look at both characters independently

```<code>"A"  # evaluates to 4.0, add 0.3 since '+' exists in the string
"+"  # evaluates to 0.3, add 0.3 since '+' exists in the string
</code>```

Which is definitely not what you want. What you should do instead is:

```<code>def lettertograde(letter):
    letter, *modifier = letter
    grade = keydict[letter]
    if "+" in modifier:
        grade += 0.3
    elif "-" in modifier:
        grade -= 0.3
    return grade
</code>```

This a, *b = ... syntax is splat unpacking, and works by pulling parts out of an iterable like so:

```<code>a, *b = "A"          # a = "A", b = []
a, *b = "A+"         # a = "A", b = ["+"]
a, *b = "A-"         # a = "A", b = ["-"]
a, *b = "Good job!"  # a = "G", b = ["o", "o", "d", " ", "j", "o", "b", "!"]
a, *b = ""           # ValueError("not enough values to unpack (expected at least 1, got 0)")
</code>```

N.B. that multiple splats in the same expression introduces ambiguity, and is not allowed.

```<code>a, *b, c, *d = "anything"  # SyntaxError("two starred expressions in assignment")
</code>```

Body:
My code here has a problem but I know what the problem is. There are 2 characters in grade, so 2 results are shown, each result is added by 0.3. That is a problem because only one result is supposed to be printed to the console.

keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3}
grade = input('Grade:')

def letter2number(letter):
    if len(grade) > 2:
        print('Too many characters')
        letter2number(grade)
    for char in grade:
        if char in keydict:
            if '+' in grade:
                print(keydict[char] + keydict['+'])
            elif '-' in grade:
                print(keydict[char] + keydict['-'])
            else:
                print(keydict[char])
        else:
            print(grade,'is an invalid input')
    return

letter2number(grade)

This is what gets printed to the screen after the user inputs "A+"(or any grade with a '+' or '-') I realize the for loop is causing this problem because there are 2 characters in the input. But I don't think there is another way to do it without using a for loop. The 4.3 is expected, the 0.6 is not what I want.

Grade: A+ # <<< Thats a user input
4.3       # <<< YES
0.6       # <<< How can I get this to NOT print

Other than the 0.6 being printed, I have no other issue with the code. In other words, I don't want the 0.6 there, but the 4.3 should stay.

Body:
Your for loop is unnecessary here, and causing your issue. Remember that the for loop is going to look at both characters independently

"A"  # evaluates to 4.0, add 0.3 since '+' exists in the string
"+"  # evaluates to 0.3, add 0.3 since '+' exists in the string

Which is definitely not what you want. What you should do instead is:

def lettertograde(letter):
    letter, *modifier = letter
    grade = keydict[letter]
    if "+" in modifier:
        grade += 0.3
    elif "-" in modifier:
        grade -= 0.3
    return grade

This a, *b = ... syntax is splat unpacking, and works by pulling parts out of an iterable like so:

a, *b = "A"          # a = "A", b = []
a, *b = "A+"         # a = "A", b = ["+"]
a, *b = "A-"         # a = "A", b = ["-"]
a, *b = "Good job!"  # a = "G", b = ["o", "o", "d", " ", "j", "o", "b", "!"]
a, *b = ""           # ValueError("not enough values to unpack (expected at least 1, got 0)")

N.B. that multiple splats in the same expression introduces ambiguity, and is not allowed.

a, *b, c, *d = "anything"  # SyntaxError("two starred expressions in assignment")


问:
Why does my COM Smart Pointer get deleted when returning from method
Why does my COM Smart Pointer try to delete when I return from func.  I would think that it's still in scope.  Is there a way to avoid this?

This is the definition in the .TLH file

```<code>_COM_SMARTPTR_TYPEDEF(IComItem, __uuidof(IComItem));
</code>```

```<code>static IComItemPtr m_pItem;

LPDISPATCH func()
{
    IComItemPtr  pItem = m_pItem;

    pItem = pItem->GetParent();  // Returns parent as IComItemPtr

    return pItem;   // Gets deleted here

}
</code>```

答:
Your function's return type is a raw IDispatch* pointer, not an IComItemPtr object (or at least an IDispatchPtr object).  The issue you are seeing is due to you incorrectly mixing a smart pointer with a raw pointer.

Since your function does not return a smart wrapper object, a conversion must be performed to convert pItem to IDispatch*.  The only conversion that pItem can perform in this situation is to IComItem*, which the compiler can then implicitly convert to IDispatch* (since IComItem derives from IDispatch, otherwise your code wouldn't compile at all).

IOW, your return statement is effectively doing this logic:

```<code>LPDISPATCH func()
{
    IComItemPtr  pItem = m_pItem;

    pItem = pItem->GetParent();  // Returns parent as IComItemPtr

    //return pItem;
    IComItem *pTemp = pItem.operator IComItem*();
    IDispatch *pDisp = (IDispatch*) pTemp;
    return pDisp;

} // <-- pItem is destructed here!
</code>```

No matter what, pItem itself is always going to go out of scope when the function exits, decrementing the object's refcount if pItem is referencing an object.

So, what is important is that you return a IDispatch* pointer to a valid object that has its refcount incremented so the object is not freed when pItem's destructor decrements its refcount.

Try this instead:

```<code>IComItemPtr func()
{
    return m_pItem->GetParent();  // Returns parent as IComItemPtr
}
</code>```

Or:

```<code>IDispatchPtr func()
{
    return m_pItem->GetParent();  // Returns parent as IComItemPtr converted to IDispatchPtr
}
</code>```

If you absolutely must return a raw IDispatch* pointer, then you have to either:

manually increment the refcount before exiting:

```<code>LPDISPATCH func()
{
    IComItemPtr pItem = m_pItem->GetParent();  // Returns parent as IComItemPtr
    pItem.AddRef();
    return pItem;
}
</code>```

manually detach the pointer from the wrapper:

```<code>LPDISPATCH func()
{
    IComItemPtr pItem = m_pItem->GetParent();  // Returns parent as IComItemPtr
    return pItem.Detach();
}
</code>```

Body:
Why does my COM Smart Pointer try to delete when I return from func.  I would think that it's still in scope.  Is there a way to avoid this?

This is the definition in the .TLH file

_COM_SMARTPTR_TYPEDEF(IComItem, __uuidof(IComItem));

static IComItemPtr m_pItem;

LPDISPATCH func()
{
    IComItemPtr  pItem = m_pItem;

    pItem = pItem->GetParent();  // Returns parent as IComItemPtr

    return pItem;   // Gets deleted here

}

Body:
Your function's return type is a raw IDispatch* pointer, not an IComItemPtr object (or at least an IDispatchPtr object).  The issue you are seeing is due to you incorrectly mixing a smart pointer with a raw pointer.

Since your function does not return a smart wrapper object, a conversion must be performed to convert pItem to IDispatch*.  The only conversion that pItem can perform in this situation is to IComItem*, which the compiler can then implicitly convert to IDispatch* (since IComItem derives from IDispatch, otherwise your code wouldn't compile at all).

IOW, your return statement is effectively doing this logic:

LPDISPATCH func()
{
    IComItemPtr  pItem = m_pItem;

    pItem = pItem->GetParent();  // Returns parent as IComItemPtr

    //return pItem;
    IComItem *pTemp = pItem.operator IComItem*();
    IDispatch *pDisp = (IDispatch*) pTemp;
    return pDisp;

} // <-- pItem is destructed here!

No matter what, pItem itself is always going to go out of scope when the function exits, decrementing the object's refcount if pItem is referencing an object.

So, what is important is that you return a IDispatch* pointer to a valid object that has its refcount incremented so the object is not freed when pItem's destructor decrements its refcount.

Try this instead:

IComItemPtr func()
{
    return m_pItem->GetParent();  // Returns parent as IComItemPtr
}

Or:

IDispatchPtr func()
{
    return m_pItem->GetParent();  // Returns parent as IComItemPtr converted to IDispatchPtr
}

If you absolutely must return a raw IDispatch* pointer, then you have to either:

manually increment the refcount before exiting:

LPDISPATCH func()
{
    IComItemPtr pItem = m_pItem->GetParent();  // Returns parent as IComItemPtr
    pItem.AddRef();
    return pItem;
}

manually detach the pointer from the wrapper:

LPDISPATCH func()
{
    IComItemPtr pItem = m_pItem->GetParent();  // Returns parent as IComItemPtr
    return pItem.Detach();
}


问:
hibernate DTO with a deviant database
I am building a spring boot application which uses REST services to deliver content to the front-end

But my DTO does not correspond to my database.
Here is a diagram of the database
And my DTO should look something like this

public class GlobeEntity extends BaseEntity {
//  for all definition years
    private List<Instance> instances;
    class Instance {
//      CountryInstance.definitionYear
        private String definitionYear;
//      for all countries
        private List<Country> countries;
        class Country {
//          Country.countryId
            String id;
//          Country.externalIdentifier
            String externalIdentifier;
//          CountryInstanceCompatibility.total
            String com;
//          CountryInstanceUtility.total
            String uti;
        }
    }
}
```

Is this possible to do with hibernate annotations?

答:
For the DTO, what is turned into JSON when you return that class from a controller depends on your JSON serializer you have configured in Spring. Then you make use of the JSON annotations to have more control over what is returned.
Depending on how you do things, you may just choose to convert between an entity and a DTO, and have a class for each. Although this is a bit annoying because it does add allot of overhead of having more classes and other classes depending on the two, it can be come a real real mess if you use the same class for both DTO and Entity representations when they are very different. For instance if you use a method in your controller, it's not clear wether this is an entity or a DTO. There are many cases when you have a controller you return a response which is not a resource in a database.</p>

Title: hibernate DTO with a deviant database

Body:
I am building a spring boot application which uses REST services to deliver content to the front-end

But my DTO does not correspond to my database.
Here is a diagram of the database
And my DTO should look something like this

public class GlobeEntity extends BaseEntity {
//  for all definition years
    private List<Instance> instances;
    class Instance {
//      CountryInstance.definitionYear
        private String definitionYear;
//      for all countries
        private List<Country> countries;
        class Country {
//          Country.countryId
            String id;
//          Country.externalIdentifier
            String externalIdentifier;
//          CountryInstanceCompatibility.total
            String com;
//          CountryInstanceUtility.total
            String uti;
        }
    }
}

Is this possible to do with hibernate annotations?


问:
Is there a better way to declare multiple parameter sets?
I'm writing a cmdlet (in PowerShell) that is responsible for writing a record into a database. With the conditional command line, it seems like I have to define four different parameter sets.

Is there a more succient way of doing this?

DETAILS

The parameters of the cmdlet are:

ComputerName (the SQL server to connect to)

Path (the location of the data)

Xml (the raw data itself)

UserName

Password

UseIntegratedSecurity (instead of username/password, use current credentials)

Path and Xml are mutually exclusive, and UserName/Password and UseIntegratedSecurity are mutually exclusive.

To get this wired up correctly, it seems like I have to define four different parameter sets, e.g.:

```<code>
function Install-WidgetData
{
    [CmdletBinding()]
    PARAM
    (
        [Parameter(ParameterSetName="Xml_AutoConnect", Mandatory=$True)]
        [Parameter(ParameterSetName="Xml_ManualConnect", Mandatory=$True)]
        [Parameter(ParameterSetName="Path_AutoConnect", Mandatory=$True, )]
        [Parameter(ParameterSetName="Path_ManualConnect", Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [string[]] $ComputerName,

        [Parameter(ParameterSetName="Path_AutoConnect", Mandatory=$True)]
        [Parameter(ParameterSetName="Path_ManualConnect", Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [string] $Path,

        [Parameter(ParameterSetName="Xml_AutoConnect", Mandatory=$True)]
        [Parameter(ParameterSetName="Xml_ManualConnect", Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [string[]] $Xml,

        [Parameter(ParameterSetName="Xml_AutoConnect")]
        [Parameter(ParameterSetName="Path_AutoConnect")]
        [switch] $UseIntegratedSecurity,

        [Parameter(ParameterSetName="Xml_ManualConnect")]
        [Parameter(ParameterSetName="Path_ManualConnect")]
        [ValidateNotNullOrEmpty()]
        [string] $UserName,

        [Parameter(ParameterSetName="Xml_ManualConnect")]
        [Parameter(ParameterSetName="Path_ManualConnect")]
        [ValidateNotNullOrEmpty()]
        [string] $Password,
    )
</code>```

答:
There is a better way, but it's a design solution rather than a technical one.

The problem is actually that your function is doing too many things. One might say it's violating the single responsibility principle. Each task it performs has two separate parameter sets. The tasks and their parameter sets are:

Build a connection string

Manual (user name and password)

Auto (OS account authentication)

Sending a query to the database

XML data

Path to XML file containing data

Since each task has its own different parameters sets, your function ends up needing the Cartesian product of them (Manual & XML, Auto & XML, Manual & path, Auto & path).

Any time you find yourself in one of these "Cartesian product" parameter situations, it's almost always a sign that you can move one piece of functionality into a separate function and make the new function's result a parameter to the original. In this case, you can split it up into New-ConnectionString and Install-WidgetData, and Install-WidgetData can accept a full connection string as a parameter. This removes the logic of building the connection string from Install-WidgetData, condensing several parameters into one and halving the number of parameter sets needed.

```<code>function New-ConnectionString(
    [Parameter(Mandatory=$True, Position=0)] # Makes it mandatory for all parameter sets
    [ValidateNotNullOrEmpty()]
    [string[]]$ComputerName,

    [Parameter(ParameterSetName="AutoConnect", Mandatory=$True)]
    [switch]$UseIntegratedSecurity,

    [Parameter(ParameterSetName="ManualConnect", Mandatory=$True, Position=1)]
    [ValidateNotNullOrEmpty()]
    [string]$UserName,

    [Parameter(ParameterSetName="ManualConnect", Mandatory=$True, Position=2)]
    [ValidateNotNullOrEmpty()]
    [string]$Password
) {
    # ... Build connection string up
    return $connString
}

function Install-WidgetData(
    [Parameter(Mandatory=$True, Position=0)]
    [ValidateNotNullOrEmpty()]
    [string]$ConnectionString,

    [Parameter(ParameterSetName="Path", Mandatory=$True, Position=1)]
    [ValidateNotNullOrEmpty()]
    [string]$Path,

    [Parameter(ParameterSetName="Xml", Mandatory=$True)]
    [ValidateNotNullOrEmpty()]
    [string[]]$Xml
) {
     # Do installation
}
</code>```

You can see that this did what you want by invoking help on the commands:

```<code>PS C:\> help New-ConnectionString

NAME
    New-ConnectionString

SYNTAX
    New-ConnectionString [-ComputerName] <string[]> -UseIntegratedSecurity  [<CommonParameters>]

    New-ConnectionString [-ComputerName] <string[]> [-UserName] <string> [-Password] <string>  [<CommonParameters>]

...

PS C:\> help Install-WidgetData

NAME
    Install-WidgetData

SYNTAX
    Install-WidgetData [-ConnectionString] <string> [-Path] <string>  [<CommonParameters>]

    Install-WidgetData [-ConnectionString] <string> -Xml <string[]>  [<CommonParameters>]

...
</code>```

Then you call them something like this:

```<code>Install-WidgetData (New-ConnectionString 'myserver.example.com' -UseIntegratedSecurity) `
    -Path '.\my-widget-data.xml'
</code>```

You can store the result of New-ConnectionString in a variable if you want, of course. You also get some additional features from doing this refactor:

New-ConnectionString's return value can be reused for any number of functions that require a connection string.

Callers can obtain connection strings from other sources if they prefer

Callers can forego your New-ConnectionString in favor of doing it themselves if they need to use features you didn't provide access to

Body:
I'm writing a cmdlet (in PowerShell) that is responsible for writing a record into a database. With the conditional command line, it seems like I have to define four different parameter sets.

Is there a more succient way of doing this?

DETAILS

The parameters of the cmdlet are:

ComputerName (the SQL server to connect to)

Path (the location of the data)

Xml (the raw data itself)

UserName

Password

UseIntegratedSecurity (instead of username/password, use current credentials)

Path and Xml are mutually exclusive, and UserName/Password and UseIntegratedSecurity are mutually exclusive.

To get this wired up correctly, it seems like I have to define four different parameter sets, e.g.:

function Install-WidgetData
{
    [CmdletBinding()]
    PARAM
    (
        [Parameter(ParameterSetName="Xml_AutoConnect", Mandatory=$True)]
        [Parameter(ParameterSetName="Xml_ManualConnect", Mandatory=$True)]
        [Parameter(ParameterSetName="Path_AutoConnect", Mandatory=$True, )]
        [Parameter(ParameterSetName="Path_ManualConnect", Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [string[]] $ComputerName,

        [Parameter(ParameterSetName="Path_AutoConnect", Mandatory=$True)]
        [Parameter(ParameterSetName="Path_ManualConnect", Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [string] $Path,

        [Parameter(ParameterSetName="Xml_AutoConnect", Mandatory=$True)]
        [Parameter(ParameterSetName="Xml_ManualConnect", Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [string[]] $Xml,

        [Parameter(ParameterSetName="Xml_AutoConnect")]
        [Parameter(ParameterSetName="Path_AutoConnect")]
        [switch] $UseIntegratedSecurity,

        [Parameter(ParameterSetName="Xml_ManualConnect")]
        [Parameter(ParameterSetName="Path_ManualConnect")]
        [ValidateNotNullOrEmpty()]
        [string] $UserName,

        [Parameter(ParameterSetName="Xml_ManualConnect")]
        [Parameter(ParameterSetName="Path_ManualConnect")]
        [ValidateNotNullOrEmpty()]
        [string] $Password,
    )

Body:
There is a better way, but it's a design solution rather than a technical one.

The problem is actually that your function is doing too many things. One might say it's violating the single responsibility principle. Each task it performs has two separate parameter sets. The tasks and their parameter sets are:

Build a connection string

Manual (user name and password)

Auto (OS account authentication)

Sending a query to the database

XML data

Path to XML file containing data

Since each task has its own different parameters sets, your function ends up needing the Cartesian product of them (Manual & XML, Auto & XML, Manual & path, Auto & path).

Any time you find yourself in one of these "Cartesian product" parameter situations, it's almost always a sign that you can move one piece of functionality into a separate function and make the new function's result a parameter to the original. In this case, you can split it up into New-ConnectionString and Install-WidgetData, and Install-WidgetData can accept a full connection string as a parameter. This removes the logic of building the connection string from Install-WidgetData, condensing several parameters into one and halving the number of parameter sets needed.

function New-ConnectionString(
    [Parameter(Mandatory=$True, Position=0)] # Makes it mandatory for all parameter sets
    [ValidateNotNullOrEmpty()]
    [string[]]$ComputerName,

    [Parameter(ParameterSetName="AutoConnect", Mandatory=$True)]
    [switch]$UseIntegratedSecurity,

    [Parameter(ParameterSetName="ManualConnect", Mandatory=$True, Position=1)]
    [ValidateNotNullOrEmpty()]
    [string]$UserName,

    [Parameter(ParameterSetName="ManualConnect", Mandatory=$True, Position=2)]
    [ValidateNotNullOrEmpty()]
    [string]$Password
) {
    # ... Build connection string up
    return $connString
}

function Install-WidgetData(
    [Parameter(Mandatory=$True, Position=0)]
    [ValidateNotNullOrEmpty()]
    [string]$ConnectionString,

    [Parameter(ParameterSetName="Path", Mandatory=$True, Position=1)]
    [ValidateNotNullOrEmpty()]
    [string]$Path,

    [Parameter(ParameterSetName="Xml", Mandatory=$True)]
    [ValidateNotNullOrEmpty()]
    [string[]]$Xml
) {
     # Do installation
}

You can see that this did what you want by invoking help on the commands:

PS C:\> help New-ConnectionString

NAME
    New-ConnectionString

SYNTAX
    New-ConnectionString [-ComputerName] <string[]> -UseIntegratedSecurity  [<CommonParameters>]

    New-ConnectionString [-ComputerName] <string[]> [-UserName] <string> [-Password] <string>  [<CommonParameters>]

...

PS C:\> help Install-WidgetData

NAME
    Install-WidgetData

SYNTAX
    Install-WidgetData [-ConnectionString] <string> [-Path] <string>  [<CommonParameters>]

    Install-WidgetData [-ConnectionString] <string> -Xml <string[]>  [<CommonParameters>]

...

Then you call them something like this:

Install-WidgetData (New-ConnectionString 'myserver.example.com' -UseIntegratedSecurity) `
    -Path '.\my-widget-data.xml'

You can store the result of New-ConnectionString in a variable if you want, of course. You also get some additional features from doing this refactor:

New-ConnectionString's return value can be reused for any number of functions that require a connection string.

Callers can obtain connection strings from other sources if they prefer

Callers can forego your New-ConnectionString in favor of doing it themselves if they need to use features you didn't provide access to


问:
Custom progress bar doesn't update smoothly
I'm trying to do a circular progress bar run smoothly but I'm not having result. The progress bar should be update in function of a timer value.

Here is how I animate the progressbar,

```<code>int progress = (int)(this.mCurrentTimerValue/1000);
this.mProgressBarAnimation = ObjectAnimator.ofInt(this.mProgressBar,"progress",progress);
this.mProgressBarAnimation.setDuration(this.mCurrentTimerValue);
this.mProgressBarAnimation.setInterpolator( new LinearInterpolator());
</code>```

where this.mCurrentTimerValue is the time in ml. For this example is 10000

And here is the result,

I want to show the progress smoothly but I can't. I tried with ObjectAnimator.ofFloat because the problem maybe is that I'm trying to progress in integer spaces but in that case animation doesn't work.

Here is how I customized the progress bar,

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/progress">
    <rotate
        android:fromDegrees="270"
        android:toDegrees="270"
        android:pivotX="50%"
        android:pivotY="50%" >
        <shape
            android:innerRadiusRatio="2.5"
            android:shape="ring"
            android:thicknessRatio="25.0" >
            <gradient
                android:centerColor="@color/yellow"
                android:endColor="@color/yellow"
                android:startColor="@color/yellow"
                android:type="sweep" />
        </shape>
    </rotate>
</item>
<item android:id="@android:id/secondaryProgress">
    <rotate
        android:fromDegrees="270"
        android:toDegrees="270"
        android:pivotX="50%"
        android:pivotY="50%" >
        <shape
            android:innerRadiusRatio="2.5"
            android:shape="ring"
            android:thicknessRatio="25.0" >
            <gradient
                android:centerColor="@color/green"
                android:endColor="@color/green"
                android:startColor="@color/green"
                android:type="sweep" />
        </shape>
    </rotate>
</item>
</code>```

```<code><ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:indeterminate="false"
        android:progress="100"
        android:progressDrawable="@drawable/custom_progress_bar" />
</code>```

I read these questions but didn't help me,

question 1

question 2

question 3

答: If somebody need a solution for this situation, this answer helped me but I admit I don't think is the best.</p>

Body:
I'm trying to do a circular progress bar run smoothly but I'm not having result. The progress bar should be update in function of a timer value.

Here is how I animate the progressbar,

int progress = (int)(this.mCurrentTimerValue/1000);
this.mProgressBarAnimation = ObjectAnimator.ofInt(this.mProgressBar,"progress",progress);
this.mProgressBarAnimation.setDuration(this.mCurrentTimerValue);
this.mProgressBarAnimation.setInterpolator( new LinearInterpolator());

where this.mCurrentTimerValue is the time in ml. For this example is 10000

And here is the result,

I want to show the progress smoothly but I can't. I tried with ObjectAnimator.ofFloat because the problem maybe is that I'm trying to progress in integer spaces but in that case animation doesn't work.

Here is how I customized the progress bar,

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/progress">
    <rotate
        android:fromDegrees="270"
        android:toDegrees="270"
        android:pivotX="50%"
        android:pivotY="50%" >
        <shape
            android:innerRadiusRatio="2.5"
            android:shape="ring"
            android:thicknessRatio="25.0" >
            <gradient
                android:centerColor="@color/yellow"
                android:endColor="@color/yellow"
                android:startColor="@color/yellow"
                android:type="sweep" />
        </shape>
    </rotate>
</item>
<item android:id="@android:id/secondaryProgress">
    <rotate
        android:fromDegrees="270"
        android:toDegrees="270"
        android:pivotX="50%"
        android:pivotY="50%" >
        <shape
            android:innerRadiusRatio="2.5"
            android:shape="ring"
            android:thicknessRatio="25.0" >
            <gradient
                android:centerColor="@color/green"
                android:endColor="@color/green"
                android:startColor="@color/green"
                android:type="sweep" />
        </shape>
    </rotate>
</item>

<ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:indeterminate="false"
        android:progress="100"
        android:progressDrawable="@drawable/custom_progress_bar" />

I read these questions but didn't help me,

question 1

question 2

question 3


问:
Group together two columns with ID, do the cumulative for two columns
Edit: I wrote the question way to unstructured, let me try again.

I want to create two new columns, winner_total_points and loser_total_points to the dataset below.

```<code>winner <- c(1,2,3,4,1,2)
loser <- c(2,3,1,3,3,1)
winner_points <- c(5,4,12,2,1,6)
loser_points <- c(5,2,2,6,6,2)
test_data <- data.frame(winner, loser, winner_points, loser_points)
</code>```

What I want those two columns to do is that winner_total_points to sum all the points the winner has gotten (excluding this match) as both the winner and the loser.

The same function for loser_total_points but for the loser.

Note that the winner and loser columns contain the respective player ids.

Now, it's fairly easy using the ave() function but that only works for grouping only column and doing the cumulative sum for one column.

Desired output:

```<code>winner loser winner_points loser_points winner_total loser_total
1      2     5             5            5            5
2      3     4             2            9 (5+4)      2
3      1     12            2            14 (2+12)    7 (5+2)
4      3     2             6            2            20 (2+12+6)
1      3     1             6            8 (5+2+1)    26 (2+12+6+6)
2      1     6             2            15 (5+4+6)   10 (5+2+1+2)
</code>```

答:
If I have correctly understood OP's requirements, he wants to compute a cumulative sum of the points by player id irrespective if winner_points or loser_points. The important point here is to note that the winner and loser columns contain the respective player ids.

The solution below reshapes the data from wide to long format whereby two value variables are reshaped simultaneously, computes the cumulative sums for each player id, and finally reshapes from long back to wide format, again.

```<code>library(data.table
cols <- c("winner", "loser")
setDT(test_data)[
  # append row id column required for subsequent reshaping
  , rn := .I][
    # reshape multiple value variables simultaneously from wide to long format
    , melt(.SD, id.vars = "rn",
           measure.vars = list(cols, paste0(cols, "_points")),
           value.name = c("id", "points"))][
             # rename variable column
             , variable := forcats::lvls_revalue(variable, cols)][
               # order by row id and compute cumulative points by id
               order(rn), total := cumsum(points), by = id][
                 # reshape multiple value variables simultaneously from long to wide format
                 , dcast(.SD, rn ~ variable, value.var = c("id", "points", "total"))]
</code>```

```<code>   rn id_winner id_loser points_winner points_loser total_winner total_loser
1:  1         1        2             5            5            5           5
2:  2         2        3             4            2            9           2
3:  3         3        1            12            2           14           7
4:  4         4        3             2            6            2          20
5:  5         1        3             1            6            8          26
6:  6         2        1             6            2           15          10
</code>```

Edit: Above result is in line with the expected result posted by the OP.
 It includes the scored points including the actual match. Meanwhile, the OP has posted a similar question where the expected result excludes the actual match.

Body:
Edit: I wrote the question way to unstructured, let me try again.

I want to create two new columns, winner_total_points and loser_total_points to the dataset below.

winner <- c(1,2,3,4,1,2)
loser <- c(2,3,1,3,3,1)
winner_points <- c(5,4,12,2,1,6)
loser_points <- c(5,2,2,6,6,2)
test_data <- data.frame(winner, loser, winner_points, loser_points)

What I want those two columns to do is that winner_total_points to sum all the points the winner has gotten (excluding this match) as both the winner and the loser.

The same function for loser_total_points but for the loser.

Note that the winner and loser columns contain the respective player ids.

Now, it's fairly easy using the ave() function but that only works for grouping only column and doing the cumulative sum for one column.

Desired output:

winner loser winner_points loser_points winner_total loser_total
1      2     5             5            5            5
2      3     4             2            9 (5+4)      2
3      1     12            2            14 (2+12)    7 (5+2)
4      3     2             6            2            20 (2+12+6)
1      3     1             6            8 (5+2+1)    26 (2+12+6+6)
2      1     6             2            15 (5+4+6)   10 (5+2+1+2)

Body:
If I have correctly understood OP's requirements, he wants to compute a cumulative sum of the points by player id irrespective if winner_points or loser_points. The important point here is to note that the winner and loser columns contain the respective player ids.

The solution below reshapes the data from wide to long format whereby two value variables are reshaped simultaneously, computes the cumulative sums for each player id, and finally reshapes from long back to wide format, again.

library(data.table
cols <- c("winner", "loser")
setDT(test_data)[
  # append row id column required for subsequent reshaping
  , rn := .I][
    # reshape multiple value variables simultaneously from wide to long format
    , melt(.SD, id.vars = "rn",
           measure.vars = list(cols, paste0(cols, "_points")),
           value.name = c("id", "points"))][
             # rename variable column
             , variable := forcats::lvls_revalue(variable, cols)][
               # order by row id and compute cumulative points by id
               order(rn), total := cumsum(points), by = id][
                 # reshape multiple value variables simultaneously from long to wide format
                 , dcast(.SD, rn ~ variable, value.var = c("id", "points", "total"))]

   rn id_winner id_loser points_winner points_loser total_winner total_loser
1:  1         1        2             5            5            5           5
2:  2         2        3             4            2            9           2
3:  3         3        1            12            2           14           7
4:  4         4        3             2            6            2          20
5:  5         1        3             1            6            8          26
6:  6         2        1             6            2           15          10

Edit: Above result is in line with the expected result posted by the OP.
 It includes the scored points including the actual match. Meanwhile, the OP has posted a similar question where the expected result excludes the actual match.


问:
maxIndex of an MVector
Data.Vector includes a function maxIndex with type maxIndex :: (Ord a) => Vector a -> Int that returns the index of the maximum value in that Vector. I'm working with mutable Vectors, however, and MVector doesn't have maxIndex defined for it.

What's the best way of getting the data I want out of the MVector I have? My code currently is:

```<code>import qualified Data.Vector.Unboxed.Mutable as MV
import           Control.Monad.ST
import           Control.Monad               (mapM_)

type MaxIndex = Int

step :: forall s. MV.MVector s Int -> MaxIndex -> ST s ()
step vec i = do
    n <- MV.unsafeRead vec i
    MV.write vec i 0
    let l      = MV.length vec
        (k, x) = n `divMod` l
    mapM_ (\j -> MV.modify vec (+k) j) [0..l-1]  -- side note, this is just
                                                 -- fmap (+k) vec, but MVector is not
                                                 -- a functor. Is there a better way?
    mapM_ (\j -> MV.modify vec (+1) (j `mod` l)) [i+1..i+x]
</code>```

where i is the index I'm looking to derive inside step. I'm doing this because the actions here need to eventually be wrapped inside an until and repeated until a predicate is satisfied, and freezing and thawing every cycle sounds ludicrously expensive.

答:
Have you considered freezing the vector with unsafeFreeze which is supposed to be fast (i.e. Θ(1))? For example you can define maxIndex for mutable vectors like this:

```<code>maxIndex = fmap V.maxIndex . V.unsafeFreeze
</code>```

This assumes that you have imported the following:

```<code>import qualified Data.Vector.Unboxed         as V
</code>```

unsafeFreeze doesn't actually copy any data and should be fast, but it would be interesting to run a criterion benchmark to see if this approach is actually faster compared to an explicit loop.

Title: maxIndex of an MVector

Body:
Data.Vector includes a function maxIndex with type maxIndex :: (Ord a) => Vector a -> Int that returns the index of the maximum value in that Vector. I'm working with mutable Vectors, however, and MVector doesn't have maxIndex defined for it.

What's the best way of getting the data I want out of the MVector I have? My code currently is:

import qualified Data.Vector.Unboxed.Mutable as MV
import           Control.Monad.ST
import           Control.Monad               (mapM_)

type MaxIndex = Int

step :: forall s. MV.MVector s Int -> MaxIndex -> ST s ()
step vec i = do
    n <- MV.unsafeRead vec i
    MV.write vec i 0
    let l      = MV.length vec
        (k, x) = n `divMod` l
    mapM_ (\j -> MV.modify vec (+k) j) [0..l-1]  -- side note, this is just
                                                 -- fmap (+k) vec, but MVector is not
                                                 -- a functor. Is there a better way?
    mapM_ (\j -> MV.modify vec (+1) (j `mod` l)) [i+1..i+x]

where i is the index I'm looking to derive inside step. I'm doing this because the actions here need to eventually be wrapped inside an until and repeated until a predicate is satisfied, and freezing and thawing every cycle sounds ludicrously expensive.

Body:
Have you considered freezing the vector with unsafeFreeze which is supposed to be fast (i.e. Θ(1))? For example you can define maxIndex for mutable vectors like this:

maxIndex = fmap V.maxIndex . V.unsafeFreeze

This assumes that you have imported the following:

import qualified Data.Vector.Unboxed         as V

unsafeFreeze doesn't actually copy any data and should be fast, but it would be interesting to run a criterion benchmark to see if this approach is actually faster compared to an explicit loop.


问:
How to display audio information of audio stream on chromecast while playing?
I'm streaming audio livestreams and audio on-demand m3u8 files from my iOS sender app to the chromecast. When doing so, the receivers screen is black and not showing any information about the current streamed audio. Only when the stream is paused, the information is shown. Is there any way to show the audio information while playing the audio? If mp3 files are streamed to the chromecast, the audio information is shown in playing and paused state.

I'm using the Cast 4.0.1 SDK, this is my media setup:

```<code>    // setup metadata with playback information

    let metadata = GCKMediaMetadata(metadataType: GCKMediaMetadataType.musicTrack)

    metadata.setString(playback.title, forKey: kGCKMetadataKeyTitle)
    metadata.setString(playback.subtitle, forKey: kGCKMetadataKeyArtist)
    metadata.addImage(GCKImage(url: playback.imageSmall, width: 1024, height: 1024))

    let streamType: GCKMediaStreamType = .buffered
    let contentType: String            = "application/vnd.apple.mpegurl"
    let duration: Double               = playback.duration

    let mediaInfo = GCKMediaInformation(contentID: streamURL.absoluteString, streamType: streamType, contentType: contentType, metadata: metadata, streamDuration: duration, mediaTracks: nil, textTrackStyle: nil, customData: nil)

    // seek to start position

    let mediaLoadOptions = GCKMediaLoadOptions()
    mediaLoadOptions.playPosition = playPosition

    // load media and start playback

    let request = session.remoteMediaClient?.loadMedia(mediaInfo, with: mediaLoadOptions)
    request?.delegate = self
</code>```

答: You should use the Chrome Remote Debugger to determine if there are any errors or debug information that will explain the issue you are seeing.</p>

Body:
I'm streaming audio livestreams and audio on-demand m3u8 files from my iOS sender app to the chromecast. When doing so, the receivers screen is black and not showing any information about the current streamed audio. Only when the stream is paused, the information is shown. Is there any way to show the audio information while playing the audio? If mp3 files are streamed to the chromecast, the audio information is shown in playing and paused state.

I'm using the Cast 4.0.1 SDK, this is my media setup:

    // setup metadata with playback information

    let metadata = GCKMediaMetadata(metadataType: GCKMediaMetadataType.musicTrack)

    metadata.setString(playback.title, forKey: kGCKMetadataKeyTitle)
    metadata.setString(playback.subtitle, forKey: kGCKMetadataKeyArtist)
    metadata.addImage(GCKImage(url: playback.imageSmall, width: 1024, height: 1024))

    let streamType: GCKMediaStreamType = .buffered
    let contentType: String            = "application/vnd.apple.mpegurl"
    let duration: Double               = playback.duration

    let mediaInfo = GCKMediaInformation(contentID: streamURL.absoluteString, streamType: streamType, contentType: contentType, metadata: metadata, streamDuration: duration, mediaTracks: nil, textTrackStyle: nil, customData: nil)

    // seek to start position

    let mediaLoadOptions = GCKMediaLoadOptions()
    mediaLoadOptions.playPosition = playPosition

    // load media and start playback

    let request = session.remoteMediaClient?.loadMedia(mediaInfo, with: mediaLoadOptions)
    request?.delegate = self


问:
Events declared in a class
I sometimes see events declared near the top of the class (i.e. below the imports but above the constructor):

```<code>/**
* Description here
*
**/

[Event(name="complete", type="flash.events.Event")]
</code>```

What exactly is this? Is this an "import" of a certain type of event?

答:
It's an as3 metadata tag. See more there: http://livedocs.adobe.com/flex/3/html/help.html?content=metadata_3.html

This particular tag is used to define valid event attributes in a MXML tag representing that class. The IDE will also use those to let you autocomplete.

ContentLicense: CC BY-SA 2.5

Title: Events declared in a class

Body:
I sometimes see events declared near the top of the class (i.e. below the imports but above the constructor):

/**
* Description here
*
**/

[Event(name="complete", type="flash.events.Event")]

What exactly is this? Is this an "import" of a certain type of event?


问:
How to validate a large value set within HAPI-FHIR framework
I have a custom implementation of org.hl7.fhir.dstu3.hapi.validation.IValidationSupport module for validating all my profiles and value sets/code systems. I am trying to figure out a way to use the same validation API to support validation of very large value set.

Currently the default implementation of validating a value set/code system within HAPI-FHIR relies on expanding the whole value set and matching the submitted code against any of the concepts within the expanded value set. Is there a way to do the validation without the need of fully expanding the value set?

答:
Does your ValueSet include a large subset of a code system? There isn't currently a way in HAPI FHIR's validation framework to implement a method asking "does this ValueSet include a specific code".. Although I'd agree that would be useful.

Please feel free to file a bug or a pull request.


问:
gsutil command to delete old files from last day
I have a bucket in google cloud storage. I have a tmp folder in bucket. Thousands of files are being created each day in this directory. I want to delete files that are older than 1 day every night. I could not find an argument on gsutil for this job. I had to use a classic and simple shell script to do this. But the files are deleting very slowly.

I have 650K files accumulated in the folder. 540K of them must be deleted. But my own shell script worked for 1 day and only 34K files could be deleted.

The gsutil lifecycle feature is not able to do exactly what I want. He's cleaning the whole bucket. I just want to delete the files regularly at the bottom of certain folder.. At the same time I want to do deletion faster.

I'm open to your suggestions and your help. Can I do this with a single gsutil command? or a different method?

simple script I created for testing (I prepared to delete bulk files temporarily.)

```<code>    ## step 1 - I pull the files together with the date format and save them to the file list1.txt.
gsutil -m ls -la gs://mygooglecloudstorage/tmp/ | awk '{print $2,$3}' > /tmp/gsutil-tmp-files/list1.txt

## step 2 - I filter the information saved in the file list1.txt. Based on the current date, I save the old dated files to file list2.txt.
cat /tmp/gsutil-tmp-files/list1.txt | awk -F "T" '{print $1,$2,$3}' | awk '{print $1,$3}' | awk -F "#" '{print $1}' |grep -v `date +%F` |sort -bnr > /tmp/gsutil-tmp-files/list2.txt

## step 3 - After the above process, I add the gsutil delete command to the first line and convert it into a shell script.
cat /tmp/gsutil-tmp-files/list2.txt | awk '{$1 = "/root/google-cloud-sdk/bin/gsutil -m rm -r "; print}' > /tmp/gsutil-tmp-files/remove-old-files.sh

## step 4 - I'm set the script permissions and delete old lists.
chmod 755 /tmp/gsutil-tmp-files/remove-old-files.sh
rm -rf /tmp/gsutil-tmp-files/list1.txt /tmp/gsutil-tmp-files/list2.txt

## step 5 - I run the shell script and I destroy it after it is done.
/bin/sh /tmp/gsutil-tmp-files/remove-old-files.sh
rm -rf /tmp/gsutil-tmp-files/remove-old-files.sh
</code>```

答:
There isn't a simple way to do this with gsutil or object lifecycle management as of today.

That being said, would it be feasible for you to change the naming format for the objects in your bucket? That is, instead of uploading them all under "gs://mybucket/tmp/", you could append the current date to that prefix, resulting in something like "gs://mybucket/tmp/2017-12-27/".  The main advantages to this would be:

Not having to do a date comparison for every object; you could run gsutil ls "gs://mybucket/tmp/" | grep "gs://[^/]\+/tmp/[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}/$" to find those prefixes, then do date comparisons on the last portion of of those paths.

Being able to supply a smaller number of arguments on the command line (prefixes, rather than the name of each individual file) to gsutil -m rm -r, thus being less likely to pass in more arguments than your shell can handle.

Body:
I have a bucket in google cloud storage. I have a tmp folder in bucket. Thousands of files are being created each day in this directory. I want to delete files that are older than 1 day every night. I could not find an argument on gsutil for this job. I had to use a classic and simple shell script to do this. But the files are deleting very slowly.

I have 650K files accumulated in the folder. 540K of them must be deleted. But my own shell script worked for 1 day and only 34K files could be deleted.

The gsutil lifecycle feature is not able to do exactly what I want. He's cleaning the whole bucket. I just want to delete the files regularly at the bottom of certain folder.. At the same time I want to do deletion faster.

I'm open to your suggestions and your help. Can I do this with a single gsutil command? or a different method?

simple script I created for testing (I prepared to delete bulk files temporarily.)

    ## step 1 - I pull the files together with the date format and save them to the file list1.txt.
gsutil -m ls -la gs://mygooglecloudstorage/tmp/ | awk '{print $2,$3}' > /tmp/gsutil-tmp-files/list1.txt

## step 2 - I filter the information saved in the file list1.txt. Based on the current date, I save the old dated files to file list2.txt.
cat /tmp/gsutil-tmp-files/list1.txt | awk -F "T" '{print $1,$2,$3}' | awk '{print $1,$3}' | awk -F "#" '{print $1}' |grep -v `date +%F` |sort -bnr > /tmp/gsutil-tmp-files/list2.txt

## step 3 - After the above process, I add the gsutil delete command to the first line and convert it into a shell script.
cat /tmp/gsutil-tmp-files/list2.txt | awk '{$1 = "/root/google-cloud-sdk/bin/gsutil -m rm -r "; print}' > /tmp/gsutil-tmp-files/remove-old-files.sh

## step 4 - I'm set the script permissions and delete old lists.
chmod 755 /tmp/gsutil-tmp-files/remove-old-files.sh
rm -rf /tmp/gsutil-tmp-files/list1.txt /tmp/gsutil-tmp-files/list2.txt

## step 5 - I run the shell script and I destroy it after it is done.
/bin/sh /tmp/gsutil-tmp-files/remove-old-files.sh
rm -rf /tmp/gsutil-tmp-files/remove-old-files.sh


问:
GenyMotion Unable to start the Genymotion virtual device
When I run Genymotion, I get the following error:

Unable to start the Genymotion virtual device.

Unable to configure the network adapter for the virtual device.

Please, check the following points:

From VirtualBox, in the main parameters of software, check a network adapter "Host-only" is present.
From VirtualBox, in the Genymotion virtual device parameters, check the first network interface has the type "Host-only". If no, then set this parameter manually.

How can I fix that?

答: it worked for me when I start Gennymotion in Admin mode


问:
Match any url in Mongoose with or without http(s) or www
What I'm trying to achieve is to find a way to verify if a URL already exists in a MongoDB document, without saving the URL twice, one with HTTP(s)(www) protocol, and other clean of HTTP(s)(www) to perform the match.
For example, if the MongoDB document contains a record:

```<code>'url': "http://mysite.co?search=pattern&co=43"
</code>```

So, I want to perform a search:

```<code>MyCollection.find({'url': "mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "http://mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "https://mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "http://www.mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "https://www.mysite.co?search=pattern&co=43"})...
</code>```

The search should match with the URL actually saved in the document.

I'm trying to use the following regex:

```<code>MyCollection.find({'url': new RegExp('^https?:\/\/(www.)?(' + 'mysite.co?search=pattern&co=43' + ')+$', 'gim')})...
</code>```

However, I'm not very clever creating regex expressions, and I still struggle with it. Seems that the question mark in the URL breaks the regex, and I'm not pretty sure if just using a replace from '?' to '\?' is the right way to go.

The search must match 'exactly' the URL in the DB, except for the HTTP(s)(www) protocol. I mean, if the URL in the document contains other params:

```<code>'url': "http://mysite.co?search=pattern&co=43&other=more_params"
</code>```

The search should not be matched this time.

I'm using Mongoose and nodejs.

Thanks in advance.

UPDATE:

Based on your answers, I have improved a little bit the regex and scaping for the URL:

First, a function to trim and 'clean' the URL of HTTP(s) or (www):

```<code>String.prototype.url_clean = function() {
    return this.trim().replace(/^(http(s|):\/\/)?(www\.|)/g, '');
};
</code>```

And a function to escape the URL:

```<code>RegExp.escape = function(s) {
    return s.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
};
</code>```

So I can perform the search:

```<code>MyCollection.find({'url': new RegExp('^(http(s|):\/\/)?(www\.|)(' + RegExp.escape(url.url_clean()) + ')(|\s)+$', "gim")})
</code>```

答:
the problem is you must escape specific elements of a url from the regex (such as '?') /^http(s|):\/\/(www\.|)mysite\.co\?search=pattern&co=43/

Instead i would write a script that pulled all the records, split them into individual fields, save the new document. Query on those new fields instead of using regex

Body:
What I'm trying to achieve is to find a way to verify if a URL already exists in a MongoDB document, without saving the URL twice, one with HTTP(s)(www) protocol, and other clean of HTTP(s)(www) to perform the match.
For example, if the MongoDB document contains a record:

'url': "http://mysite.co?search=pattern&co=43"

So, I want to perform a search:

MyCollection.find({'url': "mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "http://mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "https://mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "http://www.mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "https://www.mysite.co?search=pattern&co=43"})...

The search should match with the URL actually saved in the document.

I'm trying to use the following regex:

MyCollection.find({'url': new RegExp('^https?:\/\/(www.)?(' + 'mysite.co?search=pattern&co=43' + ')+$', 'gim')})...

However, I'm not very clever creating regex expressions, and I still struggle with it. Seems that the question mark in the URL breaks the regex, and I'm not pretty sure if just using a replace from '?' to '\?' is the right way to go.

The search must match 'exactly' the URL in the DB, except for the HTTP(s)(www) protocol. I mean, if the URL in the document contains other params:

'url': "http://mysite.co?search=pattern&co=43&other=more_params"

The search should not be matched this time.

I'm using Mongoose and nodejs.

Thanks in advance.

UPDATE:

Based on your answers, I have improved a little bit the regex and scaping for the URL:

First, a function to trim and 'clean' the URL of HTTP(s) or (www):

String.prototype.url_clean = function() {
    return this.trim().replace(/^(http(s|):\/\/)?(www\.|)/g, '');
};

And a function to escape the URL:

RegExp.escape = function(s) {
    return s.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
};

So I can perform the search:

MyCollection.find({'url': new RegExp('^(http(s|):\/\/)?(www\.|)(' + RegExp.escape(url.url_clean()) + ')(|\s)+$', "gim")})


问:
Calculate the date difference in the given format in PHP4
I need a function in php4 that will calculate the date difference in the provided date format.
eg.

```<code>$date1 = "2011-08-24 10:03:00";
$date2 = "2012-09-24 10:04:31";
$format1 = "Y W" ; //This format should return the difference in Year and week.
$format2 = "M D"; // This format should return the difference in Months and days.
// The format can be any combination of Year,Month,Day,Week,Hour,Minute,Second.

function ConvertDate($data1,$date2,$format)
</code>```

Please let me know if you need any more details on this.
Thanks in advance.

答:
Let's try something like this.

```<code>function ConvertDate($date1, $date2, $format)
{
    static $formatDefinitions = array(
        'Y' => 31536000,
        'M' => 2592000,
        'W' => 604800,
        'D' => 86400,
        'H' => 3600,
        'i' => 60,
        's' => 1
    );

    $ts1 = strtotime($date1);
    $ts2 = strtotime($date2);
    $delta = abs($ts1 - $ts2);

    $seconds = array();
    foreach ($formatDefinitions as $definition => $divider) {
        if (false !== strpos($format, $definition)) {
            $seconds[$definition] = floor($delta / $divider);
            $delta = $delta % $divider;
        }
    }

    return strtr($format, $seconds);
}
</code>```

Just keep in mind that months and years are just estimated because you cannot say "how many seconds are a month" (because a "month" can be anything between 28 and 31 days). My function counts a month as 30 days.

Body:
I need a function in php4 that will calculate the date difference in the provided date format.
eg.

$date1 = "2011-08-24 10:03:00";
$date2 = "2012-09-24 10:04:31";
$format1 = "Y W" ; //This format should return the difference in Year and week.
$format2 = "M D"; // This format should return the difference in Months and days.
// The format can be any combination of Year,Month,Day,Week,Hour,Minute,Second.

function ConvertDate($data1,$date2,$format)

Please let me know if you need any more details on this.
Thanks in advance.

Body:
Let's try something like this.

function ConvertDate($date1, $date2, $format)
{
    static $formatDefinitions = array(
        'Y' => 31536000,
        'M' => 2592000,
        'W' => 604800,
        'D' => 86400,
        'H' => 3600,
        'i' => 60,
        's' => 1
    );

    $ts1 = strtotime($date1);
    $ts2 = strtotime($date2);
    $delta = abs($ts1 - $ts2);

    $seconds = array();
    foreach ($formatDefinitions as $definition => $divider) {
        if (false !== strpos($format, $definition)) {
            $seconds[$definition] = floor($delta / $divider);
            $delta = $delta % $divider;
        }
    }

    return strtr($format, $seconds);
}

Just keep in mind that months and years are just estimated because you cannot say "how many seconds are a month" (because a "month" can be anything between 28 and 31 days). My function counts a month as 30 days.


问:
Overriding the .Add method in a List of... with validation
I have a Use Case where I want to validate a specific property in a list of objects to make sure it is unique. The basic setting can be seen in the code below.

```<code>class Program
{
    static void Main(string[] args)
    {
        Directory myDirectory = new Directory("Interaction Design");
        myDirectory.Books.Add(new Book("978-0-262-64037-4", "The Design of Everyday Things")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Designing Interactions")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Whoops, I slipped up")); //Should NOT be added
    }
}

public class Directory
{
    public Directory(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
    public List<Book> Books { get; set; } = new List<Book>();
}

public class Book
{
    public Book(string isbn, string title)
    {
        Isbn = isbn;
        Title = title;
    }
    public string Title { get; set; }
    public string Isbn { get; set; }
}
</code>```

Now, in the code above, adding a new Book in the List of Books should throw an exception if the ISBN number isn't unique.

I would like to extend on the .Add() method of the List and add that validation, but I'm not sure how to actually do that.

I've seen similar things, but they all assume that the Directory inherits from List and you write an overriding .Add method to the Directory - which doesn't look like a valid solution in this case.

Perhaps my general approach is backwards?

Please advice.

答:
If you want uniqueness, use a collection that gives you that: a set.

Make an IEqualityComparer<book> that considers two books to be equal if the Isbns match and use it in a HashSet<Book> that represents your unique list of books:

```<code>public class Directory
{

    public HashSet<Book> Books { get; }
        = new HashSet<Book>(new BookEqualityComparer());
    //...
    private class BookEqualityComparer : IEqualityComparer<Book>
    {
        public bool Equals(Book x, Book y)
        {
            if (ReferenceEquals(x, y))
                return true;

            if (ReferenceEquals(x, null) ||
                ReferenceEquals(y, null))
                return false;

            return x.Isbn == y.Isbn;
        }

        public int GetHashCode(Book obj)
            => obj.Isbn.GetHashCode();
    }
}
</code>```

And you are done, you can't have any duplicate books in Books.

ContentLicense: CC BY-SA 4.0

Body:
I have a Use Case where I want to validate a specific property in a list of objects to make sure it is unique. The basic setting can be seen in the code below.

class Program
{
    static void Main(string[] args)
    {
        Directory myDirectory = new Directory("Interaction Design");
        myDirectory.Books.Add(new Book("978-0-262-64037-4", "The Design of Everyday Things")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Designing Interactions")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Whoops, I slipped up")); //Should NOT be added
    }
}

public class Directory
{
    public Directory(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
    public List<Book> Books { get; set; } = new List<Book>();
}

public class Book
{
    public Book(string isbn, string title)
    {
        Isbn = isbn;
        Title = title;
    }
    public string Title { get; set; }
    public string Isbn { get; set; }
}

Now, in the code above, adding a new Book in the List of Books should throw an exception if the ISBN number isn't unique.

I would like to extend on the .Add() method of the List and add that validation, but I'm not sure how to actually do that.

I've seen similar things, but they all assume that the Directory inherits from List and you write an overriding .Add method to the Directory - which doesn't look like a valid solution in this case.

Perhaps my general approach is backwards?

Please advice.

Body:
If you want uniqueness, use a collection that gives you that: a set.

Make an IEqualityComparer<book> that considers two books to be equal if the Isbns match and use it in a HashSet<Book> that represents your unique list of books:

public class Directory
{

    public HashSet<Book> Books { get; }
        = new HashSet<Book>(new BookEqualityComparer());
    //...
    private class BookEqualityComparer : IEqualityComparer<Book>
    {
        public bool Equals(Book x, Book y)
        {
            if (ReferenceEquals(x, y))
                return true;

            if (ReferenceEquals(x, null) ||
                ReferenceEquals(y, null))
                return false;

            return x.Isbn == y.Isbn;
        }

        public int GetHashCode(Book obj)
            => obj.Isbn.GetHashCode();
    }
}

And you are done, you can't have any duplicate books in Books.


问:
Return Type of an Immediate await vs Postponed await
I am seeking clarification as to why an immediate await returns the type of the asynchronous, non-void task whereas postponing the await returns the task itself. If my terminology in the title or elsewhere is incorrect, please let me know.

```<code>private async Task<string> GetUserId(Guid id)
{
   string thisUserId = null;
   ... do stuff ...
   return thisUserId;
}

public async Task<IActionResult> MyFunc(Guid id)
{
   var a = await GetUserId(id);
   var b = GetUserId(id);
   ... do stuff ...
   await b;

   return Ok(true);
}
</code>```

Why is a of type string while b is of type Task<string>?

答:
In both cases, your method is always returning an object of type Task<string>. However, when you perform the await, the result of that is the result of the Task, which is your string.

So, if you do that when you originally call the method, you're processing the Task immediately. However with your second call, you don't process the Task until after you "do stuff". In that case, your variable is still the Task that will return the string. Once you finally call await on it, then you get the result of that task.

Body:
I am seeking clarification as to why an immediate await returns the type of the asynchronous, non-void task whereas postponing the await returns the task itself. If my terminology in the title or elsewhere is incorrect, please let me know.

private async Task<string> GetUserId(Guid id)
{
   string thisUserId = null;
   ... do stuff ...
   return thisUserId;
}

public async Task<IActionResult> MyFunc(Guid id)
{
   var a = await GetUserId(id);
   var b = GetUserId(id);
   ... do stuff ...
   await b;

   return Ok(true);
}

Why is a of type string while b is of type Task<string>?