问:
Android studio launch app crash on one ui 4.1.1
I'm trying to install an app from android studio to an oppo find x3 pro with one ui 4.1.1 but app crashes. I tried the installation on multiple device but it works. Only on devices with one ui 4.1.1 I found this problem.

```<code>E/OplusCustomizeRestrictionManager: sInstance is null, start a new sInstance
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.skadut, PID: 7846
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.skadut/com.example.skadut.MainActivity}: android.view.InflateException: Binary XML file line #36 in com.example.skadut:layout/activity_main: Binary XML file line #36 in com.example.skadut:layout/activity_main: Error inflating class android.widget.ListView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3780)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3942)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:109)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2345)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:233)
        at android.os.Looper.loop(Looper.java:344)
        at android.app.ActivityThread.main(ActivityThread.java:8212)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)
     Caused by: android.view.InflateException: Binary XML file line #36 in com.example.skadut:layout/activity_main: Binary XML file line #36 in com.example.skadut:layout/activity_main: Error inflating class android.widget.ListView
     Caused by: android.view.InflateException: Binary XML file line #36 in com.example.skadut:layout/activity_main: Error inflating class android.widget.ListView
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:863)
        at android.view.LayoutInflater.createView(LayoutInflater.java:785)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:939)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:959)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1013)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:970)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1132)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1093)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:692)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:542)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:488)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:706)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
        at com.example.skadut.MainActivity.onCreate(MainActivity.java:35)
        at android.app.Activity.performCreate(Activity.java:8129)
        at android.app.Activity.performCreate(Activity.java:8109)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1344)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3749)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3942)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:109)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2345)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:233)
        at android.os.Looper.loop(Looper.java:344)
        at android.app.ActivityThread.main(ActivityThread.java:8212)
        at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)
     Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 13: TypedValue{t=0x2/d=0x7f030040 a=-1}
        at android.content.res.TypedArray.getDrawableForDensity(TypedArray.java:998)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:982)
        at android.view.View.<init>(View.java:5552)
        at android.view.ViewGroup.<init>(ViewGroup.java:706)
        at android.widget.AdapterView.<init>(AdapterView.java:264)
        at android.widget.AbsListView.<init>(AbsListView.java:901)
        at android.widget.ListView.<init>(ListView.java:231)
        at android.widget.ListView.<init>(ListView.java:227)
        at android.widget.ListView.<init>(ListView.java:223)
            ... 33 more
I/Process: Sending signal. PID: 7846 SIG: 9
Disconnected from the target VM, address: 'localhost:62879', transport: 'socket'
</code>```

I would like understand why on tab s7 this works but on tab s8 doesn't work and also on find x3 pro. Someone has some similar experience?

Body:
I'm trying to install an app from android studio to an oppo find x3 pro with one ui 4.1.1 but app crashes. I tried the installation on multiple device but it works. Only on devices with one ui 4.1.1 I found this problem.

E/OplusCustomizeRestrictionManager: sInstance is null, start a new sInstance
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.skadut, PID: 7846
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.skadut/com.example.skadut.MainActivity}: android.view.InflateException: Binary XML file line #36 in com.example.skadut:layout/activity_main: Binary XML file line #36 in com.example.skadut:layout/activity_main: Error inflating class android.widget.ListView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3780)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3942)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:109)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2345)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:233)
        at android.os.Looper.loop(Looper.java:344)
        at android.app.ActivityThread.main(ActivityThread.java:8212)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)
     Caused by: android.view.InflateException: Binary XML file line #36 in com.example.skadut:layout/activity_main: Binary XML file line #36 in com.example.skadut:layout/activity_main: Error inflating class android.widget.ListView
     Caused by: android.view.InflateException: Binary XML file line #36 in com.example.skadut:layout/activity_main: Error inflating class android.widget.ListView
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:863)
        at android.view.LayoutInflater.createView(LayoutInflater.java:785)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:939)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:959)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1013)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:970)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1132)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1093)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:692)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:542)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:488)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:706)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
        at com.example.skadut.MainActivity.onCreate(MainActivity.java:35)
        at android.app.Activity.performCreate(Activity.java:8129)
        at android.app.Activity.performCreate(Activity.java:8109)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1344)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3749)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3942)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:109)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2345)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:233)
        at android.os.Looper.loop(Looper.java:344)
        at android.app.ActivityThread.main(ActivityThread.java:8212)
        at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)
     Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 13: TypedValue{t=0x2/d=0x7f030040 a=-1}
        at android.content.res.TypedArray.getDrawableForDensity(TypedArray.java:998)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:982)
        at android.view.View.<init>(View.java:5552)
        at android.view.ViewGroup.<init>(ViewGroup.java:706)
        at android.widget.AdapterView.<init>(AdapterView.java:264)
        at android.widget.AbsListView.<init>(AbsListView.java:901)
        at android.widget.ListView.<init>(ListView.java:231)
        at android.widget.ListView.<init>(ListView.java:227)
        at android.widget.ListView.<init>(ListView.java:223)
            ... 33 more
I/Process: Sending signal. PID: 7846 SIG: 9
Disconnected from the target VM, address: 'localhost:62879', transport: 'socket'

I would like understand why on tab s7 this works but on tab s8 doesn't work and also on find x3 pro. Someone has some similar experience?


来源: stackexchange

问:
GPU available but not used. Set `accelerator` and `devices` using `Trainer(accelerator='gpu', devices=1)`
```<code>model_nbeats = NBEATSModel(
    input_chunk_length=30,
    output_chunk_length=7,
    generic_architecture=True,
    num_stacks=10,
    num_blocks=1,
    num_layers=4,
    layer_widths=512,
    n_epochs=100,
    nr_epochs_val_period=1,
    batch_size=800,
    model_name="nbeats_run",
)

model_nbeats.fit(train, val_series=val, verbose=True)
</code>```

Hi,
While running the code above, "PossibleUserWarning: GPU available but not used. Set accelerator and devices using Trainer(accelerator='gpu', devices=1)." is appearing in the output cell of Google Colab. How can I fix it?

I have tried darts.nbeats to fit training data in 100 epochs. I select GPU to accelerate the training process. However, the training was not accelerated and the afferomentioned possiblewarning was appeared.

ContentLicense: CC BY-SA 4.0

Body:
model_nbeats = NBEATSModel(
    input_chunk_length=30,
    output_chunk_length=7,
    generic_architecture=True,
    num_stacks=10,
    num_blocks=1,
    num_layers=4,
    layer_widths=512,
    n_epochs=100,
    nr_epochs_val_period=1,
    batch_size=800,
    model_name="nbeats_run",
)

model_nbeats.fit(train, val_series=val, verbose=True)

Hi,
While running the code above, "PossibleUserWarning: GPU available but not used. Set accelerator and devices using Trainer(accelerator='gpu', devices=1)." is appearing in the output cell of Google Colab. How can I fix it?

I have tried darts.nbeats to fit training data in 100 epochs. I select GPU to accelerate the training process. However, the training was not accelerated and the afferomentioned possiblewarning was appeared.


问:
Adding strings into sqlite query with Python
I am trying to figure out how can I get this to work and this is a side project I decided to make apart from the studies on my own. What I need is to be able to search items in a category column by providing a string like "Mobile" and then I return a list of items in a particular category, but that is working for me for another functions.

I hope this is sufficient.

def search_ims_category_items(category):
    with DatabaseConnection('inventory.db') as connection:
        cursor = connection.cursor()
        cursor.execute(f'SELECT * FROM inventory WHERE category = ?', (category,))
```
<p>This is where the return should happen</p>
<pre class="lang-py prettyprint-override"><code>def search_category_items():
    category = input("Enter the category name you want to find: ")
    items = database.search_ims_category_items(category)
    for item in items:
        print(
            f"{item['product_name']} | {item['product_number']} | {item['category']} | ${item['price']} | ${item['discount']} | {item['quantity']}")
</code>```

Much appreciated!

What I do is I execute the query where category needs to be like input category name from other function. Tried with %s, and other methods, but I cannot get this to work. And, I have checked Python docs before coming here, but can't quite figure this out.

Body:
I am trying to figure out how can I get this to work and this is a side project I decided to make apart from the studies on my own. What I need is to be able to search items in a category column by providing a string like "Mobile" and then I return a list of items in a particular category, but that is working for me for another functions.

I hope this is sufficient.

def search_ims_category_items(category):
    with DatabaseConnection('inventory.db') as connection:
        cursor = connection.cursor()
        cursor.execute(f'SELECT * FROM inventory WHERE category = ?', (category,))

This is where the return should happen

def search_category_items():
    category = input("Enter the category name you want to find: ")
    items = database.search_ims_category_items(category)
    for item in items:
        print(
            f"{item['product_name']} | {item['product_number']} | {item['category']} | ${item['price']} | ${item['discount']} | {item['quantity']}")

Much appreciated!

What I do is I execute the query where category needs to be like input category name from other function. Tried with %s, and other methods, but I cannot get this to work. And, I have checked Python docs before coming here, but can't quite figure this out.


问:
Reporting API v4 Google analytics - Ecommerce Missing Transactions
I'm currently having an issue when comparing my custom table with Google Analytics Ecommerce UI view where a significant amount of transaction data are missing in the table.

Below is the portion of the code snippet I used to request the transaction report.

```<code>"dimensions": [
          {"name": "ga:dateHour"},
          {"name": "ga:channelGrouping"},
          {"name": "ga:source"},
          {"name": "ga:medium"},
          {"name": "ga:campaign"},
          {"name": "ga:transactionId"}
      ],
      "metrics": [
            {"expression": "ga:sessions"},
            {"expression": "ga:transactionRevenue"},
            {"expression": "ga:transactionTax"},
            {"expression": "ga:transactionShipping"}
        ]
</code>```

