问:
Background Image on ScrollingActivity header Android
So im building an app for a school project (im learning Android).
And i was wondering if you can add an image to the background of a Scrolling Activity Header. the app_bar (th ebig blue header in the image below).

I have no clue how to do it and i've been looking all over and can't find anything

My code is the following:

Activity_layout :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.juanfri.seguridadmainactivity.ActivityPeliculaJson">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:toolbarId="@+id/toolbar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_activity_pelicula_json" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>```
</div>
</div>
</p>

<p>and my Activity_Content_Layout:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.juanfri.seguridadmainactivity.ActivityPeliculaJson"
    tools:showIn="@layout/activity_pelicula_json">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="10dp"
        android:paddingRight="10dp">

        <TextView
            android:id="@+id/NombrePelicula"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="20dp"
            android:paddingTop="20dp"
            android:text="Pirates of the Carabien: Dead Men teel no tales"
            android:textSize="18sp" />

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

            <ImageView
                android:id="@+id/FotoPortada"
                android:layout_width="130dp"
                android:layout_height="200dp"
                android:layout_weight="1"
                app:srcCompat="@drawable/common_ic_googleplayservices" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical">

                <RatingBar
                    android:id="@+id/Puntuacion"
                    style="@style/Widget.AppCompat.RatingBar.Small"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:isIndicator="false"
                    android:numStars="5"
                    android:stepSize="0.25" />

            </LinearLayout>

        </LinearLayout>

        <TextView
            android:id="@+id/Sinopsis"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingBottom="10dp"
            android:paddingTop="10dp"
            android:text="TextView" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:paddingBottom="10dp"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/IdiomaOriginal"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Idioma Original:" />

            <TextView
                android:id="@+id/IdiomaOriginalValor"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

            <TextView
                android:id="@+id/Duracion"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Duración:" />

            <TextView
                android:id="@+id/DuracionVal"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:paddingBottom="10dp"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/Presupuesto"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Presupuesto:" />

            <TextView
                android:id="@+id/PresupuestoValor"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

            <TextView
                android:id="@+id/Ingreso"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Ingresos" />

            <TextView
                android:id="@+id/IngresoVal"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:paddingBottom="10dp"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/FechaLanz"
                android:layout_width="225dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Fecha Lanzamiento:" />

            <TextView
                android:id="@+id/FechaLanzVal"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

        </LinearLayout>

    </LinearLayout>
</android.support.v4.widget.NestedScrollView></code>```

答:
Do this.. and add image to the image view</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.juanfri.seguridadmainactivity.ActivityPeliculaJson">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:toolbarId="@+id/toolbar">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_activity_pelicula_json" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
</code>```

Body:
So im building an app for a school project (im learning Android).
And i was wondering if you can add an image to the background of a Scrolling Activity Header. the app_bar (th ebig blue header in the image below).

I have no clue how to do it and i've been looking all over and can't find anything

My code is the following:

Activity_layout :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.juanfri.seguridadmainactivity.ActivityPeliculaJson">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:toolbarId="@+id/toolbar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_activity_pelicula_json" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

and my Activity_Content_Layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.juanfri.seguridadmainactivity.ActivityPeliculaJson"
    tools:showIn="@layout/activity_pelicula_json">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="10dp"
        android:paddingRight="10dp">

        <TextView
            android:id="@+id/NombrePelicula"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="20dp"
            android:paddingTop="20dp"
            android:text="Pirates of the Carabien: Dead Men teel no tales"
            android:textSize="18sp" />

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

            <ImageView
                android:id="@+id/FotoPortada"
                android:layout_width="130dp"
                android:layout_height="200dp"
                android:layout_weight="1"
                app:srcCompat="@drawable/common_ic_googleplayservices" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical">

                <RatingBar
                    android:id="@+id/Puntuacion"
                    style="@style/Widget.AppCompat.RatingBar.Small"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:isIndicator="false"
                    android:numStars="5"
                    android:stepSize="0.25" />

            </LinearLayout>

        </LinearLayout>

        <TextView
            android:id="@+id/Sinopsis"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingBottom="10dp"
            android:paddingTop="10dp"
            android:text="TextView" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:paddingBottom="10dp"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/IdiomaOriginal"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Idioma Original:" />

            <TextView
                android:id="@+id/IdiomaOriginalValor"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

            <TextView
                android:id="@+id/Duracion"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Duración:" />

            <TextView
                android:id="@+id/DuracionVal"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:paddingBottom="10dp"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/Presupuesto"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Presupuesto:" />

            <TextView
                android:id="@+id/PresupuestoValor"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

            <TextView
                android:id="@+id/Ingreso"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Ingresos" />

            <TextView
                android:id="@+id/IngresoVal"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:paddingBottom="10dp"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/FechaLanz"
                android:layout_width="225dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Fecha Lanzamiento:" />

            <TextView
                android:id="@+id/FechaLanzVal"
                android:layout_width="75dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

        </LinearLayout>

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

Body:
Do this.. and add image to the image view

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.juanfri.seguridadmainactivity.ActivityPeliculaJson">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:toolbarId="@+id/toolbar">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_activity_pelicula_json" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>


来源: stackexchange

问:
How to run my ruby code after Rails server start?
I tried:

```<code>after_initialize do
  #code
end
</code>```

But: (documentation)

Some parts of your application, notably observers and routing, are not
  yet set up at the point where the after_initialize block is called.

I need routing and logger in my code

Any ideas?

答:
@house9's answer is correct, as pointed out by the comments, this will also execute when running rake tasks, console, etc.  I used the following to recognize when a server was actually being executed:</p>

```<code># application.rb
if defined?(Rails::Server)
  config.after_initialize do
    # Do stuff here
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried:

after_initialize do
  #code
end

But: (documentation)

Some parts of your application, notably observers and routing, are not
  yet set up at the point where the after_initialize block is called.

I need routing and logger in my code

Any ideas?

Body:
@house9's answer is correct, as pointed out by the comments, this will also execute when running rake tasks, console, etc.  I used the following to recognize when a server was actually being executed:

# application.rb
if defined?(Rails::Server)
  config.after_initialize do
    # Do stuff here
  end
end


问:
How do I dynamically assign properties to an object in TypeScript?
If I wanted to programatically assign a property to an object in Javascript, I would do it like this:

```<code>var obj = {};
obj.prop = "value";
</code>```

But in TypeScript, this generates an error:

The property 'prop' does not exist on value of type '{}'

How am I supposed to assign any new property to an object in TypeScript?

答:
Index signatures

It is possible to denote obj as any, but that defeats the whole purpose of using typescript. obj = {} implies obj is an Object. Marking it as any makes no sense. To accomplish the desired consistency an interface could be defined as follows, using an index signature

```<code>interface LooseObject {
    [key: string]: any
}

var obj: LooseObject = {};
</code>```

OR to make it compact:

```<code>var obj: {[k: string]: any} = {};
</code>```

LooseObject can accept fields with any string as key and any type as value.

```<code>obj.prop = "value";
obj.prop2 = 88;
</code>```

The real elegance of this solution is that you can include typesafe fields in the interface.

```<code>interface MyType {
    typesafeProp1?: number,
    requiredProp1: string,
    [key: string]: any
}

var obj: MyType ;
obj = { requiredProp1: "foo"}; // valid
obj = {} // error. 'requiredProp1' is missing
obj.typesafeProp1 = "bar" // error. typesafeProp1 should be a number

