问:
How to use Android View Binding with RecyclerView
This is not data binding, this is View binding which is new to Android Studio 3.6 Canary 11+ described here.

For using inside an Activity it is clear, you just use it like this:

Let's say we have a layout named activity_main.xml

Then in the code we can use it like this:

```<code>public class MainActivity extends Activity{

    ActivityMainBinding binding; //Name of the layout in camel case + "Binding"

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }
}
</code>```

However, It's not clear how to use View Binding with RecyclerView?

Edit: Please explain in Java.

答:
```<code>class LanguageAdapter(val context: Context, var listData: MutableList<ListData>, val listener: onCheckListner) : RecyclerView.Adapter<LanguageAdapter.ViewHolder>() {

lateinit var bindind: LangugaeItemBinding

fun onRefresh(listData: MutableList<ListData>) {
    this.listData = listData
    notifyDataSetChanged()
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    bindind = LangugaeItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)

    return ViewHolder(bindind)
}

override fun getItemCount(): Int {
    return listData.size
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.setData(listData[position])

}

inner class ViewHolder(private val binding: LangugaeItemBinding) : RecyclerView.ViewHolder(binding.getRoot()), View.OnClickListener {
    override fun onClick(v: View?) {
        when (v) {
            itemView -> {

            }
        }
    }

    init {
        itemView.radio_button.setOnClickListener(this)
    }

    fun setData(model: ListData) {
        with(binding) {
            data = model
            executePendingBindings()
        }
    }

}
}
</code>```

<p>just pass the model or arraylist into adapter and set in binding view </p>

Body:
This is not data binding, this is View binding which is new to Android Studio 3.6 Canary 11+ described here.

For using inside an Activity it is clear, you just use it like this:

Let's say we have a layout named activity_main.xml

Then in the code we can use it like this:

public class MainActivity extends Activity{

    ActivityMainBinding binding; //Name of the layout in camel case + "Binding"

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }
}

However, It's not clear how to use View Binding with RecyclerView?

Edit: Please explain in Java.

Body:
class LanguageAdapter(val context: Context, var listData: MutableList<ListData>, val listener: onCheckListner) : RecyclerView.Adapter<LanguageAdapter.ViewHolder>() {

lateinit var bindind: LangugaeItemBinding

fun onRefresh(listData: MutableList<ListData>) {
    this.listData = listData
    notifyDataSetChanged()
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    bindind = LangugaeItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)

    return ViewHolder(bindind)
}

override fun getItemCount(): Int {
    return listData.size
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.setData(listData[position])

}

inner class ViewHolder(private val binding: LangugaeItemBinding) : RecyclerView.ViewHolder(binding.getRoot()), View.OnClickListener {
    override fun onClick(v: View?) {
        when (v) {
            itemView -> {

            }
        }
    }

    init {
        itemView.radio_button.setOnClickListener(this)
    }

    fun setData(model: ListData) {
        with(binding) {
            data = model
            executePendingBindings()
        }
    }

}
}

just pass the model or arraylist into adapter and set in binding view


来源: stackexchange

问:
UITableViewAlertForLayoutOutsideViewHierarchy error: Warning once only (iOS 13 GM) in Xamarin.Forms iOS
I am facing an issue that the UI of my screen is not loading because of the following error

```<code>[TableView] Warning once only: UITableView was told to layout its visible cells and other contents without being in the view hierarchy (the table view or one of its superviews has not been added to a window). This may cause bugs by forcing views inside the table view to load and perform layout without accurate information (e.g. table view bounds, trait collection, layout margins, safe area insets, etc), and will also cause unnecessary performance overhead due to extra layout passes. Make a symbolic breakpoint at UITableViewAlertForLayoutOutsideViewHierarchy to catch this in the debugger and see what caused this to occur, so you can avoid this action altogether if possible, or defer it until the table view has been added to a window. Table view: <UITableView: 0x7fdcc8488800; frame = (0 24; 1024 1342); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x600003c013b0>; layer = <CALayer: 0x6000039f8fc0>; contentOffset: {0, 0}; contentSize: {1024, 72}; adjustedContentInset: {0, 0, 0, 0}; dataSource: <Xamarin_Forms_Platform_iOS_ListViewRenderer_ListViewDataSource: 0x600003070790>>
</code>```

Can any one please help me regarding this to resolve this issue. This issue I am getting is only in the 13.3 version of the ipad and it there are no problems in the iPhone 13.3 version.

Please help me in resolving this.

Regards.

答:
Is the issue just ran into this issue only when starting the app while the device was landscape on iPadOS 13 ?

if yes,maybe you could refer to this,even though it's native ios project.

ContentLicense: CC BY-SA 4.0

Body:
I am facing an issue that the UI of my screen is not loading because of the following error

[TableView] Warning once only: UITableView was told to layout its visible cells and other contents without being in the view hierarchy (the table view or one of its superviews has not been added to a window). This may cause bugs by forcing views inside the table view to load and perform layout without accurate information (e.g. table view bounds, trait collection, layout margins, safe area insets, etc), and will also cause unnecessary performance overhead due to extra layout passes. Make a symbolic breakpoint at UITableViewAlertForLayoutOutsideViewHierarchy to catch this in the debugger and see what caused this to occur, so you can avoid this action altogether if possible, or defer it until the table view has been added to a window. Table view: <UITableView: 0x7fdcc8488800; frame = (0 24; 1024 1342); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x600003c013b0>; layer = <CALayer: 0x6000039f8fc0>; contentOffset: {0, 0}; contentSize: {1024, 72}; adjustedContentInset: {0, 0, 0, 0}; dataSource: <Xamarin_Forms_Platform_iOS_ListViewRenderer_ListViewDataSource: 0x600003070790>>

Can any one please help me regarding this to resolve this issue. This issue I am getting is only in the 13.3 version of the ipad and it there are no problems in the iPhone 13.3 version.

Please help me in resolving this.

Regards.


问:
How can I use a PHP script in typo3 v9?
I'd like to know if there is a way to use a PHP script in the typo3 v9 or a newer version.
If possible, I'd prefer a way to call a function and not to embed the code in an HTML box.

Thanks a lot

答:
A short history:

in earlier days (TYPO3 prior to 4.2) there was a PHP content element. As of the possibility to insert bad code it was removed.

then there was a possibilty to include any file with PHP code by typoscript as a userfunc.

That was restricted by TYPO3 6 as you now can only use methods of classes as userfunc.

For usage in the front end you can build a plugin, so the editor can use a function (with parameters) as desired. or include it by typoscript (userfunc) where you need it. This can be easily done with an extension (as bandanh commented), so your code is deployable and can be included in any installation.

Title: How can I use a PHP script in typo3 v9?


问:
No fixtures found when testing an app on Django
I have finally decided to create unit test for all my code. That is I'm trying to create fixtures based on my models to test my function against them.

I have create a json fixture using dumpdata command and placed it under fixtures directory on my app. The following is the code on my test:

```<code>import unittest
from mysite.myapp.models import Post

class RatingTestCase(unittest.TestCase):
  fixtures = [
      'posts.json',
  ]

def test_me(self):
  p = Post.objects.all()
  self.assertTrue(p)
</code>```

I run my test using the following command on my Arch Linux machine:

```<code>python2.7 manage.py test myapp
</code>```

It creates a sqlite database and installs all the tables and indeces, however at the end it says no fixtures found and it says my test failed since it didn't find any data.

I'm running the latest revision of development version of Django and noticed that based on the documentation I am supposed to import unittest using:

from django.utils import unittest

However, when I do this, it complains that unittest cannot be imported. That's why I import
unittest directly from my python path which worked.

I've tried to mock django model objects before, but I think it's better to test Django apps using fixtures than using mock libraries. Any idea how to load the fixtures?

Thanks in advance.

EDIT: If I change my fixture name to initial_data.json, it will load it every time I run my test. However, I still need to have multiple fixture names for running different tests.

EDIT: I got it working by importing TestCase from the following:

```<code>from django.test import TestCase
</code>```

答:
There are a couple things that could help:

You can run the test with --verbosity=2 to see which directories django looks in for fixtures.

django TestCase is what django recommends to use, opposed to unittest.

Where is your fixture directory/file located? If it's not in your app you have to specify a fixture directory in your settings file.

ContentLicense: CC BY-SA 3.0

Body:
I have finally decided to create unit test for all my code. That is I'm trying to create fixtures based on my models to test my function against them.

I have create a json fixture using dumpdata command and placed it under fixtures directory on my app. The following is the code on my test:

import unittest
from mysite.myapp.models import Post

class RatingTestCase(unittest.TestCase):
  fixtures = [
      'posts.json',
  ]

def test_me(self):
  p = Post.objects.all()
  self.assertTrue(p)

I run my test using the following command on my Arch Linux machine:

python2.7 manage.py test myapp

It creates a sqlite database and installs all the tables and indeces, however at the end it says no fixtures found and it says my test failed since it didn't find any data.

I'm running the latest revision of development version of Django and noticed that based on the documentation I am supposed to import unittest using:

from django.utils import unittest

However, when I do this, it complains that unittest cannot be imported. That's why I import
unittest directly from my python path which worked.

I've tried to mock django model objects before, but I think it's better to test Django apps using fixtures than using mock libraries. Any idea how to load the fixtures?

Thanks in advance.

EDIT: If I change my fixture name to initial_data.json, it will load it every time I run my test. However, I still need to have multiple fixture names for running different tests.

EDIT: I got it working by importing TestCase from the following:

from django.test import TestCase


问:
How to Search and Hide on Blogger Posting
I have Table on my blogger post.

I give it an Input form to it. Reader can search data quickly.

I get code from W3school.

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table

W3school
This code run well. But I need some improvement.

The Question:

How to show the Table just when user click "Enter Key" on Input/Button Form.

And when Input Form is empty, the Table automatically Hide.

答:
See the below code. I hope it will be solve your issue.

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">

My Customers

  <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

      Name
      Country

      Alfreds Futterkiste
      Germany

      Berglunds snabbkop
      Sweden

      Island Trading
      UK

      Koniglich Essen
      Germany

      Laughing Bacchus Winecellars
      Canada

      Magazzini Alimentari Riuniti
      Italy

      North/South
      UK

      Paris specialites
      France

