问:
How do I reference the output of the previous "pipe" in a Powershell pipeline?
I wrote this code to get some (relative) file path:

```<code>function Get-ExecutingScriptDirectory() {
    return Split-Path $script:MyInvocation.MyCommand.Path  # returns this script's directory
}

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "foo.json"
</code>```

This threw the error:

```<code>Join-Path : Cannot bind argument to parameter 'Path' because it is null.
+ $some_file_path  = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "fo ...
+                                                     ~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand
</code>```

This indicates to me that the output of Get-ExecutingScriptDirectory is null - but it isn't - when I write the script out like this, it's fine:

```<code>$this_directory = Get-ExecutingScriptDirectory
$some_file_path = Join-Path -Path $this_directory -ChildPath "foo.json"
</code>```

So the problem is that $_ is null.  I would expect $_ to be reference to the previous pipe's standard output.  The MSDN documentation also suggests this, but then it seems to immediately contradict itself:

$_ contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

In the context of my code, $_ seems to qualify as the "current object in the pipeline object" - but I am not using this with a command that performs an action on every object or on selected objects in a pipeline.

$$ and $^ looked promising, but the MSDN documentation just says a few vague things here about lexical tokens.  The documentation on $PSItem was equally terse.

What I would actually like to do is create a big pipeline:

```<code>$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path {{PREVIOUS STDOUT}} -ChildPath "foo.json" | Get-Content {{PREVIOUS STDOUT}} | Convert-FromJson {{PREVIOUS STDOUT}} | {{PREVIOUS STDOUT}}.data
</code>```

I'd like to know where I'm going wrong both on a conceptual and a technical level.

答:
You can do what you want by executing the command below:

```<code>(Get-Content -Path (Get-ExecutingScriptDirectory | Join-Path -ChildPath "foo.json" | ConvertFrom-Json)).data
</code>```

Some commands support pipeline parameter binding. The options are pipeline by value or pipeline by property. A good reference for parameter binding is About Functions Advanced Parameters.

Searching online for the command you are going to use will yield parameter binding information. For example Join-Path, has a parameters section. Each parameter will have a description including the field Accept pipeline input:. For a parameter to accept pipeline input, this must be True. Usually, it will say how the value can be passed into the pipeline (ByPropertyName or ByValue).

ByPropertyName indicates that you must output an object that contains a property name that matches the parameter name. Then once the object is piped, the parameter will bind to the matching property name's value. See below for an example:

```<code>$filePath = [pscustomobject]@{Path = 'c:\temp\test1\t.txt'}
$filePath

Path
----
c:\temp\test1\t.txt

$filePath.Path # This binds to -Path in Get-Content
c:\temp\test1\t.txt
$filepath | Get-Content
</code>```

ByValue indicates that any value piped in will attempt to bind to that parameter. If there are type discrepancies at the binding time, an error will likely be thrown. See below for example:

```<code>"c:\temp" | Join-Path -ChildPath "filepath" # c:\temp binds to `-Path`
c:\temp\filepath
</code>```

Regarding $_, which is synonymous with $PSItem, is the current input object in a script block. You typically see this used with Foreach-Object and Where-Object. If you don't have a script block, you won't be able to use $_.

You can technically pipe anything into Foreach-Object or Where-Object. Then the current pipeline object will be represented by $_. You don't need a collection as a single item can be piped in. See below:

```<code>"c:\temp" | Foreach-Object { $_ }
c:\temp

$filePath | Foreach-Object { $_ }

Path
----
c:\temp\test1\t.txt

$filePath | Foreach-Object { $_.Path }
c:\temp\test1\t.txt
</code>```

Body:
I wrote this code to get some (relative) file path:

function Get-ExecutingScriptDirectory() {
    return Split-Path $script:MyInvocation.MyCommand.Path  # returns this script's directory
}

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "foo.json"

This threw the error:

Join-Path : Cannot bind argument to parameter 'Path' because it is null.
+ $some_file_path  = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "fo ...
+                                                     ~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand

This indicates to me that the output of Get-ExecutingScriptDirectory is null - but it isn't - when I write the script out like this, it's fine:

$this_directory = Get-ExecutingScriptDirectory
$some_file_path = Join-Path -Path $this_directory -ChildPath "foo.json"

So the problem is that $_ is null.  I would expect $_ to be reference to the previous pipe's standard output.  The MSDN documentation also suggests this, but then it seems to immediately contradict itself:

$_ contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

In the context of my code, $_ seems to qualify as the "current object in the pipeline object" - but I am not using this with a command that performs an action on every object or on selected objects in a pipeline.

$$ and $^ looked promising, but the MSDN documentation just says a few vague things here about lexical tokens.  The documentation on $PSItem was equally terse.

What I would actually like to do is create a big pipeline:

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path {{PREVIOUS STDOUT}} -ChildPath "foo.json" | Get-Content {{PREVIOUS STDOUT}} | Convert-FromJson {{PREVIOUS STDOUT}} | {{PREVIOUS STDOUT}}.data

I'd like to know where I'm going wrong both on a conceptual and a technical level.

Body:
You can do what you want by executing the command below:

(Get-Content -Path (Get-ExecutingScriptDirectory | Join-Path -ChildPath "foo.json" | ConvertFrom-Json)).data

Some commands support pipeline parameter binding. The options are pipeline by value or pipeline by property. A good reference for parameter binding is About Functions Advanced Parameters.

Searching online for the command you are going to use will yield parameter binding information. For example Join-Path, has a parameters section. Each parameter will have a description including the field Accept pipeline input:. For a parameter to accept pipeline input, this must be True. Usually, it will say how the value can be passed into the pipeline (ByPropertyName or ByValue).

ByPropertyName indicates that you must output an object that contains a property name that matches the parameter name. Then once the object is piped, the parameter will bind to the matching property name's value. See below for an example:

$filePath = [pscustomobject]@{Path = 'c:\temp\test1\t.txt'}
$filePath

Path
----
c:\temp\test1\t.txt

$filePath.Path # This binds to -Path in Get-Content
c:\temp\test1\t.txt
$filepath | Get-Content

ByValue indicates that any value piped in will attempt to bind to that parameter. If there are type discrepancies at the binding time, an error will likely be thrown. See below for example:

"c:\temp" | Join-Path -ChildPath "filepath" # c:\temp binds to `-Path`
c:\temp\filepath

Regarding $_, which is synonymous with $PSItem, is the current input object in a script block. You typically see this used with Foreach-Object and Where-Object. If you don't have a script block, you won't be able to use $_.

You can technically pipe anything into Foreach-Object or Where-Object. Then the current pipeline object will be represented by $_. You don't need a collection as a single item can be piped in. See below:

"c:\temp" | Foreach-Object { $_ }
c:\temp

$filePath | Foreach-Object { $_ }

Path
----
c:\temp\test1\t.txt

$filePath | Foreach-Object { $_.Path }
c:\temp\test1\t.txt


来源: stackexchange

答:
If you want to repeat the code you simply must pass the key. Consider you have a dictionary that contains lists and dictionaries within that lists, you shouldn't treat it in any different way:

```<code>for i in range(len(person_dict['Department'])):
   for k in person_dict['Department'][i]:
       print("Key =",k,"Value =",person_dict['Department'][i][k])
</code>```

This will output:

```<code>Key = cpt Value = A0001
Key = aaa Value = 1
Key = bbb Value = 2
Key = ccc Value = 3
Key = ddd Value = 4
Key = eee Value = 5
</code>```

... And so on

ContentLicense: CC BY-SA 4.0

Title: Read JSON Array in Python

Body:
I'm trying to read department array in python. I can read the first element of the array. how can I read the rest for example the values for "aaa", "bbb", "ccc"? Any suggestions?

import json

person2 = '{"FirstName":"2018 Q1 (JAN-MAR)","LastName":"aaaaaaaaaaaaaaaaaaaaaaaa","Phone":"2222222222222222","Department":[{"cpt":"A0001","aaa":"1","bbb":"2","ccc":"3","ddd":"4","eee":"5"},{"cpt":"A0002","aaa":"6","bbb":"7","ccc":"8","ddd":"9","eee":"10"},{"cpt":"A0003","aaa":"11","bbb":"21","ccc":"31","ddd":"44","eee":"55"},{"cpt":"A0004","aaa":"101","bbb":"22","ccc":"33","ddd":"44","eee":"55"},{"cpt":"A0005","ffs":"100","mmc":"23","med":"34","oth":"45","duo":"56"},{"cpt":"A0006","aaa":"111","bbb":"24","ccc":"34","ddd":"44","eee":"54"}],"checkAgree":true}'
person_dict = json.loads(person2)

#Example of how to read JSON array elements in python
print(person_dict['Department'][0]["cpt"]);

print(person_dict['Department'][1]["cpt"]);

print(person_dict['Department'][3]["cpt"]);

print(person_dict['Department'][4]["cpt"]);

print(person_dict['Department'][5]["cpt"]);

"Department": [
    {
      "cpt": "A0001",
      "aaa": "1",
      "bbb": "2",
      "ccc": "3",
      "ddd": "4",
      "eee": "5"
    },
    {
      "cpt": "A0002",
      "aaa": "6",
      "bbb": "7",
      "ccc": "8",
      "ddd": "9",
      "eee": "10"
    },
    {
      "cpt": "A0003",
      "aaa": "11",
      "bbb": "21",
      "ccc": "31",
      "ddd": "44",
      "eee": "55"
    },
    {
      "cpt": "A0004",
      "aaa": "101",
      "bbb": "22",
      "ccc": "33",
      "ddd": "44",
      "eee": "55"
    },
    {
      "cpt": "A0005",
      "aaa": "100",
      "bbb": "23",
      "ccc": "34",
      "ddd": "45",
      "eee": "56"
    },
    {
      "cpt": "A0006",
      "aaa": "111",
      "bbb": "24",
      "ccc": "34",
      "ddd": "44",
      "eee": "54"
    }
  ],

Body:
If you want to repeat the code you simply must pass the key. Consider you have a dictionary that contains lists and dictionaries within that lists, you shouldn't treat it in any different way:

for i in range(len(person_dict['Department'])):
   for k in person_dict['Department'][i]:
       print("Key =",k,"Value =",person_dict['Department'][i][k])

This will output:

Key = cpt Value = A0001
Key = aaa Value = 1
Key = bbb Value = 2
Key = ccc Value = 3
Key = ddd Value = 4
Key = eee Value = 5

... And so on


问:
ThinkingSphinx to match exact phrase
I'm using Sphinx and ThinkingSphinx gem with Rails 3 for searching.  I want to search for exact match of a certain string for an sphinx-indexed column but there seems to be no good way to do so.  According to ThinkingSphinx documentation, the matching modes are :any, :phrase, :all, but they all seem to search on substring.  For example, searching for "1997" will also match with "1997 Honda", or "1997 Ford".  In my situation, I want to search for the exact match of "1997", thus "1997 Honda" and "1997 Ford" should not match.  This is straightforward with MySQL, but I have not found a way to do so.