obj.prop = "value";
obj.prop2 = 88;
</code>```

Record<Keys,Type>  utility type

Update (August 2020): @transang brought up the Record<Keys,Type> utility type in comments

Record<Keys,Type> is a Utility type in typescript. It is a much cleaner  alternative for key-value pairs where property-names are not known.
It's worth noting that Record<Keys,Type> is a named alias to {[k: Keys]: Type} where Keys and Type are generics.
IMO, this makes it worth mentioning here

For comparison,

```<code>var obj: {[k: string]: any} = {};
</code>```

becomes

```<code>var obj: Record<string,any> = {}
</code>```

MyType can now be defined by extending Record type

```<code>interface MyType extends Record<string,any> {
    typesafeProp1?: number,
    requiredProp1: string,
}
</code>```

While this answers the Original question, the answer here by @GreeneCreations might give another perspective on how to approach the problem.

Body:
If I wanted to programatically assign a property to an object in Javascript, I would do it like this:

var obj = {};
obj.prop = "value";

But in TypeScript, this generates an error:

The property 'prop' does not exist on value of type '{}'

How am I supposed to assign any new property to an object in TypeScript?

Body:
Index signatures

It is possible to denote obj as any, but that defeats the whole purpose of using typescript. obj = {} implies obj is an Object. Marking it as any makes no sense. To accomplish the desired consistency an interface could be defined as follows, using an index signature

interface LooseObject {
    [key: string]: any
}

var obj: LooseObject = {};

OR to make it compact:

var obj: {[k: string]: any} = {};

LooseObject can accept fields with any string as key and any type as value.

obj.prop = "value";
obj.prop2 = 88;

The real elegance of this solution is that you can include typesafe fields in the interface.

interface MyType {
    typesafeProp1?: number,
    requiredProp1: string,
    [key: string]: any
}

var obj: MyType ;
obj = { requiredProp1: "foo"}; // valid
obj = {} // error. 'requiredProp1' is missing
obj.typesafeProp1 = "bar" // error. typesafeProp1 should be a number

obj.prop = "value";
obj.prop2 = 88;

Record<Keys,Type>  utility type

Update (August 2020): @transang brought up the Record<Keys,Type> utility type in comments

Record<Keys,Type> is a Utility type in typescript. It is a much cleaner  alternative for key-value pairs where property-names are not known.
It's worth noting that Record<Keys,Type> is a named alias to {[k: Keys]: Type} where Keys and Type are generics.
IMO, this makes it worth mentioning here

For comparison,

var obj: {[k: string]: any} = {};

becomes

var obj: Record<string,any> = {}

MyType can now be defined by extending Record type

interface MyType extends Record<string,any> {
    typesafeProp1?: number,
    requiredProp1: string,
}

While this answers the Original question, the answer here by @GreeneCreations might give another perspective on how to approach the problem.

ContentLicense: CC BY-SA 4.0


问:
Splitting Ionic card in half. I want to show students on the right and the teachers on the left
This is what I currently have: https://gyazo.com/7b0c0d53beef6846545bece011332cd5 .  You can see that I have a lot of pictures next to each other, but I want to have 2 halves in the ionic card. On the topleft the groupname , bottom left the teachers and on the right side the studens in the group. I want it like this: https://gyazo.com/d5e71aa9cfe6de9f121ce236f951a6d7 .

HTML

```<code>    <ion-header>
  <ion-navbar color ="primary">
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>{{ appName }}</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
<ion-grid>
  <ion-row>
    <ion-col *ngFor="let group of groupData">
      <ion-card >
        <ion-item>
          <h2>{{ group.name }}</h2>

              <div class="pic" *ngFor="let student of group.students">
                <img [src]="student.avatar" />
              </div>
              <h3>{{group.students.length}}  Leerlingen</h3>

              <div class="pic" *ngFor="let teacher of group.teachers">
                <img [src]="teacher.avatar" />
              </div>
              <h3>{{group.teachers.length}} leerkrachten</h3>

          </ion-item>

      </ion-card>
    </ion-col>
  </ion-row>
</ion-grid>

</ion-content>
</code>```

CSS

```<code>.pic{
  display: inline-block;
  height: 40px;
  width: 40px;
}
</code>```

答:
Instead of using ion-item, you can use div tag and set specifically half width of the content like so

```<code><ion-content>
<ion-grid>
  <ion-row>
    <ion-col *ngFor="let group of groupData">
      <ion-card >
        <div class="left-content">
          <div class="pic" *ngFor="let teacher of group.teachers">
             <img [src]="teacher.avatar" />
          </div>
          <h3>{{group.teachers.length}} leerkrachten</h3>
        </div>
        <div class="right-content">
          <h2>{{ group.name }}</h2>
          <div class="pic" *ngFor="let student of group.students">
              <img [src]="student.avatar" />
          </div>
          <h3>{{group.students.length}}  Leerlingen</h3>
        </div>
      </ion-card>
    </ion-col>
  </ion-row>
</ion-grid>
</ion-content>
</code>```

Css

```<code>.left-content {
  width: 50%;
  float: 'left'
}
.right-content {
  width: 50%,
  float: 'right'
}
</code>```

Body:
This is what I currently have: https://gyazo.com/7b0c0d53beef6846545bece011332cd5 .  You can see that I have a lot of pictures next to each other, but I want to have 2 halves in the ionic card. On the topleft the groupname , bottom left the teachers and on the right side the studens in the group. I want it like this: https://gyazo.com/d5e71aa9cfe6de9f121ce236f951a6d7 .

HTML

    <ion-header>
  <ion-navbar color ="primary">
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>{{ appName }}</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
<ion-grid>
  <ion-row>
    <ion-col *ngFor="let group of groupData">
      <ion-card >
        <ion-item>

{{ group.name }}

{{group.students.length}}  Leerlingen

{{group.teachers.length}} leerkrachten

          </ion-item>

      </ion-card>
    </ion-col>
  </ion-row>
</ion-grid>

</ion-content>

CSS

.pic{
  display: inline-block;
  height: 40px;
  width: 40px;
}

Body:
Instead of using ion-item, you can use div tag and set specifically half width of the content like so

<ion-content>
<ion-grid>
  <ion-row>
    <ion-col *ngFor="let group of groupData">
      <ion-card >
        <div class="left-content">
          <div class="pic" *ngFor="let teacher of group.teachers">
             <img [src]="teacher.avatar" />
          </div>
          <h3>{{group.teachers.length}} leerkrachten</h3>
        </div>
        <div class="right-content">
          <h2>{{ group.name }}</h2>
          <div class="pic" *ngFor="let student of group.students">
              <img [src]="student.avatar" />
          </div>
          <h3>{{group.students.length}}  Leerlingen</h3>
        </div>
      </ion-card>
    </ion-col>
  </ion-row>
</ion-grid>
</ion-content>

Css

.left-content {
  width: 50%;
  float: 'left'
}
.right-content {
  width: 50%,
  float: 'right'
}


问:
Storing multiple integers in a char array
I've been looking online for a few hours to find this, but haven't found anything yet that's exactly what I need. I have multiple integers that I need to put into a char* (separated by a space) to be later written to a .txt file. My best attempt until now has been this:

```<code>char* temp = (char)input.Z_pos_Camera_Temperature;
</code>```

Where input.Z_pos_Camera_Temperature is a member of a struct. I tried

```<code>char* temp = (char)input.Z_pos_Camera_Temperature + ' ' + input.Z_neg_Camera_Temperature;
</code>```

but that only added the values of the three chars individually. Can someone help me figure this out?

答:
This isn't really intended as an answer because you have already got that.  I'm posting to help you understand what you tried actually does. Looking at the first sample:

```<code>char* temp = (char)input.Z_pos_Camera_Temperature;
</code>```

First of all, you should have gotten a warning when you compiled this line.  Something like:

warning C4047: 'initializing': 'char *' differs in levels of indirection from 'char'

This is an indication that something bad is going on.  So what happens when this line is executed?

If input.Z_pos_Camera_Temperature has a value of 32, the 4-byte integer is truncated to 1 byte by your cast to char and assigned to the char* temp.  temp now contains the address 0x00000020.

If input.Z_pos_Camera_Temperature is 450 (maybe the camera is in an oven?) the value would be truncated to from 0x000001C2 to 0xC2, sign extended when assigned, and `temp' would now contain the address 0xffffffC2;

The second attempt is the same except that there is integer addition before the cast and assignment:

```<code>char* temp = (char)450 + 32 + -5; // NOTE: the 32 here is the ASCII value for ' '
</code>```

Body:
I've been looking online for a few hours to find this, but haven't found anything yet that's exactly what I need. I have multiple integers that I need to put into a char* (separated by a space) to be later written to a .txt file. My best attempt until now has been this:

char* temp = (char)input.Z_pos_Camera_Temperature;

Where input.Z_pos_Camera_Temperature is a member of a struct. I tried

char* temp = (char)input.Z_pos_Camera_Temperature + ' ' + input.Z_neg_Camera_Temperature;

but that only added the values of the three chars individually. Can someone help me figure this out?

Body:
This isn't really intended as an answer because you have already got that.  I'm posting to help you understand what you tried actually does. Looking at the first sample:

char* temp = (char)input.Z_pos_Camera_Temperature;

First of all, you should have gotten a warning when you compiled this line.  Something like:

