问:
JavaScript Sorting Multidimensional JSON
I have this JSON string:

```<code>{
"widgets":[
    {"column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ]},
    {"column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ]},
    {"column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]}
]}
</code>```

if I do

```<code>alert(testJSON.widgets.length);
</code>```

I get 3, however if I do

```<code>alert(testJSON.widgets.column1.length);
</code>```

I get "testJSON.widgets.column3 is undefined" as an error.

What I am ultimately attempting to do is take each column1-3 and sort them by weight. Through something like

```<code>testJSON.widgets.column1.sort(function(a,b) { return parseFloat(a.weight) - parseFloat(b.weight) });
</code>```

So I can then do a $.each() via jquery

答:
The "widgets" key contains an array of objects, so you need to specify an offset to grab the appropriate column.

```<code>testJSON.widgets[0].column1; // returns "column1" object

testJSON.widgets[0].column1.length; // returns 3
</code>```

You can try it here.

I would suggest revising the schema such that instead of "columnX" it's just "column". That will simplify traversal since you already know the column number via the offset of the "widget", e.g.:

```<code>alert(testJSON.widgets[0].column.length);
alert(testJSON.widgets[1].column.length);
</code>```

Demo (new schema).

Body:
I have this JSON string:

{
"widgets":[
    {"column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ]},
    {"column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ]},
    {"column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]}
]}

if I do

alert(testJSON.widgets.length);

I get 3, however if I do

alert(testJSON.widgets.column1.length);

I get "testJSON.widgets.column3 is undefined" as an error.

What I am ultimately attempting to do is take each column1-3 and sort them by weight. Through something like

testJSON.widgets.column1.sort(function(a,b) { return parseFloat(a.weight) - parseFloat(b.weight) });

So I can then do a $.each() via jquery

Body:
The "widgets" key contains an array of objects, so you need to specify an offset to grab the appropriate column.

testJSON.widgets[0].column1; // returns "column1" object

testJSON.widgets[0].column1.length; // returns 3

You can try it here.

I would suggest revising the schema such that instead of "columnX" it's just "column". That will simplify traversal since you already know the column number via the offset of the "widget", e.g.:

alert(testJSON.widgets[0].column.length);
alert(testJSON.widgets[1].column.length);

Demo (new schema).


来源: stackexchange

问:
mogrify() function with list of JSON values
I have an array with JSON content like this

{
   "time":datetimeValue,
   "Type":"TypeValue",
   "ID":"IDValue",
   "ReceiveValue":{
      "Sensor1": Value1,
      "Sensor2":Value2,
      "Sensor3": Value3,
   },
   "TransmitValue":{
      "Sensor1": Value1,
      "Sensor2":Value2,
      "Sensor3": Value3,
   }
}
```
<p>I tried to insert all of my records to PostgreSQL database in this array using this code</p>
<pre class="lang-py prettyprint-override"><code>args_str = ','.join(self.cursor.mogrify("(%s,%s,%s,%s,%s)", x.values()) for x in self.records)
self.cursor.execute("INSERT INTO util VALUES " + (args_str))
</code>```

But I got this error

```<code>'dict_values' object does not support indexing
</code>```

Is there any way to solve this error or is there are any way to insert multiple records with mogrify function?

答:
You need to make a list out of x.values() and possibly convert the values to JSON (depending on your database table):

```<code>from psycopg2.extras import Json
# All values are converted to json!
args_str = b','.join(cur.mogrify('(%s,%s,%s,%s,%s)', [Json(x) for x in item.values()]) for item in data)
sql = b"INSERT INTO util VALUES " + args_str
print(sql)
</code>```

Out:

```<code>b'INSERT INTO util VALUES (\'"Value1"\',\'"Value2"\',\'"Value3"\',\'{"Key1": "Value1", "Key2": "Value2", "Key3": "Value3", "Key4": "Value4", "Key5": "Value5", "Key6": "Value6", "Key7": "Value7", "Key8": "Value8"}\',\'{"Key1": "Value1", "Key2": "Value2", "Key3": "Value3", "Key4": "Value4", "Key5": "Value5", "Key6": "Value6", "Key7": "Value7", "Key8": "Value8"}\'),(\'"Value1"\',\'"Value2"\',\'"Value3"\',\'{"Key1": "Value1", "Key2": "Value2", "Key3": "Value3", "Key4": "Value4", "Key5": "Value5", "Key6": "Value6", "Key7": "Value7", "Key8": "Value8"}\',\'{"Key1": "Value1", "Key2": "Value2", "Key3": "Value3", "Key4": "Value4", "Key5": "Value5", "Key6": "Value6", "Key7": "Value7", "Key8": "Value8"}\')'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array with JSON content like this

{
   "time":datetimeValue,
   "Type":"TypeValue",
   "ID":"IDValue",
   "ReceiveValue":{
      "Sensor1": Value1,
      "Sensor2":Value2,
      "Sensor3": Value3,
   },
   "TransmitValue":{
      "Sensor1": Value1,
      "Sensor2":Value2,
      "Sensor3": Value3,
   }
}

I tried to insert all of my records to PostgreSQL database in this array using this code

args_str = ','.join(self.cursor.mogrify("(%s,%s,%s,%s,%s)", x.values()) for x in self.records)
self.cursor.execute("INSERT INTO util VALUES " + (args_str))

But I got this error

'dict_values' object does not support indexing

Is there any way to solve this error or is there are any way to insert multiple records with mogrify function?

Body:
You need to make a list out of x.values() and possibly convert the values to JSON (depending on your database table):

from psycopg2.extras import Json
# All values are converted to json!
args_str = b','.join(cur.mogrify('(%s,%s,%s,%s,%s)', [Json(x) for x in item.values()]) for item in data)
sql = b"INSERT INTO util VALUES " + args_str
print(sql)

Out:

b'INSERT INTO util VALUES (\'"Value1"\',\'"Value2"\',\'"Value3"\',\'{"Key1": "Value1", "Key2": "Value2", "Key3": "Value3", "Key4": "Value4", "Key5": "Value5", "Key6": "Value6", "Key7": "Value7", "Key8": "Value8"}\',\'{"Key1": "Value1", "Key2": "Value2", "Key3": "Value3", "Key4": "Value4", "Key5": "Value5", "Key6": "Value6", "Key7": "Value7", "Key8": "Value8"}\'),(\'"Value1"\',\'"Value2"\',\'"Value3"\',\'{"Key1": "Value1", "Key2": "Value2", "Key3": "Value3", "Key4": "Value4", "Key5": "Value5", "Key6": "Value6", "Key7": "Value7", "Key8": "Value8"}\',\'{"Key1": "Value1", "Key2": "Value2", "Key3": "Value3", "Key4": "Value4", "Key5": "Value5", "Key6": "Value6", "Key7": "Value7", "Key8": "Value8"}\')'


问:
Init array of structs in Go
I'm newbie in Go. This issue is driving me nuts. How do you init array of structs in Go?

```<code>type opt struct {
    shortnm      char
    longnm, help string
    needArg      bool
}

const basename_opts []opt {
        opt {
            shortnm: 'a',
            longnm: "multiple",
            needArg: false,
            help: "Usage for a"}
        },
        opt {
            shortnm: 'b',
            longnm: "b-option",
            needArg: false,
            help: "Usage for b"}
    }
</code>```

The compiler said it expecting ; after []opt.

Where should I put the braces { to init my array of struct?

答:
I came across this answer while searching for how to initialize a slice of structs. I've been working with Go just a few months myself so I'm not sure if  this was true at the time of the question or its just a new update but its not(no longer) necessary to restate the type. See a refactored version of @jimt's example</p>
```<code>type opt struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}

var basenameOpts = []opt {
    {
        shortnm: 'a',
        longnm: "multiple",
        needArg: false,
        help: "Usage for a",
    },
    {
        shortnm: 'b',
        longnm: "b-option",
        needArg: false,
        help: "Usage for b",
    },
}
</code>```

Title: Init array of structs in Go

Body:
I'm newbie in Go. This issue is driving me nuts. How do you init array of structs in Go?

type opt struct {
    shortnm      char
    longnm, help string
    needArg      bool
}

const basename_opts []opt {
        opt {
            shortnm: 'a',
            longnm: "multiple",
            needArg: false,
            help: "Usage for a"}
        },
        opt {
            shortnm: 'b',
            longnm: "b-option",
            needArg: false,
            help: "Usage for b"}
    }

The compiler said it expecting ; after []opt.

Where should I put the braces { to init my array of struct?

Body:
I came across this answer while searching for how to initialize a slice of structs. I've been working with Go just a few months myself so I'm not sure if  this was true at the time of the question or its just a new update but its not(no longer) necessary to restate the type. See a refactored version of @jimt's example

type opt struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}

var basenameOpts = []opt {
    {
        shortnm: 'a',
        longnm: "multiple",
        needArg: false,
        help: "Usage for a",
    },
    {
        shortnm: 'b',
        longnm: "b-option",
        needArg: false,
        help: "Usage for b",
    },
}


问:
INSERT statement gives column reference is ambiguous error when used in Postgres function
I have the following function in Postgres for inserting values to a table employee_leaves and the table has the following structure

id[PK]
emp_id[varchar]
lt_id[int]
from_dt[date]
from_session_id[int]
to_dt[Date]
to_session_id[int]
reasons[varchar]
contact_details[varchar]
status[int]
notify_users[jsonb]
pending_with[int]
other_info[jsonb]
created_by[int]
created_on[date]
last_updated_by[int]
last_updated_on[date]

The function is as follows:

```<code>-- FUNCTION: company.lib.org.create_edit_employee_leave(json)

-- DROP FUNCTION IF EXISTS "company.lib.org".create_edit_employee_leave(json);

CREATE OR REPLACE FUNCTION "company.lib.org".create_edit_employee_leave(
    params json)
    RETURNS json
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
--select"company.lib.org".create_edit_employee_leave('{"emp_id":292, "lt_id":1, "from_dt":"2022-01-10", "from_session_id":1,"to_dt":"2022-01-11" ,"to_session_id":"2", "reasons":"Leave Reason", "contact_details":"8884514965", "status":1, "notify_users":[1,2,3] ,"pending_with":3, "other_info":"{}"," created_by":"123", "last_updated_by":13, "last_updated_on":"2022-01-20 00:00:00"}');

declare
        emp_id character varying(50);
        query text;
        cond text;
        response json;
        message character varying(50);

        lt_id smallint;
        from_dt date;
        from_session_id smallint;
        to_dt date;
        to_session_id smallint;
        reasons character varying(1024);
        contact_details character varying(1024);
        status smallint;
        notify_users json;
        pending_with character varying(50);
        other_info json;
        created_by integer;
        created_on timestamp with time zone;
        last_updated_by integer;
        last_updated_on timestamp with time zone;

        begin
        emp_id = (params->>'emp_id');
        lt_id = (params->>'lt_id');
        from_dt = (params->>'from_dt');
        from_session_id = (params->>'from_session_id');
        to_dt =  (params->>'to_dt');
        to_session_id = (params->>'to_session_id')::smallint;
        reasons = (params->>'reasons');
        contact_details = (params->>'contact_details');
        status = (params->>'status')::smallint;
        notify_users = COALESCE((params ->> 'notify_users')::jsonb,'{}'::jsonb);
        pending_with=(params->>'pending_with');
        other_info = COALESCE((params ->> 'other_info')::jsonb,'{}'::jsonb);
        created_by = (params->>'created_by')::integer;
        created_on = (params->>'created_on')::date;
        last_updated_by = (params->>'last_updated_by')::integer;
        last_updated_on = (params->>'last_updated_on')::date;
        message = '';
        raise info 'leave_application_id %',emp_id;

        if (params->>'action') = 'C' then
        INSERT INTO "company.lib.org".employee_leaves(
        emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on)
        VALUES (
            emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on
        ) returning emp_id into emp_id;
        end if;
        message = 'New Leave application created successfully';

        response = ('{"status": 200, "leave_application_id": "' || emp_id || '", "message":"' || message ||'"}')::json;

       return response;

    EXCEPTION
        WHEN unique_violation THEN
            response = '{"status": 500, "data": "Unique key violation"}';
        WHEN check_violation THEN
            response = '{"status": 500, "data": "Check violation"}';
        WHEN no_data_found THEN
            response = '{"status": 500, "data": "Check"}';
        WHEN others THEN
            RAISE INFO 'Error Name:%', SQLERRM;
            RAISE INFO 'Error State:%', SQLSTATE;
            response = '{"status": 500, "data": "Unknown exception '|| SQLERRM || '"}';
    return response;

    END;

$BODY$;

ALTER FUNCTION "company.lib.org".create_edit_employee_leave(json)
    OWNER TO postgres;
</code>```

Now when I use the following INSERT directly, it is working fine

```<code>INSERT INTO "company.lib.org".employee_leaves(
        emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on)
        VALUES (
            '25506', 1, '2020-01-11', 1, '2020-01-12', 2, 'Leave Reasons', '8884514965', 1, '[25509,25336]', 25509, '{}', 25506, '2022-02-06T06:01:31.025Z', 25506, '2022-02-06T06:01:31.025Z'
        )
</code>```

But when I call function like this,

```<code>select "company.lib.org".create_edit_employee_leave(
    (
        '{"action":"C","emp_id":"25506","lt_id":1,"from_dt":"2020-01-11","from_session_id":1,"to_dt":"2020-01-12","to_session_id":2,"reasons":"LeaveReasons","contact_details":"8884514965","status":1,"notify_users":["25509","25336"],"pending_with":25509,"other_info":{},"created_by":"25506","created_on":"2022-02-06T06:08:11.531Z","last_updated_by":"25506","last_updated_on":"2022-02-06T06:08:11.531Z"}'
    )::json
</code>```

)

It is giving an error like

```<code>INFO:  Error Name:column reference "emp_id" is ambiguous
INFO:  Error State:42702
</code>```

As I have shown in the table structure, the column exists in the table and there are no other columns with the same name. However, I have other tables with the same column name and there is a foreign key constraint that refers to the employee table and the emp_id in that table. Also, this is an INSERT statement. So I am not sure what went wrong here. If someone can tell me what is the error here, that would be helpful.

答:
By default, PL/pgSQL will report an error if a name in an SQL
statement could refer to either a variable or a table column. You can
fix such a problem by renaming the variable or column, or by
qualifying the ambiguous reference, or by telling PL/pgSQL which
interpretation to prefer.

https://www.postgresql.org/docs/current/plpgsql-implementation.html

from here> https://www.postgresql.org/docs/12/functions-json.html.
->> return text type.
But you declare
emp_id character varying(50);. I am not so sure. I think it's fine. but maybe future will be a issue. For example:

```<code>CREATE OR REPLACE FUNCTION test_txt2()
RETURNS void
LANGUAGE 'plpgsql'
AS $BODY$
declare a varchar(1);
begin
    RAISE INFO 'Alas we are at the end of our journey';
    a = 'test'::text;
    RAISE INFO 'Alas we are at the end of our journey111';
end;
$BODY$;
</code>```

It will fail.

```<code>INFO:  Alas we are at the end of our journey
ERROR:  value too long for type character varying(1)
CONTEXT:  PL/pgSQL assignment "a = 'test'::text"
PL/pgSQL function test_txt2() line 5 at assignment
</code>```

If the expression's result data type doesn't match the variable's data
type, the value will be coerced as though by an assignment cast (see
Section 10.4). If no assignment cast is known for the pair of data
types involved, the PL/pgSQL interpreter will attempt to convert the
result value textually, that is by applying the result type's output
function followed by the variable type's input function.

further info.https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-ASSIGNMENT

Update: I deep dived a little bit.
From here https://www.postgresql.org/docs/12/errcodes-appendix.html, you get the error code. Then I searched the postgresql source code.
Then I located the final explanation  page: https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob_plain;f=src/backend/parser/README;hb=HEAD

Body:
I have the following function in Postgres for inserting values to a table employee_leaves and the table has the following structure

id[PK]
emp_id[varchar]
lt_id[int]
from_dt[date]
from_session_id[int]
to_dt[Date]
to_session_id[int]
reasons[varchar]
contact_details[varchar]
status[int]
notify_users[jsonb]
pending_with[int]
other_info[jsonb]
created_by[int]
created_on[date]
last_updated_by[int]
last_updated_on[date]

The function is as follows:

-- FUNCTION: company.lib.org.create_edit_employee_leave(json)

-- DROP FUNCTION IF EXISTS "company.lib.org".create_edit_employee_leave(json);

CREATE OR REPLACE FUNCTION "company.lib.org".create_edit_employee_leave(
    params json)
    RETURNS json
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
--select"company.lib.org".create_edit_employee_leave('{"emp_id":292, "lt_id":1, "from_dt":"2022-01-10", "from_session_id":1,"to_dt":"2022-01-11" ,"to_session_id":"2", "reasons":"Leave Reason", "contact_details":"8884514965", "status":1, "notify_users":[1,2,3] ,"pending_with":3, "other_info":"{}"," created_by":"123", "last_updated_by":13, "last_updated_on":"2022-01-20 00:00:00"}');

declare
        emp_id character varying(50);
        query text;
        cond text;
        response json;
        message character varying(50);

        lt_id smallint;
        from_dt date;
        from_session_id smallint;
        to_dt date;
        to_session_id smallint;
        reasons character varying(1024);
        contact_details character varying(1024);
        status smallint;
        notify_users json;
        pending_with character varying(50);
        other_info json;
        created_by integer;
        created_on timestamp with time zone;
        last_updated_by integer;
        last_updated_on timestamp with time zone;

        begin
        emp_id = (params->>'emp_id');
        lt_id = (params->>'lt_id');
        from_dt = (params->>'from_dt');
        from_session_id = (params->>'from_session_id');
        to_dt =  (params->>'to_dt');
        to_session_id = (params->>'to_session_id')::smallint;
        reasons = (params->>'reasons');
        contact_details = (params->>'contact_details');
        status = (params->>'status')::smallint;
        notify_users = COALESCE((params ->> 'notify_users')::jsonb,'{}'::jsonb);
        pending_with=(params->>'pending_with');
        other_info = COALESCE((params ->> 'other_info')::jsonb,'{}'::jsonb);
        created_by = (params->>'created_by')::integer;
        created_on = (params->>'created_on')::date;
        last_updated_by = (params->>'last_updated_by')::integer;
        last_updated_on = (params->>'last_updated_on')::date;
        message = '';
        raise info 'leave_application_id %',emp_id;

        if (params->>'action') = 'C' then
        INSERT INTO "company.lib.org".employee_leaves(
        emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on)
        VALUES (
            emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on
        ) returning emp_id into emp_id;
        end if;
        message = 'New Leave application created successfully';

        response = ('{"status": 200, "leave_application_id": "' || emp_id || '", "message":"' || message ||'"}')::json;

       return response;

    EXCEPTION
        WHEN unique_violation THEN
            response = '{"status": 500, "data": "Unique key violation"}';
        WHEN check_violation THEN
            response = '{"status": 500, "data": "Check violation"}';
        WHEN no_data_found THEN
            response = '{"status": 500, "data": "Check"}';
        WHEN others THEN
            RAISE INFO 'Error Name:%', SQLERRM;
            RAISE INFO 'Error State:%', SQLSTATE;
            response = '{"status": 500, "data": "Unknown exception '|| SQLERRM || '"}';
    return response;

    END;

$BODY$;

ALTER FUNCTION "company.lib.org".create_edit_employee_leave(json)
    OWNER TO postgres;

Now when I use the following INSERT directly, it is working fine

INSERT INTO "company.lib.org".employee_leaves(
        emp_id, lt_id, from_dt, from_session_id, to_dt, to_session_id, reasons, contact_details, status, notify_users, pending_with, other_info, created_by, created_on, last_updated_by, last_updated_on)
        VALUES (
            '25506', 1, '2020-01-11', 1, '2020-01-12', 2, 'Leave Reasons', '8884514965', 1, '[25509,25336]', 25509, '{}', 25506, '2022-02-06T06:01:31.025Z', 25506, '2022-02-06T06:01:31.025Z'
        )

But when I call function like this,

select "company.lib.org".create_edit_employee_leave(
    (
        '{"action":"C","emp_id":"25506","lt_id":1,"from_dt":"2020-01-11","from_session_id":1,"to_dt":"2020-01-12","to_session_id":2,"reasons":"LeaveReasons","contact_details":"8884514965","status":1,"notify_users":["25509","25336"],"pending_with":25509,"other_info":{},"created_by":"25506","created_on":"2022-02-06T06:08:11.531Z","last_updated_by":"25506","last_updated_on":"2022-02-06T06:08:11.531Z"}'
    )::json

)

It is giving an error like

INFO:  Error Name:column reference "emp_id" is ambiguous
INFO:  Error State:42702

As I have shown in the table structure, the column exists in the table and there are no other columns with the same name. However, I have other tables with the same column name and there is a foreign key constraint that refers to the employee table and the emp_id in that table. Also, this is an INSERT statement. So I am not sure what went wrong here. If someone can tell me what is the error here, that would be helpful.

Body:
By default, PL/pgSQL will report an error if a name in an SQL
statement could refer to either a variable or a table column. You can
fix such a problem by renaming the variable or column, or by
qualifying the ambiguous reference, or by telling PL/pgSQL which
interpretation to prefer.

https://www.postgresql.org/docs/current/plpgsql-implementation.html

from here> https://www.postgresql.org/docs/12/functions-json.html.
->> return text type.
But you declare
emp_id character varying(50);. I am not so sure. I think it's fine. but maybe future will be a issue. For example:

CREATE OR REPLACE FUNCTION test_txt2()
RETURNS void
LANGUAGE 'plpgsql'
AS $BODY$
declare a varchar(1);
begin
    RAISE INFO 'Alas we are at the end of our journey';
    a = 'test'::text;
    RAISE INFO 'Alas we are at the end of our journey111';
end;
$BODY$;

It will fail.

INFO:  Alas we are at the end of our journey
ERROR:  value too long for type character varying(1)
CONTEXT:  PL/pgSQL assignment "a = 'test'::text"
PL/pgSQL function test_txt2() line 5 at assignment

If the expression's result data type doesn't match the variable's data
type, the value will be coerced as though by an assignment cast (see
Section 10.4). If no assignment cast is known for the pair of data
types involved, the PL/pgSQL interpreter will attempt to convert the
result value textually, that is by applying the result type's output
function followed by the variable type's input function.

further info.https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-ASSIGNMENT

Update: I deep dived a little bit.
From here https://www.postgresql.org/docs/12/errcodes-appendix.html, you get the error code. Then I searched the postgresql source code.
Then I located the final explanation  page: https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob_plain;f=src/backend/parser/README;hb=HEAD


问:
Address of operator and r-value
There is code part below and I have a question about that.

Although I expect the compiler error, the ouput of this program is 2 5. From my point of view, &a+1 statement should lead to compiler error. The reason is that (a + 1) firstly is executed due to operator precedence and (a+1) statement points 2 in the array. Then, the address of operator (&) has (a + 1) operand but (a + 1) is an r-value expression and therefore &a+1 should cause a compiler error.

What is my fault?

```<code>int main()
{

    int a[5] = {1,2,3,4,5};

    int *ptr = (int*)(&a+1);

    printf("%d %d", *(a+1), *(ptr-1));

    return 0;
}
</code>```

答:
Arrays decay to pointer. Any of those pointers reference the same address in memory. The difference is in the type of this pointer.

```<code>int arr[5];
</code>```

arr and &arr[0] have type pointer to int (int *)

&arr has type of pointer to five elements integer array ( int (*)[5])

Then, the address of operator (&) has (a + 1) operand but (a + 1) is
an r-value expression and therefore &a+1 should cause a compiler
error.

No, the & operator is applied to a not to a + 1. &a + 1 === (&a) + 1

In your case &a is a pointer to 5 int elements. &a + 1 references the next array of 5 int elements, not the next element of the array a. Then you assign this value to int * pointer and derefence the previous int value. As pointer ptr is referencing the element one past the last element of the the array a so the previous element is the last element of the array a

Title: Address of operator and r-value

Body:
There is code part below and I have a question about that.

Although I expect the compiler error, the ouput of this program is 2 5. From my point of view, &a+1 statement should lead to compiler error. The reason is that (a + 1) firstly is executed due to operator precedence and (a+1) statement points 2 in the array. Then, the address of operator (&) has (a + 1) operand but (a + 1) is an r-value expression and therefore &a+1 should cause a compiler error.

What is my fault?

int main()
{

    int a[5] = {1,2,3,4,5};

    int *ptr = (int*)(&a+1);

    printf("%d %d", *(a+1), *(ptr-1));

    return 0;
}

Body:
Arrays decay to pointer. Any of those pointers reference the same address in memory. The difference is in the type of this pointer.

int arr[5];

arr and &arr[0] have type pointer to int (int *)

&arr has type of pointer to five elements integer array ( int (*)[5])

Then, the address of operator (&) has (a + 1) operand but (a + 1) is
an r-value expression and therefore &a+1 should cause a compiler
error.

No, the & operator is applied to a not to a + 1. &a + 1 === (&a) + 1

In your case &a is a pointer to 5 int elements. &a + 1 references the next array of 5 int elements, not the next element of the array a. Then you assign this value to int * pointer and derefence the previous int value. As pointer ptr is referencing the element one past the last element of the the array a so the previous element is the last element of the array a


问:
Python | (Tkinter) only shows text when button is pressed
So I made a button to copy something to clipboard, but the button itself is always showing, but the text on it only when its pressed, how to fix it?
(Here the part with the button code:)</p>
```<code>canvas1 = tk.Canvas(root, width=300, height=300)
canvas1.pack()

def copy_button():
    clip = tk.Tk()
    clip.withdraw()
    clip.clipboard_clear()
    clip.clipboard_append(pw)
    clip.destroy()

button1 = tk.Button(text="Copy to Clipboard", command=copy_button, bg="grey", fg="white", font=("Helvetica", 12, "bold"))
canvas1.create_window(150, 150, window=button1)
</code>```

答:
Your disappearing text issue does not appear in Linux OS but I suspect your issue is related to your button1 = tk.Button(....) statement.

The first argument to a tk.Button widget must be its parent (see this link on this requirement) and not a keyword/option.

Try button1 = tk.Button(canvas1, text="Copy to Clipboard", ....). Doing so, you define the tk.Button to be a child of the tk.Canvas widget.

If you are putting more than a button in the canvas, you might want to consider:

defining a tk.Frame to be a child of the tk.Canvas(e.g. frame1=tk.Frame(canvas1)),

replace window=button1 with window=frame1,

letting button1 to be a child of frame1, e.g. button1 = tk.Button(frame1, text="Copy to Clipboard", ....)

Do let me know if this answer addresses your issue.

Other suggestion:

You can remove  clip = tk.Tk(), clip.withdraw(), clip.destroy() and replace the clip term in clip.clipboard_clear() and clip.clipboard_append(pw) with root. Here, I assume that you had earlier defined root = tk.Tk() at the start of your code.

Body:
So I made a button to copy something to clipboard, but the button itself is always showing, but the text on it only when its pressed, how to fix it?
(Here the part with the button code:)

canvas1 = tk.Canvas(root, width=300, height=300)
canvas1.pack()

def copy_button():
    clip = tk.Tk()
    clip.withdraw()
    clip.clipboard_clear()
    clip.clipboard_append(pw)
    clip.destroy()

button1 = tk.Button(text="Copy to Clipboard", command=copy_button, bg="grey", fg="white", font=("Helvetica", 12, "bold"))
canvas1.create_window(150, 150, window=button1)


问:
php $_GET passing variables from one page to another
I'm trying to pass my variables from one page to another, I'm using $_GET and it's grabbing my variables but on the same page instead of a new one, is it possible to pass them to a new page using $_GET or do I have to do another method, I've seen this done on the site using javascript asp and jquery but cant seem to find one with PHP that is explaining things very well.

this is what I have, other then this I'm pretty clueless on how to make this happen.

```<code>foreach($obj->jigsawes as $jigsaw):

   if(isset($_GET['p']) && $_GET['p']==''.$query.'') {
echo "<a href='?p=$jigsaw_url'><img border=0 src='".$jigsaw->photo_url."'></a><br />";

echo "$jigsaw->name</ br>
 $jigsaw->address1<br />
 $jigsaw->phone<br />
 $jigsaw->city<br />
 $jigsaw->state<br />
 $jigsaw->zip<br />";

}else{
$query = htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES);

echo "<div><a href='?$query'>$jigsaw->name</a></div>";
    }
endforeach;
}
</code>```

答:
You can use $_SERVER['QUERY_STRING'] to get the current $_GET variables in a string, e.g:

```<code>$query = htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES);
echo "<a href='?$query'><img border=0 src='".$jigsaw->photo_url."'></a>";
</code>```

Note the use of htmlspecialchars in case it contains any nasty characters (potential XSS vector.)

Since in this case you're just loading the same page, href="" should work just as well.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to pass my variables from one page to another, I'm using $_GET and it's grabbing my variables but on the same page instead of a new one, is it possible to pass them to a new page using $_GET or do I have to do another method, I've seen this done on the site using javascript asp and jquery but cant seem to find one with PHP that is explaining things very well.

this is what I have, other then this I'm pretty clueless on how to make this happen.

foreach($obj->jigsawes as $jigsaw):

   if(isset($_GET['p']) && $_GET['p']==''.$query.'') {
echo "photo_url."'>
";

echo "$jigsaw->name

 $jigsaw->address1

 $jigsaw->phone

 $jigsaw->city

 $jigsaw->state

 $jigsaw->zip
";

}else{
$query = htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES);

echo "
$jigsaw->name
";
    }
endforeach;
}

Body:
You can use $_SERVER['QUERY_STRING'] to get the current $_GET variables in a string, e.g:

$query = htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES);
echo "<a href='?$query'><img border=0 src='".$jigsaw->photo_url."'></a>";

Note the use of htmlspecialchars in case it contains any nasty characters (potential XSS vector.)

Since in this case you're just loading the same page, href="" should work just as well.


问:
Athena array aggregate and filter multiple columns on condition
I have data as shown below.

uuid
movie
data

1
movie1
{title=rental, label=GA, price=50, feetype=rental, hidden=false}

1
movie1
{title=tax, label=GA, price=25, feetype=service-fees, hidden=true}

1
movie1
{title=rental, label=GA, price=50, feetype=rental, hidden=false}

1
movie1
{title=tax, label=GA, price=25, feetype=service-fees, hidden=true}

2
movie3
{title=rental, label=VIP, price=100, feetype=rental, hidden=false}

2
movie3
{title=tax, label=VIP, price=25, feetype=service-fees, hidden=true}

2
movie3
{title=promo, label=VIP, price=10, feetype=discount, hidden=false}

and, this is how i want the result to be like.

uuid
total_fee
total_discount
discount_type

1
150
0
NA

2
125
10
promo

I tried using

```<code>SELECT uuid
   , sum("fee"."price") "total_fee"
   , array_agg(distinct("fee"."feetype")) "fee_type"
   , array_agg(distinct("fee"."title")) "fee_name"
