问:
How to define textAppearence value in android layout
In my layout, I am using falling for predefined values for android:textAppearence. But, there are, as I found, at least 2 ways to define  them, which yields a very different result (like, different font size and alpha and weight value):

android:textAppearance:="@style/TextAppearance.MaterialComponents.Caption". This @style/... values are defined in (in my case) in a file
~/.gradle/caches/transforms-2/files-2.1/11ab83d2971a1126be493aa33fdd0f6e/material-1.1.0/res/values. This, for example, is defined as:

```<code><style name="TextAppearance.MaterialComponents.Caption" parent="TextAppearance.AppCompat.Caption">
  <item name="fontFamily">sans-serif</item>
  <item name="android:fontFamily">sans-serif</item>
  <item name="android:textStyle">normal</item>
  <item name="android:textAllCaps">false</item>
  <item name="android:textSize">12sp</item>
  <item name="android:letterSpacing">0.0333333333</item>
</style>
</code>```

android:textAppearance="@android:style/TextAppearance.Material.Menu". This is defined in
/home/rudra/.Android/Sdk/platforms/android-29/data/res/values/styles_material.xml. This is defined as:

```<code><style name="TextAppearance.Material.Menu">
    <item name="textSize">@dimen/text_size_menu_material</item>
    <item name="fontFamily">@string/font_family_menu_material</item>
</style>
</code>```

The main problem to me is, I am not sure which one to use for more consistent user experience. I am sure, the file for case 2 will not be shipped with my app, but maybe the user will have styles_material for his android-xx. But by realizing how values have changed with material-1.0.0 and 1.1.0, I am a bit sKeptic to depend on these values, but I am not sure.

On the other hand, this is a considerable work to redefine textAppearance for all possible scenarios.

So, I am looking for suggestions on how to define the textAppearence, and among case 1 and case 2, which should I use for more consistent result across devices

答:
If you want to define a custom textAppearance, you can define as follow. I use material-components-android.

In style.xml

```

<p>You can use this-<code>TextAppearance.Headline3</code> in layout as follow.</p>

```       <TextView
          android:id="@+id/tvAppName"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/app_name"
          android:textAppearance="?attr/textAppearanceHeadline3"
          />
```

This is my usage for custom text appearance. You can define as you like.

If you want to customize theme or style, you have to know common attributes. You can see it at this article.

I hope this will be helpful for you.

Body:
In my layout, I am using falling for predefined values for android:textAppearence. But, there are, as I found, at least 2 ways to define  them, which yields a very different result (like, different font size and alpha and weight value):

android:textAppearance:="@style/TextAppearance.MaterialComponents.Caption". This @style/... values are defined in (in my case) in a file
~/.gradle/caches/transforms-2/files-2.1/11ab83d2971a1126be493aa33fdd0f6e/material-1.1.0/res/values. This, for example, is defined as:

android:textAppearance="@android:style/TextAppearance.Material.Menu". This is defined in
/home/rudra/.Android/Sdk/platforms/android-29/data/res/values/styles_material.xml. This is defined as:

The main problem to me is, I am not sure which one to use for more consistent user experience. I am sure, the file for case 2 will not be shipped with my app, but maybe the user will have styles_material for his android-xx. But by realizing how values have changed with material-1.0.0 and 1.1.0, I am a bit sKeptic to depend on these values, but I am not sure.

On the other hand, this is a considerable work to redefine textAppearance for all possible scenarios.

So, I am looking for suggestions on how to define the textAppearence, and among case 1 and case 2, which should I use for more consistent result across devices

Body:
If you want to define a custom textAppearance, you can define as follow. I use material-components-android.

In style.xml

  <!-- Base application theme. -->
  <style name="AppTheme" parent="Theme.MaterialComponents.Light">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/primaryColor</item>
    <item name="colorPrimaryDark">@color/primaryDarkColor</item>
    <item name="colorPrimaryVariant">@color/primaryLightColor</item>
    <item name="colorOnPrimary">@color/primaryTextColor</item>
    <item name="colorSecondary">@color/secondaryColor</item>
    <item name="colorSecondaryVariant">@color/secondaryDarkColor</item>
    <item name="colorOnSecondary">@color/secondaryTextColor</item>

    <!-- This line is important -->
    <item name="textAppearanceHeadline3">@style/TextAppearance.Headline3</item>
  </style>

  <style name="TextAppearance.Headline3" parent="TextAppearance.MaterialComponents.Headline3">
    <!-- Define your custom appearance here. -->
    <item name="fontFamily">@font/work_sans_black</item>
    <item name="android:textAllCaps">false</item>
    <item name="android:textSize">@dimen/text_size</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@color/primaryTextColor</item>
  </style>

You can use this-TextAppearance.Headline3 in layout as follow.

       <TextView
          android:id="@+id/tvAppName"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/app_name"
          android:textAppearance="?attr/textAppearanceHeadline3"
          />

This is my usage for custom text appearance. You can define as you like.

If you want to customize theme or style, you have to know common attributes. You can see it at this article.

I hope this will be helpful for you.


来源: stackexchange

问:
How do I enable http2 in C# Kestrel web server over plain http?
How do I (and is it possible) to enable http2 over plain http in the C# Kestrel web server? All Microsoft documentation indicates that https/TLS is required, but I have services that will be running behind a load-balancer or nginx and as such don't need a second layer of https. The official http2 spec indicates that https is not required.</p>

答:
Make sure you are using Microsoft.AspNetCore.WebHost instead of the generic Microsoft.Extensions.Hosting.Host for the CreateDefaultBuilder as you will run into an annoying OpenSslCryptographicException when running dotnet core 3 grpc containers on docker linux instances.

Also, if you are using health checks, be sure to expose it on a different port as illustrated in the below Program.cs snippet:

```<code>public static IWebHostBuilder CreateHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureKestrel(options => {
            //grpc port for http2 connections
            options.ListenAnyIP(xxxx, listenOptions => {
                listenOptions.Protocols = HttpProtocols.Http2;
            });
            //add health check on a separate port instead of Http1AndHttp2 on same port
            options.ListenAnyIP(xxxx, listenOptions => {
                listenOptions.Protocols = HttpProtocols.Http1;
            });
        })
        .UseStartup<Startup>();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Make sure you are using Microsoft.AspNetCore.WebHost instead of the generic Microsoft.Extensions.Hosting.Host for the CreateDefaultBuilder as you will run into an annoying OpenSslCryptographicException when running dotnet core 3 grpc containers on docker linux instances.

Also, if you are using health checks, be sure to expose it on a different port as illustrated in the below Program.cs snippet:

public static IWebHostBuilder CreateHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureKestrel(options => {
            //grpc port for http2 connections
            options.ListenAnyIP(xxxx, listenOptions => {
                listenOptions.Protocols = HttpProtocols.Http2;
            });
            //add health check on a separate port instead of Http1AndHttp2 on same port
            options.ListenAnyIP(xxxx, listenOptions => {
                listenOptions.Protocols = HttpProtocols.Http1;
            });
        })
        .UseStartup<Startup>();


问:
How to run .exe file on startup on gcp windows instance
I am having a VM, windows instance (GCE) on google cloud platform. I want to run a program(.exe) every time at the start of the instance.

I am able to run the file by putting it in the startup folder. but I want to run it using startup script as suggested by google here: running startup scripts on a google compute engine

答:
To run .exe on GCP when Windows VM instance start/restart.

Click edit on VM instance

Expand Management, security, disks, networking, sole tenancy section

In the Metadata section, provide windows-startup-script-cmd as the metadata key.

In the Value box, provide /path/to/exe-file


问:
Passing view id on binding adapter?
I have been trying to pass the viewpager id to the binding adapter method. I get and error on this line

```<code>setUpViewPager="@{(main_viewpager)}"
</code>```

I get this error under this '}' symbol on above line

```<code>'->' or <expr> expected
</code>```

This is my xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
    <variable
        name="viewModel"
        type="com.example.project_budget_planner.main.MainViewModel" />

    <variable
        name="adapter"
        type="com.example.project_budget_planner.main.TabBarAdapter" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".main.MainActivity">

    <com.example.project_budget_planner.shared.NonSwipableViewPager
        android:id="@+id/main_viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        setAdapter="@{adapter}"
        app:layout_constraintBottom_toTopOf="@+id/main_tab_layout"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/main_tab_layout"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        setUpViewPager="@{(main_viewpager)}"
        app:layout_constraintBottom_toBottomOf="parent"/>

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

This is my binding adapter method

```<code> @BindingAdapter("setUpViewPager", "setAdapterForIcons")
    @JvmStatic fun bindViewPagerAndIcons(view: TabLayout, viewPager: ViewPager, tabBarAdapter: TabBarAdapter) {
        view.setupWithViewPager(viewPager)
        for (i in 1 until tabBarAdapter.count) {
            view.getTabAt(i)?.let { it.setIcon(tabBarAdapter.getItem(i).icon) }
        }
    }
</code>```

How do I solve this?

答:
You have to remove your parenthesis and add @id/ to main_viewpager

It will look like this
setUpViewPager="@{@id/main_viewpager}"

Title: Passing view id on binding adapter?

Body:
I have been trying to pass the viewpager id to the binding adapter method. I get and error on this line

setUpViewPager="@{(main_viewpager)}"

I get this error under this '}' symbol on above line

'->' or <expr> expected

This is my xml file

