问:
PowerShell to Get SharePoint Calendar items
I am looking for an option to get SharePoint Calendar items using PowerShell. Could you please answer if you have better way to achieve?

I wants to download all calendar items as csv format from windows 10 machines.

Thank you in advance.

答:
You could get all fields use the following code:

```<code>$username = "amos@contoso.onmicrosoft.com"
$password = "password."
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
$SiteURL = "https://contoso.sharepoint.com/sites/dev"
$ListName = "cal2"
$CSVPath = "C:\Temp\ListData.csv"
$ListDataCollection= @()

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials $cred
$Counter = 0
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000

#Get all items from list
$ListItems | ForEach-Object {
        $ListItem  = Get-PnPProperty -ClientObject $_ -Property FieldValuesAsText
        $ListRow = New-Object PSObject
        $Counter++
        Get-PnPField -List $ListName | ForEach-Object {
            $ListRow | Add-Member -MemberType NoteProperty -name $_.InternalName -Value $ListItem[$_.InternalName]
            }
        Write-Progress -PercentComplete ($Counter / $($ListItems.Count)  * 100) -Activity "Exporting List Items..." -Status  "Exporting Item $Counter of $($ListItems.Count)"
        $ListDataCollection += $ListRow
}
#Export the result Array to CSV file
$ListDataCollection | Export-CSV $CSVPath -NoTypeInformation
</code>```

If you want to custom columns outputed,

```<code>$username = "amos@contoso.onmicrosoft.com"
$password = "password."
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
$SiteURL = "https://contoso.sharepoint.com/sites/dev"
$ListName = "cal2"
$CSVPath = "C:\Temp\ListData.csv"
$ListDataCollection= @()

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials $cred
$Counter = 0
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000

foreach($item in $ListItems)
{
$ListDataCollection += New-Object PSObject -Property @{
                Title          = $Item["Title"]
                Location = $Item["Location"]
                EventDate =  $Item["EventDate"]
                EndDate=  $Item["EndDate"]#you can add column you want to output
            }

}
#Export the result Array to CSV file
$ListDataCollection | Export-CSV $CSVPath -NoTypeInformation
</code>```

https://www.sharepointdiary.com/2016/03/export-list-items-to-csv-in-sharepoint-online-using-powershell.html

Body:
You could get all fields use the following code:

$username = "amos@contoso.onmicrosoft.com"
$password = "password."
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
$SiteURL = "https://contoso.sharepoint.com/sites/dev"
$ListName = "cal2"
$CSVPath = "C:\Temp\ListData.csv"
$ListDataCollection= @()

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials $cred
$Counter = 0
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000

#Get all items from list
$ListItems | ForEach-Object {
        $ListItem  = Get-PnPProperty -ClientObject $_ -Property FieldValuesAsText
        $ListRow = New-Object PSObject
        $Counter++
        Get-PnPField -List $ListName | ForEach-Object {
            $ListRow | Add-Member -MemberType NoteProperty -name $_.InternalName -Value $ListItem[$_.InternalName]
            }
        Write-Progress -PercentComplete ($Counter / $($ListItems.Count)  * 100) -Activity "Exporting List Items..." -Status  "Exporting Item $Counter of $($ListItems.Count)"
        $ListDataCollection += $ListRow
}
#Export the result Array to CSV file
$ListDataCollection | Export-CSV $CSVPath -NoTypeInformation

If you want to custom columns outputed,

$username = "amos@contoso.onmicrosoft.com"
$password = "password."
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
$SiteURL = "https://contoso.sharepoint.com/sites/dev"
$ListName = "cal2"
$CSVPath = "C:\Temp\ListData.csv"
$ListDataCollection= @()

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials $cred
$Counter = 0
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000

foreach($item in $ListItems)
{
$ListDataCollection += New-Object PSObject -Property @{
                Title          = $Item["Title"]
                Location = $Item["Location"]
                EventDate =  $Item["EventDate"]
                EndDate=  $Item["EndDate"]#you can add column you want to output
            }

}
#Export the result Array to CSV file
$ListDataCollection | Export-CSV $CSVPath -NoTypeInformation

https://www.sharepointdiary.com/2016/03/export-list-items-to-csv-in-sharepoint-online-using-powershell.html


来源: stackexchange

问:
How to inflate ViewStub from fragment
I'm unable to inflate the ViewStub from a fragment.
When I tried to inflate it from an Activity it works fine.

Here's my code:
Dashboard.java

```<code>    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
        infographics = view.findViewById(R.id.infographicStub);
        infographics.setLayoutResource(R.layout.dashboard_infographics);
        infographics.inflate();
        infographics.setVisibility(View.VISIBLE);
        return view;
</code>```

fragment_dashboard.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/dashboardLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    android:paddingTop="20dp"
    tools:context=".dashboard.fragments.Dashboard">

    <ViewStub
        android:id="@+id/infographicStub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inflatedId="@+id/subTree"
        android:layout="@layout/dashboard_infographics"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:id="@+id/lightContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/style_light_container"
        android:backgroundTint="@color/colorSecondary"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/infographicStub">

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

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Can anyone tell me what I'm doing wrong?
Thanks in advance

答:
As mentioned by @IntelliJ Amiya in the comment section.

```<code><ViewStub android:id="@+id/infographicStub"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inflatedId="@+id/infographicStub"
android:layout="@layout/dashboard_infographics"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</code>```

This code will show the viewStub content but in my case it was overlapping so using another thread I resolved it.
https://stackoverflow.com/a/17215221/10386411

ContentLicense: CC BY-SA 4.0

Title: How to inflate ViewStub from fragment

Body:
I'm unable to inflate the ViewStub from a fragment.
When I tried to inflate it from an Activity it works fine.

Here's my code:
Dashboard.java

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
        infographics = view.findViewById(R.id.infographicStub);
        infographics.setLayoutResource(R.layout.dashboard_infographics);
        infographics.inflate();
        infographics.setVisibility(View.VISIBLE);
        return view;

fragment_dashboard.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/dashboardLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    android:paddingTop="20dp"
    tools:context=".dashboard.fragments.Dashboard">

    <ViewStub
        android:id="@+id/infographicStub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inflatedId="@+id/subTree"
        android:layout="@layout/dashboard_infographics"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:id="@+id/lightContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/style_light_container"
        android:backgroundTint="@color/colorSecondary"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/infographicStub">

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

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Can anyone tell me what I'm doing wrong?
Thanks in advance

Body:
As mentioned by @IntelliJ Amiya in the comment section.

<ViewStub android:id="@+id/infographicStub"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inflatedId="@+id/infographicStub"
android:layout="@layout/dashboard_infographics"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

This code will show the viewStub content but in my case it was overlapping so using another thread I resolved it.
https://stackoverflow.com/a/17215221/10386411


问:
Using multiple mapped types for objects key/values. Need only one value from union?
Having some trouble trying to get the type to work correctly here.

I want to specify in an object that each top-level key is one of the strings from a union, and the value is a nested object that has keys of one of the strings from another union, and its value can be the string from the first union (kind of like a state-machine).

Eg:

```<code>type Status = 'idle' | 'loading' | 'error' | 'view'
type Actions = 'search' | 'search_success' | 'search_failure'

const app = {
  idle: {
    search: 'loading'
  },
  loading: {
    search_success: 'view',
    search_fail: 'error',
  },
  error: {
    search: 'loading'
  }
  view: {
    search: 'loading'
  }
}
</code>```

My attempts to type this have been:

```<code>type States = { [key in Status]: { [key in Actions]: Status } };
</code>```

Though this doesn't work. Could somebody explain how I could make use of some utility types possibly to allow the nested object key to not require ALL values from the Actions type?

Thanks!

答:
The answer from @MoshFeu looks like it'll work fine, but as I've written this up, I'll post it to say that you can get more or less the same thing with a Partial:

type Status = 'idle' | 'loading' | 'error' | 'view'
type Actions = 'search' | 'search_success' | 'search_failure'

type States = { [key in Status]: Partial<{ [key in Actions]: Status }> };

const app: States = {
  idle: {
    search: 'loading'
  },
  loading: {
    search_success: 'view',
    search_failure: 'error',
  },
  error: {
    search: 'loading'
  },
  view: {
    search: 'loading'
  }
};
```

Body:
Having some trouble trying to get the type to work correctly here.

I want to specify in an object that each top-level key is one of the strings from a union, and the value is a nested object that has keys of one of the strings from another union, and its value can be the string from the first union (kind of like a state-machine).

Eg:

type Status = 'idle' | 'loading' | 'error' | 'view'
type Actions = 'search' | 'search_success' | 'search_failure'

const app = {
  idle: {
    search: 'loading'
  },
  loading: {
    search_success: 'view',
    search_fail: 'error',
  },
  error: {
    search: 'loading'
  }
  view: {
    search: 'loading'
  }
}

My attempts to type this have been:

type States = { [key in Status]: { [key in Actions]: Status } };

Though this doesn't work. Could somebody explain how I could make use of some utility types possibly to allow the nested object key to not require ALL values from the Actions type?

Thanks!


问:
Right Tooltip Menu using HTML CSS Bootstrap
I am trying to create a menu which opens up to the right like a tooltip. I tried various bootstrap methods. I am not able to add HTML li in the tooltip.

答:
You can use a little bit of jquery for that and enabling the data-html attribute equal to true if the html is complex i-e data-html="true". Then you can use html inside tooltip like this:

$('.tooltip-demo.well').tooltip({
  selector: "a[rel=tooltip]"
})
```

<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>

