问:
Use of "in" in a function's arguments
I have been following the Ray Wenderlich book Advanced iOS App Architecture, and they have a protocol that looks like the following:

```<code>protocol RideOptionDeterminedResponder {
  func pickUpUser(in rideOptionID: RideOptionID)
}
</code>```

I don't understand the us of in before the rideOptionID parameter (which, by the way, is just a typealias for String), as I always thought you only used this keyword when writing closures. I've looked around a lot for uses of in but haven't had any luck.

What is the purpose of in here, and how would the function be different if it were absent?

(If you need more information on how this function works in order to explain yourself better, just let me know.)

答:
The in keyword here is only meant to specify the argument in the function. While calling the function you can just call it as:

pickUpUser(in: rideOptionID)
```

<p>If <code>in</code> was not present, you'll have to call it as:</p>

<pre class="lang-swift prettyprint-override"><code>pickUpUser(rideOptionID: rideOptionID)
</code>```

You can go through the Swift Documentation for more detail on Specifying Argument Labels

Title: Use of "in" in a function's arguments

Body:
I have been following the Ray Wenderlich book Advanced iOS App Architecture, and they have a protocol that looks like the following:

protocol RideOptionDeterminedResponder {
  func pickUpUser(in rideOptionID: RideOptionID)
}

I don't understand the us of in before the rideOptionID parameter (which, by the way, is just a typealias for String), as I always thought you only used this keyword when writing closures. I've looked around a lot for uses of in but haven't had any luck.

What is the purpose of in here, and how would the function be different if it were absent?

(If you need more information on how this function works in order to explain yourself better, just let me know.)

Body:
The in keyword here is only meant to specify the argument in the function. While calling the function you can just call it as:

pickUpUser(in: rideOptionID)

If in was not present, you'll have to call it as:

pickUpUser(rideOptionID: rideOptionID)

You can go through the Swift Documentation for more detail on Specifying Argument Labels


来源: stackexchange

问:
ExtJS MultiSelect Edit - Not working for multi value selection
I have a GridEditPanel where the 1st column is a combobox with multiSelect. The values are being loaded correctly from the DB and is being written in the DB correctly as well. In the event where the the combobox has a single value, the drop-down highlights the value correctly as well.

The issue is when the combobox has multiple values, it displays the values correctly, however during edit the multiple values are not selected.

Model:

```<code>extend: 'Ext.data.Model',
idProperty: 'contactTypeID',
fields: [
    {
        name: 'contactTypeID',
        type: 'string'
    },
    {
        name: 'contactType',
        type: 'string'
    }
],
</code>```

View GridEditPanel

```<code>emptyText: "There are no contacts.",
insertErrorText: 'Please finish editing the current contact before inserting a new record',
addButtonText: 'Add Contact',

itemId: 'contacts',
viewConfig: {
    deferEmptyText: false
},
minHeight: 130,

initComponent: function () {
    var me = this,
        contactTypes;

    // Creating store to be referenced by column renderer
    contactTypes = Ext.create('Ext.data.Store', {
        model: '********',
        autoLoad: true,
        listeners: {
            load: function () {
                me.getView().refresh();
            }
        }
    });

    this.columns = [
        {
            text: 'Contact Role',
            dataIndex: 'contactRoleID',
            flex: 1,
            renderer: function (value) {
                // Lookup contact type to get display value
                //If a contact has multiple roles, use split by ',' to find display values.
                if (value.includes(',')) {
                    var a = value.split(','), i, contTypeIds = [];
                    var contTypes = new Array();

                    for (i = 0; i < a.length; i++) {
                        contTypeIds.push(a[i]);
                        contTypes.push(contactTypes.findRecord('contactTypeID', a[i], 0, false, false, true).get('contactType'));
                    }
                    console.log('Multi Render Return Value: ' + contTypes);
                    return contTypes;
                }
                else {//if not a contact will only have one role.
                    var rec = contactTypes.findRecord('contactTypeID', value, 0, false, false, true); // exact match
                    console.log('Single Render Return Value: ' + rec.get('contactType'));
                    return rec ? rec.get('contactType') : '<span class="colselecttext">Required</span>';
                }
            },
            align: 'center',
            autoSizeColumn: true,
            editor: {
                xtype: 'combobox',
                store: contactTypes,
                multiSelect: true,
                delimiter: ',',
                forceSelection: true,
                queryMode: 'local',
                displayField: 'contactType',
                valueField: 'contactTypeID',
                allowBlank: false
            }
        },
</code>```

答:
I cannot see the model of GridEditPanel, but I assume you are using the wrong field type, string instead of array (Have a look at the converter function, maybe it will help you to fix the problem). I wrote a small post in my blog about multiSelect combobox editor in editable grid. The sample works with v4.2
Hope it will help you to fix the bug.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a GridEditPanel where the 1st column is a combobox with multiSelect. The values are being loaded correctly from the DB and is being written in the DB correctly as well. In the event where the the combobox has a single value, the drop-down highlights the value correctly as well.

The issue is when the combobox has multiple values, it displays the values correctly, however during edit the multiple values are not selected.

Model:

extend: 'Ext.data.Model',
idProperty: 'contactTypeID',
fields: [
    {
        name: 'contactTypeID',
        type: 'string'
    },
    {
        name: 'contactType',
        type: 'string'
    }
],

View GridEditPanel

emptyText: "There are no contacts.",
insertErrorText: 'Please finish editing the current contact before inserting a new record',
addButtonText: 'Add Contact',

itemId: 'contacts',
viewConfig: {
    deferEmptyText: false
},
minHeight: 130,