<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
    <variable
        name="viewModel"
        type="com.example.project_budget_planner.main.MainViewModel" />

    <variable
        name="adapter"
        type="com.example.project_budget_planner.main.TabBarAdapter" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".main.MainActivity">

    <com.example.project_budget_planner.shared.NonSwipableViewPager
        android:id="@+id/main_viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        setAdapter="@{adapter}"
        app:layout_constraintBottom_toTopOf="@+id/main_tab_layout"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/main_tab_layout"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        setUpViewPager="@{(main_viewpager)}"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

This is my binding adapter method

 @BindingAdapter("setUpViewPager", "setAdapterForIcons")
    @JvmStatic fun bindViewPagerAndIcons(view: TabLayout, viewPager: ViewPager, tabBarAdapter: TabBarAdapter) {
        view.setupWithViewPager(viewPager)
        for (i in 1 until tabBarAdapter.count) {
            view.getTabAt(i)?.let { it.setIcon(tabBarAdapter.getItem(i).icon) }
        }
    }

How do I solve this?


问:
SQL query with conditional join based on a table variable
I need to write a SQL query and want to check if this is the optimized approach. If not, what would be a better query for this scenario?

All the joining tables are pretty big(approx 150million records).

Below is the sample code.

```<code>DECLARE @inputIds VARCHAR(50) = NULL; -- This can have a comma-separated list of ids as well.

DECLARE @inputIdsVar TABLE (ID INT);
INSERT INTO @inputIdsVar SELECT DISTINCT CAST(value AS INT) FROM fnSplit(@inputIds, ','); -- Some custom function to split the Ids list.

SELECT * FROM TABLE1 tbl1
JOIN TABLE2 tbl2 ON tbl1.JoinIndex1 = tbl2.JoinIndex1 OR @inputVar IS NULL
JOIN TABLE2 tbl3 ON tbl2.JoinIndex2 = tbl3.JoinIndex2 OR @inputVar IS NULL
JOIN @inputIdsVar iiv ON tbl3.ID = iiv.ID OR @inputVar IS NULL
WHERE tbl1.Key = 'blah'
</code>```

Here, my expected output is as follows:-

If @inputVar is NULL, return all records from TABLE1.

If @inputVar is NOT NULL, join with 2 other tables and return only the filtered records. Join with 2 other tables is required because the passed-in variable is a comma-separated id list which is present in TABLE3.

Any help would be appreciated.

答:
Digital aaron is on the right track, because OR kills performance.  However, you are using select *, so you need to be careful about the columns.

I think the equivalent query with better performance is:

```<code>SELECT *
FROM TABLE1 tbl1 LEFT JOIN
     TABLE2 tbl2
     ON 1 = 0 LEFT JOIN  -- always false
     TABLE2 tbl3
     ON 1 = 0 LEFT JOIN
     @inputIdsVar iiv
     ON 1 = 0
WHERE tbl1.Key = 'blah'
UNION ALL
SELECT *
FROM TABLE1 tbl1 JOIN
     TABLE2 tbl2
     ON tbl1.JoinIndex1 = tbl2.JoinIndex1 AND
        @inputVar IS NOT NULL JOIN
     tbl3
     ON tbl2.JoinIndex2 = tbl3.JoinIndex2 AND
        @inputVar IS NOT NULL JOIn
     @inputIdsVar iiv
     ON tbl3.ID = iiv.ID AND @inputVar IS NOT NULL
WHERE tbl1.Key = 'blah';
</code>```

Body:
I need to write a SQL query and want to check if this is the optimized approach. If not, what would be a better query for this scenario?

All the joining tables are pretty big(approx 150million records).

Below is the sample code.

DECLARE @inputIds VARCHAR(50) = NULL; -- This can have a comma-separated list of ids as well.

DECLARE @inputIdsVar TABLE (ID INT);
INSERT INTO @inputIdsVar SELECT DISTINCT CAST(value AS INT) FROM fnSplit(@inputIds, ','); -- Some custom function to split the Ids list.

SELECT * FROM TABLE1 tbl1
JOIN TABLE2 tbl2 ON tbl1.JoinIndex1 = tbl2.JoinIndex1 OR @inputVar IS NULL
JOIN TABLE2 tbl3 ON tbl2.JoinIndex2 = tbl3.JoinIndex2 OR @inputVar IS NULL
JOIN @inputIdsVar iiv ON tbl3.ID = iiv.ID OR @inputVar IS NULL
WHERE tbl1.Key = 'blah'

Here, my expected output is as follows:-

If @inputVar is NULL, return all records from TABLE1.

If @inputVar is NOT NULL, join with 2 other tables and return only the filtered records. Join with 2 other tables is required because the passed-in variable is a comma-separated id list which is present in TABLE3.

Any help would be appreciated.

Body:
Digital aaron is on the right track, because OR kills performance.  However, you are using select *, so you need to be careful about the columns.

I think the equivalent query with better performance is:

SELECT *
FROM TABLE1 tbl1 LEFT JOIN
     TABLE2 tbl2
     ON 1 = 0 LEFT JOIN  -- always false
     TABLE2 tbl3
     ON 1 = 0 LEFT JOIN
     @inputIdsVar iiv
     ON 1 = 0
WHERE tbl1.Key = 'blah'
UNION ALL
SELECT *
FROM TABLE1 tbl1 JOIN
     TABLE2 tbl2
     ON tbl1.JoinIndex1 = tbl2.JoinIndex1 AND
        @inputVar IS NOT NULL JOIN
     tbl3
     ON tbl2.JoinIndex2 = tbl3.JoinIndex2 AND
        @inputVar IS NOT NULL JOIn
     @inputIdsVar iiv
     ON tbl3.ID = iiv.ID AND @inputVar IS NOT NULL
WHERE tbl1.Key = 'blah';


问:
pandas key error when manipulating columns with time series column name
I've encountered key error when retrieving pandas columns with datetime column name.
Could anyone give me some suggestions to solve this?
Details are below:

1.I have a data frame like this:
(sample data)

```<code>        store    2019-11 00:00:00  2019-12 00:00:00  2020-01 00:00:00
    0   a          500                 10000                20000
    1   b          500                 20000                25000
    2   c          600                 30000                30000
</code>```

my purpose is do the following calculations:

Sum-up the data for the past 24 months