Thanks!

答:
Sphinx introduced the field-start and field-end operators in version 0.9.9-rc2.

To use your example, you would search for '^1997$'

ContentLicense: CC BY-SA 3.0

Title: ThinkingSphinx to match exact phrase


问:
How to keep same background-image ratio/size on all different screen sizes?
How do you keep the background-image same ratio so that it looks fitted for all different screen-sizes? In other words, how can I make sure the background-image always looks perfectly "centered". Please take note I have several other screens with other background-images so the solution should work for different images, not just the houses below.

CSS :

```<code>#background{
     background-image: url("../images/houses.png");
     background-color: whitesmoke; /* Used if the image is unavailable */
     height: 100%; /* You must set a specified height */
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover; /* Resize the background image to cover the entire container */
     text-align: center;
     padding: 2.5%;

}
</code>```

This is the desired output for ALL screen sizes. Perfectly aligned :

However when I resize and experiment with different sizes, the background gets misplaced and does not look really good. It looks like the image is a bit more to the right :

答:
try this :</p>

```<code>#background{
  background-image: url("../images/houses.png"); /* The image used */
  background-color: whitesmoke; /* Used if the image is unavailable */
  height: 500px; /* You must set a specified height */
  background-position: center; /* Center the image */
  background-repeat: no-repeat; /* Do not repeat the image */
  background-size: cover; /* Resize the background image to cover the entire container*/
}
</code>```

Body:
How do you keep the background-image same ratio so that it looks fitted for all different screen-sizes? In other words, how can I make sure the background-image always looks perfectly "centered". Please take note I have several other screens with other background-images so the solution should work for different images, not just the houses below.

CSS :

#background{
     background-image: url("../images/houses.png");
     background-color: whitesmoke; /* Used if the image is unavailable */
     height: 100%; /* You must set a specified height */
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover; /* Resize the background image to cover the entire container */
     text-align: center;
     padding: 2.5%;

}

This is the desired output for ALL screen sizes. Perfectly aligned :

However when I resize and experiment with different sizes, the background gets misplaced and does not look really good. It looks like the image is a bit more to the right :

Body:
try this :

#background{
  background-image: url("../images/houses.png"); /* The image used */
  background-color: whitesmoke; /* Used if the image is unavailable */
  height: 500px; /* You must set a specified height */
  background-position: center; /* Center the image */
  background-repeat: no-repeat; /* Do not repeat the image */
  background-size: cover; /* Resize the background image to cover the entire container*/
}


问:
This project references NuGet package(s) that are missing on this computer
I have an ASP.NET MVC5 application that worked yesterday and now I am getting this error when I try to build:

This project references NuGet package(s) that are missing on this computer.

I have the two options checked that allow nuget to automatically download and install missing packages checked / turned ON. I have also tried deleting all of the files in the packages folder and then have nuget re-download them. Also when I open nuget and look for updates it says there are none that need to be installed. I can't figure what else to do to move beyond this amazingly annoying issue.

I have also enabled nuget restore by right clicking the project and selecting that option. It then added a nuget folder and three items in that folder and does nothing to resolve the problem. I've tried re-building and still get the same error.

答:
The first thing to try is to right-click the solution and select "Restore Nuget Packages".

In my case that did not work, so I followed some recommendations on deleting "Import" and "Target" on project file, this worked for 2 of my 3 projects, but got a different error on the last one.

What worked was to open the Package Manager Console and run:

```<code>Update-Package -reinstall -ProjectName MyProjectName
</code>```

It takes some time but since it reinstall all packages your project will compile without problems

Body:
The first thing to try is to right-click the solution and select "Restore Nuget Packages".

In my case that did not work, so I followed some recommendations on deleting "Import" and "Target" on project file, this worked for 2 of my 3 projects, but got a different error on the last one.

What worked was to open the Package Manager Console and run:

Update-Package -reinstall -ProjectName MyProjectName

It takes some time but since it reinstall all packages your project will compile without problems


问:
TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"
I keep getting this error while using TypeScript's Angular2-forms framework:

There is no directive with "exportAs" set to "ngForm"

Here's my code

project dependencies :

```<code>  "dependencies": {
    "@angular/common": "2.0.0-rc.6",
    "@angular/compiler": "2.0.0-rc.6",
    "@angular/core": "2.0.0-rc.6",
    "@angular/forms": "2.0.0-rc.6",
    "@angular/http": "2.0.0-rc.6",
    "@angular/platform-browser": "2.0.0-rc.6",
    "@angular/platform-browser-dynamic": "2.0.0-rc.6",
    "@angular/router": "3.0.0-rc.2",
    "ng2-bootstrap": "^1.1.1",
    "reflect-metadata": "^0.1.8",
    "core-js": "^2.4.0",
    "es6-module-loader": "^0.17.8",
    "rxjs": "5.0.0-beta.11",
    "systemjs": "0.19.27",
    "zone.js": "0.6.17",
    "jquery": "3.0.0",
  }
</code>```

And this is the Login Template :

```<code><form #loginForm="ngForm" (ng-submit)="authenticate(loginForm.value)">
</form>
</code>```

...and  the Login Component :

```<code>import { Component } from '@angular/core';
import {Http, Headers}  from '@angular/http';
@Component({
    moduleId: module.id,
    selector: 'login-cmp',
    templateUrl: 'login.component.html'
})
export class LoginComponent {
  constructor($http: Http) {
    this.$http = $http;
  }
  authenticate(data) {
   ...
  }
}
</code>```

I have this Error :

```<code>zone.js?1474211973422:484 Unhandled Promise rejection: Template parse errors:
There is no directive with "exportAs" set to "ngForm" ("
            <form [ERROR ->]#loginForm="ngForm"
(ngsubmit)="authenticate(loginForm.value)">
</code>```

答:
In my case I had to remove the ngNoForm attribute from my <form> tag.

If you you want to import FormsModule in your application but want to skip a specific form, you can use the ngNoForm directive which will prevent ngForm from being added to the form

Reference: https://www.techiediaries.com/angular-ngform-ngnoform-template-reference-variable/

Body:
I keep getting this error while using TypeScript's Angular2-forms framework:

There is no directive with "exportAs" set to "ngForm"

Here's my code

project dependencies :

  "dependencies": {
    "@angular/common": "2.0.0-rc.6",
    "@angular/compiler": "2.0.0-rc.6",
    "@angular/core": "2.0.0-rc.6",
    "@angular/forms": "2.0.0-rc.6",
    "@angular/http": "2.0.0-rc.6",
    "@angular/platform-browser": "2.0.0-rc.6",
    "@angular/platform-browser-dynamic": "2.0.0-rc.6",
    "@angular/router": "3.0.0-rc.2",
    "ng2-bootstrap": "^1.1.1",
    "reflect-metadata": "^0.1.8",
    "core-js": "^2.4.0",
    "es6-module-loader": "^0.17.8",
    "rxjs": "5.0.0-beta.11",
    "systemjs": "0.19.27",
    "zone.js": "0.6.17",
    "jquery": "3.0.0",
  }

And this is the Login Template :

<form #loginForm="ngForm" (ng-submit)="authenticate(loginForm.value)">
</form>

...and  the Login Component :

import { Component } from '@angular/core';
import {Http, Headers}  from '@angular/http';
@Component({
    moduleId: module.id,
    selector: 'login-cmp',
    templateUrl: 'login.component.html'
})
export class LoginComponent {
  constructor($http: Http) {
    this.$http = $http;
  }
  authenticate(data) {
   ...
  }
}

I have this Error :

zone.js?1474211973422:484 Unhandled Promise rejection: Template parse errors:
There is no directive with "exportAs" set to "ngForm" ("
            <form [ERROR ->]#loginForm="ngForm"
(ngsubmit)="authenticate(loginForm.value)">


问:
Call to undefined method newCollection when using factories with Laravel-Doctrine
I would like to use Model factories, but I get this error:

```<code>1) Tests\Factory\UserFactoryTest::testUserCount
Error: Call to undefined method App\Entities\User::newCollection()

C:\Projects\factory_test\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:228
C:\Projects\factory_test\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:178
C:\Projects\factory_test\tests\Factory\UserFactoryTest.php:21
</code>```

The factory code was copied from the Laravel-Doctrine example project :

```<code>$factory->define(App\Entities\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->title,
    ];
});
</code>```

What do I wrong? Do I need additional configurations, before using factories? Doctrine works perfectly, I only have issue with factory()

The test class looks like this:

```<code>class UserFactoryTest extends TestCase {

    private $users = array();

    protected function setUp(): void
    {
        parent::setUp();

        $this->users = factory(User::class, 3)->create();
    }

    // ...

}
</code>```

答:
Your setUp() function is using the standard Laravel factory() helper to generate the test data.

Change this to:

protected function setUp(): void
{
    parent::setUp();
    $this->users = entity(User::class, 3)->create();
    //             ^^^^^^
}
```

<p>The Laravel Doctrine <code>entity()</code> helper method uses a different base class behind the scenes than the standard Laravel <code>factory()</code> helper method.</p>

```// Laravel Doctrine
$factory = app('LaravelDoctrine\ORM\Testing\Factory');
```

<p>Compare to the <code>factory()</code> helper method in the Laravel framework:</p>

<pre class="lang-php prettyprint-override"><code>// Laravel framework
$factory = app(EloquentFactory::class);
</code>```

Body:
I would like to use Model factories, but I get this error:

1) Tests\Factory\UserFactoryTest::testUserCount
Error: Call to undefined method App\Entities\User::newCollection()

C:\Projects\factory_test\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:228
C:\Projects\factory_test\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:178
C:\Projects\factory_test\tests\Factory\UserFactoryTest.php:21

The factory code was copied from the Laravel-Doctrine example project :

$factory->define(App\Entities\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->title,
    ];
});

What do I wrong? Do I need additional configurations, before using factories? Doctrine works perfectly, I only have issue with factory()

The test class looks like this:

class UserFactoryTest extends TestCase {

    private $users = array();

    protected function setUp(): void
    {
        parent::setUp();

        $this->users = factory(User::class, 3)->create();
    }

    // ...

}

Body:
Your setUp() function is using the standard Laravel factory() helper to generate the test data.

Change this to:

protected function setUp(): void
{
    parent::setUp();
    $this->users = entity(User::class, 3)->create();
    //             ^^^^^^
}

The Laravel Doctrine entity() helper method uses a different base class behind the scenes than the standard Laravel factory() helper method.

// Laravel Doctrine
$factory = app('LaravelDoctrine\ORM\Testing\Factory');

Compare to the factory() helper method in the Laravel framework:

// Laravel framework
$factory = app(EloquentFactory::class);


问:
Removing pages from search engine results
Hey everyone, I'm a bit new to SEO. I built a one page website that initially utilized several pages (but are now removed), and it looks as if Google has indexed those so that they show up as search results. Is there any way to remove those from the search results? Thanks.</p>