<div class="tooltip-demo well">
  <p style="margin-bottom: 0;" class="muted">Tight pants next level keff chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four loko mcsweeney's cleanse vegan chambray. A <b>OH WOWOWO</b> <em>one</em> here too</h1>" data-html="true" rel="tooltip"
      href="#">really ironic artisan w
  </p>
</div>
</code>```

Body:
You can use a little bit of jquery for that and enabling the data-html attribute equal to true if the html is complex i-e data-html="true". Then you can use html inside tooltip like this:

$('.tooltip-demo.well').tooltip({
  selector: "a[rel=tooltip]"
})

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>

<div class="tooltip-demo well">
  <p style="margin-bottom: 0;" class="muted">Tight pants next level keff chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four loko mcsweeney's cleanse vegan chambray. A <a title="<h1><b>OH WOWOWO</b> <em>one</em> here too</h1>" data-html="true" rel="tooltip"
      href="#">really ironic</a> artisan w
  </p>
</div>


问:
Fish: for loop: Too many args for cd command
If I run a script

```<code>#!/usr/bin/fish
cd /home/user/repos/repo1
pwd
</code>```

works as intended (changes directory and prints that path).

When I place the same logic into a for loop, cd complains about too many arguments even though there are no space and .

#! /usr/bin/fish

set REPOS "/home/user/repos/repo1" "/home/user/repos/repo1"

for REPO_PATH in $REPOS:
    echo $REPO_PATH
    cd $REPO_PATH
    pwd
end
```

<p>Using relative paths doesn't help,</p>

<pre class="lang-sh prettyprint-override"><code>set REPOS "~/repos/repo1" "~/repos/repo1"
</code>```

using variables without quotes work outside for loop, same complaint inside for loop.

Works in bash like this

#!/bin/bash
repos=("/home/user/repos/repo1" "/home/user/repos/repo1")
for path in "${repos[@]}"
do
    cd $path
    pwd
done
```

I've read List and Loops section of fish documentation.
I've noticed that cd has a fish-wrapper. Could that be the issue?

答:
Remove the colon.

The reason this shows the error "Too many arguments" is that calling a variable "...PATH" causes fish to interpret it as a path variable, which means that it will be split on ":" (like $PATH, $LD_LIBRARY_PATH etc).

So fish goes, sets $REPO_PATH to "/home/user/repos/repo1:", then splits it on the ":", making it a list of "/home/user/repos/repo1" and "".

That's then passed to cd as two arguments, one being empty, and cd complains about having a second spurious argument.

So just use

```<code>set REPOS "/home/user/repos/repo1" "/home/user/repos/repo1"

for REPO_PATH in $REPOS
    echo $REPO_PATH
    cd $REPO_PATH
    pwd
end
</code>```

Body:
If I run a script

#!/usr/bin/fish
cd /home/user/repos/repo1
pwd

works as intended (changes directory and prints that path).

When I place the same logic into a for loop, cd complains about too many arguments even though there are no space and .

#! /usr/bin/fish

set REPOS "/home/user/repos/repo1" "/home/user/repos/repo1"

for REPO_PATH in $REPOS:
    echo $REPO_PATH
    cd $REPO_PATH
    pwd
end

Using relative paths doesn't help,

set REPOS "~/repos/repo1" "~/repos/repo1"

using variables without quotes work outside for loop, same complaint inside for loop.

Works in bash like this

#!/bin/bash
repos=("/home/user/repos/repo1" "/home/user/repos/repo1")
for path in "${repos[@]}"
do
    cd $path
    pwd
done

I've read List and Loops section of fish documentation.
I've noticed that cd has a fish-wrapper. Could that be the issue?

Body:
Remove the colon.

The reason this shows the error "Too many arguments" is that calling a variable "...PATH" causes fish to interpret it as a path variable, which means that it will be split on ":" (like $PATH, $LD_LIBRARY_PATH etc).

So fish goes, sets $REPO_PATH to "/home/user/repos/repo1:", then splits it on the ":", making it a list of "/home/user/repos/repo1" and "".

That's then passed to cd as two arguments, one being empty, and cd complains about having a second spurious argument.

So just use

set REPOS "/home/user/repos/repo1" "/home/user/repos/repo1"

for REPO_PATH in $REPOS
    echo $REPO_PATH
    cd $REPO_PATH
    pwd
end


问:
how does py2app add custom modules
I try to create from a python script using flask framework a standalone mac app with py2app. The application uses the framework pyfladesk for render website within a desktop window. On testing everything works fine, but as soon as I try to deploy the app with py2app , the  folders get bundled and the app is created. But as soon as I start the app, it halts. Looking in terminal it shows a ModuleNotFoundError. The module pyfladesk is not found.
How do I add 3 party modules to a py2app project. I tried the same procedure with pyinstaller as well with the same result.

Note: the module was added with pip3 and is located inside the venv of the given folder.

答:
Solved the issue, it turns out, py2app does not rely on the dependencies from venv, but rather on the installed one.
Solution: pip3 install pyfladesk and all other used packages
update dependency search path in setup.py:

OPTIONS = {'argv_emulation': True,
           'packages': ['requests', 'jinja2', 'pyfladesk']
           }

Title: how does py2app add custom modules


问:
Running Jupyter Notebook with Different Configurations from CLI
I started to use Jupyter Notebook for my project and I use nbconvert to run it from the command line.

I want to know that is there any way to have a .ipynb file and run it with some command-line arguments or reading from stdin somewhere?

I read nbconvert documentation but I didn’t find out a way to do it.

If there is no way to do something like those, I want to know what is the best practice to have a single .ipynb file and run with different configurations?

Thank you in advance.

答:
I found a tool named papermill for parameterizing and executing Jupyter Notebooks.

Here's a a link to its documentation and how to parameterize your notebook.


问:
problem in Laravel to show vueJs component
I'm using VueJs in my laravel blade. i define component to use as a child in one of components ,now component is not defined.

defined component in app.js

```<code>Vue.component('phoneSearch', require('./components/admin/booking/PhoneSearch').default);
</code>```

my component code :

<template>

</template>

```
</div>
</div>
</p>

<p>and that parent component that i want call child in:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> <template>

    </template>

    <script>
        export default {
            name: "add-passenger",

        components: {  phoneSearch },
        }
    </script>

    <style scoped>

    </style></code>```

finally i got this error in console after run:

```<code>Uncaught ReferenceError: phoneSearch is not defined
at Module../node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/admin/booking/AddPassenger.vue?vue&type=script&lang=js& (app_admin.js:7878)
at __webpack_require__ (app_admin.js:20)
at Module../resources/js/components/admin/booking/AddPassenger.vue?vue&type=script&lang=js& (app_admin.js:144061)
at __webpack_require__ (app_admin.js:20)
at Module../resources/js/components/admin/booking/AddPassenger.vue (app_admin.js:144025)
at __webpack_require__ (app_admin.js:20)
at Object../resources/js/app_admin.js (app_admin.js:141625)
at __webpack_require__ (app_admin.js:20)
at Object.1 (app_admin.js:144544)
at __webpack_require__ (app_admin.js:20)
</code>```

anyone can help me?

答:
As @ashutosh has mentioned, you need to import that component to register it:</p>

```<code> <template>
  <div>
    <phoneSearch />
  </div>
</template>

<script>
    import phoneSearch from './your-directory/your-component.vue';

    export default {
        name: "add-passenger",
        components: {  phoneSearch },
    }
</script>

<style scoped>

</style>
</code>```

Body:
I'm using VueJs in my laravel blade. i define component to use as a child in one of components ,now component is not defined.

defined component in app.js

Vue.component('phoneSearch', require('./components/admin/booking/PhoneSearch').default);

my component code :

<template>

</template>

and that parent component that i want call child in:

 <template>

    </template>

finally i got this error in console after run:

Uncaught ReferenceError: phoneSearch is not defined
at Module../node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/admin/booking/AddPassenger.vue?vue&type=script&lang=js& (app_admin.js:7878)
at __webpack_require__ (app_admin.js:20)
at Module../resources/js/components/admin/booking/AddPassenger.vue?vue&type=script&lang=js& (app_admin.js:144061)
at __webpack_require__ (app_admin.js:20)
at Module../resources/js/components/admin/booking/AddPassenger.vue (app_admin.js:144025)
at __webpack_require__ (app_admin.js:20)
at Object../resources/js/app_admin.js (app_admin.js:141625)
at __webpack_require__ (app_admin.js:20)
at Object.1 (app_admin.js:144544)
at __webpack_require__ (app_admin.js:20)

anyone can help me?

Body:
As @ashutosh has mentioned, you need to import that component to register it:

 <template>
  <div>
    <phoneSearch />
  </div>
</template>

<script>
    import phoneSearch from './your-directory/your-component.vue';

    export default {
        name: "add-passenger",
        components: {  phoneSearch },
    }
</script>

<style scoped>

</style>


问:
Are there any languages that handle functional impurity (side effects) without modeling them as RealWorld or IO?
One thing that always bothered me in Haskell (and other functional languages, for that matter) is that the entire language is pure, but side-effects are indirectly allowed by using an object that represents the entire "real world" (the IO monad, for example).

I wonder, are there languages that handle this without modeling the entire world? For example, representing network input as a byte array that is lazily filled as the network input is read.

答:
Haskell itself was specified to use something like you describe before IO (the monad) was invented, under the name dialogues.  The following example is from Imperative functional programming (the seminal paper on IO) by Peyton Jones and Wadler, 1993:

type Dialogue = [Response] -> [Request]
main :: Dialogue