`

```<code></code>```

Body:
I'm currently having an issue when comparing my custom table with Google Analytics Ecommerce UI view where a significant amount of transaction data are missing in the table.

Below is the portion of the code snippet I used to request the transaction report.

"dimensions": [
          {"name": "ga:dateHour"},
          {"name": "ga:channelGrouping"},
          {"name": "ga:source"},
          {"name": "ga:medium"},
          {"name": "ga:campaign"},
          {"name": "ga:transactionId"}
      ],
      "metrics": [
            {"expression": "ga:sessions"},
            {"expression": "ga:transactionRevenue"},
            {"expression": "ga:transactionTax"},
            {"expression": "ga:transactionShipping"}
        ]

`


问:
Array type using 'T[]' is forbidden for non-simple types. Use 'Array<T>' instead
```<code>props<{
    lighting: {
      target: Light
      value: LightE | undefined
    }[]
  }>(),
</code>```

Getting error at lighting: {, I am not sure how to correct this error

Body:
props<{
    lighting: {
      target: Light
      value: LightE | undefined
    }[]
  }>(),

Getting error at lighting: {, I am not sure how to correct this error


问:
R: Searching a column in a dataframe for matches to a reference list in another dataframe
I am trying to categorize genes with multiple GO descriptors into bins based on what those GO descriptors are related to. I have dataframe A which contains the raw data associated with a list of geneIDs (>500,000) and their associated GO descriptors and dataframe B which classifies these GO descriptors into larger groups.

Example of dataframe A
dfA

Example of dataframe B
dfB

Ideally, the final output would reference the entire list and generate a new column in dataframe A classifying the GeneIDs into the GO_Category's associated with its specific GO_IDs -- bonus points if it removes duplicate hits on the GO_Categorys.

Looking something like this...

Example of Ideal Solution

However, I know that the ideal solution might be difficult to obtain, and I already have dataframe B listed out based on the unique GO_Categories so a solution like this might be easier to obtain.

Example of Acceptable Solution

So far I have struggled with getting any command to search for partial strings using a list from another dataframe with the goal of returning all matches.

I have had partial success with the acceptable solution approach and using:

dfA <- dfA %>%
mutate(GO_Cat_1 = c('No', 'Yes')[1+str_detect(dfA$GO_IDs, as.character(dfB$GO_IDs))])

The solution seems okay, however, it does return an error along the lines of
problem with mutate() column GO_Cat_1.
i GO_Cat_1 = ...[].
i longer object length is not a multiple of shorter object length

I have also tried to look into applying grepl/grep - but struggled to feed it a list of terms to look for partial string matches in dfA.

Any assistance is greatly appreciated!


问:
Is there a way to set global eslint options in codesendbox static template?
Is there a way to configure eslint globally in Codesandbox static project. I tried to add .eslintrc.json file to the root of the project, but I still get the eslint's no-undef warnings I try to supress:

```<code>{
  "globals": {
    "cornerstone": true
  },
  "rules": {
    "no-undef": "off"
  }
}
</code>```

Body:
Is there a way to configure eslint globally in Codesandbox static project. I tried to add .eslintrc.json file to the root of the project, but I still get the eslint's no-undef warnings I try to supress:

{
  "globals": {
    "cornerstone": true
  },
  "rules": {
    "no-undef": "off"
  }
}


问:
Create Windows DNS PTR records for existing A records using Powershell
Anyone know an easy way to force PTR record generation for existing A records that currently do not have them?

I have a couple of scenarios where this would be beneficial to me.

Members of my team have created records over time using the DNS MMC snap-in, but forgot to check the "Update PTR record" option, and

I have many reverse lookup zones for individual subnets that I'm trying to collapse into an also existing parent reverse zone... e.g. 1.192.10.in-addr.arpa -> 192.10.in-addr.arpa.

My thought process was to simply run through existing A records and run a pre-built DNS cmdlet with some sort of -updatePTR type flag, similar as can be done in the MMC snapin, but I guess nothing like that exists in Powershell.

The Add-DNSServerResourceRecord cmdlet has the -CreatePTR parameter, which sounds ideal, but that seems to only be supported when creating new records.

Is my only option to manually create the PTR records using Add-DNSServerResourceRecortPTR, or something similar, or perhaps even deleting the A record entirely and recreating with -CreatePTR?

I can do the former by following something similar to this:
https://gist.github.com/msoler8785/498332c622f93ace02b5d05e47845001, but I have hundreds of these zones I'm trying to cleanup from years of acquisitions, etc., which would make the code a lot more complex by requiring me to determine the correct Reverse zones based on the IP addresses, whereas that code uses a static zone.

Anyway, hoping I'm just missing something, or someone else has already figured this out.

::EDIT::

I found this which uses WMI/Powershell to do the first method, but I imagine this could easily converted to the native cmdlets.

https://serverfault.com/questions/163612/create-ptr-records-from-existing-a-records-windows-dns

Again, hoping someone has already figured this out.


问:
Problem with Robotium.clickOnMenuItem()
When I make this call to Robotium:

```<code>solo.clickOnMenuItem("Sync");
</code>```

sometimes I get the famous error trace:

09-19 22:27:23.647: ERROR/WindowManager(20662): android.view.WindowLeaked: Activity test.com.activities.ListActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@461d4660 that was originally added here
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.view.ViewRoot.(ViewRoot.java:253)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.app.Dialog.show(Dialog.java:241)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at test.com.activities.ListActivity$Sincronizacao.onPreExecute(ListActivity.java:272)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.os.AsyncTask.execute(AsyncTask.java:391)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at test.com.activities.ListActivity.onOptionsItemSelected(ListActivity.java:224)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.app.Activity.onOptionsItemSelected(Activity.java:2313)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.app.Activity.onMenuItemSelected(Activity.java:2201)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:740)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:538)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:142)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.view.View$PerformClick.run(View.java:8818)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.os.Handler.handleCallback(Handler.java:587)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.os.Handler.dispatchMessage(Handler.java:92)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.os.Looper.loop(Looper.java:143)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.app.ActivityThread.main(ActivityThread.java:4701)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at java.lang.reflect.Method.invokeNative(Native Method)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at java.lang.reflect.Method.invoke(Method.java:521)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at dalvik.system.NativeStart.main(Native Method)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662): FATAL EXCEPTION: main
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662): java.lang.IllegalArgumentException: View not attached to window manager
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:355)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:200)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.view.Window$LocalWindowManager.removeView(Window.java:432)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.Dialog.dismissDialog(Dialog.java:278)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.Dialog.access$000(Dialog.java:71)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.Dialog$1.run(Dialog.java:111)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.Dialog.dismiss(Dialog.java:268)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.Dialog.cancel(Dialog.java:951)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at test.com.activities.ListActivity$Sincronizacao.onPostExecute(ListActivity.java:331)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.os.AsyncTask.finish(AsyncTask.java:417)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.os.Handler.dispatchMessage(Handler.java:99)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.os.Looper.loop(Looper.java:143)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.ActivityThread.main(ActivityThread.java:4701)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at java.lang.reflect.Method.invokeNative(Native Method)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at java.lang.reflect.Method.invoke(Method.java:521)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at dalvik.system.NativeStart.main(Native Method)

But if I make the call natively like this (the menuitem is the third one):

```<code>mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_RIGHT);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_RIGHT);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);
</code>```

I don't get any errors no matter how many times I run the test. Why I'm getting that behaviour?

ContentLicense: CC BY-SA 3.0

Title: Problem with Robotium.clickOnMenuItem()

Body:
When I make this call to Robotium:

solo.clickOnMenuItem("Sync");

sometimes I get the famous error trace:

09-19 22:27:23.647: ERROR/WindowManager(20662): android.view.WindowLeaked: Activity test.com.activities.ListActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@461d4660 that was originally added here
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.view.ViewRoot.(ViewRoot.java:253)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.app.Dialog.show(Dialog.java:241)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at test.com.activities.ListActivity$Sincronizacao.onPreExecute(ListActivity.java:272)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.os.AsyncTask.execute(AsyncTask.java:391)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at test.com.activities.ListActivity.onOptionsItemSelected(ListActivity.java:224)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.app.Activity.onOptionsItemSelected(Activity.java:2313)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.app.Activity.onMenuItemSelected(Activity.java:2201)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:740)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:538)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:142)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.view.View$PerformClick.run(View.java:8818)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.os.Handler.handleCallback(Handler.java:587)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.os.Handler.dispatchMessage(Handler.java:92)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.os.Looper.loop(Looper.java:143)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at android.app.ActivityThread.main(ActivityThread.java:4701)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at java.lang.reflect.Method.invokeNative(Native Method)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at java.lang.reflect.Method.invoke(Method.java:521)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
  09-19 22:27:23.647: ERROR/WindowManager(20662):     at dalvik.system.NativeStart.main(Native Method)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662): FATAL EXCEPTION: main
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662): java.lang.IllegalArgumentException: View not attached to window manager
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:355)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:200)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.view.Window$LocalWindowManager.removeView(Window.java:432)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.Dialog.dismissDialog(Dialog.java:278)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.Dialog.access$000(Dialog.java:71)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.Dialog$1.run(Dialog.java:111)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.Dialog.dismiss(Dialog.java:268)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.Dialog.cancel(Dialog.java:951)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at test.com.activities.ListActivity$Sincronizacao.onPostExecute(ListActivity.java:331)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.os.AsyncTask.finish(AsyncTask.java:417)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.os.Handler.dispatchMessage(Handler.java:99)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.os.Looper.loop(Looper.java:143)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at android.app.ActivityThread.main(ActivityThread.java:4701)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at java.lang.reflect.Method.invokeNative(Native Method)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at java.lang.reflect.Method.invoke(Method.java:521)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
  09-19 22:27:24.209: ERROR/AndroidRuntime(20662):     at dalvik.system.NativeStart.main(Native Method)