答: Google has a page describing how to remove your site from their results.</p>


问:
React Native render() not being called after navigation
I have a Footer component which is shared to all my screens. It has a method that updates the current property and returns to Home Page

```<code>...
class FooterComp extends Component {
   changeProperty = async (data) => {
    await AsyncStorage.setItem('CurrentPropertyID', data.toString());

    await this.setState({ CurrentPropertyID: data.toString() });

    NavigationService.navigate('Home');
  }
}
...
</code>```

My navigation service:

```<code>import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

// add other navigation functions that you need and export them

export default {
  navigate,
  setTopLevelNavigator,
};
</code>```

My App.js

```<code>class App extends Component {
  render() {
    const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));

    return (
      <Provider store={store}>
        <AppContainer
          ref={navigatorRef => {
            NavigationService.setTopLevelNavigator(navigatorRef);
          }}
        />
      </Provider>
    );
  }
}

export default App;

const MainStackNavigator = createStackNavigator({
    Home: {
      screen: HomeScreen,
      navigationOptions: {
        headerTitle: 'iRent'
      }
    },
    Company: {
      screen: CompanyDetails,
      navigationOptions: {
        headerTitle: 'Company Details'
      }
    },
    Tenants: {
      screen: Tenants,
      navigationOptions: {
        headerTitle: 'Tenants'
      }
    },
    WorkOrders: {
      screen: WorkOrders,
      navigationOptions: {
        headerTitle: 'Work Orders'
      }
    },
    Applicants: {
      screen: Applicants,
      navigationOptions: {
        headerTitle: 'Applicants'
      }
    },
    Bills: {
      screen: Bills,
      navigationOptions: {
        headerTitle: 'Bills'
      }
    }
}, {
  defaultNavigationOptions: ({ navigation }) => {
      return {
        headerLeft: (
          <Ionicons
            style={{ paddingLeft: 10 }}
            onPress={() => navigation.openDrawer()}
            name="md-menu"
            size={30}
          />
        )
      };
    }
});

const AppDrawerNavigator = createDrawerNavigator({
  iRent: {
    screen: MainStackNavigator
  },
  Home: {
    screen: HomeScreen,
    navigationOptions: {
      drawerIcon: <FontAwesome name="home" size={20} />
    }
  },
  Company: {
    screen: CompanyDetails,
    navigationOptions: {
      drawerIcon: <FontAwesome name="building-o" size={20} />
    }
  },
  Tenants: {
    screen: TenantDetails,
    navigationOptions: {
      drawerIcon: <Ionicons name="ios-person" size={20} />
    }
  },
  Applicants: {
    screen: Applicants,
    navigationOptions: {
      drawerIcon: <MaterialCommunityIcons name="account-search" size={20} />
    }
  },
  WorkOrders: {
    screen: WorkOrders,
    navigationOptions: {
      title: 'Work Orders',
      drawerIcon: <Octicons name="checklist" size={20} />
    }
  },
  Bills: {
    screen: Bills,
    navigationOptions: {
      title: 'Bills',
      drawerIcon: <Entypo name="text-document" size={20} />
    }
  },
  LogOut: {
    screen: Login,
    navigationOptions: {
      title: 'Log Out',
      drawerIcon: <Entypo name="log-out" size={20} />
    }
  }
});

const AppSwitchNavigator = createSwitchNavigator({
  Login: { screen: Login },
  ForgotPassword: { screen: ForgotPassword },
  Main: { screen: AppDrawerNavigator },
  TenantDetails: { screen: TenantDetails },
  EditData: { screen: EditData },
  EditReview: { screen: EditReview },
  ApplicantDetails: { screen: ApplicantDetails },
  RunScreening: { screen: RunScreening },
  OpenBGReport: { screen: OpenBGReport },
  WorkOrderDetails: { screen: WorkOrderDetails },
  ConvertToTenant: { screen: ConvertToTenant },
  EditBill: { screen: EditBill },
  NoAccess: { screen: NoAccess },
});

const AppContainer = createAppContainer(AppSwitchNavigator);
</code>```

My HomeScreen

```<code>class HomeScreen extends Component {

  constructor(props) {
    super(props);
    this.state = {
      data: [
        { id: 1, title: 'Tenants', nav: 'Tenants', image: 'http://myirent.com/rent/appImg/tenants.jpg' },
        { id: 2, title: 'Applicants', nav: 'Applicants', image: 'http://myirent.com/rent/appImg/applicants.png' },
        { id: 3, title: 'Work Orders', nav: 'WorkOrders', image: 'http://myirent.com/rent/appImg/workOrders.png' },
        { id: 4, title: 'Bills', nav: 'Bills', image: 'http://myirent.com/rent/appImg/bills.png' }
      ],
      currentPropertyID: null
    };
  }

  componentDidMount = async () => {
    await AsyncStorage.getItem('CurrentPropertyID')
      .then((value) => {
        const propID = JSON.parse(value);
        this.setState({
          currentPropertyID: propID.toString()
        });
    });
  }

  render() {
      console.log('Render Main. PID: ' + this.state.currentPropertyID);
    return (
      <View style={styles.container}>
        <FlatList
          style={styles.list}
          data={this.state.data}
          keyExtractor={(item) => {
            return item.id.toString();
          }}
          ItemSeparatorComponent={() => {
            return (
              <View style={styles.separator} />
            );
          }}
          renderItem={(post) => {
            const item = post.item;
            return (
              <TouchableOpacity
                onPress={() => { this.props.navigation.navigate(item.nav); }}
              >
                <View style={styles.card}>
                  <Image style={styles.cardImage} source={{ uri: item.image }} />
                  <View style={styles.cardContent}>
                    <View>
                      <Text style={styles.title}>{item.title}</Text>
                    </View>
                  </View>
                </View>
              </TouchableOpacity>
            );
          }}
        />
        <FooterComp />
      </View>
    );
  }
}
</code>```

The odd things is that after The FooterComp navigate to 'Home', the console.log() inside the render() method of HomeScreen component is not called. Shouldn't it be rendered after navigate to the component? I need to call the render() method to update screen.

答:
Is not being called because the component hasn't been updated. I mean, with react-navigation the screens doesn't get unmounted, they just get blurred.

There is a component in react-navigation that will help you to solve this, just wrap your view with:

```<code><View>
    <NavigationEvents
      onDidFocus={payload => console.log('Render Main. PID: ' + this.state.currentPropertyID)}
    />
    {/*
      Your view code
    */}
  </View>
</code>```

Body:
I have a Footer component which is shared to all my screens. It has a method that updates the current property and returns to Home Page

...
class FooterComp extends Component {
   changeProperty = async (data) => {
    await AsyncStorage.setItem('CurrentPropertyID', data.toString());

    await this.setState({ CurrentPropertyID: data.toString() });

    NavigationService.navigate('Home');
  }
}
...

My navigation service:

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

// add other navigation functions that you need and export them

export default {
  navigate,
  setTopLevelNavigator,
};

My App.js

class App extends Component {
  render() {
    const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));

    return (
      <Provider store={store}>
        <AppContainer
          ref={navigatorRef => {
            NavigationService.setTopLevelNavigator(navigatorRef);
          }}
        />
      </Provider>
    );
  }
}

export default App;

const MainStackNavigator = createStackNavigator({
    Home: {
      screen: HomeScreen,
      navigationOptions: {
        headerTitle: 'iRent'
      }
    },
    Company: {
      screen: CompanyDetails,
      navigationOptions: {
        headerTitle: 'Company Details'
      }
    },
    Tenants: {
      screen: Tenants,
      navigationOptions: {
        headerTitle: 'Tenants'
      }
    },
    WorkOrders: {
      screen: WorkOrders,
      navigationOptions: {
        headerTitle: 'Work Orders'
      }
    },
    Applicants: {
      screen: Applicants,
      navigationOptions: {
        headerTitle: 'Applicants'
      }
    },
    Bills: {
      screen: Bills,
      navigationOptions: {
        headerTitle: 'Bills'
      }
    }
}, {
  defaultNavigationOptions: ({ navigation }) => {
      return {
        headerLeft: (
          <Ionicons
            style={{ paddingLeft: 10 }}
            onPress={() => navigation.openDrawer()}
            name="md-menu"
            size={30}
          />
        )
      };
    }
});

const AppDrawerNavigator = createDrawerNavigator({
  iRent: {
    screen: MainStackNavigator
  },
  Home: {
    screen: HomeScreen,
    navigationOptions: {
      drawerIcon: <FontAwesome name="home" size={20} />
    }
  },
  Company: {
    screen: CompanyDetails,
    navigationOptions: {
      drawerIcon: <FontAwesome name="building-o" size={20} />
    }
  },
  Tenants: {
    screen: TenantDetails,
    navigationOptions: {
      drawerIcon: <Ionicons name="ios-person" size={20} />
    }
  },
  Applicants: {
    screen: Applicants,
    navigationOptions: {
      drawerIcon: <MaterialCommunityIcons name="account-search" size={20} />
    }
  },
  WorkOrders: {
    screen: WorkOrders,
    navigationOptions: {
      title: 'Work Orders',
      drawerIcon: <Octicons name="checklist" size={20} />
    }
  },
  Bills: {
    screen: Bills,
    navigationOptions: {
      title: 'Bills',
      drawerIcon: <Entypo name="text-document" size={20} />
    }
  },
  LogOut: {
    screen: Login,
    navigationOptions: {
      title: 'Log Out',
      drawerIcon: <Entypo name="log-out" size={20} />
    }
  }
});

const AppSwitchNavigator = createSwitchNavigator({
  Login: { screen: Login },
  ForgotPassword: { screen: ForgotPassword },
  Main: { screen: AppDrawerNavigator },
  TenantDetails: { screen: TenantDetails },
  EditData: { screen: EditData },
  EditReview: { screen: EditReview },
  ApplicantDetails: { screen: ApplicantDetails },
  RunScreening: { screen: RunScreening },
  OpenBGReport: { screen: OpenBGReport },
  WorkOrderDetails: { screen: WorkOrderDetails },
  ConvertToTenant: { screen: ConvertToTenant },
  EditBill: { screen: EditBill },
  NoAccess: { screen: NoAccess },
});

const AppContainer = createAppContainer(AppSwitchNavigator);

My HomeScreen

class HomeScreen extends Component {

  constructor(props) {
    super(props);
    this.state = {
      data: [
        { id: 1, title: 'Tenants', nav: 'Tenants', image: 'http://myirent.com/rent/appImg/tenants.jpg' },
        { id: 2, title: 'Applicants', nav: 'Applicants', image: 'http://myirent.com/rent/appImg/applicants.png' },
        { id: 3, title: 'Work Orders', nav: 'WorkOrders', image: 'http://myirent.com/rent/appImg/workOrders.png' },
        { id: 4, title: 'Bills', nav: 'Bills', image: 'http://myirent.com/rent/appImg/bills.png' }
      ],
      currentPropertyID: null
    };
  }