warning C4047: 'initializing': 'char *' differs in levels of indirection from 'char'

This is an indication that something bad is going on.  So what happens when this line is executed?

If input.Z_pos_Camera_Temperature has a value of 32, the 4-byte integer is truncated to 1 byte by your cast to char and assigned to the char* temp.  temp now contains the address 0x00000020.

If input.Z_pos_Camera_Temperature is 450 (maybe the camera is in an oven?) the value would be truncated to from 0x000001C2 to 0xC2, sign extended when assigned, and `temp' would now contain the address 0xffffffC2;

The second attempt is the same except that there is integer addition before the cast and assignment:

char* temp = (char)450 + 32 + -5; // NOTE: the 32 here is the ASCII value for ' '


问:
Regular Expression validating with "at"
I know how to validate an email adress using regular expression, when the mail has the structure "blabla@foo.com"
The valid regular expression looks like this:

```<code>([\w\-]([\.\w])+[\w]+@([\w\-]+\.)+[A-Za-z]{2,4})
</code>```

But at my university, my professors do have websites in which their email adresses look like this: prof[at]foo.bla

What is the correct regular expression for this kind of emails? Changing @ to [at] didn't work.

Is there any tutorial for this kind of problems? Can you please recommend something?

答:
You can use optional capture here - the | character in a group works as a logical or, so:

```<code>(\w-+[\w]+(@|\[at\])([\w-]+.)+[A-Za-z]{2,4})
</code>```

Should do the trick. You can set it as non-capturing group (?:@|\[at\]) if you're not interested in it. Also, note that the square brackets are escaped - you need to escape them if you want to treat them as literal characters instead of character group indicators.

UPDATE

Since you didn't specify the language you're using in the original question, here's what I'd suggest you to use:

```<code>Pattern emailRe = Pattern.compile("(\\w[\\w.+\\-]+?(?:@|\\[at\\])[\\w\\-]+\\.[\\w\\-.]+)");
</code>```

instead as a much more solid pattern. Then you can re-use it to match email(s) in your strings as many times as you like, for example: emailRe.match(your_string)...

Title: Regular Expression validating with "at"

Body:
I know how to validate an email adress using regular expression, when the mail has the structure "blabla@foo.com"
The valid regular expression looks like this:

([\w\-]([\.\w])+[\w]+@([\w\-]+\.)+[A-Za-z]{2,4})

But at my university, my professors do have websites in which their email adresses look like this: prof[at]foo.bla

What is the correct regular expression for this kind of emails? Changing @ to [at] didn't work.

Is there any tutorial for this kind of problems? Can you please recommend something?

Body:
You can use optional capture here - the | character in a group works as a logical or, so:

(\w-+[\w]+(@|\[at\])([\w-]+.)+[A-Za-z]{2,4})

Should do the trick. You can set it as non-capturing group (?:@|\[at\]) if you're not interested in it. Also, note that the square brackets are escaped - you need to escape them if you want to treat them as literal characters instead of character group indicators.

UPDATE

Since you didn't specify the language you're using in the original question, here's what I'd suggest you to use:

Pattern emailRe = Pattern.compile("(\\w[\\w.+\\-]+?(?:@|\\[at\\])[\\w\\-]+\\.[\\w\\-.]+)");

instead as a much more solid pattern. Then you can re-use it to match email(s) in your strings as many times as you like, for example: emailRe.match(your_string)...


问:
How to pass generic class objects with a different type to one List?
Hello I need some inspiration,

I have a waypoint class like so:

```<code>public class Waypoint<T> {

}
</code>```

and I would like to add all my waypoints to one list like so:

```<code>var w1 = new Waypoint<Item>();
var w2 = new Waypoint<Player>();
var waypoints = new List<Waypoint<?>>();
</code>```

Problem is, they are not all of the same Type.
Is there a way that I can add different types to one list?

Anybody know an easy workaround?
Language: C#

Kind regards,

Venomous

答:
Not sure if this can help, but you could do something like this:

```<code>struct AbstractWayPoint {};

template<typename T>
struct WayPoint : AbstractWayPoint {};

std::list<AbstractWayPoint*> theList;
</code>```

Of course this only makes sense, if the interface of whatever you want to do with that waypoints in the list does not depend on the template parameter. However, this isnt such a huge restriction as it may seem at first glance, eg one can do something like this:

```<code>struct AbstractWayPoint {
    virtual void doSomething(double x) = 0;
};

template<typename T>
struct WayPoint : AbstractWayPoint {
    virtual void doSomething(double x) {
        T t;
        t.someMethod(x);
    }
};
</code>```

PS: when I wrote this answer, I thought the question is about C++. I know only little C#, so unless someone will point out that something like this cannot be done in C# I will just leave the answer. Anyhow OP was asking for "some inspiration" ;)

PPS: ...btw if your waypoints dont share a common interface, imho it is questionable whether it makes sense to put them into a list in the first place.

Body:
Hello I need some inspiration,

I have a waypoint class like so:

public class Waypoint<T> {

}

and I would like to add all my waypoints to one list like so:

var w1 = new Waypoint<Item>();
var w2 = new Waypoint<Player>();
var waypoints = new List<Waypoint<?>>();

Problem is, they are not all of the same Type.
Is there a way that I can add different types to one list?

Anybody know an easy workaround?
Language: C#

Kind regards,

Venomous

Body:
Not sure if this can help, but you could do something like this:

struct AbstractWayPoint {};

template<typename T>
struct WayPoint : AbstractWayPoint {};

std::list<AbstractWayPoint*> theList;

Of course this only makes sense, if the interface of whatever you want to do with that waypoints in the list does not depend on the template parameter. However, this isnt such a huge restriction as it may seem at first glance, eg one can do something like this:

struct AbstractWayPoint {
    virtual void doSomething(double x) = 0;
};

template<typename T>
struct WayPoint : AbstractWayPoint {
    virtual void doSomething(double x) {
        T t;
        t.someMethod(x);
    }
};

PS: when I wrote this answer, I thought the question is about C++. I know only little C#, so unless someone will point out that something like this cannot be done in C# I will just leave the answer. Anyhow OP was asking for "some inspiration" ;)

PPS: ...btw if your waypoints dont share a common interface, imho it is questionable whether it makes sense to put them into a list in the first place.


问:
Is there any way to use default parameters out of order without having to pass them explicitly in a Python function?
For example, I have this function:

```<code>def do_something(a=None, b=None, c=None):
    pass
</code>```

Let's say I want to pass only the last parameter to this function, so the call of this function would be like this:do_something(None, None, 15). Is there anyway to do this without passing the first two parameters explicitly?

答:
Yes, just issue</p>

```<code>do_something(c=15)
</code>```

Body:
For example, I have this function:

def do_something(a=None, b=None, c=None):
    pass

Let's say I want to pass only the last parameter to this function, so the call of this function would be like this:do_something(None, None, 15). Is there anyway to do this without passing the first two parameters explicitly?

Body:
Yes, just issue

do_something(c=15)


问:
boost intall on windows and typescript
I'd like to install boost on windows 10. I downloaded the package (1.64), launched boostrap, and got the fail log below. I indeed don't have typescript installed in C:\Program Files (x86)\Microsoft SDKs . But I do have Visual Studio 2017 installed (working just fine).

Since I'm no specialist of windows, and doesn't want to try anything messy, I would appreciate any advice on this issue.

** Visual Studio 2017 Developer Command Prompt v15.0.26430.12

** Copyright (c) 2017 Microsoft Corporation

[ERROR:typescript.bat] TypeScript was not added to PATH since a valid installation was not found
[ERROR:VsDevCmd.bat] * VsDevCmd.bat encountered errors. Environment may be incomplete and/or incorrect. *

答:
Solved, thanks to Typescript Support for Visual Studio 2017
Typescript was not installed by default with visual studio 2017. Running the installer as described in one of the answers in the linked question solved the problem.</p>

Title: boost intall on windows and typescript


问:
VBA - calculate and print answer for many rows
I am still new to vba and am writing a macro to calculate the time between two dates in two columns using dateDiff then print the difference in the cell next to it. i would also like do use a do until empty

Column A holds the start date
Column B holds the end date
Column C will hold the answer

i have some useful code but most of it is written to understand the goal of the macro and needs changed.

```<code>Range("A2").Select
Do Until IsEmpty(ActiveCell)
 For i = 2 To 25
  date1 = ["A" & i]
  date2 = ["B" & i]
  answer = DateDiff("n", date1, date2)
  "C" & i = answer
 next i