```

Body:
See the below code. I hope it will be solve your issue.

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

  <style>
    * {
      box-sizing: border-box;
    }

    #myInput {
      background-image: url('/css/searchicon.png');
      background-position: 10px 10px;
      background-repeat: no-repeat;
      width: 100%;
      font-size: 16px;
      padding: 12px 20px 12px 40px;
      border: 1px solid #ddd;
      margin-bottom: 12px;
    }

    #myTable {
      border-collapse: collapse;
      width: 100%;
      border: 1px solid #ddd;
      font-size: 18px;
    }

    #myTable th,
    #myTable td {
      text-align: left;
      padding: 12px;
    }

    #myTable tr {
      border-bottom: 1px solid #ddd;
    }

    #myTable tr.header,
    #myTable tr:hover {
      background-color: #f1f1f1;
    }
  </style>
</head>

<body>

  <h2>My Customers</h2>

  <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

  <table id="myTable">
    <tr class="header">
      <th style="width:60%;">Name</th>
      <th style="width:40%;">Country</th>
    </tr>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Berglunds snabbkop</td>
      <td>Sweden</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Koniglich Essen</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Laughing Bacchus Winecellars</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari Riuniti</td>
      <td>Italy</td>
    </tr>
    <tr>
      <td>North/South</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Paris specialites</td>
      <td>France</td>
    </tr>
  </table>

  <style>
    #myTable {
      display: none;
    }

    #myTable.hide {
      display: table;
    }
  </style>

  <script>
    function myFunction() {
      var input, filter, table, tr, td, i, txtValue;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {
          txtValue = td.textContent || td.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          } else {
            tr[i].style.display = "none";
          }
        }
      }

      var inputvalues = $("#myInput").val();
      if (inputvalues.length > 0) {
        $("#myTable").addClass("hide");
      }
      if(inputvalues == "" || inputvalues== null)
      $("#myTable").removeClass("hide");
    }
  </script>

</body>

</html>


问:
Create Excel file from C# SQL
I have a ASP.NET Web Application where I am importing an Excel file (.xlsx) and storing the data in a database.

Here is my code to read the Excel file:

```<code>private void ImportBulkRegistraion(HttpContext context)
{
 if (context.Request.Files.Count > 0)
 {
  HttpFileCollection files = context.Request.Files;
  HttpPostedFile MyFile = files[0];

  DataTable dt = new DataTable();
  using(var excel = new ExcelPackage(MyFile.InputStream))
  {
   //loop for all of sheets
   for (int sheetcount = 1; sheetcount <= 1; sheetcount++)
   {
    ExcelWorksheet worksheet = excel.Workbook.Worksheets[sheetcount];
    ExcelCellAddress startCell = worksheet.Dimension.Start;
    ExcelCellAddress endCell = worksheet.Dimension.End;

    // place all the data into DataTable
    for (int row = startCell.Row; row <= endCell.Row; row++)
    {
     if (row == 1)
     {
      //Add columns
      if (sheetcount == 1)
       for (int col = startCell.Column; col <= endCell.Column; col++)
        dt.Columns.Add(worksheet.Cells[row, col].Value.ToString());
     }
     else
     {
      //Add Rows
      DataRow dr = dt.NewRow();
      int x = 0;
      for (int col = startCell.Column; col <= endCell.Column; col++)
       dr[x++] = worksheet.Cells[row, col].Value;
      dt.Rows.Add(dr);
     }
    }
   }
  }
  ExportUserToDB(dt);
 }
}
</code>```

//ExportUserToDB(dt); function calls the Stored Procedure where I am inserting the rows into the database.

I want to generate an Excel file where if any of the rows from the input Excel file fails  to process, the same rows will be stored in this newly created Excel file (in the same format), which can be fixed manually and then reprocessed again.

For example: If a row has Name column with name as "O'Mac", is not processed by SQL. This is a failed row and should be inserted into newly created Excel file.

答:
Create a DataTable object dedicated for exceptions e.g.:

DataTable dtException = new DataTable();

Add all those DataRows in dtException which gets fail

Write a method e.g. WriteException() and pass dtException to write all exceptions in Excel sheet:

```
        private void WriteException(DataTable dt)
        {<br>
            using (ExcelPackage excel = new ExcelPackage())
            {
                excel.Workbook.Worksheets.Add("Exceptions");</p>

<code>            var worksheet = excel.Workbook.Worksheets["Exceptions"];

            worksheet.Cells["A1"].LoadFromDataTable(dt,false);

            FileInfo excelFile = new FileInfo(@"C:\Temp\AllExceptions.xlsx");
            excel.SaveAs(excelFile);
        }
    }
</code>```

Title: Create Excel file from C# SQL

Body:
I have a ASP.NET Web Application where I am importing an Excel file (.xlsx) and storing the data in a database.

Here is my code to read the Excel file:

private void ImportBulkRegistraion(HttpContext context)
{
 if (context.Request.Files.Count > 0)
 {
  HttpFileCollection files = context.Request.Files;
  HttpPostedFile MyFile = files[0];

  DataTable dt = new DataTable();
  using(var excel = new ExcelPackage(MyFile.InputStream))
  {
   //loop for all of sheets
   for (int sheetcount = 1; sheetcount <= 1; sheetcount++)
   {
    ExcelWorksheet worksheet = excel.Workbook.Worksheets[sheetcount];
    ExcelCellAddress startCell = worksheet.Dimension.Start;
    ExcelCellAddress endCell = worksheet.Dimension.End;

    // place all the data into DataTable
    for (int row = startCell.Row; row <= endCell.Row; row++)
    {
     if (row == 1)
     {
      //Add columns
      if (sheetcount == 1)
       for (int col = startCell.Column; col <= endCell.Column; col++)
        dt.Columns.Add(worksheet.Cells[row, col].Value.ToString());
     }
     else
     {
      //Add Rows
      DataRow dr = dt.NewRow();
      int x = 0;
      for (int col = startCell.Column; col <= endCell.Column; col++)
       dr[x++] = worksheet.Cells[row, col].Value;
      dt.Rows.Add(dr);
     }
    }
   }
  }
  ExportUserToDB(dt);
 }
}

//ExportUserToDB(dt); function calls the Stored Procedure where I am inserting the rows into the database.

I want to generate an Excel file where if any of the rows from the input Excel file fails  to process, the same rows will be stored in this newly created Excel file (in the same format), which can be fixed manually and then reprocessed again.

For example: If a row has Name column with name as "O'Mac", is not processed by SQL. This is a failed row and should be inserted into newly created Excel file.

Body:
Create a DataTable object dedicated for exceptions e.g.:

DataTable dtException = new DataTable();

Add all those DataRows in dtException which gets fail

Write a method e.g. WriteException() and pass dtException to write all exceptions in Excel sheet:

        private void WriteException(DataTable dt)
        {

            using (ExcelPackage excel = new ExcelPackage())
            {
                excel.Workbook.Worksheets.Add("Exceptions");

            var worksheet = excel.Workbook.Worksheets["Exceptions"];

            worksheet.Cells["A1"].LoadFromDataTable(dt,false);

            FileInfo excelFile = new FileInfo(@"C:\Temp\AllExceptions.xlsx");
            excel.SaveAs(excelFile);
        }
    }


问:
How to set flashdevelop with AIR 2.6
I would like to set my FlashDevelop to use the new AIR 2.6 SDK. I saw this thread on the FD forum but I couldn't get a working walkthrough.

Any help?

答: hey, you can try this tutorial I've written: http://jvcaalim.blogspot.com/2011/05/how-tos-android-development-using.html, if you have any questions feel free to post them on the blog, hope it helps!</p>

Title: How to set flashdevelop with AIR 2.6


问:
Vue Router: hide parent template when child is open
Im trying to install Vue.js with the router and im running into some view issues. I have a router.js with child routes. I want to use this method for simple breadcrumbs and generate a clear overview so i know which route belongs where.

Opening each route works like a charm, everything shows up. When i open /apps I get a nice view from my Apps.vue that displays App overview
. But now im opening /apps/app-one and then I see the Apps.vue and AppOne.vue template. How can I prevent that both templates are displayed?

The vue components looks like this:

Router.js

```<code>import Router from 'vue-router';
import AppsPage from './components/Apps.vue'
import AppOne from './components/AppOne.vue'
import AppTwo from './components/AppTwo.vue'

export default new Router({
    // mode: 'history',
    routes: [
        {
            path: '/apps',
            component: AppsPage,
            children: [
                {
                    path: '/apps/app-one',
                    component: AppOne,
                },
                {
                    path: '/apps/app-two',
                    component: AppTwo,
                },
            ]
        },
    ]
});
</code>```

Apps.vue

```<code><template>
    <div id="app-overview">
        <h1>App overview</h1>
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name: 'app_page'
    }
</script>
</code>```

App1.vue

```<code><template>
    <div>
        <h1>App 1</h1>
    </div>

</template>

<script>
export default {
    name: 'app_one'
}
</script>
</code>```

App2.vue

```<code><template>
    <div>
        <h1>App 2</h1>
    </div>

</template>

<script>
export default {
    name: 'app_two'
}
</script>
</code>```

答:
It's possible and pretty easy too.You can achieve this by followings:

```<code><template>

    <div>

        <div v-show="isExactActive">
            Parent component contents will be here
        </div>

        <router-view ref="rv"></router-view>

    </div>

</template>

<script>

    export default {

        data() {
            return {
                isExactActive: true,
            }
        },

        updated() {
            this.isExactActive = typeof this.$refs.rv === 'undefined';
        },

        mounted() {
            this.isExactActive = typeof this.$refs.rv === 'undefined';
        }

    }
</script>
</code>```

Hope, this will be helpful.

Body:
Im trying to install Vue.js with the router and im running into some view issues. I have a router.js with child routes. I want to use this method for simple breadcrumbs and generate a clear overview so i know which route belongs where.

Opening each route works like a charm, everything shows up. When i open /apps I get a nice view from my Apps.vue that displays App overview
. But now im opening /apps/app-one and then I see the Apps.vue and AppOne.vue template. How can I prevent that both templates are displayed?

The vue components looks like this:

Router.js

import Router from 'vue-router';
import AppsPage from './components/Apps.vue'
import AppOne from './components/AppOne.vue'
import AppTwo from './components/AppTwo.vue'

export default new Router({
    // mode: 'history',
    routes: [
        {
            path: '/apps',
            component: AppsPage,
            children: [
                {
                    path: '/apps/app-one',
                    component: AppOne,
                },
                {
                    path: '/apps/app-two',
                    component: AppTwo,
                },
            ]
        },
    ]
});

Apps.vue

<template>

App overview

        <router-view></router-view>

</template>

App1.vue

<template>

App 1

</template>

App2.vue

<template>

App 2

</template>

Body:
It's possible and pretty easy too.You can achieve this by followings:

<template>

    <div>

        <div v-show="isExactActive">
            Parent component contents will be here
        </div>

        <router-view ref="rv"></router-view>

    </div>

</template>

<script>

    export default {

        data() {
            return {
                isExactActive: true,
            }
        },

        updated() {
            this.isExactActive = typeof this.$refs.rv === 'undefined';
        },

        mounted() {
            this.isExactActive = typeof this.$refs.rv === 'undefined';
        }

    }
</script>

Hope, this will be helpful.


问:
The component does not have a resource identified by the uri
I want to create a Generic DataGrid to use on all my Views/UserControls.

This is my structure:

Class Library called "Core":

Class called "ViewBase":

```<code>public class ViewBase : UserControl
{
    public ViewBase()
    {
    }

    //Rest of Methods and Properties
}
</code>```

Class Library called "Controls":

UserControl Called "GridView":

XAML:

```<code>    <vb:ViewBase x:Class="Controls.GridView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:vb="clr-namespace:Core;assembly=Core">

    <Grid>
        <DataGrid></DataGrid>
    </Grid>

    </vb:ViewBase>