  componentDidMount = async () => {
    await AsyncStorage.getItem('CurrentPropertyID')
      .then((value) => {
        const propID = JSON.parse(value);
        this.setState({
          currentPropertyID: propID.toString()
        });
    });
  }

  render() {
      console.log('Render Main. PID: ' + this.state.currentPropertyID);
    return (
      <View style={styles.container}>
        <FlatList
          style={styles.list}
          data={this.state.data}
          keyExtractor={(item) => {
            return item.id.toString();
          }}
          ItemSeparatorComponent={() => {
            return (
              <View style={styles.separator} />
            );
          }}
          renderItem={(post) => {
            const item = post.item;
            return (
              <TouchableOpacity
                onPress={() => { this.props.navigation.navigate(item.nav); }}
              >
                <View style={styles.card}>
                  <Image style={styles.cardImage} source={{ uri: item.image }} />
                  <View style={styles.cardContent}>
                    <View>
                      <Text style={styles.title}>{item.title}</Text>
                    </View>
                  </View>
                </View>
              </TouchableOpacity>
            );
          }}
        />
        <FooterComp />
      </View>
    );
  }
}

The odd things is that after The FooterComp navigate to 'Home', the console.log() inside the render() method of HomeScreen component is not called. Shouldn't it be rendered after navigate to the component? I need to call the render() method to update screen.

Body:
Is not being called because the component hasn't been updated. I mean, with react-navigation the screens doesn't get unmounted, they just get blurred.

There is a component in react-navigation that will help you to solve this, just wrap your view with:

<View>
    <NavigationEvents
      onDidFocus={payload => console.log('Render Main. PID: ' + this.state.currentPropertyID)}
    />
    {/*
      Your view code
    */}
  </View>


问:
Sorting with Nulls Last
I have the following:

```<code>public IEnumerable<Customer> SortByRegion(IEnumerable<Customer> customerList)
{
    return customerList.OrderBy(x => x.Region).ThenBy(x => x.ContactName);
}
</code>```

It needs to Orderby Region, then by ContactName. But have the Null Regions at the bottom. I have tried the following:

```<code>customerList.OrderBy(x => x.Region != null).ThenBy(x => x.ContactName);
</code>```

But id did not work. Been googling for a while. Cant seem to find it.

答:
Well, since false < true for null last you can put

```<code> OrderBy(x => x.Region == null)
</code>```

Title: Sorting with Nulls Last

Body:
I have the following:

public IEnumerable<Customer> SortByRegion(IEnumerable<Customer> customerList)
{
    return customerList.OrderBy(x => x.Region).ThenBy(x => x.ContactName);
}

It needs to Orderby Region, then by ContactName. But have the Null Regions at the bottom. I have tried the following:

customerList.OrderBy(x => x.Region != null).ThenBy(x => x.ContactName);

But id did not work. Been googling for a while. Cant seem to find it.

Body:
Well, since false < true for null last you can put

 OrderBy(x => x.Region == null)


问:
Creating a view table with reference table and submission table
So I have two tables:
One table has ID's and field labels, the other table with the form submission data but it shows the IDs referenced from the first table.

picture of table 1 and table 2 as well as desired joined table

I want to make a view that shows the form submission data but with the labels from the first table instead of the ID's associated with it. How can I do this?

答:
Here is how you can join two tables to get the desired result:

```<code>CREATE VIEW test_view (Probability) AS
SELECT t1.label
from table_1 t1
left join table_2 t2
on t1.id = t2.probability_id;
</code>```

Here is a demo

Body:
Here is how you can join two tables to get the desired result:

CREATE VIEW test_view (Probability) AS
SELECT t1.label
from table_1 t1
left join table_2 t2
on t1.id = t2.probability_id;

Here is a demo


答:
You just have to change the name of the element you are looking for

```<code>print(person_dict['Department'][0]["aaa"])
print(person_dict['Department'][0]["bbb"])
print(person_dict['Department'][0]["ccc"])
</code>```

etc.

You can also do this in a loop depending on what you are trying to achieve, just as an example

```<code>def get_attr(elem, attr):
  if attr in elem:
    return elem[attr]
  return ''

for e in person_dict['Department']:
  print('%s %s %s %s' % (get_attr(e, 'cpt'), get_attr(e, 'aaa'), get_attr(e, 'bbb'), get_attr(e, 'ccc')))
</code>```

Outputs:

```<code>A0001 1 2 3
A0002 6 7 8
A0003 11 21 31
A0004 101 22 33
A0005
A0006 111 24 34
</code>```

Title: Read JSON Array in Python

Body:
You just have to change the name of the element you are looking for

print(person_dict['Department'][0]["aaa"])
print(person_dict['Department'][0]["bbb"])
print(person_dict['Department'][0]["ccc"])

etc.

You can also do this in a loop depending on what you are trying to achieve, just as an example

def get_attr(elem, attr):
  if attr in elem:
    return elem[attr]
  return ''

for e in person_dict['Department']:
  print('%s %s %s %s' % (get_attr(e, 'cpt'), get_attr(e, 'aaa'), get_attr(e, 'bbb'), get_attr(e, 'ccc')))

Outputs:

A0001 1 2 3
A0002 6 7 8
A0003 11 21 31
A0004 101 22 33
A0005
A0006 111 24 34


问:
Line wrap in a JTextArea causes JScrollPane to missbehave with MiGLayout
I am having trouble with the same thing as this guy:

MigLayout JTextArea is not shrinking when used with linewrap=true

and I used the solution described in one of the answers; to set the minimum size explicitly. This works fine if one places the JPanel which contains the JTextArea directly in a JFrame, and then resizes the window.

However, when placing the panel which contains the JTextArea inside a JScrollPane,
the same problem occurs again. Why is this, and how can one fix it?

Cheers

EDIT: An example

```<code>public class MiGTest2 extends JFrame{
public MiGTest2(){
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new MigLayout("fillx, debug", "[fill]"));
    JTextArea textArea  = new JTextArea();
    textArea.setLineWrap(true);
    panel.add(textArea, "wmin 10");
    //panel.add(new JTextField());
    JScrollPane scrollPane = new JScrollPane(panel);
    //add(panel);
    add(scrollPane);
    pack();
}
public static void main(String[] args){
    new MiGTest2().setVisible(true);
}
}
</code>```

If you uncomment //add(panel);, and comment add(scrollPane);, shrinking the window size will also shrink the JTextArea. That is, it does not work with a JScrollPane. Also note how the layout manager seems to flip out and starts "shaking" all its contents when shrinking the size of the window after first enlarging it

答:
Normally, you would put the JTextArea into your JScrollPane. Like this:</p>

```<code>JTextArea area = new JTextArea();
JScrollPane scroll = new JScrollPane(area);
JPanel panel = new JPanel();
panel.add(scroll);
</code>```

Body:
I am having trouble with the same thing as this guy:

MigLayout JTextArea is not shrinking when used with linewrap=true

and I used the solution described in one of the answers; to set the minimum size explicitly. This works fine if one places the JPanel which contains the JTextArea directly in a JFrame, and then resizes the window.

However, when placing the panel which contains the JTextArea inside a JScrollPane,
the same problem occurs again. Why is this, and how can one fix it?

Cheers

EDIT: An example

public class MiGTest2 extends JFrame{
public MiGTest2(){
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new MigLayout("fillx, debug", "[fill]"));
    JTextArea textArea  = new JTextArea();
    textArea.setLineWrap(true);
    panel.add(textArea, "wmin 10");
    //panel.add(new JTextField());
    JScrollPane scrollPane = new JScrollPane(panel);
    //add(panel);
    add(scrollPane);
    pack();
}
public static void main(String[] args){
    new MiGTest2().setVisible(true);
}
}

If you uncomment //add(panel);, and comment add(scrollPane);, shrinking the window size will also shrink the JTextArea. That is, it does not work with a JScrollPane. Also note how the layout manager seems to flip out and starts "shaking" all its contents when shrinking the size of the window after first enlarging it

Body:
Normally, you would put the JTextArea into your JScrollPane. Like this:

JTextArea area = new JTextArea();
JScrollPane scroll = new JScrollPane(area);
JPanel panel = new JPanel();
panel.add(scroll);


问:
Get line number with abstract syntax tree in node js
Im making a program that takes some code via parameter, and transform the code adding some console.logs to the code. This is the program:

```<code>const escodegen = require('escodegen');
const espree = require('espree');
const estraverse = require('estraverse');

function addLogging(code) {
    const ast = espree.parse(code);
    estraverse.traverse(ast, {
        enter: function(node, parent) {
            if (node.type === 'FunctionDeclaration' ||
                node.type === 'FunctionExpression') {
                addBeforeCode(node);
            }
        }
    });
    return escodegen.generate(ast);
}

function addBeforeCode(node) {
    const name = node.id ? node.id.name : '<anonymous function>';
    const beforeCode = "console.log('Entering " + name + "()');";
    const beforeNodes = espree.parse(beforeCode).body;
    node.body.body = beforeNodes.concat(node.body.body);
}
</code>```

So if we pass this code to the function:

```<code>console.log(addLogging(`
function foo(a, b) {
  var x = 'blah';
  var y = (function () {
    return 3;
  })();
}
foo(1, 'wut', 3);
`));
</code>```

This is the output of this program:

```<code>function foo(a, b) {
    console.log('Entering foo()');
    var x = 'blah';
    var y = function () {
        console.log('Entering <anonymous function>()');
        return 3;
    }();
}
foo(1, 'wut', 3);
</code>```

And this is the AST (Abstract Syntax Tree) for that last function passed to addLoggin:

https://astexplorer.net/#/gist/b5826862c47dfb7dbb54cec15079b430/latest

So i wanted to add more information to the console logs like for example the line number we are on. As far as i know, in the ast, the node has a value caled 'start' and 'end' which indicates in which character that node starts and where it ends. How can i use this to get the line number we are on? Seems pretty confusing to me to be honest. I was thinking about doing a split of the file by "\n", so that way i have the total line numbers, but then how can i know i which one im on?

Thank you in advance.

答:
Your idea is fine. First find the offsets in the original code where each line starts. Then compare the start index of the node with those collected indexes to determine the line number.

I will assume here that you want the reported line number to refer to the original code, not the code as it is returned by your function.

So from bottom up, make the following changes. First expect the line number as argument to addBeforeCode:

```<code>function addBeforeCode(node, lineNum) {
    const name = node.id ? node.id.name : '<anonymous function>';
    const beforeCode = `console.log("${lineNum}: Entering ${name}()");`;
    const beforeNodes = espree.parse(beforeCode).body;
    node.body.body = beforeNodes.concat(node.body.body);
}
</code>```

Define a function to collect the offsets in the original code that correspond to the starts of the lines:

```<code>function getLineOffsets(str) {
    const regex = /\r?\n/g;
    const offsets = [0];
    while (regex.exec(str)) offsets.push(regex.lastIndex);
    offsets.push(str.length);
    return offsets;
}
</code>```

NB: If you have support for matchAll, then the above can be written a bit more concise.

Then use the above in your main function:

```<code>function addLogging(code) {
    const lineStarts = getLineOffsets(code);   // <---
    let lineNum = 0;                           // <---
    const ast = espree.parse(code);
    estraverse.traverse(ast, {
        enter: function(node, parent) {
            if (node.type === 'FunctionDeclaration' ||
                     node.type === 'FunctionExpression') {
                // Look for the corresponding line number in the source code:
                while (lineStarts[lineNum] < node.body.body[0].start) lineNum++;
                // Actually we now went one line too far, so pass one less:
                addBeforeCode(node, lineNum-1);
            }
        }
    });
    return escodegen.generate(ast);
}
</code>```

Unrelated to your question, but be aware that functions can be arrow functions, which have an expression syntax. So they would not have a block, and you would not be able to inject a console.log in the same way. You might want to make your code capable to deal with that, or alternatively, to skip over those.

Body:
Im making a program that takes some code via parameter, and transform the code adding some console.logs to the code. This is the program:

const escodegen = require('escodegen');
const espree = require('espree');
const estraverse = require('estraverse');

function addLogging(code) {
    const ast = espree.parse(code);
    estraverse.traverse(ast, {
        enter: function(node, parent) {
            if (node.type === 'FunctionDeclaration' ||
                node.type === 'FunctionExpression') {
                addBeforeCode(node);
            }
        }
    });
    return escodegen.generate(ast);
}

function addBeforeCode(node) {
    const name = node.id ? node.id.name : '<anonymous function>';
    const beforeCode = "console.log('Entering " + name + "()');";
    const beforeNodes = espree.parse(beforeCode).body;
    node.body.body = beforeNodes.concat(node.body.body);
}

So if we pass this code to the function:

console.log(addLogging(`
function foo(a, b) {
  var x = 'blah';
  var y = (function () {
    return 3;
  })();
}
foo(1, 'wut', 3);
`));

This is the output of this program:

function foo(a, b) {
    console.log('Entering foo()');
    var x = 'blah';
    var y = function () {
        console.log('Entering <anonymous function>()');
        return 3;
    }();
}
foo(1, 'wut', 3);

And this is the AST (Abstract Syntax Tree) for that last function passed to addLoggin:

https://astexplorer.net/#/gist/b5826862c47dfb7dbb54cec15079b430/latest

So i wanted to add more information to the console logs like for example the line number we are on. As far as i know, in the ast, the node has a value caled 'start' and 'end' which indicates in which character that node starts and where it ends. How can i use this to get the line number we are on? Seems pretty confusing to me to be honest. I was thinking about doing a split of the file by "\n", so that way i have the total line numbers, but then how can i know i which one im on?

Thank you in advance.

Body:
Your idea is fine. First find the offsets in the original code where each line starts. Then compare the start index of the node with those collected indexes to determine the line number.

I will assume here that you want the reported line number to refer to the original code, not the code as it is returned by your function.

So from bottom up, make the following changes. First expect the line number as argument to addBeforeCode:

function addBeforeCode(node, lineNum) {
    const name = node.id ? node.id.name : '<anonymous function>';
    const beforeCode = `console.log("${lineNum}: Entering ${name}()");`;
    const beforeNodes = espree.parse(beforeCode).body;
    node.body.body = beforeNodes.concat(node.body.body);
}

Define a function to collect the offsets in the original code that correspond to the starts of the lines:

function getLineOffsets(str) {
    const regex = /\r?\n/g;
    const offsets = [0];
    while (regex.exec(str)) offsets.push(regex.lastIndex);
    offsets.push(str.length);
    return offsets;
}

NB: If you have support for matchAll, then the above can be written a bit more concise.

Then use the above in your main function:

function addLogging(code) {
    const lineStarts = getLineOffsets(code);   // <---
    let lineNum = 0;                           // <---
    const ast = espree.parse(code);
    estraverse.traverse(ast, {
        enter: function(node, parent) {
            if (node.type === 'FunctionDeclaration' ||
                     node.type === 'FunctionExpression') {
                // Look for the corresponding line number in the source code:
                while (lineStarts[lineNum] < node.body.body[0].start) lineNum++;
                // Actually we now went one line too far, so pass one less:
                addBeforeCode(node, lineNum-1);
            }
        }
    });
    return escodegen.generate(ast);
}

Unrelated to your question, but be aware that functions can be arrow functions, which have an expression syntax. So they would not have a block, and you would not be able to inject a console.log in the same way. You might want to make your code capable to deal with that, or alternatively, to skip over those.


问:
Add image in pdf using jspdf
I am using jspdf to convert an image into a PDF.

I have converted the image into a URI using base64encode. But the problem is that there are no errors or warnings shown in the console.

A PDF is generated with the text Hello World on it but no image is added in it.

Here is my code.

```<code>function convert(){
        var doc = new jsPDF();
        var imgData = 'data:image/jpeg;base64,'+ Base64.encode('Koala.jpeg');
        console.log(imgData);
        doc.setFontSize(40);
        doc.text(30, 20, 'Hello world!');
        doc.output('datauri');
        doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);

    }
</code>```

答:
For result in base64, before convert to canvas:</p>

```<code>var getBase64ImageUrl = function(url, callback, mine) {

                    var img = new Image();

                    url = url.replace("http://","//");

                    img.setAttribute('crossOrigin', 'anonymous');

                    img.onload = function () {
                        var canvas = document.createElement("canvas");
                        canvas.width =this.width;
                        canvas.height =this.height;

                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(this, 0, 0);

                        var dataURL = canvas.toDataURL(mine || "image/jpeg");

                        callback(dataURL);
                    };
                    img.src = url;

                    img.onerror = function(){

                        console.log('on error')
                        callback('');

                    }

            }

   getBase64ImageUrl('Koala.jpeg', function(img){
         //img is a base64encode result
         //return img;
          console.log(img);

          var doc = new jsPDF();
              doc.setFontSize(40);
              doc.text(30, 20, 'Hello world!');
              doc.output('datauri');
              doc.addImage(img, 'JPEG', 15, 40, 180, 160);
    });
</code>```

Title: Add image in pdf using jspdf

Body:
I am using jspdf to convert an image into a PDF.

I have converted the image into a URI using base64encode. But the problem is that there are no errors or warnings shown in the console.

A PDF is generated with the text Hello World on it but no image is added in it.

Here is my code.

function convert(){
        var doc = new jsPDF();
        var imgData = 'data:image/jpeg;base64,'+ Base64.encode('Koala.jpeg');
        console.log(imgData);
        doc.setFontSize(40);
        doc.text(30, 20, 'Hello world!');
        doc.output('datauri');
        doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);

    }

Body:
For result in base64, before convert to canvas:

var getBase64ImageUrl = function(url, callback, mine) {

                    var img = new Image();

                    url = url.replace("http://","//");

                    img.setAttribute('crossOrigin', 'anonymous');

                    img.onload = function () {
                        var canvas = document.createElement("canvas");
                        canvas.width =this.width;
                        canvas.height =this.height;

                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(this, 0, 0);

                        var dataURL = canvas.toDataURL(mine || "image/jpeg");

                        callback(dataURL);
                    };
                    img.src = url;

                    img.onerror = function(){

                        console.log('on error')
                        callback('');

                    }

            }

   getBase64ImageUrl('Koala.jpeg', function(img){
         //img is a base64encode result
         //return img;
          console.log(img);

          var doc = new jsPDF();
              doc.setFontSize(40);
              doc.text(30, 20, 'Hello world!');
              doc.output('datauri');
              doc.addImage(img, 'JPEG', 15, 40, 180, 160);
    });


问:
Asp.net core 502.5 - Process Failure error when deployed - logging issue
I need some help getting logging working on my asp.net core, mvc version 2.1 site.  I've been able to get the site to write errors to the Event log successfully, but only to the Application/Application EventLog/Source.  I was hoping to set the Source to "MySite", so I can easily filter the logs.

Here's my Program.cs code that produces the 502.5 error when deployed:

```<code>        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            var eventLogSettings = new EventLogSettings();
            eventLogSettings.SourceName = "MySite";

            logging.AddEventLog(eventLogSettings);
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
        })
            .UseIISIntegration()
            .UseStartup<Startup>();
</code>```

When I deploy the site, and go to the /home/index page, I get the 502.5 error and see the following error logged in the Event viewer:

Application: dotnet.exe
CoreCLR Version: 4.6.27019.6
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AggregateException: An error occurred while writing to logger(s). (The source was not found, but some or all event logs could not be searched.  To create the source, you need permission to read all event logs to make sure that the new source name is unique.  Inaccessible logs: Security.) ---> System.Security.SecurityException: The source was not found, but some or all event logs could not be searched.  To create the source, you need permission to read all event logs to make sure that the new source name is unique.  Inaccessible logs: Security.
   at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate)
   at System.Diagnostics.EventLog.SourceExists(String source, String machineName, Boolean wantToCreate)

What am I missing?

答:
Well It was right there in the exception, dang it.
The CoreCLR was bombing out when it tried to verify the source, which didn't exist on the server.
I created the source by running the following command in powershell as administrator:
[System.Diagnostics.EventLog]::CreateEventSource(“MySite”, “Application”)

After that the site worked fine and the errors from it have the source "MySite".

Body:
I need some help getting logging working on my asp.net core, mvc version 2.1 site.  I've been able to get the site to write errors to the Event log successfully, but only to the Application/Application EventLog/Source.  I was hoping to set the Source to "MySite", so I can easily filter the logs.

Here's my Program.cs code that produces the 502.5 error when deployed:

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            var eventLogSettings = new EventLogSettings();
            eventLogSettings.SourceName = "MySite";

            logging.AddEventLog(eventLogSettings);
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
        })
            .UseIISIntegration()
            .UseStartup<Startup>();

When I deploy the site, and go to the /home/index page, I get the 502.5 error and see the following error logged in the Event viewer:

Application: dotnet.exe
CoreCLR Version: 4.6.27019.6
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AggregateException: An error occurred while writing to logger(s). (The source was not found, but some or all event logs could not be searched.  To create the source, you need permission to read all event logs to make sure that the new source name is unique.  Inaccessible logs: Security.) ---> System.Security.SecurityException: The source was not found, but some or all event logs could not be searched.  To create the source, you need permission to read all event logs to make sure that the new source name is unique.  Inaccessible logs: Security.
   at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate)
   at System.Diagnostics.EventLog.SourceExists(String source, String machineName, Boolean wantToCreate)

What am I missing?


问:
How do I load things from GitHub into my code?
I am using  NodeJS and am making a discord bot using lots of API's (i am just playing around with them) and now I am wondering how I can import code from GitHub to my application without downloading it. Thanks!</p>