Loop
</code>```

I appreciate any help!

答:
A couple of things:

a. You can't have a variable when using the shorthand []:

```<code>[A1]
</code>```

will work but

```<code>i = 1
["A" & i]
</code>```

Will not.  So you must use.

```<code>Range("A" & i)
</code>```

Or

```<code>Cells(i,1)
</code>```

b. Your do loop does not change the ActiveCell. So it will never end if there is a value in A2

c. It is better practice to find the last row and use a FOR Loop. See here for many ways on finding the last row: Error in finding last used cell in VBA

d. Get in the habit now of declaring the parent of EVERY Range object, even if it is the ActiveSheet.

e. Always declare every variable, even if you declare it as Variant.

```<code>Dim i as Long
Dim lastRow as long
Dim date1 as double
Dim Date2 as double
Dim answer as long
With ActiveSheet
 lastRow = .Cells(.Rows.Count,1).End(xlUp).row
 For i = 2 To lastRow
  date1 = .Cells(i,1)
  date2 = .Cells(i,2)
  answer = DateDiff("n", date1, date2)
  .Cells(i,3) = answer
 next i
End With
</code>```

Body:
I am still new to vba and am writing a macro to calculate the time between two dates in two columns using dateDiff then print the difference in the cell next to it. i would also like do use a do until empty

Column A holds the start date
Column B holds the end date
Column C will hold the answer

i have some useful code but most of it is written to understand the goal of the macro and needs changed.

Range("A2").Select
Do Until IsEmpty(ActiveCell)
 For i = 2 To 25
  date1 = ["A" & i]
  date2 = ["B" & i]
  answer = DateDiff("n", date1, date2)
  "C" & i = answer
 next i
Loop

I appreciate any help!

Body:
A couple of things:

a. You can't have a variable when using the shorthand []:

[A1]

will work but

i = 1
["A" & i]

Will not.  So you must use.

Range("A" & i)

Or

Cells(i,1)

b. Your do loop does not change the ActiveCell. So it will never end if there is a value in A2

c. It is better practice to find the last row and use a FOR Loop. See here for many ways on finding the last row: Error in finding last used cell in VBA

d. Get in the habit now of declaring the parent of EVERY Range object, even if it is the ActiveSheet.

e. Always declare every variable, even if you declare it as Variant.

Dim i as Long
Dim lastRow as long
Dim date1 as double
Dim Date2 as double
Dim answer as long
With ActiveSheet
 lastRow = .Cells(.Rows.Count,1).End(xlUp).row
 For i = 2 To lastRow
  date1 = .Cells(i,1)
  date2 = .Cells(i,2)
  answer = DateDiff("n", date1, date2)
  .Cells(i,3) = answer
 next i
End With


问:
How to change menu title (vertical to horizontal) in ASP.NET MVC
/Shared/_Layout.cshtml

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="~/Content/jquery-1.10.2.min.js"></script>
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @Html.Action("Menu", "Nav")
    </div>
</body>
</html>
</code>```

/view/Nav/Menu.cshtml

```<code>@model IEnumerable<string>
@Html.ActionLink("Home","List","Product",null,
    new {@class ="btn btn-block btn-default btn-lg"})
@foreach (var link in Model)
{
  @Html.RouteLink(link, new { controller = "Product", action = "List", category = link, page = 1 },
     new{@class = "btn btn-block btn-default btn-lg display:inline" }
  )
}
</code>```

browser view

:

i want to change item view like below picture .

how to make item arrange vertical to horizontal

答:
To make the buttons display horizontally just remove the btn-block class from the list of classes:

new{@class = "btn btn-default btn-lg" }

You don't need display:inline and that wouldn't work anyways because you included it in the class attribute. It has to be included in the style attribute because it is a CSS rule not a CSS class.

To remove the borders around the buttons like you have in your second screenshot you can override Bootstrap like this:
style = border: 0;

CSS rules included in the style attribute take precedence over CSS classes.

Body:
/Shared/_Layout.cshtml

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>@ViewBag.Title</title>

        @Html.Action("Menu", "Nav")

/view/Nav/Menu.cshtml

@model IEnumerable<string>
@Html.ActionLink("Home","List","Product",null,
    new {@class ="btn btn-block btn-default btn-lg"})
@foreach (var link in Model)
{
  @Html.RouteLink(link, new { controller = "Product", action = "List", category = link, page = 1 },
     new{@class = "btn btn-block btn-default btn-lg display:inline" }
  )
}

browser view

:

i want to change item view like below picture .

how to make item arrange vertical to horizontal


问:
How to restrict UITextField to take only numbers in Swift?
I want the user to only enter numeric values in a UITextField. On iPhone we can show the numeric keyboard, but on iPad the user can switch to any keyboard.

Is there  any way to restrict user to enter only numeric values in a UITextField?

Note: This is an old question with many many answers. More than one third of the posted answers are wrong. Even some of the highly upvoted answers are wrong. Please, DO NOT post a new answer unless it somehow finds a vastly improved way to solve this question in a way that isn't shown already. Make sure your answer works in all circumstances. It must work for both iPhones and iPads. It must work when a user pastes text into the text field. It must work if the user has an external keyboard. It must work if the user changes the text selection in the text field before typing or pasting text. It must properly support decimal numbers (one decimal separator appropriate for the user's locale).

答:
```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

        {
            let textString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

            if textField == self.phoneTextField  && string.characters.count > 0{
                let numberOnly = NSCharacterSet.decimalDigits
                let strValid = numberOnly.contains(UnicodeScalar.init(string)!)
                return strValid && textString.characters.count <= 10
            }
            return true
        }
</code>```

in above code is working in swift 3

NSCharacterSet.decimalDigits

You are also use letters only

NSCharacterSet.Letters

and uppercase,Lowercaseand,alphanumerics,whitespaces
is used same code
 or  See the Link

Body:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

        {
            let textString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

            if textField == self.phoneTextField  && string.characters.count > 0{
                let numberOnly = NSCharacterSet.decimalDigits
                let strValid = numberOnly.contains(UnicodeScalar.init(string)!)
                return strValid && textString.characters.count <= 10
            }
            return true
        }

in above code is working in swift 3

NSCharacterSet.decimalDigits

You are also use letters only

NSCharacterSet.Letters

and uppercase,Lowercaseand,alphanumerics,whitespaces
is used same code
 or  See the Link


问:
Finding errors of Reactive Form subgroup
I cannot find a way to retrieve errors of subgroup of my reactive form.