data Request = Putc Char | Getc
data Response = OK | OKCh Char

echo :: Dialogue
echo resps = Getc :
             if (a == eof)
             then []
             else Putc a :
                  echo (drop 2 resps)
           where
             OKCh a = resps !! 1
```

It is preceded by the explanation:

The I/O system specifed for the Haskell language (Hudak et al. [1992])
  is based on dialogues, also called lazy streams (Dwelly [1989];
  O'Donnell [1985]; Thompson [1989]). In Haskell, the value of the
  program has type Dialogue, a  synonym for a function between a list
  of I/O responses to a list of I/O requests.

and concluded with some difficulties:

It is easy to extract the wrong element of the responses, a synchronisation error,

The Response data type has to contain a constructor for every possible response to every request, and

even more seriously, the style is not composable.

Body:
Haskell itself was specified to use something like you describe before IO (the monad) was invented, under the name dialogues.  The following example is from Imperative functional programming (the seminal paper on IO) by Peyton Jones and Wadler, 1993:

type Dialogue = [Response] -> [Request]
main :: Dialogue

data Request = Putc Char | Getc
data Response = OK | OKCh Char

echo :: Dialogue
echo resps = Getc :
             if (a == eof)
             then []
             else Putc a :
                  echo (drop 2 resps)
           where
             OKCh a = resps !! 1

It is preceded by the explanation:

The I/O system specifed for the Haskell language (Hudak et al. [1992])
  is based on dialogues, also called lazy streams (Dwelly [1989];
  O'Donnell [1985]; Thompson [1989]). In Haskell, the value of the
  program has type Dialogue, a  synonym for a function between a list
  of I/O responses to a list of I/O requests.

and concluded with some difficulties:

It is easy to extract the wrong element of the responses, a synchronisation error,

The Response data type has to contain a constructor for every possible response to every request, and

even more seriously, the style is not composable.


问:
Creating an Uri in .NET automatically urldecodes all parameters from passed string
Suppose I want to create an Uri object from the following string:

```<code>string url = @"http://someserver.com?param1=1&url=http%3a%2f%2fwww.otherserver.com";
Uri uri = new Uri(url, UriKind.Absolute);
</code>```

Expected result would be:

```<code>http://someserver.com?param1=1&url=http%3a%2f%2fwww.otherserver.com
</code>```

Obtained:

```<code>http://someserver.com/?param1=1&url=http://www.otherserver.com
</code>```

The same behavior is noticed in many related methods that allow Uri creation: Uri.TryCreate, UriBuilder.Uri, etc.

How would I get an Uri that preserve initial encoded parameter?

答:
I recommend using the library Flurl. It allows a fluent and correct build and analysis of URIs. See their examples. https://flurl.dev/docs/fluent-url/

It is available as NuGet package. You don't need the HTTP-Stuff

```<code>    using Flurl;

    var url = "http://www.some-api.com"
    .AppendPathSegment("endpoint")
    .SetQueryParams(new {
        api_key = ConfigurationManager.AppSettings["SomeApiKey"],
        max_results = 20,
        q = "Don't worry, I'll get encoded!"
    })
    .SetFragment("after-hash");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose I want to create an Uri object from the following string:

string url = @"http://someserver.com?param1=1&url=http%3a%2f%2fwww.otherserver.com";
Uri uri = new Uri(url, UriKind.Absolute);

Expected result would be:

http://someserver.com?param1=1&url=http%3a%2f%2fwww.otherserver.com

Obtained:

http://someserver.com/?param1=1&url=http://www.otherserver.com

The same behavior is noticed in many related methods that allow Uri creation: Uri.TryCreate, UriBuilder.Uri, etc.

How would I get an Uri that preserve initial encoded parameter?

Body:
I recommend using the library Flurl. It allows a fluent and correct build and analysis of URIs. See their examples. https://flurl.dev/docs/fluent-url/

It is available as NuGet package. You don't need the HTTP-Stuff

    using Flurl;

    var url = "http://www.some-api.com"
    .AppendPathSegment("endpoint")
    .SetQueryParams(new {
        api_key = ConfigurationManager.AppSettings["SomeApiKey"],
        max_results = 20,
        q = "Don't worry, I'll get encoded!"
    })
    .SetFragment("after-hash");


问:
setvbuf not changing buffer size?
I have the following toy code to test out I/O buffering on fread, and I'm getting results that I didn't expect:

```<code>#include <stdio.h>
#include <stdio_ext.h>

int main()
{
    FILE *fp;
    char buff[255];
    fp = fopen("/home/install.sh", "r");
    int result = setvbuf(fp, NULL, _IOFBF, 700); // set buffering size to some arbitrary value, say 700
    printf("Result of setting buffer: %d\n", result ); // "Result of setting buffer: 0"
    printf("Buffer size: %zd\n", __fbufsize(fp) ); // "Buffer size: 4096"

    fread(buff, 255, 1, fp);
    printf("%s\n", buff ); // prints 255 bytes as I would expect

}
</code>```

From above, it seems like the setvbuf call was successful as it returned 0, however the buffer size stays at 4096. Moreover, I tried printing out BUFSIZ and it says 8192. Running strace does show the underlying read call as being 4096 bytes. Turning off buffering seems to work fine, as buffer size gets set to 1.

Moreover, I don't understand why BUFSIZ (8192) is not the same as the default value of these reads (4096).

I tried many different values for the buffer size but to no avail.

I am running ldd (Ubuntu GLIBC 2.27-3ubuntu1) 2.27

答:
setvbuf not changing buffer size?

Glibc setvbuf implementation just ignores the size argument when mode == _IOFBF and buff == NULL. Which is fine - characteristics of buffering modes are implementation defined. And __fbufsize is a nonstandard extensions. Generally you shouldn't depend on the buffering of the underlying FILE.

I don't understand why BUFSIZ (8192) is not the same as the default value of these reads (4096).

Glibc does mmap the file. Because of mmap the size get's rounded to page size.

Title: setvbuf not changing buffer size?

Body:
I have the following toy code to test out I/O buffering on fread, and I'm getting results that I didn't expect:

#include <stdio.h>
#include <stdio_ext.h>

int main()
{
    FILE *fp;
    char buff[255];
    fp = fopen("/home/install.sh", "r");
    int result = setvbuf(fp, NULL, _IOFBF, 700); // set buffering size to some arbitrary value, say 700
    printf("Result of setting buffer: %d\n", result ); // "Result of setting buffer: 0"
    printf("Buffer size: %zd\n", __fbufsize(fp) ); // "Buffer size: 4096"

    fread(buff, 255, 1, fp);
    printf("%s\n", buff ); // prints 255 bytes as I would expect

}

From above, it seems like the setvbuf call was successful as it returned 0, however the buffer size stays at 4096. Moreover, I tried printing out BUFSIZ and it says 8192. Running strace does show the underlying read call as being 4096 bytes. Turning off buffering seems to work fine, as buffer size gets set to 1.

Moreover, I don't understand why BUFSIZ (8192) is not the same as the default value of these reads (4096).

I tried many different values for the buffer size but to no avail.

I am running ldd (Ubuntu GLIBC 2.27-3ubuntu1) 2.27


问:
Django REST framework: want to switch API processing depending on conditions
I want to replace all processes of a specific API according to specific conditions (settings or database value).

Example : it usually returns a value from the DB, but returns a fixed value for a specific client.

I thought that it is possible by using middleware, I implemented the following, but it does not work.

error content
"The response content must be rendered before it can be accessed"

I would like to render it, but please tell me how to do it.

# extensions.test_middleware
from extensions.hoge import hogehoge

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.path == '/api/v1/hogehoge/':
            return hogehoge(request)
        response = self.get_response(request)
        return response
```

<pre class="lang-py prettyprint-override"><code># extensions.hoge
from rest_framework import status
from rest_framework.response import Response

def hogehoge(request):
    return Response(status=status.HTTP_200_OK)
</code>```

# settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'extensions.test_middleware.SimpleMiddleware'
]
```

```[ERROR] 2020-05-21 12:58:53,658 log 1320 /usr/local/lib/python3.7/site-packages/django/utils/log.py 228 Internal Server Error: /api/v1/hogehoge/
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/utils/deprecation.py", line 96, in __call__
    response = self.process_response(request, response)
  File "/usr/local/lib/python3.7/site-packages/django/middleware/common.py", line 112, in process_response
    response['Content-Length'] = str(len(response.content))
  File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 128, in content
    'The response content must be rendered before it can be accessed.'
django.template.response.ContentNotRenderedError: The response content must be rendered before it can be accessed.
[ERROR] 2020-05-21 12:58:53,659 basehttp 1320 /usr/local/lib/python3.7/site-packages/django/core/servers/basehttp.py 154 "GET /api/v1/hogehoge/ HTTP/1.1" 500 65447
```

答:
Although it is not the best, I got a good implementation, so I will answer it myself.

# extensions.test_middleware
from django.http import JsonResponse
from rest_framework.request import Request

from extensions.hoge import HogeView

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        # if view_func.__name__ == 'HogeView': # compare by class name
        if request.path == '/api/v1/hogehoge/': # compare by class url path
            # Django and DRF have different Request
            # convert django.core.handlers.wsgi.WSGIRequest to rest_framework.request.Request
            req = Request(request)
            res = HogeView.get(HogeView, req)

            # process_view must return django.http.Response
            # DRF's view returns rest_framework.response.Response
            # convert rest_framework.response.Response to django.http.Response
            return JsonResponse(res.data, status=res.status_code)
        else:
            return None
```