答:
Do you mean using GitHub like a CDN for code or something? I think that's not recommended. What you can do is adding the code you need from GitHub as a package, installing it with npm like:

$> npm i git+https://git@github.com/user/project.git

More info here: How to install an npm package from GitHub directly?


问:
Javascript filter array by another array of filters
I have a filtersArray which is a bunch of {id, value} and I want to filter my data (also array of JSON objects) to get back only the elements that match all of the filters? Is there a better way to do this than iterating through the arrayOfFilters with each filter using a for loop and doing a filter on each criteria?

the data is an array of JSON objects - ie

```<code>[{formID:1234, name:"sam", email:"sam@gmail.com", status:"open", phone: "333-444-5555"},
 {formID:2155, name:"charlie", email:"charlie@gmail.com", status:"closed", phone: "888-323-1234"},...]
</code>```

and the filtersArray [{"status":"closed"}, {"name":"charlie"}, {"id":2155}...]

I have tried doing

```<code>for(var criteria in arrayOfFilters){
   this.data = this.data.filter( d => d.status === criteria.status)
                    .filter(d => d.name === criteria.name)
                    .filter(d => d.address === criteria.address)...
}
</code>```

it does not work real well since criteria is a JSON object like {"status":"closed"}, {"name":"charlie"}...

答:
```<code>const result = arrayOfData.filter(
                     data => arrayOfFilters.map(d =>d.status).includes(data.status))&&
                             arrayOfFilters.map(d =>d.name).includes(data.name))&&
                             arrayOfFilters.map(d =>d.address).includes(data.address) )
                                 )
</code>```

Or

```<code>let result = []
for(var criteria in arrayOfFilters){
 result.push(this.data.filter( d => d.status === criteria.status &&
                                    d.name === criteria.name &&
                                    d.address === criteria.address)...
}
</code>```

Body:
I have a filtersArray which is a bunch of {id, value} and I want to filter my data (also array of JSON objects) to get back only the elements that match all of the filters? Is there a better way to do this than iterating through the arrayOfFilters with each filter using a for loop and doing a filter on each criteria?

the data is an array of JSON objects - ie

[{formID:1234, name:"sam", email:"sam@gmail.com", status:"open", phone: "333-444-5555"},
 {formID:2155, name:"charlie", email:"charlie@gmail.com", status:"closed", phone: "888-323-1234"},...]

and the filtersArray [{"status":"closed"}, {"name":"charlie"}, {"id":2155}...]

I have tried doing

for(var criteria in arrayOfFilters){
   this.data = this.data.filter( d => d.status === criteria.status)
                    .filter(d => d.name === criteria.name)
                    .filter(d => d.address === criteria.address)...
}

it does not work real well since criteria is a JSON object like {"status":"closed"}, {"name":"charlie"}...

Body:
const result = arrayOfData.filter(
                     data => arrayOfFilters.map(d =>d.status).includes(data.status))&&
                             arrayOfFilters.map(d =>d.name).includes(data.name))&&
                             arrayOfFilters.map(d =>d.address).includes(data.address) )
                                 )

Or

let result = []
for(var criteria in arrayOfFilters){
 result.push(this.data.filter( d => d.status === criteria.status &&
                                    d.name === criteria.name &&
                                    d.address === criteria.address)...
}


问:
How to force UIC to generate ui_mainwindow.h in the source directory using cmake
UIC successfully creates the ui_mainwindow.h file but it stores it in the build directory. This causes the compile time error 'ui_mainwindow.h: No such file or directory found'.

If I add the full path to the ui_mainwindow.h file in the build directory, cmake (catkin_make) successfully builds the project. Obviously I'd like to avoid using the absolute path to a header file in my source code.

The relevant parts of my CMakeLists:

```<code>set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt5 REQUIRED COMPONENTS Widgets Core )
add_executable(monitor src/mainwindow.cpp src/main.cpp src/mainwindow.ui)
qt5_use_modules(monitor Widgets)

target_link_libraries(monitor Qt5::Core Qt5::Widgets ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${OpenCV_LIBRARIES} ${OpenCV_LIBS} )
</code>```

How do I force UIC to build the ui_mainwindow.h file in my source directory. Or how do I include the cmake build directory in my CMakeLists.txt

I've tried

```<code>qt5_wrap_ui (monitor_UI src/mainwindow.ui OPTIONS -o 'ui_mainwindow.h')
add_executable(monitor src/mainwindow.cpp src/main.cpp ${monitor_UI})
</code>```

with no success.

答:
Based on hyde's comment, I simply added the build directory in the includepaths using

```<code>include_directories(
  ${CMAKE_CURRENT_BINARY_DIR}
)
</code>```

which solved my problem.

Body:
UIC successfully creates the ui_mainwindow.h file but it stores it in the build directory. This causes the compile time error 'ui_mainwindow.h: No such file or directory found'.

If I add the full path to the ui_mainwindow.h file in the build directory, cmake (catkin_make) successfully builds the project. Obviously I'd like to avoid using the absolute path to a header file in my source code.

The relevant parts of my CMakeLists:

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt5 REQUIRED COMPONENTS Widgets Core )
add_executable(monitor src/mainwindow.cpp src/main.cpp src/mainwindow.ui)
qt5_use_modules(monitor Widgets)

target_link_libraries(monitor Qt5::Core Qt5::Widgets ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${OpenCV_LIBRARIES} ${OpenCV_LIBS} )

How do I force UIC to build the ui_mainwindow.h file in my source directory. Or how do I include the cmake build directory in my CMakeLists.txt

I've tried

qt5_wrap_ui (monitor_UI src/mainwindow.ui OPTIONS -o 'ui_mainwindow.h')
add_executable(monitor src/mainwindow.cpp src/main.cpp ${monitor_UI})

with no success.

Body:
Based on hyde's comment, I simply added the build directory in the includepaths using

include_directories(
  ${CMAKE_CURRENT_BINARY_DIR}
)

which solved my problem.


问:
ag-grid auto height for entire grid
I can't find a good way to size the grid to fit all rows perfectly.

documentation only points to sizing by % or px.

Since I want it to size based on rows, I came up with the following function. Seem like im re-inventing the wheel, so maybe there is a better way?

```<code>getHeight(type:EntityType) {
    var c = this.Apis[type] && this.Apis[type].api && this.Apis[type].api.rowModel // get api for current grid
        ? this.Apis[type].api.rowModel.rowsToDisplay.length
        : -1;
    return c > 0
        ? (40+(c*21))+'px' // not perfect but close formula for grid height
        : '86%';
}
</code>```

there has to be a less messy way..

答:
```<code>determineHeight() {
    setTimeout(() => {
      console.log(this.gridApi.getDisplayedRowCount());
      if (this.gridApi.getDisplayedRowCount() < 20) {
        this.gridApi.setDomLayout("autoHeight");
      }
      else {
        this.gridApi.setDomLayout("normal");
        document.getElementById('myGrid').style.height = "600px";
      }
    }, 500);
  }
</code>```

Title: ag-grid auto height for entire grid

Body:
I can't find a good way to size the grid to fit all rows perfectly.

documentation only points to sizing by % or px.

Since I want it to size based on rows, I came up with the following function. Seem like im re-inventing the wheel, so maybe there is a better way?

getHeight(type:EntityType) {
    var c = this.Apis[type] && this.Apis[type].api && this.Apis[type].api.rowModel // get api for current grid
        ? this.Apis[type].api.rowModel.rowsToDisplay.length
        : -1;
    return c > 0
        ? (40+(c*21))+'px' // not perfect but close formula for grid height
        : '86%';
}

there has to be a less messy way..


问:
How to make exponents in the SwiftUI
I found the new method in SwiftUI to allow you to create an exponent.

Here what I write code is based in SwiftUI on the Swift Playground.

```<code>import SwiftUI
import PlaygroundSupport

struct V: View {

    var body: some View {

        HStack {

            Text("8")
            Text("2\n").font(Font.system(size: 10))

            }

        }

}

PlaygroundPage.current.setLiveView(V())
</code>```

The \n allows you to break the line and make a new line in UIKit. However, SwiftUI gives you to make a top while break line and make a new line inside the second Text. You can make a size for the Font in the Text.

That's it! You made the exponent in SwiftUI!

答:
The following seems look more naturally... as variant

```<code>var body: some View {
    Text("8") + Text("2").font(.system(.footnote))
                  .baselineOffset(UIFont.systemFontSize * 2 / 3)
}
</code>```

Title: How to make exponents in the SwiftUI

Body:
I found the new method in SwiftUI to allow you to create an exponent.

Here what I write code is based in SwiftUI on the Swift Playground.

import SwiftUI
import PlaygroundSupport

struct V: View {

    var body: some View {

        HStack {

            Text("8")
            Text("2\n").font(Font.system(size: 10))

            }

        }

}

PlaygroundPage.current.setLiveView(V())

The \n allows you to break the line and make a new line in UIKit. However, SwiftUI gives you to make a top while break line and make a new line inside the second Text. You can make a size for the Font in the Text.

That's it! You made the exponent in SwiftUI!

Body:
The following seems look more naturally... as variant

var body: some View {
    Text("8") + Text("2").font(.system(.footnote))
                  .baselineOffset(UIFont.systemFontSize * 2 / 3)
}


问:
Iterate through a list and split into a 1d list
Im trying to loop through a list in python and split words based on characters. I want to return a 1 dimension list as the result.

Example

```<code>wordlist = ['border\collie', 'dog\cat', 'horse\hound'] # slash fix
</code>```

Expected outcome
new_list = ['border', 'collie', 'dog', 'cat', 'horse', 'hound']

Everything that Ive tried results in a 2d list.

```<code>def split_slash_words(text):
    new_list = []
    new_list.append([i.split("\\") for i in text])
    return new_list

</code>```

returned a two dimensional array, and I cannot also resplit the new_list (as it is in a list type)

答:
```<code>import re
wordlist = ['border/collie', 'dog\cat', 'horse/hound']

out = []
for item in wordlist:
    for element in re.findall('\w+', item):
        out.append(element)
</code>```

Output:

```<code>['border', 'collie', 'dog', 'cat', 'horse', 'hound']
</code>```

Body:
Im trying to loop through a list in python and split words based on characters. I want to return a 1 dimension list as the result.

Example

wordlist = ['border\collie', 'dog\cat', 'horse\hound'] # slash fix

Expected outcome
new_list = ['border', 'collie', 'dog', 'cat', 'horse', 'hound']

Everything that Ive tried results in a 2d list.

def split_slash_words(text):
    new_list = []
    new_list.append([i.split("\\") for i in text])
    return new_list

returned a two dimensional array, and I cannot also resplit the new_list (as it is in a list type)

Body:
import re
wordlist = ['border/collie', 'dog\cat', 'horse/hound']

out = []
for item in wordlist:
    for element in re.findall('\w+', item):
        out.append(element)

Output:

['border', 'collie', 'dog', 'cat', 'horse', 'hound']