But if I make the call natively like this (the menuitem is the third one):

mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_RIGHT);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_RIGHT);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);

I don't get any errors no matter how many times I run the test. Why I'm getting that behaviour?


问:
How to authenticate Google account via Python
This following snippet authenticates user account on Colab:

```<code>from google.colab import auth

auth.authenticate_user()
</code>```

However, I am writing a script to run this on a desktop so I can't use this feature. How can I authenticate a Google account in Python?

This is my full code:

```<code>import gspread, json
import pandas as pd
from google.auth import default
from google.colab import auth

auth.authenticate_user()

creds, _ = default()
gc = gspread.authorize(creds)

SCOPE = ["https://docs.google.com/forms/d/aBCdefGHJ/edit"]
SECRETS_FILE = "client_secret.json"
SPREADSHEET = "GForm doc"

json_key = json.load(open(SECRETS_FILE))

gc = gspread.authorize(creds)

workbook = gc.open(SPREADSHEET)

sheet = workbook.sheet1

data = pd.DataFrame(sheet.get_all_records())

print(data['Email Address'])
print(list(data['Links']))
</code>```

As you can see, I am using the Colab library so it makes this code useless as a standalone Python script. I want to authenticate without logging in with my email and password since I don't want to expose those. Is there a way to authenticate Google credentials?

Body:
This following snippet authenticates user account on Colab:

from google.colab import auth

auth.authenticate_user()

However, I am writing a script to run this on a desktop so I can't use this feature. How can I authenticate a Google account in Python?

This is my full code:

import gspread, json
import pandas as pd
from google.auth import default
from google.colab import auth

auth.authenticate_user()

creds, _ = default()
gc = gspread.authorize(creds)

SCOPE = ["https://docs.google.com/forms/d/aBCdefGHJ/edit"]
SECRETS_FILE = "client_secret.json"
SPREADSHEET = "GForm doc"

json_key = json.load(open(SECRETS_FILE))

gc = gspread.authorize(creds)

workbook = gc.open(SPREADSHEET)

sheet = workbook.sheet1

data = pd.DataFrame(sheet.get_all_records())

print(data['Email Address'])
print(list(data['Links']))

As you can see, I am using the Colab library so it makes this code useless as a standalone Python script. I want to authenticate without logging in with my email and password since I don't want to expose those. Is there a way to authenticate Google credentials?


问:
axios is giving Typescript error in React Native project
I am getting a typescript error in my React Native project. I am not sure how to address this. Im new to Typescript. I have a function that is called throughout the app. I have to append headers to my api call. To keep code clean I add the headers in this function.

The error I get is with the axios function await axios(options) :

other files in the project will call like this

```<code>useEffect(() => {
    const options = {
      method: 'get',
      url: `${network}/getMaps`,
    };

    Api.apiRequest(options)
      .then(response => {
        setData(response.data.items);
      })
      .catch(function (e) {
        console.log('another error happened fetching cameras:' + e?.message);
      })

  }, []);
</code>```

Below is where I have the issue
apiRequest.ts

```<code>// these interface types are in different files and I import them in. They are just here for now to simplify things

interface ApiRequest {
    method: 'get' | 'post';
    url: string;
  }

  interface Options extends ApiRequest {
    headers: {
      'UUID': string | number[] | undefined;
      'ClientName': 'ELMC';
      'DeviceName': string;
      'ClientIcon': string;
    };
  }

const apiRequest = async (options:Options) =>{
    const GUID = await getHttpRquestUUID();
    const DeviceName = await getDeviceName();

     // append headers to the request options
     options.headers = {
        'UUID': GUID,
        'ClientName': 'MyApp',
        'DeviceName': getDeviceName,
        'ClientIcon': 'http:url.com'
      };

    try {
        const results = await axios(options);
    } catch (error) {
        console.log(error)
    }
}

const Api = {
    apiRequest,
  };

export {Api};
</code>```

error
No overload matches this call.
Overload 1 of 2, '(config: AxiosRequestConfig): Promise<AxiosResponse<any, any>>', gave the following error.
Argument of type 'APIOptions' is not assignable to parameter of type 'AxiosRequestConfig'.
Types of property 'headers' are incompatible.
Type '{ '-UUID': string | number[] | undefined; '-ClientName': "MyApp"; '-DeviceName': string; '-ClientIcon': string; }' is not assignable to type 'Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>'.
Property ''-UUID'' is incompatible with index signature.
Type 'string | number[] | undefined' is not assignable to type 'AxiosHeaderValue | undefined'.

Body:
I am getting a typescript error in my React Native project. I am not sure how to address this. Im new to Typescript. I have a function that is called throughout the app. I have to append headers to my api call. To keep code clean I add the headers in this function.

The error I get is with the axios function await axios(options) :

other files in the project will call like this

useEffect(() => {
    const options = {
      method: 'get',
      url: `${network}/getMaps`,
    };

    Api.apiRequest(options)
      .then(response => {
        setData(response.data.items);
      })
      .catch(function (e) {
        console.log('another error happened fetching cameras:' + e?.message);
      })

  }, []);

Below is where I have the issue
apiRequest.ts

// these interface types are in different files and I import them in. They are just here for now to simplify things

interface ApiRequest {
    method: 'get' | 'post';
    url: string;
  }

  interface Options extends ApiRequest {
    headers: {
      'UUID': string | number[] | undefined;
      'ClientName': 'ELMC';
      'DeviceName': string;
      'ClientIcon': string;
    };
  }

const apiRequest = async (options:Options) =>{
    const GUID = await getHttpRquestUUID();
    const DeviceName = await getDeviceName();

     // append headers to the request options
     options.headers = {
        'UUID': GUID,
        'ClientName': 'MyApp',
        'DeviceName': getDeviceName,
        'ClientIcon': 'http:url.com'
      };

    try {
        const results = await axios(options);
    } catch (error) {
        console.log(error)
    }
}

const Api = {
    apiRequest,
  };

export {Api};

error
No overload matches this call.
Overload 1 of 2, '(config: AxiosRequestConfig): Promise<AxiosResponse<any, any>>', gave the following error.
Argument of type 'APIOptions' is not assignable to parameter of type 'AxiosRequestConfig'.
Types of property 'headers' are incompatible.
Type '{ '-UUID': string | number[] | undefined; '-ClientName': "MyApp"; '-DeviceName': string; '-ClientIcon': string; }' is not assignable to type 'Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>'.
Property ''-UUID'' is incompatible with index signature.
Type 'string | number[] | undefined' is not assignable to type 'AxiosHeaderValue | undefined'.


问:
JS High Chart Download Not Work In Android Web View Activity
I have web page which has the high charts. This charts are exportable with desktop browser. I use this web page with android web view activity. But high charts export properties did not work. I read a lot of tutorial about this problem like as below:

Stackoverflow Question Which Is About Android Web View Activity Downloading

```<code>mWebView.setDownloadListener(new DownloadListener() {

    @Override
    public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));

            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Mathematics II ");
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
                    Toast.LENGTH_LONG).show();

        }
    });
</code>```

But when i click highchart pdf export button the url came like as below:
https://export.highcharts.com

How can i download highchart as pdf or image in Android web view page. Highchart web page is work with browser but it can not work in Android web view activity page.
Thanks for your advices.

I want to be able to download a web page containing highcharts in android web view activity page.

Body:
I have web page which has the high charts. This charts are exportable with desktop browser. I use this web page with android web view activity. But high charts export properties did not work. I read a lot of tutorial about this problem like as below:

Stackoverflow Question Which Is About Android Web View Activity Downloading

mWebView.setDownloadListener(new DownloadListener() {

    @Override
    public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));

            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Mathematics II ");
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
                    Toast.LENGTH_LONG).show();

        }
    });

But when i click highchart pdf export button the url came like as below:
https://export.highcharts.com

How can i download highchart as pdf or image in Android web view page. Highchart web page is work with browser but it can not work in Android web view activity page.
Thanks for your advices.

I want to be able to download a web page containing highcharts in android web view activity page.


问:
Oracle datediff function with employee data
I have the following datediff function that is working fine for the most part. But when I pass it some employees data I seem to get an error. How can I modify the function to work in both cases?

Thanks in advance for your expertise and to all who answer. Below is my test CASE