<pre class="lang-py prettyprint-override"><code># extensions.hoge.HogeView
from rest_framework.response import Response
from rest_framework.views import APIView
class HogeView(APIView):
    def get(self, request):
        return Response({'aaa': 'bbb'})
</code>```

# settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'extensions.test_middleware.SimpleMiddleware'
]
```

Body:
I want to replace all processes of a specific API according to specific conditions (settings or database value).

Example : it usually returns a value from the DB, but returns a fixed value for a specific client.

I thought that it is possible by using middleware, I implemented the following, but it does not work.

error content
"The response content must be rendered before it can be accessed"

I would like to render it, but please tell me how to do it.

# extensions.test_middleware
from extensions.hoge import hogehoge

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.path == '/api/v1/hogehoge/':
            return hogehoge(request)
        response = self.get_response(request)
        return response

# extensions.hoge
from rest_framework import status
from rest_framework.response import Response

def hogehoge(request):
    return Response(status=status.HTTP_200_OK)

# settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'extensions.test_middleware.SimpleMiddleware'
]

[ERROR] 2020-05-21 12:58:53,658 log 1320 /usr/local/lib/python3.7/site-packages/django/utils/log.py 228 Internal Server Error: /api/v1/hogehoge/
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/utils/deprecation.py", line 96, in __call__
    response = self.process_response(request, response)
  File "/usr/local/lib/python3.7/site-packages/django/middleware/common.py", line 112, in process_response
    response['Content-Length'] = str(len(response.content))
  File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 128, in content
    'The response content must be rendered before it can be accessed.'
django.template.response.ContentNotRenderedError: The response content must be rendered before it can be accessed.
[ERROR] 2020-05-21 12:58:53,659 basehttp 1320 /usr/local/lib/python3.7/site-packages/django/core/servers/basehttp.py 154 "GET /api/v1/hogehoge/ HTTP/1.1" 500 65447

Body:
Although it is not the best, I got a good implementation, so I will answer it myself.

# extensions.test_middleware
from django.http import JsonResponse
from rest_framework.request import Request

from extensions.hoge import HogeView

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        # if view_func.__name__ == 'HogeView': # compare by class name
        if request.path == '/api/v1/hogehoge/': # compare by class url path
            # Django and DRF have different Request
            # convert django.core.handlers.wsgi.WSGIRequest to rest_framework.request.Request
            req = Request(request)
            res = HogeView.get(HogeView, req)

            # process_view must return django.http.Response
            # DRF's view returns rest_framework.response.Response
            # convert rest_framework.response.Response to django.http.Response
            return JsonResponse(res.data, status=res.status_code)
        else:
            return None

# extensions.hoge.HogeView
from rest_framework.response import Response
from rest_framework.views import APIView
class HogeView(APIView):
    def get(self, request):
        return Response({'aaa': 'bbb'})

# settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'extensions.test_middleware.SimpleMiddleware'
]


问:
how can i fix that android studio does not accept or detect my xml layouts when doing setContentView()?
Dunno why but every time I create a new Activity, Fragment or whatever it says that the layout doesn't exist (when the layout is generated with the activity) and I can clearly see the XML file in my layout folder but the android studio says it doesn't exist.

Any help?

The error I got

i let u a image where u cant see the R.layout.etc marking an error
at the left u can see the folder layout with the correct layout

答:
Please go to file-->Invalidate cache/Restart.
Android Studio will detect the layout file.

Happy Coding!


问:
NgRX - Store Modelling
Im creating an interface to send notifications.
The form will have the following fields:

title

message

users <-- Autocomplete

Im not sure how to model the state for this behaviour.

I already have an store:

```<code>export interface NotificationState extends EntityState<NotificationModle> {
  loading: boolean;
  loaded: boolean;
  total: number;
  current_page: number;
  per_page: number;
}
</code>```

Should I add a new users properties to my state or create a new one?

答:
What you have for NotificationModel is correct.

User is a separate entity and should have its own EntityState.

Title: NgRX - Store Modelling

Body:
Im creating an interface to send notifications.
The form will have the following fields:

title

message

users <-- Autocomplete

Im not sure how to model the state for this behaviour.

I already have an store:

export interface NotificationState extends EntityState<NotificationModle> {
  loading: boolean;
  loaded: boolean;
  total: number;
  current_page: number;
  per_page: number;
}

Should I add a new users properties to my state or create a new one?


问:
question about shift operation and bracket operation
```<code>for(i=0; i<8 ;i++)
{
    SRCLK = 0;
    SER = (sendData>>7);
    sendData <<= 1;
    SRCLK = 1;
}
</code>```

and

```<code>for(i=0; i<8 ;i++)
{
    SRCLK = 0;
    SER = (sendData>>(7-i));
    SRCLK = 1;
}
</code>```

i think there is no difference bettween them. i builded the code and download to my 51MCU. i use SER to send serial data to 74HC595, these codes displayed different phenomenon. thank for your explanation of this question.

答:
first, thank the guys @ChrisDodd and @dixv for help.
actually, SER represent the pin3.4 of 51MCU, so it can just recieve bool data 0 or 1.so the code SER = sendData; is NOT to give the last bit to SER but to run follow mission:

judge sendData equal 0 or not

sendData equal 0, then give false 0 to SER. in contrast, 1 to SER

eg: if LED means pin0.0 of 51MCU

LED = 0x0a;//0x08 = 0000 1010, the last bit is 0, but LED = 1

Body:
for(i=0; i<8 ;i++)
{
    SRCLK = 0;
    SER = (sendData>>7);
    sendData <<= 1;
    SRCLK = 1;
}

and

for(i=0; i<8 ;i++)
{
    SRCLK = 0;
    SER = (sendData>>(7-i));
    SRCLK = 1;
}

i think there is no difference bettween them. i builded the code and download to my 51MCU. i use SER to send serial data to 74HC595, these codes displayed different phenomenon. thank for your explanation of this question.


问:
Why can't add tags into terraform modules
I got some problem to provision with tags on Azure database for PostgreSQL services, My code be like

```<code>module "postgresql" {
  source = "./modules/postgresql"
  service               = var.service
  .
  .
  .
  tags = { test = "test" }
</code>```

And error happend

```<code>53:  tags = {

An argument named "tags" is not expected here.
</code>```

Why always happened like this, Actually in the Resource_Group module has tags but It doesn't error at all
, I'm kinda confused about this Does anyone knows about this please help me and Thank you for your kind help

答:
As the error stated: "An argument named "tags" is not expected here.", you should define the variable tags in your child module when you're calling a child module because most of the arguments correspond to input variables defined by the module. Alternatively, if the resources does not support tags arguments, you can not use tags under that resource.

For example, you will have input variable tags in your modules configuration file if the resources support tags.

```<code>variable "tags" {

}
...

resource "azurerm_virtual_network" "myterraformnetwork" {
  name                = var.vnetname
  address_space       = var.address_space
  location            = var.location
  resource_group_name = var.rgname
  tags = var.tags
}
</code>```

Body:
I got some problem to provision with tags on Azure database for PostgreSQL services, My code be like

