问:
How to read data from tensorflow 2 summary writer
I'm having trouble with reading data from a tensorflow summary writer.

I'm using the writer from the example on the tensorflow website: https://www.tensorflow.org/tensorboard/migrate

```<code>import tensorflow as tf
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator

writer = tf.summary.create_file_writer("/tmp/mylogs/eager")

# write to summary writer
with writer.as_default():
  for step in range(100):
    # other model code would go here
    tf.summary.scalar("my_metric", 0.5, step=step)
    writer.flush()

# read from summary writer
event_acc = EventAccumulator("/tmp/mylogs/eager")
event_acc.Reload()
event_acc.Tags()
</code>```

yields:

```<code> 'distributions': [],
 'graph': False,
 'histograms': [],
 'images': [],
 'meta_graph': False,
 'run_metadata': [],
 'scalars': [],
 'tensors': ['my_metric']}```

```

<p>If I try to grab the tensor data:</p>

```import pandas as pd
pd.DataFrame(event_acc.Tensors('my_metric'))
```

<p>I don't get the right values:</p>

```wall_time   step    tensor_proto
0   1.590743e+09    3   dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
1   1.590743e+09    20  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
2   1.590743e+09    24  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
3   1.590743e+09    32  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
...
```

How do I grab the actual summary data (which should be 0.5, for each of 100 steps)?

Here is a colab notebook with the code above: https://colab.research.google.com/drive/1RlgZrGD_vY-YcOBLF_sEPelmtVuygkqz?usp=sharing

答:
To avoid a subset of steps, I would suggest:

```<code>event_acc = EventAccumulator("/tmp/mylogs/eager", size_guidance={'tensors': 0})
</code>```

Body:
I'm having trouble with reading data from a tensorflow summary writer.

I'm using the writer from the example on the tensorflow website: https://www.tensorflow.org/tensorboard/migrate

import tensorflow as tf
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator

writer = tf.summary.create_file_writer("/tmp/mylogs/eager")

# write to summary writer
with writer.as_default():
  for step in range(100):
    # other model code would go here
    tf.summary.scalar("my_metric", 0.5, step=step)
    writer.flush()

# read from summary writer
event_acc = EventAccumulator("/tmp/mylogs/eager")
event_acc.Reload()
event_acc.Tags()

yields:

 'distributions': [],
 'graph': False,
 'histograms': [],
 'images': [],
 'meta_graph': False,
 'run_metadata': [],
 'scalars': [],
 'tensors': ['my_metric']}```

If I try to grab the tensor data:

import pandas as pd
pd.DataFrame(event_acc.Tensors('my_metric'))

I don't get the right values:

wall_time   step    tensor_proto
0   1.590743e+09    3   dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
1   1.590743e+09    20  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
2   1.590743e+09    24  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
3   1.590743e+09    32  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
...

How do I grab the actual summary data (which should be 0.5, for each of 100 steps)?

Here is a colab notebook with the code above: https://colab.research.google.com/drive/1RlgZrGD_vY-YcOBLF_sEPelmtVuygkqz?usp=sharing

Body:
To avoid a subset of steps, I would suggest:

event_acc = EventAccumulator("/tmp/mylogs/eager", size_guidance={'tensors': 0})


来源: stackexchange

问:
Is it possible to execute non-test Apex code directly?
I've slung alot of code in multiple languages but am new to Salesforce and Apex.
I see Apex is very much like Java.
I see where one can execute @IsTest methods within a @IsTest Apex class.
But how does one execute non-test code directly? Or must one always build and fire off a Job?
Or do you write Java in VSC with the Salesforce CLI and Apex plugins? Any equivalent "Hello World" examples?

TIA,

Still-learning Steve

答:
sharing a very basic example here

```<code>public class Stack {

    public static void printDetails(){
        system.debug('in static method');
    }

    public void printDetails1(){
        system.debug('in non static method');
    }

}
</code>```

in order to trigger the above class you have created you can use the developer console
Developer Console -> Debug -> Open Execute Anonymous Window and pase the below lines and click on execute

```<code>Stack.printDetails();
Stack s= new Stack();
s.printDetails1();
</code>```

https://help.salesforce.com/articleView?id=code_dev_console.htm&type=5

ContentLicense: CC BY-SA 4.0

Body:
sharing a very basic example here

public class Stack {

    public static void printDetails(){
        system.debug('in static method');
    }

    public void printDetails1(){
        system.debug('in non static method');
    }

}

in order to trigger the above class you have created you can use the developer console
Developer Console -> Debug -> Open Execute Anonymous Window and pase the below lines and click on execute

Stack.printDetails();
Stack s= new Stack();
s.printDetails1();

https://help.salesforce.com/articleView?id=code_dev_console.htm&type=5


问:
How to deploy an Expo/React Native app to iOS Device from Xcode
I'm somewhat new to react native and expo but I've been trying to deploy a test version to my phone but can't figure out how to get it to build.