private setupFormValidation() {
    this.progressForm = new FormGroup({
      'preImplementationGroup': new FormGroup({
        'otherProgramName': new FormControl(null, [Validators.required]),
        'programType': new FormControl(null, [Validators.required]),
        ...
      }),
      'testingReviewGroup': new FormGroup({
        ...
      })
    });```

What would be the best way to find all errors only for 'preImplementationGroup' Form Group?

答:
I have found a way, in case someone would be looking for the similar:

    sign() {
    var preImplementationGroup = <FormGroup>this.progressService.progressForm.get('preImplementationGroup');
    this.getFormValidationErrors(preImplementationGroup);
  }

  getFormValidationErrors(fg: FormGroup) {
    Object.keys(fg.controls).forEach(key => {

      const controlErrors: ValidationErrors = fg.get(key).errors;
      if (controlErrors != null) {
        Object.keys(controlErrors).forEach(keyError => {
          console.log('Key control: ' + key + ', keyError: ' + keyError + ', err value: ', controlErrors[keyError]);
        });
      }
    });
  }```

Body:
I cannot find a way to retrieve errors of subgroup of my reactive form.

private setupFormValidation() {
    this.progressForm = new FormGroup({
      'preImplementationGroup': new FormGroup({
        'otherProgramName': new FormControl(null, [Validators.required]),
        'programType': new FormControl(null, [Validators.required]),
        ...
      }),
      'testingReviewGroup': new FormGroup({
        ...
      })
    });

What would be the best way to find all errors only for 'preImplementationGroup' Form Group?


问:
Should a c# class generate instances of itself?
I have a class that defines a CallRate type. I need to add the ability to create multiple instances of my class by reading the data from a file.

I added a static method to my class CallRate that returns a List<CallRate>. Is it ok for a class to generate new instances of itself by calling one of its own constructors? It works, I just wonder if it's the proper thing to do.

```<code>List<CallRates> cr = CallRates.ProcessCallsFile(file);
</code>```

答:
It's perfectly acceptable to do this. When I do, I typically make the real constructors for the class private so that it's clear that the only way to construct instances is through the static method.

This is very useful in cases where "construction" may not always return a new instance. For example, you may want to return a previously cached object instead.

Body:
I have a class that defines a CallRate type. I need to add the ability to create multiple instances of my class by reading the data from a file.

I added a static method to my class CallRate that returns a List<CallRate>. Is it ok for a class to generate new instances of itself by calling one of its own constructors? It works, I just wonder if it's the proper thing to do.

List<CallRates> cr = CallRates.ProcessCallsFile(file);

OwnerDisplayName: munificent

ContentLicense: CC BY-SA 2.5


问:
How to import string from require in nodeJS when imported function takes time to finish?
I am calling following code which imports a search query function

```<code>var match_all = require('./match_all');
var data=match_all.func();
console.log('uo yoyo');
console.log(data);
</code>```

Match_all is as follows:

```<code>var string_of_da;

//a function which queries for all pid and syscalls
var string = function(){
var client = new elasticsearch.Client({
      .....
    })

//queries to ES
function getmeres(client,syscall){
        client.search({
         ........

},function (error,response) {
      .......
showdocs(d)
}
});
}
function showdocs(d){
var da = d["hits"]["hits"].map(function(i){
        return i['_source'];
});
string_of_da = JSON.stringify(da,null,'\t');
}
return string_of_da;
};
module.exports.func = string;
module.exports.string = string_of_da;
</code>```

Now when I execute my earlier js program, it queries properly, but before match_all.func() is called and returns string, console.log is called. So my output looks like

uo yoyo

undefined

...elasticsearch search logs...

what is going wrong here?

答: because you are using call backs .call back  work asynchronous. so thats why console.log  is printing first.in asynchronous it will not wait till he get a response .Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks.</p>

Body:
I am calling following code which imports a search query function

var match_all = require('./match_all');
var data=match_all.func();
console.log('uo yoyo');
console.log(data);

Match_all is as follows:

var string_of_da;

//a function which queries for all pid and syscalls
var string = function(){
var client = new elasticsearch.Client({
      .....
    })

//queries to ES
function getmeres(client,syscall){
        client.search({
         ........

},function (error,response) {
      .......
showdocs(d)
}
});
}
function showdocs(d){
var da = d["hits"]["hits"].map(function(i){
        return i['_source'];
});
string_of_da = JSON.stringify(da,null,'\t');
}
return string_of_da;
};
module.exports.func = string;
module.exports.string = string_of_da;

Now when I execute my earlier js program, it queries properly, but before match_all.func() is called and returns string, console.log is called. So my output looks like

uo yoyo

undefined

...elasticsearch search logs...

what is going wrong here?


问:
Splitting A Set Of Numbers Among Arrays
I am creating a game where I need to divide numbers 1-21 among the 7 players to divide the 21 cards among them, so each player gets 3 cards. I need it to be random, so I tried to make a function where for every number, it will add it to a random one of the 7 arrays, and if the array it was trying to add to already had three numbers (or in this case cards) then it would give that number to another card. Thank you in advance, David.</p>

答:
Alright, using the answer by adjan and Lestat, and the changing it into code that unity uses, here is the code I used. While I'm sure their code would work in standard C#, unity has it's own functions that don't always work with standard C#, so this is how I changed it. Feel free to use it.

```<code>private void divideAmong() {
    int[] numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21};
    int[] result = numbers.OrderBy(i => Random.Range(0,22)).ToArray();

}
</code>```

Note: You need to make sure you are using System.Linq

Title: Splitting A Set Of Numbers Among Arrays

Body:
Alright, using the answer by adjan and Lestat, and the changing it into code that unity uses, here is the code I used. While I'm sure their code would work in standard C#, unity has it's own functions that don't always work with standard C#, so this is how I changed it. Feel free to use it.

private void divideAmong() {
    int[] numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21};
    int[] result = numbers.OrderBy(i => Random.Range(0,22)).ToArray();

}

Note: You need to make sure you are using System.Linq


问:
How to reset PTS for Stream
I am trying reset pts on input stream and create new pts and publish stream to RTMP.

```<code>ffmpeg -re -f lavfi -i "movie=${SOURCE}:s=0+1[out0][out1];[0:v]setpts=N/(FRAME_RATE*TB),[0:a]asetpts=N/(FRAME_RATE*TB)" \
       -r 24 -crf 20 \
       -c:v libx264 \
       -c:a aac -ar 44100 -ab 128k -ac 2 -strict -2 \
       -f flv ${DEST}
</code>```

If I remove the setpts and asetpts filters them command works. But I need to setpts and asetpts at source before it is given to encoder.

Please help.

答:
Alter the PTS outside the source graph.</p>

```<code>ffmpeg -re -f lavfi -i "movie=${SOURCE}:s=0+1" \
   -vf setpts=N/FRAME_RATE/TB -af asetpts=N/SR/TB
   -r 24 -crf 20 \
   -c:v libx264 \
   -c:a aac -ar 44100 -ab 128k -ac 2 -strict -2 \
   -f flv ${DEST}
</code>```

Title: How to reset PTS for Stream

Body:
I am trying reset pts on input stream and create new pts and publish stream to RTMP.

ffmpeg -re -f lavfi -i "movie=${SOURCE}:s=0+1[out0][out1];[0:v]setpts=N/(FRAME_RATE*TB),[0:a]asetpts=N/(FRAME_RATE*TB)" \
       -r 24 -crf 20 \
       -c:v libx264 \
       -c:a aac -ar 44100 -ab 128k -ac 2 -strict -2 \
       -f flv ${DEST}

If I remove the setpts and asetpts filters them command works. But I need to setpts and asetpts at source before it is given to encoder.

Please help.

Body:
Alter the PTS outside the source graph.

ffmpeg -re -f lavfi -i "movie=${SOURCE}:s=0+1" \
   -vf setpts=N/FRAME_RATE/TB -af asetpts=N/SR/TB
   -r 24 -crf 20 \
   -c:v libx264 \
   -c:a aac -ar 44100 -ab 128k -ac 2 -strict -2 \
   -f flv ${DEST}


问:
PHP UPDATE data where there are ID matches
I'm passing an id from a URL from the previous page and then try to update database values in the row of that id. I feel like I'm close. I'm able to update the value librarian_fname when I add into the update query the specific id number, but when I try and pass that value through the code, it must not be picking it up because it won't update when I use id = '$id'. Not sure what I'm doing wrong. And I am still learning so forgive me if this isn't perfect.

```<code><?php
$id = $_GET['id'];
echo $id;
?>
    <?php
  // This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
        foreach ($params as &$var) {
            // check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
            is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
            unset($var);
        }
}

// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);

            $librarian_fname = $_POST['librarian_fname'];
            $id = $_POST['id'];
 ?>

        <?php
         if(isset($_POST['add'])) {
            $dbhost = 'localhost';
            $dbuser = '';
            $dbpass = '';
            $conn = mysql_connect($dbhost, $dbuser, $dbpass);

            if(! $conn ) {
               die('Could not connect: ' . mysql_error());
            }
            $sql = "UPDATE table SET librarian_fname = '$librarian_fname' WHERE id = '$id'";
            mysql_select_db('Events');
            $result = mysql_query( $sql, $conn );

            if(! $result ) {
               die('Could not enter data: ' . mysql_error());
            }

            mysql_close($conn);
            header("Location: search.php");
         }

         else {
            ?>

            <?php
// define variables and set to empty values
$librarian_fname = $id = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $librarian_fname = test_input($_POST["librarian_fname"]);
  $id = test_input($_POST["id"]);
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
                    <legend><b>Appointment Topic</b></legend>
                    <input type="hidden" name="id" value="<? echo $id; ?>">
                    <label for="librarian_fname">First Name <em>*</em></label>
                    <input type="text" name="librarian_fname" size="50" required="no" validateat="onsubmit" message="Please enter your first name."> input name = "add" type = "submit" id = "add" value = "Submit">
                </form>
                <?php
         }
      ?>
</code>```

答:
Try this    </p>