module "postgresql" {
  source = "./modules/postgresql"
  service               = var.service
  .
  .
  .
  tags = { test = "test" }

And error happend

53:  tags = {

An argument named "tags" is not expected here.

Why always happened like this, Actually in the Resource_Group module has tags but It doesn't error at all
, I'm kinda confused about this Does anyone knows about this please help me and Thank you for your kind help

Body:
As the error stated: "An argument named "tags" is not expected here.", you should define the variable tags in your child module when you're calling a child module because most of the arguments correspond to input variables defined by the module. Alternatively, if the resources does not support tags arguments, you can not use tags under that resource.

For example, you will have input variable tags in your modules configuration file if the resources support tags.

variable "tags" {

}
...

resource "azurerm_virtual_network" "myterraformnetwork" {
  name                = var.vnetname
  address_space       = var.address_space
  location            = var.location
  resource_group_name = var.rgname
  tags = var.tags
}


问:
update_post_meta add latest data from meta_value array
I want to add list of color to a product attribute with following code: </p>

```<code>function wcproduct_set_attributes($post_id, $_attributes) {
        $i = 0;
            foreach ($_attributes as $name => $value) {
                wp_set_object_terms($post_id, $value, $name);
                $product_attributes[$i] = array (
                    'name' => $name, // set attribute name
                    'value' => $value, // set attribute value
                    'is_visible' => 0,
                    'is_variation' => 1,
                    'is_taxonomy' => 1
                );
            }
            $i++;

        update_post_meta($post_id, '_product_attributes', $product_attributes);
    };

    wcproduct_set_attributes($_product_id_data, $my_product_attributes);
</code>```

<p>$product_attributes is an array of colors and $name is pa_color and $value is color name. this function works but it add last color to pa_color.</p>

答:
The final parameter wp_set_object_terms function need to be true.So,

```<code>wp_set_object_terms($post_id, $value, $name, true);
</code>```

I must add true at the last parameter.

Body:
I want to add list of color to a product attribute with following code:

function wcproduct_set_attributes($post_id, $_attributes) {
        $i = 0;
            foreach ($_attributes as $name => $value) {
                wp_set_object_terms($post_id, $value, $name);
                $product_attributes[$i] = array (
                    'name' => $name, // set attribute name
                    'value' => $value, // set attribute value
                    'is_visible' => 0,
                    'is_variation' => 1,
                    'is_taxonomy' => 1
                );
            }
            $i++;

        update_post_meta($post_id, '_product_attributes', $product_attributes);
    };

    wcproduct_set_attributes($_product_id_data, $my_product_attributes);

$product_attributes is an array of colors and $name is pa_color and $value is color name. this function works but it add last color to pa_color.

Body:
The final parameter wp_set_object_terms function need to be true.So,

wp_set_object_terms($post_id, $value, $name, true);

I must add true at the last parameter.


问:
Reinforcement Learning tools
What is the difference between Tensorforce, Kerasrl, and chainerrl used for Reinforcement Learning?
AS far as I've found all three work with OpenAI gym environments and have the same reinforcement learning algorithms that have been implemented. Is there a difference in performance?

答:
they are different Deep learning bank-ends.
TensorFlow , Keras and Chainer are different libraries used for inference of Neural network based AI algorithms.
Open AI is a Reinforcement Learning library.
These are two different technologies.
if you want Reinforcement learning for Tensorflow, back-end and RL tf library, checkout

https://github.com/google/dopamine

This has no connection with OpenAI. Pure Google tech.

Title: Reinforcement Learning tools


问:
SwiftUI ZStack alignment bug
Here is a simple code that produces a strange top alignment and shrunk text of the second element inside ZStack.

BUT if you change the second text a bit (replace text2 by text2Alt1 or by text2Alt2) making it longer or shorter everything becomes correct.

What is the reason for this behavior?

struct VCardView: View {
    let text: String
    let color: UIColor

    var body: some View {
        VStack {
            Rectangle()
                .fill(Color(self.color))
                .frame(idealWidth: 800, idealHeight: 500)
                .aspectRatio(contentMode: .fit)

            Text(self.text)
        }
    }
}

struct ContentView: View {
    var body: some View {
        ZStack(alignment: .topLeading) {
            VCardView(text: text1, color: .blue)
                .frame(width: 180, height: nil)
                .alignmentGuide(.leading) { _ in 180 }
                .alignmentGuide(.top) { _ in 0 }

            //Replace text2 by text2Alt1 or text2Alt2 here:
            VCardView(text: text2, color: .green)
                .frame(width: 180, height: nil)
                .alignmentGuide(.leading) { _ in 0 }
                .alignmentGuide(.top) { _ in 0 }
        }
    }

    let text1 = "1Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidu!"

    let text2 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis nat!"

    let text2Alt1 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. C"

    let text2Alt2 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis nat! Cum sociis nat!"
}

```

Also, you could replace Rectangle() by Image() with appropriate proportions because it was the initial state. Rectangle with the ideal size is just for demonstration.

Here I use ZStack with explicit alignment guides (not HStack) because it's a part of another library. It is essential.

XCode 11.5
iOS 13.5 iPhone SE 2020

Bug looks like this:

Expected layout:

答:
I've seen such Text truncation problems often in SwiftUI. The workaround which most of the time helps: ensure that Text is allowed to adjust it's font size automatically using the minimumScaleFactor modifier.

By modifying VCardView

Text(self.text)
    .minimumScaleFactor(0.5)
```

The misalignment problem disappears for all possible text values (text1, text2, text2Alt1 and text2Alt2).

The resulting text does not look scaled at all. Everything fits nicely.
I do not have a good explanation, but I think if you tell SwiftUI that your Text is not 100% rigid/stiff, it performs better in calculating the elements extents.

Perhaps it is a SwiftUI bug, but I was always OK with this minimumScaleFactor workaround as it hadn't negatively impacted my results.

Title: SwiftUI ZStack alignment bug

Body:
Here is a simple code that produces a strange top alignment and shrunk text of the second element inside ZStack.

BUT if you change the second text a bit (replace text2 by text2Alt1 or by text2Alt2) making it longer or shorter everything becomes correct.

What is the reason for this behavior?

struct VCardView: View {
    let text: String
    let color: UIColor

    var body: some View {
        VStack {
            Rectangle()
                .fill(Color(self.color))
                .frame(idealWidth: 800, idealHeight: 500)
                .aspectRatio(contentMode: .fit)

            Text(self.text)
        }
    }
}

struct ContentView: View {
    var body: some View {
        ZStack(alignment: .topLeading) {
            VCardView(text: text1, color: .blue)
                .frame(width: 180, height: nil)
                .alignmentGuide(.leading) { _ in 180 }
                .alignmentGuide(.top) { _ in 0 }

            //Replace text2 by text2Alt1 or text2Alt2 here:
            VCardView(text: text2, color: .green)
                .frame(width: 180, height: nil)
                .alignmentGuide(.leading) { _ in 0 }
                .alignmentGuide(.top) { _ in 0 }
        }
    }

    let text1 = "1Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidu!"

    let text2 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis nat!"

    let text2Alt1 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. C"

    let text2Alt2 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis nat! Cum sociis nat!"
}

Also, you could replace Rectangle() by Image() with appropriate proportions because it was the initial state. Rectangle with the ideal size is just for demonstration.

Here I use ZStack with explicit alignment guides (not HStack) because it's a part of another library. It is essential.

XCode 11.5
iOS 13.5 iPhone SE 2020

Bug looks like this:

Expected layout:

Body:
I've seen such Text truncation problems often in SwiftUI. The workaround which most of the time helps: ensure that Text is allowed to adjust it's font size automatically using the minimumScaleFactor modifier.

By modifying VCardView

Text(self.text)
    .minimumScaleFactor(0.5)

The misalignment problem disappears for all possible text values (text1, text2, text2Alt1 and text2Alt2).

The resulting text does not look scaled at all. Everything fits nicely.
I do not have a good explanation, but I think if you tell SwiftUI that your Text is not 100% rigid/stiff, it performs better in calculating the elements extents.

Perhaps it is a SwiftUI bug, but I was always OK with this minimumScaleFactor workaround as it hadn't negatively impacted my results.


问:
Google Bearer auth on http request via Node-RED
I want to use the AutoML API via Node-RED and I have the request URL, but I have to create a bearer token from the service account .json somehow regularly, because the token expires in 3.600 seconds. Any clue how I can achieve this or any other idea how to call the AutoML API in a different way?

Any help is very, very much appreciated!

答:
To do this you probably need 2 flows working together.

The first uses an inject node to every hour (3600 seconds) that gets a new auth token. This token is stored in a context variable.

You can then use this context variable to set the right headers on the http-request node to AutoML API


问:
Unable to make Google Analytics filter work
I wish to create a custom filter on Google Analytics (GA), that would allow me to block all views except the genuine ones onto my webpage.

I want to do this because the google-analytics ID associated with my property (UA-XXXXXXXX-X) is public. Hence in theory, my analytics data is open to attack.

I was trying to follow the instructions here. As suggested I created a custom filter to exclude any hits from Hostnames other than my webpage (or any sub-webpages) - https://ishank-juneja.github.io/. In particular the steps I followed were -

New filter --> custom -->  include --> Choose filter field as Hostname

Then I entered the filter pattern as https://ishank-juneja\.github\.io/. Which I believe is the correct regex corresponding to my site URL/Hostname.

I thought this would be enough to make the filter work, however to be sure, I changed the filter type to exclude instead of include, expecting that if the configuration is correct this filter would start rejecting hits from the url https://ishank-juneja.github.io/ and any of its sub-pages.

However when I clicked the filter verification button available at the bottom of the create-filter page, I received the message-

"This filter would not have changed your data. Either the filter configuration is incorrect, or the set of sampled data is too small."

Since I am certain that all my earlier hits were from the mentioned url, it seems that the filter is not configured correctly even in the include mode.

Any help in correcting the working of the filter, so that only hits from the desired Hostname are recorded, would be appreciated.

答:
Try to use this regex for hostname (without protocol and trailing slash):</p>

```<code>ishank-juneja\.github\.io
</code>```

Body:
Try to use this regex for hostname (without protocol and trailing slash):

ishank-juneja\.github\.io


问:
ERROR 1449 (HY000): The user specified as a definer ('mysql.infoschema'@'localhost') does not exist
I am trying to list all tables from mysql database on ubuntu os. But I am getting this error all time;

```<code>mysql> use mysql;
Database changed
mysql> show tables;
ERROR 1449 (HY000): The user specified as a definer ('mysql.infoschema'@'localhost') does not exist
</code>```

I have checked my mysql version:

```<code>mysql  Ver 8.0.20 for Linux on x86_64 (MySQL Community Server - GPL)
</code>```

So it seems it is last version of mysql.

How can I fix this error?

Please help

答:
This error occurs when there is any view / trigger in that database (mysql in your case) that has a definer (in other words a user) that is a definer for the view but then the user itself doesnt exists. A fresh install of mysql should have that user

```<code>mysql> select user,host from mysql.user where user='mysql.infoschema';
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mysql.infoschema | localhost |
+------------------+-----------+
1 row in set (0.00 sec)
</code>```

With the permissions :

```<code>mysql> show grants for 'mysql.infoschema'@'localhost';
+-------------------------------------------------------+
| Grants for mysql.infoschema@localhost                 |
+-------------------------------------------------------+
| GRANT SELECT ON *.* TO `mysql.infoschema`@`localhost` |
+-------------------------------------------------------+
1 row in set (0.00 sec)
</code>```

For some reason that user is missing / deleted in your users list and is why when you list tables its also checking for views in it and complaining about its missing definer.

Solution :

Simply create the user with the permissions above and that should stop showing the error.

Create user:

```<code>mysql> CREATE USER 'mysql.infoschema'@'localhost' IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.00 sec)
</code>```

Grant permissions:

```<code>mysql> GRANT SELECT ON *.* TO `mysql.infoschema`@`localhost`;
Query OK, 0 rows affected, 1 warning (0.00 sec)
</code>```

Body:
I am trying to list all tables from mysql database on ubuntu os. But I am getting this error all time;

mysql> use mysql;
Database changed
mysql> show tables;
ERROR 1449 (HY000): The user specified as a definer ('mysql.infoschema'@'localhost') does not exist

I have checked my mysql version:

mysql  Ver 8.0.20 for Linux on x86_64 (MySQL Community Server - GPL)

So it seems it is last version of mysql.

How can I fix this error?

Please help

Body:
This error occurs when there is any view / trigger in that database (mysql in your case) that has a definer (in other words a user) that is a definer for the view but then the user itself doesnt exists. A fresh install of mysql should have that user

mysql> select user,host from mysql.user where user='mysql.infoschema';
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mysql.infoschema | localhost |
+------------------+-----------+
1 row in set (0.00 sec)

With the permissions :

mysql> show grants for 'mysql.infoschema'@'localhost';
+-------------------------------------------------------+
| Grants for mysql.infoschema@localhost                 |
+-------------------------------------------------------+
| GRANT SELECT ON *.* TO `mysql.infoschema`@`localhost` |
+-------------------------------------------------------+
1 row in set (0.00 sec)

For some reason that user is missing / deleted in your users list and is why when you list tables its also checking for views in it and complaining about its missing definer.

Solution :

Simply create the user with the permissions above and that should stop showing the error.

Create user:

mysql> CREATE USER 'mysql.infoschema'@'localhost' IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.00 sec)

Grant permissions:

mysql> GRANT SELECT ON *.* TO `mysql.infoschema`@`localhost`;
Query OK, 0 rows affected, 1 warning (0.00 sec)


问:
How to read uptill a particular character in a file, without going through the file, character by character?
Want to detect the '\n' without going through each and every character of a text file. Any hints?</p>

答:
Something has to read all the bytes to check for that delimiter.

Use one of the getline (or istream::getline) functions so that the library does the searching, not your code.


问:
Exclude file in Visual Studio from git Commit by default
Several developers are working on a project and each one has their own connection string in Web.Config.
Every once in a while (usually few hours!!) a developer forgets to exclude web.config from their commit and soon everyone has to go though the cycle of getting an error, discovering that its because of wrong connection string, and correct it.
The reason is that when people choose to commit their changes, VS adds all changes to commit. They can exclude it, but they forget.

Is there a way to exclude a file from commits By Default?
Please note that this is different from excluding the file from repository which can be done in .gitignore.

答:
You can save the connection string in Windows Registry. This way you can maintain different registry values for different machines (ex: if the different database name is used for test server and production server).

More info:
https://my.axerosolutions.com/spaces/5/communifire-documentation/wiki/view/757/sql-connection-string-in-registry


问:
Snowflake Stages - Can nt see
We have been loading data through ETL tool to snowflake tables, however when I executed "show stages in account " command in snowflake, it did not return any stages defined. I do not think any one of us have created external stages yet, but I was expecting to see at least the result of Snowflake managed internal stage.

Could it be my access issue ? or something else is happening ? We are connecting to snowflake through ODBC driver while loading the data.

Thank you

答:
We have been loading data through ETL tool to snowflake tables,
  however when I executed "show stages in account " command in
  snowflake, it did not return any stages defined.

It's possible to load data without using a STAGE object. Snowflake supports loading files directly from an external location:

https://docs.snowflake.com/en/sql-reference/sql/copy-into-table.html#loading-files-directly-from-an-external-location

I was expecting to see at least the result of Snowflake managed
  internal stage.

If you mean "table stages", they are not separate database objects; rather, they are implicit stages tied to the table itself. Table stages cannot be altered or dropped. Therefore they are not listed with SHOW STAGES command.

Title: Snowflake Stages - Can nt see


问:
BatchUpdateException is not continues the flow once exception occurs
My business scenario is to read a csv file and its contents and then persist in to the oracle database.

Consider that csv file having 1000 rows in it. Iterating each line and their columns values and setting in to preparedstatement and then adding in to batch using preparedStatement.addBatch() and then executing the batch. refer example below.

```<code>try {
  for(List<String> mainList:dataList) { //lines
     int i=1;
     ps = conn.prepareStatement(insertQuery);
     for(String value:mainList) { //column values
        ps.setString(i++, value);
     }
     ps.addBatch();
  }
  int[] updateCounts = ps.executeBatch(); //50th record not valid

  } catch(BatchUpdateException e){
       int[] updateCounts = e.getUpdateCounts();
  }
</code>```

Here addbatch will have all lines(1000) and values, say example 50th record values is not valid. As of now batch executed(inserted) 49 records properly in database table. At the time of 50th record insertion, executebatch throwing BatchUpdateException (it might be any issue) in catch block since not a valid record.

After this, flow is blocked and does not continues to execute the remaining 950 records in the batch. what I want is once exception is thrown my code should run and insert remaining 950 records in the database.

Please help to resolve this issue or provide me any other alternate way to achieve this logic.

CSV sample:

```<code>Name,Id,Firstname,Lastname
Bharathi,2070,Bharathi,Raja   --> row 1
Craig,Text,Craig,Johnson      --> row 2
Mary,9346,Mary,Jenk           --> row 3
</code>```

Consider row 2 is the 50th record, value for the Id is Text which is not valid it should be number so exception thrown.

I'm having below dependencies in pom.xml and using Spring Boot Application

```<code><dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>
</code>```

答:
The official Oracle JDBC drivers are on central maven. Sample GAV is as shown below.  </p>

```<code><dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>
</code>```

Body:
My business scenario is to read a csv file and its contents and then persist in to the oracle database.

Consider that csv file having 1000 rows in it. Iterating each line and their columns values and setting in to preparedstatement and then adding in to batch using preparedStatement.addBatch() and then executing the batch. refer example below.

try {
  for(List<String> mainList:dataList) { //lines
     int i=1;
     ps = conn.prepareStatement(insertQuery);
     for(String value:mainList) { //column values
        ps.setString(i++, value);
     }
     ps.addBatch();
  }
  int[] updateCounts = ps.executeBatch(); //50th record not valid

  } catch(BatchUpdateException e){
       int[] updateCounts = e.getUpdateCounts();
  }

Here addbatch will have all lines(1000) and values, say example 50th record values is not valid. As of now batch executed(inserted) 49 records properly in database table. At the time of 50th record insertion, executebatch throwing BatchUpdateException (it might be any issue) in catch block since not a valid record.

After this, flow is blocked and does not continues to execute the remaining 950 records in the batch. what I want is once exception is thrown my code should run and insert remaining 950 records in the database.

Please help to resolve this issue or provide me any other alternate way to achieve this logic.

CSV sample:

Name,Id,Firstname,Lastname
Bharathi,2070,Bharathi,Raja   --> row 1
Craig,Text,Craig,Johnson      --> row 2
Mary,9346,Mary,Jenk           --> row 3

Consider row 2 is the 50th record, value for the Id is Text which is not valid it should be number so exception thrown.

I'm having below dependencies in pom.xml and using Spring Boot Application

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>

Body:
The official Oracle JDBC drivers are on central maven. Sample GAV is as shown below.

<dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>


问:
The mysqli_connect not working
I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.

```<code>$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
</code>```

Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?

My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?

答:
If you pass no values, I think MySQL is using defaults from the settings ini. So maybe this happens too if you pass empty values.  In that case the connection could actually be established, and the result won't 'die'. Best thing is to use var_dump to check what $dbc contains after the call and continue from there.

But anyway, there is no way, PHP is going to tell you which settings to use if you don't remember them. :)

Title: The mysqli_connect not working

Body:
I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.

$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');

Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?

My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?


问:
Menu problems driving me NUTS
I have a WordPress site running the DIVI theme which works OK except for the menu.
When the browser width is < 982 the menu is the hamburger, all well and good.
When the browser window is > 982 & < 1516 the menu is vertical NOT what is required.
When the browser window is > 1516 the menu is horizontal which is what I hoped it would be!

Furthermore, I have the sticky plugin installed such that as the user scrolls the menu sticks at the top of the page, at this point the vertical menu becomes horizontal.

I have spent hours trying to solve this, got passed logic and went deep into poke and hope which is not my choice of problem-solving, no joy.

Does anyone have a clue as to what the problem can be? My theory is that it is something so stupid I have been missing it for days.

You can see the problem at https://udsl.com

Many thanks.

答: After much aggravation, a friend suggested that it might not be something I had done wrong. Turned out she was right, was a bug in the template update. Good that it was not my error, annoying for al the time wasted trying to find my mistake that was not there!</p>

Title: Menu problems driving me NUTS


问:
Question about the difference between Integer triple pointer and float triple pointer
I'm doing a project for school and they force us to use a type float triple pointer in a function that multiply two matrices,
and for the last day i can't figure out why when I'm using int triple pointer I get the numbers needed but when I'm using float I get zeros.
I wrote something simple just for example for the problem.
Thank you !!

```<code>    int ***ptr3;
    int Matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
    int i;

    ptr3 = malloc(sizeof(int));
    ptr3 = Matrix;
    for (i = 0; i < 9; i++) {printf_s("%d ", ptr3[i]);}

    printf_s("\n");

    float ***ptr3_f;
    float Matrix_f[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    ptr3_f = malloc(sizeof(float));
    ptr3_f = Matrix_f;
    for (i = 0; i < 9; i++) {printf_s("%.1f ", ptr3_f[i]);}

</code>```

enter image description here

答:
You don't need triple pointer for such arrays.

With:

```<code>#include <stdio.h>

#include <stdlib.h>

int main()
{

    int *ptr3_i;
    int Matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    float *ptr3_f;
    float Matrix_f[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    int i;

    ptr3_i = (int *)Matrix;
    printf("ptr3_i:");
    for (i = 0; i < 9; i++)
        printf("%d ", ptr3_i[i]);
    printf("\n");

    ptr3_f = (float *)Matrix_f;
    printf("ptr3_f:");
    for (i = 0; i < 9; i++)
        printf("%.1f ", ptr3_f[i]);
    printf("\n");

    return 0;
}
</code>```

I get:

```<code>ptr3_i:1 2 3 4 5 6 7 8 9
ptr3_f:1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
</code>```

Body:
I'm doing a project for school and they force us to use a type float triple pointer in a function that multiply two matrices,
and for the last day i can't figure out why when I'm using int triple pointer I get the numbers needed but when I'm using float I get zeros.
I wrote something simple just for example for the problem.
Thank you !!