For some extra context, I built most of it in Expo and then ejected it (yes I know this isn't the best choice but I liked the features Expo provided). I ejected it because I needed NFC support which isn't currently supported in Expo so I added that in manually in Xcode after I ejected.

When I open the Xcode workspace and try to deploy it to my phone I get the following error:

```<code>Error: Failed to connect to the packager server. If you did not start this build by running 'react-native run-android', you can start the packager manually by running 'react-native start' in the project directory. (Error: Request to packager server failed: 500)
    at /Users/user/Downloads/honorProj-reactNatveFinal/honorProj/reactNative/ethelontisApp/node_modules/expo-updates/scripts/createManifest.js:40:11
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
Command PhaseScriptExecution failed with a nonzero exit code
</code>```

I know it says run react-native start in the project directory (although I'm not entirely what the at /Users/... is refering too) but what really threw me was that it mentioned react-native run-android which doesn't seem like it should be related at all.

Lastly I'm completely and utterly lost with what Command PhaseScriptExecution is.

Thanks for the help.

答:
I was facing the exact same issue. So I just completed the set up the android development first.

But before doing anything, follow the below steps, it may solves the problem.

Step-1: Open terminal and navigate to your project directory example: cd Your project path.

Step-2: Type npx react-native start

Step-3: If you get any error like "error listen EADDRINUSE: address already in use :::8081"

Then follow step-4 to 6:

Step-4 : type sudo lsof -n -i4TCP:8081 // You will get PID from here

Step-5: type kill -9 PIDvalue

Step-6: Repeat the step 2 and 3 once again

If you will not get any error in step- 2 then type npx react-native run-android
and check if there is any error. If yes, then you have to set up the android development first to make it working - (As of now I found this way, but not sure if anyone can find any better way).

Else Open the code using xcode then clean the build and also clean the build folder then try to run.

Thanks, Hope it will help.

Body:
I'm somewhat new to react native and expo but I've been trying to deploy a test version to my phone but can't figure out how to get it to build.

For some extra context, I built most of it in Expo and then ejected it (yes I know this isn't the best choice but I liked the features Expo provided). I ejected it because I needed NFC support which isn't currently supported in Expo so I added that in manually in Xcode after I ejected.

When I open the Xcode workspace and try to deploy it to my phone I get the following error:

Error: Failed to connect to the packager server. If you did not start this build by running 'react-native run-android', you can start the packager manually by running 'react-native start' in the project directory. (Error: Request to packager server failed: 500)
    at /Users/user/Downloads/honorProj-reactNatveFinal/honorProj/reactNative/ethelontisApp/node_modules/expo-updates/scripts/createManifest.js:40:11
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
Command PhaseScriptExecution failed with a nonzero exit code

I know it says run react-native start in the project directory (although I'm not entirely what the at /Users/... is refering too) but what really threw me was that it mentioned react-native run-android which doesn't seem like it should be related at all.

Lastly I'm completely and utterly lost with what Command PhaseScriptExecution is.

Thanks for the help.


问:
How to enable ASP.NET write access to the registry key 'HKEY_CURRENT_USER\Software\myAppKey\subdir'?
In my ASP.NET web app My.Computer.Registry.SetValue(Key_Name, Value_Name, Metric) causes "access to registry key is denied" error.

App is running on Azure Windows Server 2012 VM.
However, my .NET windows app also running on same VM, writes to registry ok.

I've tried setting regedit > the key:  to everyone=full control, still denied.

My .NET windows app on same computer (Azure Windows Server 2012 R2) writes to registry key  "HKEY_CURRENT_USER\Software\" & SOFTWARE_PROGRAM_NAME _
        & "\Metrics\" & Key_Name   without problem.

HERE IS ASP.NET CODE THAT CAUSES PROBLEM...………..

```<code>' Set the key address within the System Registry:
Key_Name = "HKEY_CURRENT_USER\Software\" & SOFTWARE_PROGRAM_NAME _
    & "\Metrics\" & Key_Name

Metric = My.Computer.Registry.GetValue(Key_Name, Value_Name, 0)  ' read present value
if metric_function = 1
    metric = 0
else if metric_function = 2
    Metric = metric_value
else
    Metric += 1                                                      ' increment it
End If
My.Computer.Registry.SetValue(Key_Name, Value_Name, Metric)      ' store new value
</code>```

HERE IS ERROR WHEN I BROWSE MY ASP.NET WEB.....

```<code>Server Error in '/' Application.

Access to the registry key 'HKEY_CURRENT_USER\Software\myApp\Metrics\WEB Communication' is denied.
Exception Details: System.UnauthorizedAccessException: Access to the registry key 'HKEY_CURRENT_USER\Software\Pray\Metrics\WEB Communication' is denied.
Source Error:

Line 152:               Metric += 1                                                      ' increment it
Line 153:           End If
Line 154:           My.Computer.Registry.SetValue(Key_Name, Value_Name, Metric)      ' store new value
Line 155:
Line 156:       ' Update the metrics display in the control pane:

Source File: C:\PRIMARY\INTERNET\APPS\DEPLOYED\myApp\myApp web\App_Code\Metrics.vb    Line: 154

Stack Trace:

[UnauthorizedAccessException: Access to the registry key 'HKEY_CURRENT_USER\Software\myApp\Metrics\WEB Communication' is denied.]
   Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str) +144
   Microsoft.Win32.RegistryKey.CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, Object registrySecurityObj, RegistryOptions registryOptions) +14824601
   Microsoft.Win32.RegistryKey.CreateSubKey(String subkey) +25
   Microsoft.Win32.Registry.SetValue(String keyName, String valueName, Object value, RegistryValueKind valueKind) +78
   Microsoft.VisualBasic.MyServices.RegistryProxy.SetValue(String keyName, String valueName, Object value) +48
   Metrics.inc(Object& Key_Name, Object& Value_Name, Object metric_function, Object metric_value) in C:\PRIMARY\INTERNET\APPS\DEPLOYED\myApp\myApp web\App_Code\Metrics.vb:154
   Metrics.Communication(Object& Value_Name, Object reset_metric) in C:\PRIMARY\INTERNET\APPS\DEPLOYED\myApp\myApp web\App_Code\Metrics.vb:88
   _Default.Page_Load(Object sender, EventArgs e) in C:\PRIMARY\INTERNET\APPS\DEPLOYED\myApp\myApp web\Default.aspx.vb:142
   System.Web.UI.Control.OnLoad(EventArgs e) +103
   System.Web.UI.Control.LoadRecursive() +68
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1381
</code>```

答: You go to your IIS pool, open advanced properties. There you probably see some default identity selected as identity for your pool. There you need to set an identity that has permissions to access file system and correspondingly, the registry. I usually create a local user with admin rights and permanent password, and then use that local admin as identity for my IIS apps. This way I don't worry if app needs to write a file, etc</p>

Body:
In my ASP.NET web app My.Computer.Registry.SetValue(Key_Name, Value_Name, Metric) causes "access to registry key is denied" error.

App is running on Azure Windows Server 2012 VM.
However, my .NET windows app also running on same VM, writes to registry ok.

I've tried setting regedit > the key:  to everyone=full control, still denied.

My .NET windows app on same computer (Azure Windows Server 2012 R2) writes to registry key  "HKEY_CURRENT_USER\Software\" & SOFTWARE_PROGRAM_NAME _
        & "\Metrics\" & Key_Name   without problem.

HERE IS ASP.NET CODE THAT CAUSES PROBLEM...………..

' Set the key address within the System Registry:
Key_Name = "HKEY_CURRENT_USER\Software\" & SOFTWARE_PROGRAM_NAME _
    & "\Metrics\" & Key_Name

Metric = My.Computer.Registry.GetValue(Key_Name, Value_Name, 0)  ' read present value
if metric_function = 1
    metric = 0
else if metric_function = 2
    Metric = metric_value
else
    Metric += 1                                                      ' increment it
End If
My.Computer.Registry.SetValue(Key_Name, Value_Name, Metric)      ' store new value

HERE IS ERROR WHEN I BROWSE MY ASP.NET WEB.....

Server Error in '/' Application.

Access to the registry key 'HKEY_CURRENT_USER\Software\myApp\Metrics\WEB Communication' is denied.
Exception Details: System.UnauthorizedAccessException: Access to the registry key 'HKEY_CURRENT_USER\Software\Pray\Metrics\WEB Communication' is denied.
Source Error:

Line 152:               Metric += 1                                                      ' increment it
Line 153:           End If
Line 154:           My.Computer.Registry.SetValue(Key_Name, Value_Name, Metric)      ' store new value
Line 155:
Line 156:       ' Update the metrics display in the control pane:

Source File: C:\PRIMARY\INTERNET\APPS\DEPLOYED\myApp\myApp web\App_Code\Metrics.vb    Line: 154

Stack Trace:

[UnauthorizedAccessException: Access to the registry key 'HKEY_CURRENT_USER\Software\myApp\Metrics\WEB Communication' is denied.]
   Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str) +144
   Microsoft.Win32.RegistryKey.CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, Object registrySecurityObj, RegistryOptions registryOptions) +14824601
   Microsoft.Win32.RegistryKey.CreateSubKey(String subkey) +25
   Microsoft.Win32.Registry.SetValue(String keyName, String valueName, Object value, RegistryValueKind valueKind) +78
   Microsoft.VisualBasic.MyServices.RegistryProxy.SetValue(String keyName, String valueName, Object value) +48
   Metrics.inc(Object& Key_Name, Object& Value_Name, Object metric_function, Object metric_value) in C:\PRIMARY\INTERNET\APPS\DEPLOYED\myApp\myApp web\App_Code\Metrics.vb:154
   Metrics.Communication(Object& Value_Name, Object reset_metric) in C:\PRIMARY\INTERNET\APPS\DEPLOYED\myApp\myApp web\App_Code\Metrics.vb:88
   _Default.Page_Load(Object sender, EventArgs e) in C:\PRIMARY\INTERNET\APPS\DEPLOYED\myApp\myApp web\Default.aspx.vb:142
   System.Web.UI.Control.OnLoad(EventArgs e) +103
   System.Web.UI.Control.LoadRecursive() +68
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1381


问:
Why is the following code throwing an exception of 0?
I'm using mariadb 10, python, and pymysql to put together a register command for my discord server.  In mariadb, I have a stored procedure that has the following syntax:

```<code>DELIMITER //

CREATE PROCEDURE registerUser(IN iUser_Name varchar(50), OUT isExists bool)
BEGIN

    IF EXISTS (SELECT 1 FROM user where user_name = iUser_Name) THEN
        SET isExists = true;
    ELSE
        SET isExists = false;
        insert into user(user_name, user_create_date) VALUES(iUser_Name, curdate());
    END IF;
END //

DELIMITER ;
</code>```

The goal of the stored procedure is to determine if the user exists, if yes, set isExists to true else false and insert the user.

In my python script, i have tried a variety of solutions based on what I found here on stackoverflow and tried to implement it but none work.  The following is the latest attempt and I'm getting the error message: Something went wrong: 0

```<code>import pymysql.cursors
...

@client.command(name="register", pass_context=True)
async def register(ctx):
    #db connection
    cnx = pymysql.connect(user='db_user'
    , password = 'pwd'
    , host='localhost'
    , database='db_name'
    , port=3306
    , cursorclass=pymysql.cursors.DictCursor)

    cursor = cnx.cursor()

    try:
        # https://stackoverflow.com/questions/24139849/mysqldb-stored-procedure-out-parameter-not-working

        cursor.callproc('registerUser', (ctx.message.author.name, 'True'))
        cursor.execute("select @_registerUser_1")
        result = cursor.fetchone()

        if result[0] == False:
            await ctx.channel.send("{}, you are all set to weekly trade.".format(ctx.message.author.mention))
        elif result[0] == True:
            await ctx.channel.send("{}, you have already registered.".format(ctx.message.author.mention))

        cnx.commit()
        cursor.close()
        cnx.close()
    except Exception as err:
        await ctx.channel.send("Something went wrong: {}".format(err))
</code>```

any suggestions to get this thing working would be greatly appreciate.

thanks.

答: This documenation suggests that you simply use the value returned by the #fetchone() call, not try to index it like an array. It seems you should be comparing if result['@_registerUser_1'] == False:, better yet if not result['@_registerUser_1']:

Body:
I'm using mariadb 10, python, and pymysql to put together a register command for my discord server.  In mariadb, I have a stored procedure that has the following syntax:

DELIMITER //

CREATE PROCEDURE registerUser(IN iUser_Name varchar(50), OUT isExists bool)
BEGIN

    IF EXISTS (SELECT 1 FROM user where user_name = iUser_Name) THEN
        SET isExists = true;
    ELSE
        SET isExists = false;
        insert into user(user_name, user_create_date) VALUES(iUser_Name, curdate());
    END IF;
END //

DELIMITER ;

The goal of the stored procedure is to determine if the user exists, if yes, set isExists to true else false and insert the user.

In my python script, i have tried a variety of solutions based on what I found here on stackoverflow and tried to implement it but none work.  The following is the latest attempt and I'm getting the error message: Something went wrong: 0

import pymysql.cursors
...

@client.command(name="register", pass_context=True)
async def register(ctx):
    #db connection
    cnx = pymysql.connect(user='db_user'
    , password = 'pwd'
    , host='localhost'
    , database='db_name'
    , port=3306
    , cursorclass=pymysql.cursors.DictCursor)

    cursor = cnx.cursor()

    try:
        # https://stackoverflow.com/questions/24139849/mysqldb-stored-procedure-out-parameter-not-working

        cursor.callproc('registerUser', (ctx.message.author.name, 'True'))
        cursor.execute("select @_registerUser_1")
        result = cursor.fetchone()

        if result[0] == False:
            await ctx.channel.send("{}, you are all set to weekly trade.".format(ctx.message.author.mention))
        elif result[0] == True:
            await ctx.channel.send("{}, you have already registered.".format(ctx.message.author.mention))

        cnx.commit()
        cursor.close()
        cnx.close()
    except Exception as err:
        await ctx.channel.send("Something went wrong: {}".format(err))

any suggestions to get this thing working would be greatly appreciate.

thanks.


问:
Is there an up to date heroku buildpack for R
I am using the virtualstaticvoid buildpack for heroku, but it is on the heroku-16 stack and only supports up to version 3.4.4 of R. I am after a buildpack that works on the latest stack (heroku-18) and supports at least version 3.6 of R, and has no outdated dependencies.  The hmdc buildpack appears to support heroku-18 and version 3.6.0 of R, but requires packrat which is soft deprecated in favour of renv.</p>

答: Some good news, virtual_static_void has been updated so the R buildpack now uses version 4.0.0, works on both heroku-18 and heroku-16 stacks, and it supports renv.


答:
In order to get the correlation by year you might want to be able to turn the dttm column into something that allows us to do equality by year. We can use the year function in lubridate for that, the code should work then.

```<code>library(lubridate)

df$year <- year(df$date)

for (y in unique(df$year)){
  df %>%
    filter(year == y) %>%
    mutate(correlation = cor(x, y)) %>%
    print(unique(correlation))
}
</code>```

Alternatively we can be a little more succinct and do the following transformation with a group_by.

```<code>yearDf <- df %>%
  group_by(year) %>%
  summarize(correlation = cor(x, y))

print(yearDf)
</code>```

Title: How can I simplify a correlation code in R?

Body:
This is my df:

                  date                     z         x                    y
   <dttm>                               <dbl>    <dbl>                <dbl>
 1 2019-01-01 00:00:00                   1333  3339072.         456700000000
 2 2019-02-01 00:00:00                    915  4567582.         904600000000
 3 2019-03-01 00:00:00                   1433  7887962.         247900000000
 4 2019-04-01 00:00:00                   1444  3454559.         905700000000
 5 2019-05-01 00:00:00                   1231  9082390.         245600000000
 6 2019-06-01 00:00:00                    346   781224.         346700000000

How can I simplify this code to a for loop?

df %>%
filter(year(df$date) == 2017) %>%
mutate(correlation = cor(x, y))

df %>%
filter(year(df$date) == 2018) %>%
mutate(correlation = cor(x, y))

df %>%
filter(year(df$date) == 2019) %>%
mutate(correlation = cor(x, y))

df %>%
filter(year(df$date) == 2020) %>%
mutate(correlation = cor(x, y))

That's what I tried so far, but I've got some NAs:

years <- c(2017, 2018, 2019, 2020)
for (y in years) {
  df %>%
    filter(date == y) %>%
    mutate(correlation = cor(x, y))
    print(df$correlation[y])
}

My desired output would be something like

[1] 2017: 0.23
[1] 2018: -0.38
[1] 2019: 0.40
[1] 2020: 0.15

Body:
In order to get the correlation by year you might want to be able to turn the dttm column into something that allows us to do equality by year. We can use the year function in lubridate for that, the code should work then.

library(lubridate)

df$year <- year(df$date)

for (y in unique(df$year)){
  df %>%
    filter(year == y) %>%
    mutate(correlation = cor(x, y)) %>%
    print(unique(correlation))
}

Alternatively we can be a little more succinct and do the following transformation with a group_by.

yearDf <- df %>%
  group_by(year) %>%
  summarize(correlation = cor(x, y))

print(yearDf)


问:
How to set a variable from another yaml file in azure-pipeline.yml
I have an environment.yml shown as follow, I would like to read out the content of the name variable (core-force) and set it as a value of the global variable in my azure-pipeline.yamal file how can I do it?

```<code>name: core-force
channels:
  - conda-forge
dependencies:
  - click
  - Sphinx
  - sphinx_rtd_theme
  - numpy
  - pylint
  - azure-cosmos
  - python=3
  - flask
  - pytest
  - shapely
</code>```

in my azure-pipeline.yml file I would like to have something like

```<code>variables:
  tag: get the value of the name from the environment.yml aka 'core-force'
</code>```

答:
Global variables should be stored in a separate template file.  This file ideally would be in a separate repo where other repos can refer to this.

Here is another answer for this

Body:
I have an environment.yml shown as follow, I would like to read out the content of the name variable (core-force) and set it as a value of the global variable in my azure-pipeline.yamal file how can I do it?

name: core-force
channels:
  - conda-forge
dependencies:
  - click
  - Sphinx
  - sphinx_rtd_theme
  - numpy
  - pylint
  - azure-cosmos
  - python=3
  - flask
  - pytest
  - shapely

in my azure-pipeline.yml file I would like to have something like

variables:
  tag: get the value of the name from the environment.yml aka 'core-force'


问:
amCharts 4: External Data Source
I'm struggling to generate a simple XY horizontal bar chart in amCharts 4 using an external data source.

Everything works fine with static data (where I adapted one of the chart demos from the amCharts documentation).

But when I replace the static data with the external dataSource URL, the chart won't generate.

I suspect that the problem might be the Airtable JSON output is a different structure to the static data.

However, I could be completely wrong on that suspicion, so I'd really appreciate any help to a solution please.

(I've obviously XXX'd out the Airtable information in the code below.)

Static Data Source

```<code>// Create chart instance
var chart = am4core.create("CHARTDIV", am4charts.XYChart);

// Add data
chart.data = [{
  "Name": "Brand Guidelines",
  "Aggregate Responses": 7
}, {
  "Name": "SAP",
  "Aggregate Responses": 3
}, {
  "Name": "Email",
  "Aggregate Responses": 5
}, {
  "Name": "Social Media",
  "Aggregate Responses": 3
}, {
  "Name": "Google Drive",
  "Aggregate Responses": 3
}, {
  "Name": "OneDrive",
  "Aggregate Responses": 4
}, {
  "Name": "SharePoint",
  "Aggregate Responses": 1
}, {
  "Name": "Slack",
  "Aggregate Responses": 3
}, {
  "Name": "Drupal",
  "Aggregate Responses": 2
}, {
  "Name": "Telephone",
  "Aggregate Responses": 3
}];

// Create axes

var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "Name";
categoryAxis.renderer.grid.template.location = 0;
categoryAxis.renderer.minGridDistance = 30;

var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());

// Create series
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueX = "Aggregate Responses";
series.dataFields.categoryY = "Name";
series.name = "Aggregate Responses";
series.columns.template.tooltipText = "{categoryY}: [bold]{valueX}[/]";
series.columns.template.fillOpacity = .8;

var columnTemplate = series.columns.template;
columnTemplate.strokeWidth = 2;
columnTemplate.strokeOpacity = 1;
</code>```

External Data Source

```<code>// Create chart instance
var chart = am4core.create("CHARTDIV", am4charts.XYChart);

// External data source
chart.dataSource.url = "https://api.airtable.com/v0/appXXXXXXX/airtable-table-name?api_key=keyXXXXXXX";

// Create axes

var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "Name";
categoryAxis.renderer.grid.template.location = 0;
categoryAxis.renderer.minGridDistance = 30;

var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());

// Create series
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueX = "Aggregate Responses";
series.dataFields.categoryY = "Name";
series.name = "Aggregate Responses";
series.columns.template.tooltipText = "{categoryY}: [bold]{valueX}[/]";
series.columns.template.fillOpacity = .8;

var columnTemplate = series.columns.template;
columnTemplate.strokeWidth = 2;
columnTemplate.strokeOpacity = 1;
</code>```

Airtable JSON Output

```<code>{
  "records": [
    {
      "id": "recXXXXXX",
      "fields": {
        "Name": "EpiServer",
        "Typeform Responses": [
          "recXXXXXX",
          "recXXXXXX",
          "recXXXXXX"
        ],
        "Aggregate Responses": 3
      },
      "createdTime": "2020-05-22T16:11:01.000Z"
    },
    {
      "id": "recXXXXXX",
      "fields": {
        "Name": "OneDrive",
        "Typeform Responses": [
          "recXXXXXX",
          "recXXXXXX",
          "recXXXXXX",
          "recXXXXXX"
        ],
        "Aggregate Responses": 4
      },
      "createdTime": "2020-05-22T16:50:41.000Z"
    },
  ]
}
</code>```

答:
Your suspicion about the format being different is the right one. AmCharts needs a simple, flattened array of objects where it can find the fields you've specified, so you'll need to convert your external data into a format that AmCharts can accept. You can use the parseended event to re-map your data like so:

```<code>    chart.dataSource.events.on("parseended", function(ev) {
      // parsed data is assigned to data source's `data` property
      // pluck data from the records array in your raw data
      ev.target.data = ev.target.data.records.map(function(dataItem) {
        return {
          "Aggregate Responses": dataItem.fields["Aggregate Responses"],
          "Name": dataItem.fields.Name
        }
      });
    });
</code>```

Example below using your code and a base64 encoded data URL of your sample data as demonstration:

// Create chart instance
var chart = am4core.create("CHARTDIV", am4charts.XYChart);

// External data source
//chart.dataSource.url = "https://api.airtable.com/v0/appXXXXXXX/airtable-table-name?api_key=keyXXXXXXX";
chart.dataSource.url = dataURI(); //fake URL for demonstration purposes
chart.dataSource.events.on("parseended", function(ev) {
  // parsed data is assigned to data source's `data` property
  ev.target.data = ev.target.data.records.map(function(dataItem) {
    return {
      "Aggregate Responses": dataItem.fields["Aggregate Responses"],
      "Name": dataItem.fields.Name
    }
  });
});

// Create axes

var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "Name";
categoryAxis.renderer.grid.template.location = 0;
categoryAxis.renderer.minGridDistance = 30;

var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());

// Create series
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueX = "Aggregate Responses";
series.dataFields.categoryY = "Name";
series.name = "Aggregate Responses";
series.columns.template.tooltipText = "{categoryY}: [bold]{valueX}[/]";
series.columns.template.fillOpacity = .8;

var columnTemplate = series.columns.template;
columnTemplate.strokeWidth = 2;
columnTemplate.strokeOpacity = 1;

// base64 encoded version of sample data as a data URI
function dataURI() {
  return "data:application/json;base64,eyAicmVjb3JkcyI6IFsgeyAiaWQiOiAicmVjWFhYWFhYIiwgImZpZWxkcyI6IHsgIk5hbWUiOiAiRXBpU2VydmVyIiwgIlR5cGVmb3JtIFJlc3BvbnNlcyI6IFsgInJlY1hYWFhYWCIsICJyZWNYWFhYWFgiLCAicmVjWFhYWFhYIiBdLCAiQWdncmVnYXRlIFJlc3BvbnNlcyI6IDMgfSwgImNyZWF0ZWRUaW1lIjogIjIwMjAtMDUtMjJUMTY6MTE6MDEuMDAwWiIgfSwgeyAiaWQiOiAicmVjWFhYWFhYIiwgImZpZWxkcyI6IHsgIk5hbWUiOiAiT25lRHJpdmUiLCAiVHlwZWZvcm0gUmVzcG9uc2VzIjogWyAicmVjWFhYWFhYIiwgInJlY1hYWFhYWCIsICJyZWNYWFhYWFgiLCAicmVjWFhYWFhYIiBdLCAiQWdncmVnYXRlIFJlc3BvbnNlcyI6IDQgfSwgImNyZWF0ZWRUaW1lIjogIjIwMjAtMDUtMjJUMTY6NTA6NDEuMDAwWiIgfSBdIH0=";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//www.amcharts.com/lib/4/core.js"></script>
<script src="//www.amcharts.com/lib/4/charts.js"></script>
<div id="CHARTDIV" style="width: 100%; height: 98vh"></div></code>```

Make sure your data is valid JSON as your sample has an incorrect trailing comma.

Title: amCharts 4: External Data Source

Body:
I'm struggling to generate a simple XY horizontal bar chart in amCharts 4 using an external data source.

Everything works fine with static data (where I adapted one of the chart demos from the amCharts documentation).

But when I replace the static data with the external dataSource URL, the chart won't generate.

I suspect that the problem might be the Airtable JSON output is a different structure to the static data.

However, I could be completely wrong on that suspicion, so I'd really appreciate any help to a solution please.

(I've obviously XXX'd out the Airtable information in the code below.)

Static Data Source

// Create chart instance
var chart = am4core.create("CHARTDIV", am4charts.XYChart);

// Add data
chart.data = [{
  "Name": "Brand Guidelines",
  "Aggregate Responses": 7
}, {
  "Name": "SAP",
  "Aggregate Responses": 3
}, {
  "Name": "Email",
  "Aggregate Responses": 5
}, {
  "Name": "Social Media",
  "Aggregate Responses": 3
}, {
  "Name": "Google Drive",
  "Aggregate Responses": 3
}, {
  "Name": "OneDrive",
  "Aggregate Responses": 4
}, {
  "Name": "SharePoint",
  "Aggregate Responses": 1
}, {
  "Name": "Slack",
  "Aggregate Responses": 3
}, {
  "Name": "Drupal",
  "Aggregate Responses": 2
}, {
  "Name": "Telephone",
  "Aggregate Responses": 3
}];

// Create axes

var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "Name";
categoryAxis.renderer.grid.template.location = 0;
categoryAxis.renderer.minGridDistance = 30;

var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());

// Create series
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueX = "Aggregate Responses";
series.dataFields.categoryY = "Name";
series.name = "Aggregate Responses";
series.columns.template.tooltipText = "{categoryY}: [bold]{valueX}[/]";
series.columns.template.fillOpacity = .8;

var columnTemplate = series.columns.template;
columnTemplate.strokeWidth = 2;
columnTemplate.strokeOpacity = 1;

External Data Source

// Create chart instance
var chart = am4core.create("CHARTDIV", am4charts.XYChart);

// External data source
chart.dataSource.url = "https://api.airtable.com/v0/appXXXXXXX/airtable-table-name?api_key=keyXXXXXXX";

// Create axes

var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "Name";
categoryAxis.renderer.grid.template.location = 0;
categoryAxis.renderer.minGridDistance = 30;

var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());

// Create series
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueX = "Aggregate Responses";
series.dataFields.categoryY = "Name";
series.name = "Aggregate Responses";
series.columns.template.tooltipText = "{categoryY}: [bold]{valueX}[/]";
series.columns.template.fillOpacity = .8;

var columnTemplate = series.columns.template;
columnTemplate.strokeWidth = 2;
columnTemplate.strokeOpacity = 1;

Airtable JSON Output

{
  "records": [
    {
      "id": "recXXXXXX",
      "fields": {
        "Name": "EpiServer",
        "Typeform Responses": [
          "recXXXXXX",
          "recXXXXXX",
          "recXXXXXX"
        ],
        "Aggregate Responses": 3
      },
      "createdTime": "2020-05-22T16:11:01.000Z"
    },
    {
      "id": "recXXXXXX",
      "fields": {
        "Name": "OneDrive",
        "Typeform Responses": [
          "recXXXXXX",
          "recXXXXXX",
          "recXXXXXX",
          "recXXXXXX"
        ],
        "Aggregate Responses": 4
      },
      "createdTime": "2020-05-22T16:50:41.000Z"
    },
  ]
}

Body:
Your suspicion about the format being different is the right one. AmCharts needs a simple, flattened array of objects where it can find the fields you've specified, so you'll need to convert your external data into a format that AmCharts can accept. You can use the parseended event to re-map your data like so:

    chart.dataSource.events.on("parseended", function(ev) {
      // parsed data is assigned to data source's `data` property
      // pluck data from the records array in your raw data
      ev.target.data = ev.target.data.records.map(function(dataItem) {
        return {
          "Aggregate Responses": dataItem.fields["Aggregate Responses"],
          "Name": dataItem.fields.Name
        }
      });
    });

Example below using your code and a base64 encoded data URL of your sample data as demonstration:

// Create chart instance
var chart = am4core.create("CHARTDIV", am4charts.XYChart);

// External data source
//chart.dataSource.url = "https://api.airtable.com/v0/appXXXXXXX/airtable-table-name?api_key=keyXXXXXXX";
chart.dataSource.url = dataURI(); //fake URL for demonstration purposes
chart.dataSource.events.on("parseended", function(ev) {
  // parsed data is assigned to data source's `data` property
  ev.target.data = ev.target.data.records.map(function(dataItem) {
    return {
      "Aggregate Responses": dataItem.fields["Aggregate Responses"],
      "Name": dataItem.fields.Name
    }
  });
});

// Create axes

var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "Name";
categoryAxis.renderer.grid.template.location = 0;
categoryAxis.renderer.minGridDistance = 30;

var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());

// Create series
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueX = "Aggregate Responses";
series.dataFields.categoryY = "Name";
series.name = "Aggregate Responses";
series.columns.template.tooltipText = "{categoryY}: [bold]{valueX}[/]";
series.columns.template.fillOpacity = .8;

var columnTemplate = series.columns.template;
columnTemplate.strokeWidth = 2;
columnTemplate.strokeOpacity = 1;

// base64 encoded version of sample data as a data URI
function dataURI() {
  return "data:application/json;base64,eyAicmVjb3JkcyI6IFsgeyAiaWQiOiAicmVjWFhYWFhYIiwgImZpZWxkcyI6IHsgIk5hbWUiOiAiRXBpU2VydmVyIiwgIlR5cGVmb3JtIFJlc3BvbnNlcyI6IFsgInJlY1hYWFhYWCIsICJyZWNYWFhYWFgiLCAicmVjWFhYWFhYIiBdLCAiQWdncmVnYXRlIFJlc3BvbnNlcyI6IDMgfSwgImNyZWF0ZWRUaW1lIjogIjIwMjAtMDUtMjJUMTY6MTE6MDEuMDAwWiIgfSwgeyAiaWQiOiAicmVjWFhYWFhYIiwgImZpZWxkcyI6IHsgIk5hbWUiOiAiT25lRHJpdmUiLCAiVHlwZWZvcm0gUmVzcG9uc2VzIjogWyAicmVjWFhYWFhYIiwgInJlY1hYWFhYWCIsICJyZWNYWFhYWFgiLCAicmVjWFhYWFhYIiBdLCAiQWdncmVnYXRlIFJlc3BvbnNlcyI6IDQgfSwgImNyZWF0ZWRUaW1lIjogIjIwMjAtMDUtMjJUMTY6NTA6NDEuMDAwWiIgfSBdIH0=";
}

<script src="//www.amcharts.com/lib/4/core.js"></script>
<script src="//www.amcharts.com/lib/4/charts.js"></script>
<div id="CHARTDIV" style="width: 100%; height: 98vh"></div>

Make sure your data is valid JSON as your sample has an incorrect trailing comma.


问:
setState hook not updating after fetch with HTTP PUT
So I'm trying out basic todo app with edit and delete feature. I'm having problems with my edit feature. I have two main components in my app namely InputTodo for adding todo items and ListTodo which contains two additional subcomponents (TodoItem for each todo and EditTodo which shows an editor for a selected todo). Whenever the Edit Button inside a certain TodoItem is clicked, the EditTodo component is showed. When the Confirm button in EditTodo component is clicked, a PUT request will be sent to update the database (PostgreSQL in this case) through Node. After successfully  sending this send request, I would like to re-render the list of TodoItem components. I'm doing this by fetching the updated list of values from the database through a different GET request then calling setState given the response from the GET request. However, the GET request's response doesn't reflect the PUT request done earlier. Thus, the app still renders the un-updated list of todos from the database.

Here are some code snippets

```<code>const ListTodo = (props) => {
  const [todos, setTodos] = useState([]);
  const [editorOpen, setEditorOpen] = useState(false);
  const [selectedId, setSelectedId] = useState();

  const getTodos = async () => {
    console.log('getTodos() called');
    try {
      const response = await fetch("http://localhost:5000/todos");
      const jsonData = await response.json();
      setTodos(jsonData);
      console.log(todos);
    } catch (err) {
      console.error(err.message);
    }
    console.log('getTodos() finished');
  };
const editTodo = async description_string => {
    console.log('editTodo() called');
    try {
      const body = { description: description_string };
      const response = await fetch(
        `http://localhost:5000/todos/${selectedId}`,
        {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body)
        }
      );
      console.log(response);
      await getTodos();
      props.handleListModified();
    } catch (err) {
      console.error(err.message);
    }
    console.log('editTodo() finised');
  }

  const handleItemButtonClick = (button, row_key) => {
    if (button === 'delete') {
      deleteTodo(row_key);
      setEditorOpen(false);
    } else if (button === 'edit') {
      setEditorOpen(true);
      setSelectedId(row_key);
      console.log(todos.filter(todo => { return todo.todo_id === row_key})[0].description);
    }
  };
  const handleEditorButtonClick = async (button, description_string) => {
    if (button === 'cancel') {
      setSelectedId(null);
    } else if (button === 'confirm') {
      await editTodo(description_string);
    }
    setEditorOpen(false);
  };

  useEffect(() => {
    console.log('ListTodo useEffect() trigerred');
    getTodos();
  }, [props.listModified]);

  return(
    <Fragment>
      <table>
        <tbody>
          {todos.map( todo => (
            <TodoItem
              key={todo.todo_id}
              todo_id={todo.todo_id}
              description={todo.description}

              handleClick={handleItemButtonClick} />
          ))}
        </tbody>
      </table>
      { editorOpen &&
        <EditTodo
          handleEditorButtonClick={handleEditorButtonClick}

          description={todos.filter(todo => { return todo.todo_id === selectedId})[0].description}
          selectedId={selectedId} /> }
    </Fragment>
  );
};
</code>```

答:
I guess that the problem is - In editTodo function, you are calling getTodos() function. But, you are not updating the state with the response you get. See if this helps.

```<code>  const response = await fetch(
    `http://localhost:5000/todos/${selectedId}`,
    {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body)
    }
  );
  console.log(response);
  setTodo(await getTodos()); // Update the state with the values from fetch