```<code>
CREATE FUNCTION datediff (p_from timestamp, p_to timestamp)
return varchar2 is
  v_from     TIMESTAMP := LEAST(p_from, p_to);
  v_to       TIMESTAMP := GREATEST(p_from, p_to);
  l_years    PLS_INTEGER;
  l_from     TIMESTAMP;
  l_interval interval day(3) to second(6);
begin
  l_years    := TRUNC(MONTHS_BETWEEN(v_to, v_from)/12);
  l_from     := CAST(TRUNC(ADD_MONTHS(v_from, l_years * 12), 'MI') AS TIMESTAMP)
                  + NUMTODSINTERVAL( EXTRACT(SECOND FROM v_from), 'SECOND' );
  l_interval := (v_to - l_from) DAY(3) TO SECOND(6);
  return l_years || ' Years '
    || extract (day from l_interval) || ' Days '
    || extract (hour from l_interval) || ' Hours '
    || extract (minute from l_interval) || ' Minutes '
    || extract (second from l_interval) || ' Seconds';
end datediff;
/

/* works fine */

SELECT
datediff( TO_DATE('2022-04-03 10:11:13','YYYY-MM-DD HH24:MI:SS'),
TO_DATE('1981-04-01 17:48:09','YYYY-MM-DD HH24:MI:SS')) as  diff FROM DUAL

DIFF
41 Years 1 Days 16 Hours 23 Minutes 4 Seconds

CREATE TABLE departments(  department_id, department_name) AS
SELECT 1, 'IT' FROM DUAL UNION ALL
SELECT 2, 'DBA' FROM DUAL UNION ALL
SELECT 3, 'Sales' FROM DUAL UNION ALL
SELECT 4, 'Programming' FROM DUAL;

CREATE TABLE employees (employee_id, first_name, last_name, hire_date, salary,  department_id) AS
SELECT 1, 'Lisa', 'Saladino', DATE '2001-04-03', 160000, 1 FROM DUAL UNION ALL
SELECT 2, 'Sandy', 'Herring', DATE '2001-04-04', 150200, 1 FROM DUAL UNION ALL
SELECT 3, 'Beth', 'Cooper', DATE '2001-04-05', 60700, 1 FROM DUAL UNION ALL
SELECT 4, 'Carol', 'Orr', DATE '2001-04-06', 70125,1 FROM DUAL UNION ALL
SELECT 5, 'Vicky', 'Palazzo', DATE '2001-04-07', 68525,2 FROM DUAL UNION ALL
SELECT 6, 'Cheryl', 'Ford', DATE '2001-04-08', 110000,1 FROM DUAL UNION ALL
SELECT 7, 'Leslee', 'Altman', DATE '2001-04-10', 66666, 1 FROM DUAL UNION ALL
SELECT 8, 'Jill', 'Coralnick', DATE '2001-04-11', 190000, 2 FROM DUAL UNION ALL
SELECT 9, 'Faith', 'Aaron', DATE '2001-04-17', 122000,2 FROM DUAL UNION ALL
SELECT 10, 'Silvio', 'Dante', DATE '2022-10-16', 102150,4 FROM DUAL UNION ALL
SELECT 11, 'Jerry', 'Torchiano', DATE '2022-10-30', 112660,4 FROM DUAL;

/* problem with function here */
SELECT
       E.first_name ,
       E.last_name ,
       E.department_id ,
       D.department_name,
       datediff (TRUNC(SYSDATE, E.hire_date))
        FROM employees E
         JOIN departments D
          ON E.department_id = D.department_id;

ORA-00932: inconsistent datatypes: expected DATE UNIT got DATE

</code>```

Body:
I have the following datediff function that is working fine for the most part. But when I pass it some employees data I seem to get an error. How can I modify the function to work in both cases?

Thanks in advance for your expertise and to all who answer. Below is my test CASE

CREATE FUNCTION datediff (p_from timestamp, p_to timestamp)
return varchar2 is
  v_from     TIMESTAMP := LEAST(p_from, p_to);
  v_to       TIMESTAMP := GREATEST(p_from, p_to);
  l_years    PLS_INTEGER;
  l_from     TIMESTAMP;
  l_interval interval day(3) to second(6);
begin
  l_years    := TRUNC(MONTHS_BETWEEN(v_to, v_from)/12);
  l_from     := CAST(TRUNC(ADD_MONTHS(v_from, l_years * 12), 'MI') AS TIMESTAMP)
                  + NUMTODSINTERVAL( EXTRACT(SECOND FROM v_from), 'SECOND' );
  l_interval := (v_to - l_from) DAY(3) TO SECOND(6);
  return l_years || ' Years '
    || extract (day from l_interval) || ' Days '
    || extract (hour from l_interval) || ' Hours '
    || extract (minute from l_interval) || ' Minutes '
    || extract (second from l_interval) || ' Seconds';
end datediff;
/

/* works fine */

SELECT
datediff( TO_DATE('2022-04-03 10:11:13','YYYY-MM-DD HH24:MI:SS'),
TO_DATE('1981-04-01 17:48:09','YYYY-MM-DD HH24:MI:SS')) as  diff FROM DUAL

DIFF
41 Years 1 Days 16 Hours 23 Minutes 4 Seconds

CREATE TABLE departments(  department_id, department_name) AS
SELECT 1, 'IT' FROM DUAL UNION ALL
SELECT 2, 'DBA' FROM DUAL UNION ALL
SELECT 3, 'Sales' FROM DUAL UNION ALL
SELECT 4, 'Programming' FROM DUAL;

CREATE TABLE employees (employee_id, first_name, last_name, hire_date, salary,  department_id) AS
SELECT 1, 'Lisa', 'Saladino', DATE '2001-04-03', 160000, 1 FROM DUAL UNION ALL
SELECT 2, 'Sandy', 'Herring', DATE '2001-04-04', 150200, 1 FROM DUAL UNION ALL
SELECT 3, 'Beth', 'Cooper', DATE '2001-04-05', 60700, 1 FROM DUAL UNION ALL
SELECT 4, 'Carol', 'Orr', DATE '2001-04-06', 70125,1 FROM DUAL UNION ALL
SELECT 5, 'Vicky', 'Palazzo', DATE '2001-04-07', 68525,2 FROM DUAL UNION ALL
SELECT 6, 'Cheryl', 'Ford', DATE '2001-04-08', 110000,1 FROM DUAL UNION ALL
SELECT 7, 'Leslee', 'Altman', DATE '2001-04-10', 66666, 1 FROM DUAL UNION ALL
SELECT 8, 'Jill', 'Coralnick', DATE '2001-04-11', 190000, 2 FROM DUAL UNION ALL
SELECT 9, 'Faith', 'Aaron', DATE '2001-04-17', 122000,2 FROM DUAL UNION ALL
SELECT 10, 'Silvio', 'Dante', DATE '2022-10-16', 102150,4 FROM DUAL UNION ALL
SELECT 11, 'Jerry', 'Torchiano', DATE '2022-10-30', 112660,4 FROM DUAL;

/* problem with function here */
SELECT
       E.first_name ,
       E.last_name ,
       E.department_id ,
       D.department_name,
       datediff (TRUNC(SYSDATE, E.hire_date))
        FROM employees E
         JOIN departments D
          ON E.department_id = D.department_id;

ORA-00932: inconsistent datatypes: expected DATE UNIT got DATE


问:
ignore tests in crate nested in workpace
I have a crate nested in a workspace as a git subtree folder, and I don't want to run any tests on that nested crate whenever I run cargo test in the workspace.  Is there a way to tell it to ignore this particular crate?


问:
is it possible to create a delay between each page build? (Next.js ISR)
I am working on some project that I need to use ISR on, the pages critical info come from a third-party API, the problem is that this API allows only a maximum of 15 requests per second while the pages I need to be generated are hundreds and it needs hundreds of requests at build time, (by the fetching code ran inside getStaticProps()), so this obviously exceeds the limit of the APIs allowed requests per second,

How can I possibly solve that??
Is there any configuration for this matter that I don't know of or something to create a time gap between each page build?

Btw, I already tried making a delay before an API request happens using promises and timeout but that just doesn't work for some reason, would be glad if someone explained...


问:
error does not load position styles when showing cdk overlay in leaflet in a position in Angular
I'm trying to put a "contextMenu" in angular leaflet, when done in an empty div it works. Image 01
Image 01
But when it tried to place over the leaflet, it doesn't load the position or overlay styles.
Image 02
Imagen html
And when I activate the button toolpit, it just loads the overlay styles
Image 03
Imagen html load
CODE:

```<code>
const openPan = (val) => this.open(val);
this.map.addEventListener('contextmenu' , openPan);`

open($event){
  this.closePanel();
  const positionStrategy = this.overlay.position()
  .flexibleConnectedTo($event.containerPoint)
  .withPositions([
    {
      originX: 'end',
      originY: 'bottom',
      overlayX: 'end',
      overlayY: 'top',
    }
    ]);
    this.overlayRef = this.overlay.create({
      positionStrategy,
      scrollStrategy: this.overlay.scrollStrategies.close(),
      disposeOnNavigation: true
    },
    );
    this.overlayRef.attach(new TemplatePortal(this.userMenu, this.viewContainerRef));

  this.sub = fromEvent<MouseEvent>(document, 'click')
    .pipe(
      filter(event => {
        const clickTarget = event.target as HTMLElement;
        return !!this.overlayRef && !this.overlayRef.overlayElement.contains(clickTarget);
      }),
      take(1)
    ).subscribe(() => this.closePanel());
}

</code>```

html

```<code>
<div
  class="map"
  leaflet
  [leafletOptions]="options"
  (leafletDrawStart)="onDrawStart($event)"
  (contextmenu)=" $event. preventDefault();"
  (leafletMapZoom)="eventZoom($event)"
  (leafletMapReady)="onMapReady($event)"
>
</div>
<ng-template #userMenu   cdkConnectedOverlay>
  <section class="user-menu">

      <div>Option 1 </div>

  </section>
</ng-template>
</code>```

How can I solve that?

Body:
I'm trying to put a "contextMenu" in angular leaflet, when done in an empty div it works. Image 01
Image 01
But when it tried to place over the leaflet, it doesn't load the position or overlay styles.
Image 02
Imagen html
And when I activate the button toolpit, it just loads the overlay styles
Image 03
Imagen html load
CODE:

const openPan = (val) => this.open(val);
this.map.addEventListener('contextmenu' , openPan);`