</code>```

Code Behind:

```<code>using Core;

public partial class GridView : ViewBase
{
    public GridView ()
    {
        InitializeComponent();
    }
}
</code>```

Then is the WPF Aplication called "WPFApp":

Class called "View":

```<code>using Controls;

public class View : GridView
{
    public View()
    {
        InitializeComponent();
    }
}
</code>```

My whole idea is to use GridView where i need a DataGrid.

When i run the application i get this error:

```<code>"The component 'WpfApp.View' does not have a resource identified by the URI '/Controls;component/GridView.xaml'."
</code>```

What am i doing wrong?

Is this the correct approach or am i way off?

答:
Hi the way solve this problem was to rename the xaml usercontrol to all smallcaps on InitializeComponent()...

enter image description here

enter image description here

Body:
I want to create a Generic DataGrid to use on all my Views/UserControls.

This is my structure:

Class Library called "Core":

Class called "ViewBase":

public class ViewBase : UserControl
{
    public ViewBase()
    {
    }

    //Rest of Methods and Properties
}

Class Library called "Controls":

UserControl Called "GridView":

XAML:

    <vb:ViewBase x:Class="Controls.GridView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:vb="clr-namespace:Core;assembly=Core">

    <Grid>
        <DataGrid></DataGrid>
    </Grid>

    </vb:ViewBase>

Code Behind:

using Core;

public partial class GridView : ViewBase
{
    public GridView ()
    {
        InitializeComponent();
    }
}

Then is the WPF Aplication called "WPFApp":

Class called "View":

using Controls;

public class View : GridView
{
    public View()
    {
        InitializeComponent();
    }
}

My whole idea is to use GridView where i need a DataGrid.

When i run the application i get this error:

"The component 'WpfApp.View' does not have a resource identified by the URI '/Controls;component/GridView.xaml'."

What am i doing wrong?

Is this the correct approach or am i way off?


问:
Django CRUD template not showing up
Im making a CRUD application using class instances.
My app is a very simple accounting app:

Django: 3.03
Python: 3.8.0

accounts/models.py

```<code>class Project(models.Model):
    ## normal fields
</code>```

accounts/views.py

```<code>class ProjectCreate(CreateView):
    model = Project
    fields = '__all__'

class ProjectUpdate(UpdateView):
    model = Project
    fields = '__all__'

class ProjectDelete(DeleteView):
    model = Project
    success_url = reverse_lazy('project')
</code>```

accounts/urls.py:

```<code>urlpatterns = [

path('project/create/', project_views.ProjectCreate.as_view(), name='project_create'),
    path('project/<int:pk>/update/', project_views.ProjectUpdate.as_view(), name='project_update'),
    path('project/<int:pk>/delete/', project_views.ProjectDelete.as_view(), name='project_delete'),

]
</code>```

I have 2 template files under the following directory:

```<code>accounts
    accounts
        templates
            project
                project_form.html
                project_confirm_delete.html
        models.py
        urls.py
        views.py
        forms.py
</code>```

When i call the view:

http://localhost:8000/accounts/project/create/

I get the following error:

```<code>47, in select_template
    raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: accounts/project_form.html
</code>```

settings.py:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'accounts.utils.accounts_vars',
            ],
        },
    },
]
</code>```

I cant figure out why this is not working. Can you please help.
Any help would be much appreciated. Thanks.

答:
check your settings.py file

The views is not able to render your template. Mention templates directory in settings.py and also check wether your template is present or not

Title: Django CRUD template not showing up

Body:
Im making a CRUD application using class instances.
My app is a very simple accounting app:

Django: 3.03
Python: 3.8.0

accounts/models.py

class Project(models.Model):
    ## normal fields

accounts/views.py

class ProjectCreate(CreateView):
    model = Project
    fields = '__all__'

class ProjectUpdate(UpdateView):
    model = Project
    fields = '__all__'

class ProjectDelete(DeleteView):
    model = Project
    success_url = reverse_lazy('project')

accounts/urls.py:

urlpatterns = [

path('project/create/', project_views.ProjectCreate.as_view(), name='project_create'),
    path('project/<int:pk>/update/', project_views.ProjectUpdate.as_view(), name='project_update'),
    path('project/<int:pk>/delete/', project_views.ProjectDelete.as_view(), name='project_delete'),

]

I have 2 template files under the following directory:

accounts
    accounts
        templates
            project
                project_form.html
                project_confirm_delete.html
        models.py
        urls.py
        views.py
        forms.py

When i call the view:

http://localhost:8000/accounts/project/create/

I get the following error:

47, in select_template
    raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: accounts/project_form.html

settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'accounts.utils.accounts_vars',
            ],
        },
    },
]

I cant figure out why this is not working. Can you please help.
Any help would be much appreciated. Thanks.


问:
LayoutInflater fails to inflate layout with reference to class
I try to inflate Layout which contain class.
I create inflater instance with:

```<code> LayoutInflater inflate =(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRelLayout = (RelativeLayout) inflate.inflate(
                    R.layout.app_layout, null);
</code>```

My app_layout.xml layout is:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:panel="http://schemas.android.com/apk/res/com.alpha"
            android:id="@+id/layoutMain"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="top|right">
</code>```

        .
        .
        .

Inflation fails with exception: java.lang.RuntimeException: Your Panel must have a child View whose id attribute is 'R.id.panelHandle'

Thanks for help

答:
Have you tryed to remove xmlns:panel="http://schemas.android.com/apk/res/com.alpha"?

Can you post the entire layout?

Body:
I try to inflate Layout which contain class.
I create inflater instance with:

 LayoutInflater inflate =(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRelLayout = (RelativeLayout) inflate.inflate(
                    R.layout.app_layout, null);

My app_layout.xml layout is:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:panel="http://schemas.android.com/apk/res/com.alpha"
            android:id="@+id/layoutMain"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="top|right">

        .
        .
        .

Inflation fails with exception: java.lang.RuntimeException: Your Panel must have a child View whose id attribute is 'R.id.panelHandle'

Thanks for help


问:
how to check how many voice channel my discord bot is in?
I want my bot(coded in discord.js) to show how many voice channels my discord bot is in, and I have no idea how to do that.

Can I get some help? I would offer My bot's premium silver edition to those who helped just dm A350-1000#6715 on discord for redeem code.

答:
After reading the discord.js docs, I found under the class Client a .channels property that returns a ChannelManager which helps handle every channel the client is handling. In the ChannelManager class, there is a property .cache that returns a collection of channels, so I suppose you can loop through the collection and count every channel that is a voice channel, every Channel object has a property .type which returns a string.

Discord.js docs: https://discord.js.org/#/docs/main/master/class/Client


问:
SwiftUI - How to close the sheet view, while dismissing that view
I want to achieve the function. Like, "Look up" view that is from Apple.

My aim is when the sheet view push another view by navigation, the user can tap the navigation item button to close the sheet view. Like, this below gif.

I try to achieve this function.

I found a problem that is when the user tap the "Done" button. The App doesn't close the sheet view. It only pop the view to parent view. Like, this below gif.

This is my code.

import SwiftUI

struct ContentView: View {
    @State var isShowSheet = false
    var body: some View {
        Button(action: {
            self.isShowSheet.toggle()
        }) {
            Text("Tap to show the sheet")
        }.sheet(isPresented: $isShowSheet) {
            NavView()
        }
    }
}

struct NavView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: NavSubView()) {
                Text("Enter Sub View")
            }
        } .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct NavSubView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Text("Hello")
        .navigationBarItems(trailing:
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            }){
                Text("Done")
            }
        )
    }
}

```

How did I achieve this function? :)
Please help me, thank you. :)

答:
I haven't tried SwiftUI ever, but I came from UIKit + RxSwift, so I kinda know how binding works. I read quite a bit of sample codes from a SwiftUI Tutorial, and the way you dismiss a modal is actually correct, but apparently not for a navigation stack.

One way I learned just now is use a @Binding var. This might not be the best solution, but it worked!

So you have this $isShowSheet in your ContentView. Pass that object to your NavView struct by declaring a variable in that NavView.

ContentView

```<code>    .....

    }.sheet(isPresented: $isShowSheet) {
        NavView(isShowSheet: self.$isShowSheet)
    }
</code>```

NavView

```<code>struct NavView: View {
    @Binding var isShowSheet: Bool

    var body: some View {
        NavigationView {
            NavigationLink(destination: NavSubView(isShowSheet: self.$isShowSheet)) {
                Text("Enter Sub View")
            }
        } .navigationViewStyle(StackNavigationViewStyle())
    }
}
</code>```

and finally, do the same thing to your subView.

NavSubView

```<code>struct NavSubView: View {
    @Environment(\.presentationMode) var presentationMode

    @Binding var isShowSheet: Bool

    var body: some View {
        Text("Hello")
        .navigationBarItems(trailing:
            Button(action: {
                //self.presentationMode.projectedValue.wrappedValue.dismiss()
                self.isShowSheet = false
            }){
                Text("Done")
            }
        )
    }
}
</code>```

Now as you can see, you just need to send a new signal to that isShowSheet binding var - false.

self.isShowSheet = false

Voila!

Body:
I want to achieve the function. Like, "Look up" view that is from Apple.

My aim is when the sheet view push another view by navigation, the user can tap the navigation item button to close the sheet view. Like, this below gif.

I try to achieve this function.

I found a problem that is when the user tap the "Done" button. The App doesn't close the sheet view. It only pop the view to parent view. Like, this below gif.

This is my code.

import SwiftUI

struct ContentView: View {
    @State var isShowSheet = false
    var body: some View {
        Button(action: {
            self.isShowSheet.toggle()
        }) {
            Text("Tap to show the sheet")
        }.sheet(isPresented: $isShowSheet) {
            NavView()
        }
    }
}

struct NavView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: NavSubView()) {
                Text("Enter Sub View")
            }
        } .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct NavSubView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Text("Hello")
        .navigationBarItems(trailing:
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            }){
                Text("Done")
            }
        )
    }
}