```<code><form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
                        <legend><b>Appointment Topic</b></legend>
                        <input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
                        <label for="librarian_fname">First Name <em>*</em></label>
                        <input type="text" name="librarian_fname" size="50" required="no" validateat="onsubmit" message="Please enter your first name."> <input name = "add" type = "submit" id = "add" value = "Submit">
                        <input type="reset" name="resetButton" id="resetButton" vvalue="Reset Form" style="margin-right: 20px;" />
     </form>
</code>```

Body:
I'm passing an id from a URL from the previous page and then try to update database values in the row of that id. I feel like I'm close. I'm able to update the value librarian_fname when I add into the update query the specific id number, but when I try and pass that value through the code, it must not be picking it up because it won't update when I use id = '$id'. Not sure what I'm doing wrong. And I am still learning so forgive me if this isn't perfect.

<?php
$id = $_GET['id'];
echo $id;
?>
    <?php
  // This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
        foreach ($params as &$var) {
            // check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
            is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
            unset($var);
        }
}

// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);

            $librarian_fname = $_POST['librarian_fname'];
            $id = $_POST['id'];
 ?>

        <?php
         if(isset($_POST['add'])) {
            $dbhost = 'localhost';
            $dbuser = '';
            $dbpass = '';
            $conn = mysql_connect($dbhost, $dbuser, $dbpass);

            if(! $conn ) {
               die('Could not connect: ' . mysql_error());
            }
            $sql = "UPDATE table SET librarian_fname = '$librarian_fname' WHERE id = '$id'";
            mysql_select_db('Events');
            $result = mysql_query( $sql, $conn );

            if(! $result ) {
               die('Could not enter data: ' . mysql_error());
            }

            mysql_close($conn);
            header("Location: search.php");
         }

         else {
            ?>

            <?php
// define variables and set to empty values
$librarian_fname = $id = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $librarian_fname = test_input($_POST["librarian_fname"]);
  $id = test_input($_POST["id"]);
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
                    <legend>Appointment Topic</legend>
                    <input type="hidden" name="id" value="<? echo $id; ?>">
                    First Name *
                    <input type="text" name="librarian_fname" size="50" required="no" validateat="onsubmit" message="Please enter your first name."> input name = "add" type = "submit" id = "add" value = "Submit">
                </form>
                <?php
         }
      ?>

Body:
Try this

<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
                        <legend><b>Appointment Topic</b></legend>
                        <input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
                        <label for="librarian_fname">First Name <em>*</em></label>
                        <input type="text" name="librarian_fname" size="50" required="no" validateat="onsubmit" message="Please enter your first name."> <input name = "add" type = "submit" id = "add" value = "Submit">
                        <input type="reset" name="resetButton" id="resetButton" vvalue="Reset Form" style="margin-right: 20px;" />
     </form>


问:
unexpected word boundaries behavior in regex
```<code>import re
text = 'washington d.c. columbia'
templ_1 = 'washington d.c'
templ_2 = 'washington d.c.'
print(re.sub(r'\b%s\b'%templ_1, '', text))
</code>```

I got . columbia as expected

```<code>print(re.sub(r'\b%s\b'%templ_2, '', text))
</code>```

I got washington d.c. columbia instead of . columbia How to fix it?

答:
A word boundary is the transition from a word to non-word, or from a non-word to a word.

In your case, you fixed that transition based on what the literal is next

to the boundary construct \b

In the first regex its \bwashington d.c\b

meaning after the c it expects a non-word.

In the second regex its \bwashington d.c.\b

and in this case, the meaning after the . is undefined until it finds

the character represented by a metachar dot.

In this case, it finds a literal dot . in the target, then the boundary

expects the next character to be a word.

So, in the second  case, the target has a space after the dot, which is

not a word. Thus, no match.

Body:
import re
text = 'washington d.c. columbia'
templ_1 = 'washington d.c'
templ_2 = 'washington d.c.'
print(re.sub(r'\b%s\b'%templ_1, '', text))

I got . columbia as expected

print(re.sub(r'\b%s\b'%templ_2, '', text))

I got washington d.c. columbia instead of . columbia How to fix it?


问:
Make webpack paths relative to current directory

The Question:

I am using Rails 5.0 with Webpacker, and I am trying to setup our initial Webpack config. In Rails+Webpacker Webpack generates a different build file for each item in the app/javascript/packs folder. Is there a way to get these Webpack "packs" to resolve different paths for modules based on a files containing folder?

The Problem:

Redundant sections of paths in my import statements resulting in imports like:

main/pages/home.js:

```<code>import Engine from 'main/engine'
import Routes from 'main/engine/routes.js'
</code>```

dev_panel/pages/home.js:

```<code>import Engine from 'dev_panel/engine'
import Routes from 'dev_panel/engine/routes.js'
</code>```

etc...

And this is compounded for every file and subdirectory of course. This is not only monotonous, but also makes re-organization of files and code a headache.

Desired Pattern:

main/pages/home.js:

```<code>// but still refers to /main/engine/routes.js
import Engine from 'engine'
import Routes from 'engine/routes.js'
</code>```

dev_panel/pages/home.js:

```<code>// but still refers to /dev_panel/engine/routes.js
import Engine from 'engine'
import Routes from 'engine/routes.js'
</code>```

etc...

Example Structure:

```<code>app/javascript
├── packs
│   ├── dev_panel.js
│   ├── admin_panel.js
│   └── main.js
├── main
│   ├── data.js
│   ├── engine
│   │   ├── index.js
│   │   └── routes.js
│   ├── index.js
│   └── pages
│       ├── home.js
│       └── index.js
├── dev_panel
│   ├── data.js
│   ├── engine
│   │   ├── index.js
│   │   └── routes.js
│   ├── index.js
│   └── pages
│       ├── home.js
│       └── index.js
└── admin_panel.js
    ├── data.js
    ├── engine
    │   ├── index.js
    │   └── routes.js
    ├── index.js
    └── pages
        ├── home.js
        └── index.js
</code>```

答:
You can use .. to go one level up in the directory structure:

```<code>import Engine from '../engine'
import Routes from '../engine/routes.js'
</code>```

Body:
The Question:

I am using Rails 5.0 with Webpacker, and I am trying to setup our initial Webpack config. In Rails+Webpacker Webpack generates a different build file for each item in the app/javascript/packs folder. Is there a way to get these Webpack "packs" to resolve different paths for modules based on a files containing folder?

The Problem:

Redundant sections of paths in my import statements resulting in imports like:

main/pages/home.js:

import Engine from 'main/engine'
import Routes from 'main/engine/routes.js'

dev_panel/pages/home.js:

import Engine from 'dev_panel/engine'
import Routes from 'dev_panel/engine/routes.js'

etc...

And this is compounded for every file and subdirectory of course. This is not only monotonous, but also makes re-organization of files and code a headache.

Desired Pattern:

main/pages/home.js:

// but still refers to /main/engine/routes.js
import Engine from 'engine'
import Routes from 'engine/routes.js'

dev_panel/pages/home.js:

// but still refers to /dev_panel/engine/routes.js
import Engine from 'engine'
import Routes from 'engine/routes.js'

etc...

Example Structure:

app/javascript
├── packs
│   ├── dev_panel.js
│   ├── admin_panel.js
│   └── main.js
├── main
│   ├── data.js
│   ├── engine
│   │   ├── index.js
│   │   └── routes.js
│   ├── index.js
│   └── pages
│       ├── home.js
│       └── index.js
├── dev_panel
│   ├── data.js
│   ├── engine
│   │   ├── index.js
│   │   └── routes.js
│   ├── index.js
│   └── pages
│       ├── home.js
│       └── index.js
└── admin_panel.js
    ├── data.js
    ├── engine
    │   ├── index.js
    │   └── routes.js
    ├── index.js
    └── pages
        ├── home.js
        └── index.js

Body:
You can use .. to go one level up in the directory structure:

import Engine from '../engine'
import Routes from '../engine/routes.js'


问:
What is Google Apps?
What is google apps and why are so many startup companies using it?</p>

答:
Google Apps are...
“A set of intelligent apps including Gmail, Docs, Drive, and Calendar to connect the people in your company, no matter where in the world they are.”

Source:  https://gsuite.google.com/together/

Examples:  Google Calendar, Google Drive, Google Hangouts, Google Slides, Google Spreadsheets - those are all web-based applications ("apps").