    int ***ptr3;
    int Matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
    int i;

    ptr3 = malloc(sizeof(int));
    ptr3 = Matrix;
    for (i = 0; i < 9; i++) {printf_s("%d ", ptr3[i]);}

    printf_s("\n");

    float ***ptr3_f;
    float Matrix_f[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    ptr3_f = malloc(sizeof(float));
    ptr3_f = Matrix_f;
    for (i = 0; i < 9; i++) {printf_s("%.1f ", ptr3_f[i]);}

enter image description here

Body:
You don't need triple pointer for such arrays.

With:

#include <stdio.h>

#include <stdlib.h>

int main()
{

    int *ptr3_i;
    int Matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    float *ptr3_f;
    float Matrix_f[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    int i;

    ptr3_i = (int *)Matrix;
    printf("ptr3_i:");
    for (i = 0; i < 9; i++)
        printf("%d ", ptr3_i[i]);
    printf("\n");

    ptr3_f = (float *)Matrix_f;
    printf("ptr3_f:");
    for (i = 0; i < 9; i++)
        printf("%.1f ", ptr3_f[i]);
    printf("\n");

    return 0;
}

I get:

ptr3_i:1 2 3 4 5 6 7 8 9
ptr3_f:1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0


问:
reactjs how to filter / check if a any object in an array is present in another array of objects?
im facing the issue when trying to implement some conditional rendering. Here is the context:

the data:

```<code>groups_a : [
             {id:1} ,
             {id:2}
            ]

groups_b : [
             {id:1} ,
             {id:3}
            ]
</code>```

The condition:

I wish to be check each item in groups_b , whether they exist in groups_a . So in this case , the condition should return back true because groups_b has id:1 and so does groups_a

JSX :

```<code>            {###the condition ##
                         ?
            <Button>Approve</Button>
            :
            null
            }
</code>```

答:
checkout this </p>

```<code>function App(){

    const groupA = [{id:1}, {id:2}];
    const groupB = [{id:1}, {id:3}];

    const gourpAIds = groupA.map(item => item.id);

    return groupB.map(item => {
        if(gourpAIds.includes(item.id)){
            return <Button>Approve</Button>   ;
        }else{
            return null;
        }
    });

}
</code>```

Body:
im facing the issue when trying to implement some conditional rendering. Here is the context:

the data:

groups_a : [
             {id:1} ,
             {id:2}
            ]

groups_b : [
             {id:1} ,
             {id:3}
            ]

The condition:

I wish to be check each item in groups_b , whether they exist in groups_a . So in this case , the condition should return back true because groups_b has id:1 and so does groups_a

JSX :

            {###the condition ##
                         ?
            <Button>Approve</Button>
            :
            null
            }

Body:
checkout this

function App(){

    const groupA = [{id:1}, {id:2}];
    const groupB = [{id:1}, {id:3}];

    const gourpAIds = groupA.map(item => item.id);

    return groupB.map(item => {
        if(gourpAIds.includes(item.id)){
            return <Button>Approve</Button>   ;
        }else{
            return null;
        }
    });

}


问:
Syntax error when running setup.py egg_info
I am trying to run the installation of the OBITools package using the developers python script.

When running the installation as suggested python get-obitools.py, I receive the following error message:

```<code>    Traceback (most recent call last):
  File "<string>", line 17, in <module>
  File "/tmp/pip_build_tamara/OBITools/setup.py", line 39, in <module>
    from obidistutils.core import setup
  File "distutils.ext/obidistutils/core.py", line 27, in <module>
    from obidistutils.command.build_sphinx import build_sphinx
  File "distutils.ext/obidistutils/command/build_sphinx.py", line 15, in <module>
    from sphinx.setup_command import BuildDoc as ori_build_sphinx
  File "/usr/local/lib/python2.7/dist-packages/sphinx/setup_command.py", line 23, in <module>
    from sphinx.application import Sphinx
  File "/usr/local/lib/python2.7/dist-packages/sphinx/application.py", line 22, in <module>
    from docutils.parsers.rst import Directive, directives, roles
  File "/usr/local/lib/python2.7/dist-packages/docutils/parsers/rst/__init__.py", line 75, in <module>
    from docutils.parsers.rst import roles, states
  File "/usr/local/lib/python2.7/dist-packages/docutils/parsers/rst/roles.py", line 78, in <module>
    from docutils.utils.code_analyzer import Lexer, LexerError
  File "/usr/local/lib/python2.7/dist-packages/docutils/utils/code_analyzer.py", line 19, in <module>
    from pygments.formatters.html import _get_ttype_class
  File "/usr/local/lib/python2.7/dist-packages/pygments/formatters/html.py", line 554
    file=sys.stderr)
        ^
SyntaxError: invalid syntax
</code>```

What am I doing wrong?

I am using:
Ubuntu 19.10
Python 2.7.17
Python 3.7.5

Thank you very much in advance!

答:
The code causing an error uses print as a function, but in Python 2 it was a statement, therefore it throws a syntax error.

As discussed in the comments OBItool installs a package (Sphinx) which has a requirement (pygment) not supporting python2. You need to clone the OBItools from the repository https://git.metabarcoding.org/obitools/obitools/tree/master, change the Spinx package version in requirements.txt. The Sphinx 2.0 drops support for python 2 https://github.com/sphinx-doc/sphinx/blob/3.x/CHANGES#L1013, so choose some older one like 1.8.0

Then install the OBI tools using python3 setup.py install command.

Body:
I am trying to run the installation of the OBITools package using the developers python script.

When running the installation as suggested python get-obitools.py, I receive the following error message:

    Traceback (most recent call last):
  File "<string>", line 17, in <module>
  File "/tmp/pip_build_tamara/OBITools/setup.py", line 39, in <module>
    from obidistutils.core import setup
  File "distutils.ext/obidistutils/core.py", line 27, in <module>
    from obidistutils.command.build_sphinx import build_sphinx
  File "distutils.ext/obidistutils/command/build_sphinx.py", line 15, in <module>
    from sphinx.setup_command import BuildDoc as ori_build_sphinx
  File "/usr/local/lib/python2.7/dist-packages/sphinx/setup_command.py", line 23, in <module>
    from sphinx.application import Sphinx
  File "/usr/local/lib/python2.7/dist-packages/sphinx/application.py", line 22, in <module>
    from docutils.parsers.rst import Directive, directives, roles
  File "/usr/local/lib/python2.7/dist-packages/docutils/parsers/rst/__init__.py", line 75, in <module>
    from docutils.parsers.rst import roles, states
  File "/usr/local/lib/python2.7/dist-packages/docutils/parsers/rst/roles.py", line 78, in <module>
    from docutils.utils.code_analyzer import Lexer, LexerError
  File "/usr/local/lib/python2.7/dist-packages/docutils/utils/code_analyzer.py", line 19, in <module>
    from pygments.formatters.html import _get_ttype_class
  File "/usr/local/lib/python2.7/dist-packages/pygments/formatters/html.py", line 554
    file=sys.stderr)
        ^
SyntaxError: invalid syntax

What am I doing wrong?

I am using:
Ubuntu 19.10
Python 2.7.17
Python 3.7.5

Thank you very much in advance!


问:
Laravel 5.7.28 Debug not setting off in live server [ APP_DEBUG = false ] not working
I have uploaded one laravel project to live server. I have set APP_DEBUG=false

But it still loading things into debug mode.

ie. Showign .env file output when we open in browser

Laravel version is 5.7.28

.env ==> [ APP_DEBUG=false ] Done

config/app.php  ==> 'debug' => env('APP_DEBUG', false),   DONE
Both above changes has been made but it still shoing all the output.

I don't have access to live server terminal to install any addition server. Can anyone helps me to find any other setting to prevent debug on in live server.

How to prevent debugging and direct access to file.
Any suggestion or help appreciated.

答:
Generally to stop debug mode in laravel following should work.

.env ==> [ APP_DEBUG=false ]

config/app.php ==> 'debug' => env('APP_DEBUG', false),

You said you cannot access terminal. Is it require for php artisan command ??

For that you can use route call to execute laravel command.

```<code>Route::get('/clear-cache', function() {
    Artisan::call('cache:clear');
    return "Cache is cleared";
});
</code>```

You said you want to prevent direct access of file.

Generally into google you can easily search for websites which have .env files. And direct access are generally open.

Do following changes into .htaccess file.

```<code># To Disable index view
Options -Indexes

# To Hide a .env file
<Files .env>
    Order allow,deny
    Deny from all
</Files>

# To Hide all .(DOT) files
<FilesMatch "^\.(.+)$">
   order deny,allow
   deny from all
   allow from 127.0.0.1
</FilesMatch>
</code>```

Body:
Generally to stop debug mode in laravel following should work.

.env ==> [ APP_DEBUG=false ]

config/app.php ==> 'debug' => env('APP_DEBUG', false),

You said you cannot access terminal. Is it require for php artisan command ??

For that you can use route call to execute laravel command.

Route::get('/clear-cache', function() {
    Artisan::call('cache:clear');
    return "Cache is cleared";
});

You said you want to prevent direct access of file.

Generally into google you can easily search for websites which have .env files. And direct access are generally open.

Do following changes into .htaccess file.

# To Disable index view
Options -Indexes

# To Hide a .env file
<Files .env>
    Order allow,deny
    Deny from all
</Files>

# To Hide all .(DOT) files
<FilesMatch "^\.(.+)$">
   order deny,allow
   deny from all
   allow from 127.0.0.1
</FilesMatch>


问:
Retrieve sources for all installed gems
I'm in the process of switching all my projects over to using the rather wonderful rvm and bundler.  On one of them, i want to basically mirror the gem environment on the server which hosts the app.

In order to do this, i did the following:

went onto the server

-did "gem list" which gave me a big list of gems like

```<code>actionmailer (2.2.2)
actionpack (2.2.2)
activerecord (2.2.2)
activeresource (2.2.2)
activesupport (2.2.2)
amatch (0.2.3)
archive-tar-minitar (0.5.2)
etc
</code>```

copied this into a new Gemfile in my local project folder

did a bit of find and replace to change the format into the Gemfile-friendly format

added the gem sources that i knew about to the top of the Gemfile

did "bundle install"
-FAIL

The fail is happening because there's always some gem that can't be found because the source isn't specified.  So, what i was wondering was

a) on the server, is there any way to query the installed gems to get a list of the sources where each was installed from?

b) is this even a good way to do it?  Would it be better to somehow export the gems that are on the server, and install them directly in my new gemset, rather than try to install them from remote sources?  Or something else?