initComponent: function () {
    var me = this,
        contactTypes;

    // Creating store to be referenced by column renderer
    contactTypes = Ext.create('Ext.data.Store', {
        model: '********',
        autoLoad: true,
        listeners: {
            load: function () {
                me.getView().refresh();
            }
        }
    });

    this.columns = [
        {
            text: 'Contact Role',
            dataIndex: 'contactRoleID',
            flex: 1,
            renderer: function (value) {
                // Lookup contact type to get display value
                //If a contact has multiple roles, use split by ',' to find display values.
                if (value.includes(',')) {
                    var a = value.split(','), i, contTypeIds = [];
                    var contTypes = new Array();

                    for (i = 0; i < a.length; i++) {
                        contTypeIds.push(a[i]);
                        contTypes.push(contactTypes.findRecord('contactTypeID', a[i], 0, false, false, true).get('contactType'));
                    }
                    console.log('Multi Render Return Value: ' + contTypes);
                    return contTypes;
                }
                else {//if not a contact will only have one role.
                    var rec = contactTypes.findRecord('contactTypeID', value, 0, false, false, true); // exact match
                    console.log('Single Render Return Value: ' + rec.get('contactType'));
                    return rec ? rec.get('contactType') : 'Required';
                }
            },
            align: 'center',
            autoSizeColumn: true,
            editor: {
                xtype: 'combobox',
                store: contactTypes,
                multiSelect: true,
                delimiter: ',',
                forceSelection: true,
                queryMode: 'local',
                displayField: 'contactType',
                valueField: 'contactTypeID',
                allowBlank: false
            }
        },


问:
CSS background image on top of
How does one repeat this 1px x 1px CSS background image on top of the HTML ?

http://jsfiddle.net/hjv74tdw/1/

I came across CSS show div background image on top of other contained elements, however it seems to require an extra div. Ideally I wish I didn't have to use a div at all, but according to CSS Background-image over HTML img that's not really possible, at least not for a 100% width responsive scenario.

.test {
  background: url(http://placehold.it/1/1) repeat;
  position: relative;
  z-index: 100;
  width: 200px;
}
.test img {
  width: 100%;
  display: block;
  position: absolute;
  z-index: 50;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test">
    <img src="http://lorempixel.com/400/400">
</div></code>```

答:
Here's what I did for my solution. Essentially, I'm using the "IMG" as a placeholder. So that my Background image maintains the correct proportions as the browser resizes.

```<code>.image-overlay {
  background-image: url("insert image here");
  display: inline-block;
  position: relative;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
.image-overlay img {
  opacity: 0;
}
</code>```

HTML

```<code><div class="category-overlay">
    <img src="/images/placeholder.jpg" alt="">
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Title: CSS background image on top of <img>

Body:
Here's what I did for my solution. Essentially, I'm using the "IMG" as a placeholder. So that my Background image maintains the correct proportions as the browser resizes.

.image-overlay {
  background-image: url("insert image here");
  display: inline-block;
  position: relative;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
.image-overlay img {
  opacity: 0;
}

HTML

<div class="category-overlay">
    <img src="/images/placeholder.jpg" alt="">
</div>


问:
Implementing a cache
I'm trying to implement a transparent cache that can load a specific object when it's not available, or return an already existing object indexed by (name).

I've tried running this:

```<code>loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs)
  Just obj →  (obj, loader' objs)
  where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
loader = loader' []
</code>```

but I'm getting a

```
Occurs check: cannot construct the infinite type:
  t = (ObjType, String -> t)
```

which looks exactly like something I want :)

How can I fix the function so that it compiles?

Clarifications:

As requested, signatures (findObj either returns a known value found via a key, or Nothing, readObj creates a new obj for a key):

```<code>findObj :: [(String, ObjType)] -> String -> Maybe ObjType
readObj :: String -> ObjType
</code>```

And yes - I need a cache, because the keys are filenames and I don't want to read+parse the file each time some object is needed.

答:
Haskell doesn't support types like this:

```<code>type t = Int -> t
</code>```

This is because the compiler tries to unfold this type, to type check it. Since the type system is quit strict, this would result in an infinite loop during type checking. Now it would be nice to have a more lazy type system, than you would be able to do this, but, that's not has Haskell at the moment.

However, as MarkusQ says, its easier just to change what the loader' function does. I think I would write it something like this:

```<code>type Cache = [(String, ObjType)]

loader' :: Cache -> String -> (ObjType, Cache)
</code>```

That is a function taking the cache and the search string, returning both the answer and the (possibly updated) cache.

OwnerDisplayName: viraptor

ContentLicense: CC BY-SA 2.5

Title: Implementing a cache

Body:
I'm trying to implement a transparent cache that can load a specific object when it's not available, or return an already existing object indexed by (name).

I've tried running this:

loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs)
  Just obj →  (obj, loader' objs)
  where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
loader = loader' []

but I'm getting a

Occurs check: cannot construct the infinite type:
  t = (ObjType, String -> t)

which looks exactly like something I want :)

How can I fix the function so that it compiles?

Clarifications:

As requested, signatures (findObj either returns a known value found via a key, or Nothing, readObj creates a new obj for a key):

findObj :: [(String, ObjType)] -> String -> Maybe ObjType
readObj :: String -> ObjType

And yes - I need a cache, because the keys are filenames and I don't want to read+parse the file each time some object is needed.

LastEditorDisplayName: David Segonds

Body:
Haskell doesn't support types like this:

type t = Int -> t

This is because the compiler tries to unfold this type, to type check it. Since the type system is quit strict, this would result in an infinite loop during type checking. Now it would be nice to have a more lazy type system, than you would be able to do this, but, that's not has Haskell at the moment.

However, as MarkusQ says, its easier just to change what the loader' function does. I think I would write it something like this:

type Cache = [(String, ObjType)]

loader' :: Cache -> String -> (ObjType, Cache)

That is a function taking the cache and the search string, returning both the answer and the (possibly updated) cache.

OwnerDisplayName: Tom Lokhorst


问:
ExtJS Create a component like editor of stackoverflow
I want to create a component on ExtJS like the editor that have stackoverflow for ask question (only Bold and Emphasis buttons). I think that should be an extension of textarea but i dont know how to select text selected and how to replace with tags+text. Please give me some ideas.

Thanks

答:
If you're talking about the ability to use asterisks for bullets and such, in that mode StackOverflow's editor uses something called "Markdown".

Here's one example of someone trying to make a markdown-based textarea with preview in Extjs:

http://www.sencha.com/learn/Extension:Ext.ux.MarkdownEditor

If you look around for other Markdown-related editors, you might find some ideas.  If you're instead looking for just an "Online Rich-Text Editor" there's plenty of those.

UPDATE 29-APR-2014: There's actually a project you should take a look at.  It's called "StackEdit":

https://stackedit.io

It's an open source initiative to supply a markdown editing component.  Not ExtJS based, but those who find this question may be interested in what they are doing it.

(I discovered it through one of SO's open-source-recruiting sidebar campaigns; advertising can be useful, apparently.)


问:
What is the type of a?
I have the following statement:

```<code>Prelude> :t error "Hello"
error "Hello" :: a
</code>```

that I would like to know, what is the type of a?

答:
a is a type variable, one that could be unified with any concrete type you like. Want to add error "Hello" to an Integer? OK.

```<code>> :t error "Hello" + (3 :: Integer)
error "Hello" + (3 :: Integer) :: Integer
</code>```

Want to prepend a Maybe Char value? No problem.

```<code>> :t Just 'c' : error "Hello"
Just 'c' : error "Hello" :: [Maybe Char]
</code>```

Whatever you want a to be, error will tell you it can return a value of that type.

Of course, this is a moot point, because error will never actually return.

```<code>> error "Hello" + (3 :: Integer)
*** Exception: Hello
CallStack (from HasCallStack):
  error, called at <interactive>:3:1 in interactive:Ghci1

> Just 'c' : error "Hello"
[Just 'c'*** Exception: Hello
CallStack (from HasCallStack):
  error, called at <interactive>:4:12 in interactive:Ghci1
</code>```

Especially in the last one: ghci starts to output a value of type [Maybe Char], and succeeds at outputting the first element, because (:) is non-strict in its second element. Not until an attempt is actually made to get the second value does error "Hello" get evaluated and its "bluff" is called. Rather than being able to match it against either [] or (:), a runtime exception occurs.

Title: What is the type of a?

Body:
I have the following statement:

Prelude> :t error "Hello"
error "Hello" :: a

that I would like to know, what is the type of a?

Body:
a is a type variable, one that could be unified with any concrete type you like. Want to add error "Hello" to an Integer? OK.

> :t error "Hello" + (3 :: Integer)
error "Hello" + (3 :: Integer) :: Integer

Want to prepend a Maybe Char value? No problem.

> :t Just 'c' : error "Hello"
Just 'c' : error "Hello" :: [Maybe Char]

Whatever you want a to be, error will tell you it can return a value of that type.

Of course, this is a moot point, because error will never actually return.

> error "Hello" + (3 :: Integer)
*** Exception: Hello
CallStack (from HasCallStack):
  error, called at <interactive>:3:1 in interactive:Ghci1

> Just 'c' : error "Hello"
[Just 'c'*** Exception: Hello
CallStack (from HasCallStack):
  error, called at <interactive>:4:12 in interactive:Ghci1

Especially in the last one: ghci starts to output a value of type [Maybe Char], and succeeds at outputting the first element, because (:) is non-strict in its second element. Not until an attempt is actually made to get the second value does error "Hello" get evaluated and its "bluff" is called. Rather than being able to match it against either [] or (:), a runtime exception occurs.


问:
Android SQLite query to return rows that contains certain text
I need a sqlite query for my local DB that returns all the rows of a table that contains a certain String in a column. The issue is I only have part of that String.

```<code>ID  COLUMN1   COLUMN2    COLUMN3
1  myString11111  timestamp   some_value
2. myString22222  timestamp   some_value
</code>```

So in the example above I only know myString which is only part of the content of COLUMN1.
Here is what I tried so far:

```<code>String myQuery = "select * from " +  MY_TABLE + " where " + COLUMN1 + " LIKE ? " + "' " + myString + " '";
</code>```

Using this query throws an exception

```<code>android.database.sqlite.SQLiteException: near "' foo '": syntax error (code 1): , while compiling: select * from my_table where COLUMN1 LIKE ? ' foo '
</code>```

Does anyone know is is possible to retrieve rows if only part of the content is known?
Thank you in advance!

答:
Since you use ? place holders for the parameters there is no need to concatenate them. You can pass them in the 2nd argument of the rawQuery() method:

```<code>String myQuery = "select * from " +  MY_TABLE + " where " + COLUMN1 + " LIKE '%' || ? || '%'";
Cursor c = db.rawQuery(myQuery, new String[] {myString});
</code>```

where db is an instance of SQLiteDatabase.

The query will return all the rows that contain the value of the string myString in the column COLUMN1.

You can do the same with the function INSTR() instead of the operator LIKE:

```<code>String myQuery = "select * from " +  MY_TABLE + " where instr(" + COLUMN1 + ", ?)";
</code>```

Body:
I need a sqlite query for my local DB that returns all the rows of a table that contains a certain String in a column. The issue is I only have part of that String.

ID  COLUMN1   COLUMN2    COLUMN3
1  myString11111  timestamp   some_value
2. myString22222  timestamp   some_value

So in the example above I only know myString which is only part of the content of COLUMN1.
Here is what I tried so far:

String myQuery = "select * from " +  MY_TABLE + " where " + COLUMN1 + " LIKE ? " + "' " + myString + " '";

Using this query throws an exception

android.database.sqlite.SQLiteException: near "' foo '": syntax error (code 1): , while compiling: select * from my_table where COLUMN1 LIKE ? ' foo '

Does anyone know is is possible to retrieve rows if only part of the content is known?
Thank you in advance!

Body:
Since you use ? place holders for the parameters there is no need to concatenate them. You can pass them in the 2nd argument of the rawQuery() method:

String myQuery = "select * from " +  MY_TABLE + " where " + COLUMN1 + " LIKE '%' || ? || '%'";
Cursor c = db.rawQuery(myQuery, new String[] {myString});

where db is an instance of SQLiteDatabase.

The query will return all the rows that contain the value of the string myString in the column COLUMN1.

You can do the same with the function INSTR() instead of the operator LIKE:

String myQuery = "select * from " +  MY_TABLE + " where instr(" + COLUMN1 + ", ?)";


问:
v-tabs and vue-router reuses components on Vue.js
This is my original component (called 'Main'), it basically displays 3 sub-components driven by tabs, 2 of which are the same type. And this all works fine:

<v-tabs v-model="tab">
    <v-tab key='scenario'>Scenario</v-tab>
    <v-tab key='primary'>Primary</v-tab>
    <v-tab key='spouse'>Spouse</v-tab>
</v-tabs>

<v-tabs-items>
    <v-tab-item key='scenario'>
        <ScenarioView></ScenarioView>
        </v-tab-item>
    <v-tab-item key='primary'>
        <CustomerView :isPrimary="true"></CustomerView>
    </v-tab-item>
    <v-tab-item key='spouse'>
        <CustomerView :isPrimary="false"></CustomerView>
    </v-tab-item>
</v-tabs-items>

```

<p>However, one of the problems with tab navigation is you don't get browser history, so I wanted to add that using vue-router. From some googling, I ended up with:</p>

<pre class="lang-html prettyprint-override"><code><v-tabs v-model="tab">
    <v-tab key='scenario' to='/main/scenario'>Scenario</tab>
    <v-tab key='primary' to='/main/primary'>Primary</v-tab>
    <v-tab key='spouse' to='/main/spouse'>Spouse</v-tab>
</v-tabs>
<router-view></router-view>
</code>```

And this works fine, except that it looks like the CustomerView component is being reused, i don't get separate components. I think this is expected behavior.

The snippet from my router/index.js:

```<code>// ...
path: '/main',
name: 'Main',
component: Main,
children: [
    {
      path: 'scenario',
      component: ScenarioView
    },
    {
      path: 'primary',
      component: CustomerView,
      props: { isPrimary: true }
    },
    {
      path: 'spouse',
      component: CustomerView,
      props: { isPrimary: false }
    },
  ]
</code>```

So, is there some way to NOT have vue-router reuse a component? Or is there a better way to add vue-router navigation to vuetify v-tabs?

Thx.

答:
Add a :key to <router-view> :

```<code><v-tabs v-model="tab">
    <v-tab key='scenario' to='/main/scenario'>Scenario</tab>
    <v-tab key='primary' to='/main/primary'>Primary</v-tab>
    <v-tab key='spouse' to='/main/spouse'>Spouse</v-tab>
</v-tabs>
<router-view :key="$route.path"></router-view>
</code>```

Body:
This is my original component (called 'Main'), it basically displays 3 sub-components driven by tabs, 2 of which are the same type. And this all works fine:

<v-tabs v-model="tab">
    <v-tab key='scenario'>Scenario</v-tab>
    <v-tab key='primary'>Primary</v-tab>
    <v-tab key='spouse'>Spouse</v-tab>
</v-tabs>

<v-tabs-items>
    <v-tab-item key='scenario'>
        <ScenarioView></ScenarioView>
        </v-tab-item>
    <v-tab-item key='primary'>
        <CustomerView :isPrimary="true"></CustomerView>
    </v-tab-item>
    <v-tab-item key='spouse'>
        <CustomerView :isPrimary="false"></CustomerView>
    </v-tab-item>
</v-tabs-items>

However, one of the problems with tab navigation is you don't get browser history, so I wanted to add that using vue-router. From some googling, I ended up with:

<v-tabs v-model="tab">
    <v-tab key='scenario' to='/main/scenario'>Scenario</tab>
    <v-tab key='primary' to='/main/primary'>Primary</v-tab>
    <v-tab key='spouse' to='/main/spouse'>Spouse</v-tab>
</v-tabs>
<router-view></router-view>

And this works fine, except that it looks like the CustomerView component is being reused, i don't get separate components. I think this is expected behavior.

The snippet from my router/index.js:

// ...
path: '/main',
name: 'Main',
component: Main,
children: [
    {
      path: 'scenario',
      component: ScenarioView
    },
    {
      path: 'primary',
      component: CustomerView,
      props: { isPrimary: true }
    },
    {
      path: 'spouse',
      component: CustomerView,
      props: { isPrimary: false }
    },
  ]

So, is there some way to NOT have vue-router reuse a component? Or is there a better way to add vue-router navigation to vuetify v-tabs?

Thx.

Body:
Add a :key to <router-view> :

<v-tabs v-model="tab">
    <v-tab key='scenario' to='/main/scenario'>Scenario</tab>
    <v-tab key='primary' to='/main/primary'>Primary</v-tab>
    <v-tab key='spouse' to='/main/spouse'>Spouse</v-tab>
</v-tabs>
<router-view :key="$route.path"></router-view>


问:
Metronic Datatable with Laravel and many-to-many relationship
I have the following problem:

I have a many-to-many relationship between customers and branches. This is tested and is working. However now i wan't to use this relationship to display the name of the branch in the customers datatable.

I am getting this error:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'branches.name' in 'field list' (SQL: select customers.*, branches.name from customers where customers.deleted_at is null order by id asc limit 50 offset 0)"

I am not sure how to select the right table alongside the customers table.

This is the controller method responsible for calling the datatable class:

```<code>public function fetch(Request $request) {
    Notification::visit(CustomersRetrieved::class);
    return response()->json((new CustomerDatatable($request))->render());
}
</code>```

This is the datatable class:

```<code><?php
/**
 * Created by PhpStorm.
 * User: NEWPC-1
 * Date: 4-1-2019
 * Time: 08:31
 */

namespace Modules\CRM\Datatables;

use App\Support\Datatables\Datatable;
use App\Support\Datatables\DatatableContract;
use Illuminate\Support\Facades\Log;
use Modules\CRM\Models\Customer;

class CustomerDatatable extends Datatable implements DatatableContract
{
    /**
     * @return mixed|string
     */
    public function model()
    {
        return Customer::class;
    }

    /**
     * @return array|mixed
     */
    public function orders()
    {
        return [
            'code' => 'code',
            'name' => 'name',
            'branch' => 'branch',
            'email' => 'email',
            'phone_number' => 'phone_number',
            'postal_code' => 'postal_code',
            'city' => 'city',
            'address' => 'address',
            'address_number' => 'address_number',
        ];
    }

    /**
     * @return mixed
     */
    protected function newQuery()
    {
        $query = parent::newQuery()->with('branches')->select(['customers.*','branches.name']);
        Log::info(json_encode($query));
        if(isset($this->input['query']) && strlen($q = $this->input['query']) > 0) {
            $query->search($q);
        }
        return $query;
    }

    /**
     * @return mixed
     */
    protected function getQueryCount()
    {
        $query = parent::newQuery();

        if(isset($this->input['query']) && strlen($q = $this->input['query']) > 0) {
            $query->search($q);
        }
        return $query->count();
    }

    public function exportable()
    {
        return [
            ['key' => 'name'],
            ['key' => 'branch'],
            ['key' => 'address'],
            ['key' => 'address_number'],
            ['key' => 'postal_code'],
            ['key' => 'city'],
        ];
    }
}
</code>```

And this is the corresponding javascript:

```<code>customer_datatable = customer_element.CustomDataTable({
        rows: {
            beforeTemplate: function (row, data, index) {
                row.on('click', function (e) {
                    if ($(e.target).hasClass('kt-badge--info') || $(e.target).hasClass('la') || $(e.target).hasClass('fa') || $(e.target).hasClass('btn') || $(e.target).hasClass('kt-datatable__cell--center')) {
                    } else {
                        window.open(customer_element.data('route-url') + '/crm/customers/' + data.id, '_blank');
                    }
                });
            },
        },
        detail: {
            title: customer_element.data('text-load_contacts'),
            content: contactsInit,
        },
        columns: [
            {
                field: 'id',
                title: '',
                sortable: false,
                width: 20,
                textAlign: 'center',
            },
            {
                field: 'code',
                width: 75,
                title: customer_element.data('column-code'),
                template: function (row) {
                    return row.code;
                }
            },
            {
                field: 'name',
                title: customer_element.data('column-name'),
                width: 300,
                template: function (row) {
                    return '<a href="' + customer_element.data('route-show').replace('__id__', row.id) + '">' + row.name + '</a>';
                }
            },
    //this is the part causing/part of the problem
            {
                field: 'branch',
                title: customer_element.data('column-branch'),
                width: 300,
                template: function (row) {
                    console.log(row);
                }
            },
            {
                field: 'email',
                title: customer_element.data('column-email'),
                width: 250,
                template: function (row) {
                    if (row.email === '') {
                        return '';
                    }
                    var e = row.email.split(','), r = new Array();

                    $.each(e, function (i, x) {
                        r.push('<a href="mailto:' + $.trim(x) + '" class="kt-badge kt-badge--info  kt-badge--inline kt-badge--pill">' + $.trim(x) + '</a>');
                    });
                    return '<span style="line-height:2rem !important;"  title="E-mail this customer">' + r.join('   ') + '</span>';
                }
            },
            {
                field: 'phone_number',
                title: customer_element.data('column-phone_number'),
                width: 100,
                template: function (row) {
                    if (row.phone_number.length === 0) {
                        return '';
                    }
                    let number = parsePhoneNumber(row.phone_number);

                    return '<a href="tel:' + phoneUtil.format(number, PNF.E164) + '" class="kt-badge kt-badge--brand  kt-badge--inline kt-badge--pill">' + phoneUtil.format(number, PNF.NATIONAL) + '</a>';
                }
            },
            {
                field: 'postal_code',
                title: customer_element.data('column-postal_code'),
                width: 100,
                template: function (row) {
                    return row.postal_code;
                }
            },
            {
                field: 'city',
                title: customer_element.data('column-city'),
                width: 100,
                template: function (row) {
                    return row.city;
                }
            },
        ],
    });
</code>```

So this is how i finally solved it thanks to Ali Alghozali and this post:
MySQL join many to many single row

```<code>protected function newQuery()
    {
        $query = parent::newQuery()
                ->leftJoin('branch_customers', 'customers.id', '=', 'branch_customers.customer_id')
                ->leftJoin('branches', 'branches.id', '=', 'branch_customers.branch_id')
                ->select(['customers.*','branches.name as branch']);
        Log::info(json_encode($query));
        if(isset($this->input['query']) && strlen($q = $this->input['query']) > 0) {
            $query->search($q);
        }
        return $query;
    }
</code>```

答: You can't select column in with tables. You need to use join or leftJoin instead.

Body:
I have the following problem:

I have a many-to-many relationship between customers and branches. This is tested and is working. However now i wan't to use this relationship to display the name of the branch in the customers datatable.

I am getting this error:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'branches.name' in 'field list' (SQL: select customers.*, branches.name from customers where customers.deleted_at is null order by id asc limit 50 offset 0)"

I am not sure how to select the right table alongside the customers table.

This is the controller method responsible for calling the datatable class:

public function fetch(Request $request) {
    Notification::visit(CustomersRetrieved::class);
    return response()->json((new CustomerDatatable($request))->render());
}

This is the datatable class:

<?php
/**
 * Created by PhpStorm.
 * User: NEWPC-1
 * Date: 4-1-2019
 * Time: 08:31
 */

namespace Modules\CRM\Datatables;

use App\Support\Datatables\Datatable;
use App\Support\Datatables\DatatableContract;
use Illuminate\Support\Facades\Log;
use Modules\CRM\Models\Customer;

class CustomerDatatable extends Datatable implements DatatableContract
{
    /**
     * @return mixed|string
     */
    public function model()
    {
        return Customer::class;
    }

    /**
     * @return array|mixed
     */
    public function orders()
    {
        return [
            'code' => 'code',
            'name' => 'name',
            'branch' => 'branch',
            'email' => 'email',
            'phone_number' => 'phone_number',
            'postal_code' => 'postal_code',
            'city' => 'city',
            'address' => 'address',
            'address_number' => 'address_number',
        ];
    }

    /**
     * @return mixed
     */
    protected function newQuery()
    {
        $query = parent::newQuery()->with('branches')->select(['customers.*','branches.name']);
        Log::info(json_encode($query));
        if(isset($this->input['query']) && strlen($q = $this->input['query']) > 0) {
            $query->search($q);
        }
        return $query;
    }

    /**
     * @return mixed
     */
    protected function getQueryCount()
    {
        $query = parent::newQuery();

        if(isset($this->input['query']) && strlen($q = $this->input['query']) > 0) {
            $query->search($q);
        }
        return $query->count();
    }

    public function exportable()
    {
        return [
            ['key' => 'name'],
            ['key' => 'branch'],
            ['key' => 'address'],
            ['key' => 'address_number'],
            ['key' => 'postal_code'],
            ['key' => 'city'],
        ];
    }
}

And this is the corresponding javascript:

customer_datatable = customer_element.CustomDataTable({
        rows: {
            beforeTemplate: function (row, data, index) {
                row.on('click', function (e) {
                    if ($(e.target).hasClass('kt-badge--info') || $(e.target).hasClass('la') || $(e.target).hasClass('fa') || $(e.target).hasClass('btn') || $(e.target).hasClass('kt-datatable__cell--center')) {
                    } else {
                        window.open(customer_element.data('route-url') + '/crm/customers/' + data.id, '_blank');
                    }
                });
            },
        },
        detail: {
            title: customer_element.data('text-load_contacts'),
            content: contactsInit,
        },
        columns: [
            {
                field: 'id',
                title: '',
                sortable: false,
                width: 20,
                textAlign: 'center',
            },
            {
                field: 'code',
                width: 75,
                title: customer_element.data('column-code'),
                template: function (row) {
                    return row.code;
                }
            },
            {
                field: 'name',
                title: customer_element.data('column-name'),
                width: 300,
                template: function (row) {
                    return '' + row.name + '';
                }
            },
    //this is the part causing/part of the problem
            {
                field: 'branch',
                title: customer_element.data('column-branch'),
                width: 300,
                template: function (row) {
                    console.log(row);
                }
            },
            {
                field: 'email',
                title: customer_element.data('column-email'),
                width: 250,
                template: function (row) {
                    if (row.email === '') {
                        return '';
                    }
                    var e = row.email.split(','), r = new Array();

                    $.each(e, function (i, x) {
                        r.push('' + $.trim(x) + '');
                    });
                    return '' + r.join('   ') + '';
                }
            },
            {
                field: 'phone_number',
                title: customer_element.data('column-phone_number'),
                width: 100,
                template: function (row) {
                    if (row.phone_number.length === 0) {
                        return '';
                    }
                    let number = parsePhoneNumber(row.phone_number);

                    return '' + phoneUtil.format(number, PNF.NATIONAL) + '';
                }
            },
            {
                field: 'postal_code',
                title: customer_element.data('column-postal_code'),
                width: 100,
                template: function (row) {
                    return row.postal_code;
                }
            },
            {
                field: 'city',
                title: customer_element.data('column-city'),
                width: 100,
                template: function (row) {
                    return row.city;
                }
            },
        ],
    });

So this is how i finally solved it thanks to Ali Alghozali and this post:
MySQL join many to many single row

protected function newQuery()
    {
        $query = parent::newQuery()
                ->leftJoin('branch_customers', 'customers.id', '=', 'branch_customers.customer_id')
                ->leftJoin('branches', 'branches.id', '=', 'branch_customers.branch_id')
                ->select(['customers.*','branches.name as branch']);
        Log::info(json_encode($query));
        if(isset($this->input['query']) && strlen($q = $this->input['query']) > 0) {
            $query->search($q);
        }
        return $query;
    }


答:
a is the type; that is, error "Hello" can be any type, and GHCi can't tell you what specific type it should be without more context.

Values of type a (with no constraints, not e.g. Eq a => a) are called "bottom values," and they arise as exceptional states or certain non-terminating expressions. Perhaps the best-known bottom value is Prelude.undefined:

```<code>undefined :: a
</code>```

Trying to examine this value will throw

```<code>*** Exception: Prelude.undefined
</code>```

Likewise, your error "Hello" will throw

```<code>*** Exception: Hello
</code>```

(Thus undefined is just error "Prelude.undefined".) An example of a nonterminating expression with type a is:

```<code>let q = q in q
:t q
q :: a
</code>```

And attempting to evaluate that expression will enter an infinite loop.

Title: What is the type of a?

Body:
a is the type; that is, error "Hello" can be any type, and GHCi can't tell you what specific type it should be without more context.

Values of type a (with no constraints, not e.g. Eq a => a) are called "bottom values," and they arise as exceptional states or certain non-terminating expressions. Perhaps the best-known bottom value is Prelude.undefined:

undefined :: a

Trying to examine this value will throw

*** Exception: Prelude.undefined

Likewise, your error "Hello" will throw

*** Exception: Hello

(Thus undefined is just error "Prelude.undefined".) An example of a nonterminating expression with type a is:

let q = q in q
:t q
q :: a

And attempting to evaluate that expression will enter an infinite loop.


问:
how to detect Empty paragraph in Word Document using Microsoft.Office.Interop.Word in C#4.0?
I want to detect Empty paragraphs in Word Document using Microsoft.Office.Interop.Word.
Suppose, if my word document have some empty paragraphs,then

Assume paragraph 3 is an empty paragraph...

```<code>Microsoft.Office.Interop.Word.Paragraph para = wordDoc.Content.Paragraphs[3];
int cSent = para.Range.Sentences.Count;

for (int j = 1; j <= cSent; j++)
{
 Microsoft.Office.Interop.Word.Range sent = para.Range.Sentences[j];
 MessageBox.Show("Sent lines :" + sent.Text.ToString());
}
</code>```

Then empty paragraphs has taken the last sentence of the last non-empty paragraph.So, I can't able to detect empty paragraphs in my Word Document.

Is there a way to get Empty paragraph list?

Please Guide me to Get out of this problem...

答:
Well, first, you may need to iterate through all the headers and footers of all sections if you also want to look for empty paras in those headers/footers.

Second, something like this should work

```<code>for each p in Doc.Content.Paragraphs
    if (p.Range.End - p.Range.Start) > 1 then (The paragraph is not empty)
Next
</code>```

You may need to play with that "1" number, because I can't recall where Word sets the start and end points, empty paragraphs may be 2 chars long from start to end, not just one.

You can also do things like

```<code>p.Range.Sentences.Count > 0
</code>```

or

```<code>p.Range.Characters.Count > 0
</code>```

But those techniques are typically slower than checking the start and end positions.

Body:
I want to detect Empty paragraphs in Word Document using Microsoft.Office.Interop.Word.
Suppose, if my word document have some empty paragraphs,then

Assume paragraph 3 is an empty paragraph...

Microsoft.Office.Interop.Word.Paragraph para = wordDoc.Content.Paragraphs[3];
int cSent = para.Range.Sentences.Count;

for (int j = 1; j <= cSent; j++)
{
 Microsoft.Office.Interop.Word.Range sent = para.Range.Sentences[j];
 MessageBox.Show("Sent lines :" + sent.Text.ToString());
}

Then empty paragraphs has taken the last sentence of the last non-empty paragraph.So, I can't able to detect empty paragraphs in my Word Document.

Is there a way to get Empty paragraph list?

Please Guide me to Get out of this problem...

Body:
Well, first, you may need to iterate through all the headers and footers of all sections if you also want to look for empty paras in those headers/footers.

Second, something like this should work

for each p in Doc.Content.Paragraphs
    if (p.Range.End - p.Range.Start) > 1 then (The paragraph is not empty)
Next

You may need to play with that "1" number, because I can't recall where Word sets the start and end points, empty paragraphs may be 2 chars long from start to end, not just one.

You can also do things like

p.Range.Sentences.Count > 0

or

p.Range.Characters.Count > 0

But those techniques are typically slower than checking the start and end positions.


问:
How to rewrite EF LINQ query that used to work in .NET Core 2.0 but doesn't in 3.0?
I am developing an online shop in .NET Core 3, following some tutorials delevoped with .NET CORE 2. EF LINQ is erroring after trying to execute this simple line of code:

```<code>var stocksToUpdate = _context.Stock
                             .Where(x => request.Stocks
                                                .Any(y => y.StockId == x.Id))
                             .ToList();
</code>```

I got the following error:

InvalidOperationException: The LINQ expression 'DbSet<Stock> .Where(s
  => __request_Stocks_0 .Any(y => y.StockId == s.Id))' could not be translated. Either rewrite the query in a form that can be translated,
  or switch to client evaluation explicitly by inserting a call to
  either AsEnumerable(), AsAsyncEnumerable(), ToList(), or
  ToListAsync().

I honestly don't know how to write that query in a different way. I have tried to replace the .ToList() for .AsEnumerable as suggested, but it still erroring, same error. Does anyone know whats the fix in .NET Core 3?
Thanks in advance!

答:
It was "working" in EF Core 2.x because of the implicit client evaluation, which has been removed in 3.0. You can get the previous behavior by inserting AsEnumerable() before the reported problematic operator - in your case, Where:

```<code>var stocksToUpdate = _context.Stock
    .AsEnumerable()
    .Where(x => request.Stocks.Any(y => y.StockId == x.Id))
    .ToList();
</code>```

But the main reason for removing the implicit client evaluation is because it's inefficient - the filtering happens in memory after retrieving the whole table.

So rather than switching to client evaluation, it's always better to find a translatable construct.

The problem with your query is that request.Stocks is a in-memory collection, and EF Core supports only in-memory collections of primitive values, and basically Contains method. So the following works

```<code>var stocksToUpdate = _context.Stock
    .Where(x => request.Stocks.Select(y => y.StockId).Contains(x.Id))
    .ToList();
</code>```

You could also use

```<code>.Where(x => request.Stocks.Select(y => y.StockId).Any(y => y == x.Id))
</code>```

The essential part here is to convert the in-memory complex object enumerable to single primitive value enumerable before "calling" it with Contains or Any on it.

Body:
I am developing an online shop in .NET Core 3, following some tutorials delevoped with .NET CORE 2. EF LINQ is erroring after trying to execute this simple line of code:

var stocksToUpdate = _context.Stock
                             .Where(x => request.Stocks
                                                .Any(y => y.StockId == x.Id))
                             .ToList();

I got the following error:

InvalidOperationException: The LINQ expression 'DbSet<Stock> .Where(s
  => __request_Stocks_0 .Any(y => y.StockId == s.Id))' could not be translated. Either rewrite the query in a form that can be translated,
  or switch to client evaluation explicitly by inserting a call to
  either AsEnumerable(), AsAsyncEnumerable(), ToList(), or
  ToListAsync().

I honestly don't know how to write that query in a different way. I have tried to replace the .ToList() for .AsEnumerable as suggested, but it still erroring, same error. Does anyone know whats the fix in .NET Core 3?
Thanks in advance!

Body:
It was "working" in EF Core 2.x because of the implicit client evaluation, which has been removed in 3.0. You can get the previous behavior by inserting AsEnumerable() before the reported problematic operator - in your case, Where:

var stocksToUpdate = _context.Stock
    .AsEnumerable()
    .Where(x => request.Stocks.Any(y => y.StockId == x.Id))
    .ToList();

But the main reason for removing the implicit client evaluation is because it's inefficient - the filtering happens in memory after retrieving the whole table.

So rather than switching to client evaluation, it's always better to find a translatable construct.

The problem with your query is that request.Stocks is a in-memory collection, and EF Core supports only in-memory collections of primitive values, and basically Contains method. So the following works

var stocksToUpdate = _context.Stock
    .Where(x => request.Stocks.Select(y => y.StockId).Contains(x.Id))
    .ToList();

You could also use

.Where(x => request.Stocks.Select(y => y.StockId).Any(y => y == x.Id))

The essential part here is to convert the in-memory complex object enumerable to single primitive value enumerable before "calling" it with Contains or Any on it.


问:
Lazy/Enforced Initialization of Primitive Typed Property in C#
Often when coding in C# I like to use this pattern for a lazy getter property:

```<code>private string _myProp;
string MyProp => _myProp ?? (_myProp = getMyProp());
</code>```

I think this is pretty standard C# practice. The function getMyProp() is just some function that computes and returns a string. It is called just once to initialize the property, and henceforth it's cached. I can use this for any object type I like, not just string. However, when I try to do it for a primitive type like an int, I run into an issue. For example, if I try the following:

```<code>private int _operationCount;
int OperationCount => _operationCount ?? (_operationCount = GetOperationCountFromUser());
</code>```

I get a compiler error here. It says:

Error CS0019  Operator '??' cannot be applied to operands of type 'int' and 'int'

I understand the error means that int is a primitive type, so we can't apply the null-checking operator to it, because an int is never null. But is there any way I can achieve what I want here? I'm looking for a solution with the following:

On the first access, the int property is initialized to the return value of the function call.

On subsequent accesses, the int property is retrieved from a loaded variable in memory i.e. the function is not called again.

Update: Why Write Properties Like This?

The original question just cited "laziness" as the reason for writing one of these properties, but as I collaborated on this question I realised that probably the primary use case I have for the above pattern using the ?? operator is enforced initialization. By forcing initialization of a property this way, it'll always be initialized the first time you access it. Meaning you don't have to worry about injecting an initial value into multiple constructors- which clutters them up on the one hand and also isn't reliable because you might forget to initialize in one of the constructors.

答:
I personally don't see anything bad in accessing lazy object through Value (at least it shows you explicitly that there can be a delay when you getting the value). But you can skip even this and become very lazy. Unfortunately, you cannot define an implicit operator for conversion between two third party types, but you can inherit from Lazy<T> and define an implicit conversion for your type:

```<code>public class VeryLazy<T> : Lazy<T>
{
    public VeryLazy(Func<T> valueFactory) : base(valueFactory) { }
    public static implicit operator T (VeryLazy<T> lazy) => lazy.Value;
}
</code>```

And usage becomes very lazy - you can use operationCount whenever you want to use int:

```<code>class X
{
 private readonly VeryLazy<int> _operationCount = new VeryLazy(GetOperationCountFromUser);
 public int OperationCount => _operationCount; // implicit conversion to int
 private static int GetOperationCountFromUser() => 38;
}
</code>```

But I'm not that lazy, and I find code without implicit conversions more readable

```<code>class X
{
 private readonly Lazy<int> _operationCount = new Lazy(GetOperationCountFromUser);
 public int OperationCount => _operationCount.Value; // we see there can be delay
 private static int GetOperationCountFromUser() => 38;
}
</code>```

Also Lazy<T> is better than using nullable types. Sometimes object which initialization you defer might not be available - lazy would return null in that case (e.g. when you tried to get something from the database, but there is no value). What would nullable field tell you in that case? You might end up trying to initialize it on each property access.

Body:
Often when coding in C# I like to use this pattern for a lazy getter property:

private string _myProp;
string MyProp => _myProp ?? (_myProp = getMyProp());

I think this is pretty standard C# practice. The function getMyProp() is just some function that computes and returns a string. It is called just once to initialize the property, and henceforth it's cached. I can use this for any object type I like, not just string. However, when I try to do it for a primitive type like an int, I run into an issue. For example, if I try the following:

private int _operationCount;
int OperationCount => _operationCount ?? (_operationCount = GetOperationCountFromUser());

I get a compiler error here. It says:

Error CS0019  Operator '??' cannot be applied to operands of type 'int' and 'int'

I understand the error means that int is a primitive type, so we can't apply the null-checking operator to it, because an int is never null. But is there any way I can achieve what I want here? I'm looking for a solution with the following:

On the first access, the int property is initialized to the return value of the function call.

On subsequent accesses, the int property is retrieved from a loaded variable in memory i.e. the function is not called again.

Update: Why Write Properties Like This?

The original question just cited "laziness" as the reason for writing one of these properties, but as I collaborated on this question I realised that probably the primary use case I have for the above pattern using the ?? operator is enforced initialization. By forcing initialization of a property this way, it'll always be initialized the first time you access it. Meaning you don't have to worry about injecting an initial value into multiple constructors- which clutters them up on the one hand and also isn't reliable because you might forget to initialize in one of the constructors.

Body:
I personally don't see anything bad in accessing lazy object through Value (at least it shows you explicitly that there can be a delay when you getting the value). But you can skip even this and become very lazy. Unfortunately, you cannot define an implicit operator for conversion between two third party types, but you can inherit from Lazy<T> and define an implicit conversion for your type:

public class VeryLazy<T> : Lazy<T>
{
    public VeryLazy(Func<T> valueFactory) : base(valueFactory) { }
    public static implicit operator T (VeryLazy<T> lazy) => lazy.Value;
}

And usage becomes very lazy - you can use operationCount whenever you want to use int:

class X
{
 private readonly VeryLazy<int> _operationCount = new VeryLazy(GetOperationCountFromUser);
 public int OperationCount => _operationCount; // implicit conversion to int
 private static int GetOperationCountFromUser() => 38;
}

But I'm not that lazy, and I find code without implicit conversions more readable

class X
{
 private readonly Lazy<int> _operationCount = new Lazy(GetOperationCountFromUser);
 public int OperationCount => _operationCount.Value; // we see there can be delay
 private static int GetOperationCountFromUser() => 38;
}

Also Lazy<T> is better than using nullable types. Sometimes object which initialization you defer might not be available - lazy would return null in that case (e.g. when you tried to get something from the database, but there is no value). What would nullable field tell you in that case? You might end up trying to initialize it on each property access.


问:
Can numpy bincount work with 2D arrays?
I am seeing behaviour with numpy bincount that I cannot make sense of.  I want to bin the values in a 2D array in a row-wise manner and see the behaviour below.  Why would it work with dbArray but fail with simarray?</p>

```<code>>>> dbArray
array([[1, 0, 1, 0, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 0, 1, 1],
       [1, 0, 0, 0, 0],
       [0, 0, 0, 1, 1],
       [0, 1, 0, 1, 0]])
>>> N.apply_along_axis(N.bincount,1,dbArray)
array([[2, 3],
       [0, 5],
       [1, 4],
       [4, 1],
       [3, 2],
       [3, 2]], dtype=int64)
>>> simarray
array([[2, 0, 2, 0, 2],
       [2, 1, 2, 1, 2],
       [2, 1, 1, 1, 2],
       [2, 0, 1, 0, 1],
       [1, 0, 1, 1, 2],
       [1, 1, 1, 1, 1]])
>>> N.apply_along_axis(N.bincount,1,simarray)

Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    N.apply_along_axis(N.bincount,1,simarray)
  File "C:\Python27\lib\site-packages\numpy\lib\shape_base.py", line 118, in apply_along_axis
    outarr[tuple(i.tolist())] = res
ValueError: could not broadcast input array from shape (2) into shape (3)
</code>```

答:
As @DSM has already mentioned, bincount of a 2d array cannot be done without knowing the maximum value of the array, because it would mean an inconsistency of array sizes.

But thanks to the power of numpy's indexing, it was fairly easy to make a faster implementation of 2d bincount, as it doesn't use concatenation or anything.

```<code>def bincount2d(arr, bins=None):
    if bins is None:
        bins = np.max(arr) + 1
    count = np.zeros(shape=[len(arr), bins], dtype=np.int64)
    indexing = (np.ones_like(arr).T * np.arange(len(arr))).T
    np.add.at(count, (indexing, arr), 1)

    return count
</code>```

Title: Can numpy bincount work with 2D arrays?

Body:
I am seeing behaviour with numpy bincount that I cannot make sense of.  I want to bin the values in a 2D array in a row-wise manner and see the behaviour below.  Why would it work with dbArray but fail with simarray?

>>> dbArray
array([[1, 0, 1, 0, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 0, 1, 1],
       [1, 0, 0, 0, 0],
       [0, 0, 0, 1, 1],
       [0, 1, 0, 1, 0]])
>>> N.apply_along_axis(N.bincount,1,dbArray)
array([[2, 3],
       [0, 5],
       [1, 4],
       [4, 1],
       [3, 2],
       [3, 2]], dtype=int64)
>>> simarray
array([[2, 0, 2, 0, 2],
       [2, 1, 2, 1, 2],
       [2, 1, 1, 1, 2],
       [2, 0, 1, 0, 1],
       [1, 0, 1, 1, 2],
       [1, 1, 1, 1, 1]])
>>> N.apply_along_axis(N.bincount,1,simarray)

Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    N.apply_along_axis(N.bincount,1,simarray)
  File "C:\Python27\lib\site-packages\numpy\lib\shape_base.py", line 118, in apply_along_axis
    outarr[tuple(i.tolist())] = res
ValueError: could not broadcast input array from shape (2) into shape (3)

Body:
As @DSM has already mentioned, bincount of a 2d array cannot be done without knowing the maximum value of the array, because it would mean an inconsistency of array sizes.

But thanks to the power of numpy's indexing, it was fairly easy to make a faster implementation of 2d bincount, as it doesn't use concatenation or anything.

def bincount2d(arr, bins=None):
    if bins is None:
        bins = np.max(arr) + 1
    count = np.zeros(shape=[len(arr), bins], dtype=np.int64)
    indexing = (np.ones_like(arr).T * np.arange(len(arr))).T
    np.add.at(count, (indexing, arr), 1)

    return count


答:
The thing with promises is that you cannot pull anything out of them, so every action with the response that you get by axios should be used with .then()

In your case it's price_data().then(data => console.log(data))

In the code above, you call price_data() function, which returns a promise with some data inside. After that you use .then(data => console.log(data)) to console that data

I hope it helps,

Cheers

EDIT:
You can use async/await to assign data from promise to variable, but you will need to wrap your function into an async function like this:

```<code>async function getData (url) { // this is an async wrapping function
  function price_data () { // this is a function that you already have
    return axios(url)
  }
  const result = await price_data() // assign the data from price_data() to a varible using await
  console.log(result) // console your variable
}
</code>```

Here you can learn more on async/await

I really hope it will help you

Title: Return Axios data so I can use it

Body:
I am pulling some data from a local API I made for testing, and need to use the resulting data outside of the function. I am new to JS and am having trouble working with Promises.
Here is my code:

const axios = require('axios').default;

function price_data () {
    return axios.post('http://127.0.0.1:8000/api/token/', {
      username: 'parke',
      password: 'password'
    })
    .then(function (response) {
      var token = response['data']['access'];
      return axios.get('http://127.0.0.1:8000/price', {
      headers:{'Authorization': 'Bearer ' + token}
    })
      .then(function (response) {
        var all_data = []
        for (i = 0; i < response['data'].length; i ++) {
          all_data.push(response['data'][i]['close'])
        }
        console.log(all_data);
        return(all_data)
      })
      .catch(function (error) {
        console.log(error)
    })
    .catch(function (error) {
      console.log(error);
    })
    })
}
console.log(price_data())

The result looks like this:

Promise { <pending> }
[
       1,      1,      1,      1,      1,      1,      1, 1.5907,
  1.5318, 1.5318, 1.5907, 1.5907, 1.5907, 1.5907, 1.5907, 1.5318,
  1.3551,  1.414,  1.414,  1.414,  1.414, 1.3551, 1.2372, 1.2372,
   1.414,  1.414, 1.3551,  1.414,  1.414,  1.414,  1.414,  1.414,
   1.414,  1.414,  1.414,  1.414,  1.414, 1.2961, 1.2961, 1.2961,
   1.414,  1.414,  1.414,  1.414,  1.414, 1.3551, 1.3551, 1.3551,
  1.3551, 1.3551, 1.3551, 1.3551, 1.3551, 1.2961, 1.2961, 1.2961,
  1.2961, 1.2961, 1.2961, 1.2961, 1.3551, 1.2961, 1.2961, 1.3551,
   1.414,  1.414,  1.414, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729,
  1.4729,  1.414,  1.414,  1.414,  1.414,  1.414,  1.414,  1.414,
   1.414,  1.414, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729,
  1.4729, 1.4729, 1.5907, 1.5613, 1.5907, 1.5465,  1.576, 1.5318,
  1.5318, 1.5539, 1.5907, 1.5907,
  ... 1101 more items
]

I kinda understand that the function is returning before the console.log prints, but I need to get that data that is being logged outside of the function. It would be greatly appreciated if someone could help me out real quick. Thanks!

Body:
The thing with promises is that you cannot pull anything out of them, so every action with the response that you get by axios should be used with .then()

In your case it's price_data().then(data => console.log(data))

In the code above, you call price_data() function, which returns a promise with some data inside. After that you use .then(data => console.log(data)) to console that data

I hope it helps,

Cheers

EDIT:
You can use async/await to assign data from promise to variable, but you will need to wrap your function into an async function like this:

async function getData (url) { // this is an async wrapping function
  function price_data () { // this is a function that you already have
    return axios(url)
  }
  const result = await price_data() // assign the data from price_data() to a varible using await
  console.log(result) // console your variable
}

Here you can learn more on async/await

I really hope it will help you


问:
Need some advice to choose the proper container
I'm trying to design a task scheduler to a game engine. A task could be an animation, a trigger controller, etc.

My problem is what container to choose. The idea is: when you insert a new task, the container must reorder and put the task in the proper place. Once executed, task could change and be scheduled again or deleted. This is mainly push and pop.

But, if possible, it would be nice if I could have random access to an element, but not vital. No matter if the container supports one or more elements with the same key.

I think that priority queue fits my needs but I saw that is based on vector implementation, and I think that this container must be somehow  optimized to push and pop.

Opinions?

答:
std::vector is pretty good for this task, especially if the "steady-state" size of the container remains reasonably constant (you have a number of tasks on the queue doesn't differ widely).

If you need an updatable queue (and std::priority_queue is not), I would suggest you use the d_ary_heap_indirect (which can be found in the Boost.Graph "detail" folder). This is a priority queue used a lot for Dijkstra and A* algorithms that require an updatable priority queue. Random-access is necessary, anyways. Also, using an indirect makes the insertion and deletion from the queue quite efficient. Finally, you can choose your container (as a template argument), but it has to be random-access (so, you can try either vector or deque). Pop is constant-time, push and/or update is log-time, and the proper choice of container will make the container insertion constant-amortized (and the d_ary_heap_indirect amortizes a second time as well, so I wouldn't worry about that).


问:
VS code runs python with no errors only if started from conda terminal
One of the projects that I work on in Python is pretty big and uses a lot of libraries.
I started developing it in Spyder then switched to VS Code.
I also use conda environment.

The problem is with VS Code only: when I open VS Code itself and try to run the project - I get all kinds of import errors.

However, if I open the conda terminal first and just type "code" in it and execute it - the VS Code opens, I can select my project and everything runs just fine, no errors.

In both cases the environment is the same, I did the Ctrl+Shift+P to select it, plus it shows as selected in the bottom left corner anyway. It's the default env.

How can I fix this so I don't have to start VS Code from conda terminal each time?

答:
at the conda the modules are installed by default.

in vscode or any other of ides you have to install it manually.

open your terminal or cmd and type:
pip install module-name


问:
How to persist Login with token?
Hello there I have created dotnet core web api for login and register but in the app after refresh it always tries to log in again. Since I am new to react native I could not apply solutions to my project. I use redux and here is my action :

```<code>export const signin = (email, password) => {
  return async dispatch => {
    const response = await fetch(
      'http://localhost:5000/api/user/login',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: email,
          password: password,

        }),
      }
    );

    if (!response.ok) {
      throw new Error('Something went wrong!');
    }

    const resData = await response.json();
    console.log(resData);
    dispatch({ type: SINGIN, token: resData.token, userId: resData.id });
    saveDataToStorage(resData.token);
  };
};

const saveDataToStorage = (token, userId) => {
  AsyncStorage.setItem('userData', JSON.stringify({
    token: token,
  })
  );
};
</code>```

And here is my navigator with react navigation 5 :

```<code>export const Navigator = () => {
    const [userToken, setUserToken] = React.useState(null);
    const userData = AsyncStorage.getItem('userData');

    const authContext = React.useMemo(() => {
        return {
            signIn: () => {
                setUserToken(userData);
            },
            singnUp: () => {
                setUserToken(userData);
            },
            signOut: () => {
                setUserToken(null);
            },
        };
    }, [userData]);

    return (
        <AuthContext.Provider value={authContext}>
            <NavigationContainer>
                <RootStackScreen userToken={userToken} />
            </NavigationContainer>
        </AuthContext.Provider >
    );
};
</code>```

As I said I could not find a way to apply solutions that I found. Thank you for you help.

答:
First, make sure all of your actions with AsyncStorage should be async(Use promise or async/await).

Then follow this to implement the authentication flow of your application.

https://reactnavigation.org/docs/auth-flow

My this answer will be helpful for you.

React Navigation 5 Auth Flow

Title: How to persist Login with token?

Body:
Hello there I have created dotnet core web api for login and register but in the app after refresh it always tries to log in again. Since I am new to react native I could not apply solutions to my project. I use redux and here is my action :

export const signin = (email, password) => {
  return async dispatch => {
    const response = await fetch(
      'http://localhost:5000/api/user/login',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: email,
          password: password,

        }),
      }
    );

    if (!response.ok) {
      throw new Error('Something went wrong!');
    }

    const resData = await response.json();
    console.log(resData);
    dispatch({ type: SINGIN, token: resData.token, userId: resData.id });
    saveDataToStorage(resData.token);
  };
};

const saveDataToStorage = (token, userId) => {
  AsyncStorage.setItem('userData', JSON.stringify({
    token: token,
  })
  );
};

And here is my navigator with react navigation 5 :

export const Navigator = () => {
    const [userToken, setUserToken] = React.useState(null);
    const userData = AsyncStorage.getItem('userData');

    const authContext = React.useMemo(() => {
        return {
            signIn: () => {
                setUserToken(userData);
            },
            singnUp: () => {
                setUserToken(userData);
            },
            signOut: () => {
                setUserToken(null);
            },
        };
    }, [userData]);

    return (
        <AuthContext.Provider value={authContext}>
            <NavigationContainer>
                <RootStackScreen userToken={userToken} />
            </NavigationContainer>
        </AuthContext.Provider >
    );
};

As I said I could not find a way to apply solutions that I found. Thank you for you help.


问:
Cannot use ng-repeat inside a directive's template
I cannot make my ng-repeat to work inside the directive template. It shows as "ngRepeat: day in days track by $index".

```
    angular
        .module('Auto')
        .directive('calendar', CalendarDirective);</p>

```CalendarDirective.$inject = ['$interpolate'];
CalendarDirectiveController.$inject = ['$scope', '$rootScope', '$attrs', '$location'];

function CalendarDirective($interpolate) {
    return {
        restrict: 'E',
        scope: true,
        template: $('#template-calendar').html(),
        replace: true,
        link: function(scope, element) {
            var startSym = $interpolate.startSymbol();
            var endSym = $interpolate.endSymbol();
            var rawExp = element.html();
            var transformedExp = rawExp.replace(/<@/g, startSym).replace(/@>/g, endSym);
            var parsedExp = $interpolate(transformedExp);
            scope.$watch(parsedExp, function(newValue) {
                element.html(newValue);
            });
        },
        controller: CalendarDirectiveController,
    };
}

function CalendarDirectiveController($scope, $rootScope, $attrs, $location) {
    $scope.monthText = moment().format('MM YYYY');
    $scope.days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

    $scope.title = function () {
        return 'Directive';
    }
}
```

<p><code></p>

<script type="text/html" id="template-calendar">
<div>
    <table>
        <thead>
        <tr ng-repeat="day in days track by $index">
            <th><@day@></th>
        </tr>
        </thead>
        <tbody>
        <tr>
        </tr>
        </tbody>
    </table>
</div>
</code>```

I'm currently out of ideas

Here is the plunker

答:
$interpolateProvider already does the job, a.e.

```<code>angular.module('plunker', [], function($interpolateProvider) {
        $interpolateProvider.startSymbol('<@');
        $interpolateProvider.endSymbol('@>');
})
</code>```

So you don't need a $watch inside a link.

```<code>function CalendarDirective($interpolate) {
    return {
        restrict: 'E',
        scope: true,
        template: $('#template-calendar').html(),
        replace: true,
        link: function(scope, element) {
           // removed
        },
        controller: CalendarDirectiveController,
    };
}
</code>```

Plunker Demo

Body:
I cannot make my ng-repeat to work inside the directive template. It shows as "ngRepeat: day in days track by $index".

    angular
        .module('Auto')
        .directive('calendar', CalendarDirective);

CalendarDirective.$inject = ['$interpolate'];
CalendarDirectiveController.$inject = ['$scope', '$rootScope', '$attrs', '$location'];

function CalendarDirective($interpolate) {
    return {
        restrict: 'E',
        scope: true,
        template: $('#template-calendar').html(),
        replace: true,
        link: function(scope, element) {
            var startSym = $interpolate.startSymbol();
            var endSym = $interpolate.endSymbol();
            var rawExp = element.html();
            var transformedExp = rawExp.replace(/<@/g, startSym).replace(/@>/g, endSym);
            var parsedExp = $interpolate(transformedExp);
            scope.$watch(parsedExp, function(newValue) {
                element.html(newValue);
            });
        },
        controller: CalendarDirectiveController,
    };
}

function CalendarDirectiveController($scope, $rootScope, $attrs, $location) {
    $scope.monthText = moment().format('MM YYYY');
    $scope.days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

    $scope.title = function () {
        return 'Directive';
    }
}

Body:
$interpolateProvider already does the job, a.e.

angular.module('plunker', [], function($interpolateProvider) {
        $interpolateProvider.startSymbol('<@');
        $interpolateProvider.endSymbol('@>');
})

So you don't need a $watch inside a link.

function CalendarDirective($interpolate) {
    return {
        restrict: 'E',
        scope: true,
        template: $('#template-calendar').html(),
        replace: true,
        link: function(scope, element) {
           // removed
        },
        controller: CalendarDirectiveController,
    };
}

Plunker Demo


问:
validation: date today in javascript
I have a problem with the today date. I have 2 checkings.

-The first validation is to avoid that the user enters a previous date to the today date. (my validation is ok)

-My second validation is to limit the dates to 2 years maximum (my validation is ok also)

My problem is that if I enter the today date, I get an error message. Normally, my date must be ok.

I think my problem is here?

```<code>const inputDate = new Date(date_start);
const today = new Date();

if (inputDate < today) {
    document.getElementById('date_startError').innerHTML = " ** Obsolete date ! ";
    return false;
}
</code>```

Thank you for your help and your time.

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start);
    const today = new Date();

    if (inputDate < today) {
        document.getElementById('date_startError').innerHTML = " ** Obsolete date ! ";
        return false;
    }

    const yearFromImputDate = inputDate.getFullYear();

    const now = new Date();
    const twoYearsFromNow = now.getFullYear() + 2;

    if(yearFromImputDate > twoYearsFromNow) {
        document.getElementById('date_startError').innerHTML = " ** Maximum 2 years ! ";
        return false;
    }

} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form>
</body>
</html></code>```

答:
Take off the timezone using Date.UTC() and set hours, minutes and seconds to zero.

By the way, add 2 years from today to compare max date, instead of only year.

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start);
    const today = new Date(Date.UTC(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), 0,0,0,0));

    if (inputDate < today) {
        console.log(inputDate, today);
        document.getElementById('date_startError').innerHTML = " ** Obsolete date ! ";
        return false;
    }

    const twoYearsFromNow = new Date(today);
    twoYearsFromNow.setYear(today.getFullYear() + 2);

    if(inputDate > twoYearsFromNow) {
        document.getElementById('date_startError').innerHTML = " ** Maximum 2 years ! ";
        return false;
    }

    console.log(inputDate, today, twoYearsFromNow);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form>
</body>
</html></code>```

Title: validation: date today in javascript

Body:
I have a problem with the today date. I have 2 checkings.

-The first validation is to avoid that the user enters a previous date to the today date. (my validation is ok)

-My second validation is to limit the dates to 2 years maximum (my validation is ok also)

My problem is that if I enter the today date, I get an error message. Normally, my date must be ok.

I think my problem is here?

const inputDate = new Date(date_start);
const today = new Date();

if (inputDate < today) {
    document.getElementById('date_startError').innerHTML = " ** Obsolete date ! ";
    return false;
}

Thank you for your help and your time.

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start);
    const today = new Date();

    if (inputDate < today) {
        document.getElementById('date_startError').innerHTML = " ** Obsolete date ! ";
        return false;
    }

    const yearFromImputDate = inputDate.getFullYear();

    const now = new Date();
    const twoYearsFromNow = now.getFullYear() + 2;

    if(yearFromImputDate > twoYearsFromNow) {
        document.getElementById('date_startError').innerHTML = " ** Maximum 2 years ! ";
        return false;
    }

}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">