问:
typeof body changes from string to undefined when placed in a conditional
The last if block does not take in the value of the body variable and converts it to undefined. The console log before the block shows the type of the variable is "string" but somehow in the condition and statement of the conditional the body turns to undefined.

doc = doc.map(el => {
        let { title, body, _id, likes } = el
        if (title && title.length > 20) {
          el = {
            ...el,
            title:`${title.slice(0, 20)}...`,
          }
        } else if (!title || typeof title === 'undefined') {
          el = {
            ...el,
            title: '',
          }
        }
        console.log(typeof body)
        if (body.length > 55) {
          el = {
            ...el,
            body: `${body.slice(0, 55)}...`,
          }
        }
        title = el.title
        body = el.body
        console.log(typeof body)
        return {_id,title,body,likes}
      })
```

<p>The terminal output of the logs is as follows:</p>

```[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
App running on port 5000...
string
undefined
string
undefined
string
undefined
```

The three different results represent three different documents in the doc array and hence the six console log outputs pertaining to each body value and its change.
I do not use semicolons in javascript, could it be the cause of this problem?

答:
Still no idea why the earlier code didn't work but this much smaller code seems to do the trick

```<code>doc = doc.map(el => {
        let { title, body, _id, likes } = el
        body = `${body.slice(0, 55)}...`
        if (title && title.length > 20) {
          title=`${title.slice(0, 20)}...`
        } else if (!title || typeof title === 'undefined') {
          title= '...'
        }
        return {_id,title,body,likes}
      })
</code>```

It works because of the fact that I don't need to check if the length of body is greater than 55, since a smaller value will always restore to its original size. So I trim the body first and then the title.

Thanks to anyone who helped! Will still like to find the error/ problem with earlier code.

Body:
The last if block does not take in the value of the body variable and converts it to undefined. The console log before the block shows the type of the variable is "string" but somehow in the condition and statement of the conditional the body turns to undefined.

doc = doc.map(el => {
        let { title, body, _id, likes } = el
        if (title && title.length > 20) {
          el = {
            ...el,
            title:`${title.slice(0, 20)}...`,
          }
        } else if (!title || typeof title === 'undefined') {
          el = {
            ...el,
            title: '',
          }
        }
        console.log(typeof body)
        if (body.length > 55) {
          el = {
            ...el,
            body: `${body.slice(0, 55)}...`,
          }
        }
        title = el.title
        body = el.body
        console.log(typeof body)
        return {_id,title,body,likes}
      })

The terminal output of the logs is as follows:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
App running on port 5000...
string
undefined
string
undefined
string
undefined

The three different results represent three different documents in the doc array and hence the six console log outputs pertaining to each body value and its change.
I do not use semicolons in javascript, could it be the cause of this problem?

Body:
Still no idea why the earlier code didn't work but this much smaller code seems to do the trick

doc = doc.map(el => {
        let { title, body, _id, likes } = el
        body = `${body.slice(0, 55)}...`
        if (title && title.length > 20) {
          title=`${title.slice(0, 20)}...`
        } else if (!title || typeof title === 'undefined') {
          title= '...'
        }
        return {_id,title,body,likes}
      })

It works because of the fact that I don't need to check if the length of body is greater than 55, since a smaller value will always restore to its original size. So I trim the body first and then the title.

Thanks to anyone who helped! Will still like to find the error/ problem with earlier code.


问:
Are type arguments in interfaces an actual type?
Don't think the title is best wording for this question, I have an interface with two type arguments, and I seem to be able to cast this as both of the types at the same time, see reproducable example:

```<code>interface BaseResult<S : BaseResult<S, E>, E : BaseResult<S, E>> {

    @Suppress("UNCHECKED_CAST")
    fun isSuccess(): Boolean {
        return try {
            val a = this as S //ClassCastException expected
            val b = this as E
            println(a) //com.BaseResultTest$ExampleResult$Error@17d10166
            println(b) //com.BaseResultTest$ExampleResult$Error@17d10166
            true
        } catch (e: Exception) {
            false
        }
    }
}
</code>```

Test:

```<code>class BaseResultTest {

    sealed class ExampleResult: BaseResult<ExampleResult.Success, ExampleResult.Error> {
        object Success: ExampleResult()
        object Error: ExampleResult()
    }

    @Test
    fun test() {
        val error = ExampleResult.Error
        assertEquals(error.isSuccess(), false)
    }
}
</code>```

Am I missing something, or is this a bug in the language? Using v1.3.61

答:
It is type erasure, which works the same way for all generics, not just for interfaces. In this case both casts become equivalent to as BaseResult<*, *>.

Kotlin has a way to avoid it, but only for type parameters of inline methods, not classes or interfaces.

Body:
Don't think the title is best wording for this question, I have an interface with two type arguments, and I seem to be able to cast this as both of the types at the same time, see reproducable example:

interface BaseResult<S : BaseResult<S, E>, E : BaseResult<S, E>> {

    @Suppress("UNCHECKED_CAST")
    fun isSuccess(): Boolean {
        return try {
            val a = this as S //ClassCastException expected
            val b = this as E
            println(a) //com.BaseResultTest$ExampleResult$Error@17d10166
            println(b) //com.BaseResultTest$ExampleResult$Error@17d10166
            true
        } catch (e: Exception) {
            false
        }
    }
}

Test:

class BaseResultTest {

    sealed class ExampleResult: BaseResult<ExampleResult.Success, ExampleResult.Error> {
        object Success: ExampleResult()
        object Error: ExampleResult()
    }

    @Test
    fun test() {
        val error = ExampleResult.Error
        assertEquals(error.isSuccess(), false)
    }
}

Am I missing something, or is this a bug in the language? Using v1.3.61


问:
problem with vue-slick in laravel project
I facing a problem with using vue-slick carousel im my laravel project
I import it in main.js file import VueSlickCarousel from 'vue-slick-carousel'
Vue.use(VueSlickCarousel);

```<code>components: {
        VueSlickCarousel
    },
</code>```

this is the component in my blade file

```<code><VueSlickCarousel :arrows="true" :dots="true">
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <div>4</div>
        </VueSlickCarousel>
</code>```

this is the error in the console
[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

please help me, Thanks in advance.

component code:

```<code>@push('scripts')
<script type="text/x-template" id="products-slider">
    <div class="container" style="overflow:hidden;">
        <div class="row">
            <div class="col-12">
                <h2 class="section-divider">
                    <span>
                        {{__('shop::app.home.new-products')}}
                    </span>
                    {{-- <a href="">view all</a> --}}
                </h2>
                <VueSlickCarousel :arrows="true" :dots="true">
                    <div>1</div>
                    <div>2</div>
                    <div>3</div>
                    <div>4</div>
                </VueSlickCarousel>
                {{-- <section class="regular slider">

                    @foreach (app('Webkul\Product\Repositories\ProductRepository')->getNewProducts() as $productFlat)

                            @include ('shop::products.list.old-card', ['product' => $productFlat])

                    @endforeach
                </section> --}}
            </div>
        </div>
    </div>
</script>

<script>

    Vue.component('products-slider', {
        import VueSlickCarousel from 'vue-slick-carousel',

        template: '#products-slider',

        components: {
            VueSlickCarousel
        },

        data: function() {
            return {
                //products datat from API
                products: [],
            }
        },

        mounted: function () {
            this.fetchProducts();
        },

        methods: {
            // get products API
            getProducts () {
                return axios.get('{{url("/")}}/api/products?new=1&limit=6&order=desc&sort=created_at')
                /* .then(response => {
                    const products = response.data.data;
                    this.products = products;
                    console.log(this.products);
                }) */

                /*try{
                    let prod = await axios.get('http://localhost/kshopnew/public/api/products');
                    const products = prod.data.data;
                    this.products = products;
                }catch(e){

                }*/

                /*.then(response => {
                    this.products = response.data
                })
                .catch(e => {
                    this.errors.push(e)
                })*/
            },

            // fetch products data
            fetchProducts () {
                this.getProducts ().then(response => {
                    const products = response.data.data;
                    this.products = products;
                    /* console.log(this.products); */
                })
            },
        }

    })

</script>
</code>```

@endpush

答:
my problem is fixed with :

```<code>Vue.component("VueSlickCarousel", require("vue-slick-carousel"));
</code>```

instead of:

```<code>import VueSlickCarousel from 'vue-slick-carousel'
components: { VueSlickCarousel }
</code>```

Body:
I facing a problem with using vue-slick carousel im my laravel project
I import it in main.js file import VueSlickCarousel from 'vue-slick-carousel'
Vue.use(VueSlickCarousel);

components: {
        VueSlickCarousel
    },

this is the component in my blade file

<VueSlickCarousel :arrows="true" :dots="true">

1

2

3

4

        </VueSlickCarousel>

this is the error in the console
[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

please help me, Thanks in advance.

component code:

@push('scripts')

@endpush

Body:
my problem is fixed with :

Vue.component("VueSlickCarousel", require("vue-slick-carousel"));

instead of:

import VueSlickCarousel from 'vue-slick-carousel'
components: { VueSlickCarousel }


问:
Assign variables into row numbers in excel
A simple Question, my first row is like: 1,3,5,2,6,4,...

Then I would like my second row is: =R1C1, =R3C1, =R5C1, =R2C1, =R6C1, =R4C1....

In a word, I would "read" the first line as my row number in one certain column.
Is there a function like that?

答:
Use INDEX.  Assuming B1 is the 1, Put this in B2 and copy over:

```<code>=INDEX($A:$A,B1)
</code>```

If one has the Dynamic Array formula then just putting:

```<code>=INDEX(A:A,B1:G1)
</code>```

in B2 would suffice, Excel will spill the results across.

Body:
Use INDEX.  Assuming B1 is the 1, Put this in B2 and copy over:

=INDEX($A:$A,B1)

If one has the Dynamic Array formula then just putting:

=INDEX(A:A,B1:G1)

in B2 would suffice, Excel will spill the results across.


问:
How to load CSS background images in to admin section
I am trying to create a Gutenberg version of my site, and obviously I want the backend editor to show the same view as on the frontend. So .. I have two stylesheets, both put in the theme root (and referenced the right way in functions.php (and they are working correctly)

A frontend sass file (styles.scss)

and a backend sass file (editor-styles.scss)

In both sass files I am including a scss partial called _elements.scss, where I (among other things) insert some custom bullet points for a list:

```<code>.default-checklist-item {  //this is a <li> element
  list-style: none;
  line-height: 3rem;
  position: relative;
  padding-left: 4.5rem;
  margin-bottom: 2rem;
  text-align: left;

  &:before {
    content: "";
    background-image: url('icons/custom/checkmark-round.svg');
    background-repeat: no-repeat;
    width: 3rem;
    height: 3rem;
    position: absolute;
    left: 0;
    top: 0;
    fill: green;
  }
}
</code>```

So both stylesheets will pull the background-image from the same relative path, but obviously the bullets won't show in the editor, becasue the file path here is attached to the https://example.com/wp-admin/ path:

On frontend, the file displays correctly

In the editor the file (obviously) can't be found at https://example.com/wp-admin/

I really desire to make use of the same style partial, so only have to maintain it one place, and absolute paths are impossible, since I work on both local, staging and live environments, so what to do??

答:
How about:

```<code>add_action( 'admin_enqueue_scripts' , function () {

    wp_register_style( 'admin-checklist-handle' , false );
    wp_enqueue_style( 'admin-checklist-handle' );

    wp_add_inline_style( 'admin-checklist-handle' , '.default-checklist-item:before { background-image: url( "' . get_template_directory_uri() . '/icons/custom/checkmark-round.svg" )!important; }' );

} );
</code>```

This should add an inline style element in the admin view. And that should override your default pseudo-element. (untested though)

Body:
I am trying to create a Gutenberg version of my site, and obviously I want the backend editor to show the same view as on the frontend. So .. I have two stylesheets, both put in the theme root (and referenced the right way in functions.php (and they are working correctly)

A frontend sass file (styles.scss)

and a backend sass file (editor-styles.scss)

In both sass files I am including a scss partial called _elements.scss, where I (among other things) insert some custom bullet points for a list:

.default-checklist-item {  //this is a
 element
  list-style: none;
  line-height: 3rem;
  position: relative;
  padding-left: 4.5rem;
  margin-bottom: 2rem;
  text-align: left;

  &:before {
    content: "";
    background-image: url('icons/custom/checkmark-round.svg');
    background-repeat: no-repeat;
    width: 3rem;
    height: 3rem;
    position: absolute;
    left: 0;
    top: 0;
    fill: green;
  }
}

So both stylesheets will pull the background-image from the same relative path, but obviously the bullets won't show in the editor, becasue the file path here is attached to the https://example.com/wp-admin/ path:

On frontend, the file displays correctly

In the editor the file (obviously) can't be found at https://example.com/wp-admin/

I really desire to make use of the same style partial, so only have to maintain it one place, and absolute paths are impossible, since I work on both local, staging and live environments, so what to do??

Body:
How about:

add_action( 'admin_enqueue_scripts' , function () {

    wp_register_style( 'admin-checklist-handle' , false );
    wp_enqueue_style( 'admin-checklist-handle' );

    wp_add_inline_style( 'admin-checklist-handle' , '.default-checklist-item:before { background-image: url( "' . get_template_directory_uri() . '/icons/custom/checkmark-round.svg" )!important; }' );

} );

This should add an inline style element in the admin view. And that should override your default pseudo-element. (untested though)


问:
How can I sum dynamic column's amounts?
Each animation can have one (an only one) theme linked, other themes can be created, also have no animation linked.
How can I sum the amounts of each theme at the bottom of this table ?
This displays 'Array' according to the number of amounts of a column..
(pardon my french)

```<code>--------------------------------------------------------------------------
            | Theme A  | Theme B  | Theme C  | Theme D  |  Theme n  | ...
Animation 1 |       5  |       -  |       -  |       -  |     ...
Animation 2 |       -  |       -  |       -  |       7  |     ...
Animation 3 |       6  |       -  |       -  |       -  |     ...
Animation 4 |       -  |       -  |       9  |       -  |     ...
Animation 5 |       -  |       -  |       -  |       1  |     ...
Animation n ...
       Sums:       11          0          9          8        ...

</code>```

In the database, 'theme' is the id of the linked theme (from the 'themes' table), 'demiJournees' is the amount to sum.

```<code>CREATE TABLE `animations` (
  `id` int(11) NOT NULL,
  `nom` varchar(50) NOT NULL,
  `dateAnim` varchar(11) DEFAULT NULL,
  `theme` int(11) DEFAULT NULL,   // One theme per animation
  `projet` int(11) DEFAULT NULL,
  `partenaires` int(11) DEFAULT NULL,
  `etablissement` int(11) DEFAULT NULL,
  `lieu` int(11) DEFAULT NULL,
  `public` int(11) DEFAULT NULL,
  `effectif` int(11) DEFAULT NULL,
  `demiJournees` int(11) DEFAULT NULL,   // The amount of the theme in an animation
  `matthias` int(11) DEFAULT NULL,
  `noellie` int(11) DEFAULT NULL,
  `benevoles` int(11) DEFAULT NULL,
  `notes` varchar(255) DEFAULT NULL
)
</code>```

Model/AnimationManager.php

```<code>public function sumTheme()
{
    $sql = "SELECT theme, SUM(demiJournees) FROM animations GROUP BY theme";
    $req = $this->db->query($sql);
    $sum = array();
    while ($ligne = $req->fetch())
    {
        $sum[] = new Animation($ligne);
    }
    return $sum;
}

</code>```

View/animation.php

1st loop, display each theme's amount in the animation row (works):

```<code>foreach ($animations as $animation)
{
    foreach ($themes as $theme)
    {
        echo '<td id="' .    $theme->getId()  . '">';
        if ($animation->getTheme() == $theme->getId())
        {
            echo  $animation->getDemiJournees() . '</td>';
        } else {
            echo ' ';
        }
        echo '</td>';
    }
}
</code>```

2nd loop: sum amounts in each theme's column (err: displays 'Array'):

```<code>foreach ($themes as $theme)
{
    echo '<td id="' . $theme->getId() . '">';
    foreach ($animations as $animation)
    {
        if ($animation->getTheme() == $theme->getId())
        {
            echo $animationManager->sumTheme();
        }
      }
    echo '</td>';
}
</code>```

答:
Found it : Changed the 2nd loop with creating a variable to store the sum for each theme:

```<code>foreach ($themes as $theme) {
    echo '<td id="' . $theme->getId() . '">';

    // Initialise a variable for each theme
    $sumTheme = 0;
    foreach ($animations as $animation) {
        if ($animation->getTheme() == $theme->getId()) {
            // Ajoute la valeur à la variable du thème
            $sumTheme += $animation->getDemiJournees();
        }
    }
    // Display the total
    echo $sumTheme;
    echo '</td>';
}```
```

(moved answer inappropriately posted as edit to question)

Title: How can I sum dynamic column's amounts?

Body:
Each animation can have one (an only one) theme linked, other themes can be created, also have no animation linked.
How can I sum the amounts of each theme at the bottom of this table ?
This displays 'Array' according to the number of amounts of a column..
(pardon my french)

--------------------------------------------------------------------------
            | Theme A  | Theme B  | Theme C  | Theme D  |  Theme n  | ...
Animation 1 |       5  |       -  |       -  |       -  |     ...
Animation 2 |       -  |       -  |       -  |       7  |     ...
Animation 3 |       6  |       -  |       -  |       -  |     ...
Animation 4 |       -  |       -  |       9  |       -  |     ...
Animation 5 |       -  |       -  |       -  |       1  |     ...
Animation n ...
       Sums:       11          0          9          8        ...

In the database, 'theme' is the id of the linked theme (from the 'themes' table), 'demiJournees' is the amount to sum.

CREATE TABLE `animations` (
  `id` int(11) NOT NULL,
  `nom` varchar(50) NOT NULL,
  `dateAnim` varchar(11) DEFAULT NULL,
  `theme` int(11) DEFAULT NULL,   // One theme per animation
  `projet` int(11) DEFAULT NULL,
  `partenaires` int(11) DEFAULT NULL,
  `etablissement` int(11) DEFAULT NULL,
  `lieu` int(11) DEFAULT NULL,
  `public` int(11) DEFAULT NULL,
  `effectif` int(11) DEFAULT NULL,
  `demiJournees` int(11) DEFAULT NULL,   // The amount of the theme in an animation
  `matthias` int(11) DEFAULT NULL,
  `noellie` int(11) DEFAULT NULL,
  `benevoles` int(11) DEFAULT NULL,
  `notes` varchar(255) DEFAULT NULL
)

Model/AnimationManager.php

public function sumTheme()
{
    $sql = "SELECT theme, SUM(demiJournees) FROM animations GROUP BY theme";
    $req = $this->db->query($sql);
    $sum = array();
    while ($ligne = $req->fetch())
    {
        $sum[] = new Animation($ligne);
    }
    return $sum;
}

View/animation.php

1st loop, display each theme's amount in the animation row (works):

foreach ($animations as $animation)
{
    foreach ($themes as $theme)
    {
        echo 'getId()  . '">';
        if ($animation->getTheme() == $theme->getId())
        {
            echo  $animation->getDemiJournees() . '	';
        } else {
            echo ' ';
        }
        echo '	';
    }
}

2nd loop: sum amounts in each theme's column (err: displays 'Array'):

foreach ($themes as $theme)
{
    echo 'getId() . '">';
    foreach ($animations as $animation)
    {
        if ($animation->getTheme() == $theme->getId())
        {
            echo $animationManager->sumTheme();
        }
      }
    echo '	';
}

Body:
Found it : Changed the 2nd loop with creating a variable to store the sum for each theme:

foreach ($themes as $theme) {
    echo '<td id="' . $theme->getId() . '">';

    // Initialise a variable for each theme
    $sumTheme = 0;
    foreach ($animations as $animation) {
        if ($animation->getTheme() == $theme->getId()) {
            // Ajoute la valeur à la variable du thème
            $sumTheme += $animation->getDemiJournees();
        }
    }
    // Display the total
    echo $sumTheme;
    echo '</td>';
}```

(moved answer inappropriately posted as edit to question)


问:
Grep to extract one-line comments starting with or enclosed in forward slash/asterisk
I'm trying to make a regex to identify a comment. It has to start with // and end with a new line or a *) pattern.</p>

答:
Without your inputfile it is hard to understand what you want.

I think the comments don't start at the beginning of the line and you only want to see the comments. Try this:

```<code>grep -Eon '//.*|^/\*.*\*/' WindchillFactor.java
</code>```

Body:
Without your inputfile it is hard to understand what you want.

I think the comments don't start at the beginning of the line and you only want to see the comments. Try this:

grep -Eon '//.*|^/\*.*\*/' WindchillFactor.java


问:
How can I turn this jquery into a function?
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the href> tag somewhere.

html code

```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="linkpage.htm" class="newslink1">Link 1</a></li>
    <li><a href="linkpage.htm" class="newslink2">Link 2</a></li>
    <li><a href="linkpage.htm" class="newslink3">Link 3</a></li>
</ul>
</code>```

jquery

```<code>$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});
</code>```

答:
```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="linkpage.htm" class="newslink" rel='1.png'>Link 1</a></li>
    <li><a href="linkpage.htm" class="newslink" rel='2.png'>Link 2</a></li>
    <li><a href="linkpage.htm" class="newslink" rel='3.png'>Link 3</a></li>
</ul>

$('a.newslink').bind('mouseover', function() {
    $('img#storyimg').attr("src", $(this).attr('rel'));
});
</code>```

Body:
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the  tag somewhere.

html code

Link 1

Link 2

Link 3

jquery

$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});