grateful for any advice - max

答:
At the risk of stating the obvious, there are some gems being required in the Gemfile that are not available in the sources specified. At the top of the file there should be one or more sources:

```<code>source 'http://rubygems.org'
</code>```

You could try adding

```<code>source "http://gems.rubyforge.org"
</code>```

If bundler still can't find a gem, you could try googling the gem name - see if its been renamed or something. I'd be surprised if it wasn't out there, though, unless it was one you handrolled locally. If you're really stuck, you could copy the gem off the server and include it in the vendor/gems directory of your project, in which case you would need to specify its path in the Gemfile (see the bundler manual for that).

Bear in mind that you don't have to specify all your gem's dependencies; requiring rails will automatically require activerecord, activeresource etc. You can specify them if you like, but if you upgrade a dependent gem then you will have to edit the versions of the dependencies if they don't match.

To answer your original question, I don't believe there is a way of tracing the exact source of the gems installed on a machine.

Title: Retrieve sources for all installed gems

Body:
I'm in the process of switching all my projects over to using the rather wonderful rvm and bundler.  On one of them, i want to basically mirror the gem environment on the server which hosts the app.

In order to do this, i did the following:

went onto the server

-did "gem list" which gave me a big list of gems like

actionmailer (2.2.2)
actionpack (2.2.2)
activerecord (2.2.2)
activeresource (2.2.2)
activesupport (2.2.2)
amatch (0.2.3)
archive-tar-minitar (0.5.2)
etc