<form action="#" onsubmit="return validation()" >

  Date start :

  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">

  <input type="submit" value="ok">
</form>

Body:
Take off the timezone using Date.UTC() and set hours, minutes and seconds to zero.

By the way, add 2 years from today to compare max date, instead of only year.

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start);
    const today = new Date(Date.UTC(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), 0,0,0,0));

    if (inputDate < today) {
        console.log(inputDate, today);
        document.getElementById('date_startError').innerHTML = " ** Obsolete date ! ";
        return false;
    }

    const twoYearsFromNow = new Date(today);
    twoYearsFromNow.setYear(today.getFullYear() + 2);

    if(inputDate > twoYearsFromNow) {
        document.getElementById('date_startError').innerHTML = " ** Maximum 2 years ! ";
        return false;
    }

    console.log(inputDate, today, twoYearsFromNow);
}

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form>
</body>
</html>


问:
Backspacing in C# window forms
So i'm making a self grading aptitude test that is done except for, if I backspace the entire field of a textbox to be empty is errors out and closes, not upon pressing but upon clearing all the characters. I've been reading some documentation and have had a hard time finding a proper way to implement some way to handle this error. the message after crashing is: This exception was originally thrown at this call stack:

```<code>private void AA3_TextChanged(object sender, EventArgs e)
        {
            int A3 = Int32.Parse(AA3.Text);
            if (A3 == 14200)
            {

                percent +=1;
                exp.Text = percent.ToString();

            }
        }
</code>```