</code>```

This gives the result as shown below,

uuid
total_fee
fee_type
fee_name

1
100
[rental]
[rental]

1
50
[service-fees]
[tax]

2
100
[rental]
[rental]

2
25
[service-fees]
[tax]

2
10
[discount]
[promo]

Now how do I aggregate on total_fee and filter fee_name based on fee_type?

I tried using

```<code>, CASE WHEN regexp_like(array_join(fee_type, ','), 'discount') THEN sum("fee") ELSE 0  END "discount"
</code>```

but that resulted in

```<code>SYNTAX_ERROR: line 207:6: '(CASE WHEN "regexp_like"("array_join"(fee_type, ','), 'discount') THEN "sum"("fee") ELSE 0 END)' must be an aggregate expression or appear in GROUP BY clause
</code>```

答:
You should be able to do something like this:

SELECT
  uuid,
  SUM(fee.price) AS total_fee,
  SUM(fee.price) FILTER (WHERE fee.feetype = 'discount') AS total_discount,
  ARBITRARY(fee.title) FILTER (WHERE fee.feetype = 'discount') AS discount_type
FROM …
GROUP BY uuid
```

(I'm assuming the data column in your example is the same as the fee column in your query).

Aggregate functions support a FILTER clause that selects the rows to include into the aggregation. This can also be achieved by e.g. SUM(IF(fee.feetype = 'discount', fee.price, 0)), which is more compact but not as elegant.

The ARBITRARY aggregate function picks an arbitrary value from the group. I don't know if that's appropriate in your case, but I assume that there will only be one discount row per group. If there are more than one you might want to use ARRAY_AGG with the DISTINCT clause (e.g. ARRAY_AGG(DISTINCT fee.title) to get the all).

Body:
I have data as shown below.

uuid
movie
data

1
movie1
{title=rental, label=GA, price=50, feetype=rental, hidden=false}

1
movie1
{title=tax, label=GA, price=25, feetype=service-fees, hidden=true}

1
movie1
{title=rental, label=GA, price=50, feetype=rental, hidden=false}

1
movie1
{title=tax, label=GA, price=25, feetype=service-fees, hidden=true}

2
movie3
{title=rental, label=VIP, price=100, feetype=rental, hidden=false}

2
movie3
{title=tax, label=VIP, price=25, feetype=service-fees, hidden=true}

2
movie3
{title=promo, label=VIP, price=10, feetype=discount, hidden=false}

and, this is how i want the result to be like.

uuid
total_fee
total_discount
discount_type

1
150
0
NA

2
125
10
promo

I tried using

SELECT uuid
   , sum("fee"."price") "total_fee"
   , array_agg(distinct("fee"."feetype")) "fee_type"
   , array_agg(distinct("fee"."title")) "fee_name"

This gives the result as shown below,

uuid
total_fee
fee_type
fee_name

1
100
[rental]
[rental]

1
50
[service-fees]
[tax]

2
100
[rental]
[rental]

2
25
[service-fees]
[tax]

2
10
[discount]
[promo]

Now how do I aggregate on total_fee and filter fee_name based on fee_type?

I tried using

, CASE WHEN regexp_like(array_join(fee_type, ','), 'discount') THEN sum("fee") ELSE 0  END "discount"

but that resulted in

SYNTAX_ERROR: line 207:6: '(CASE WHEN "regexp_like"("array_join"(fee_type, ','), 'discount') THEN "sum"("fee") ELSE 0 END)' must be an aggregate expression or appear in GROUP BY clause

Body:
You should be able to do something like this:

SELECT
  uuid,
  SUM(fee.price) AS total_fee,
  SUM(fee.price) FILTER (WHERE fee.feetype = 'discount') AS total_discount,
  ARBITRARY(fee.title) FILTER (WHERE fee.feetype = 'discount') AS discount_type
FROM …
GROUP BY uuid

(I'm assuming the data column in your example is the same as the fee column in your query).

Aggregate functions support a FILTER clause that selects the rows to include into the aggregation. This can also be achieved by e.g. SUM(IF(fee.feetype = 'discount', fee.price, 0)), which is more compact but not as elegant.

The ARBITRARY aggregate function picks an arbitrary value from the group. I don't know if that's appropriate in your case, but I assume that there will only be one discount row per group. If there are more than one you might want to use ARRAY_AGG with the DISTINCT clause (e.g. ARRAY_AGG(DISTINCT fee.title) to get the all).


问:
Can't perform a React state update on an unmounted component Error on Firebase onAuthStateChanged
I am trying to route to '/' after the user successfully logs in.

Currently, in my Login.JS file, I have the handleSubmit function that gets the result from the form:

```<code> async function handleSubmit(e) {
        e.preventDefault()

        try {
            setError("")
            setLoading(true)
            await login(emailRef.current.value, passwordRef.current.value)
            history.push("/")
        } catch(error) {
            console.log(error)
            setError("Failed to Log In")
        }
        setLoading(false)
    }
</code>```

Then, I have a AuthContext that passes the Login context

```<code>import React, { useContext, useEffect, useState } from 'react';
import { onAuthStateChanged, getAuth, signInWithEmailAndPassword} from 'firebase/auth';
import app from '../firebase'

const AuthContext = React.createContext()

export function useAuth() {
    return useContext(AuthContext)
}

export function AuthProvider({ children }) {
    const auth = getAuth()
    const [currentUser, setCurrentUser] = useState()
    const [loading, setLoading] = useState(true)

    function login(email, password) {
        return signInWithEmailAndPassword(auth, email, password)
    }

    useEffect(() => {
        const unsubscribe = onAuthStateChanged(auth, (user) => {
            setCurrentUser(user)
            setLoading(false)
        })
        return unsubscribe;
    }, [auth])

    const value = {
        currentUser,
        login
    }
    return (
        <AuthContext.Provider value={value}>
            {!loading && children}
        </AuthContext.Provider>
    )
}
</code>```

I can see that the user is able to LogIn, however, it doesn't render anything in the '/' page and shows this error message in the console:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

答:
There are two possible spots that might be causing this; i'm not sure which one it is.

First possibility: in the use effect, you set state twice back to back. React tries to batch multiple set states and do a single render, but since this is an asynchronous callback outside of react's control, it can't do so here. So you'll probably get one render for changing the user, then another render for changing loading. If that first render causes the component to unmount, it might result in the error when you set loading.

In react 18, this batching issue will be gone, but until then, you can make the two set states happen as a group like this:

```<code>import { unstable_batchedUpdates } from "react-dom";
// ...

useEffect(() => {
  const unsubscribe = onAuthStateChanged(auth, (user) => {
    unstable_batchedUpdates(() => {
      setCurrentUser(user);
      setLoading(false);
    });
  });
  return unsubscribe;
}, [auth]);

</code>```

Second possibility: it could be in handleSubmit. You set some state, kick off the login and await it, push to history, then set state again. If the component unmounts while waiting for the promise, or when pushing to history, you would get this issue. If this is the cause, then you can have a ref which gets updated when the component unmounts, and check that ref before doing your final set state:

```<code>const mounted = useRef(true);
useEffect(() => {
  return () => {
    mounted.current = false;
  }
}, []);

async function handleSubmit(e) {
  e.preventDefault();

  try {
    setError("");
    setLoading(true);
    await login(emailRef.current.value, passwordRef.current.value);
    history.push("/");
  } catch (error) {
    console.log(error);
    if (mounted.current) {
      setError("Failed to Log In");
    }
  }
  if (mounted.current) {
    setLoading(false);
  }
}
</code>```

P.S, they will be removing this warning from react because of all the false positives it results in, your case being one of them. There's no actual memory leak in your code. You set state a single time after unmounting, which react harmlessly ignores, and then that's it You are correctly tearing down your onAuthStateChanged listener.

Body:
I am trying to route to '/' after the user successfully logs in.

Currently, in my Login.JS file, I have the handleSubmit function that gets the result from the form:

 async function handleSubmit(e) {
        e.preventDefault()

        try {
            setError("")
            setLoading(true)
            await login(emailRef.current.value, passwordRef.current.value)
            history.push("/")
        } catch(error) {
            console.log(error)
            setError("Failed to Log In")
        }
        setLoading(false)
    }

Then, I have a AuthContext that passes the Login context

import React, { useContext, useEffect, useState } from 'react';
import { onAuthStateChanged, getAuth, signInWithEmailAndPassword} from 'firebase/auth';
import app from '../firebase'

const AuthContext = React.createContext()

export function useAuth() {
    return useContext(AuthContext)
}

export function AuthProvider({ children }) {
    const auth = getAuth()
    const [currentUser, setCurrentUser] = useState()
    const [loading, setLoading] = useState(true)

    function login(email, password) {
        return signInWithEmailAndPassword(auth, email, password)
    }

    useEffect(() => {
        const unsubscribe = onAuthStateChanged(auth, (user) => {
            setCurrentUser(user)
            setLoading(false)
        })
        return unsubscribe;
    }, [auth])

    const value = {
        currentUser,
        login
    }
    return (
        <AuthContext.Provider value={value}>
            {!loading && children}
        </AuthContext.Provider>
    )
}

I can see that the user is able to LogIn, however, it doesn't render anything in the '/' page and shows this error message in the console:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Body:
There are two possible spots that might be causing this; i'm not sure which one it is.

First possibility: in the use effect, you set state twice back to back. React tries to batch multiple set states and do a single render, but since this is an asynchronous callback outside of react's control, it can't do so here. So you'll probably get one render for changing the user, then another render for changing loading. If that first render causes the component to unmount, it might result in the error when you set loading.

In react 18, this batching issue will be gone, but until then, you can make the two set states happen as a group like this:

import { unstable_batchedUpdates } from "react-dom";
// ...

useEffect(() => {
  const unsubscribe = onAuthStateChanged(auth, (user) => {
    unstable_batchedUpdates(() => {
      setCurrentUser(user);
      setLoading(false);
    });
  });
  return unsubscribe;
}, [auth]);

Second possibility: it could be in handleSubmit. You set some state, kick off the login and await it, push to history, then set state again. If the component unmounts while waiting for the promise, or when pushing to history, you would get this issue. If this is the cause, then you can have a ref which gets updated when the component unmounts, and check that ref before doing your final set state:

const mounted = useRef(true);
useEffect(() => {
  return () => {
    mounted.current = false;
  }
}, []);

async function handleSubmit(e) {
  e.preventDefault();

  try {
    setError("");
    setLoading(true);
    await login(emailRef.current.value, passwordRef.current.value);
    history.push("/");
  } catch (error) {
    console.log(error);
    if (mounted.current) {
      setError("Failed to Log In");
    }
  }
  if (mounted.current) {
    setLoading(false);
  }
}

P.S, they will be removing this warning from react because of all the false positives it results in, your case being one of them. There's no actual memory leak in your code. You set state a single time after unmounting, which react harmlessly ignores, and then that's it You are correctly tearing down your onAuthStateChanged listener.


问:
Looping in R to only add leading zeros to specified length
how would I be able to go from a column like this:
1
1
1
2
3
4
9
25
100

to one like this:
01
01
01
02
03
04
09
25
100

Basically, I want to add a leading zero to any value with only length 1. The actual data frame is much bigger than this. Thanks!

答:
As an alternative str_pad from stringr package:

```<code>library(stringr)
str_pad(vec, 2, pad = "0")
</code>```
```<code>[1] "01"  "01"  "01"  "02"  "03"  "04"  "09"  "25"  "100"
</code>```

Body:
As an alternative str_pad from stringr package:

library(stringr)
str_pad(vec, 2, pad = "0")

[1] "01"  "01"  "01"  "02"  "03"  "04"  "09"  "25"  "100"


问:
Timeout Pattern - How bad is Thread.Abort really?
I've read at various websites that Thread.Abort is not very good to use. In this case, how do you implement a timeout pattern? For instance, I've read that MS uses the pattern below (which I've wrapped in an extension method) throughout the framework. Personally, I think this is a pretty cool extension, but I'm worried about the Thread.Abort. Does anyone have a better way?</p>

```<code> public static bool CallandWait(this Action action, int timeout)
    {
        Thread subThread = null;
        Action wrappedAction = () =>
        {
            subThread = Thread.CurrentThread;
            action();
        };

        IAsyncResult result = wrappedAction.BeginInvoke(null, null);

        if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
        {
            if (subThread != null)
            {
                subThread.Abort();
            }

            return false;
        }
        else
        {
            wrappedAction.EndInvoke(result);
            return true;
        }
    }
</code>```

答:
It's bad because the thread might be in an inconsistent state or in the middle of some work, and not have the opportunity to clear itself up.

To close it properly, you signal for it to stop what it's doing by calling a method or setting a property, then do Thread.Join to wait until it closes before closing your application or moving onto other tasks.

OwnerDisplayName: Steve

ContentLicense: CC BY-SA 2.5

Body:
I've read at various websites that Thread.Abort is not very good to use. In this case, how do you implement a timeout pattern? For instance, I've read that MS uses the pattern below (which I've wrapped in an extension method) throughout the framework. Personally, I think this is a pretty cool extension, but I'm worried about the Thread.Abort. Does anyone have a better way?

 public static bool CallandWait(this Action action, int timeout)
    {
        Thread subThread = null;
        Action wrappedAction = () =>
        {
            subThread = Thread.CurrentThread;
            action();
        };

        IAsyncResult result = wrappedAction.BeginInvoke(null, null);

        if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
        {
            if (subThread != null)
            {
                subThread.Abort();
            }

            return false;
        }
        else
        {
            wrappedAction.EndInvoke(result);
            return true;
        }
    }

OwnerDisplayName: Neil Barnwell


答:
Instead of:

```<code>alert(testJSON.widgets.column1.length);
</code>```

use

```<code>alert(testJSON.widgets[0].column1.length);
</code>```

"column1" is a property in the first of object of the array "testJSON.widgets"

Title: JavaScript Sorting Multidimensional JSON

Body:
I have this JSON string:

{
"widgets":[
    {"column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ]},
    {"column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ]},
    {"column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]}
]}

if I do

alert(testJSON.widgets.length);

I get 3, however if I do

alert(testJSON.widgets.column1.length);

I get "testJSON.widgets.column3 is undefined" as an error.

What I am ultimately attempting to do is take each column1-3 and sort them by weight. Through something like

testJSON.widgets.column1.sort(function(a,b) { return parseFloat(a.weight) - parseFloat(b.weight) });

So I can then do a $.each() via jquery

Body:
Instead of:

alert(testJSON.widgets.column1.length);

use

alert(testJSON.widgets[0].column1.length);

"column1" is a property in the first of object of the array "testJSON.widgets"


问:
Scalable set of controls to display file tiles
What certain set of xaml controls enables UI to display file tiles in a wpf window?

There are 3 rows on a grid, I need to display any folder's data on the second row and the first column.

```<code><Grid x:Name="explorerGrid" MouseLeftButtonDown="explorerGrid_MouseRightButtonDown">
    <Grid.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF08C0F0" Offset="0"/> <GradientStop Color="White" Offset="1"/>
        </LinearGradientBrush>
    </Grid.Background>
    <Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="320"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="24"></RowDefinition><RowDefinition Height="*"></RowDefinition> <RowDefinition Height="35"></RowDefinition>
    </Grid.RowDefinitions> <!--other controls-->
</Grid>
</code>```

答:
I've found the solution - it is the ItemsControl  with an ItemsControl.ItemsPanel

```<code>public class FileIconInfo
{
    public Icon Icon { get; set; }
    public FileInfo FileInfo { get; set; }
    public ImageSource IconSource { get; set; }
}
</code>```

<ItemsControl Background="#34808F80" x:Name="icFiles" Grid.Row="1" Grid.Column="0" ItemsSource="{Binding FileIconInfos}">
    <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <WrapPanel> </WrapPanel> </ItemsPanelTemplate> </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="White" BorderThickness="1" Margin="10" Padding="10">
                <StackPanel Background="#44808F80" Orientation="Vertical">
                    <Image Height="32" Width="32" Source="{Binding IconSource}" />
                    <TextBlock Foreground="White" FontSize="12" Text="{Binding FileInfo.FullName}"/>
                    <TextBlock Foreground="White" FontSize="12" Text="{Binding FileInfo.DirectoryName}"/>
                </StackPanel>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
```

Body:
What certain set of xaml controls enables UI to display file tiles in a wpf window?

There are 3 rows on a grid, I need to display any folder's data on the second row and the first column.

<Grid x:Name="explorerGrid" MouseLeftButtonDown="explorerGrid_MouseRightButtonDown">
    <Grid.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF08C0F0" Offset="0"/> <GradientStop Color="White" Offset="1"/>
        </LinearGradientBrush>
    </Grid.Background>
    <Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="320"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="24"></RowDefinition><RowDefinition Height="*"></RowDefinition> <RowDefinition Height="35"></RowDefinition>
    </Grid.RowDefinitions>
</Grid>

Body:
I've found the solution - it is the ItemsControl  with an ItemsControl.ItemsPanel

public class FileIconInfo
{
    public Icon Icon { get; set; }
    public FileInfo FileInfo { get; set; }
    public ImageSource IconSource { get; set; }
}

<ItemsControl Background="#34808F80" x:Name="icFiles" Grid.Row="1" Grid.Column="0" ItemsSource="{Binding FileIconInfos}">
    <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <WrapPanel> </WrapPanel> </ItemsPanelTemplate> </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="White" BorderThickness="1" Margin="10" Padding="10">
                <StackPanel Background="#44808F80" Orientation="Vertical">
                    <Image Height="32" Width="32" Source="{Binding IconSource}" />
                    <TextBlock Foreground="White" FontSize="12" Text="{Binding FileInfo.FullName}"/>
                    <TextBlock Foreground="White" FontSize="12" Text="{Binding FileInfo.DirectoryName}"/>
                </StackPanel>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>


问:
React From Group input field is not working
I attached dropdown items to my form group input field (image below). When I add onChange() key in order to get its value, I cannot write anything to input field. But when I remove onChange() key, it is working, I am able to write anything, but I need to get the value of input field. Is there any other way than onChange() key or any solution? Thank you in advance :)
Here is the my code:

```<code><Form.Control
        ref={ref}
        onClick={e => {
          e.preventDefault();
          onClick(e);
        }}
        size="sm"
        type="text"
        className="search-or-jump shadow-none"
        placeholder="Search or jump to..."
        onChange={event => setSearchName(event.target.value)}
      />
      {children}
    </Form.Group>
</code>```

答:
You have to add value attributes, like

```<code><Form.Control
    ref={ref}
    onClick={e => {
        e.preventDefault();
        onClick(e);
    }}
    size="sm"
    type="text"
    className="search-or-jump shadow-none"
    placeholder="Search or jump to..."
    value={searchName}
    onChange={event => setSearchName(event.target.value)}
/>
   {children}
</Form.Group>
</code>```

Your code didn't have value attribule but you called 'value' on 'onChange' that why your code didn't work.

Body:
I attached dropdown items to my form group input field (image below). When I add onChange() key in order to get its value, I cannot write anything to input field. But when I remove onChange() key, it is working, I am able to write anything, but I need to get the value of input field. Is there any other way than onChange() key or any solution? Thank you in advance :)
Here is the my code:

<Form.Control
        ref={ref}
        onClick={e => {
          e.preventDefault();
          onClick(e);
        }}
        size="sm"
        type="text"
        className="search-or-jump shadow-none"
        placeholder="Search or jump to..."
        onChange={event => setSearchName(event.target.value)}
      />
      {children}
    </Form.Group>

Body:
You have to add value attributes, like

<Form.Control
    ref={ref}
    onClick={e => {
        e.preventDefault();
        onClick(e);
    }}
    size="sm"
    type="text"
    className="search-or-jump shadow-none"
    placeholder="Search or jump to..."
    value={searchName}
    onChange={event => setSearchName(event.target.value)}
/>
   {children}
</Form.Group>

Your code didn't have value attribule but you called 'value' on 'onChange' that why your code didn't work.


问:
Laravel Get method return value for each related model
I have a Client model that has a hasMany relationship to a Location model. In my Location model I have a status() method that returns an array.

In my ClientController, I'm getting the client model, and then getting all related Locations, but I also want to include the array returned from the status method attached to each location. I'm unsure of how to do this. I'm sure I can do it by just using a foreach loop over each location, but I'm wondering if there's an "eloquent" way of doing it.

Here is my ClientController:

```<code>    public function show($id)
    {
        $client = Client::findOrFail($id);

        $locations = $client->locations()->withTrashed()->get();

        //foreach($locations as $location)
        //{
         //   print_r($location->status());
        //}

        return view('pages.clients.show')
            ->with('client', $client)
            ->with('locations', $locations)
    }
</code>```

Here's my Location Model method:

```<code>    public function status()
    {
        $result = array();

        if($this->deleted_at)
        {
           $result['color'] = 'danger';
           $result['value'] = 'Inactive';
        }
        elseif($this->is_onboarding_completed)
        {
            $result['color'] = 'success';
            $result['value'] = 'Active';
        }
        else
        {
            $result['color'] = 'warning';
            $result['value'] = 'Onboarding';
        }

        return $result;
    }
</code>```

My Location relationship:

```<code>    public function client()
    {
        return $this->belongsTo(Client::class);
    }
</code>```

My Client relationship:

```<code>    public function locations()
    {
       return $this->hasMany(Location::class);
    }
</code>```

Also, I'd like to know if/how I can return the status automatically with the location whenever it's returned. I know I can do this with locations using protected $with = [];, but I get an error when I tried to include a non-relationship.

Also, any design improvements welcome, if there's a better way to do this.

答:
As @lagbox said in the comment box, you need an accessor.

Location model :

```<code>public function getStatusAttribute()
{
    $result = [];

    if($this->deleted_at)
    {
        $result['color'] = 'danger';
        $result['value'] = 'Inactive';
    }
    elseif($this->is_onboarding_completed)
    {
        $result['color'] = 'success';
        $result['value'] = 'Active';
    }
    else
    {
        $result['color'] = 'warning';
        $result['value'] = 'Onboarding';
    }

    return $result;
}
</code>```

Controller :

```<code>public function show($id)
{
    $client = Client::findOrFail($id);
    $locations = $client->locations()->withTrashed()->get();

    foreach($locations as $location)
    {
       dd($location->status);
    }

    ...
}
</code>```

Body:
I have a Client model that has a hasMany relationship to a Location model. In my Location model I have a status() method that returns an array.

In my ClientController, I'm getting the client model, and then getting all related Locations, but I also want to include the array returned from the status method attached to each location. I'm unsure of how to do this. I'm sure I can do it by just using a foreach loop over each location, but I'm wondering if there's an "eloquent" way of doing it.

Here is my ClientController:

    public function show($id)
    {
        $client = Client::findOrFail($id);

        $locations = $client->locations()->withTrashed()->get();

        //foreach($locations as $location)
        //{
         //   print_r($location->status());
        //}

        return view('pages.clients.show')
            ->with('client', $client)
            ->with('locations', $locations)
    }

Here's my Location Model method:

    public function status()
    {
        $result = array();

        if($this->deleted_at)
        {
           $result['color'] = 'danger';
           $result['value'] = 'Inactive';
        }
        elseif($this->is_onboarding_completed)
        {
            $result['color'] = 'success';
            $result['value'] = 'Active';
        }
        else
        {
            $result['color'] = 'warning';
            $result['value'] = 'Onboarding';
        }

        return $result;
    }

My Location relationship:

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

My Client relationship:

    public function locations()
    {
       return $this->hasMany(Location::class);
    }

Also, I'd like to know if/how I can return the status automatically with the location whenever it's returned. I know I can do this with locations using protected $with = [];, but I get an error when I tried to include a non-relationship.

Also, any design improvements welcome, if there's a better way to do this.

Body:
As @lagbox said in the comment box, you need an accessor.

Location model :

public function getStatusAttribute()
{
    $result = [];

    if($this->deleted_at)
    {
        $result['color'] = 'danger';
        $result['value'] = 'Inactive';
    }
    elseif($this->is_onboarding_completed)
    {
        $result['color'] = 'success';
        $result['value'] = 'Active';
    }
    else
    {
        $result['color'] = 'warning';
        $result['value'] = 'Onboarding';
    }

    return $result;
}

Controller :

public function show($id)
{
    $client = Client::findOrFail($id);
    $locations = $client->locations()->withTrashed()->get();

    foreach($locations as $location)
    {
       dd($location->status);
    }

    ...
}


问:
Forcing the MobX state to be changed through declared actions only in the Flutter framework
I'm experimenting with MobX state management solution in Flutter. I really like its conciseness and its simplicity but I'm a bit concerned in the drawbacks its way of mutating the state can introduce.
Theoretically , we can force the state to be mutated only using actions and this is great because we can have a history of the changes using the spy feature the package provides.
However, actions are automatically created by the framework if we do not use a specific one. For example, in the code below, I created a counter store class and I used it in the main function to assign a new value for the counter without using a predeclared action. The stric-mode has been previously set to "always".

```<code>
abstract class _Counter with Store {
  @observable
  int value = 0;

  @action
  void increment() {
    value++;
  }
}

final counter = Counter(); // Instantiate the store
void main() {
  mainContext.config = mainContext.config
      .clone(isSpyEnabled: true, writePolicy: ReactiveWritePolicy.always);
  mainContext.spy((event) {
    print("event name : " + event.name);
    print("event type : " + event.type);
  });
  Counter counter = Counter();
  counter.value = 10;
}
</code>```

I was expecting an error to raise saying that it is not possible to change the state outside of action but this does not happen because an ad hoc action is created , called value_set, automatically. I'm wondering ,then, which is the point of forcing to use actions if it is possible to avoid using   them. I mean, if we directly change the state, an action is created automatically and seen by the spy functionality making all the process more robust and predictable but, what if I want the state to be changed only by actions I previously implemented? Is there a way of doing so? For example, in the counter code I just provided , is there a way of making the counter incrementalbe only by 1? Because, in the way Mobx works, I could write everywhere in the code something like

```<code>counter.value = 10
</code>```

and this will work just fine without any problems. Forcing people to use preset actions could increase the predicatability a lot and facilitate the teamwork too I think.
I tried to make the value variable private but it still remains accessible from the outside , also if annotated with @readonly.

答:
At the end, I found out that the behaviour I was looking for was obtainable with the @readonly annotation. Marking a variable with @readonly annotation avoids automatically creating its setter and getter methods. Moreover it requires the annotated variable to be private, denying the variable to be set directly.

Note: By the way, the way the Dart language is implemented, it is necessary to locate the Counter in a separate file to provide the desired behaviour, otherwise its private fields would be accessible anyway.

Body:
I'm experimenting with MobX state management solution in Flutter. I really like its conciseness and its simplicity but I'm a bit concerned in the drawbacks its way of mutating the state can introduce.
Theoretically , we can force the state to be mutated only using actions and this is great because we can have a history of the changes using the spy feature the package provides.
However, actions are automatically created by the framework if we do not use a specific one. For example, in the code below, I created a counter store class and I used it in the main function to assign a new value for the counter without using a predeclared action. The stric-mode has been previously set to "always".

abstract class _Counter with Store {
  @observable
  int value = 0;

  @action
  void increment() {
    value++;
  }
}

final counter = Counter(); // Instantiate the store
void main() {
  mainContext.config = mainContext.config
      .clone(isSpyEnabled: true, writePolicy: ReactiveWritePolicy.always);
  mainContext.spy((event) {
    print("event name : " + event.name);
    print("event type : " + event.type);
  });
  Counter counter = Counter();
  counter.value = 10;
}

I was expecting an error to raise saying that it is not possible to change the state outside of action but this does not happen because an ad hoc action is created , called value_set, automatically. I'm wondering ,then, which is the point of forcing to use actions if it is possible to avoid using   them. I mean, if we directly change the state, an action is created automatically and seen by the spy functionality making all the process more robust and predictable but, what if I want the state to be changed only by actions I previously implemented? Is there a way of doing so? For example, in the counter code I just provided , is there a way of making the counter incrementalbe only by 1? Because, in the way Mobx works, I could write everywhere in the code something like

counter.value = 10

and this will work just fine without any problems. Forcing people to use preset actions could increase the predicatability a lot and facilitate the teamwork too I think.
I tried to make the value variable private but it still remains accessible from the outside , also if annotated with @readonly.


问:
How to Create a Java Quiz GUI?
I would like to create a quiz for my Java GUI.

I'd like it to display a question on one page, then have a next button which takes the user to another page telling them if that question was correct or not, and if it is correct they can move on to the next question (by clicking another next button) and if they got it wrong, have to go back and answer it again. However I have no clue how to do this!!

So far I have a simple GUI with a welcome page and tabs down the side, one of which includes a quiz. Would it be a better idea to create the quiz in Flash or something and then embed it into my Java application? Or just do the whole thing in Java? I'm really new to java so I'm not at all sure what to do, any help would be greatly appreciated!

Thanks

答:
It would be best to use just Java. Consider using CardLayout with your GUI to allow swapping questions, or else you can create and modify key components on the fly such as the text displayed by JLabels and JRadioButtons.

Key though before considering any GUI structures  is to first create solid OOPS based non GUI classes to handle your questions. For instance, you may want classes for:

Question class that holds a question String, a List of possible answer Strings, a correct answer String. This class can randomly order the incorrect and correct answers, can have a method for checking if the answer selected is correct.

A Test class that holds a collection of questions, that can present questions in random order, that can hold the score obtained.

A QuestionReaderWriter class that can read and write questions to a text file (you definitely do not want to hard-code the question text).

Title: How to Create a Java Quiz GUI?


问:
How do i turn this string into 2 arrays in python?
I have this string and want to turn it into two arrays, one has the film title and the other one has the year. Their positions in the array need to correspond with each other. Is there a way to do this?</p>
```<code>films = ("""Endless Love (1981), Top Gun (1986), The Color of Money (1986), Rain Man (1988),
Born on the Fourth of July (1989), Interview with the Vampire: The Vampire Chronicles (1994),
Mission: Impossible (1996), Jerry Maguire (1996), The Matrix (1999), Mission: Impossible II (2000),
Vanilla Sky (2001), Cocktail (1988), A Few Good Men (1992), The Firm (1993), Eyes Wide Shut (1999),
Magnolia (1999), Minority Report (2002), Austin Powers in Goldmember (2002), Days of Thunder (1990),
The Powers of Matthew Star (1982), Cold Mountain (2003), The Talented Mr. Ripley (1999),
 War of the Worlds (2005), The Oprah Winfrey Show (1986), Far and Away (1992), Taps (1981),
 The Last Samurai (2003), Valkyrie (2008), Jack Reacher (2012), Edge of Tomorrow (2014),
 Enemy of the State (1998), Mission: Impossible III (2006), Crimson Tide (1995), Reign Over Me (2007),
 Batman Forever (1995), Batman Begins (2005), The Simpsons (1989), The Simpsons: Brother from the Same Planet (1993),
 The Simpsons: When You Dish Upon a Star (1998), End of Days (1999), House of D (2004), The Indian Runner (1991),
  Harry & Son (1984), Mission: Impossible - Ghost Protocol (2011), Aladdin (1992), Pacific Rim (2013),
  Oblivion (2013), Knight and Day (2010),
""")
</code>```

答:
You can do something like this (without any kind of import or extra module needed, or regex complexity):

```<code>delimeter = ", "
movies_with_year = pfilms.split(delimeter)
movies = []
years = []
for movie_with_year in movies_with_year:
    movie = movie_with_year[:-6]
    year = movie_with_year[-6:].replace("(","").replace(")","")
    movies.append(movie)
    years.append(year)
</code>```

This script will result in something like this:

movies : ['Endless Love ', ...]

years : ['1981', ...]

Body:
I have this string and want to turn it into two arrays, one has the film title and the other one has the year. Their positions in the array need to correspond with each other. Is there a way to do this?

films = ("""Endless Love (1981), Top Gun (1986), The Color of Money (1986), Rain Man (1988),
Born on the Fourth of July (1989), Interview with the Vampire: The Vampire Chronicles (1994),
Mission: Impossible (1996), Jerry Maguire (1996), The Matrix (1999), Mission: Impossible II (2000),
Vanilla Sky (2001), Cocktail (1988), A Few Good Men (1992), The Firm (1993), Eyes Wide Shut (1999),
Magnolia (1999), Minority Report (2002), Austin Powers in Goldmember (2002), Days of Thunder (1990),
The Powers of Matthew Star (1982), Cold Mountain (2003), The Talented Mr. Ripley (1999),
 War of the Worlds (2005), The Oprah Winfrey Show (1986), Far and Away (1992), Taps (1981),
 The Last Samurai (2003), Valkyrie (2008), Jack Reacher (2012), Edge of Tomorrow (2014),
 Enemy of the State (1998), Mission: Impossible III (2006), Crimson Tide (1995), Reign Over Me (2007),
 Batman Forever (1995), Batman Begins (2005), The Simpsons (1989), The Simpsons: Brother from the Same Planet (1993),
 The Simpsons: When You Dish Upon a Star (1998), End of Days (1999), House of D (2004), The Indian Runner (1991),
  Harry & Son (1984), Mission: Impossible - Ghost Protocol (2011), Aladdin (1992), Pacific Rim (2013),
  Oblivion (2013), Knight and Day (2010),
""")

Body:
You can do something like this (without any kind of import or extra module needed, or regex complexity):

delimeter = ", "
movies_with_year = pfilms.split(delimeter)
movies = []
years = []
for movie_with_year in movies_with_year:
    movie = movie_with_year[:-6]
    year = movie_with_year[-6:].replace("(","").replace(")","")
    movies.append(movie)
    years.append(year)

This script will result in something like this:

movies : ['Endless Love ', ...]

years : ['1981', ...]


问:
Javascript toggle element display
I have a website with a menu element in a header grid and when the page is first displayd the menu is visible.
I have a hamburger element which I want to use to toggle the menu display when it is clicked.

The CSS for the menu is:

```<code>/*==================================================================*/
/* NAVIGATION */
.main-nav {
    grid-area: N;
    text-transform: uppercase;
}

/* Style the nav links */
.main-nav ul {
    display: grid;
    grid-template-columns: repeat(4,20vw);
}

.main-nav li {
    /* No bullets */
    text-align: center;
    list-style-type: none;
    min-width: 20vw;
}

.main-nav a {
    /* Not italic unlike all other a elements */
    text-decoration: none;
    font-style: normal;
}
</code>```

The hanburger uses a javascript function:

```<code>/* Toggle between showing and hiding the navigation menu links when the user clicks on the hamburger menu / bar icon */
function toggleMenu() {
    let menu = document.getElementById("main-nav");

    if (menu.display == "none"){
        alert("Hidden");
        menu.style.display = "grid";
    }
    else {
        alert("Displayed");
        menu.style.display = "none";
    }

};
</code>```

When the page loads, this function is used in the hamburger's click event listener:

```<code> document.getElementById("hamburger").addEventListener("click", toggleMenu);
</code>```

Now, what happens is this - the page loads, the menu is visible:

I click on the hamburger the alert tells me the menu is currently visible:

Then the menu is hidden:

However, if I now click the hamburger again I get a message telling me that the menu is displayed(!) and it does not re-appear:

So, what I don't understand is why the element's style.display status is incorrect when the menu is clearly display:none;?

Of course, this then means that the function fails to re-show the menu as the status check is incorrect.

If you need any more code let me know but as far as I can see all the code involved is in the question.

Thanks in advance,

Dermot

答:
In the end it was a simple error of leaving out .style as per Simon K's comment:

```<code>if (menu.style.display == "none"){
        alert("Hidden");
        menu.style.display = "grid";
    }
    else {
        alert("Displayed");
        menu.style.display = "none";
    }
</code>```

Checking for meun.display did nothing as there was nothing to check for!

Many thanks to Simon K for spotting that!

Title: Javascript toggle element display

Body:
I have a website with a menu element in a header grid and when the page is first displayd the menu is visible.
I have a hamburger element which I want to use to toggle the menu display when it is clicked.

The CSS for the menu is:

/*==================================================================*/
/* NAVIGATION */
.main-nav {
    grid-area: N;
    text-transform: uppercase;
}

/* Style the nav links */
.main-nav ul {
    display: grid;
    grid-template-columns: repeat(4,20vw);
}

.main-nav li {
    /* No bullets */
    text-align: center;
    list-style-type: none;
    min-width: 20vw;
}

.main-nav a {
    /* Not italic unlike all other a elements */
    text-decoration: none;
    font-style: normal;
}

The hanburger uses a javascript function:

/* Toggle between showing and hiding the navigation menu links when the user clicks on the hamburger menu / bar icon */
function toggleMenu() {
    let menu = document.getElementById("main-nav");

    if (menu.display == "none"){
        alert("Hidden");
        menu.style.display = "grid";
    }
    else {
        alert("Displayed");
        menu.style.display = "none";
    }

};

When the page loads, this function is used in the hamburger's click event listener:

 document.getElementById("hamburger").addEventListener("click", toggleMenu);

Now, what happens is this - the page loads, the menu is visible:

I click on the hamburger the alert tells me the menu is currently visible:

Then the menu is hidden:

However, if I now click the hamburger again I get a message telling me that the menu is displayed(!) and it does not re-appear:

So, what I don't understand is why the element's style.display status is incorrect when the menu is clearly display:none;?

Of course, this then means that the function fails to re-show the menu as the status check is incorrect.

If you need any more code let me know but as far as I can see all the code involved is in the question.

Thanks in advance,

Dermot

Body:
In the end it was a simple error of leaving out .style as per Simon K's comment:

if (menu.style.display == "none"){
        alert("Hidden");
        menu.style.display = "grid";
    }
    else {
        alert("Displayed");
        menu.style.display = "none";
    }

Checking for meun.display did nothing as there was nothing to check for!

Many thanks to Simon K for spotting that!


问:
How to send an email with Gmail as provider using Python?
I am trying to send email (Gmail) using python, but I am getting following error.

```<code>Traceback (most recent call last):
File "emailSend.py", line 14, in <module>
server.login(username,password)
File "/usr/lib/python2.5/smtplib.py", line 554, in login
raise SMTPException("SMTP AUTH extension not supported by server.")
smtplib.SMTPException: SMTP AUTH extension not supported by server.
</code>```

The Python script is the following.

```<code>import smtplib

fromaddr = 'user_me@gmail.com'
toaddrs  = 'user_you@gmail.com'
msg = 'Why,Oh why!'
username = 'user_me@gmail.com'
password = 'pwd'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</code>```

答:
Dec, 2022 Update:

You need to use an app password to allow your app to access your google account.

Sign in with App Passwords:

An App Password is a 16-digit passcode that gives a less secure app or
device permission to access your Google Account. App Passwords can
only be used with accounts that have 2-Step Verification turned on.

In addition, google hasn't allowed your app to access your google account with username(email address) and password since May 30, 2022. So now, you need username(email address) and an app password to access your google account.

Less secure apps & your Google Account:

To help keep your account secure, from May 30, 2022, Google no
longer supports the use of third-party apps or devices which ask you
to sign in to your Google Account using only your username and
password.

How to generate an app password:

First, click on Account from 9 dots:

Then, click on App passwords from Security. *Don't forget to turn on 2-Step Verification before generating an app password otherwise you cannot generate an app password:

Then, click on Other (Custom name):

Then, put your app name, then click on GENERATE:

Finally, you could generate the app password xylnudjdiwpojwzm:

So, your code with the app password above is as shown below:

import smtplib

fromaddr = 'user_me@gmail.com'
toaddrs  = 'user_you@gmail.com'
msg = 'Why,Oh why!'
username = 'user_me@gmail.com'
password = 'xylnudjdiwpojwzm' # Here
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

```
<p>In addition, <code>settings.py</code> with <strong>the app password above</strong> in <strong>Django</strong> is as shown below:</p>
<pre class="lang-py prettyprint-override"><code># "settings.py"

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'myaccount@gmail.com'
EMAIL_HOST_PASSWORD = 'xylnudjdiwpojwzm' # Here
</code>```

Body:
I am trying to send email (Gmail) using python, but I am getting following error.

Traceback (most recent call last):
File "emailSend.py", line 14, in <module>
server.login(username,password)
File "/usr/lib/python2.5/smtplib.py", line 554, in login
raise SMTPException("SMTP AUTH extension not supported by server.")
smtplib.SMTPException: SMTP AUTH extension not supported by server.

The Python script is the following.

import smtplib

fromaddr = 'user_me@gmail.com'
toaddrs  = 'user_you@gmail.com'
msg = 'Why,Oh why!'
username = 'user_me@gmail.com'
password = 'pwd'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

Body:
Dec, 2022 Update:

You need to use an app password to allow your app to access your google account.

Sign in with App Passwords:

An App Password is a 16-digit passcode that gives a less secure app or
device permission to access your Google Account. App Passwords can
only be used with accounts that have 2-Step Verification turned on.

In addition, google hasn't allowed your app to access your google account with username(email address) and password since May 30, 2022. So now, you need username(email address) and an app password to access your google account.

Less secure apps & your Google Account:

To help keep your account secure, from May 30, 2022, Google no
longer supports the use of third-party apps or devices which ask you
to sign in to your Google Account using only your username and
password.

How to generate an app password:

First, click on Account from 9 dots:

Then, click on App passwords from Security. *Don't forget to turn on 2-Step Verification before generating an app password otherwise you cannot generate an app password:

Then, click on Other (Custom name):

Then, put your app name, then click on GENERATE:

Finally, you could generate the app password xylnudjdiwpojwzm:

So, your code with the app password above is as shown below:

import smtplib

fromaddr = 'user_me@gmail.com'
toaddrs  = 'user_you@gmail.com'
msg = 'Why,Oh why!'
username = 'user_me@gmail.com'
password = 'xylnudjdiwpojwzm' # Here
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

In addition, settings.py with the app password above in Django is as shown below:

# "settings.py"

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'myaccount@gmail.com'
EMAIL_HOST_PASSWORD = 'xylnudjdiwpojwzm' # Here


问:
Autohotkey ELSE statements not working. Any replacement?
I‘m making an autohotkey script.

What the problem is that the ELSE commands are sometimes not working.

How to fix this problem?

答:
use IF commands instead.

For example:

```<code><^<!-::
If GetKeyState ("u", "p")
MsgBox hey!
If not GetKeyState ("u", "p")
MsgBox bye!
</code>```

hope that helped.

Body:
use IF commands instead.

For example:

<^<!-::
If GetKeyState ("u", "p")
MsgBox hey!
If not GetKeyState ("u", "p")
MsgBox bye!

hope that helped.


问:
Drop rows of df with fewer entries
I'm working currently with pandas in python.

I've got a dataset of customers (user_id on column1) and of the item they bought (column2).

Example dataset:

ID_user
ID_item

0
1

0
2

0
3

1
2

2
1

3
3

...
...

Now I want only to focus on customers, which have bought more than 10 items. How can I create a new dataframe with pandas and drop all other customers with less than 10 items bought?

Thank you very much!

答:
A simple groupby + filter will do the job:

```<code>>>> df.groupby('ID_user').filter(lambda g: len(g) > 10)
Empty DataFrame
Columns: [ID_user, ID_item]
Index: []
</code>```

Now, in your example, there aren't actually any groups that do have more than 10 items, so it's showing an empty dataframe here. But in your real data, this would work.

Title: Drop rows of df with fewer entries

Body:
A simple groupby + filter will do the job:

>>> df.groupby('ID_user').filter(lambda g: len(g) > 10)
Empty DataFrame
Columns: [ID_user, ID_item]
Index: []

Now, in your example, there aren't actually any groups that do have more than 10 items, so it's showing an empty dataframe here. But in your real data, this would work.


问:
How can I use a Timer of 2 seconds inside a fragment?
This is my Fragment.kt

class SplashFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_splash, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
            // My Timer
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
                }
            }, 2000)

    }
}
```
<p><code>This is my Logcat error</code></p>
```2022-02-06 20:37:34.755 27478-27510/com.finite.livelocationtest E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    Process: com.finite.livelocationtest, PID: 27478
    java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
        at android.widget.Toast.getLooper(Toast.java:179)
        at android.widget.Toast.<init>(Toast.java:164)
        at android.widget.Toast.makeText(Toast.java:492)
        at android.widget.Toast.makeText(Toast.java:480)
        at com.finite.livelocationtest.ui.fragment.SplashFragment$onViewCreated$1.run(SplashFragment.kt:31)
        at java.util.TimerThread.mainLoop(Timer.java:562)
        at java.util.TimerThread.run(Timer.java:512)
```

What do I want to achieve?

I want to go from this fragment to the next fragment after a time of 2 seconds time, please let me know any possible way to achieve this.

答:
Instead of trying to use Timer class, we can use coroutines.

lifecycleScope.launch {
  delay(2000)
  findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
}
```

Using this solves the problem I was having, The reason why my app was crashing was that I was trying to Execute UI related things from a background thread, which doesn't work as it is a non-UI thread, so we need to do it on Main Thread.

Body:
This is my Fragment.kt

class SplashFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_splash, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
            // My Timer
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
                }
            }, 2000)

    }
}

This is my Logcat error

2022-02-06 20:37:34.755 27478-27510/com.finite.livelocationtest E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    Process: com.finite.livelocationtest, PID: 27478
    java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
        at android.widget.Toast.getLooper(Toast.java:179)
        at android.widget.Toast.<init>(Toast.java:164)
        at android.widget.Toast.makeText(Toast.java:492)
        at android.widget.Toast.makeText(Toast.java:480)
        at com.finite.livelocationtest.ui.fragment.SplashFragment$onViewCreated$1.run(SplashFragment.kt:31)
        at java.util.TimerThread.mainLoop(Timer.java:562)
        at java.util.TimerThread.run(Timer.java:512)

What do I want to achieve?

I want to go from this fragment to the next fragment after a time of 2 seconds time, please let me know any possible way to achieve this.

Body:
Instead of trying to use Timer class, we can use coroutines.

lifecycleScope.launch {
  delay(2000)
  findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
}

Using this solves the problem I was having, The reason why my app was crashing was that I was trying to Execute UI related things from a background thread, which doesn't work as it is a non-UI thread, so we need to do it on Main Thread.


问:
Opposite of PreventDefault for links and drop-down selector?
I have a jquery click event for a bunch of links and one drop-down selector in my MVC view and I preventDefault on them before doing the event, because most of them redirect to a view (the redirect stops my jquery code doesn't it?). After all of my callbacks in my click event, I would like the links and drop-down selector to do their default event so it doesn't just sit on the page like nothing has happened.

Is there an easy way to get all of the links/drop-down to return to default and then programatically click them in jquery? I've tried $(this).click() and $(this).submit() and e.click() and e.submit() with no luck.

Here is my code

```<code> $("input,a,select").not("#SubmitButton").click(function (e) {
        e.preventDefault();
        console.log("prevented default");
        deletePreview($(this));
    });
    function deletePreview(button) {
        console.log("clicked");
        //Delete Offer from DB
        $.post('@Url.Content("~/")Offer/DeleteJoAnnOffer/?offerId=' + offerID, function (data) {
              console.log("finished deleting");
              if (button.attr('id') == "CancelButton") {
                 window.location.href = '@Url.Content("~/")Offer/CreateJoAnn/';
              } else {

                  //DO DEFAULT ACTION HERE

              }
       });
    };
</code>```

[EDIT]: One more question: If I don't use preventDefault(), my jquery event executes (well the initial part because my console logs "clicked"), but I cannot confirm if the jquery posts are actually executing because the console refreshes on the new page.

答:
"post" function in jquery is async operation (async flag is true by default). Your code inside click event will execute in full before page will reload so there is no need to use preventDefault. You have to change post function in deletePreview to be synchronous:

```<code>        $("input,a,select").not("#SubmitButton").click(function (e) {
             console.log("you do not need to call prevented default :)");
             deletePreview($(this));
         });
         function deletePreview(button) {
             console.log("clicked");
             //Delete Offer from DB
             $.ajax('@Url.Content("~/")Offer/DeleteJoAnnOffer/?offerId=' + offerID,
             {
                 async: false,
                 success: function (data) {
                     console.log("finished deleting");
                     if (button.attr('id') == "CancelButton") {
                         window.location.href = '@Url.Content("~/")Offer/CreateJoAnn/';
                     } else {

                         //DO DEFAULT ACTION HERE

                     }
                 }
             });
         };
</code>```

This means that code inside click event will wait until ajax call in deletePreview is completed.

See http://api.jquery.com/jQuery.ajax/ for explanation on async parameter

Body:
I have a jquery click event for a bunch of links and one drop-down selector in my MVC view and I preventDefault on them before doing the event, because most of them redirect to a view (the redirect stops my jquery code doesn't it?). After all of my callbacks in my click event, I would like the links and drop-down selector to do their default event so it doesn't just sit on the page like nothing has happened.

Is there an easy way to get all of the links/drop-down to return to default and then programatically click them in jquery? I've tried $(this).click() and $(this).submit() and e.click() and e.submit() with no luck.

Here is my code

 $("input,a,select").not("#SubmitButton").click(function (e) {
        e.preventDefault();
        console.log("prevented default");
        deletePreview($(this));
    });
    function deletePreview(button) {
        console.log("clicked");
        //Delete Offer from DB
        $.post('@Url.Content("~/")Offer/DeleteJoAnnOffer/?offerId=' + offerID, function (data) {
              console.log("finished deleting");
              if (button.attr('id') == "CancelButton") {
                 window.location.href = '@Url.Content("~/")Offer/CreateJoAnn/';
              } else {

                  //DO DEFAULT ACTION HERE

              }
       });
    };

[EDIT]: One more question: If I don't use preventDefault(), my jquery event executes (well the initial part because my console logs "clicked"), but I cannot confirm if the jquery posts are actually executing because the console refreshes on the new page.

Body:
"post" function in jquery is async operation (async flag is true by default). Your code inside click event will execute in full before page will reload so there is no need to use preventDefault. You have to change post function in deletePreview to be synchronous:

        $("input,a,select").not("#SubmitButton").click(function (e) {
             console.log("you do not need to call prevented default :)");
             deletePreview($(this));
         });
         function deletePreview(button) {
             console.log("clicked");
             //Delete Offer from DB
             $.ajax('@Url.Content("~/")Offer/DeleteJoAnnOffer/?offerId=' + offerID,
             {
                 async: false,
                 success: function (data) {
                     console.log("finished deleting");
                     if (button.attr('id') == "CancelButton") {
                         window.location.href = '@Url.Content("~/")Offer/CreateJoAnn/';
                     } else {

                         //DO DEFAULT ACTION HERE

                     }
                 }
             });
         };

This means that code inside click event will wait until ajax call in deletePreview is completed.

See http://api.jquery.com/jQuery.ajax/ for explanation on async parameter