copied this into a new Gemfile in my local project folder

did a bit of find and replace to change the format into the Gemfile-friendly format

added the gem sources that i knew about to the top of the Gemfile

did "bundle install"
-FAIL

The fail is happening because there's always some gem that can't be found because the source isn't specified.  So, what i was wondering was

a) on the server, is there any way to query the installed gems to get a list of the sources where each was installed from?

b) is this even a good way to do it?  Would it be better to somehow export the gems that are on the server, and install them directly in my new gemset, rather than try to install them from remote sources?  Or something else?

grateful for any advice - max

Body:
At the risk of stating the obvious, there are some gems being required in the Gemfile that are not available in the sources specified. At the top of the file there should be one or more sources:

source 'http://rubygems.org'

You could try adding

source "http://gems.rubyforge.org"

If bundler still can't find a gem, you could try googling the gem name - see if its been renamed or something. I'd be surprised if it wasn't out there, though, unless it was one you handrolled locally. If you're really stuck, you could copy the gem off the server and include it in the vendor/gems directory of your project, in which case you would need to specify its path in the Gemfile (see the bundler manual for that).

Bear in mind that you don't have to specify all your gem's dependencies; requiring rails will automatically require activerecord, activeresource etc. You can specify them if you like, but if you upgrade a dependent gem then you will have to edit the versions of the dependencies if they don't match.

To answer your original question, I don't believe there is a way of tracing the exact source of the gems installed on a machine.


问:
Const in JavaScript: when to use it and is it necessary?
I've recently come across the const keyword in JavaScript. From what I can tell, it is used to create immutable variables, and I've tested to ensure that it cannot be redefined (in Node.js):

```<code>const x = 'const';
const x = 'not-const';

// Will give an error: 'constant 'x' has already been defined'
</code>```

I realise that it is not yet standardized across all browsers - but I'm only interested in the context of Node.js V8, and I've noticed that certain developers / projects seem to favor it heavily when the var keyword could be used to the same effect.

When is it appropriate to use const in place of var?

Should it be used every time a variable which is not going to be
re-assigned is declared?

Does it actually make any difference if var is used in place of
const or vice-versa?

答:
When it comes to the decision between let and const (both block scoped), always prefer const so that the usage is clear in the code. That way, if you try to redeclare the variable, you'll get an error. If there's no other choice but redeclare it, just switch for let. Note that, as Anthony says, the const values aren't immutable (for instances, a const object can have properties mutated).

When it comes to var, since ES6 is out, I never used it in production code and can't think of a use case for it. One point that might consider one to use it is JavaScript hoisting - while let and const are not hoisted, var declaration is. Yet, beware that variables declared with var  have a function scope, not a block scope («if declared outside any function, they will be globally available throughout the program; if declared within a function, they are only available within the function itself», in HackerRank - Variable Declaration Keywords). You can think of let as the block scoped version of var.

Body:
I've recently come across the const keyword in JavaScript. From what I can tell, it is used to create immutable variables, and I've tested to ensure that it cannot be redefined (in Node.js):

const x = 'const';
const x = 'not-const';

// Will give an error: 'constant 'x' has already been defined'

I realise that it is not yet standardized across all browsers - but I'm only interested in the context of Node.js V8, and I've noticed that certain developers / projects seem to favor it heavily when the var keyword could be used to the same effect.

When is it appropriate to use const in place of var?

Should it be used every time a variable which is not going to be
re-assigned is declared?

Does it actually make any difference if var is used in place of
const or vice-versa?


问:
scala List zipWithIndex different results?
```<code>val df = Seq(

        (1, "A, B, C, D"),
        (2, "E, F, G,5"),
        (3, "H, I,5,7"),
        (4, "J,sd,cc,23")
).toDF("number","letters")
df.show()
</code>```

```<code>output:
+------+----------+
|number|   letters|
+------+----------+
|     1|A, B, C, D|
|     2| E, F, G,5|
|     3|  H, I,5,7|
|     4|J,sd,cc,23|
+------+----------+

</code>```

```<code>val arr = df.filter($"number"===1).select($"letters").head.toSeq
val list1 = arr.toList
list1.zipWithIndex

</code>```

// why there is not  List( ("A",0),("B",1),("C",2),("D",3) ) ?

```<code>output:
arr: Seq[Any] = WrappedArray(A, B, C, D)
list1: List[Any] = List(A, B, C, D)
res87: List[(Any, Int)] = List((A, B, C, D,0))
</code>```

however

```<code>List("a", "b", "c").zipWithIndex
output:
    res88: List[(String, Int)] = List((a,0), (b,1), (c,2))
</code>```

Why are they all zipwithindex with different output formats?

答:
When you call .head on a DataFrame you are returning a Row.

If you look at the size of list1 you will see it only contains a single element.

You need to extract the String at element 0 of the Row:

```<code>df
  .filter($"number"===1)
  .select($"letters")
  .head
  .getString(0)
  .split(",")
  .zipWithIndex
</code>```

Body:
val df = Seq(

        (1, "A, B, C, D"),
        (2, "E, F, G,5"),
        (3, "H, I,5,7"),
        (4, "J,sd,cc,23")
).toDF("number","letters")
df.show()

output:
+------+----------+
|number|   letters|
+------+----------+
|     1|A, B, C, D|
|     2| E, F, G,5|
|     3|  H, I,5,7|
|     4|J,sd,cc,23|
+------+----------+

val arr = df.filter($"number"===1).select($"letters").head.toSeq
val list1 = arr.toList
list1.zipWithIndex

// why there is not  List( ("A",0),("B",1),("C",2),("D",3) ) ?

output:
arr: Seq[Any] = WrappedArray(A, B, C, D)
list1: List[Any] = List(A, B, C, D)
res87: List[(Any, Int)] = List((A, B, C, D,0))

however

List("a", "b", "c").zipWithIndex
output:
    res88: List[(String, Int)] = List((a,0), (b,1), (c,2))

Why are they all zipwithindex with different output formats?

Body:
When you call .head on a DataFrame you are returning a Row.

If you look at the size of list1 you will see it only contains a single element.

You need to extract the String at element 0 of the Row:

df
  .filter($"number"===1)
  .select($"letters")
  .head
  .getString(0)
  .split(",")
  .zipWithIndex