How did I achieve this function? :)
Please help me, thank you. :)

Body:
I haven't tried SwiftUI ever, but I came from UIKit + RxSwift, so I kinda know how binding works. I read quite a bit of sample codes from a SwiftUI Tutorial, and the way you dismiss a modal is actually correct, but apparently not for a navigation stack.

One way I learned just now is use a @Binding var. This might not be the best solution, but it worked!

So you have this $isShowSheet in your ContentView. Pass that object to your NavView struct by declaring a variable in that NavView.

ContentView

    .....

    }.sheet(isPresented: $isShowSheet) {
        NavView(isShowSheet: self.$isShowSheet)
    }

NavView

struct NavView: View {
    @Binding var isShowSheet: Bool

    var body: some View {
        NavigationView {
            NavigationLink(destination: NavSubView(isShowSheet: self.$isShowSheet)) {
                Text("Enter Sub View")
            }
        } .navigationViewStyle(StackNavigationViewStyle())
    }
}

and finally, do the same thing to your subView.

NavSubView

struct NavSubView: View {
    @Environment(\.presentationMode) var presentationMode

    @Binding var isShowSheet: Bool

    var body: some View {
        Text("Hello")
        .navigationBarItems(trailing:
            Button(action: {
                //self.presentationMode.projectedValue.wrappedValue.dismiss()
                self.isShowSheet = false
            }){
                Text("Done")
            }
        )
    }
}

Now as you can see, you just need to send a new signal to that isShowSheet binding var - false.

self.isShowSheet = false

Voila!


问:
Best practice to record large amount of hits into MySQL database
Well, this is the thing. Let's say that my future PHP CMS need to drive 500k visitors daily and I need to record them all in MySQL database (referrer, ip address, time etc.). This way I need to insert 300-500 rows per minute and update 50 more. The main problem is that script would call database every time I want to insert new row, which is every time someone hits a page.

My question, is there any way to locally cache incoming hits first (and what is the best solution for that apc, csv...?) and periodically send them to database every 10 minutes for example? Is this good solution and what is the best practice for this situation?

答:
Save them to a directory-based database (or flat file, depends) somewhere and at a certain time, use a PHP code to insert/update them into your MySQL database. Your php code can be executed periodically using Cron, so check if your server has Cron so that you can set the schedule for that, say every 10 minutes.

Have a look at this page: http://damonparker.org/blog/2006/05/10/php-cron-script-to-run-automated-jobs/. Some codes have been written in the cloud and are ready for you to use :)


问:
TypeError: <class 'datetime.time'> is not convertible to datetime
The problem is somewhat simple. My objective is to compute the days difference between two dates, say A and B.

These are my attempts:

```<code>df['daydiff'] = df['A']-df['B']

df['daydiff'] = ((df['A']) - (df['B'])).dt.days

df['daydiff'] = (pd.to_datetime(df['A'])-pd.to_datetime(df['B'])).dt.days
</code>```

These works for me before but for some reason, I'm keep getting this error this time:

TypeError: class 'datetime.time' is not convertible to datetime

When I export the df to excel, then the date works just fine. Any thoughts?

答:
When I applied the solution offered by emmet02, I got TypeError: Cannot convert input [00:00:00] of type  as well. It's basically saying that the dataframe contains missing timestamp values which are represented as [00:00:00], and this value is rejected by pandas.Timestamp function.

To address this, simply apply a suitable missing-value strategy to clean your data set, before using

```<code>df.apply(pd.Timestamp)
</code>```

Body:
The problem is somewhat simple. My objective is to compute the days difference between two dates, say A and B.

These are my attempts:

df['daydiff'] = df['A']-df['B']

df['daydiff'] = ((df['A']) - (df['B'])).dt.days

df['daydiff'] = (pd.to_datetime(df['A'])-pd.to_datetime(df['B'])).dt.days

These works for me before but for some reason, I'm keep getting this error this time:

TypeError: class 'datetime.time' is not convertible to datetime

When I export the df to excel, then the date works just fine. Any thoughts?

Body:
When I applied the solution offered by emmet02, I got TypeError: Cannot convert input [00:00:00] of type  as well. It's basically saying that the dataframe contains missing timestamp values which are represented as [00:00:00], and this value is rejected by pandas.Timestamp function.

To address this, simply apply a suitable missing-value strategy to clean your data set, before using

df.apply(pd.Timestamp)


问:
lerna import always returns EDESTDIR
I have a pre-existing project that I'd like to import into my existing lerna monorepo that uses yarn workspaces.

Command(s):

I've tried running all of the following commands. The error remains stubbornly unchanged. Also, petstore has a package.json file and is a git repo.

```<code>lerna import ./petstore --dest="./packages/"
lerna import ./petstore --dest="./packages/api/"
</code>```

ERROR:

```<code>lerna notice cli v3.20.2
lerna ERR! EDESTDIR --dest does not match with the package directories: packages/**
</code>```

Also, lerna import ../petstore results in a packages/**/petstore being created which is not an expected result.

I hope this consists of all the relevant code. We have supporting packages under packages/shared and apis under packages/api.

lerna.json

```<code>{
  "packages": [
    "packages/**/*"
  ],
  "npmClient": "yarn",
  "useWorkspaces": true,
  "private": true,
  "version": "0.0.1",
  "lerna": "2.11.0"
}
</code>```

package.json

```<code>{
  "name": "root",
  "devDependencies": {
    "lerna": "^2.11.0"
  },
  "workspaces": [
    "packages/**/*"
  ],
}
</code>```

Resources I have looked at:

Lerna troubleshooting page but it does not have any info on this error.

Lerna Github Issue #1872

Lerna Github Issue #1197

Lerna Slack Link Broken

答:
Lerna reads the packages from the key workspaces on package.json instead of the packages on lerna.json.

lerna reads all the values with a /* and considers them package directories. It interprets ** literally and does not parse it as a wildcard and expand it.

The solution is to remove packages from lerna.json:

```<code>{
  "npmClient": "yarn",
  "useWorkspaces": true,
  "private": true,
  "version": "0.0.1",
  "lerna": "2.11.0"
}
</code>```

and update the workspaces path to refer to any sub-directories in your packages explicitly if your monorepo is structured that way:

```<code>{
  "name": "root",
  "devDependencies": {
    "lerna": "^2.11.0"
  },
  "workspaces": [
    "packages/a/*",
    "packages/api/*"
  ],
}
</code>```

To import the pet-store project into packages/api in the monorepo from a directory outside the mono-repo:

```<code>lerna import ../pet-store --dest="./packages/api/"
</code>```

Title: lerna import always returns EDESTDIR

Body:
I have a pre-existing project that I'd like to import into my existing lerna monorepo that uses yarn workspaces.

Command(s):

I've tried running all of the following commands. The error remains stubbornly unchanged. Also, petstore has a package.json file and is a git repo.

lerna import ./petstore --dest="./packages/"
lerna import ./petstore --dest="./packages/api/"

ERROR:

lerna notice cli v3.20.2
lerna ERR! EDESTDIR --dest does not match with the package directories: packages/**

Also, lerna import ../petstore results in a packages/**/petstore being created which is not an expected result.

I hope this consists of all the relevant code. We have supporting packages under packages/shared and apis under packages/api.

lerna.json

{
  "packages": [
    "packages/**/*"
  ],
  "npmClient": "yarn",
  "useWorkspaces": true,
  "private": true,
  "version": "0.0.1",
  "lerna": "2.11.0"
}

package.json

{
  "name": "root",
  "devDependencies": {
    "lerna": "^2.11.0"
  },
  "workspaces": [
    "packages/**/*"
  ],
}

Resources I have looked at:

Lerna troubleshooting page but it does not have any info on this error.

Lerna Github Issue #1872

Lerna Github Issue #1197

Lerna Slack Link Broken

Body:
Lerna reads the packages from the key workspaces on package.json instead of the packages on lerna.json.