</code>```

Body:
So I'm trying out basic todo app with edit and delete feature. I'm having problems with my edit feature. I have two main components in my app namely InputTodo for adding todo items and ListTodo which contains two additional subcomponents (TodoItem for each todo and EditTodo which shows an editor for a selected todo). Whenever the Edit Button inside a certain TodoItem is clicked, the EditTodo component is showed. When the Confirm button in EditTodo component is clicked, a PUT request will be sent to update the database (PostgreSQL in this case) through Node. After successfully  sending this send request, I would like to re-render the list of TodoItem components. I'm doing this by fetching the updated list of values from the database through a different GET request then calling setState given the response from the GET request. However, the GET request's response doesn't reflect the PUT request done earlier. Thus, the app still renders the un-updated list of todos from the database.

Here are some code snippets

const ListTodo = (props) => {
  const [todos, setTodos] = useState([]);
  const [editorOpen, setEditorOpen] = useState(false);
  const [selectedId, setSelectedId] = useState();

  const getTodos = async () => {
    console.log('getTodos() called');
    try {
      const response = await fetch("http://localhost:5000/todos");
      const jsonData = await response.json();
      setTodos(jsonData);
      console.log(todos);
    } catch (err) {
      console.error(err.message);
    }
    console.log('getTodos() finished');
  };
const editTodo = async description_string => {
    console.log('editTodo() called');
    try {
      const body = { description: description_string };
      const response = await fetch(
        `http://localhost:5000/todos/${selectedId}`,
        {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body)
        }
      );
      console.log(response);
      await getTodos();
      props.handleListModified();
    } catch (err) {
      console.error(err.message);
    }
    console.log('editTodo() finised');
  }

  const handleItemButtonClick = (button, row_key) => {
    if (button === 'delete') {
      deleteTodo(row_key);
      setEditorOpen(false);
    } else if (button === 'edit') {
      setEditorOpen(true);
      setSelectedId(row_key);
      console.log(todos.filter(todo => { return todo.todo_id === row_key})[0].description);
    }
  };
  const handleEditorButtonClick = async (button, description_string) => {
    if (button === 'cancel') {
      setSelectedId(null);
    } else if (button === 'confirm') {
      await editTodo(description_string);
    }
    setEditorOpen(false);
  };

  useEffect(() => {
    console.log('ListTodo useEffect() trigerred');
    getTodos();
  }, [props.listModified]);

  return(
    <Fragment>

          {todos.map( todo => (
            <TodoItem
              key={todo.todo_id}
              todo_id={todo.todo_id}
              description={todo.description}

              handleClick={handleItemButtonClick} />
          ))}

      { editorOpen &&
        <EditTodo
          handleEditorButtonClick={handleEditorButtonClick}

          description={todos.filter(todo => { return todo.todo_id === selectedId})[0].description}
          selectedId={selectedId} /> }
    </Fragment>
  );
};