open($event){
  this.closePanel();
  const positionStrategy = this.overlay.position()
  .flexibleConnectedTo($event.containerPoint)
  .withPositions([
    {
      originX: 'end',
      originY: 'bottom',
      overlayX: 'end',
      overlayY: 'top',
    }
    ]);
    this.overlayRef = this.overlay.create({
      positionStrategy,
      scrollStrategy: this.overlay.scrollStrategies.close(),
      disposeOnNavigation: true
    },
    );
    this.overlayRef.attach(new TemplatePortal(this.userMenu, this.viewContainerRef));

  this.sub = fromEvent<MouseEvent>(document, 'click')
    .pipe(
      filter(event => {
        const clickTarget = event.target as HTMLElement;
        return !!this.overlayRef && !this.overlayRef.overlayElement.contains(clickTarget);
      }),
      take(1)
    ).subscribe(() => this.closePanel());
}

html

<ng-template #userMenu   cdkConnectedOverlay>

Option 1

</ng-template>

How can I solve that?


问:
export Bigquery results to GCS based on value of a column
I've been using the following code to export BQ result to GCS.

```<code>  export_query = f"""
      EXPORT DATA
      OPTIONS(
        uri='{uri}',
        format=format,
        overwrite=true,
        compression='GZIP')
      AS {query}"""
  client.query(export_query, project=project).result()
</code>```

Now I need to split a large table base on the value of a particular column, and then export each part separately , i.e.

```<code>query_k = """
SELECT * FROM table WHERE col = k
"""
</code>```

for k = 1,2,3...N

I can do it by running N queries, but that seems to be very slow and consume a lot of resources. I am wondering if it is possible to accomplish the task with one single query.

Body:
I've been using the following code to export BQ result to GCS.

  export_query = f"""
      EXPORT DATA
      OPTIONS(
        uri='{uri}',
        format=format,
        overwrite=true,
        compression='GZIP')
      AS {query}"""
  client.query(export_query, project=project).result()

Now I need to split a large table base on the value of a particular column, and then export each part separately , i.e.

query_k = """
SELECT * FROM table WHERE col = k
"""

for k = 1,2,3...N

I can do it by running N queries, but that seems to be very slow and consume a lot of resources. I am wondering if it is possible to accomplish the task with one single query.


问:
How to show and expand only one frame in tkinter frame swapping?
Both frames show when using pack(). The login frame is supposed to show first, and when register is clicked, the register email frame is supposed to show.

Works fine when using grid(), but the frame doesn't fill the container. I tried doing sticky on all four corners, but it only sticks to one corner.
The size of the container might not be the problem since I made sure it expanded to fill the 400x400 window, so it's just the frames themselves causing the issue

How do I fix this?

```<code>`
import tkinter as tk
import customtkinter as ctk

class Window(ctk.CTk):
    def __init__(self, *args, **kwargs):
        super().__init__()

        self.geometry('400x400')
        self.title('Music Mayhem')
        self.resizable(False, False)

        container = ctk.CTkFrame(master=self)
        container.pack(side='top', fill='both', expand=True)

        self.frames={}

        for F in (LoginFrame, RegEmailFrame):
            frame = F(container, self)
            self.frames[F] = frame
            #frame.grid(row=0, column=0, sticky= 'n'+'e'+'s'+'w')
            frame.pack(expand= True, fill = 'both')

        self.show_frame(LoginFrame)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

#Create a frame to place the logo in
class LogoFrame(ctk.CTkFrame):
    def __init__(self, *args, header_name="Logo Frame", **kwargs):
        super().__init__(*args, **kwargs)

        self.logo = ctk.CTkLabel(master=self, text='PLACE LOGO HERE')
        self.logo.grid(row=0, column=0)

#First Frame that will show when app is opened
class LoginFrame (tk.Frame):
    def __init__(self,parent, controller, header_name="Login"):
        tk.Frame.__init__(self, parent, bg='#363635')

        self.logo = LogoFrame(self, header_name='Logo')
        self.logo.grid(row=0, column=0)

        self.emailEntry = ctk.CTkEntry(master=self,
                                 placeholder_text = 'Email Address',
                                 width=150,
                                 height=35)
        self.emailEntry.grid(row=1,column=0, pady = 5)

        self.passwordEntry = ctk.CTkEntry(master=self,
                                     placeholder_text = 'Password',
                                     width = 150,
                                     height =35)
        self.passwordEntry.grid(row=2, column = 0, pady = 5)

        self.loginBtn = ctk.CTkButton(master = self,
                                      width = 60,
                                      height = 30,
                                      text = 'Login')
        self.loginBtn.grid(row=3, column=0, pady=10)

        self.regBtn = ctk.CTkButton(master=self,
                                    width=60,
                                    height=20,
                                    text = 'Register',
                                    fg_color = 'transparent',
                                    command= lambda:
                                    controller.show_frame(RegEmailFrame))
        self.regBtn.grid(row=4, column=0, pady=5)

class RegEmailFrame(tk.Frame):
    def __init__(self, parent, controller,header_name="Register Email"):
        tk.Frame.__init__(self, parent, bg='#81817e')

        self.logo = LogoFrame(self)
        self.logo.grid(row=0, column=0)

        self.emailLabel = ctk.CTkLabel(master=self,
                                       text='Register Email:')
        self.emailLabel.grid(row=1, column=0, pady=5)

        self.emailEntry = ctk.CTkEntry(master=self,
                                       placeholder_text = 'Email Address',
                                       width=150,
                                       height=35)
        self.emailEntry.grid(row=2, column=0)

        self.contBtn = ctk.CTkButton(master=self,
                                     width=60,
                                     height=30,
                                     text = 'Continue')
        self.contBtn.grid(row=3, column=0, pady=5)

        self.backBtn = ctk.CTkButton(master=self,
                                    width=60,
                                    height=20,
                                    text = 'Back',
                                    fg_color = 'transparent',
                                    command= lambda:
                                    controller.show_frame(LoginFrame))
        self.backBtn.grid(row=4, column=0, pady=5)

if __name__ == '__main__':
    app = Window()
    app.mainloop()

`
</code>```

EDIT

I tried to implement forget(). Changes to parts of the code showed below:

```<code>def show_frame(self, cont, prev):
    prev = self.frames[prev]
    prev.forget()
    frame = self.frames[cont]
    frame.tkraise()

self.regBtn = ctk.CTkButton(master=self,
                            width=60,
                            height=20,
                            text = 'Register',
                            fg_color = 'transparent',
                            command= lambda:
                            controller.show_frame(RegEmailFrame, LoginFrame))

self.backBtn = ctk.CTkButton(master=self,
                                    width=60,
                                    height=20,
                                    text = 'Back',
                                    fg_color = 'transparent',
                                    command= lambda:
                                    controller.show_frame(LoginFrame, RegEmailFrame))
</code>```

However, an error appears :
TypeError: Window.show_frame() missing 1 required positional argument: 'prev'

SOLUTION:

```<code>    for F in (LoginFrame, RegEmailFrame):
        frame = F(container, self)
        self.frames[F] = frame
        frame.grid(row=0, column=0, sticky= 'n'+'e'+'s'+'w')
        frame.grid_columnconfigure(0,weight=1)
        frame.grid_rowconfigure(0,weight=1)
</code>```

Body:
Both frames show when using pack(). The login frame is supposed to show first, and when register is clicked, the register email frame is supposed to show.

Works fine when using grid(), but the frame doesn't fill the container. I tried doing sticky on all four corners, but it only sticks to one corner.
The size of the container might not be the problem since I made sure it expanded to fill the 400x400 window, so it's just the frames themselves causing the issue

How do I fix this?

`
import tkinter as tk
import customtkinter as ctk

class Window(ctk.CTk):
    def __init__(self, *args, **kwargs):
        super().__init__()

        self.geometry('400x400')
        self.title('Music Mayhem')
        self.resizable(False, False)

        container = ctk.CTkFrame(master=self)
        container.pack(side='top', fill='both', expand=True)

        self.frames={}

        for F in (LoginFrame, RegEmailFrame):
            frame = F(container, self)
            self.frames[F] = frame
            #frame.grid(row=0, column=0, sticky= 'n'+'e'+'s'+'w')
            frame.pack(expand= True, fill = 'both')

        self.show_frame(LoginFrame)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

#Create a frame to place the logo in
class LogoFrame(ctk.CTkFrame):
    def __init__(self, *args, header_name="Logo Frame", **kwargs):
        super().__init__(*args, **kwargs)

        self.logo = ctk.CTkLabel(master=self, text='PLACE LOGO HERE')
        self.logo.grid(row=0, column=0)

#First Frame that will show when app is opened
class LoginFrame (tk.Frame):
    def __init__(self,parent, controller, header_name="Login"):
        tk.Frame.__init__(self, parent, bg='#363635')

        self.logo = LogoFrame(self, header_name='Logo')
        self.logo.grid(row=0, column=0)

        self.emailEntry = ctk.CTkEntry(master=self,
                                 placeholder_text = 'Email Address',
                                 width=150,
                                 height=35)
        self.emailEntry.grid(row=1,column=0, pady = 5)

        self.passwordEntry = ctk.CTkEntry(master=self,
                                     placeholder_text = 'Password',
                                     width = 150,
                                     height =35)
        self.passwordEntry.grid(row=2, column = 0, pady = 5)

        self.loginBtn = ctk.CTkButton(master = self,
                                      width = 60,
                                      height = 30,
                                      text = 'Login')
        self.loginBtn.grid(row=3, column=0, pady=10)

        self.regBtn = ctk.CTkButton(master=self,
                                    width=60,
                                    height=20,
                                    text = 'Register',
                                    fg_color = 'transparent',
                                    command= lambda:
                                    controller.show_frame(RegEmailFrame))
        self.regBtn.grid(row=4, column=0, pady=5)

class RegEmailFrame(tk.Frame):
    def __init__(self, parent, controller,header_name="Register Email"):
        tk.Frame.__init__(self, parent, bg='#81817e')

        self.logo = LogoFrame(self)
        self.logo.grid(row=0, column=0)

        self.emailLabel = ctk.CTkLabel(master=self,
                                       text='Register Email:')
        self.emailLabel.grid(row=1, column=0, pady=5)

        self.emailEntry = ctk.CTkEntry(master=self,
                                       placeholder_text = 'Email Address',
                                       width=150,
                                       height=35)
        self.emailEntry.grid(row=2, column=0)

        self.contBtn = ctk.CTkButton(master=self,
                                     width=60,
                                     height=30,
                                     text = 'Continue')
        self.contBtn.grid(row=3, column=0, pady=5)

        self.backBtn = ctk.CTkButton(master=self,
                                    width=60,
                                    height=20,
                                    text = 'Back',
                                    fg_color = 'transparent',
                                    command= lambda:
                                    controller.show_frame(LoginFrame))
        self.backBtn.grid(row=4, column=0, pady=5)

if __name__ == '__main__':
    app = Window()
    app.mainloop()

`