G Suite is the name given by Google for their collection of applications.  Formerly named “Google Apps for Work” and “Google Apps for Your Domain”, G Suite is resource implemented by I.T. Administrators, to enable access to Google Apps, through a domain (and their aliases).

For Example:  Rather than using your standard Gmail address (username@gmail.com), users in a business or organization would login to access those web-apps using an email address with their own domain, like (username@example.com).

The interface is the same as for standard Google Account holders, yet G Suite admins have the ability to add some branding, and control features - through the G Suite Admin Console.

I'm going to stop here before this post starts to resemble a pitch - let's just say that I really enjoy the fact that my workplace has implemented G Suite for our organization - it has made my duties, that much easier!

Title: What is Google Apps?


答:
you can use (\w[-.\w]+(?:@|\[at\])[\w-]+\.[A-Za-z]{2,4})

just add an non-capturing group with or anchor | to match either @ or \[at\] as mentioned here

Note : you need not to escape - and . inside []

Title: Regular Expression validating with "at"

Body:
I know how to validate an email adress using regular expression, when the mail has the structure "blabla@foo.com"
The valid regular expression looks like this:

([\w\-]([\.\w])+[\w]+@([\w\-]+\.)+[A-Za-z]{2,4})

But at my university, my professors do have websites in which their email adresses look like this: prof[at]foo.bla

What is the correct regular expression for this kind of emails? Changing @ to [at] didn't work.

Is there any tutorial for this kind of problems? Can you please recommend something?


问:
List files (recursively) which have no matching pair
I have a set of files in multiple directories. Most of them have a related pair with a different extension and the same base name. The related files are always within the same directory. I need to list only files (and path) without pairs within a directory including all sub directories. How can I do that in bash?

```<code>file1.xxx
file1.yyy

file2.xxx
file2.zzz

file3.xxx
file3.aaa

file4.xxx
</code>```

Any help is much appreciated!

答:
You could use find and pipe to perl to sort the data

```<code>find . -type f -print0 |\
perl -0 -l012 -ne 'if(/.*\/(.*)\./){$x{$1}++;$y{$1}=$_}
}{for(keys %x){print $y{$_} if $x{$_}==1}'
</code>```

This adds the name with no suffix to a hash and incremements for each match, whilst adding the full line to another hash with the same key.

In the end it just checks which have a single match and prints.

As the filenames are null delimited it should work with all filenames.

Body:
I have a set of files in multiple directories. Most of them have a related pair with a different extension and the same base name. The related files are always within the same directory. I need to list only files (and path) without pairs within a directory including all sub directories. How can I do that in bash?

file1.xxx
file1.yyy

file2.xxx
file2.zzz

file3.xxx
file3.aaa

file4.xxx

Any help is much appreciated!

Body:
You could use find and pipe to perl to sort the data