Body:
I guess that the problem is - In editTodo function, you are calling getTodos() function. But, you are not updating the state with the response you get. See if this helps.

  const response = await fetch(
    `http://localhost:5000/todos/${selectedId}`,
    {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body)
    }
  );
  console.log(response);
  setTodo(await getTodos()); // Update the state with the values from fetch


问:
SQL Count Totals Within Date Ranges
I have a CHANGES table with fields VALUE(integer) and CREATED_AT(timestamp). I want to know the total of the VALUE column grouped by each of the past 30 days (without making 30 queries).

So if yesterday there were records created with VALUEs of 10, -7, and 12; I would want a record returned with CREATED_AT = yesterday and TOTAL = 15.

Any help?

答:
Well, it slightly depends on what kind the timestamp is formatted in (SQL/ Unix/ etc). But this type of query might help you along:</p>

```<code>SELECT
   DATE_FORMAT(CREATED_AT, '%Y-%m-%d') ym,
   COUNT(VALUE)
FROM foo
GROUP BY ym
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL Count Totals Within Date Ranges

Body:
Well, it slightly depends on what kind the timestamp is formatted in (SQL/ Unix/ etc). But this type of query might help you along:

SELECT
   DATE_FORMAT(CREATED_AT, '%Y-%m-%d') ym,
   COUNT(VALUE)
FROM foo
GROUP BY ym


问:
SpreadsheetApp.getUi().alert() caught as an exception when script run by FormSubmit; Fine when run interactively
The below is the code that despite the ui.alert("Some message") code being run only when SpreadsheetApp.getUi() can get the UI (when run interactively) fails with error TypeError: Cannot read property 'alert' of undefined at sendEmails(E-mail form submissions:76:32)

```<code>var DisplayAlerts = 0