EDIT

I tried to implement forget(). Changes to parts of the code showed below:

def show_frame(self, cont, prev):
    prev = self.frames[prev]
    prev.forget()
    frame = self.frames[cont]
    frame.tkraise()

self.regBtn = ctk.CTkButton(master=self,
                            width=60,
                            height=20,
                            text = 'Register',
                            fg_color = 'transparent',
                            command= lambda:
                            controller.show_frame(RegEmailFrame, LoginFrame))

self.backBtn = ctk.CTkButton(master=self,
                                    width=60,
                                    height=20,
                                    text = 'Back',
                                    fg_color = 'transparent',
                                    command= lambda:
                                    controller.show_frame(LoginFrame, RegEmailFrame))

However, an error appears :
TypeError: Window.show_frame() missing 1 required positional argument: 'prev'

SOLUTION:

    for F in (LoginFrame, RegEmailFrame):
        frame = F(container, self)
        self.frames[F] = frame
        frame.grid(row=0, column=0, sticky= 'n'+'e'+'s'+'w')
        frame.grid_columnconfigure(0,weight=1)
        frame.grid_rowconfigure(0,weight=1)


问:
Using flexsearch document results in "Document only refers to a type"
I have an Angular app that uses flexsearch@0.7.31

I import the Document object, but when I try to call the constructor I get "Document only refers to a type".

The index.d.ts file indeed defines Document as an interface, with the Document object in src/document.js not exposed as a type.

I'm not sure how to get this to work.

```<code>import { Document } from "flexsearch";
...
const researchplanIndex = new Document({
      language: lang,
      document: {
        id: 'id',
        index: [
          'objective',
          'items[]:title',
          'items[]:note',
          'items[]:repository',
        ],
      },
    });
</code>```

The error occurs at new Document

Body:
I have an Angular app that uses flexsearch@0.7.31

I import the Document object, but when I try to call the constructor I get "Document only refers to a type".

The index.d.ts file indeed defines Document as an interface, with the Document object in src/document.js not exposed as a type.

I'm not sure how to get this to work.

import { Document } from "flexsearch";
...
const researchplanIndex = new Document({
      language: lang,
      document: {
        id: 'id',
        index: [
          'objective',
          'items[]:title',
          'items[]:note',
          'items[]:repository',
        ],
      },
    });

The error occurs at new Document


问:
The phylo tree can not display the color
The following code generates a phylo tree, which you can see here:

,

But I have no idea why the tree can't display the color.

coul <- brewer.pal(4, "PuOr");coul

ReSo<-metadata %>% select(c("id","region","source" ));ReSo

colR <- colorRampPalette(coul)(length(unique (metadata_campy$region)));colR

regionCol <- data.frame(colR,ord = unique (metadata_campy$region));regionCol

ReSo$region<-factor(ReSo$region, levels = regionCol$ord);ReSo$region

colorTreeTip = function(tree,metadata_campy,var) {

  if(var %in% c("region")){

    t<-tree %<+% ReSo + geom_tippoint(mapping =

    aes(color = region), size=5, alpha=0.35) +

    scale_color_manual(values=regionCol$colR,

     drop=FALSE,na.translate = FALSE)+

    geom_tiplab(linetype = "dashed",align = TRUE) +

     theme(legend.justification = c("right", "bottom"))

     ;t

 }

 t + ggexpand(0.3, side = "h")

}

And give the following warning:

    Warning: Removed 18 rows containing missing

      values(geom_point_g_gtree()).

Thanks for your help to understand what is wrong.


问:
What options do I pass to a gcc Mips compiler to generate a mips assembly code with sections labels
I am able to generate the assembly code but I would want the assembly code to have in it section labels like .data,  .text, .file etc as part of the output.
What options do I need to pass to the compiler for this effect.

Below is the link and an image to my source code, and asm output.

link


问:
Where to put environment variables for a SPA during docker build time in a CI pipeline?
At build time in localhost, the environment variables are set in .env files.
At build time during a Continuos Integration process are set onto the Dockerfile using ARG and ENV so the CI is responsible of "hydrating" the values as build argument for docker build command.

I'm wondering if this is an scalable solution when the docker image needs a considerable amount of environment variables making the CI command line a bit cumbersome. Keeping in mind that is for a SPA and not sensible information or secret is been added as environment variable.
`

```<code># This is an example of a dummy Dockerfile with multi stage
FROM your.npmregistry.com/node:16-alpine3.11 AS nginx_conf
LABEL owner=whoever
WORKDIR /build
COPY . .

FROM your.npmregistry.com/node:16-alpine3.11 AS build

LABEL owner=whoever
RUN apk --no-cache add python build-base
WORKDIR /app
COPY . .

ARG THEME
ARG NEW_RELIC_ENABLED="true"

ENV REACT_APP_THEME=$THEME
ENV REACT_APP_NEW_RELIC_ENABLED=$NEW_RELIC_ENABLED

RUN yarn --frozen-lockfile && yarn build

FROM your.npmregistry.com/nginx:stable-alpine AS dist

LABEL owner=whoever
RUN this and that
WORKDIR /app
COPY ./foo.sh .
ENTRYPOINT ["./foo.sh"]
CMD ["nginx", "-g", "pid /tmp/nginx.pid; daemon off;"]

# This is just an example
EXPOSE XYZ XYZ

</code>```

`

An example of Jenkinsfile with just 2 arguments looks like this one below.

```<code>agent {
  dockerfile {
    filename 'docker/Dockerfile.nonprod'
    additionalBuildArgs "--target build --build-arg THEME=foo --build-arg NEW_RELIC_ENABLED=false -t foo-build"
    reuseNode true
  }
}
</code>```

However if it requires a considerable amount of environment variables it could become cumbersome.
Just a dummy example below.

```<code>agent {
  dockerfile {
    filename 'docker/Dockerfile.nonprod'
    additionalBuildArgs "--target build --build-arg THEME=foo --build-arg NEW_RELIC_ENABLED=false --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo -t foo-build"
    reuseNode true
  }
}

</code>```

I expect to have a solution that makes the code more readable.

Body:
At build time in localhost, the environment variables are set in .env files.
At build time during a Continuos Integration process are set onto the Dockerfile using ARG and ENV so the CI is responsible of "hydrating" the values as build argument for docker build command.

I'm wondering if this is an scalable solution when the docker image needs a considerable amount of environment variables making the CI command line a bit cumbersome. Keeping in mind that is for a SPA and not sensible information or secret is been added as environment variable.
`

# This is an example of a dummy Dockerfile with multi stage
FROM your.npmregistry.com/node:16-alpine3.11 AS nginx_conf
LABEL owner=whoever
WORKDIR /build
COPY . .

FROM your.npmregistry.com/node:16-alpine3.11 AS build

LABEL owner=whoever
RUN apk --no-cache add python build-base
WORKDIR /app
COPY . .

ARG THEME
ARG NEW_RELIC_ENABLED="true"

ENV REACT_APP_THEME=$THEME
ENV REACT_APP_NEW_RELIC_ENABLED=$NEW_RELIC_ENABLED

RUN yarn --frozen-lockfile && yarn build

FROM your.npmregistry.com/nginx:stable-alpine AS dist

LABEL owner=whoever
RUN this and that
WORKDIR /app
COPY ./foo.sh .
ENTRYPOINT ["./foo.sh"]
CMD ["nginx", "-g", "pid /tmp/nginx.pid; daemon off;"]

# This is just an example
EXPOSE XYZ XYZ

`

An example of Jenkinsfile with just 2 arguments looks like this one below.

agent {
  dockerfile {
    filename 'docker/Dockerfile.nonprod'
    additionalBuildArgs "--target build --build-arg THEME=foo --build-arg NEW_RELIC_ENABLED=false -t foo-build"
    reuseNode true
  }
}

However if it requires a considerable amount of environment variables it could become cumbersome.
Just a dummy example below.

agent {
  dockerfile {
    filename 'docker/Dockerfile.nonprod'
    additionalBuildArgs "--target build --build-arg THEME=foo --build-arg NEW_RELIC_ENABLED=false --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo --build-arg another0=foo -t foo-build"
    reuseNode true
  }
}

I expect to have a solution that makes the code more readable.


问:
MySQL InnoDB Full-text search: Override default stopword list
I'm using MySQL8.0 InnoDB and its full-text search features. The default stopwords list of InnoDB only contains 36 words. Extending the stopword list to 500+ words helps to lift our full-text queries speed a lot.