find . -type f -print0 |\
perl -0 -l012 -ne 'if(/.*\/(.*)\./){$x{$1}++;$y{$1}=$_}
}{for(keys %x){print $y{$_} if $x{$_}==1}'

This adds the name with no suffix to a hash and incremements for each match, whilst adding the full line to another hash with the same key.

In the end it just checks which have a single match and prints.

As the filenames are null delimited it should work with all filenames.


问:
django - Can't login after creating user
I can't login after create user. Here's my code:

```<code>class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        username = validated_data.pop('username')
        password = validated_data.pop('password')
        return User.objects.create_user(username, password, **validated_data)
</code>```

My api:

```<code>from django.contrib.auth.models import User
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
</code>```

any help is appreciated.
Updated: Here's my test case

```<code>class UserAPITestCase(APITestCase):

def setUp(self):
    self.client = APIClient()

    self.user = User.objects.create_user(
        username='anhnguyen',
        password=PASSWORD,
    )
    self.user.save()

def test_create_user(self):
    data = {
        'username': 'khoavo',
        'password': PASSWORD,
    }

    user = self.client.post(URL, data, format='json')
    self.assertEqual(user.status_code, status.HTTP_201_CREATED)

    url = reverse(URL1, args=[2])
    response = self.client.get(url)
    self.assertEqual(response.status_code, status.HTTP_200_OK)

    login = self.client.login(username='khoavo', password=PASSWORD)
    self.assertTrue(login)
</code>```

The test case failed at login statement after creating a user

答:
The easiest way to do that is sending all with **:

```<code>...
def create(self, validated_data):
    return User.objects.create_user(**validated_data)
...
</code>```

It would solve your issue

Body:
I can't login after create user. Here's my code:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        username = validated_data.pop('username')
        password = validated_data.pop('password')
        return User.objects.create_user(username, password, **validated_data)

My api:

from django.contrib.auth.models import User
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

any help is appreciated.
Updated: Here's my test case

class UserAPITestCase(APITestCase):

def setUp(self):
    self.client = APIClient()

    self.user = User.objects.create_user(
        username='anhnguyen',
        password=PASSWORD,
    )
    self.user.save()

def test_create_user(self):
    data = {
        'username': 'khoavo',
        'password': PASSWORD,
    }

    user = self.client.post(URL, data, format='json')
    self.assertEqual(user.status_code, status.HTTP_201_CREATED)

    url = reverse(URL1, args=[2])
    response = self.client.get(url)
    self.assertEqual(response.status_code, status.HTTP_200_OK)

    login = self.client.login(username='khoavo', password=PASSWORD)
    self.assertTrue(login)

The test case failed at login statement after creating a user

Body:
The easiest way to do that is sending all with **:

...
def create(self, validated_data):
    return User.objects.create_user(**validated_data)
...

It would solve your issue


问:
CSS selectors for inner grid lines with variable items
I have a list view of data displayed as cards and I'm trying to get to a pure CSS solution where I'll have only inner border lines.

The cards will display a max of two per row and will wrap to the next line when there are more. We're using bootstrap col-md-6 to achieve this.

Here's an example of three data items displayed as cards and what I'm trying to achieve with the inner grid lines.

Notes:

If there are only two items then the bottom line shouldn't be visible

I thought I could use adapt the technique mentioned here by Lea Verou, but I haven't been able to get it to work.

Regardless of how many items there are none of the outer borders should ever show. This is especially so with the last 1 or two items depending on the total count of items

Here's an example of the HTML markup for an individual list item:

```<code><div class="col-md-6">
    <div class="form-group">
        <label class="control-label">Name</label>
        <div class="form-control-static">Fund</div>
    </div>

    <div class="form-group">
        <label class="control-label">Tax Rate</label>
        <div class="form-control-static">1</div>
    </div>

    <div class="form-group">
        <label class="control-label">Amount</label>
        <div class="form-control-static">10</div>
    </div>

    <div class="edit-buttons">
        <a class="btn btn-link"><span class="glyphicon glyphicon-pencil"></span> edit</a>
        <a class="btn btn-link><span class="glyphicon glyphicon-remove"></span> delete</a>
    </div>
</div>
</code>```

I know to get the middle line I can use:
.col-md-6:nth-child(odd){
    border-right:1px solid gray;
}

The problem comes in with the bottom border, i.e. if you have a total of three data items then only the last one should have its bottom border set to 'none'. If there are four then the last two would need their bottom borders set to 'none'.

What's the best approach to getting this to work without the use of tables?

答:
In other words, the last item should have always border: none.
And the before-the last item, only when it's odd.

I will skip the style to make the grid, since this is not really relevant

Let's begin setting border to all but the last 2:

div {
  display: inline-block;
}

.container {
  border: solid 1px black;
}

.container div {
  width: 50px;
  height: 50px;
  margin: 5px;
  background-color: lightblue;
}

.container div:nth-last-child(n + 3) {
  border-bottom: solid 4px green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div></code>```

And now the before-the-lasty, if even

div {
  display: inline-block;
}
.container {
  border: solid 1px black;
}

.container div {
  width: 50px;
  height: 50px;
  margin: 5px;
  background-color: lightblue;
}

.container div:nth-last-child(2):nth-child(even) {
  border-bottom: solid 4px red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div></code>```

So, the end result:

div {
  display: inline-block;
}
.container {
  border: solid 1px black;
  width: 130px;
  vertical-align: top;
}

.container div {
  width: 50px;
  height: 50px;
  margin: 5px;
  background-color: lightblue;
}

.container div:nth-last-child(n + 3),
.container div:nth-last-child(2):nth-child(even) {
  border-bottom: solid 4px blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div></code>```

Body:
I have a list view of data displayed as cards and I'm trying to get to a pure CSS solution where I'll have only inner border lines.

The cards will display a max of two per row and will wrap to the next line when there are more. We're using bootstrap col-md-6 to achieve this.

Here's an example of three data items displayed as cards and what I'm trying to achieve with the inner grid lines.

Notes:

If there are only two items then the bottom line shouldn't be visible

I thought I could use adapt the technique mentioned here by Lea Verou, but I haven't been able to get it to work.

Regardless of how many items there are none of the outer borders should ever show. This is especially so with the last 1 or two items depending on the total count of items

Here's an example of the HTML markup for an individual list item:

        Name

Fund

        Tax Rate

1

        Amount

10

         edit
         delete

I know to get the middle line I can use:
.col-md-6:nth-child(odd){
    border-right:1px solid gray;
}

The problem comes in with the bottom border, i.e. if you have a total of three data items then only the last one should have its bottom border set to 'none'. If there are four then the last two would need their bottom borders set to 'none'.

What's the best approach to getting this to work without the use of tables?

Body:
In other words, the last item should have always border: none.
And the before-the last item, only when it's odd.

I will skip the style to make the grid, since this is not really relevant

Let's begin setting border to all but the last 2:

div {
  display: inline-block;
}

.container {
  border: solid 1px black;
}

.container div {
  width: 50px;
  height: 50px;
  margin: 5px;
  background-color: lightblue;
}

.container div:nth-last-child(n + 3) {
  border-bottom: solid 4px green;
}

<div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

And now the before-the-lasty, if even

div {
  display: inline-block;
}
.container {
  border: solid 1px black;
}

.container div {
  width: 50px;
  height: 50px;
  margin: 5px;
  background-color: lightblue;
}

.container div:nth-last-child(2):nth-child(even) {
  border-bottom: solid 4px red;
}

<div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

So, the end result:

div {
  display: inline-block;
}
.container {
  border: solid 1px black;
  width: 130px;
  vertical-align: top;
}

.container div {
  width: 50px;
  height: 50px;
  margin: 5px;
  background-color: lightblue;
}

.container div:nth-last-child(n + 3),
.container div:nth-last-child(2):nth-child(even) {
  border-bottom: solid 4px blue;
}

<div class="container">
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>


问:
Pandas dataframe boolean mask on multiple columns
I have a dataframe (df) containing several columns with an actual measure and corresponding number of columns (A,B,...) with an uncertainty (dA, dB, ...) for each of these columns:

```<code>   A    B    dA      dB
0 -1    3    0.31    0.08
1  2   -4    0.263   0.357
2  5    5    0.382   0.397
3 -4   -0.5  0.33    0.115
</code>```

I apply a function to find values in the measurement columns that are valid according to my definition

```<code>df[["A","B"]].apply(lambda x: x.abs()-5*df['d'+x.name] > 0)
</code>```

This will return a boolean array:

```<code>     A          B
0    False      True
1    True       True
2    True       True
3    True       False
</code>```

I would like to use this array to select rows in dataframe for which the condition is true within a single column, e.g. A -> row 1-3, and also find rows where the condition is true for all the input columns, e.g. row 1 and 2.
Is there an efficient way to do this with pandas?

答:
Using the underlying array data, a vectorized approach would be like so -

```<code>cols = ['A','B'] # list holding relevant column names
dcols = ['d'+i for i in cols]
out = np.abs(df[cols].values) - 5*df[dcols].values > 0
</code>```

Sample run -

```<code>In [279]: df
Out[279]:
   A    B     dA     dB
0 -1  3.0  0.310  0.080
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
3 -4 -0.5  0.330  0.115

In [280]: cols = ['A','B'] # list holding relevant column names
     ...: dcols = ['d'+i for i in cols]
     ...: out = np.abs(df[cols].values) - 5*df[dcols].values > 0
     ...:

In [281]: out
Out[281]:
array([[False,  True],
       [ True,  True],
       [ True,  True],
       [ True, False]], dtype=bool)
</code>```

To extract out the valid ones by setting the invalid ones as NaNs, we could use np.where -

```<code>In [293]: df[cols] = np.where(out, df[cols], np.nan)

In [294]: df
Out[294]:
     A    B     dA     dB
0  NaN  3.0  0.310  0.080
1  2.0 -4.0  0.263  0.357
2  5.0  5.0  0.382  0.397
3 -4.0  NaN  0.330  0.115
</code>```

Also, we could get the rows with all matches with all() reduction along each row -

```<code>In [283]: np.flatnonzero(out.all(axis=1))
Out[283]: array([1, 2])
</code>```

Body:
I have a dataframe (df) containing several columns with an actual measure and corresponding number of columns (A,B,...) with an uncertainty (dA, dB, ...) for each of these columns:

   A    B    dA      dB
0 -1    3    0.31    0.08
1  2   -4    0.263   0.357
2  5    5    0.382   0.397
3 -4   -0.5  0.33    0.115

I apply a function to find values in the measurement columns that are valid according to my definition

df[["A","B"]].apply(lambda x: x.abs()-5*df['d'+x.name] > 0)

This will return a boolean array:

     A          B
0    False      True
1    True       True
2    True       True
3    True       False

I would like to use this array to select rows in dataframe for which the condition is true within a single column, e.g. A -> row 1-3, and also find rows where the condition is true for all the input columns, e.g. row 1 and 2.
Is there an efficient way to do this with pandas?

Body:
Using the underlying array data, a vectorized approach would be like so -

cols = ['A','B'] # list holding relevant column names
dcols = ['d'+i for i in cols]
out = np.abs(df[cols].values) - 5*df[dcols].values > 0

Sample run -

In [279]: df
Out[279]:
   A    B     dA     dB
0 -1  3.0  0.310  0.080
1  2 -4.0  0.263  0.357
2  5  5.0  0.382  0.397
3 -4 -0.5  0.330  0.115

In [280]: cols = ['A','B'] # list holding relevant column names
     ...: dcols = ['d'+i for i in cols]
     ...: out = np.abs(df[cols].values) - 5*df[dcols].values > 0
     ...:

In [281]: out
Out[281]:
array([[False,  True],
       [ True,  True],
       [ True,  True],
       [ True, False]], dtype=bool)

To extract out the valid ones by setting the invalid ones as NaNs, we could use np.where -

In [293]: df[cols] = np.where(out, df[cols], np.nan)

In [294]: df
Out[294]:
     A    B     dA     dB
0  NaN  3.0  0.310  0.080
1  2.0 -4.0  0.263  0.357
2  5.0  5.0  0.382  0.397
3 -4.0  NaN  0.330  0.115

Also, we could get the rows with all matches with all() reduction along each row -

In [283]: np.flatnonzero(out.all(axis=1))
Out[283]: array([1, 2])


问:
Overriding arithmetic operators on Int via implicit conversions
Say that, for aesthetical reasons, I want to be able to write:

```<code>3 / 4
</code>```

and have / be a method on a class that there exists an implicit conversion from Int to, e.g.:

```<code>class Foo(val i: Int) {
  def /(that: Int) = // something
}

implicit def intToFoo(i: Int) = new Foo(i)
</code>```

Is this at all possible, i.e. is it possible to "disable" the / method on Int?

答:
In short:  No, you can't.

Implicit resolution will only take place if you attempt to call a method that doesn't already exist.

A more "idiomatic" solution would be to create your own pseudo-number type, something like:

```<code>case class Rational(a: Int, b: Int) {
  // other methods
}

val foo = Rational(3, 4)
</code>```

or

```<code>case class Path(value: String) {
  def /(other: String): Path = ...
}

val p = Path("3") / "4"
</code>```

Body:
Say that, for aesthetical reasons, I want to be able to write:

3 / 4

and have / be a method on a class that there exists an implicit conversion from Int to, e.g.:

class Foo(val i: Int) {
  def /(that: Int) = // something
}

implicit def intToFoo(i: Int) = new Foo(i)

Is this at all possible, i.e. is it possible to "disable" the / method on Int?

Body:
In short:  No, you can't.

Implicit resolution will only take place if you attempt to call a method that doesn't already exist.

A more "idiomatic" solution would be to create your own pseudo-number type, something like:

case class Rational(a: Int, b: Int) {
  // other methods
}

val foo = Rational(3, 4)

or

case class Path(value: String) {
  def /(other: String): Path = ...
}

val p = Path("3") / "4"