// See if getUi will load; If not, we are likely not running this script interactively, so disable prompts
try
{
  var ui = SpreadsheetApp.getUi();
}
catch(err)
{
  DisplayAlerts = 1
}

if(DisplayAlerts){ui.alert("E-mail(s) sent");}
</code>```

The script at https://xfanatical.com/blog/how-to-edit-google-forms-responses-in-the-spreadsheet/ utilise SpreadsheetApp.getUi().alert() and runs interactively (producing the prompt at line 119) and via formsubmit trigger. What is the difference in that script to my login above? What do I need to do to not have two different scripts doing the same thing bar popping up alerts when running interactively?

答:
I found that if run it this way:

```<code>var DisplayAlerts =true;
try{
  var ui = SpreadsheetApp.getUi();
}
catch(err) {
  DisplayAlerts = false;
}
if(DisplayAlerts){ui.alert("E-mail(s) sent");}
</code>```

It doesn't get the alert on the formSubmit because it's opening up a Spreadsheet instance on the server which does have any UI.  And when I run another script from the script editor the alert fires correctly because it runs every time you run a function and I opened the container spreadsheet so it has a UI.

So I think the problem is that you have your 0 and 1 or true and false reversed.

Body:
The below is the code that despite the ui.alert("Some message") code being run only when SpreadsheetApp.getUi() can get the UI (when run interactively) fails with error TypeError: Cannot read property 'alert' of undefined at sendEmails(E-mail form submissions:76:32)

var DisplayAlerts = 0

// See if getUi will load; If not, we are likely not running this script interactively, so disable prompts
try
{
  var ui = SpreadsheetApp.getUi();
}
catch(err)
{
  DisplayAlerts = 1
}

if(DisplayAlerts){ui.alert("E-mail(s) sent");}

The script at https://xfanatical.com/blog/how-to-edit-google-forms-responses-in-the-spreadsheet/ utilise SpreadsheetApp.getUi().alert() and runs interactively (producing the prompt at line 119) and via formsubmit trigger. What is the difference in that script to my login above? What do I need to do to not have two different scripts doing the same thing bar popping up alerts when running interactively?

Body:
I found that if run it this way:

var DisplayAlerts =true;
try{
  var ui = SpreadsheetApp.getUi();
}
catch(err) {
  DisplayAlerts = false;
}
if(DisplayAlerts){ui.alert("E-mail(s) sent");}

It doesn't get the alert on the formSubmit because it's opening up a Spreadsheet instance on the server which does have any UI.  And when I run another script from the script editor the alert fires correctly because it runs every time you run a function and I opened the container spreadsheet so it has a UI.

So I think the problem is that you have your 0 and 1 or true and false reversed.


问:
Get last 12 months of data grouped by month even if 0
I am trying to get a COUNT of the last 12 months of appointments grouped by month for output into a chart.  The following works fine but I need it to return 0 if no results for each month.

```<code>$query = "SELECT COUNT(id) as total_month FROM appointments WHERE created >= DATE(NOW()) - INTERVAL 365 DAY GROUP BY Month(created)";
    $query = $mysqli->real_escape_string($query);
      if($result = $mysqli->query($query)){
        while($row = $result->fetch_array())
          {
          $month_total_appointments .= $row['total_month'].',';
        }
      }

echo $month_total_appointments;

================================================================
    Simple table structure and example for appointments Table
    id    customer_name    created

    1     John             2020-05-01 08:00:00 <= stored as datetime
    2     Mike             2020-04-01 09:00:00
    3     Steve            2020-02-01 10:00:00

    Output would be 0,0,0,0,0,0,0,0,1,0,1,1
======================================================
</code>```

Current output is: 1,1,1

I've read some use a month table and LEFT JOIN but everything i've tried doesn't seem to work.  Can anyone help please?

答:
You won't get zeroes for rows that aren't there. Grouping combines rows that match particular criteria, but it can't fabricate them out of nothing.

That's why it's typical to include the grouping criteria in the results:

```<code>SELECT COUNT(id), MONTH(created) AS created_month
  FROM appointments
  WHERE created >= DATE(NOW()) - INTERVAL 365 DAY
  GROUP BY created_month
</code>```

Then you can expand that in your application code to fill in the missing values. The alternative is you need a fully populated list of all possible dates to JOIN against.

Keep in mind the MONTH() thing will wrap around and group January 2020 with January 2021. You may want to split this up:

```<code>SELECT COUNT(id), YEAR(created) AS created_year, MONTH(created) AS created_month
  FROM appointments
  WHERE created >= DATE(NOW()) - INTERVAL 365 DAY
  GROUP BY created_year, created_month
</code>```

Body:
I am trying to get a COUNT of the last 12 months of appointments grouped by month for output into a chart.  The following works fine but I need it to return 0 if no results for each month.

$query = "SELECT COUNT(id) as total_month FROM appointments WHERE created >= DATE(NOW()) - INTERVAL 365 DAY GROUP BY Month(created)";
    $query = $mysqli->real_escape_string($query);
      if($result = $mysqli->query($query)){
        while($row = $result->fetch_array())
          {
          $month_total_appointments .= $row['total_month'].',';
        }
      }

echo $month_total_appointments;

================================================================
    Simple table structure and example for appointments Table
    id    customer_name    created

    1     John             2020-05-01 08:00:00 <= stored as datetime
    2     Mike             2020-04-01 09:00:00
    3     Steve            2020-02-01 10:00:00

    Output would be 0,0,0,0,0,0,0,0,1,0,1,1
======================================================

Current output is: 1,1,1

I've read some use a month table and LEFT JOIN but everything i've tried doesn't seem to work.  Can anyone help please?

Body:
You won't get zeroes for rows that aren't there. Grouping combines rows that match particular criteria, but it can't fabricate them out of nothing.

That's why it's typical to include the grouping criteria in the results:

SELECT COUNT(id), MONTH(created) AS created_month
  FROM appointments
  WHERE created >= DATE(NOW()) - INTERVAL 365 DAY
  GROUP BY created_month

Then you can expand that in your application code to fill in the missing values. The alternative is you need a fully populated list of all possible dates to JOIN against.

Keep in mind the MONTH() thing will wrap around and group January 2020 with January 2021. You may want to split this up:

SELECT COUNT(id), YEAR(created) AS created_year, MONTH(created) AS created_month
  FROM appointments
  WHERE created >= DATE(NOW()) - INTERVAL 365 DAY
  GROUP BY created_year, created_month


问:
jQuery width() not returning correct value on a div with generated content
With the code below, the alert doesn't return the actual size of #main, it always returns the value of #main's css width with the % dropped.  So in this case I get 95 in the alert.  If I alert parent().width() I get 100.

The data returned from the .get() call is a ul that sometimes is wider than #main, and sometimes not.  The width of the content doesn't seem to have any bearing on what .width() returns.

So my question is, how do I get the true pixel width of #main?

CSS:

```<code>#container {
    width: 100%;
}

#main {
    width: 95%;
    overflow: hidden;
}
</code>```

HTML:

```<code><div id="conatiner">
    <div id="main"></div>
</div>
</code>```

Javascript/jQuery:

```<code>$.get('page.php', function(result) {
    $('#main').html(result);
});
alert($('#main').width();
</code>```

答: I can't seem to replicate this behavior.  Perhaps someone overrode jQuery.fn.width() with an implementation that returns the value as a percentage?  I'd debug in Firebug or similar and inspect that function to be sure.

Body:
With the code below, the alert doesn't return the actual size of #main, it always returns the value of #main's css width with the % dropped.  So in this case I get 95 in the alert.  If I alert parent().width() I get 100.

The data returned from the .get() call is a ul that sometimes is wider than #main, and sometimes not.  The width of the content doesn't seem to have any bearing on what .width() returns.

So my question is, how do I get the true pixel width of #main?

CSS:

#container {
    width: 100%;
}

#main {
    width: 95%;
    overflow: hidden;
}

HTML:

Javascript/jQuery:

$.get('page.php', function(result) {
    $('#main').html(result);
});
alert($('#main').width();


问:
Python calendar with loops
```<code>days = int(input("Enter number of days: "))
day_of_week = input("The first day of the week: ")

print("{:>3}{:>3}{:>3}{:>3}{:>3}{:>3}{:>3}".format("S","M","T","W","Th","F","S"))

for d in range(1, days + 1):
  print("{:3}".format(d),end="")
  if (d %  7 == 0):
    print()
</code>```

Here's my output:

I'm confused... What should I add so that the first day of the week is my input's?

答:
```<code>days_of_week = ["S","M","T","W","Th","F","St"]

days = int(input("Enter number of days: "))
day_of_week = input("The first day of the week: ")

index = days_of_week.index(day_of_week)
new_days_of_week = days_of_week[index:]+days_of_week[:index]

print("{:>3}{:>3}{:>3}{:>3}{:>3}{:>3}{:>3}".format(*new_days_of_week))

for d in range(1, days + 1):
  print("{:3}".format(d),end="")
  if (d %  7 == 0):
    print()

Output

Enter number of days: 31
The first day of the week: Th
 Th  F St  S  M  T  W
  1  2  3  4  5  6  7
  8  9 10 11 12 13 14
 15 16 17 18 19 20 21
 22 23 24 25 26 27 28
 29 30 31
</code>```

Title: Python calendar with loops

Body:
days = int(input("Enter number of days: "))
day_of_week = input("The first day of the week: ")

print("{:>3}{:>3}{:>3}{:>3}{:>3}{:>3}{:>3}".format("S","M","T","W","Th","F","S"))

for d in range(1, days + 1):
  print("{:3}".format(d),end="")
  if (d %  7 == 0):
    print()

Here's my output:

I'm confused... What should I add so that the first day of the week is my input's?


问:
How can I reject user registration with certain username in default laravel register form?
I'm trying to block users from using certain names like 'admin' or 'operator'.

I've tried fiddling with both Controllers/Auth/RegisterController and Controller/RegisterController but failed.

What I've tried was something like this:

```<code>in Controllers/Auth/RegisterController,

if ($data['name'] === 'admin' || $data['name'] === 'operator') {
             return redirect()->back()->withErrors(['Invalid username']);
        }
else {
    session()->flash('message', 'Welcome!');

    return User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => Hash::make($data['password']),
            ]);
        }