The problem is according to this doc, we will need to SET GLOBAL config innodb_ft_server_stopword_table = 'test/my_stopwords'. However, our team doesn't have the DB super user right and we cannot modify the stopword table config. The workaround I have found is to SET SESSION config innodb_ft_user_table = 'test/my_stopwords', and rebuild FULLTEXT index within the same session.

But the limitations of this workaround is that whenever we did a DB cleanup, or even whenever we update/insert new data, it won't be using the customized stopword table, and we will have to set the SESSION config and rebuild FULLTEXT index again. (I assume existing data's index built with the customized stopword table shouldn't be impacted even if the session is closed?)

Is there any other ways to use the customized stopword table without the GLOBAL config?

Two solutions to this problem I can think of:

SET SESSION config and rebuild FULLTEXT index time to time, whenever there is a DB cleanup, or when search is performing noticeable slow.

In our code, before executing any full-text queries, read the customized stopword table and toss any stopword in the search string and only search remaining words.


问:
Having challenges configuring node:path not resolving in Remix
I'm trying to configure a Remix app to use i18next module for translations.
So far I've been following the guide on Github: https://github.com/sergiodxa/remix-i18next

It seems okay except I can't get node:path to resolve to a module.

I tried a few different things:

Updated nvm to use node 18 instead of 17. Neither works.

I also tried using const path = require('path') which works but then throws a different error trying to load the resource files.

I needed to remove the changeLanguage code in root.tsx to get it to start.

I'd like to isolate it by first trying to fix why the node:path isn't resolving so if someone could help with that, it would be a start?

Debug mode recommends:  You can mark the path "node:path" as external to exclude it from the bundle, which will remove this error

But how do I mark it 'external' and what does that mean?


问:
Can't run quantised models on machine
I'm trying to get the 8bit quantised bloom models running on my machine.
I (seem to have) installed all of the dependencies, however, when I run my script, it errors - saying it can't find the cudaGetRuntime
I then tried switching to to conda environemnt - using conda activate (and conda install cudatoolkit)

and it says it cant find "bitsandbytes"

root@localhost:~# pip install bitsandbytes accelerate transformers

```<code>Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com
Requirement already satisfied: bitsandbytes in /usr/local/lib/python3.10/dist-packages (0.35.4)
Requirement already satisfied: accelerate in /usr/local/lib/python3.10/dist-packages (0.15.0)
Requirement already satisfied: transformers in /usr/local/lib/python3.10/dist-packages (4.25.1)
Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from accelerate) (21.3)
Requirement already satisfied: psutil in /usr/local/lib/python3.10/dist-packages (from accelerate) (5.9.4)
Requirement already satisfied: pyyaml in /usr/lib/python3/dist-packages (from accelerate) (5.4.1)
Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from accelerate) (1.23.4)
Requirement already satisfied: torch>=1.4.0 in /usr/local/lib/python3.10/dist-packages (from accelerate) (1.13.0)
Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.10/dist-packages (from transformers) (4.64.1)
Requirement already satisfied: requests in /usr/lib/python3/dist-packages (from transformers) (2.27.1)
Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from transformers) (3.8.2)
Requirement already satisfied: tokenizers!=0.11.3,<0.14,>=0.11.1 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.13.2)
Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.10/dist-packages (from transformers) (2022.10.31)
Requirement already satisfied: huggingface-hub<1.0,>=0.10.0 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.11.1)
Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.10/dist-packages (from huggingface-hub<1.0,>=0.10.0->transformers) (4.4.0)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/lib/python3/dist-packages (from packaging>=20.0->accelerate) (3.0.7)
Requirement already satisfied: nvidia-cuda-nvrtc-cu11==11.7.99 in /usr/local/lib/python3.10/dist-packages (from torch>=1.4.0->accelerate) (11.7.99)
Requirement already satisfied: nvidia-cublas-cu11==11.10.3.66 in /usr/local/lib/python3.10/dist-packages (from torch>=1.4.0->accelerate) (11.10.3.66)
Requirement already satisfied: nvidia-cuda-runtime-cu11==11.7.99 in /usr/local/lib/python3.10/dist-packages (from torch>=1.4.0->accelerate) (11.7.99)
Requirement already satisfied: nvidia-cudnn-cu11==8.5.0.96 in /usr/local/lib/python3.10/dist-packages (from torch>=1.4.0->accelerate) (8.5.0.96)
Requirement already satisfied: wheel in /usr/local/lib/python3.10/dist-packages (from nvidia-cublas-cu11==11.10.3.66->torch>=1.4.0->accelerate) (0.38.4)
Requirement already satisfied: setuptools in /usr/local/lib/python3.10/dist-packages (from nvidia-cublas-cu11==11.10.3.66->torch>=1.4.0->accelerate) (65.5.1)
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
</code>```

root@localhost:~# python /tmp/pycharm_project_354/bloom8.py

```<code>  File "/tmp/pycharm_project_354/bloom8.py", line 6, in <module>
    from bitsandbytes.functional import quantize_blockwise, dequantize_blockwise
ModuleNotFoundError: No module named 'bitsandbytes'
</code>```

Title: Can't run quantised models on machine

Body:
I'm trying to get the 8bit quantised bloom models running on my machine.
I (seem to have) installed all of the dependencies, however, when I run my script, it errors - saying it can't find the cudaGetRuntime
I then tried switching to to conda environemnt - using conda activate (and conda install cudatoolkit)

and it says it cant find "bitsandbytes"

root@localhost:~# pip install bitsandbytes accelerate transformers

Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com
Requirement already satisfied: bitsandbytes in /usr/local/lib/python3.10/dist-packages (0.35.4)
Requirement already satisfied: accelerate in /usr/local/lib/python3.10/dist-packages (0.15.0)
Requirement already satisfied: transformers in /usr/local/lib/python3.10/dist-packages (4.25.1)
Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from accelerate) (21.3)
Requirement already satisfied: psutil in /usr/local/lib/python3.10/dist-packages (from accelerate) (5.9.4)
Requirement already satisfied: pyyaml in /usr/lib/python3/dist-packages (from accelerate) (5.4.1)
Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from accelerate) (1.23.4)
Requirement already satisfied: torch>=1.4.0 in /usr/local/lib/python3.10/dist-packages (from accelerate) (1.13.0)
Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.10/dist-packages (from transformers) (4.64.1)
Requirement already satisfied: requests in /usr/lib/python3/dist-packages (from transformers) (2.27.1)
Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from transformers) (3.8.2)
Requirement already satisfied: tokenizers!=0.11.3,<0.14,>=0.11.1 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.13.2)
Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.10/dist-packages (from transformers) (2022.10.31)
Requirement already satisfied: huggingface-hub<1.0,>=0.10.0 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.11.1)
Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.10/dist-packages (from huggingface-hub<1.0,>=0.10.0->transformers) (4.4.0)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/lib/python3/dist-packages (from packaging>=20.0->accelerate) (3.0.7)
Requirement already satisfied: nvidia-cuda-nvrtc-cu11==11.7.99 in /usr/local/lib/python3.10/dist-packages (from torch>=1.4.0->accelerate) (11.7.99)
Requirement already satisfied: nvidia-cublas-cu11==11.10.3.66 in /usr/local/lib/python3.10/dist-packages (from torch>=1.4.0->accelerate) (11.10.3.66)
Requirement already satisfied: nvidia-cuda-runtime-cu11==11.7.99 in /usr/local/lib/python3.10/dist-packages (from torch>=1.4.0->accelerate) (11.7.99)
Requirement already satisfied: nvidia-cudnn-cu11==8.5.0.96 in /usr/local/lib/python3.10/dist-packages (from torch>=1.4.0->accelerate) (8.5.0.96)
Requirement already satisfied: wheel in /usr/local/lib/python3.10/dist-packages (from nvidia-cublas-cu11==11.10.3.66->torch>=1.4.0->accelerate) (0.38.4)
Requirement already satisfied: setuptools in /usr/local/lib/python3.10/dist-packages (from nvidia-cublas-cu11==11.10.3.66->torch>=1.4.0->accelerate) (65.5.1)
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

root@localhost:~# python /tmp/pycharm_project_354/bloom8.py

  File "/tmp/pycharm_project_354/bloom8.py", line 6, in <module>
    from bitsandbytes.functional import quantize_blockwise, dequantize_blockwise
ModuleNotFoundError: No module named 'bitsandbytes'


问:
Nodejs app in Docker not accessible on localhost:3000
I am trying to run a Node application in a Docker container. The installation instructions specified that after adding host: '0.0.0.0' to config/local.js and running docker-compose up the app should be accessible at localhost:3000, but I get an error message in the browser saying "The connection was reset - The connection to the server was reset while the page was loading."

I have tried to add the host: '0.0.0.0' in different places, or remove it entirely, access https://localhost:3000 as opposed to at http, connecting to localhost:3000/webpack-dev-server/index.html, etc.

What could be going wrong?


问:
MQTT async worker in Django
In my Django application, I need to connect to a MQTT broker from several locations.

It will be great if I can create some kind of MQTT worker, which will run in the background/different thread and I can use this worker to publish/subscribe for messages and I don't have to create a separate MQTT connection for each function.

Example:

Create MQTT worker with connection details. On startup, this connection is started and handled, restarted if connection lost, etc... (maybe use Celery for this?)

Create functions which is available inside my Django projects for publish and subscribe. Publish seems more straighforward, but I'm not sure about the subscribe part.

My current implementation:

```<code>@shared_task(
    bind=True,
    name="tasks.send_command",
)
def send_command(self, username):
    pedestals = User.objects.filter(username=username)
    client = MqttClient("scheduled")
    client.connect()
    ...

@shared_task(
    bind=True,
    name="tasks.toggle_switch",
)
def toggle_switch(self, switch):
    from django.core.cache import cache
    client = MqttClient("toggle-switch")
    client.connect()
    ...
</code>```