the code inside is just a counter for the grade at the end, but i am lost why some backspace is okay but not a clear field. Sorry if this is poorly worded.

答:
Here's a minimal fix for you.</p>

```<code>private void AA3_TextChanged(object sender, EventArgs e)
{
    if (int.TryParse(AA3.Text, out int A3)) {
        if (A3 == 14200)
        {
            percent +=1;
            exp.Text = percent.ToString();
        }
    } else {
        // The input is not valid.
        // TODO: Consider telling the user nicely about that.
    }
}
</code>```

Title: Backspacing in C# window forms

Body:
So i'm making a self grading aptitude test that is done except for, if I backspace the entire field of a textbox to be empty is errors out and closes, not upon pressing but upon clearing all the characters. I've been reading some documentation and have had a hard time finding a proper way to implement some way to handle this error. the message after crashing is: This exception was originally thrown at this call stack:

private void AA3_TextChanged(object sender, EventArgs e)
        {
            int A3 = Int32.Parse(AA3.Text);
            if (A3 == 14200)
            {

                percent +=1;
                exp.Text = percent.ToString();

            }
        }

the code inside is just a counter for the grade at the end, but i am lost why some backspace is okay but not a clear field. Sorry if this is poorly worded.

Body:
Here's a minimal fix for you.

private void AA3_TextChanged(object sender, EventArgs e)
{
    if (int.TryParse(AA3.Text, out int A3)) {
        if (A3 == 14200)
        {
            percent +=1;
            exp.Text = percent.ToString();
        }
    } else {
        // The input is not valid.
        // TODO: Consider telling the user nicely about that.
    }
}