</code>```

The code above gave me this error:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an
  instance of Illuminate\Contracts\Auth\Authenticatable, string given,
  called in /var/www/vendor/laravel/ui/auth-backend/RegistersUsers.php
  on line 36

I've also searched whether validators can block specific words but failed.
I know I can work this around by using JS, but I think Laravel would have some function like this.

答:
You can try to validate if requested name is not in the list of predefined blocked names:

```<code>use Illuminate\Validation\Rule;

Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['admin', 'superuser']),//etc..
    ],
]);
</code>```

Hope it helps.

Body:
I'm trying to block users from using certain names like 'admin' or 'operator'.

I've tried fiddling with both Controllers/Auth/RegisterController and Controller/RegisterController but failed.

What I've tried was something like this:

in Controllers/Auth/RegisterController,

if ($data['name'] === 'admin' || $data['name'] === 'operator') {
             return redirect()->back()->withErrors(['Invalid username']);
        }
else {
    session()->flash('message', 'Welcome!');

    return User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => Hash::make($data['password']),
            ]);
        }

The code above gave me this error:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an
  instance of Illuminate\Contracts\Auth\Authenticatable, string given,
  called in /var/www/vendor/laravel/ui/auth-backend/RegistersUsers.php
  on line 36

I've also searched whether validators can block specific words but failed.
I know I can work this around by using JS, but I think Laravel would have some function like this.

Body:
You can try to validate if requested name is not in the list of predefined blocked names:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['admin', 'superuser']),//etc..
    ],
]);

Hope it helps.


问:
what is the scope of this variable in c++?
If i define a function like this

```<code>std::string& returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}
</code>```

and if i use this temp which is passed by reference to another function like this

```<code>void displaystring(std::string &temp)
{
    std::cout<<temp;
}
</code>```

would the string temp still be in scope when i pass it by reference to displaystring function?

答:
Nope since the temp variable is local to the returnstring function and once the code is out of the retuernstring function the temp variable is no longer valid.
If at all you want to send the reference and get the answer then better option is to send the argument by reference as below,

```<code>void copyLineAsString(std::istringstream &ist, std::string& tempString)
{
    std::getline(ist,tempString);
    return;
}
</code>```

I have few other suggestions to your code for the good coding practice,
Never use the '&' for the return type / return a variable by reference. Use camel casing or _ separator for the function names(Ex returnString or return_string).

Body:
If i define a function like this

std::string& returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}

and if i use this temp which is passed by reference to another function like this

void displaystring(std::string &temp)
{
    std::cout<<temp;
}

would the string temp still be in scope when i pass it by reference to displaystring function?

Body:
Nope since the temp variable is local to the returnstring function and once the code is out of the retuernstring function the temp variable is no longer valid.
If at all you want to send the reference and get the answer then better option is to send the argument by reference as below,

void copyLineAsString(std::istringstream &ist, std::string& tempString)
{
    std::getline(ist,tempString);
    return;
}

I have few other suggestions to your code for the good coding practice,
Never use the '&' for the return type / return a variable by reference. Use camel casing or _ separator for the function names(Ex returnString or return_string).


问:
Codeigniter: Unknown column 'stud.id' in 'where clause'
I encounter the error "Unknown column 'stud.id' in 'where clause'. I don't have any stud.id in my files and also in my database. What do you think the problem with this? I'm using Codeigniter 4.

Below is my code on my Controller:

```<code>    $model = new Mod_Stud();
    $id = $this->request->getVar('stud_id');

    $data = [
                'stud_id' => $this->request->getVar('stud_id'),
                'lname' => $this->request->getVar('lname'),
                'fname' => $this->request->getVar('fname'),
                'mname' => $this->request->getVar('mname'),
    ];

    $save = $model->update($id,$data);
    return redirect()->to( base_url('/') );
</code>```

Code for my Model:

```<code>    protected $table = 'stud';
    protected $allowedFields = ['stud_id', 'sy', 'dpt', 'grd', 'lname', 'fname', 'mname', 'gender', 'bday', 'birthplace', 'religion', 'nationality', 'country', 'address', 'f_name', 'f_occ', 'm_name', 'm_occ', 'g_name', 'g_rel', 'created_at', 'updated_at'];
</code>```

I already fix it!

Below is the codes that I use.

```<code>$model->set($data);
$model->where('stud_id', $id);
$model->update();
</code>```

答:
Probably this will help,

```<code>protected $primaryKey = 'stud_id';
</code>```

remove stud_id from your protected $allowedFields

Body:
I encounter the error "Unknown column 'stud.id' in 'where clause'. I don't have any stud.id in my files and also in my database. What do you think the problem with this? I'm using Codeigniter 4.

Below is my code on my Controller:

    $model = new Mod_Stud();
    $id = $this->request->getVar('stud_id');

    $data = [
                'stud_id' => $this->request->getVar('stud_id'),
                'lname' => $this->request->getVar('lname'),
                'fname' => $this->request->getVar('fname'),
                'mname' => $this->request->getVar('mname'),
    ];

    $save = $model->update($id,$data);
    return redirect()->to( base_url('/') );

Code for my Model:

    protected $table = 'stud';
    protected $allowedFields = ['stud_id', 'sy', 'dpt', 'grd', 'lname', 'fname', 'mname', 'gender', 'bday', 'birthplace', 'religion', 'nationality', 'country', 'address', 'f_name', 'f_occ', 'm_name', 'm_occ', 'g_name', 'g_rel', 'created_at', 'updated_at'];

I already fix it!

Below is the codes that I use.

$model->set($data);
$model->where('stud_id', $id);
$model->update();

Body:
Probably this will help,

protected $primaryKey = 'stud_id';

remove stud_id from your protected $allowedFields


问:
TAR override the contents of the directory
My understanding of tar command that it will override the content of the file if file exist. Otherwise it would keep as existing.

```<code>[root@something~]# ls -al /etc/init.d/
total XX
drwxr-xr-x.  2 root root    83 Jun 14  2018 .
drwxr-xr-x. 10 root root   127 Jun  6  2017 ..
-rwxr-xr-x.  1 root root  7293 Jan  2  2018 network
-rw-r--r--.  1 root root  1160 Feb 20  2018 README
[root@something~]# tar tvf /tmp/env_pkg_1.tar
drwxr-xr-x staff    0 2020-05-29 19:42 etc/
drwxr-xr-x user/staff    0 2020-05-29 18:04 etc/init.d/
-rw-r--r-- user/staff 3383 2020-05-29 18:04 etc/init.d/sshd
[root@something~]# cd /
[root@something /]# tar xf /tmp/env_pkg_1.tar
[root@something/]# ls -al /etc/init.d/
total 16
drwxr-xr-x   2 XXXXXX XXXXXX 18 May 29 18:04 .
drwxr-xr-x. 85 XXXXXX XXXXXX 8192 May 29 19:42 ..
-rw-r--r--   1 XXXXXX XXXXXX 3383 May 29 18:04 sshd
</code>```

I am not understand why tar is replacing the entire contents of /etc/init.d

Any inputs would be helpful ?

答:
You can use -k or --keep-old-files, so it does not touch any files that are already within the destination. Judging by your output in /etc/init.d/ you want to keep network and README and next to them extract sshd, so in your case, they do not overlap.

Alternatively --keep-newer-files will have tar replace files that are newer from the tar archive, than what's on the destination..

Body:
My understanding of tar command that it will override the content of the file if file exist. Otherwise it would keep as existing.

[root@something~]# ls -al /etc/init.d/
total XX
drwxr-xr-x.  2 root root    83 Jun 14  2018 .
drwxr-xr-x. 10 root root   127 Jun  6  2017 ..
-rwxr-xr-x.  1 root root  7293 Jan  2  2018 network
-rw-r--r--.  1 root root  1160 Feb 20  2018 README
[root@something~]# tar tvf /tmp/env_pkg_1.tar
drwxr-xr-x staff    0 2020-05-29 19:42 etc/
drwxr-xr-x user/staff    0 2020-05-29 18:04 etc/init.d/
-rw-r--r-- user/staff 3383 2020-05-29 18:04 etc/init.d/sshd
[root@something~]# cd /
[root@something /]# tar xf /tmp/env_pkg_1.tar
[root@something/]# ls -al /etc/init.d/
total 16
drwxr-xr-x   2 XXXXXX XXXXXX 18 May 29 18:04 .
drwxr-xr-x. 85 XXXXXX XXXXXX 8192 May 29 19:42 ..
-rw-r--r--   1 XXXXXX XXXXXX 3383 May 29 18:04 sshd

I am not understand why tar is replacing the entire contents of /etc/init.d

Any inputs would be helpful ?


问:
Comparing runtimes
I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.

1) Is it actually worth taking such things into account?

2) Assuming it is worth taking it into account, how do I do this?

I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.

答:
It's worth taking speed into account if you're optimizing code. You should generally know why you're optimizing code (as in: a specific task in your existing codebase is taking too long, not "I heard PHP is slower than Python"). It's not worth taking speed into account if you don't actually plan on switching languages. Just because one tiny module does something slightly faster doesn't mean rewriting your app in another language is a good idea. There are many other factors to choosing a language besides speed.

You benchmark, of course. Run the two codebases multiple times and compare the timing. You can use the time command if both scripts are executable from the shell, or use respective benchmarking functionality from each language; the latter case depends heavily on the actual language, naturally.

OwnerDisplayName: Teifion

Title: Comparing runtimes

LastEditorDisplayName: hoyhoy

ContentLicense: CC BY-SA 2.5


问:
'Back' browser action in Ruby on Rails
Can the 'Back' browser functionality be invoked from a Rails 'Back' link? </p>

答:
Use

```<code><%= link_to 'Back', :back %>
</code>```

This is specificied in the RDoc here

This generates some Javascript to navigate backward.  I've just tested it, and it works.

OwnerDisplayName: alamodey

Title: 'Back' browser action in Ruby on Rails

Body:
Use

<%= link_to 'Back', :back %>

This is specificied in the RDoc here

This generates some Javascript to navigate backward.  I've just tested it, and it works.

OwnerDisplayName: Tilendor

LastEditorDisplayName: Tilendor


问:
R.id Cannot be resolved
I guess something should be done with the Android-Manifest.xml file or something in the layout folder. I am new to Android so I don't know what I should write.</p>

```<code>public class AndroidPong extends Activity implements  OnClickListener {
    static String tag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super .onCreate(savedInstanceState);

        tag = getResources().getString(R.string.app_name);
        fullScreen();
        splashScreen();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        return super .onCreateDialog(id);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super .onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super .onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super .onStop();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super .onDestroy();
    }

    void startGame() {
        setContentView(R.layout.game);// error
        this .findViewById(R.id.Button01).setOnClickListener(this );//error
        this .findViewById(R.id.Button02).setOnClickListener(this );//Error
    }

    void splashScreen() {
        setContentView(R.layout.splash);// error
        this .findViewById(R.id.pongtable).setOnClickListener(this );//error
    }

    void gameMenu() {

    }

    void fullScreen() {
        this .requestWindowFeature(Window.FEATURE_NO_TITLE);
        this .getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public static void debug(String debug) {
        Log.d(tag, debug);
    }

<?xml version="1.0" encoding="utf-8"?>
<absoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">

<Button android:id="@+id/Button01"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"

<Button android:id="+id/Button02"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
 </absoluteLayout>
</code>```

答:
It looks like you're having two different types of errors. I'll address the one you refer to in your question title first. This has to do with the resource id.

R.id Cannot be resolved

That error happens when the compiler cannot find the resource that you are referencing for some resource (like a string, layout, menu, etc...). This usually is the result of a few things that you can try.

First, make sure that you're using the correct names to reference your resource id. For example, you have R.id.Button01. If you're using this to reference the res id of a button, then make sure that your button in XML has the attribute android:id="@+id/Button01"

Secondly, make sure there are no errors in your XML layout file. If there are other errors, than often Eclipse (I'm assuming you're using Eclipse) won't recognize that the resource id for that item was created.

If you can't see any obvious error like this, then try to clean up your build. Do this by going to Project -> Clean...

The other errors have to do with your OnClickListeners

```<code>this .findViewById(R.id.Button01).setOnClickListener(this );//error
this .findViewById(R.id.Button02).setOnClickListener(this );//Error
</code>```

and

```<code>this .findViewById(R.id.pongtable).setOnClickListener(this );//error
</code>```

This error is more straightforward. You are setting up your click listeners incorrectly. The setOnClickListener method takes an OnClickListener as an argument. If you want to set up a new one you'll need to pass in a new OnClickListener that you build. You can do it like this...

```<code>this.someButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
             // whatever the button will do
        }
    });