As you can see, I need to create the client in every task. Also I'm using it multiple times in Django as well, not just as a Celery task.
How can I create a worker for this. So like:

```<code>@shared_task(
    bind=True,
    name="tasks.toggle_switch",
)
def toggle_switch(self, switch):
    from django.core.cache import cache
    from mqtt.worker import mqtt_worker
    mqtt_worker.publish()
    ...
</code>```

That way I could simplify my codebase and I would not have to wait for the client to connect every time the task runs.

I have found mqttasgi but I don't know if it will fit my needs.

Title: MQTT async worker in Django

Body:
In my Django application, I need to connect to a MQTT broker from several locations.

It will be great if I can create some kind of MQTT worker, which will run in the background/different thread and I can use this worker to publish/subscribe for messages and I don't have to create a separate MQTT connection for each function.

Example:

Create MQTT worker with connection details. On startup, this connection is started and handled, restarted if connection lost, etc... (maybe use Celery for this?)

Create functions which is available inside my Django projects for publish and subscribe. Publish seems more straighforward, but I'm not sure about the subscribe part.

My current implementation:

@shared_task(
    bind=True,
    name="tasks.send_command",
)
def send_command(self, username):
    pedestals = User.objects.filter(username=username)
    client = MqttClient("scheduled")
    client.connect()
    ...

@shared_task(
    bind=True,
    name="tasks.toggle_switch",
)
def toggle_switch(self, switch):
    from django.core.cache import cache
    client = MqttClient("toggle-switch")
    client.connect()
    ...

As you can see, I need to create the client in every task. Also I'm using it multiple times in Django as well, not just as a Celery task.
How can I create a worker for this. So like:

@shared_task(
    bind=True,
    name="tasks.toggle_switch",
)
def toggle_switch(self, switch):
    from django.core.cache import cache
    from mqtt.worker import mqtt_worker
    mqtt_worker.publish()
    ...

That way I could simplify my codebase and I would not have to wait for the client to connect every time the task runs.

I have found mqttasgi but I don't know if it will fit my needs.


问:
PATH Export Behavior With Same File In Two Locations
Numerous posts online state to add a new path to the end of your existing $PATH value to ensure that any regular system paths are prioritized first (It is also written in Steve Parkers "Shell Scripting" book).  So I tested this to see what happens if I had 2 new directories added to my path, with both having the same filename in with 755 permissions.

```<code>$ cat /home/john/testpath1/aaa
echo "hi from testpath1/aaa"
$ cat /home/john/testpath2/aaa
echo "hi from testpath2/aaa"
$ export PATH=$PATH:/home/john/testpath1:/home/john/testpath2
$ aaa
hi from testpath1/aaa
</code>```

Sure enough, I got the result I was expecting, showing that it's prioritised the testpath1 directory over testpath2's directory.  Good. Now I want to test to see what happens when I delete this file, to ensure the aaa file in testpath2 gets executed:

```<code>$ rm /home/john/testpath1/aaa
$ aaa
bash: /home/john/testpath1/aaa: No such file or directory
</code>```

I was not expecting this, since the file is definately there. So why doesn't it find it? It's like it's cached the first path file or something..?  Anyways I validate that the file definately executes and works if the testpath1 directory is removed, and it does:

```<code>$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/home/john/testpath1:/home/john/testpath2
$ export PATH=/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/home/john/testpath2
$ aaa
hi from testpath2/aaa
</code>```

So clearly the aaa file in testpath2 works, but can only be found once I remove testpath1..?

Can someone explain why aaa is removed from testfile1, that the aaa file in testfile2 does not get found?

Body:
Numerous posts online state to add a new path to the end of your existing $PATH value to ensure that any regular system paths are prioritized first (It is also written in Steve Parkers "Shell Scripting" book).  So I tested this to see what happens if I had 2 new directories added to my path, with both having the same filename in with 755 permissions.

$ cat /home/john/testpath1/aaa
echo "hi from testpath1/aaa"
$ cat /home/john/testpath2/aaa
echo "hi from testpath2/aaa"
$ export PATH=$PATH:/home/john/testpath1:/home/john/testpath2
$ aaa
hi from testpath1/aaa

Sure enough, I got the result I was expecting, showing that it's prioritised the testpath1 directory over testpath2's directory.  Good. Now I want to test to see what happens when I delete this file, to ensure the aaa file in testpath2 gets executed:

$ rm /home/john/testpath1/aaa
$ aaa
bash: /home/john/testpath1/aaa: No such file or directory

I was not expecting this, since the file is definately there. So why doesn't it find it? It's like it's cached the first path file or something..?  Anyways I validate that the file definately executes and works if the testpath1 directory is removed, and it does:

$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/home/john/testpath1:/home/john/testpath2
$ export PATH=/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/home/john/testpath2
$ aaa
hi from testpath2/aaa

So clearly the aaa file in testpath2 works, but can only be found once I remove testpath1..?

Can someone explain why aaa is removed from testfile1, that the aaa file in testfile2 does not get found?


问:
Can we batch rename excel variable names?
Image you have an excel sheet, with names as variables for formulas, references, etc. (all viewable the Names Manager).

You want to create clones of this sheet, and add them as separate sheets to another workbook.

However, the names will conflict.

E.g. FirstColumnTitle will be the same for each sheet.

Excel seems to latch the basic function to batch rename variable names in the Names Manager, so the same name can be renamed (e.g. append ‘_sheet1’ to  FirstColumnTitle making it ‘FirstColumnTitle_sheet1’).

How would one go about this?

I tried Names Manager, and a VB Macro (link below) that was supposed to work (but only renamed a single variable).

```<code>Sub RenameCells()
Dim n As Name
    For Each n In ThisWorkbook.Names
        n.Name = "KUTOOLS_" & n.Name
    Next n
End Sub
</code>```

I can manually change the names one by one, but… what if there are hundreds of names on a sheet that will be cloned to the same workbook a handful of times?

Example: the sheet/worksheet is a loan amortization template. In the Template, it has names such as “LoanAmount” which refers to the cell where the loan amount is entered, and “LoanInterestRate” referring to the cell sign the APR.

If I try to copy that whole worksheet into another workbook twice (two different copies of the loan worksheet in two tabs in one workbook) the variable names (found in Names Manager) conflict with one another and end up interfering with one another or blocking calculations/functionality in one or the other worksheet (if they have different values.)

How to reproduce the problem (that I'm trying to solve):

Create a new spreadsheet from the "Loan Amortization Schedule" template,

then create a copy of that sheet a couple times to the same workbook (or another).

Now set a loan balance, APR, loan term, and payments per year (make it different for each sheet such that the number of payments should be different).

Notice that in the second (and third and fourth) sheet, the result for "Actual Number of Payments" for each sheet is whatever the value is for the first sheet. Open Names Manager, and the name for each indicates that its scope is only for the appropriate sheet, yet somehow sheet1's ActualNumberOfPayments reference name is referred to in the other sheets (even though their respective ActualNumberOfPayments appropriately refers to the other reference names in their own sheet only).

Body:
Image you have an excel sheet, with names as variables for formulas, references, etc. (all viewable the Names Manager).

You want to create clones of this sheet, and add them as separate sheets to another workbook.

However, the names will conflict.

E.g. FirstColumnTitle will be the same for each sheet.

Excel seems to latch the basic function to batch rename variable names in the Names Manager, so the same name can be renamed (e.g. append ‘_sheet1’ to  FirstColumnTitle making it ‘FirstColumnTitle_sheet1’).

How would one go about this?

I tried Names Manager, and a VB Macro (link below) that was supposed to work (but only renamed a single variable).

Sub RenameCells()
Dim n As Name
    For Each n In ThisWorkbook.Names
        n.Name = "KUTOOLS_" & n.Name
    Next n
End Sub

I can manually change the names one by one, but… what if there are hundreds of names on a sheet that will be cloned to the same workbook a handful of times?

Example: the sheet/worksheet is a loan amortization template. In the Template, it has names such as “LoanAmount” which refers to the cell where the loan amount is entered, and “LoanInterestRate” referring to the cell sign the APR.

If I try to copy that whole worksheet into another workbook twice (two different copies of the loan worksheet in two tabs in one workbook) the variable names (found in Names Manager) conflict with one another and end up interfering with one another or blocking calculations/functionality in one or the other worksheet (if they have different values.)

How to reproduce the problem (that I'm trying to solve):

Create a new spreadsheet from the "Loan Amortization Schedule" template,

then create a copy of that sheet a couple times to the same workbook (or another).

Now set a loan balance, APR, loan term, and payments per year (make it different for each sheet such that the number of payments should be different).

Notice that in the second (and third and fourth) sheet, the result for "Actual Number of Payments" for each sheet is whatever the value is for the first sheet. Open Names Manager, and the name for each indicates that its scope is only for the appropriate sheet, yet somehow sheet1's ActualNumberOfPayments reference name is referred to in the other sheets (even though their respective ActualNumberOfPayments appropriately refers to the other reference names in their own sheet only).


问:
Checking for special characters in file paths that are used to dynamically generate SQL queries
I have a python script that iterates through file paths and the inserts those paths into a SQL DB. This is specifically running against Athena and S3 Inventory. Sometimes someone might create a path with a special character, such as this path: "'Archive012/2406-2150 CustomerInt'l Melange-1/Melange-1'.

That extra ' in Int'l causes an issue as SQL thinks that's the end of the path. Here's the query:

whereStatement += f" OR key LIKE '{p}%'"

Is there a way to dump that a line like that and have it report the offending line and preferably continue?

Thanks