lerna reads all the values with a /* and considers them package directories. It interprets ** literally and does not parse it as a wildcard and expand it.

The solution is to remove packages from lerna.json:

{
  "npmClient": "yarn",
  "useWorkspaces": true,
  "private": true,
  "version": "0.0.1",
  "lerna": "2.11.0"
}

and update the workspaces path to refer to any sub-directories in your packages explicitly if your monorepo is structured that way:

{
  "name": "root",
  "devDependencies": {
    "lerna": "^2.11.0"
  },
  "workspaces": [
    "packages/a/*",
    "packages/api/*"
  ],
}

To import the pet-store project into packages/api in the monorepo from a directory outside the mono-repo:

lerna import ../pet-store --dest="./packages/api/"


问:
Call node.setSelected(true) but row is not selected from React
My React application has a "Merge" button, which calls a web service to combine 2 rows in the ag-grid into one row.

After calling the web service, I want to re-render the grid, with the first row selected.  I call my ReRender function to do this.  The function calls my web service to re-retrieve the data, then it tries to select the row.

No errors happen, the data is re-rendered,  the console shows I did find the matching row to select, so I call node.setSelection(true), but the row is not selected.  What can I do?  The grid is paginated.

Code:

```<code>    ReRender = (inventorykey) => {
            console.log(inventorykey)
            this.rowChecked = []
            fetch( 'http://apsrp07823.svr.com:8088/mpa/getCockpit?userkey=' + this.state.userkey )
            .then(res=>res.json())
            .then(resj=>{
                if (resj.rows && resj.rows.length>0) {
                    this.setState({rowData:resj.rows})
                }
            })
            .then(
                    console.log('invKey loop:'),
                    this.gridApi.forEachNode( (node) => {
                        if ( node.data.inventorykey === inventorykey ) {
                        console.log('Found it!')
                        node.setSelected(true);}
                        else{console.log('no '+inventorykey)}
                    })
                )

            .catch(console.log)
            //this.gridApi.redrawRows(redrawRowsParams)
            //this.gridApi.refreshCells()
        }
</code>```

```<code>--Console log output---
</code>```

```<code>    27991
    InventoryList.js:114 invKey loop:
    InventoryList.js:119 Found it!
    105
    InventoryList.js:121 no 27991
    UserBoard.js:86 forceUpdate
</code>```

According to the Console Log, it found the row and made the call to select it.  So why isn't it selected?  Please advise.

答:
What @Pratik is suggesting is correct, I'd like to add something on top of that.

You could directly set rowSelection property on the grid element itself (apart from gridOptions).

```<code>    <AgGridReact
      ...
      onGridReady={this.onGridReady}
      rowData={this.state.rowData}
      rowSelection='single'
    />
</code>```

rowSelection: Type of row selection, set to either 'single' or 'multiple' to enable selection. 'single' will use single row selection, such that when you select a row, any previously selected row gets unselected. 'multiple' allows multiple rows to be selected.

Reference: Row Selection

Body:
My React application has a "Merge" button, which calls a web service to combine 2 rows in the ag-grid into one row.

After calling the web service, I want to re-render the grid, with the first row selected.  I call my ReRender function to do this.  The function calls my web service to re-retrieve the data, then it tries to select the row.

No errors happen, the data is re-rendered,  the console shows I did find the matching row to select, so I call node.setSelection(true), but the row is not selected.  What can I do?  The grid is paginated.

Code:

    ReRender = (inventorykey) => {
            console.log(inventorykey)
            this.rowChecked = []
            fetch( 'http://apsrp07823.svr.com:8088/mpa/getCockpit?userkey=' + this.state.userkey )
            .then(res=>res.json())
            .then(resj=>{
                if (resj.rows && resj.rows.length>0) {
                    this.setState({rowData:resj.rows})
                }
            })
            .then(
                    console.log('invKey loop:'),
                    this.gridApi.forEachNode( (node) => {
                        if ( node.data.inventorykey === inventorykey ) {
                        console.log('Found it!')
                        node.setSelected(true);}
                        else{console.log('no '+inventorykey)}
                    })
                )

            .catch(console.log)
            //this.gridApi.redrawRows(redrawRowsParams)
            //this.gridApi.refreshCells()
        }

--Console log output---

    27991
    InventoryList.js:114 invKey loop:
    InventoryList.js:119 Found it!
    105
    InventoryList.js:121 no 27991
    UserBoard.js:86 forceUpdate

According to the Console Log, it found the row and made the call to select it.  So why isn't it selected?  Please advise.

Body:
What @Pratik is suggesting is correct, I'd like to add something on top of that.

You could directly set rowSelection property on the grid element itself (apart from gridOptions).

    <AgGridReact
      ...
      onGridReady={this.onGridReady}
      rowData={this.state.rowData}
      rowSelection='single'
    />

rowSelection: Type of row selection, set to either 'single' or 'multiple' to enable selection. 'single' will use single row selection, such that when you select a row, any previously selected row gets unselected. 'multiple' allows multiple rows to be selected.

Reference: Row Selection


问:
Suggestions on how to get a consistent xpath for a dom element in javascript
I have been testing multiple code snippets, npm packages, etc. trying to find a way to consistently get an xpath from a dom node.  The only solution I found that works consistently is by using the chrome dev tools and choosing copy -> copyFullXpath.

What I currently have is working reasonably well but it doesn't seem to work well for a tags.  I'm specifically trying to get data from the shopify admin.  I realize they have an api but I need something I can implement in a chrome extension.  Shopify frontend is implemented in React but I don't think it's related.  I'm currently using this with success other than shopify a tags: https://github.com/firebug/firebug/blob/f8cf7e9c918dcf67c58f5affc0fb3716b0660232/extension/content/firebug/lib/xpath.js

I see chrome dev tools is open source but I don't know enough to extract the xpath portion (DomPath.js).

Any suggestions are appreciated.

答: After more debugging, I found that hovering over anchor tags was causing a div to be inserted several nodes up in the hierarchy.  It was, in fact, due to the site.  I decided when get the xpath from the element, to clone the current node and re-append it to it's parent so the event listeners would be removed.  This solved my issue.</p>


问:
How to ignore spell checking in Android lint using lint.xml or gradle script?
I tried using

```<code><issue id="Typos" severity="ignore"/>
</code>```

But it showing Spelling -> Typo error

答: It warning not by lint. It is an internal tool for Android Studio. If you want to disable typo warning, you need to do it Settings>Editor>Inspection>Spelling>Typo.

Body:
I tried using

<issue id="Typos" severity="ignore"/>

But it showing Spelling -> Typo error


问:
Cannot start docker daemon in CentOS7
After executing systemctl start docker, I got:

Failed to start docker.service: Unit not found.

And this is the output for systemctl status docker -l:

```<code>[root@HP11012078 init.d]# systemctl status docker -l
● docker.service - Docker Application Container Engine
   Loaded: loaded (/etc/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: https://docs.docker.com

Feb 09 17:04:35 HP11012078 docker[28152]: time="2017-02-09T17:04:35.104333869+08:00" level=warning msg="container 58a5c6ba6710240bb5b1fd79e4600b547cf4c882eb2ca85e15c59c1404106877 restart canceled"
Feb 09 17:04:35 HP11012078 docker[28152]: time="2017-02-09T17:04:35.113914527+08:00" level=warning msg="container d320ba5f02cdd8567893acfc62b6673a24b6c8a43ccb52342bb3470ff420230d restart canceled"
Feb 09 17:04:35 HP11012078 docker[28152]: time="2017-02-09T17:04:35.122613873+08:00" level=warning msg="container 4030daadb9481a1b96b7a5c614c8910a601f83f2dced8340f4ea4c3583e7e844 restart canceled"
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45.002120051+08:00" level=info msg="Container c13f11ce792c477d9b663c6fdbcfe9694663f7843a40540c58922893f4b41247 failed to exit within 10 seconds of signal 15 - using the force"
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45.002120421+08:00" level=info msg="Container 0457d15d8b0bc83458dd3eea0c0b84699465da9746defc2429db89e426dbfa75 failed to exit within 10 seconds of signal 15 - using the force"
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45.002870012+08:00" level=warning msg="Cannot kill container c13f11ce792c477d9b663c6fdbcfe9694663f7843a40540c58922893f4b41247: rpc error: code = 2 desc = \"containerd: container not found\""
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45.049505738+08:00" level=warning msg="container 0457d15d8b0bc83458dd3eea0c0b84699465da9746defc2429db89e426dbfa75 restart canceled"
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45.173034929+08:00" level=error msg="Force shutdown daemon"
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45+08:00" level=info msg="stopping containerd after receiving terminated"
Feb 09 17:04:46 HP11012078 systemd[1]: Stopped Docker Application Container Engine.
</code>```

But I can start docker using docker daemon command. Help, please

答:
If you get this error when installing Docker on CentOS 8:

On CentOS 8.1 the podman-manpages are in conflict with docker-ce (podman is Red Hat's container engine, and which comes pre-installed as a replacement for Docker).

A simple solution is to uninstall podman if you don't need it:

sudo yum -y remove podman

https://github.com/containers/libpod/issues/4791

Then you can install Docker:

sudo dnf install docker-ce --nobest -y

and

```<code>sudo systemctl daemon-reload
sudo systemctl start docker
sudo systemctl enable docker
</code>```

Title: Cannot start docker daemon in CentOS7

Body:
After executing systemctl start docker, I got:

Failed to start docker.service: Unit not found.

And this is the output for systemctl status docker -l:

[root@HP11012078 init.d]# systemctl status docker -l
● docker.service - Docker Application Container Engine
   Loaded: loaded (/etc/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: https://docs.docker.com

Feb 09 17:04:35 HP11012078 docker[28152]: time="2017-02-09T17:04:35.104333869+08:00" level=warning msg="container 58a5c6ba6710240bb5b1fd79e4600b547cf4c882eb2ca85e15c59c1404106877 restart canceled"
Feb 09 17:04:35 HP11012078 docker[28152]: time="2017-02-09T17:04:35.113914527+08:00" level=warning msg="container d320ba5f02cdd8567893acfc62b6673a24b6c8a43ccb52342bb3470ff420230d restart canceled"
Feb 09 17:04:35 HP11012078 docker[28152]: time="2017-02-09T17:04:35.122613873+08:00" level=warning msg="container 4030daadb9481a1b96b7a5c614c8910a601f83f2dced8340f4ea4c3583e7e844 restart canceled"
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45.002120051+08:00" level=info msg="Container c13f11ce792c477d9b663c6fdbcfe9694663f7843a40540c58922893f4b41247 failed to exit within 10 seconds of signal 15 - using the force"
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45.002120421+08:00" level=info msg="Container 0457d15d8b0bc83458dd3eea0c0b84699465da9746defc2429db89e426dbfa75 failed to exit within 10 seconds of signal 15 - using the force"
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45.002870012+08:00" level=warning msg="Cannot kill container c13f11ce792c477d9b663c6fdbcfe9694663f7843a40540c58922893f4b41247: rpc error: code = 2 desc = \"containerd: container not found\""
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45.049505738+08:00" level=warning msg="container 0457d15d8b0bc83458dd3eea0c0b84699465da9746defc2429db89e426dbfa75 restart canceled"
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45.173034929+08:00" level=error msg="Force shutdown daemon"
Feb 09 17:04:45 HP11012078 docker[28152]: time="2017-02-09T17:04:45+08:00" level=info msg="stopping containerd after receiving terminated"
Feb 09 17:04:46 HP11012078 systemd[1]: Stopped Docker Application Container Engine.

But I can start docker using docker daemon command. Help, please

Body:
If you get this error when installing Docker on CentOS 8:

On CentOS 8.1 the podman-manpages are in conflict with docker-ce (podman is Red Hat's container engine, and which comes pre-installed as a replacement for Docker).

A simple solution is to uninstall podman if you don't need it:

sudo yum -y remove podman

https://github.com/containers/libpod/issues/4791

Then you can install Docker:

sudo dnf install docker-ce --nobest -y

and

sudo systemctl daemon-reload
sudo systemctl start docker
sudo systemctl enable docker


问:
prefabs are missing in unity3d project
I am learning unity . I downloaded a project from version control ( and that app is live ) but I cannot build it locally ; its giving me missing prefabs ; tried everything that's available in unity forums still can't resolve. Any help would be greatly acknowledged. Thanks in advance .

p.s. The project is built using unity 5.4.2 and I am using 2018.4.17f1 (if that would help )

答:
In general avoid huge version jumps in Unity. Rather backup and upgrade a project in incremental steps and each time test between them! Between 5.4.2 (Okt 2016) and 2018.4.17LTS (Feb 2020) there passed over 3 years and a lot of things changed!

Especially the entire prefab system changed as there now are nested Prefabs etc. This might be the problem.

It is also very probable that a Unity git repository uses Git LFS (large file storage).

In this case certain file types are not pushed into the repository itself but rather to the large file storage. In the git repository the files will then only contain references to where to download these large files.

You can try and

Download and install Git LFS

Open your Git Bash in the repository directory and run

```<code>git lfs install
</code>```

This is needed once for each repository.

Download all LFS referenced files for a repository via

```<code>git lfs fetch --all
</code>```

Title: prefabs are missing in unity3d project

Body:
In general avoid huge version jumps in Unity. Rather backup and upgrade a project in incremental steps and each time test between them! Between 5.4.2 (Okt 2016) and 2018.4.17LTS (Feb 2020) there passed over 3 years and a lot of things changed!

Especially the entire prefab system changed as there now are nested Prefabs etc. This might be the problem.

It is also very probable that a Unity git repository uses Git LFS (large file storage).

In this case certain file types are not pushed into the repository itself but rather to the large file storage. In the git repository the files will then only contain references to where to download these large files.

You can try and

Download and install Git LFS

Open your Git Bash in the repository directory and run

git lfs install

This is needed once for each repository.

Download all LFS referenced files for a repository via

git lfs fetch --all


问:
Facing issue while creating wear App XML : AAPT: error: attribute android:boxedEdges not found
In the below XML, I am getting error over android:boxedEdges="all". I have tried to remove this line but not solved it.

I am still getting the AAPT: error: attribute android:boxedEdges not found

```<code> <?xml version="1.0" encoding="utf-8"?>
    <androidx.wear.widget.BoxInsetLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/dark_grey"
        android:padding="@dimen/box_inset_layout_padding"
        tools:context=".MainActivity"
        tools:deviceIds="wear">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="@dimen/inner_frame_layout_padding"
            android:boxedEdges="all">

            <TextView
                android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="@string/hello_world" />

            <Button
                android:layout_width="wrap_content"
                android:layout_gravity="center"
                android:layout_height="wrap_content"
                android:text="Press Here" />

        </FrameLayout>
    </androidx.wear.widget.BoxInsetLayout>
</code>```

This is a simple wear OS project. I am new on that so any help or link will appreciates.

答: It is app:boxedEdges, not android:boxedEdges as per the BoxInsetLayout documentation.

Body:
In the below XML, I am getting error over android:boxedEdges="all". I have tried to remove this line but not solved it.

I am still getting the AAPT: error: attribute android:boxedEdges not found

 <?xml version="1.0" encoding="utf-8"?>
    <androidx.wear.widget.BoxInsetLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/dark_grey"
        android:padding="@dimen/box_inset_layout_padding"
        tools:context=".MainActivity"
        tools:deviceIds="wear">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="@dimen/inner_frame_layout_padding"
            android:boxedEdges="all">

            <TextView
                android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="@string/hello_world" />

            <Button
                android:layout_width="wrap_content"
                android:layout_gravity="center"
                android:layout_height="wrap_content"
                android:text="Press Here" />

        </FrameLayout>
    </androidx.wear.widget.BoxInsetLayout>

This is a simple wear OS project. I am new on that so any help or link will appreciates.


问:
Getting command not found: rasa on using rasa commands
I have installed rasa using:

```<code>pip3 install rasa
</code>```

When I try to use rasa commands like:

```<code>rasa init
</code>```

I get zsh errors:

command not found: rasa error

I am on Mac OS Catalina, using:

Python version 2.7.16

Python3 version 3.7.6

pip version 19.2.3

My path variable looks like this:

```<code>/Library/Frameworks/Python.framework/Versions/3.7/bin
:/usr/local/bin
:/usr/bin
:/bin
:/usr/sbin
:/sbin
</code>```

答:
I had followed these following steps and it's working fine for me

Firstly, create a directory name of your choice and get inside of it

```<code>mkdir rasaprojects #directory name of your choice in place of rasaprojects
cd rasaprojects   #get inside that directory
</code>```

Now create virtual environment of python3

```<code>virtualenv rasaenv -p python3 #write your environment name instead of rasaenv
</code>```

Now activate the environment

```<code>source rasaenv/bin/activate
</code>```

Finally you are good to go with rasa installation

```<code>pip3 install rasa
</code>```

Body:
I have installed rasa using:

pip3 install rasa

When I try to use rasa commands like:

rasa init

I get zsh errors:

command not found: rasa error

I am on Mac OS Catalina, using:

Python version 2.7.16

Python3 version 3.7.6

pip version 19.2.3

My path variable looks like this:

/Library/Frameworks/Python.framework/Versions/3.7/bin
:/usr/local/bin
:/usr/bin
:/bin
:/usr/sbin
:/sbin

Body:
I had followed these following steps and it's working fine for me

Firstly, create a directory name of your choice and get inside of it

mkdir rasaprojects #directory name of your choice in place of rasaprojects
cd rasaprojects   #get inside that directory

Now create virtual environment of python3

virtualenv rasaenv -p python3 #write your environment name instead of rasaenv

Now activate the environment

source rasaenv/bin/activate

Finally you are good to go with rasa installation

pip3 install rasa


问:
Fastest way to see added, removed, and changed Objects (not primitives) between two arrays
I have a completely manual, ugly way to find all added, removed, and changed Objects (not primitives) between two arrays, and I'm wondering if there is a faster, more efficient way to accomplish this same thing. Any libraries that accomplish this?  the lodash difference function tells me all differences rather than which ones have been added and which have changed, so it doesn't do what I need.

Here is my code.  It works, and i want to do exactly this, just the most efficient way available:

```<code>    let previousState = state[0]; //<-- an array of object literals
    let currentState = state[1]; //<-- an array of object literals

    let added = [];
    let removed = [];
    let edited = [];

    for(let i = 0; i < previousState.length; i++){
        let old = previousState[i];
        let current = currentState.find(x => x.id === old.id);
        if(!current){
            removed.push(current);
        }
    }

    for(let i = 0; i < currentState.length; i++){
        let current = currentState[i];
        let old = previousState.find(x => x.id === current.id);
        if(!old){
            added.push(current);
            continue;
        }
        if(!_.isEqual(current, old)){ //<-- this is the lodash .isEqual function
            edited.push(current);
        }
    }
</code>```

答:
This isn't necessarily faster in execution time, but it does make it a little more "functional". Hopefully this helps.

// You just need to rename the "a" and "b" variables to your variable names where "a" is the original array and "b" is the array that you're comparing to it.
const a = [{ id: 1, name: 'a' }, { id: 2, name: 'b' }];
const b = [{ id: 1, name: 'abc' }, { id: 3, name: 'c' }];

const removedFromA = _.differenceBy(a, b, 'id');
const addedToA = _.differenceBy(b, a, 'id');
const changedInA = _.chain(a)
 .reject((v) => _.find(removedFromA, { id: v.id }) || _.find(addedToA, { id: v.id }))
  .reject((v) => _.chain(b).find({ id: v.id }).isEqual(v).value())
  .value();

console.log('Removed From A: ', removedFromA);
console.log('Added To A: ', addedToA);
console.log('Changed In A: ', changedInA);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script></code>```

Body:
I have a completely manual, ugly way to find all added, removed, and changed Objects (not primitives) between two arrays, and I'm wondering if there is a faster, more efficient way to accomplish this same thing. Any libraries that accomplish this?  the lodash difference function tells me all differences rather than which ones have been added and which have changed, so it doesn't do what I need.

Here is my code.  It works, and i want to do exactly this, just the most efficient way available:

    let previousState = state[0]; //<-- an array of object literals
    let currentState = state[1]; //<-- an array of object literals

    let added = [];
    let removed = [];
    let edited = [];

    for(let i = 0; i < previousState.length; i++){
        let old = previousState[i];
        let current = currentState.find(x => x.id === old.id);
        if(!current){
            removed.push(current);
        }
    }

    for(let i = 0; i < currentState.length; i++){
        let current = currentState[i];
        let old = previousState.find(x => x.id === current.id);
        if(!old){
            added.push(current);
            continue;
        }
        if(!_.isEqual(current, old)){ //<-- this is the lodash .isEqual function
            edited.push(current);
        }
    }

Body:
This isn't necessarily faster in execution time, but it does make it a little more "functional". Hopefully this helps.

// You just need to rename the "a" and "b" variables to your variable names where "a" is the original array and "b" is the array that you're comparing to it.
const a = [{ id: 1, name: 'a' }, { id: 2, name: 'b' }];
const b = [{ id: 1, name: 'abc' }, { id: 3, name: 'c' }];

const removedFromA = _.differenceBy(a, b, 'id');
const addedToA = _.differenceBy(b, a, 'id');
const changedInA = _.chain(a)
 .reject((v) => _.find(removedFromA, { id: v.id }) || _.find(addedToA, { id: v.id }))
  .reject((v) => _.chain(b).find({ id: v.id }).isEqual(v).value())
  .value();

console.log('Removed From A: ', removedFromA);
console.log('Added To A: ', addedToA);
console.log('Changed In A: ', changedInA);

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>


问:
azure ad b2c custom policy - how to get user object id and email in the claim?
went through the instructions here https://learn.microsoft.com/en-us/azure/active-directory-b2c/custom-policy-get-started?tabs=app-reg-preview to create a custom policy to use Local account sign up/in. however the user object id and email address are missing from the token. any idea on how to get these claims?</p>

答:
sub is the user object id and signInName is the email.

Here is the OutputClaims.

```<code><OutputClaims>
        <OutputClaim ClaimTypeReferenceId="displayName" />
        <OutputClaim ClaimTypeReferenceId="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" />
        <OutputClaim ClaimTypeReferenceId="email" />
        <OutputClaim ClaimTypeReferenceId="signInName" DefaultValue="" />
        <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
        <OutputClaim ClaimTypeReferenceId="tenantId" AlwaysUseDefaultValue="true" DefaultValue="{Policy:TenantObjectId}" />

      </OutputClaims>
</code>```

Body:
sub is the user object id and signInName is the email.

Here is the OutputClaims.

<OutputClaims>
        <OutputClaim ClaimTypeReferenceId="displayName" />
        <OutputClaim ClaimTypeReferenceId="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" />
        <OutputClaim ClaimTypeReferenceId="email" />
        <OutputClaim ClaimTypeReferenceId="signInName" DefaultValue="" />
        <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
        <OutputClaim ClaimTypeReferenceId="tenantId" AlwaysUseDefaultValue="true" DefaultValue="{Policy:TenantObjectId}" />

      </OutputClaims>


问:
Twilio not sending webhooks in Progammable Chat
I would like to ask a question or maybe report a bug after solving my doubts. I started working with Programmable Chat and Twilio do not want to send a webhook to specific url but only when I'm sending message from my PHP code. I downloaded example node app and sending message from that, everything is working really nice, I'm getting post request from Twilio but if only I will send message from PHP, nothing at all. And strange is, after sending message from PHP, it will appear immediately in chat which means that it's working.

How does it possible? Could it mean that Twilio on theirs backend has an a bug when they receive message from PHP and becuase of that they are not fire webhook event?

I eliminated all differences, everything is that same beside that one message is sending from PHP and another from node. Same situation from API Explorer.

Gif presentation

答:
Twilio developer evangelist here.

When you send messages to Programmable Chat from the REST API then webhooks aren't triggered. I think the reasoning is because you are making the call from your server, then your server is already aware that you are sending a message and you don't need to receive a webhook to do so. It also saves from the potential of infinite loops (if your webhook sends a message via the REST API, the requests would just go in circles).

So, it's not a bug, but a design choice. If you need to trigger your webhooks when you send a message from the REST API, you will need to make the webhook from your own server.


问:
How to make the progressbar work, It freezes the window
I tried making the progressbar but instead of working, it freezes the tkinter window, I also tried closing it but it froze the window

```<code>from tkinter import *
from tkinter.ttk import *
import time

root = Tk()

pbar = Progressbar(root, orient = HORIZONTAL,
                       length = 100, mode = 'determinate')

def bar():
    pbar['value'] = 20
    time.sleep(0.5)

    pbar['value'] = 40
    time.sleep(0.5)

    pbar['value'] = 60
    time.sleep(0.5)

    pbar['value'] = 80
    time.sleep(0.5)

    pbar['value'] = 100

pbar.pack()

Button(root, text = 'Start Bar', command = bar).pack()

root.mainloop()
</code>```

How to make it work !

答:
The correct approach is to use root.after, while making sure that multiple button presses are dropped while the progress bar is active:

Here we are using a key word argument with default value to identify if the call originated from the button, or from a callback. We are also storing the callback id in a closure that is implemented via a mutable default value keyword argument; this allows us to cleanly cancel further callbacks when the work is complete.

```<code>import tkinter as tk
import tkinter.ttk as ttk

def bar(btn=True, status=[None]):
    """activates and updates the progress bar status
    while making sure that multiple button presses only
    start it once.
    """

    if btn and status[0] is not None:
        return 'break'
    elif pbar['value'] < 100:
        pbar['value'], status[0] = pbar['value'] + 1, root.after(10, bar, False)
    else:
        root.after_cancel(status[0])
        pbar['value'], status[0] = 0, None

root = tk.Tk()
pbar = ttk.Progressbar(root, orient=tk.HORIZONTAL, length=100, mode='determinate')
pbar.pack()
tk.Button(root, text='Start Bar', command=bar).pack()
root.mainloop()
</code>```

Body:
I tried making the progressbar but instead of working, it freezes the tkinter window, I also tried closing it but it froze the window

from tkinter import *
from tkinter.ttk import *
import time

root = Tk()

pbar = Progressbar(root, orient = HORIZONTAL,
                       length = 100, mode = 'determinate')

def bar():
    pbar['value'] = 20
    time.sleep(0.5)

    pbar['value'] = 40
    time.sleep(0.5)

    pbar['value'] = 60
    time.sleep(0.5)

    pbar['value'] = 80
    time.sleep(0.5)

    pbar['value'] = 100

pbar.pack()

Button(root, text = 'Start Bar', command = bar).pack()

root.mainloop()

How to make it work !

Body:
The correct approach is to use root.after, while making sure that multiple button presses are dropped while the progress bar is active:

Here we are using a key word argument with default value to identify if the call originated from the button, or from a callback. We are also storing the callback id in a closure that is implemented via a mutable default value keyword argument; this allows us to cleanly cancel further callbacks when the work is complete.

import tkinter as tk
import tkinter.ttk as ttk

def bar(btn=True, status=[None]):
    """activates and updates the progress bar status
    while making sure that multiple button presses only
    start it once.
    """

    if btn and status[0] is not None:
        return 'break'
    elif pbar['value'] < 100:
        pbar['value'], status[0] = pbar['value'] + 1, root.after(10, bar, False)
    else:
        root.after_cancel(status[0])
        pbar['value'], status[0] = 0, None

root = tk.Tk()
pbar = ttk.Progressbar(root, orient=tk.HORIZONTAL, length=100, mode='determinate')
pbar.pack()
tk.Button(root, text='Start Bar', command=bar).pack()
root.mainloop()


问:
Change the subsite Logo URL IN SharePoint
I have created a main site and I have created many subsite under the main site.

When I am in any main page and click on the logo icon, the page redirects to the home page.

But, when I am in any subsite and click on the logo icon, the page redirects to the subsite homepage rather than the main hompage.

I would like to change the navigation URL to the root site.  Let me know if I have to edit any masterpage, or is there any common page that will inherit to all the child application.

Thanks

答:
It works.
Edit on the SharePoint Designer Master Pages > seattle.master .
Crtl F - Search for DeltaSiteLogo

DEFAULT:

```<code><SharePoint:SPSimpleSiteLink CssClass="ms-siteicon-a" runat="server" id="onetidProjectPropertyTitleGraphic" >
        <SharePoint:SiteLogoImage CssClass="ms-siteicon-img" name="onetidHeadbnnr0" id="onetidHeadbnnr2" LogoImageUrl="/_layouts/15/images/siteIcon.png?rev=47" runat="server"/>
    </SharePoint:SPSimpleSiteLink>
</code>```

Change To This (copy & paste the script):

```<code><SharePoint:SPLinkButton runat="server" NavigateUrl="~sitecollection/" CssClass="ms-siteicon-a" ID="x7917ecc8c38d4bd69f58e338eab54c8c">
        <SharePoint:SiteLogoImage CssClass="ms-siteicon-img" name="onetidHeadbnnr0" id="onetidHeadbnnr2" LogoImageUrl="/_layouts/15/images/siteIcon.png?rev=47" runat="server"/>
    </SharePoint:SPLinkButton>
</code>```

Body:
It works.
Edit on the SharePoint Designer Master Pages > seattle.master .
Crtl F - Search for DeltaSiteLogo

DEFAULT:

<SharePoint:SPSimpleSiteLink CssClass="ms-siteicon-a" runat="server" id="onetidProjectPropertyTitleGraphic" >
        <SharePoint:SiteLogoImage CssClass="ms-siteicon-img" name="onetidHeadbnnr0" id="onetidHeadbnnr2" LogoImageUrl="/_layouts/15/images/siteIcon.png?rev=47" runat="server"/>
    </SharePoint:SPSimpleSiteLink>

Change To This (copy & paste the script):

<SharePoint:SPLinkButton runat="server" NavigateUrl="~sitecollection/" CssClass="ms-siteicon-a" ID="x7917ecc8c38d4bd69f58e338eab54c8c">
        <SharePoint:SiteLogoImage CssClass="ms-siteicon-img" name="onetidHeadbnnr0" id="onetidHeadbnnr2" LogoImageUrl="/_layouts/15/images/siteIcon.png?rev=47" runat="server"/>
    </SharePoint:SPLinkButton>


问:
Remove padding from chartJs horizontal bar chart
Hey :) thanks in advance for helping me out on this issue.

I have a horizontal chart in ChartJs with some dummy info. I currently want to line it up with the statistic above it. In ChartJs the charts get rendered inside a <canvas> tag. I want to remove the spacing in the chart. I'm assuming this is padding but its not on the canvas it's within the chart itself. I've read up on the docs and tried a few of the choices.

Just some extra info, I customized the chart and it now looks like this:

Removed the legend

Flipped the labels

Changed the label colour

Removed the grid lines

HTML:
<canvas id="myChart" width="400" height="150"></canvas>

```<code>    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'horizontalBar',
        data: {
            labels: ['1', '2'],
            datasets: [{
                label: 'Money in',
                data: [5, 19],
                backgroundColor: [
                    'rgb(0,51,160)',
                    'rgb(26,121,191)'
                ],
                borderWidth: 0
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        fontColor: 'white',
                        display: true,
                        position: top,
                        mirror: true,
                        beginAtZero: true,
                        fontSize: 17,
                        padding: -9,
                        z: 1
                    },
                    gridLines: {
                        display: false
                    }
                }],
                xAxes: [{
                    gridLines: {
                        display: false
                    },
                    ticks: {
                        beginAtZero: true,
                        display: false
                    }
                }]
            },
            legend: {
                display: false
            }
        }
    });
</code>```

答:
You can define the layout with negative left padding as follows:

```<code>options: {
    layout: {
      padding: {
        left: -10
      }
    },
    ...
</code>```

Please have a look at the following code snippet where the chart canvas is defined with a border in order to emphasize the alignment with the preceding text.

var myChart = new Chart(document.getElementById('myChart'), {
  type: 'horizontalBar',
  data: {
    labels: ['1', '2'],
    datasets: [{
      label: 'Money in',
      data: [5, 19],
      backgroundColor: ['rgb(0,51,160)', 'rgb(26,121,191)'],
      borderWidth: 0
    }]
  },
  options: {
    layout: {
      padding: {
        left: -10
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          fontColor: 'white',
          mirror: true,
          beginAtZero: true,
          fontSize: 17,
          padding: -9,
          z: 1
        },
        gridLines: {
          display: false
        }
      }],
      xAxes: [{
        gridLines: {
          display: false
        },
        ticks: {
          beginAtZero: true,
          display: false
        }
      }]
    },
    legend: {
      display: false
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas{
  max-width: 300px;
  border: 1px solid #000;
}</code>```

Text here

<canvas id="myChart" width="400" height="150"></canvas>```

Body:
Hey :) thanks in advance for helping me out on this issue.

I have a horizontal chart in ChartJs with some dummy info. I currently want to line it up with the statistic above it. In ChartJs the charts get rendered inside a <canvas> tag. I want to remove the spacing in the chart. I'm assuming this is padding but its not on the canvas it's within the chart itself. I've read up on the docs and tried a few of the choices.

Just some extra info, I customized the chart and it now looks like this:

Removed the legend

Flipped the labels

Changed the label colour

Removed the grid lines

HTML:
<canvas id="myChart" width="400" height="150"></canvas>

    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'horizontalBar',
        data: {
            labels: ['1', '2'],
            datasets: [{
                label: 'Money in',
                data: [5, 19],
                backgroundColor: [
                    'rgb(0,51,160)',
                    'rgb(26,121,191)'
                ],
                borderWidth: 0
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        fontColor: 'white',
                        display: true,
                        position: top,
                        mirror: true,
                        beginAtZero: true,
                        fontSize: 17,
                        padding: -9,
                        z: 1
                    },
                    gridLines: {
                        display: false
                    }
                }],
                xAxes: [{
                    gridLines: {
                        display: false
                    },
                    ticks: {
                        beginAtZero: true,
                        display: false
                    }
                }]
            },
            legend: {
                display: false
            }
        }
    });

Body:
You can define the layout with negative left padding as follows:

options: {
    layout: {
      padding: {
        left: -10
      }
    },
    ...

Please have a look at the following code snippet where the chart canvas is defined with a border in order to emphasize the alignment with the preceding text.

var myChart = new Chart(document.getElementById('myChart'), {
  type: 'horizontalBar',
  data: {
    labels: ['1', '2'],
    datasets: [{
      label: 'Money in',
      data: [5, 19],
      backgroundColor: ['rgb(0,51,160)', 'rgb(26,121,191)'],
      borderWidth: 0
    }]
  },
  options: {
    layout: {
      padding: {
        left: -10
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          fontColor: 'white',
          mirror: true,
          beginAtZero: true,
          fontSize: 17,
          padding: -9,
          z: 1
        },
        gridLines: {
          display: false
        }
      }],
      xAxes: [{
        gridLines: {
          display: false
        },
        ticks: {
          beginAtZero: true,
          display: false
        }
      }]
    },
    legend: {
      display: false
    }
  }
});

canvas{
  max-width: 300px;
  border: 1px solid #000;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<p>Text here</p>
<canvas id="myChart" width="400" height="150"></canvas>


问:
Change style depending on RouterURL in Angular 8
I have one component named 'NavigatorComponent'. There I have my 'routerLink'. All the urls are attached to different components. Now the scenario is I have to change the link color depending on url it is currently. I am new to Angular and so I have no idea how to do it. Any help will be greatly appreciated. Below is the code snippet for Navigator.html and app-routing.module.ts file.

```<code><ul>
   <li><a class="active" [routerLink] = "'/welcome-information'">Welcome Information</a></li>
   <li><a class="disable" [routerLink] = "'/your-plan'">Select Your Plan</a></li>
   <li><a class="disable" [routerLink] = "'/your-data'">Confirm Your Data</a></li>
   <li><a class="disable" [routerLink] = "'/bank-draft'">Bank Draft</a></li>
   <li><a class="disable" [routerLink] = "'/your-choice'">Finalize Your Choice</a></li>
</ul>

const routes: Routes = [
  {path: 'welcome-information' , component: WelcomeInformationComponent},
  {path: 'your-plan' , component: YourPlanComponent},
  {path: 'your-data' , component: YourDataComponent},
  {path: 'bank-draft' , component: BankDraftComponent},
  {path: 'your-choice' , component: YourChoiceComponent},
];
</code>```

答:
Use routerLinkActive directive.

This directive adds a CSS class to an element when the link's route becomes active.

```<code><li><a  routerLinkActive="active" [routerLink] = "'/welcome-information'">Welcome Information</a></li>
<li><a  routerLinkActive="active"  class="disable" [routerLink] = "'/your-plan'">Select Your Plan</a></li>
</code>```

Demo

Body:
I have one component named 'NavigatorComponent'. There I have my 'routerLink'. All the urls are attached to different components. Now the scenario is I have to change the link color depending on url it is currently. I am new to Angular and so I have no idea how to do it. Any help will be greatly appreciated. Below is the code snippet for Navigator.html and app-routing.module.ts file.

Welcome Information

Select Your Plan

Confirm Your Data

Bank Draft

Finalize Your Choice

const routes: Routes = [
  {path: 'welcome-information' , component: WelcomeInformationComponent},
  {path: 'your-plan' , component: YourPlanComponent},
  {path: 'your-data' , component: YourDataComponent},
  {path: 'bank-draft' , component: BankDraftComponent},
  {path: 'your-choice' , component: YourChoiceComponent},
];

Body:
Use routerLinkActive directive.

This directive adds a CSS class to an element when the link's route becomes active.

<li><a  routerLinkActive="active" [routerLink] = "'/welcome-information'">Welcome Information</a></li>
<li><a  routerLinkActive="active"  class="disable" [routerLink] = "'/your-plan'">Select Your Plan</a></li>

Demo


问:
Padding printed output of tabular data
I know this is probably dead simple, but I've got some data such as this in one file:

Artichoke

Green Globe, Imperial Star, Violetto

24" deep

Beans, Lima

Bush Baby, Bush Lima, Fordhook, Fordhook 242

12" wide x 8-10" deep
```

<p>that I'd like to be able to format into a nice TSV type of table, to look something like this:</p>

<pre class="lang-none prettyprint-override"><code>    Name  | Varieties    | Container Data
----------|------------- |-------
some data here nicely padded with even spacing and right aligned text
</code>```

答: Kernel.sprintf should get you started.</p>

OwnerDisplayName: The Pied Pipes

Title: Padding printed output of tabular data

Body:
I know this is probably dead simple, but I've got some data such as this in one file:

Artichoke

Green Globe, Imperial Star, Violetto

24" deep

Beans, Lima

Bush Baby, Bush Lima, Fordhook, Fordhook 242

12" wide x 8-10" deep

that I'd like to be able to format into a nice TSV type of table, to look something like this:

    Name  | Varieties    | Container Data
----------|------------- |-------
some data here nicely padded with even spacing and right aligned text

Body: Kernel.sprintf should get you started.

OwnerDisplayName: Michael Sepcot

ContentLicense: CC BY-SA 2.5


问:
Python Find the words in the set have word pairs on dataframe
I have set of words

```<code>{'DNA',
 'pada',
 'yang',...}
</code>```

I am trying to find whether the words in the set have word pairs on the following bigram dataframe

```<code>                bigramf    freq
0           (DNA, yang)      15
1          (DNA, dalam)       6
2            (DNA, ini)       5
3       (DNA, memiliki)       4
4         (DNA, unting)       4
5           (pada, DNA)       4
6        (pada, urutan)       3
7     (yang, diperoleh)       3
8         (yang, lebih)       3
9      (pada, sejumlah)       2
10          (pada, RNA)       2
11          (pada, satu)      2
12       (yang, berbeda)      2
13          (yang, sama)      2
14       (yang, tumpang)      2
</code>```

If so, then the expected output will be like this:

```<code>yang [('lebih', 3), ('diperoleh', 3), ('berbeda', 2), ('tumpang', 2), ('sama', 2)]

DNA [('yang', 15), ('dalam', 6), ('ini', 5), ('memiliki', 4), ('unting', 4)]

pada [('DNA', 4), ('urutan', 3), ('sejumlah', 2), ('RNA', 2), ('satu', 2)]
</code>```

How do I find?. Can anyone can help? Thanks. Any help is much appreciated.

答:
First convert column with tuples to new 2 columns (dont use apply(pd.Series), because slow), then filter matched values by Series.isin in boolean indexing and convert in GroupBy.apply values to list of tuples:

```<code>s = {'DNA',
 'pada',
 'yang'}

df[['s', 'v']] = pd.DataFrame(df['bigramf'].tolist(), index=df.index)

s = df[df['s'].isin(s)].groupby('s')['v','freq'].apply(lambda x: list(map(tuple, x.values)))
print (s)
s
DNA     [(yang, 15), (dalam, 6), (ini, 5), (memiliki, ...
pada    [(DNA, 4), (urutan, 3), (sejumlah, 2), (RNA, 2...
yang    [(diperoleh, 3), (lebih, 3), (berbeda, 2), (sa...
dtype: object
</code>```

If need dictionary add Series.to_dict:

```<code>d = s.to_dict()
print (d)
{'DNA': [('yang', 15), ('dalam', 6), ('ini', 5), ('memiliki', 4), ('unting', 4)],
 'pada': [('DNA', 4), ('urutan', 3), ('sejumlah', 2), ('RNA', 2), ('satu', 2)],
 'yang': [('diperoleh', 3), ('lebih', 3), ('berbeda', 2), ('sama', 2), ('tumpang', 2)]}
</code>```

Another solution with collections.defaultdict:

```<code>from collections import defaultdict

d = defaultdict(list)
for (s1, v1), f1 in df.to_numpy():
    if s1 in s:
        d[s1].append((v1, f1))

d = dict(d)
print (d)
{'DNA': [('yang', 15), ('dalam', 6), ('ini', 5), ('memiliki', 4), ('unting', 4)],
 'pada': [('DNA', 4), ('urutan', 3), ('sejumlah', 2), ('RNA', 2), ('satu', 2)],
 'yang': [('diperoleh', 3), ('lebih', 3), ('berbeda', 2), ('sama', 2), ('tumpang', 2)]}
</code>```

Body:
I have set of words

{'DNA',
 'pada',
 'yang',...}

I am trying to find whether the words in the set have word pairs on the following bigram dataframe

                bigramf    freq
0           (DNA, yang)      15
1          (DNA, dalam)       6
2            (DNA, ini)       5
3       (DNA, memiliki)       4
4         (DNA, unting)       4
5           (pada, DNA)       4
6        (pada, urutan)       3
7     (yang, diperoleh)       3
8         (yang, lebih)       3
9      (pada, sejumlah)       2
10          (pada, RNA)       2
11          (pada, satu)      2
12       (yang, berbeda)      2
13          (yang, sama)      2
14       (yang, tumpang)      2

If so, then the expected output will be like this:

yang [('lebih', 3), ('diperoleh', 3), ('berbeda', 2), ('tumpang', 2), ('sama', 2)]

DNA [('yang', 15), ('dalam', 6), ('ini', 5), ('memiliki', 4), ('unting', 4)]

pada [('DNA', 4), ('urutan', 3), ('sejumlah', 2), ('RNA', 2), ('satu', 2)]

How do I find?. Can anyone can help? Thanks. Any help is much appreciated.

Body:
First convert column with tuples to new 2 columns (dont use apply(pd.Series), because slow), then filter matched values by Series.isin in boolean indexing and convert in GroupBy.apply values to list of tuples:

s = {'DNA',
 'pada',
 'yang'}

df[['s', 'v']] = pd.DataFrame(df['bigramf'].tolist(), index=df.index)

s = df[df['s'].isin(s)].groupby('s')['v','freq'].apply(lambda x: list(map(tuple, x.values)))
print (s)
s
DNA     [(yang, 15), (dalam, 6), (ini, 5), (memiliki, ...
pada    [(DNA, 4), (urutan, 3), (sejumlah, 2), (RNA, 2...
yang    [(diperoleh, 3), (lebih, 3), (berbeda, 2), (sa...
dtype: object

If need dictionary add Series.to_dict:

d = s.to_dict()
print (d)
{'DNA': [('yang', 15), ('dalam', 6), ('ini', 5), ('memiliki', 4), ('unting', 4)],
 'pada': [('DNA', 4), ('urutan', 3), ('sejumlah', 2), ('RNA', 2), ('satu', 2)],
 'yang': [('diperoleh', 3), ('lebih', 3), ('berbeda', 2), ('sama', 2), ('tumpang', 2)]}

Another solution with collections.defaultdict:

from collections import defaultdict

d = defaultdict(list)
for (s1, v1), f1 in df.to_numpy():
    if s1 in s:
        d[s1].append((v1, f1))

d = dict(d)
print (d)
{'DNA': [('yang', 15), ('dalam', 6), ('ini', 5), ('memiliki', 4), ('unting', 4)],
 'pada': [('DNA', 4), ('urutan', 3), ('sejumlah', 2), ('RNA', 2), ('satu', 2)],
 'yang': [('diperoleh', 3), ('lebih', 3), ('berbeda', 2), ('sama', 2), ('tumpang', 2)]}