</code>```

Title: R.id Cannot be resolved

Body:
I guess something should be done with the Android-Manifest.xml file or something in the layout folder. I am new to Android so I don't know what I should write.

public class AndroidPong extends Activity implements  OnClickListener {
    static String tag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super .onCreate(savedInstanceState);

        tag = getResources().getString(R.string.app_name);
        fullScreen();
        splashScreen();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        return super .onCreateDialog(id);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super .onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super .onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super .onStop();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super .onDestroy();
    }

    void startGame() {
        setContentView(R.layout.game);// error
        this .findViewById(R.id.Button01).setOnClickListener(this );//error
        this .findViewById(R.id.Button02).setOnClickListener(this );//Error
    }

    void splashScreen() {
        setContentView(R.layout.splash);// error
        this .findViewById(R.id.pongtable).setOnClickListener(this );//error
    }

    void gameMenu() {

    }

    void fullScreen() {
        this .requestWindowFeature(Window.FEATURE_NO_TITLE);
        this .getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public static void debug(String debug) {
        Log.d(tag, debug);
    }

<?xml version="1.0" encoding="utf-8"?>
<absoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">

<Button android:id="@+id/Button01"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"

<Button android:id="+id/Button02"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
 </absoluteLayout>

Body:
It looks like you're having two different types of errors. I'll address the one you refer to in your question title first. This has to do with the resource id.

R.id Cannot be resolved

That error happens when the compiler cannot find the resource that you are referencing for some resource (like a string, layout, menu, etc...). This usually is the result of a few things that you can try.

First, make sure that you're using the correct names to reference your resource id. For example, you have R.id.Button01. If you're using this to reference the res id of a button, then make sure that your button in XML has the attribute android:id="@+id/Button01"

Secondly, make sure there are no errors in your XML layout file. If there are other errors, than often Eclipse (I'm assuming you're using Eclipse) won't recognize that the resource id for that item was created.

If you can't see any obvious error like this, then try to clean up your build. Do this by going to Project -> Clean...

The other errors have to do with your OnClickListeners

this .findViewById(R.id.Button01).setOnClickListener(this );//error
this .findViewById(R.id.Button02).setOnClickListener(this );//Error

and

this .findViewById(R.id.pongtable).setOnClickListener(this );//error

This error is more straightforward. You are setting up your click listeners incorrectly. The setOnClickListener method takes an OnClickListener as an argument. If you want to set up a new one you'll need to pass in a new OnClickListener that you build. You can do it like this...

this.someButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
             // whatever the button will do
        }
    });


问:
In the event object for an onEdit trigger how is it that range get's defined as a real range object and a property identifier at the same time?
I have a little code sample to highlight the difference between an object that I created and the trigger event object.  In the trigger event object I can  use the term e.range along with the standard range class functions and it works fine.  However, I don't really know how to create a psuedo event object so that the range term is more than just the name of a property.

```<code>   function onEdit(e) {
      console.log(JSON.stringify(e));
      var sh=e.range.getSheet();//e.range is a real range object
      if(sh.getName()=='Sheet2' && e.range.columnStart>1) {
        sh.getRange(1,1).setValue(JSON.stringify(e)+ '\n' + e.range.getA1Notation());
        var rg=sh.getRange(e.range.getA1Notation());//e.range is a real range object
        var myObj={value:rg.getValue,range:{columnStart:e.range.columnStart,rowStart:e.range.rowStart,columnEnd:e.range.columnEnd,rowEnd:e.range.rowEnd}};
        console.log(JSON.stringify(myObj));
        try{
          sh.getRange(2,1).setValue(JSON.stringify(myObj)+ '\n' + myObj.range.getA1Notation());//myObj.range is not a real range object
        }
        catch(m) {
          console.log('Error: ' + m);
        }
        try{
          sh.getRange(3,1).setValue(e.range.getValue());
        }
        catch(n) {
          console.log('Error: ' + n);
        }
      }
    }
</code>```

If you edit Sheet2 appropriately you will get the following Stack Driver Logs:

Stackdriver logs

```<code>May 29, 2020, 1:21:30 PM    Debug   {"source":{},"value":"55","user":{"email":"","nickname":""},"range":{"columnEnd":5,"columnStart":5,"rowEnd":3,"rowStart":3},"authMode":"LIMITED"}
May 29, 2020, 1:21:30 PM    Debug   {"range":{"columnStart":5,"rowStart":3,"columnEnd":5,"rowEnd":3}}
May 29, 2020, 1:21:30 PM    Debug   Error: TypeError: myObj.range.getA1Notation is not a function
</code>```

Notice above I cannot use myObj.range with the getA1Notation() method.  (note: I didn't actually expect it to work...I'd like to know how to build the object correctly so that it will work and I haven't stumbled on the correct explanation yet.

So the thing I'd like to learn is how to create a psuedo event object so I can use myObj.range in the same way as I  can use e.range.

I feel real bad after Tanaike has gone to so much trouble.  But my real goal is to be able to create the event object precisely as it is created by the server. So that I could test onEdit()s with a test function calling the onEdit(e) rather than requiring actual edits.  And more importantly I'd really just like know how to build such an object.

I think this says what I'm shooting for.  I want to know how to create the event object precisely as it is provided to us from the onEdit trigger including having e.range to be an object that is equivalent to Class Range and thus capable of utilizing any of the methods found here.  I hope that's possible.  I apologize for these late additions but they were prompted from some of Tanaike's questions.  I'll probably need to review the question again and make it more clear.

This is some code I'm working on and it's far from complete but this is the sort of thing one might do with the knowledge of the answer to my question.

```<code>function onXditTest(row) {
  var row=row||2;
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('OnEditTest');
  const v=sh.getRange(row,1,1,sh.getLastColumn()).getValues()[0];
  const xsh=ss.getSheetByName(v[5]);
  const xrg=xsh.getRange(v[0],v[2],v[1]-v[0]+1,v[3]-v[2]+1);
  const evobj={range:{rowStart:v[0],rowEnd:v[1],columnStart:v[2],columnEnd:v[3]},value:v[4],range:xrg,source:ss};
  onXdit(evobj);
}
</code>```

The real question is how to make evobj so that evobj.range is an object of Class Range and at the sametime have available evobj.range.columnStart, evobj.range.rowStart, evobj.range.columnEnd and evobj.range.rowEnd so that the code under test behaves the same way in onEdit(e) as it does in onXdit(e)

```<code>function onXdit(e) {//changed name so edits dont trigger the function
  e.source.toast('Entry');
  console.log(JSON.stringify(e));
  const sh=e.range.getSheet();
  if(sh.getName()=="Sheet2" && e.range.columnStart==4 && e.value=="TRUE" ) {
    e.source.toast('Past Condition');
    e.range.setValue("FALSE");
  }
}
</code>```

答:
I believe your goal as follows.

You want to create an event object like the event object returned with OnEdit event trigger using Google Apps Script.

For this, how about this answer?

I think that the event object from the OnEdit event trigger is returned from the internal server at Google side. So I'm not sure about the actual script for this. So in this answer, I would like to propose the method for creating the pseudo event object as you say.

In this answer, I used the JavaScript classes which can be used with V8. But I'm not sure whether this is the direction you expect.

Sample script:

In order to use this script, please copy and paste the following script to the script editor, and save it. Then, please edit the cell. By this, onEdit is run by the OnEdit event trigger.

```<code>const createEventObject = obj => {
  // Class for creating the range object.
  class createRangeObject {
    constructor(obj) {
      this.columnEnd = obj.columnEnd;
      this.columnStart = obj.columnStart;
      this.rowEnd = obj.rowEnd;
      this.rowStart = obj.rowStart;
    }

    getA1Notation() {
      return SpreadsheetApp
        .getActiveSheet()
        .getRange(this.rowStart, this.columnStart, this.rowEnd - this.rowStart + 1, this.columnEnd - this.columnStart + 1)
        .getA1Notation();
    }

    getSheet() {
      return SpreadsheetApp
        .getActiveSheet();
    }
  }

  // Main script of createEventObject.
  class main {
    constructor(obj) {
      this.obj = obj;
    }

    get range() {
      return new createRangeObject(this.obj);
    }
  }
  return new main(obj);
}