Sum-up the data for year-to-end (if it's 2020 February, retrieve 2020 January and February only)

3.To make manipulation be more easily, I transformed subset columns to date

df.columns = GC_df.columns[:5].tolist() + pd.to_datetime(df.columns[5:]).to_period('M').tolist()

4.When I tried to retrieve data from a specific month, a key error occurred:
    print(GC_df.loc[:,"2016-03"])

Error Message:

```<code>    `KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2656             try:
-> 2657                 return self._engine.get_loc(key)
   2658             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: '2016-03'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-62-dd7e58799d99> in <module>
      1 #print(GC_df.head())
----> 2 print(GC_df.loc[:,"2016-03"])

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1492             except (KeyError, IndexError, AttributeError):
   1493                 pass
-> 1494             return self._getitem_tuple(key)
   1495         else:
   1496             # we by definition only have the 0th axis

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
    866     def _getitem_tuple(self, tup):
    867         try:
--> 868             return self._getitem_lowerdim(tup)
    869         except IndexingError:
    870             pass

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_lowerdim(self, tup)
    986         for i, key in enumerate(tup):
    987             if is_label_like(key) or isinstance(key, tuple):
--> 988                 section = self._getitem_axis(key, axis=i)
    989
    990                 # we have yielded a scalar ?

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1911         # fall thru to straight lookup
   1912         self._validate_key(key, axis)
-> 1913         return self._get_label(key, axis=axis)
   1914
   1915

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
    139             raise IndexingError('no slices here, handle elsewhere')
    140
--> 141         return self.obj._xs(label, axis=axis)
    142
    143     def _get_loc(self, key, axis=None):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
   3574
   3575         if axis == 1:
-> 3576             return self[key]
   3577
   3578         self._consolidate_inplace()

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2925             if self.columns.nlevels > 1:
   2926                 return self._getitem_multilevel(key)
-> 2927             indexer = self.columns.get_loc(key)
   2928             if is_integer(indexer):
   2929                 indexer = [indexer]

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2657                 return self._engine.get_loc(key)
   2658             except KeyError:
-> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2661         if indexer.ndim > 1 or indexer.size > 1:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: '2016-03'`
</code>```

答:
.to_period return Period index not string

Use:

```<code>pd.to_datetime(df.columns[5:], format = '%Y-%m %H:%M:%S').strftime('%Y-%m').tolist()
</code>```

Body:
I've encountered key error when retrieving pandas columns with datetime column name.
Could anyone give me some suggestions to solve this?
Details are below:

1.I have a data frame like this:
(sample data)

        store    2019-11 00:00:00  2019-12 00:00:00  2020-01 00:00:00
    0   a          500                 10000                20000
    1   b          500                 20000                25000
    2   c          600                 30000                30000

my purpose is do the following calculations:

Sum-up the data for the past 24 months

Sum-up the data for year-to-end (if it's 2020 February, retrieve 2020 January and February only)

3.To make manipulation be more easily, I transformed subset columns to date

df.columns = GC_df.columns[:5].tolist() + pd.to_datetime(df.columns[5:]).to_period('M').tolist()

4.When I tried to retrieve data from a specific month, a key error occurred:
    print(GC_df.loc[:,"2016-03"])

Error Message:

    `KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2656             try:
-> 2657                 return self._engine.get_loc(key)
   2658             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: '2016-03'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-62-dd7e58799d99> in <module>
      1 #print(GC_df.head())
----> 2 print(GC_df.loc[:,"2016-03"])

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1492             except (KeyError, IndexError, AttributeError):
   1493                 pass
-> 1494             return self._getitem_tuple(key)
   1495         else:
   1496             # we by definition only have the 0th axis

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
    866     def _getitem_tuple(self, tup):
    867         try:
--> 868             return self._getitem_lowerdim(tup)
    869         except IndexingError:
    870             pass

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_lowerdim(self, tup)
    986         for i, key in enumerate(tup):
    987             if is_label_like(key) or isinstance(key, tuple):
--> 988                 section = self._getitem_axis(key, axis=i)
    989
    990                 # we have yielded a scalar ?

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1911         # fall thru to straight lookup
   1912         self._validate_key(key, axis)
-> 1913         return self._get_label(key, axis=axis)
   1914
   1915

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
    139             raise IndexingError('no slices here, handle elsewhere')
    140
--> 141         return self.obj._xs(label, axis=axis)
    142
    143     def _get_loc(self, key, axis=None):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
   3574
   3575         if axis == 1:
-> 3576             return self[key]
   3577
   3578         self._consolidate_inplace()

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2925             if self.columns.nlevels > 1:
   2926                 return self._getitem_multilevel(key)
-> 2927             indexer = self.columns.get_loc(key)
   2928             if is_integer(indexer):
   2929                 indexer = [indexer]

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2657                 return self._engine.get_loc(key)
   2658             except KeyError:
-> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2661         if indexer.ndim > 1 or indexer.size > 1:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: '2016-03'`

Body:
.to_period return Period index not string

Use:

pd.to_datetime(df.columns[5:], format = '%Y-%m %H:%M:%S').strftime('%Y-%m').tolist()


问:
which is a better approach for fibonacci series generation
The two general approaches for Fibonacci series generation are:

The traditional approach, i.e., running through a for loop inside a function.

Recursion

I came across another solution

```<code>#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}
</code>```

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?

答:
The solution you found is decent for when you need to store the state (for example, when you calculate a Fibonacci number, do something based on it, and then calculate another), but using this from two places in your code will likely give funny results.  This is because the static variables will always be the same, no matter from where you call it.  I would instead suggest:

```<code>class FiboNumbers {
  public:
    FiboNumbers() :
        x_(1), y_() {}

    int getNext() {
        x_ += y_;
        y_ = x_ - y_;
        return x_;
    }

  private:
    int x_, y_;
};
</code>```

This offers the same keeping-of-state, but allows you to create multiple instances of the class, therefore allowing you to have different parts of the code that calculate their own Fibonacci series.

Minor note:  the code I posted will produce the same series as the example you posted, but it will produce the real Fibonacci sequence, which starts with 0 1 1 2...

ContentLicense: CC BY-SA 3.0

Body:
The two general approaches for Fibonacci series generation are:

The traditional approach, i.e., running through a for loop inside a function.

Recursion

I came across another solution

#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?

Body:
The solution you found is decent for when you need to store the state (for example, when you calculate a Fibonacci number, do something based on it, and then calculate another), but using this from two places in your code will likely give funny results.  This is because the static variables will always be the same, no matter from where you call it.  I would instead suggest:

class FiboNumbers {
  public:
    FiboNumbers() :
        x_(1), y_() {}

    int getNext() {
        x_ += y_;
        y_ = x_ - y_;
        return x_;
    }

  private:
    int x_, y_;
};

This offers the same keeping-of-state, but allows you to create multiple instances of the class, therefore allowing you to have different parts of the code that calculate their own Fibonacci series.

Minor note:  the code I posted will produce the same series as the example you posted, but it will produce the real Fibonacci sequence, which starts with 0 1 1 2...


问:
django processes interfering with each other
I think my problem might have something to do with the multi-threaded-ness of Django, but let me know what your thoughts are.

I have a Django web project which will eventually be accessed by multiple users. Through the interface the users will be able to kick off calculations using a module called spiceypy. This is a module which allows you to compute relative position and velocity of planetary objects, spacecraft, etc.

Spiceypy requires loading a 'kernel set' (aka 'kernel library') before performing the computations. The kernel set includes information about a spacecraft trajectory, among other things.

In my project, different users might choose to use different kernel sets. I have a Django Form which allows you to select the kernel set, then perform the calculations.

The calculations are done inside my Class Based View's post() method.

So, the post method looks something like this.

def post(self, request, *args, **kwargs):
    form = self.get_form()

    if form.is_valid():
        data = form.cleaned_data

        spiceypy.furnsh(data['kernel_set']) # THIS LOADS THE KERNEL SET SELECTED BY USER
        spiceypy.<computations>   # THIS PERFORMS VARIOUS SPICEYPY COMPUTATIONS
        spiceypy.unload()  # THIS UNLOADS THE KERNEL SET

        return self.form_valid(form)

```

I'm finding that if multiple users kick off the computations around the same time, there is interference. E.g. Say User A loads Kernel Set A, and calculations start. Then, before computations are complete, User B loads Kernel Set B, and kick off their computations. I'm finding that the computations for User A ends up using the wrong kernel set (i/e. the kernel set selected by User B.)

This is likely caused by the Django development server being multi-threaded instead of single threaded. Is that the case?

I don't really want to make it single-threaded (would that be a solution?) since some of the computations take a while, and I don't want users to have to "wait in line" for their computations.

I'd like to find a way to make the processes independent of each other. Can someone recommend the best way to do this? Do I need to use something like subprocess? Or is there a method within Django that would allow me to run independent processes?

答:
I think the issue is with the spicepy library that you are using - spicepy is mixing up calls sent from different Django threads. Looks from this issue like it doesn't support multithreading.

The way to verify this would be to disable threading in Django, and see whether that resolves the issue. How you do that depends on which wsgi server you are using in production. With uwsgi for example, you'd add this to your configuration:

```<code>[uwsgi]
processes = 4
threads = 1
</code>```

(Where you are adding multiple processes to compensate for disabling threads - so that blocking one process with an expensive operation doesn't prevent anyone else from accessing it).

The Django development server also doesn't use multithreading, so if you are not able to reproduce the issue there then it would point to this being the issue.

There may some performance impact to disabling multithreading, which you can mitigate by running multiple processes. Not ideal, but not disastrous either.

Body:
I think my problem might have something to do with the multi-threaded-ness of Django, but let me know what your thoughts are.

I have a Django web project which will eventually be accessed by multiple users. Through the interface the users will be able to kick off calculations using a module called spiceypy. This is a module which allows you to compute relative position and velocity of planetary objects, spacecraft, etc.

Spiceypy requires loading a 'kernel set' (aka 'kernel library') before performing the computations. The kernel set includes information about a spacecraft trajectory, among other things.

In my project, different users might choose to use different kernel sets. I have a Django Form which allows you to select the kernel set, then perform the calculations.

The calculations are done inside my Class Based View's post() method.

So, the post method looks something like this.

def post(self, request, *args, **kwargs):
    form = self.get_form()

    if form.is_valid():
        data = form.cleaned_data

        spiceypy.furnsh(data['kernel_set']) # THIS LOADS THE KERNEL SET SELECTED BY USER
        spiceypy.<computations>   # THIS PERFORMS VARIOUS SPICEYPY COMPUTATIONS
        spiceypy.unload()  # THIS UNLOADS THE KERNEL SET

        return self.form_valid(form)

I'm finding that if multiple users kick off the computations around the same time, there is interference. E.g. Say User A loads Kernel Set A, and calculations start. Then, before computations are complete, User B loads Kernel Set B, and kick off their computations. I'm finding that the computations for User A ends up using the wrong kernel set (i/e. the kernel set selected by User B.)

This is likely caused by the Django development server being multi-threaded instead of single threaded. Is that the case?

I don't really want to make it single-threaded (would that be a solution?) since some of the computations take a while, and I don't want users to have to "wait in line" for their computations.

I'd like to find a way to make the processes independent of each other. Can someone recommend the best way to do this? Do I need to use something like subprocess? Or is there a method within Django that would allow me to run independent processes?

Body:
I think the issue is with the spicepy library that you are using - spicepy is mixing up calls sent from different Django threads. Looks from this issue like it doesn't support multithreading.

The way to verify this would be to disable threading in Django, and see whether that resolves the issue. How you do that depends on which wsgi server you are using in production. With uwsgi for example, you'd add this to your configuration:

[uwsgi]
processes = 4
threads = 1

(Where you are adding multiple processes to compensate for disabling threads - so that blocking one process with an expensive operation doesn't prevent anyone else from accessing it).

The Django development server also doesn't use multithreading, so if you are not able to reproduce the issue there then it would point to this being the issue.

There may some performance impact to disabling multithreading, which you can mitigate by running multiple processes. Not ideal, but not disastrous either.


问:
Ignore thumbnail space if there is no thumbnail
So I have the below code that loops through my posts and displays posts in a list format. Here is the code that I'm using:

```<code><?php while (have_posts()) : the_post(); ?>
    <div class="one-sixth first"><?php the_post_thumbnail(); ?></div>
    <div class="five-sixths"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></div>
<?php endwhile; ?>
</code>```

Here is the image with the thumbnail:

Here is when no post thumbnail is available, it just leaves an empty space:

答:
If check thumbnail if have displayed otherwise display placeholder image. Hope this help you.</p>

```<code><?php
// Must be inside a loop.

if ( has_post_thumbnail() ) {
    the_post_thumbnail();
}
else {
    echo '<img src="' . get_bloginfo( 'stylesheet_directory' )
        . '/images/placeholder.jpg" />';
}
?>
</code>```

Body:
So I have the below code that loops through my posts and displays posts in a list format. Here is the code that I'm using:

<?php while (have_posts()) : the_post(); ?>

<?php the_post_thumbnail(); ?>

<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>

<?php endwhile; ?>

Here is the image with the thumbnail:

Here is when no post thumbnail is available, it just leaves an empty space:

Body:
If check thumbnail if have displayed otherwise display placeholder image. Hope this help you.

<?php
// Must be inside a loop.

if ( has_post_thumbnail() ) {
    the_post_thumbnail();
}
else {
    echo '<img src="' . get_bloginfo( 'stylesheet_directory' )
        . '/images/placeholder.jpg" />';
}
?>


问:
Eclipse & Intellij DE - Unable to connect to mysql database
I followed the instructions of downloading the connector driver (version 8.0.19) of MYSQL database (5.1) and getting connected to eclipse IDE(13 version), but shows the error message as

```<code>java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/employee
at java.sql.DriverManager.getConnection(DriverManager.java:700)
at java.sql.DriverManager.getConnection(DriverManager.java:258)
at jdbcdemo.Driver.main(Driver.java:14
</code>```

I first downloaded the driver connector jar file and saved it in the folder.
I tired every possible options in Eclipse and Intellij IDE, but failed to connect.
Do I need to set up anything such as environment variables in advanced system settings under control panel home?

Please could you help me with this connection?

答:
In case you are using Java language to access database, then make sure you use the following statement before opening the connection:
 Class.forName("com.mysql.jdbc.Driver");

Try if it works.

Body:
I followed the instructions of downloading the connector driver (version 8.0.19) of MYSQL database (5.1) and getting connected to eclipse IDE(13 version), but shows the error message as

java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/employee
at java.sql.DriverManager.getConnection(DriverManager.java:700)
at java.sql.DriverManager.getConnection(DriverManager.java:258)
at jdbcdemo.Driver.main(Driver.java:14

I first downloaded the driver connector jar file and saved it in the folder.
I tired every possible options in Eclipse and Intellij IDE, but failed to connect.
Do I need to set up anything such as environment variables in advanced system settings under control panel home?

Please could you help me with this connection?


问:
React Native adb reverse ENOENT
I am trying to get React-Native to work with Android V4.2.2 (Genymotion) but I am unable to test the app on the Emulator. When I ran react-native run-android, I get this error Could not run adb reverse: spawnSync

Here is a log

```<code>JS server already running.
Running ~/Library/Android/sdk/platform-tools/adb reverse tcp:8081 tcp:8081
Could not run adb reverse: spawnSync ~/Library/Android/sdk/platform-tools/adb ENOENT
Building and installing the app on the device (cd android && ./gradlew installDebug...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> The SDK directory '~/Library/Android/sdk' does not exist.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 3.785 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html
</code>```

NOTE: In the log it saids SDK directory does not exist, I have double check that I do have the SDK installed in that directory.

I found my android emulator when executing adb devices

```<code>List of devices attached
192.168.56.101:5555 device
</code>```

I have tried the following steps from Stack Overflow post, but still no luck
https://stackoverflow.com/a/38536290/4540216

答:
Starting with macOS Catalina, your Mac uses zsh as the default login shell and interactive shell. You can make zsh the default in earlier versions of macOS as well.
More details on zsh from Apple

So on your Mac:

1 - Open your .zshrc file:

```<code>open ~/.zshrc
</code>```

2 - if .zshrc file doesn't exist, you need to create one & open again(Step 1)

```<code>touch ~/.zshrc
</code>```

3 - Add this to your .zshrc file(Add JAVA_HOME to use Android Studio Embedded JDK)

UPDATE: The new Android Studio Electric Eel is using jbr, not jre.

[New code] From Android Studio Electric Eel

```<code>export JAVA_HOME=/Applications/Android Studio.app/Contents/jbr/Contents/Home
export ANDROID_HOME=/Users/<your_computer_name_here>/Library/Android/sdk
export PATH=$ANDROID_HOME/emulator:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/tools/bin:$PATH
</code>```

[Old code] Before Android Studio Electric Eel

```<code>export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/Contents/Home
export ANDROID_HOME=/Users/<your_computer_name_here>/Library/Android/sdk
export PATH=$ANDROID_HOME/emulator:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/tools/bin:$PATH
</code>```

4 - Save and close

5 - Compile your changes

```<code>source ~/.zshrc
</code>```

& make sure to restart your terminal.

Title: React Native adb reverse ENOENT

Body:
I am trying to get React-Native to work with Android V4.2.2 (Genymotion) but I am unable to test the app on the Emulator. When I ran react-native run-android, I get this error Could not run adb reverse: spawnSync

Here is a log

JS server already running.
Running ~/Library/Android/sdk/platform-tools/adb reverse tcp:8081 tcp:8081
Could not run adb reverse: spawnSync ~/Library/Android/sdk/platform-tools/adb ENOENT
Building and installing the app on the device (cd android && ./gradlew installDebug...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> The SDK directory '~/Library/Android/sdk' does not exist.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 3.785 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

NOTE: In the log it saids SDK directory does not exist, I have double check that I do have the SDK installed in that directory.

I found my android emulator when executing adb devices

List of devices attached
192.168.56.101:5555 device

I have tried the following steps from Stack Overflow post, but still no luck
https://stackoverflow.com/a/38536290/4540216

Body:
Starting with macOS Catalina, your Mac uses zsh as the default login shell and interactive shell. You can make zsh the default in earlier versions of macOS as well.
More details on zsh from Apple

So on your Mac:

1 - Open your .zshrc file:

open ~/.zshrc

2 - if .zshrc file doesn't exist, you need to create one & open again(Step 1)

touch ~/.zshrc

3 - Add this to your .zshrc file(Add JAVA_HOME to use Android Studio Embedded JDK)

UPDATE: The new Android Studio Electric Eel is using jbr, not jre.

[New code] From Android Studio Electric Eel

export JAVA_HOME=/Applications/Android Studio.app/Contents/jbr/Contents/Home
export ANDROID_HOME=/Users/<your_computer_name_here>/Library/Android/sdk
export PATH=$ANDROID_HOME/emulator:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/tools/bin:$PATH

[Old code] Before Android Studio Electric Eel

export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/Contents/Home
export ANDROID_HOME=/Users/<your_computer_name_here>/Library/Android/sdk
export PATH=$ANDROID_HOME/emulator:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/tools/bin:$PATH

4 - Save and close

5 - Compile your changes

source ~/.zshrc

& make sure to restart your terminal.


问:
Is there a built-in Python function or module that will sum digits multiplied by their integer weight?
What I need to do is take a 10-digit ISBN number and check if it's valid, according to this rule:

According to the 2001 edition of the International ISBN Agency's official user manual,[47] the ISBN-10 check digit (which is the last digit of the 10-digit ISBN) must range from 0 to 10 (the symbol 'X' is used for 10), and must be such that the sum of the ten digits, each multiplied by its (integer) weight, descending from 10 to 1, is a multiple of 11.

In other words, if the number is 0-306-40615-2, I need to calculate:

(0 * 10) + (3 * 9) + (0 * 8) + (6 * 7) + (4 * 6) + (0 * 5) + (6 * 4) + (1 * 3) + (5 * 2) + (2 * 1) mod 11

While suggestions or hints on how to write such a function are welcome, my main question is simply whether Python already has a way of doing this, perhaps in the math module.

This is my attempt, but the for loops don't work because the inner one keeps starting over. Plus it just seems messy!

```<code>    checksum = 0
    for digit in isbn:
        for weight in range(10, 0, -1):
            if digit == 'X':
                checksum += 10 * weight
                break
            checksum += int(digit) * weight
            break
    return checksum % 11```
```

答:
No, that is way too specific to be something in a standard library. It is fairly simple to write though:

```<code>def check_isbn(isbn):
    isbn_digits = (
        10 if ch == 'X' else int(ch)
        for ch in isbn
        if ch.isdigit() or ch == 'X')

    checksum = sum(
        (10 - index) * digit
        for index, digit
        in enumerate(isbn_digits)
    ) % 11

    return checksum % 11 == 0
</code>```

I like the comprehension way; but the imperative way should also work, you just have some logic errors. In particular, you don't want to iterate all weights for each digit. Each character has exactly one weight if it's a digit, or none if it is not. So an imperative rewrite would be:

```<code>def check_isbn(isbn):
    checksum = 0
    weight = 10
    for ch in isbn:
        if ch == 'X':
            digit = 10
        elif ch.isdigit():
            digit = int(ch)
        else:
            continue
        checksum += digit * weight
        weight -= 1

    return checksum % 11 == 0
</code>```

EDIT: various bugs

Body:
What I need to do is take a 10-digit ISBN number and check if it's valid, according to this rule:

According to the 2001 edition of the International ISBN Agency's official user manual,[47] the ISBN-10 check digit (which is the last digit of the 10-digit ISBN) must range from 0 to 10 (the symbol 'X' is used for 10), and must be such that the sum of the ten digits, each multiplied by its (integer) weight, descending from 10 to 1, is a multiple of 11.

In other words, if the number is 0-306-40615-2, I need to calculate:

(0 * 10) + (3 * 9) + (0 * 8) + (6 * 7) + (4 * 6) + (0 * 5) + (6 * 4) + (1 * 3) + (5 * 2) + (2 * 1) mod 11

While suggestions or hints on how to write such a function are welcome, my main question is simply whether Python already has a way of doing this, perhaps in the math module.

This is my attempt, but the for loops don't work because the inner one keeps starting over. Plus it just seems messy!

    checksum = 0
    for digit in isbn:
        for weight in range(10, 0, -1):
            if digit == 'X':
                checksum += 10 * weight
                break
            checksum += int(digit) * weight
            break
    return checksum % 11```

Body:
No, that is way too specific to be something in a standard library. It is fairly simple to write though:

def check_isbn(isbn):
    isbn_digits = (
        10 if ch == 'X' else int(ch)
        for ch in isbn
        if ch.isdigit() or ch == 'X')

    checksum = sum(
        (10 - index) * digit
        for index, digit
        in enumerate(isbn_digits)
    ) % 11

    return checksum % 11 == 0

I like the comprehension way; but the imperative way should also work, you just have some logic errors. In particular, you don't want to iterate all weights for each digit. Each character has exactly one weight if it's a digit, or none if it is not. So an imperative rewrite would be:

def check_isbn(isbn):
    checksum = 0
    weight = 10
    for ch in isbn:
        if ch == 'X':
            digit = 10
        elif ch.isdigit():
            digit = int(ch)
        else:
            continue
        checksum += digit * weight
        weight -= 1

    return checksum % 11 == 0

EDIT: various bugs


问:
Is there a way to use a non-login user to run Rundeck jobs?
So my goal is to create a Rundeck job that runs on a schedule and isn't run as my personal user, or any "regular" user, but rather a bot user. Ideally this bot user wouldn't have login access and restricted permissions for security reasons, but would be able to run certain jobs. I've tried searching, but the only information I'm finding is about how to create a "regular" user in Rundeck. Even if I go down that route of creating the bot user as a "regular" user, to use it, you need to pass in either the login credentials or an API token. An API token would be fine, if it could be generated and pulled in on the fly. However, that is not the case, the API has an expiration itself. If there is something I'm missing, please let me know. I'd love to get this working.

Rundeck Version: Rundeck 3.2.1-20200113

Rundeck Cli Version: 1.1.7

答:
The way I've implemented bots is as a user who is a member of a 'bot' user group, with ACLs that lock down that group as required. Any passwords required for the scheduled job are loaded into the key storage of the bot user.

With this approach you still need someone who knows the bot credentials to login as them and set passwords/SSH keys, but that's a one-off. Is that what you're trying to avoid?

The one annoying thing I've found is that a scheduled job always seems to run as the last user to edit the job - so I grant edit access to bot users and make sure to set/reset the schedule after any edit by a normal user. Hoping to address this through https://github.com/rundeck/rundeck/issues/1603, you might want to give it a .


问:
How do I open a script file in RStudio using an R command?
I have a simple script file called test.R. It's saved in the working directory. When I go to File > Open > test.R, it opens the file in the editor (without executing the code, which is what I want).

How do I do this by typing a command in the console window? To be clear, I just want to open (not execute) the file.

答: It appears that if you are using RStudio then another option is to use rstudioapi::navigateToFile("test.R")


问:
"Permission Denied" trying to run Python on Windows 10
Seems as though an update on Windows 10 overnight broke Python. Just trying to run python --version returned a "Permission Denied" error.  None of the three updates; KB4507453, KB4506991, or KB4509096 look like they'd be the culprit but the timing of the issue is suspicious. Rather than messing with rolling back, I'm hoping there's a simpler fix that I'm missing.

The permissions on python are "-rwxr-xr-x" and I haven't changed anything besides letting the Windows update reboot machine after installing last night's patches.

According to the System Information, I'm running 10.0.18362

Should also note that this is happening whether I (try) to execute Python from git-bash using "run as administrator" or not, and if I try using PowerShell, it just opens the Windows store as if the app isn't installed so I'm thinking it can't see the contents of my /c/Users/david/AppData/Local/Microsoft/WindowsApps/ folder for some reason.

I've also tried to reinstall Python 3.7.4, but that didn't help either. Is there something else I should be looking at?

答:
save you time :
use wsl  and vscode remote extension to properly work with python even with win10
and dont't forget virtualenv!
useful https://linuxize.com/post/how-to-install-visual-studio-code-on-ubuntu-18-04/


问:
Scroll to top of ScrollView
Is there a way to scroll to the top of a ScrollView in response to a button press?

I can force a re-render of the whole page but that seems very inefficient.

答:
Simple example->

```<code> constructor(props) {
    super(props);
    this.state = {

    }

  this.listView1 = null
  this.listView2 = null
  this.listViewY = 0.0
  this.scrollInterval = null
}

async componentDidMount() {

  this.autoScroll()

}

autoScroll() {
    setTimeout(() => {
      this.scrollInterval = setInterval(() => {
        if (this.listView !== null) {
          this.listView.scrollTo({ y: this.listViewY + 1 })
          this.listViewY += 1
        }
      }, 50);
    }, 1000);
  }

_stopScoller = () => {
if (this.scrollInterval !== null) {
  clearInterval(this.scrollInterval)
}
</code>```

}

```<code>render() {
return(
  <ScrollView style={styles.fullListScrollView} ref={ref => this.listView = ref} onScrollBeginDrag={this._stopScoller}>
 </ScrollView>
)
}
</code>```

Title: Scroll to top of ScrollView

Body:
Simple example->

 constructor(props) {
    super(props);
    this.state = {

    }

  this.listView1 = null
  this.listView2 = null
  this.listViewY = 0.0
  this.scrollInterval = null
}

async componentDidMount() {

  this.autoScroll()

}

autoScroll() {
    setTimeout(() => {
      this.scrollInterval = setInterval(() => {
        if (this.listView !== null) {
          this.listView.scrollTo({ y: this.listViewY + 1 })
          this.listViewY += 1
        }
      }, 50);
    }, 1000);
  }

_stopScoller = () => {
if (this.scrollInterval !== null) {
  clearInterval(this.scrollInterval)
}

}

render() {
return(
  <ScrollView style={styles.fullListScrollView} ref={ref => this.listView = ref} onScrollBeginDrag={this._stopScoller}>
 </ScrollView>
)
}


问:
List Azure Security Center Policies status using Azure AZ Powershell Cmdlets
Please let me know the command available to list Security Policies associated with particular subscription.

What I am trying to list is below:

In the navigation panel, choose Security policy to access Policy Management portal.

On the Policy Management page, click on the name of the subscription that you want to examine to access the selected subscription configuration settings.

On the Security Policy page, in the Compute and Apps category, check the Vulnerabilities in security configuration on your machines should be remediated setting status. If the configuration setting is set to Disabled, the OS vulnerability monitoring is not enabled for the Microsoft Azure virtual machines (VMs) available in the current subscription.

Want to list above policy status using powershell command.

Using Get-AzPolicyAssignment

Not retrieving the same policies as compared to whatever listed on portal.

Thanks.

答:
If I don't misunderstand, you want to check the status of the Vulnerabilities in security configuration on your machines should be remediated parameter in the policy [Preview]: Enable Monitoring in Azure Security Center.

Currently, we can get it with

```<code>$policy = Get-AzPolicyAssignment | Where-Object {$_.Properties.displayName -eq '[Preview]: Enable Monitoring in Azure Security Center'}
</code>```

but seems we could not get the parameter' status in this command by default

If your ultimate goal is to check the status, if it is Disabled, then you will set it with AuditIfNotExists.

If so, you could use the commands below to set it directly, no matter if it is Disabled or AuditIfNotExists, it will both be set to AuditIfNotExists(If you want to set it to Disabled, just change the command with systemConfigurationsMonitoringEffect = "Disabled").

```<code>$policy = Get-AzPolicyAssignment | Where-Object {$_.Properties.displayName -eq '[Preview]: Enable Monitoring in Azure Security Center'}
Set-AzPolicyAssignment -Id $policy.ResourceId -PolicyParameterObject @{systemConfigurationsMonitoringEffect = "AuditIfNotExists"}
</code>```

Then we check the $policy.Properties.parameters, it appears. Check in the portal, you will find it also works.

Update:

If you just use Get-AzPolicyAssignment without any parameter, the Initiative policy will not return.

Navigate to the Policy -> Assignments in the portal, find the Initiative type policy you want, click it, copy the Assignment ID.

Then use the command below.

```<code>Get-AzPolicyAssignment -Id <Assignment ID>
</code>```

If you want to get all the policies under the Initiative policy, try the command below, the  $policies is that you want.

```<code>$initiative = Get-AzPolicyAssignment -Id <Assignment ID>
$policies = (Get-AzPolicySetDefinition -Id $initiative.Properties.policyDefinitionId).Properties.policyDefinitions
</code>```

Check them in the portal:

Body:
If I don't misunderstand, you want to check the status of the Vulnerabilities in security configuration on your machines should be remediated parameter in the policy [Preview]: Enable Monitoring in Azure Security Center.

Currently, we can get it with

$policy = Get-AzPolicyAssignment | Where-Object {$_.Properties.displayName -eq '[Preview]: Enable Monitoring in Azure Security Center'}

but seems we could not get the parameter' status in this command by default

If your ultimate goal is to check the status, if it is Disabled, then you will set it with AuditIfNotExists.

If so, you could use the commands below to set it directly, no matter if it is Disabled or AuditIfNotExists, it will both be set to AuditIfNotExists(If you want to set it to Disabled, just change the command with systemConfigurationsMonitoringEffect = "Disabled").

$policy = Get-AzPolicyAssignment | Where-Object {$_.Properties.displayName -eq '[Preview]: Enable Monitoring in Azure Security Center'}
Set-AzPolicyAssignment -Id $policy.ResourceId -PolicyParameterObject @{systemConfigurationsMonitoringEffect = "AuditIfNotExists"}

Then we check the $policy.Properties.parameters, it appears. Check in the portal, you will find it also works.

Update:

If you just use Get-AzPolicyAssignment without any parameter, the Initiative policy will not return.

Navigate to the Policy -> Assignments in the portal, find the Initiative type policy you want, click it, copy the Assignment ID.

Then use the command below.

Get-AzPolicyAssignment -Id <Assignment ID>

If you want to get all the policies under the Initiative policy, try the command below, the  $policies is that you want.

$initiative = Get-AzPolicyAssignment -Id <Assignment ID>
$policies = (Get-AzPolicySetDefinition -Id $initiative.Properties.policyDefinitionId).Properties.policyDefinitions

Check them in the portal:


问:
initState in Flutter return null on SQLite database?
I create a button to test the database. it returns a set of data. While i did in initState function, what i get is null.</p>

```<code>@override
void initState() {
  db.queryData('username').then((val) {
    _userAuthData = val;
  });
  super.initState();
  print(_userAuthData);
}```

** both async/await and future.then() works the same in button on press function.
</code>```

答:
you can execute async function on init method by using future</p>

```<code>@override
void initState() {
  super.initState();
  Future.delayed(Duration.zero,()async{
   final _userAuthData=await db.queryData('username');
   print(_userAuthData);
 });
});
</code>```

Body:
I create a button to test the database. it returns a set of data. While i did in initState function, what i get is null.

@override
void initState() {
  db.queryData('username').then((val) {
    _userAuthData = val;
  });
  super.initState();
  print(_userAuthData);
}```

** both async/await and future.then() works the same in button on press function.

Body:
you can execute async function on init method by using future

@override
void initState() {
  super.initState();
  Future.delayed(Duration.zero,()async{
   final _userAuthData=await db.queryData('username');
   print(_userAuthData);
 });
});


问:
How does the Databricks Delta Lake `mergeSchema` option handle differing data types?
What does the Databricks Delta Lake mergeSchema option do if a pre-existing column is appended with a different data type?

For example, given a Delta Lake table with schema foo INT, bar INT, what would happen when trying to write-append new data with schema foo INT, bar DOUBLE when specifying the option mergeSchema = true?

答: The write fails. (as of Delta Lake 0.5.0 on Databricks 6.3)</p>


问:
firestore simple way to get one field in a document by function
I am trying to return one field in a document. Is there a simple way to do this?  This seems overkill:

```<code>let p = await (await this.afs.doc(`users/${uid}`).get().toPromise()).data()!.photoURL;

let p = await this.afs.doc(`users/${uid}`).ref.get().then((m) => { return m.data()!.photoURL; });
</code>```

I was thinking something like this, but obviously it doesn't work:

```<code>let p = await this.afs.doc(`users/${uid}`).get('photoURL);
</code>```

Any ideas?

答:
This should be all that's needed:

```<code>let p = await (firebase.firestore().doc(`users/${uid}`).get()).get('photoURL');
</code>```

The await (firebase.firestore().doc(users/${uid}).get()) awaits for the document to be loaded, and then then get('photoURL') gets the field.

Body:
I am trying to return one field in a document. Is there a simple way to do this?  This seems overkill:

let p = await (await this.afs.doc(`users/${uid}`).get().toPromise()).data()!.photoURL;

let p = await this.afs.doc(`users/${uid}`).ref.get().then((m) => { return m.data()!.photoURL; });

I was thinking something like this, but obviously it doesn't work:

let p = await this.afs.doc(`users/${uid}`).get('photoURL);

Any ideas?

Body:
This should be all that's needed:

let p = await (firebase.firestore().doc(`users/${uid}`).get()).get('photoURL');

The await (firebase.firestore().doc(users/${uid}).get()) awaits for the document to be loaded, and then then get('photoURL') gets the field.


问:
APK and Expo Client android app are different
I am building a cross-platform app with expo SDK36. I am testing with the expo client on android and ios.

It seems that the built expo apk downloaded on expo is different than the android version tested from my android expo client.

I can't scroll on my views with the app APK, hopefully, I saw it.

Is this an expo bug and is this expected? I was expecting to have the same app on both expo and real app.

I must rebuild until I find the bug, the APK and expo pipelines are quite busy, how can I troubleshoot efficiently without ejecting?

答:
Maybe your expo project on the cloud didn't update. Try

expo publish


问:
Reactjs + Redux Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
When implementing the authentication with react + redux, when I try to register the user in the actions of the redux using async / await, I get this error in the catch, here is the code of the actions:

```<code>import axios from 'axios';
import { setAlert } from './alert';
import { REGISTRO_CORRECTO, REGISTRO_FALLIDO } from './types';

// Registro de Usuario
export const registro = ({
  usuario,
  interfac,
  password,
  descripcion
}) => async dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const body = JSON.stringify({ usuario, password, interfac, descripcion });

  try {
    // Conex to backend
    const res = await axios.post('http://localhost:5000/api/usuarios', body, config);

    dispatch({
      type: REGISTRO_CORRECTO,
      payload: res.data
    });
  } catch (err) {
    const errors = err.response.data.errors;

    if (errors) {
      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({
      type: REGISTRO_FALLIDO
    });
  }
};
</code>```

Running the submit gives me this error:

```<code>  26 |      payload: res.data
  27 |    });
  28 |  } catch (err) {
> 29 |    const errors = err.response.data.errors;
     | ^  30 |
  31 |    if (errors) {
  32 |      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
</code>```

best regards

答:
You get the error because the field errors could not exist in object data. In this case, it should make some condition to check format of returning Object before it refer to get data from it.

So, you could refer checking below for you program.

```<code>  } catch (err) {
    if(err.response.data && err.response.data.message){
       // todo
    }else if(err.response.data && err.response.data.errors){
       // todo
    }
</code>```

Body:
When implementing the authentication with react + redux, when I try to register the user in the actions of the redux using async / await, I get this error in the catch, here is the code of the actions:

import axios from 'axios';
import { setAlert } from './alert';
import { REGISTRO_CORRECTO, REGISTRO_FALLIDO } from './types';

// Registro de Usuario
export const registro = ({
  usuario,
  interfac,
  password,
  descripcion
}) => async dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const body = JSON.stringify({ usuario, password, interfac, descripcion });

  try {
    // Conex to backend
    const res = await axios.post('http://localhost:5000/api/usuarios', body, config);

    dispatch({
      type: REGISTRO_CORRECTO,
      payload: res.data
    });
  } catch (err) {
    const errors = err.response.data.errors;

    if (errors) {
      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({
      type: REGISTRO_FALLIDO
    });
  }
};

Running the submit gives me this error:

  26 |      payload: res.data
  27 |    });
  28 |  } catch (err) {
> 29 |    const errors = err.response.data.errors;
     | ^  30 |
  31 |    if (errors) {
  32 |      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));

best regards

Body:
You get the error because the field errors could not exist in object data. In this case, it should make some condition to check format of returning Object before it refer to get data from it.

So, you could refer checking below for you program.

  } catch (err) {
    if(err.response.data && err.response.data.message){
       // todo
    }else if(err.response.data && err.response.data.errors){
       // todo
    }


问:
Make hyperlink clickable when accessibility is on
I'm making application accessible using accessibility with Talk/Voice Over.

How to make links clickable with accessibility?

Using following methods for making Hyperlink clickable in TextView.

```<code>/**
 * This method creates the link and associates the ClickableSpan to it.
 * Once the ClickableSpan is clicked, it will call the
 * ClickableSpanListener.performAction
 */
public static void makeLinkClickable(
  final ClickableSpanListener clickableSpanListener,
  final SpannableStringBuilder strBuilder,
  final URLSpan span) {
final int start = strBuilder.getSpanStart(span);
final int end = strBuilder.getSpanEnd(span);
final int flags = strBuilder.getSpanFlags(span);

//get the String that is used as the link
final char[] characters = new char[end - start];
strBuilder.getChars(start, end, characters, 0);

  final ClickableSpan clickable = new ClickableSpan() {
    public void onClick(final View view) {
       clickableSpanListener.performAction(span.getURL(), new String(characters));
     }
   };
  strBuilder.setSpan(clickable, start, end, flags);
  strBuilder.removeSpan(span);
}

/**
 * This method takes in a String that contains at least one link defined by HTML <a></a> tags.
 * A link will be created in the String and added to the TextView.
 * The link will become clickable and the action (onClick) is defined by the
 * ClickableSpanListener.
 */
  public static void setTextViewHTML(
  final ClickableSpanListener clickableSpanListener,
  final TextView text,
  final String html) {
final CharSequence sequence = Html.fromHtml(html);
final SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
final URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
  for (final URLSpan span : urls) {
    makeLinkClickable(clickableSpanListener, strBuilder, span);
    }
   text.setText(strBuilder);
   text.setMovementMethod(LinkMovementMethod.getInstance());
 }

/**
 * This is the interface that should be implemented by classes to define the action
 * that will occur when a clickablespan is clicked
 */
 public interface ClickableSpanListener {
    void performAction(String url, String linkText);
 }

 setTextViewHTML(
    this,
    txtTermsPrivacy,
    getString(R.string.terms_condition_privacy_policy)
);
</code>```

Tried:

As mentioned in the google support for accessibility Google Support - Accessibility, I have tried using Linkify but it does not seem to work though.

答:
```<code>val clickSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                // Handel your click
                Util.launchUrl(activity, getString(R.string.permissions_request_agreement_url))
            }
        }

        val agreementLabel = getString(R.string.permissions_request_agreement_label)
        val textHeadingSpannable: SpannableString = SpannableString(agreementLabel)

        //From "I agree to the Optus Privacy Policy", make "Optus Privacy Policy" clickable
        textHeadingSpannable.setSpan(clickSpan, 15, agreementLabel.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        privacyLink.text = textHeadingSpannable

        privacyLink.movementMethod = LinkMovementMethod.getInstance()

        listener = ValidatedListener {
            btnPrimary.isEnabled = isValidated()
        }
</code>```

On the other hand:

```<code><string name="permissions_request_agreement_label">I agree to the Optus Privacy Policy</string>

<string name="permissions_request_agreement_url">https://www.optus.com.au/about/legal/privacy/telco-services</string>
</code>```

Reference and also Java sample

Body:
I'm making application accessible using accessibility with Talk/Voice Over.

How to make links clickable with accessibility?

Using following methods for making Hyperlink clickable in TextView.

/**
 * This method creates the link and associates the ClickableSpan to it.
 * Once the ClickableSpan is clicked, it will call the
 * ClickableSpanListener.performAction
 */
public static void makeLinkClickable(
  final ClickableSpanListener clickableSpanListener,
  final SpannableStringBuilder strBuilder,
  final URLSpan span) {
final int start = strBuilder.getSpanStart(span);
final int end = strBuilder.getSpanEnd(span);
final int flags = strBuilder.getSpanFlags(span);

//get the String that is used as the link
final char[] characters = new char[end - start];
strBuilder.getChars(start, end, characters, 0);

  final ClickableSpan clickable = new ClickableSpan() {
    public void onClick(final View view) {
       clickableSpanListener.performAction(span.getURL(), new String(characters));
     }
   };
  strBuilder.setSpan(clickable, start, end, flags);
  strBuilder.removeSpan(span);
}

/**
 * This method takes in a String that contains at least one link defined by HTML  tags.
 * A link will be created in the String and added to the TextView.
 * The link will become clickable and the action (onClick) is defined by the
 * ClickableSpanListener.
 */
  public static void setTextViewHTML(
  final ClickableSpanListener clickableSpanListener,
  final TextView text,
  final String html) {
final CharSequence sequence = Html.fromHtml(html);
final SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
final URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
  for (final URLSpan span : urls) {
    makeLinkClickable(clickableSpanListener, strBuilder, span);
    }
   text.setText(strBuilder);
   text.setMovementMethod(LinkMovementMethod.getInstance());
 }

/**
 * This is the interface that should be implemented by classes to define the action
 * that will occur when a clickablespan is clicked
 */
 public interface ClickableSpanListener {
    void performAction(String url, String linkText);
 }

 setTextViewHTML(
    this,
    txtTermsPrivacy,
    getString(R.string.terms_condition_privacy_policy)
);

Tried:

As mentioned in the google support for accessibility Google Support - Accessibility, I have tried using Linkify but it does not seem to work though.

Body:
val clickSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                // Handel your click
                Util.launchUrl(activity, getString(R.string.permissions_request_agreement_url))
            }
        }

        val agreementLabel = getString(R.string.permissions_request_agreement_label)
        val textHeadingSpannable: SpannableString = SpannableString(agreementLabel)

        //From "I agree to the Optus Privacy Policy", make "Optus Privacy Policy" clickable
        textHeadingSpannable.setSpan(clickSpan, 15, agreementLabel.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        privacyLink.text = textHeadingSpannable

        privacyLink.movementMethod = LinkMovementMethod.getInstance()

        listener = ValidatedListener {
            btnPrimary.isEnabled = isValidated()
        }

On the other hand:

<string name="permissions_request_agreement_label">I agree to the Optus Privacy Policy</string>

<string name="permissions_request_agreement_url">https://www.optus.com.au/about/legal/privacy/telco-services</string>

Reference and also Java sample


问:
How to post an Ajax onClick through a looping input form (Dinamically) from MySql query result
I would like to be suggested on how to solve an Ajax post through a looping input form (Dynamically) from MySql query result.

```<code><?php
// Query Result
foreach ($sql->result() as $row) {
echo '
<div class="media mt-4">
  <div class="media-body text-muted text-small">
    <input class="d-none" value="'.$row->cY.'" name="post_X" id="post_X">
    <input class="d-none" value="'.$row->cZ.'" name="post_Y" id="post_Y">
    <div class="input-group">
      <input style="background:#fafafa" type="text" name="post_Z" id="post_Z" placeholder="Join conversation here..." class="form-control">
      <div class="input-group-append">
        <button type="button" onclick="addPost()" class="btn btn-outline-secondary"><i class="fa fa-send"></i></button>
      </div>
    </div>
  </div>
</div>';
}
?>
</code>```

Ajax script

```<code><script>
function addPost() {
    if(!$("#post_Z").val()) {
        // An Alert!
    } else {
        var post_X = $("#post_X").val();
        var post_Y = $("#post_Y").val();
        var post_Z = $("#post_Z").val();
        $.post("reply.php", {
            uid: post_X,
            cid: post_Y,
            txt: post_Z
        }, function (data, status) {
            // An Alert!
        });
    };
}
</script>
</code>```

Thanks alot

答:
give an id for each iteration, and add the id in the addPost event so that the post only retrieves data according to the id that is defined

change the code to be like this

```<code><?php
// Query Result

$uniq = 1;
foreach ($sql->result() as $row) {
echo '
<div class="media mt-4">
  <div class="media-body text-muted text-small">
    <input class="d-none" value="'.$row->cY.'" name="post_X_'.$uniq.'" id="post_X_'.$uniq.'">
    <input class="d-none" value="'.$row->cZ.'" name="post_Y_'.$uniq.'" id="post_Y_'.$uniq.'">
    <div class="input-group">
      <input style="background:#fafafa" type="text" name="post_Z_'.$uniq.'" id="post_Z_'.$uniq.'" placeholder="Join conversation here..." class="form-control">
      <div class="input-group-append">
        <button type="button" onclick="addPost('.$uniq.')" class="btn btn-outline-secondary"><i class="fa fa-send"></i></button>
      </div>
    </div>
  </div>
</div>';
$uniq++;
}
?>
</code>```

and the ajax

```<code><script>
function addPost(id) {
    if(!$("#post_Z_"+id).val()) {
        // An Alert!
    } else {
        var post_X = $("#post_X_"+id).val();
        var post_Y = $("#post_Y_"+id).val();
        var post_Z = $("#post_Z_"+id).val();
        $.post("reply.php", {
            uid: post_X,
            cid: post_Y,
            txt: post_Z
        }, function (data, status) {
            // An Alert!
        });
    };
}
</script>
</code>```

may these help

Body:
I would like to be suggested on how to solve an Ajax post through a looping input form (Dynamically) from MySql query result.

<?php
// Query Result
foreach ($sql->result() as $row) {
echo '

    <input class="d-none" value="'.$row->cY.'" name="post_X" id="post_X">
    <input class="d-none" value="'.$row->cZ.'" name="post_Y" id="post_Y">

      <input style="background:#fafafa" type="text" name="post_Z" id="post_Z" placeholder="Join conversation here..." class="form-control">

        <button type="button" onclick="addPost()" class="btn btn-outline-secondary"></button>

';
}
?>

Ajax script

Thanks alot

Body:
give an id for each iteration, and add the id in the addPost event so that the post only retrieves data according to the id that is defined

change the code to be like this

<?php
// Query Result

$uniq = 1;
foreach ($sql->result() as $row) {
echo '
<div class="media mt-4">
  <div class="media-body text-muted text-small">
    <input class="d-none" value="'.$row->cY.'" name="post_X_'.$uniq.'" id="post_X_'.$uniq.'">
    <input class="d-none" value="'.$row->cZ.'" name="post_Y_'.$uniq.'" id="post_Y_'.$uniq.'">
    <div class="input-group">
      <input style="background:#fafafa" type="text" name="post_Z_'.$uniq.'" id="post_Z_'.$uniq.'" placeholder="Join conversation here..." class="form-control">
      <div class="input-group-append">
        <button type="button" onclick="addPost('.$uniq.')" class="btn btn-outline-secondary"><i class="fa fa-send"></i></button>
      </div>
    </div>
  </div>
</div>';
$uniq++;
}
?>

and the ajax

<script>
function addPost(id) {
    if(!$("#post_Z_"+id).val()) {
        // An Alert!
    } else {
        var post_X = $("#post_X_"+id).val();
        var post_Y = $("#post_Y_"+id).val();
        var post_Z = $("#post_Z_"+id).val();
        $.post("reply.php", {
            uid: post_X,
            cid: post_Y,
            txt: post_Z
        }, function (data, status) {
            // An Alert!
        });
    };
}
</script>

may these help


问:
/storage/emulated/0/Notes/ (No such file or directory)?
I tried this link:

How to create text file and insert data to that file on Android

But, it says "No such file or directory". Can anybody help me please? Thanks in advance!

答:
---- Updated answer----

I think you can't create a directory inside the internal storage of the device. Except you've a root access for the app. You can only create the directory inside your app private folder within the following path String path = getFilesDir().

you can use like this below -

```<code>File mydir = context.getDir("mydirectory", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myAwesomeFile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.
</code>```

getDir(StringName, int mode) method to create or access directories in internal storage.

/storage/emulated/0/Notes/ will always return No such file or directory except device is rooted and dir.mkDirs() will always return false for this path.

Hope this will help you.

Body:
---- Updated answer----

I think you can't create a directory inside the internal storage of the device. Except you've a root access for the app. You can only create the directory inside your app private folder within the following path String path = getFilesDir().

you can use like this below -

File mydir = context.getDir("mydirectory", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myAwesomeFile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.

getDir(StringName, int mode) method to create or access directories in internal storage.

/storage/emulated/0/Notes/ will always return No such file or directory except device is rooted and dir.mkDirs() will always return false for this path.

Hope this will help you.


问:
Do tests that run on Firebase test lab run parallel and not sequential
I'm running UI instrumented tests using Espresso on Firebase test lab.
Dose the tests execution is in parallel or sequential?</p>

答:
If you implement cucumber on your espresso test, you can set in cucumber option in your instrumentation file for ordering test case sequentially.

```<code>@CucumberOptions(
    features = "features",
    tags = "@first-feature,@second-feature,@third-feature,@last-feature",
    glue = "package name")
</code>```

like @Doug Stevenson answer, you can use Flank for parallel.

Body:
If you implement cucumber on your espresso test, you can set in cucumber option in your instrumentation file for ordering test case sequentially.

@CucumberOptions(
    features = "features",
    tags = "@first-feature,@second-feature,@third-feature,@last-feature",
    glue = "package name")

like @Doug Stevenson answer, you can use Flank for parallel.


问:
Rounding off a positive number to the next nearest multiple of 5
I need to round of a number (the input is guaranteed to be an integer & is positive) to the next multiple of 5.

I tried this:

```<code>int round = ((grades[j] + 2)/5) * 5;
</code>```

However, this rounds off the number to the nearest multiple of 5.

Eg: 67 is rounded off to 65, not 70.

答:
This is my solution using cmath::abs

```<code>int rounded = n + abs((n % denom) - denom);
</code>```

You can change the denom with any other denomination you want

Body:
I need to round of a number (the input is guaranteed to be an integer & is positive) to the next multiple of 5.

I tried this:

int round = ((grades[j] + 2)/5) * 5;

However, this rounds off the number to the nearest multiple of 5.

Eg: 67 is rounded off to 65, not 70.

Body:
This is my solution using cmath::abs

int rounded = n + abs((n % denom) - denom);

You can change the denom with any other denomination you want


问:
Grant full access to JupyterLab after updating to macOS Catalina
After updating my MacBook to "Catalina", Anaconda was sent to the folder "Relocated Items" on Desktop. I followed the official guide Restore Anaconda and everything seemed to work fine.

Although, I realised that I cannot navigate to directories such as Documents and Desktop via Jupyterlab, while I can via Jupyter. I have already given full disk access to Anaconda from Settings and I can access any non-default directory, such as OneDrive or IntelliJ.

There is no response every time I try to click on default directories and I do not get any particular error.

If there is not any obvious solution, what am I going to lose if I reinstall Anaconda?

答:
I gave up anaconda and turned to homebrew to install jupyter.
I had this issue as well, running Catalina on my old MBP 2012.
I tried re-install anaconda (2019-10 version) but it failed to update jupyter lab and notebook.
I had many problems with anaconda's update function these days, and I had enough of it.
So, I tried installing jupyter with homebrew and it worked perfectly.
When I access Desktop or Documents, a system dialog asking for permission would pop up.
Grant it permission and everything worked fine.
You might wanna try other ways to install jupyter lab as well, such as pip and docker.</p>


问:
awk convert number to date format to select line bigger than specific mmyy
INPUT:

```<code>test,1120,1
test,1219,2
</code>```

Expected Output

```<code>test,1120,1
</code>```

Goal: trying to print line where $2 which is mmyy format is bigger than 1020 as example.

I've tried with the following:

awk -F, '{ if ( $2 > 1020 ) { print $0 }}' file that's will not give the expected output because it's still number etc.. 1219 is bigger than 1020.

答:
Assuming the 2nd field always contains 4 digits, how about:

```<code>awk -F, 'substr($2, 3, 2) substr($2, 1, 2) > 2010' input
</code>```

Please note that I have interpreted the word bigger as later, meaning 0921 is bigger than 1020. If my assumption is incorrect, please let me know.

Body:
INPUT:

test,1120,1
test,1219,2

Expected Output

test,1120,1

Goal: trying to print line where $2 which is mmyy format is bigger than 1020 as example.

I've tried with the following:

awk -F, '{ if ( $2 > 1020 ) { print $0 }}' file that's will not give the expected output because it's still number etc.. 1219 is bigger than 1020.

Body:
Assuming the 2nd field always contains 4 digits, how about:

awk -F, 'substr($2, 3, 2) substr($2, 1, 2) > 2010' input

Please note that I have interpreted the word bigger as later, meaning 0921 is bigger than 1020. If my assumption is incorrect, please let me know.


问:
How to check if all items in a list are of the same type?
I'm trying to have a function validate that all items in a list are of the same type. See "check for integer type" section. However, that section of my function returns False no matter the input at the moment.

What would be the best way to have that section check for the type of input (float, string, integer), return False if they are not all the same, and return True otherwise? And have the function ask for another input if they are not of all the same type.

```<code>def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()
</code>```

Edit:

I've now tried combining a couple of the answers into a section of the code:

```<code>def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()
</code>```

Any pointers on how I could modify this to do what I'm trying to get to? It should return 'c' if I input (a,b,c) and give me the error message if I enter (1,2,a). When I print the value for typecheck, it returns a value of "True" even if I enter something like 1,2,a.

答:
You can check the input value type first by update this section:

```<code>Value1 = input_int ('Enter the first value here:  \n')
Value2 = input_int ('Enter the second value here:  \n')
Value3 = input_int ('Enter the third value here:  \n')
</code>```

use this custom input function:

```<code>def input_int(input_msg: str) -> int:
    try:
        val = input(input_msg)
        return int(val)
    except Exception:
        return input_int(input_msg)
</code>```

Body:
I'm trying to have a function validate that all items in a list are of the same type. See "check for integer type" section. However, that section of my function returns False no matter the input at the moment.

What would be the best way to have that section check for the type of input (float, string, integer), return False if they are not all the same, and return True otherwise? And have the function ask for another input if they are not of all the same type.

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

Edit:

I've now tried combining a couple of the answers into a section of the code:

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

Any pointers on how I could modify this to do what I'm trying to get to? It should return 'c' if I input (a,b,c) and give me the error message if I enter (1,2,a). When I print the value for typecheck, it returns a value of "True" even if I enter something like 1,2,a.

Body:
You can check the input value type first by update this section:

Value1 = input_int ('Enter the first value here:  \n')
Value2 = input_int ('Enter the second value here:  \n')
Value3 = input_int ('Enter the third value here:  \n')

use this custom input function:

def input_int(input_msg: str) -> int:
    try:
        val = input(input_msg)
        return int(val)
    except Exception:
        return input_int(input_msg)


问:
Print a character till end of line
I am wondering if its possible to print any character till end of line. I know its a silly to ask.
but if its possible then this will help me to improve me the cosmetic look of my script as people use different size of putty windows.

currently I am printing "-" till EOL based on size of my window. but the size differ and "-" comes to next line on other terminals.
like below:

echo "-------------------------------------------------------------------------------------------"

I need this to be done in shell script. Is there any way to find the screen width and print accordingly ?

答:
It works in zsh without the eval...

```<code>eval printf '=%.0s' {1..$(tput cols)}
</code>```

bash eval replaces $(tput cols) with the terminal column count

bash substitutes {1..count} with space separated list of integers.

bash printf evaluates format =%.0s upon each of its arguments.

printf echoes the equal sign because it is not format translated

printf % beings format secification

printf %. beings width specification

printf %.0 specifies zero characters wide

printf %.0s specifies ends the width specification and says that the argument is to be treated like a string and also ends the format sequence.

Title: Print a character till end of line

Body:
It works in zsh without the eval...

eval printf '=%.0s' {1..$(tput cols)}

bash eval replaces $(tput cols) with the terminal column count

bash substitutes {1..count} with space separated list of integers.

bash printf evaluates format =%.0s upon each of its arguments.

printf echoes the equal sign because it is not format translated

printf % beings format secification

printf %. beings width specification

printf %.0 specifies zero characters wide

printf %.0s specifies ends the width specification and says that the argument is to be treated like a string and also ends the format sequence.