问:
Is it necessary to install Typescript before installing Angular?
According to an Angular book (updated to Angular 9) that I'm currently reading, the Angular installation steps are:

Installing Node.js

Installing Typescript: npm install -g typescript

Installing Typings: npm install --save @types/npm

Installing Angular CLI: npm install -g @angular/cli

Then, I went to the official Angular setup documentation and the Typescript and Typings installation are not included.

Do you know what is the purpose of those installations? Is it a deprecated way of installing Angular? The latest Angular version already include those packages?

I made some research but I couldn't find an answer to these questions.

Thanks!

答:
The only thing necessary is Node.js. There is no benefit of installing typescript. This will all be handled by the Angular CLI. They require a specific typescript version, which is usually one version behind the actual latest version of typescript.

My advice, stick to the excellent guides on angular.io. It's your safest bet.


问:
Unit Testing Service with Unit of Work with xunit .NET Core 3.1 and Moq
being fairly new to xUnit, I have an application that uses the Unit of Work pattern to return data to a service and I'm trying to unit test this service.

Here is the service code:

```<code> public async Task<IEnumerable<CatDto>> GetActiveCatsAsync()
    {
        var catList = new List<CatDto>();
        var catEFList = await _uow.Repository<Cat>().GetActiveCatsAsync();
        catList.AddRange(catEFList.Select(c => new CatDto
        {
            CatId = c.CatId,
            CatName = c.CatName,
            DisplayOrd = c.DisplayOrd
        }));

        return catList;
    }
</code>```