// This function is run by editing cells.
function onEdit(e) {
  // This is your object.
  var myObj={range:{columnStart:e.range.columnStart,rowStart:e.range.rowStart,columnEnd:e.range.columnEnd,rowEnd:e.range.rowEnd}};

  // Create the pseudo event object.
  const obj = createEventObject(myObj.range);

  console.log(obj.range)
  console.log(obj.range.getA1Notation())
  console.log(obj.range.getSheet().getSheetName())
}
</code>```

Result:

In above sample script, for example, when the cells "B3:C5" are edited, the following result are retrieved.

obj.range is { columnEnd: 3, columnStart: 2, rowEnd: 5, rowStart: 3 }.

obj.range.getA1Notation() is B3:C5.

obj.range.getSheet().getSheetName() is Sheet1 which is the active sheet.

Note:

This answer, which uses the JavaScript classes, is one methodology. So I think that there might be more simpler methods.

This is a simple script for explaining of this workaround. So when you want to use this for your actual situation, please modify this.

Please use this script with V8.

Reference:

Classes

Body:
I have a little code sample to highlight the difference between an object that I created and the trigger event object.  In the trigger event object I can  use the term e.range along with the standard range class functions and it works fine.  However, I don't really know how to create a psuedo event object so that the range term is more than just the name of a property.

   function onEdit(e) {
      console.log(JSON.stringify(e));
      var sh=e.range.getSheet();//e.range is a real range object
      if(sh.getName()=='Sheet2' && e.range.columnStart>1) {
        sh.getRange(1,1).setValue(JSON.stringify(e)+ '\n' + e.range.getA1Notation());
        var rg=sh.getRange(e.range.getA1Notation());//e.range is a real range object
        var myObj={value:rg.getValue,range:{columnStart:e.range.columnStart,rowStart:e.range.rowStart,columnEnd:e.range.columnEnd,rowEnd:e.range.rowEnd}};
        console.log(JSON.stringify(myObj));
        try{
          sh.getRange(2,1).setValue(JSON.stringify(myObj)+ '\n' + myObj.range.getA1Notation());//myObj.range is not a real range object
        }
        catch(m) {
          console.log('Error: ' + m);
        }
        try{
          sh.getRange(3,1).setValue(e.range.getValue());
        }
        catch(n) {
          console.log('Error: ' + n);
        }
      }
    }

If you edit Sheet2 appropriately you will get the following Stack Driver Logs:

Stackdriver logs

May 29, 2020, 1:21:30 PM    Debug   {"source":{},"value":"55","user":{"email":"","nickname":""},"range":{"columnEnd":5,"columnStart":5,"rowEnd":3,"rowStart":3},"authMode":"LIMITED"}
May 29, 2020, 1:21:30 PM    Debug   {"range":{"columnStart":5,"rowStart":3,"columnEnd":5,"rowEnd":3}}
May 29, 2020, 1:21:30 PM    Debug   Error: TypeError: myObj.range.getA1Notation is not a function

Notice above I cannot use myObj.range with the getA1Notation() method.  (note: I didn't actually expect it to work...I'd like to know how to build the object correctly so that it will work and I haven't stumbled on the correct explanation yet.

So the thing I'd like to learn is how to create a psuedo event object so I can use myObj.range in the same way as I  can use e.range.

I feel real bad after Tanaike has gone to so much trouble.  But my real goal is to be able to create the event object precisely as it is created by the server. So that I could test onEdit()s with a test function calling the onEdit(e) rather than requiring actual edits.  And more importantly I'd really just like know how to build such an object.

I think this says what I'm shooting for.  I want to know how to create the event object precisely as it is provided to us from the onEdit trigger including having e.range to be an object that is equivalent to Class Range and thus capable of utilizing any of the methods found here.  I hope that's possible.  I apologize for these late additions but they were prompted from some of Tanaike's questions.  I'll probably need to review the question again and make it more clear.

This is some code I'm working on and it's far from complete but this is the sort of thing one might do with the knowledge of the answer to my question.

function onXditTest(row) {
  var row=row||2;
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('OnEditTest');
  const v=sh.getRange(row,1,1,sh.getLastColumn()).getValues()[0];
  const xsh=ss.getSheetByName(v[5]);
  const xrg=xsh.getRange(v[0],v[2],v[1]-v[0]+1,v[3]-v[2]+1);
  const evobj={range:{rowStart:v[0],rowEnd:v[1],columnStart:v[2],columnEnd:v[3]},value:v[4],range:xrg,source:ss};
  onXdit(evobj);
}

The real question is how to make evobj so that evobj.range is an object of Class Range and at the sametime have available evobj.range.columnStart, evobj.range.rowStart, evobj.range.columnEnd and evobj.range.rowEnd so that the code under test behaves the same way in onEdit(e) as it does in onXdit(e)

function onXdit(e) {//changed name so edits dont trigger the function
  e.source.toast('Entry');
  console.log(JSON.stringify(e));
  const sh=e.range.getSheet();
  if(sh.getName()=="Sheet2" && e.range.columnStart==4 && e.value=="TRUE" ) {
    e.source.toast('Past Condition');
    e.range.setValue("FALSE");
  }
}

Body:
I believe your goal as follows.

You want to create an event object like the event object returned with OnEdit event trigger using Google Apps Script.

For this, how about this answer?

I think that the event object from the OnEdit event trigger is returned from the internal server at Google side. So I'm not sure about the actual script for this. So in this answer, I would like to propose the method for creating the pseudo event object as you say.

In this answer, I used the JavaScript classes which can be used with V8. But I'm not sure whether this is the direction you expect.

Sample script:

In order to use this script, please copy and paste the following script to the script editor, and save it. Then, please edit the cell. By this, onEdit is run by the OnEdit event trigger.

const createEventObject = obj => {
  // Class for creating the range object.
  class createRangeObject {
    constructor(obj) {
      this.columnEnd = obj.columnEnd;
      this.columnStart = obj.columnStart;
      this.rowEnd = obj.rowEnd;
      this.rowStart = obj.rowStart;
    }

    getA1Notation() {
      return SpreadsheetApp
        .getActiveSheet()
        .getRange(this.rowStart, this.columnStart, this.rowEnd - this.rowStart + 1, this.columnEnd - this.columnStart + 1)
        .getA1Notation();
    }

    getSheet() {
      return SpreadsheetApp
        .getActiveSheet();
    }
  }

  // Main script of createEventObject.
  class main {
    constructor(obj) {
      this.obj = obj;
    }

    get range() {
      return new createRangeObject(this.obj);
    }
  }
  return new main(obj);
}

// This function is run by editing cells.
function onEdit(e) {
  // This is your object.
  var myObj={range:{columnStart:e.range.columnStart,rowStart:e.range.rowStart,columnEnd:e.range.columnEnd,rowEnd:e.range.rowEnd}};

  // Create the pseudo event object.
  const obj = createEventObject(myObj.range);

  console.log(obj.range)
  console.log(obj.range.getA1Notation())
  console.log(obj.range.getSheet().getSheetName())
}

Result:

In above sample script, for example, when the cells "B3:C5" are edited, the following result are retrieved.

obj.range is { columnEnd: 3, columnStart: 2, rowEnd: 5, rowStart: 3 }.

obj.range.getA1Notation() is B3:C5.

obj.range.getSheet().getSheetName() is Sheet1 which is the active sheet.

Note:

This answer, which uses the JavaScript classes, is one methodology. So I think that there might be more simpler methods.

This is a simple script for explaining of this workaround. So when you want to use this for your actual situation, please modify this.

Please use this script with V8.

Reference:

Classes


问:
Copy to Clipboard - Ajax has been denied
Im trying to copy to clipboard the return result from ajax but every time i get "document.execCommand(‘cut’/‘copy’) was denied"
i try few time to fix it but without success </p>

```<code>$('form').submit(function(e){
    e.preventDefault();
    $.ajax({
      url: $('#test').attr('action'),
      data: $('#test').serialize(),
      type: 'post',
      dataType: 'json',
      success: function(data){
        var $temp = $("<input />");
        $(data.response).append($temp).select();
        document.execCommand("copy");
        $temp.remove();
        console.log(data.response);
      }
    });

  });
</code>```

答:
I'm similarly bewildered.  The main thread on this seems to be:

How do I copy to the clipboard in JavaScript?

Reading through the document.execCommand("copy") method you and I are trying, two caveats jump out at me:

*) it is only allowed over https connections (which I can't simulate by default in my home server testing environment, so maybe that applies to you as well)

*) it has to be a part of a user-initiated action (so as to prevent hidden copies confusing users).  The 'click' event is the example commonly given.  The event you've chosen to bind, form submits, could be called within a function. Perhaps, then, through its more universal access it doesn't meet the pedigree of user-initiated interaction?

Body:
Im trying to copy to clipboard the return result from ajax but every time i get "document.execCommand(‘cut’/‘copy’) was denied"
i try few time to fix it but without success

$('form').submit(function(e){
    e.preventDefault();
    $.ajax({
      url: $('#test').attr('action'),
      data: $('#test').serialize(),
      type: 'post',
      dataType: 'json',
      success: function(data){
        var $temp = $("<input />");
        $(data.response).append($temp).select();
        document.execCommand("copy");
        $temp.remove();
        console.log(data.response);
      }
    });

  });


问:
is there any way to force copy? copy without overwrite prompt, using windows?
I want to write a list of windows commands(it's a long list) where it does all these magical things for me, but whenever I use copy, it stops to ask fro overwrite prompt. When I type yes, it overwrites the old file then just stops there.

How do I make it such that whenever the windows sees the copy command, it just overwrites the old file without that prompt?

答:
MOVE  /-Y Source Destination

Note:/-y will make the announcement of yes/no for overwrite


问:
Is it possible to disable sorting for particular column with customfields in React Admin
I have a custom field for user status but I want to disable the default sorting on that column.

like when we use predefined fields like

答:
It is possible to disable sorting for a specific field by passing a sortable property set to false: https://marmelab.com/react-admin/List.html#disabling-sorting

<TextField source="id" sortable={false} />