And here is the extension that this service calls:

```<code> public static async Task<List<Cat>> GetActiveCatsAsync(this IRepository<Cat> repository)
    {
        return await repository.AsQueryableRepo().Items.Where(c =>c.IsActive == true).OrderBy(c=>c.DisplayOrd).ToListAsync();
    }
}
</code>```

Here is the Interface used by the extension:

```<code> internal static IQueryableRepository<T> AsQueryableRepo<T>(this IRepository<T> repository) where T : class
    {
        return (IQueryableRepository<T>)repository;
    }
</code>```

Here is the concrete unit of work class:

```<code> public class SQLUnitOfWork<TContext> : BaseUnitOfWork, ISQLUnitOfWork<TContext>
    where TContext : IDbContext, IDisposable
{
    public SQLUnitOfWork(TContext context) : base(context)
    {
    }
}
</code>```

And here is where I am with a single unit test so far:

```<code>  [Fact]
    public void GetActiveCatsAsync_ReturnsTypeIEnumerableCatDto()
    {
        var mockLogger = new Mock<ILogger<CatService>>();
        var mockUoW = new Mock<ISQLUnitOfWork>();

        var catServ = new CatService(mockLogger.Object, mockUoW.Object);

        var result = catServ.GetActiveCatsAsync();

        Assert.IsType<Task<IEnumerable<CatDto>>>(result);
    }
</code>```

This test actually passes, but obviously the "result" variable has no data in it because there is no setup for the mocks. I also tried setting up:

```<code> var mockRepo = new Mock<IRepository<Cat>>();
</code>```

But this doesn't allow me to get at the extensions methods above. It doesn't show me the "asQueryableRepo()" method to provide a return value for. So I'm not sure how I can mock the return data, which would be a simple Cat object with three properties shown in the service call. I have also tried using xUnit's .ReturnAsync() and Task.FromResult() functionality.

After a few searches, I tried implementing xUnit.DependencyInjection, but that requires configuration in the test project's Startup.cs file. My test project (created with the Visual Studio xUnit project template) doesn't have a Startup.cs file. Did I use the wrong template?

I have also seen something similar to the following used:

```<code>      scope = new CustomWebApplicationFactory<Startup>().Server.Host.Services.CreateScope();
service = scope.ServiceProvider.GetRequiredService<IDashboardService>();
context = scope.ServiceProvider.GetRequiredService<DTBContext>();
</code>```

Which also seems to reference a startup class, so I really haven't been able to get this approach working either. Do I need to start again with a project that includes a Startup.cs folder? Or can I Unit Test the code above without it? I'm still researching this, but so far I cannot find a way to mock the dependencies of the service calls and the Unit of Work elements.

Any suggestions or advice is greatly appreciated! Thank you!

UPDATE: I think I now understand the xUnit.DependencyInjection, so I added a startup.cs class, and added the references referred to on their GitHub page. I also had to install Microsoft.Extensions.Hosting package to take care of a "does not have an implementation" error and now my project has a startup and the test that passed above now passes. I'm hoping that I can now handle dependencies within the testing project, but I'll find out.

答:
You can try using As:

[Fact]
public async Task GetActiveCatsAsync_ReturnsTypeIEnumerableCatDto()
{
    var mockLogger = new Mock<ILogger<CatService>>();
    var mockRepo = new Mock<IRepository<Cat>>();
    var cat = new Cat
    {
        IsActive = true
    };
    mockRepo
        .As<IQueryableRepository<Cat>>()
        .Setup(x => x.Items)
        .Returns(x => new[] { cat }.AsQueryable);
    var mockUoW = new Mock<ISQLUnitOfWork>();
    mockUoW.Setup(x => x.Repository<Cat>()).Returns(mockRepo.Object);
    var catServ = new CatService(mockLogger.Object, mockUoW.Object);

    var result = await catServ.GetActiveCatsAsync();

    var single = Assert.Single(result);
    Assert.Equal(cat, single);
}
```

<p><strong>UPDATE:</strong></p>

<p>Yes, testing Entity Framework is a separate issue. In that case, I would recommend testing the repository separately using <code>InMemoroyDatabase</code> or something, which would be inappropriate to pull in to the service test.</p>

<p>To really just test the service is doing what it's supposed to do, ideally you would verify like this:</p>

<pre class="lang-cs prettyprint-override"><code>[Fact]
public async Task GetActiveCatsAsync_ReturnsTypeIEnumerableCatDto()
{
    var mockLogger = new Mock<ILogger<CatService>>();
    var mockRepo = new Mock<IRepository<Cat>>();
    var mockUoW = new Mock<ISQLUnitOfWork>();
    mockUoW.Setup(x => x.Repository<Cat>()).Returns(mockRepo.Object);
    var catServ = new CatService(mockLogger.Object, mockUoW.Object);

    var result = await catServ.GetActiveCatsAsync();

    mockRepo.Verify(x => x.GetActiveCatsAsync(), Times.Once);
}
</code>```

But you won't be able to do this on an extension method. Unfortunately, the code you're testing doesn't lend itself to easily writing pure unit tests against it. Specifically, having the UoW expose the repository is troublesome. It would be easier to have ISQLUnitOfWork have its own GetActiveCatsAsync method so the repository wouldn't be visible (leaky abstraction) - that way you could do the verification directly on the UoW:

mockUoW.Verify(x => x.GetActiveCatsAsync(), Times.Once);
```

Body:
being fairly new to xUnit, I have an application that uses the Unit of Work pattern to return data to a service and I'm trying to unit test this service.

Here is the service code:

 public async Task<IEnumerable<CatDto>> GetActiveCatsAsync()
    {
        var catList = new List<CatDto>();
        var catEFList = await _uow.Repository<Cat>().GetActiveCatsAsync();
        catList.AddRange(catEFList.Select(c => new CatDto
        {
            CatId = c.CatId,
            CatName = c.CatName,
            DisplayOrd = c.DisplayOrd
        }));

        return catList;
    }

And here is the extension that this service calls:

 public static async Task<List<Cat>> GetActiveCatsAsync(this IRepository<Cat> repository)
    {
        return await repository.AsQueryableRepo().Items.Where(c =>c.IsActive == true).OrderBy(c=>c.DisplayOrd).ToListAsync();
    }
}

Here is the Interface used by the extension:

 internal static IQueryableRepository<T> AsQueryableRepo<T>(this IRepository<T> repository) where T : class
    {
        return (IQueryableRepository<T>)repository;
    }

Here is the concrete unit of work class:

 public class SQLUnitOfWork<TContext> : BaseUnitOfWork, ISQLUnitOfWork<TContext>
    where TContext : IDbContext, IDisposable
{
    public SQLUnitOfWork(TContext context) : base(context)
    {
    }
}

And here is where I am with a single unit test so far:

  [Fact]
    public void GetActiveCatsAsync_ReturnsTypeIEnumerableCatDto()
    {
        var mockLogger = new Mock<ILogger<CatService>>();
        var mockUoW = new Mock<ISQLUnitOfWork>();

        var catServ = new CatService(mockLogger.Object, mockUoW.Object);

        var result = catServ.GetActiveCatsAsync();

        Assert.IsType<Task<IEnumerable<CatDto>>>(result);
    }

This test actually passes, but obviously the "result" variable has no data in it because there is no setup for the mocks. I also tried setting up:

 var mockRepo = new Mock<IRepository<Cat>>();

But this doesn't allow me to get at the extensions methods above. It doesn't show me the "asQueryableRepo()" method to provide a return value for. So I'm not sure how I can mock the return data, which would be a simple Cat object with three properties shown in the service call. I have also tried using xUnit's .ReturnAsync() and Task.FromResult() functionality.

After a few searches, I tried implementing xUnit.DependencyInjection, but that requires configuration in the test project's Startup.cs file. My test project (created with the Visual Studio xUnit project template) doesn't have a Startup.cs file. Did I use the wrong template?

I have also seen something similar to the following used:

      scope = new CustomWebApplicationFactory<Startup>().Server.Host.Services.CreateScope();
service = scope.ServiceProvider.GetRequiredService<IDashboardService>();
context = scope.ServiceProvider.GetRequiredService<DTBContext>();

Which also seems to reference a startup class, so I really haven't been able to get this approach working either. Do I need to start again with a project that includes a Startup.cs folder? Or can I Unit Test the code above without it? I'm still researching this, but so far I cannot find a way to mock the dependencies of the service calls and the Unit of Work elements.

Any suggestions or advice is greatly appreciated! Thank you!

UPDATE: I think I now understand the xUnit.DependencyInjection, so I added a startup.cs class, and added the references referred to on their GitHub page. I also had to install Microsoft.Extensions.Hosting package to take care of a "does not have an implementation" error and now my project has a startup and the test that passed above now passes. I'm hoping that I can now handle dependencies within the testing project, but I'll find out.

Body:
You can try using As:

[Fact]
public async Task GetActiveCatsAsync_ReturnsTypeIEnumerableCatDto()
{
    var mockLogger = new Mock<ILogger<CatService>>();
    var mockRepo = new Mock<IRepository<Cat>>();
    var cat = new Cat
    {
        IsActive = true
    };
    mockRepo
        .As<IQueryableRepository<Cat>>()
        .Setup(x => x.Items)
        .Returns(x => new[] { cat }.AsQueryable);
    var mockUoW = new Mock<ISQLUnitOfWork>();
    mockUoW.Setup(x => x.Repository<Cat>()).Returns(mockRepo.Object);
    var catServ = new CatService(mockLogger.Object, mockUoW.Object);

    var result = await catServ.GetActiveCatsAsync();

    var single = Assert.Single(result);
    Assert.Equal(cat, single);
}

UPDATE:

Yes, testing Entity Framework is a separate issue. In that case, I would recommend testing the repository separately using InMemoroyDatabase or something, which would be inappropriate to pull in to the service test.

To really just test the service is doing what it's supposed to do, ideally you would verify like this:

[Fact]
public async Task GetActiveCatsAsync_ReturnsTypeIEnumerableCatDto()
{
    var mockLogger = new Mock<ILogger<CatService>>();
    var mockRepo = new Mock<IRepository<Cat>>();
    var mockUoW = new Mock<ISQLUnitOfWork>();
    mockUoW.Setup(x => x.Repository<Cat>()).Returns(mockRepo.Object);
    var catServ = new CatService(mockLogger.Object, mockUoW.Object);

    var result = await catServ.GetActiveCatsAsync();

    mockRepo.Verify(x => x.GetActiveCatsAsync(), Times.Once);
}

But you won't be able to do this on an extension method. Unfortunately, the code you're testing doesn't lend itself to easily writing pure unit tests against it. Specifically, having the UoW expose the repository is troublesome. It would be easier to have ISQLUnitOfWork have its own GetActiveCatsAsync method so the repository wouldn't be visible (leaky abstraction) - that way you could do the verification directly on the UoW:

mockUoW.Verify(x => x.GetActiveCatsAsync(), Times.Once);


问:
display if the numbers are consecutive for upto 3 positions exactly in pandas
I have a df "Index_label", which has only one column(name: column1) which contain numbers.

if we have consecutive position ==3. i would want it as out put

column1

25

26------------consecutive upto 2 positions

110

111

112

113---------------------consecutive upto 4 positions

455

456

457---------------------consecutive upto 3 positions

desired o/p:

110

111

112

455

456

457

答:
This works (I think?), using a while loop and jumping up the count when a consecutive series is found:

```<code>def three_in_a_row(array):
    output=[]
    c = 0
    while c < len(array)-2:
        if (array[c] + 1 == array[c+1]) and (array[c] + 2 == array[c+2]):
            output += [array[c],array[c+1],array[c+2]]
            d = 1
            while (array[c] + d == array[c+d]):
                d+=1
                if (d+c) >= len(array):
                    break
            c += d
        else:
            c+=1
    return output

print(three_in_a_row([1,2,3,4,5,6,7,8,9]))
print(three_in_a_row([1,2,3,7,8,9]))
print(three_in_a_row([1,8,9,4,2,4,5,6,7,8]))
</code>```

Output:

```<code>[1, 2, 3]
[1, 2, 3, 7, 8, 9]
[4, 5, 6]
</code>```

Fun exercise!

Body:
This works (I think?), using a while loop and jumping up the count when a consecutive series is found:

def three_in_a_row(array):
    output=[]
    c = 0
    while c < len(array)-2:
        if (array[c] + 1 == array[c+1]) and (array[c] + 2 == array[c+2]):
            output += [array[c],array[c+1],array[c+2]]
            d = 1
            while (array[c] + d == array[c+d]):
                d+=1
                if (d+c) >= len(array):
                    break
            c += d
        else:
            c+=1
    return output

print(three_in_a_row([1,2,3,4,5,6,7,8,9]))
print(three_in_a_row([1,2,3,7,8,9]))
print(three_in_a_row([1,8,9,4,2,4,5,6,7,8]))

Output:

[1, 2, 3]
[1, 2, 3, 7, 8, 9]
[4, 5, 6]

Fun exercise!