问:
Postgresql dynamic function with current table name
I have a function (audit.create_audit_table()) that accepts an array of table names. It creates a single function audit.if_modified_func() and then loops through each table name and creates an audit table and applies a trigger to the main table. The function compiles and is created with no errors. When I run the function

```<code>select audit.create_audit_table(ARRAY['organization'])
</code>```

I keep getting the following error and I am not sure why because I thought that TG_TABLE_NAME is a automatic variable which will give me access to the current table that is executing audit.if_modified_func()

ERROR:

```<code>ERROR:  column "tg_table_name" does not exist
LINE 3:   audit_row audit.' || quote_ident(TG_TABLE_NAME::TEXT)||';
                                           ^
</code>```

Here's the function:

```<code>    CREATE OR REPLACE FUNCTION audit.create_audit_table(table_names character varying[])
RETURNS character varying AS
$BODY$
    DECLARE
    table_name varchar;
    i int;
BEGIN
    EXECUTE 'CREATE OR REPLACE FUNCTION audit.if_modified_func() RETURNS TRIGGER AS $$
    DECLARE
        audit_row audit.' || quote_ident(TG_TABLE_NAME::TEXT)||';
        include_values boolean;
        log_diffs boolean;
        h_old hstore;
        h_new hstore;
        excluded_cols text[] = ARRAY[]::text[];
    BEGIN
        IF TG_WHEN <> ''AFTER'' THEN
            RAISE EXCEPTION ''audit.if_modified_func() may only run as an AFTER trigger'';
        END IF;

        audit_row = ROW(
            nextval(''audit.'|| quote_ident(TG_TABLE_NAME::text) ||'_event_id_seq''), -- event_id
            TG_TABLE_SCHEMA::text,                        -- schema_name
            TG_TABLE_NAME::text,                          -- table_name
            TG_RELID,                                     -- relation OID for much quicker searches
            session_user::text,                           -- session_user_name
            current_timestamp,                            -- action_tstamp_tx
            statement_timestamp(),                        -- action_tstamp_stm
            clock_timestamp(),                            -- action_tstamp_clk
            txid_current(),                               -- transaction ID
            current_setting(''application_name''),          -- client application
            inet_client_addr(),                           -- client_addr
            inet_client_port(),                           -- client_port
            current_query(),                              -- top-level query or queries (if multistatement) from client
            substring(TG_OP,1,1),                         -- action
            NULL, NULL,                                   -- row_data, changed_fields
            ''f''                                           -- statement_only
            );

        IF NOT TG_ARGV[0]::boolean IS DISTINCT FROM ''f''::boolean THEN
            audit_row.client_query = NULL;
        END IF;

        IF TG_ARGV[1] IS NOT NULL THEN
            excluded_cols = TG_ARGV[1]::text[];
        END IF;

        IF (TG_OP = ''UPDATE'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(OLD.*) - excluded_cols;
            audit_row.changed_fields =  (hstore(NEW.*) - audit_row.row_data) - excluded_cols;
            IF audit_row.changed_fields = hstore('''') THEN
                -- All changed fields are ignored. Skip this update.
                RETURN NULL;
            END IF;
        ELSIF (TG_OP = ''DELETE'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(OLD.*) - excluded_cols;
        ELSIF (TG_OP = ''INSERT'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(NEW.*) - excluded_cols;
        ELSIF (TG_LEVEL = ''STATEMENT'' AND TG_OP IN (''INSERT'',''UPDATE'',''DELETE'',''TRUNCATE'')) THEN
            audit_row.statement_only = ''t'';
        ELSE
            RAISE EXCEPTION ''[audit.if_modified_func] - Trigger func added as trigger for unhandled case: %%, %%'',TG_OP, TG_LEVEL;
            RETURN NULL;
        END IF;
        INSERT INTO audit.'|| quote_ident(TG_TABLE_NAME::TEXT) ||' VALUES (audit_row.*);
    RETURN null;
    END;
    $$
    LANGUAGE plpgsql;
    ALTER FUNCTION audit.if_modified_func()
    OWNER TO postgres;';

    FOR i in 1..array_upper(table_names, 1) LOOP

        EXECUTE format('
        DROP TABLE IF EXISTS audit.%1$s;
        CREATE TABLE audit.%1$s (
        event_id bigserial primary key,
        schema_name text not null,
        table_name text not null,
        relid oid not null,
        session_user_name text,
        action_tstamp_tx TIMESTAMP WITH TIME ZONE NOT NULL,
        action_tstamp_stm TIMESTAMP WITH TIME ZONE NOT NULL,
        action_tstamp_clk TIMESTAMP WITH TIME ZONE NOT NULL,
        transaction_id bigint,
        application_name text,
        client_addr inet,
        client_port integer,
        client_query text,
        action TEXT NOT NULL CHECK (action IN (''I'',''D'',''U'', ''T'')),
        row_data hstore,
        changed_fields hstore,
        statement_only boolean not null
        );

        REVOKE ALL ON audit.%1$s FROM public;

        COMMENT ON TABLE audit.%1$s IS ''History of auditable actions on audited tables, from audit.if_modified_func()'';
        COMMENT ON COLUMN audit.%1$s.event_id IS ''Unique identifier for each auditable event'';
        COMMENT ON COLUMN audit.%1$s.schema_name IS ''Database schema audited table for this event is in'';
        COMMENT ON COLUMN audit.%1$s.table_name IS ''Non-schema-qualified table name of table event occured in'';
        COMMENT ON COLUMN audit.%1$s.relid IS ''Table OID. Changes with drop/create. Get with ''''tablename''''::regclass'';
        COMMENT ON COLUMN audit.%1$s.session_user_name IS ''Login / session user whose statement caused the audited event'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_tx IS ''Transaction start timestamp for tx in which audited event occurred'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_stm IS ''Statement start timestamp for tx in which audited event occurred'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_clk IS ''Wall clock time at which audited event''''s trigger call occurred'';
        COMMENT ON COLUMN audit.%1$s.transaction_id IS ''Identifier of transaction that made the change. May wrap, but unique paired with action_tstamp_tx.'';
        COMMENT ON COLUMN audit.%1$s.client_addr IS ''IP address of client that issued query. Null for unix domain socket.'';
        COMMENT ON COLUMN audit.%1$s.client_port IS ''Remote peer IP port address of client that issued query. Undefined for unix socket.'';
        COMMENT ON COLUMN audit.%1$s.client_query IS ''Top-level query that caused this auditable event. May be more than one statement.'';
        COMMENT ON COLUMN audit.%1$s.application_name IS ''Application name set when this audit event occurred. Can be changed in-session by client.'';
        COMMENT ON COLUMN audit.%1$s.action IS ''Action type; I = insert, D = delete, U = update, T = truncate'';
        COMMENT ON COLUMN audit.%1$s.row_data IS ''Record value. Null for statement-level trigger. For INSERT this is the new tuple. For DELETE and UPDATE it is the old tuple.'';
        COMMENT ON COLUMN audit.%1$s.changed_fields IS ''New values of fields changed by UPDATE. Null except for row-level UPDATE events.'';
        COMMENT ON COLUMN audit.%1$s.statement_only IS ''''''t'''' if audit event is from an FOR EACH STATEMENT trigger, ''''f'''' for FOR EACH ROW'';

        CREATE INDEX %1$s_relid_idx ON audit.%1$s(relid);
        CREATE INDEX %1$s_action_tstamp_tx_stm_idx ON audit.%1$s(action_tstamp_stm);
        CREATE INDEX %1$s_action_idx ON audit.%1$s(action);
        ', table_names[i]);

        EXECUTE format('
        DROP TRIGGER IF EXISTS audit_trigger_row ON %1$s;
        CREATE TRIGGER audit_trigger_row
        AFTER INSERT OR UPDATE OR DELETE
        ON public.%1$s
        FOR EACH ROW
        EXECUTE PROCEDURE audit.if_modified_func();', table_names[i]);

        EXECUTE format('
        DROP TRIGGER IF EXISTS audit_trigger_stm ON %1$s;
        CREATE TRIGGER audit_trigger_stm
        AFTER TRUNCATE
        ON public.%1$s
        FOR EACH STATEMENT
        EXECUTE PROCEDURE audit.if_modified_func();', table_names[i]);

    END LOOP;

RETURN 'SUCCESS';
END;
$BODY$
LANGUAGE plpgsql;
ALTER FUNCTION audit.create_audit_table(character varying[])
OWNER TO postgres;
</code>```

UPDATE 03/31:

Ok, so I created the if_modified_func() function without the dynamic sql and I declared the audit_row as audit_row RECORD; I am not sure about the part of "needing a cast upon inserting the values". I am also not sure if this is the correct way to do the insert

EXECUTE format($string$INSERT INTO audit.%1$s VALUES (audit_row.*);$string$, TG_TABLE_NAME::text);

I am now getting this error when I run select audit.create_audit_table(ARRAY['organization'])

ERROR:

```<code>ERROR:  record "audit_row" has no field "row_data"
CONTEXT:  PL/pgSQL function audit.if_modified_func() line 42 at assignment
</code>```

Here's the updated function:

```<code>CREATE OR REPLACE FUNCTION audit.if_modified_func() RETURNS TRIGGER AS $$
        DECLARE
            audit_row RECORD;
            include_values boolean;
            log_diffs boolean;
            h_old hstore;
            h_new hstore;
            excluded_cols text[] = ARRAY[]::text[];
        BEGIN
            IF TG_WHEN <> 'AFTER' THEN
                RAISE EXCEPTION 'audit.if_modified_func() may only run as an AFTER trigger';
            END IF;

            audit_row = ROW(
                nextval(format('audit.%1$s_event_id_seq',TG_TABLE_NAME::text)), -- event_id
                TG_TABLE_SCHEMA::text,                        -- schema_name
                TG_TABLE_NAME::text,                          -- table_name
                TG_RELID,                                     -- relation OID for much quicker searches
                session_user::text,                           -- session_user_name
                current_timestamp,                            -- action_tstamp_tx
                statement_timestamp(),                        -- action_tstamp_stm
                clock_timestamp(),                            -- action_tstamp_clk
                txid_current(),                               -- transaction ID
                current_setting('application_name'),          -- client application
                inet_client_addr(),                           -- client_addr
                inet_client_port(),                           -- client_port
                current_query(),                              -- top-level query or queries (if multistatement) from client
                substring(TG_OP,1,1),                         -- action
                NULL, NULL,                                   -- row_data, changed_fields
                'f'                                           -- statement_only
                );

            IF NOT TG_ARGV[0]::boolean IS DISTINCT FROM 'f'::boolean THEN
                audit_row.client_query = NULL;
            END IF;

            IF TG_ARGV[1] IS NOT NULL THEN
                excluded_cols = TG_ARGV[1]::text[];
            END IF;

            IF (TG_OP = 'UPDATE' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(OLD.*) - excluded_cols;
                audit_row.changed_fields =  (hstore(NEW.*) - audit_row.row_data) - excluded_cols;
                IF audit_row.changed_fields = hstore('') THEN
                    -- All changed fields are ignored. Skip this update.
                    RETURN NULL;
                END IF;
            ELSIF (TG_OP = 'DELETE' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(OLD.*) - excluded_cols;
            ELSIF (TG_OP = 'INSERT' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(NEW.*) - excluded_cols;
            ELSIF (TG_LEVEL = 'STATEMENT' AND TG_OP IN ('INSERT','UPDATE','DELETE','TRUNCATE')) THEN
                audit_row.statement_only = 't';
            ELSE
                RAISE EXCEPTION '[audit.if_modified_func] - Trigger func added as trigger for unhandled case: %, %',TG_OP, TG_LEVEL;
                RETURN NULL;
            END IF;
            EXECUTE format('INSERT INTO audit.%1$s VALUES (audit_row.*)', TG_TABLE_NAME::text);

        RETURN null;
        END;
        $$
        LANGUAGE plpgsql;
        ALTER FUNCTION audit.if_modified_func()
        OWNER TO postgres;
</code>```

答:
TG_TABLE_NAME is a special, trigger variable, which is only available inside trigger functions. Your create_audit_table() is not a trigger function.

Also, you constantly redefining your real trigger function (if_modified_func()), which "invalidates" any earlier created triggers.

Create your trigger function without the dynamic SQL magic (dynamic SQL will only need to insert values to these audit tables). Then, you can add your audit logic to a table with:

```<code>CREATE TRIGGER audit_trigger_row
  AFTER INSERT OR UPDATE OR DELETE
  ON public.<your_table_name>
  FOR EACH ROW
  EXECUTE PROCEDURE <your_audit_trigger_function_name>();
</code>```

You can put this (but only this -- maybe with drop if exists) inside a function, to allow attaching this audit logic more easily.

Notes:

Inside the trigger function, you cannot use a %ROWTYPE variable (because you don't know the exact table. you only have its name). The solution is simple: just use the RECORD type instead (you will need a cast upon inserting the values though).

Don't use single quotes for such long strings. Use the $your_keyword$<string_value>$your_keyword$ format instead. With possibly the format() function instead of just concatenating values. Your code will be much more readable.

Edit: to utilize your RECORD variable, you should either:

Initialize it with a structure. You can do this in your case with f.ex.

```<code>SELECT nextval('audit.'|| quote_ident(TG_TABLE_NAME) || '_event_id_seq') AS event_id,
       TG_TABLE_SCHEMA                        AS schema_name,
       TG_TABLE_NAME                          AS table_name,
       TG_RELID                               AS relid,
       session_user                           AS session_user_name,
       current_timestamp                      AS action_tstamp_tx,
       statement_timestamp()                  AS action_tstamp_stm,
       clock_timestamp()                      AS action_tstamp_clk,
       txid_current()                         AS transaction_id,
       current_setting('application_name')    AS application_name,
       inet_client_addr()                     AS client_addr,
       inet_client_port()                     AS client_port,
       current_query()                        AS client_query,
       substring(TG_OP, 1, 1)                 AS action,
       NULL::hstore                           AS row_data,
       NULL::hstore                           AS changed_fields,
       FALSE                                  AS statement_only
INTO   audit_row;
</code>```

Use the predefined names of the ROW() constructor. The first column's name if f1, the second's is f2, etc.

```<code>audit_row.f15 = hstore(OLD.*) - excluded_cols;
</code>```

After choosing one of the above methods, you should insert the row like:

```<code>EXECUTE format('INSERT INTO audit.%1$s VALUES (($1::text::audit.%1$s).*)', quote_ident(TG_TABLE_NAME)) USING audit_row;
</code>```

Note: even the cast to text is required due to the fact that EXECUTE cannot know the actual structure of audit_row.

http://rextester.com/GUAJ1339

Body:
I have a function (audit.create_audit_table()) that accepts an array of table names. It creates a single function audit.if_modified_func() and then loops through each table name and creates an audit table and applies a trigger to the main table. The function compiles and is created with no errors. When I run the function

select audit.create_audit_table(ARRAY['organization'])

I keep getting the following error and I am not sure why because I thought that TG_TABLE_NAME is a automatic variable which will give me access to the current table that is executing audit.if_modified_func()

ERROR:

ERROR:  column "tg_table_name" does not exist
LINE 3:   audit_row audit.' || quote_ident(TG_TABLE_NAME::TEXT)||';
                                           ^

Here's the function:

    CREATE OR REPLACE FUNCTION audit.create_audit_table(table_names character varying[])
RETURNS character varying AS
$BODY$
    DECLARE
    table_name varchar;
    i int;
BEGIN
    EXECUTE 'CREATE OR REPLACE FUNCTION audit.if_modified_func() RETURNS TRIGGER AS $$
    DECLARE
        audit_row audit.' || quote_ident(TG_TABLE_NAME::TEXT)||';
        include_values boolean;
        log_diffs boolean;
        h_old hstore;
        h_new hstore;
        excluded_cols text[] = ARRAY[]::text[];
    BEGIN
        IF TG_WHEN <> ''AFTER'' THEN
            RAISE EXCEPTION ''audit.if_modified_func() may only run as an AFTER trigger'';
        END IF;

        audit_row = ROW(
            nextval(''audit.'|| quote_ident(TG_TABLE_NAME::text) ||'_event_id_seq''), -- event_id
            TG_TABLE_SCHEMA::text,                        -- schema_name
            TG_TABLE_NAME::text,                          -- table_name
            TG_RELID,                                     -- relation OID for much quicker searches
            session_user::text,                           -- session_user_name
            current_timestamp,                            -- action_tstamp_tx
            statement_timestamp(),                        -- action_tstamp_stm
            clock_timestamp(),                            -- action_tstamp_clk
            txid_current(),                               -- transaction ID
            current_setting(''application_name''),          -- client application
            inet_client_addr(),                           -- client_addr
            inet_client_port(),                           -- client_port
            current_query(),                              -- top-level query or queries (if multistatement) from client
            substring(TG_OP,1,1),                         -- action
            NULL, NULL,                                   -- row_data, changed_fields
            ''f''                                           -- statement_only
            );

        IF NOT TG_ARGV[0]::boolean IS DISTINCT FROM ''f''::boolean THEN
            audit_row.client_query = NULL;
        END IF;

        IF TG_ARGV[1] IS NOT NULL THEN
            excluded_cols = TG_ARGV[1]::text[];
        END IF;

        IF (TG_OP = ''UPDATE'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(OLD.*) - excluded_cols;
            audit_row.changed_fields =  (hstore(NEW.*) - audit_row.row_data) - excluded_cols;
            IF audit_row.changed_fields = hstore('''') THEN
                -- All changed fields are ignored. Skip this update.
                RETURN NULL;
            END IF;
        ELSIF (TG_OP = ''DELETE'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(OLD.*) - excluded_cols;
        ELSIF (TG_OP = ''INSERT'' AND TG_LEVEL = ''ROW'') THEN
            audit_row.row_data = hstore(NEW.*) - excluded_cols;
        ELSIF (TG_LEVEL = ''STATEMENT'' AND TG_OP IN (''INSERT'',''UPDATE'',''DELETE'',''TRUNCATE'')) THEN
            audit_row.statement_only = ''t'';
        ELSE
            RAISE EXCEPTION ''[audit.if_modified_func] - Trigger func added as trigger for unhandled case: %%, %%'',TG_OP, TG_LEVEL;
            RETURN NULL;
        END IF;
        INSERT INTO audit.'|| quote_ident(TG_TABLE_NAME::TEXT) ||' VALUES (audit_row.*);
    RETURN null;
    END;
    $$
    LANGUAGE plpgsql;
    ALTER FUNCTION audit.if_modified_func()
    OWNER TO postgres;';

    FOR i in 1..array_upper(table_names, 1) LOOP

        EXECUTE format('
        DROP TABLE IF EXISTS audit.%1$s;
        CREATE TABLE audit.%1$s (
        event_id bigserial primary key,
        schema_name text not null,
        table_name text not null,
        relid oid not null,
        session_user_name text,
        action_tstamp_tx TIMESTAMP WITH TIME ZONE NOT NULL,
        action_tstamp_stm TIMESTAMP WITH TIME ZONE NOT NULL,
        action_tstamp_clk TIMESTAMP WITH TIME ZONE NOT NULL,
        transaction_id bigint,
        application_name text,
        client_addr inet,
        client_port integer,
        client_query text,
        action TEXT NOT NULL CHECK (action IN (''I'',''D'',''U'', ''T'')),
        row_data hstore,
        changed_fields hstore,
        statement_only boolean not null
        );

        REVOKE ALL ON audit.%1$s FROM public;

        COMMENT ON TABLE audit.%1$s IS ''History of auditable actions on audited tables, from audit.if_modified_func()'';
        COMMENT ON COLUMN audit.%1$s.event_id IS ''Unique identifier for each auditable event'';
        COMMENT ON COLUMN audit.%1$s.schema_name IS ''Database schema audited table for this event is in'';
        COMMENT ON COLUMN audit.%1$s.table_name IS ''Non-schema-qualified table name of table event occured in'';
        COMMENT ON COLUMN audit.%1$s.relid IS ''Table OID. Changes with drop/create. Get with ''''tablename''''::regclass'';
        COMMENT ON COLUMN audit.%1$s.session_user_name IS ''Login / session user whose statement caused the audited event'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_tx IS ''Transaction start timestamp for tx in which audited event occurred'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_stm IS ''Statement start timestamp for tx in which audited event occurred'';
        COMMENT ON COLUMN audit.%1$s.action_tstamp_clk IS ''Wall clock time at which audited event''''s trigger call occurred'';
        COMMENT ON COLUMN audit.%1$s.transaction_id IS ''Identifier of transaction that made the change. May wrap, but unique paired with action_tstamp_tx.'';
        COMMENT ON COLUMN audit.%1$s.client_addr IS ''IP address of client that issued query. Null for unix domain socket.'';
        COMMENT ON COLUMN audit.%1$s.client_port IS ''Remote peer IP port address of client that issued query. Undefined for unix socket.'';
        COMMENT ON COLUMN audit.%1$s.client_query IS ''Top-level query that caused this auditable event. May be more than one statement.'';
        COMMENT ON COLUMN audit.%1$s.application_name IS ''Application name set when this audit event occurred. Can be changed in-session by client.'';
        COMMENT ON COLUMN audit.%1$s.action IS ''Action type; I = insert, D = delete, U = update, T = truncate'';
        COMMENT ON COLUMN audit.%1$s.row_data IS ''Record value. Null for statement-level trigger. For INSERT this is the new tuple. For DELETE and UPDATE it is the old tuple.'';
        COMMENT ON COLUMN audit.%1$s.changed_fields IS ''New values of fields changed by UPDATE. Null except for row-level UPDATE events.'';
        COMMENT ON COLUMN audit.%1$s.statement_only IS ''''''t'''' if audit event is from an FOR EACH STATEMENT trigger, ''''f'''' for FOR EACH ROW'';

        CREATE INDEX %1$s_relid_idx ON audit.%1$s(relid);
        CREATE INDEX %1$s_action_tstamp_tx_stm_idx ON audit.%1$s(action_tstamp_stm);
        CREATE INDEX %1$s_action_idx ON audit.%1$s(action);
        ', table_names[i]);

        EXECUTE format('
        DROP TRIGGER IF EXISTS audit_trigger_row ON %1$s;
        CREATE TRIGGER audit_trigger_row
        AFTER INSERT OR UPDATE OR DELETE
        ON public.%1$s
        FOR EACH ROW
        EXECUTE PROCEDURE audit.if_modified_func();', table_names[i]);

        EXECUTE format('
        DROP TRIGGER IF EXISTS audit_trigger_stm ON %1$s;
        CREATE TRIGGER audit_trigger_stm
        AFTER TRUNCATE
        ON public.%1$s
        FOR EACH STATEMENT
        EXECUTE PROCEDURE audit.if_modified_func();', table_names[i]);

    END LOOP;

RETURN 'SUCCESS';
END;
$BODY$
LANGUAGE plpgsql;
ALTER FUNCTION audit.create_audit_table(character varying[])
OWNER TO postgres;

UPDATE 03/31:

Ok, so I created the if_modified_func() function without the dynamic sql and I declared the audit_row as audit_row RECORD; I am not sure about the part of "needing a cast upon inserting the values". I am also not sure if this is the correct way to do the insert

EXECUTE format($string$INSERT INTO audit.%1$s VALUES (audit_row.*);$string$, TG_TABLE_NAME::text);

I am now getting this error when I run select audit.create_audit_table(ARRAY['organization'])

ERROR:

ERROR:  record "audit_row" has no field "row_data"
CONTEXT:  PL/pgSQL function audit.if_modified_func() line 42 at assignment

Here's the updated function:

CREATE OR REPLACE FUNCTION audit.if_modified_func() RETURNS TRIGGER AS $$
        DECLARE
            audit_row RECORD;
            include_values boolean;
            log_diffs boolean;
            h_old hstore;
            h_new hstore;
            excluded_cols text[] = ARRAY[]::text[];
        BEGIN
            IF TG_WHEN <> 'AFTER' THEN
                RAISE EXCEPTION 'audit.if_modified_func() may only run as an AFTER trigger';
            END IF;

            audit_row = ROW(
                nextval(format('audit.%1$s_event_id_seq',TG_TABLE_NAME::text)), -- event_id
                TG_TABLE_SCHEMA::text,                        -- schema_name
                TG_TABLE_NAME::text,                          -- table_name
                TG_RELID,                                     -- relation OID for much quicker searches
                session_user::text,                           -- session_user_name
                current_timestamp,                            -- action_tstamp_tx
                statement_timestamp(),                        -- action_tstamp_stm
                clock_timestamp(),                            -- action_tstamp_clk
                txid_current(),                               -- transaction ID
                current_setting('application_name'),          -- client application
                inet_client_addr(),                           -- client_addr
                inet_client_port(),                           -- client_port
                current_query(),                              -- top-level query or queries (if multistatement) from client
                substring(TG_OP,1,1),                         -- action
                NULL, NULL,                                   -- row_data, changed_fields
                'f'                                           -- statement_only
                );

            IF NOT TG_ARGV[0]::boolean IS DISTINCT FROM 'f'::boolean THEN
                audit_row.client_query = NULL;
            END IF;

            IF TG_ARGV[1] IS NOT NULL THEN
                excluded_cols = TG_ARGV[1]::text[];
            END IF;

            IF (TG_OP = 'UPDATE' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(OLD.*) - excluded_cols;
                audit_row.changed_fields =  (hstore(NEW.*) - audit_row.row_data) - excluded_cols;
                IF audit_row.changed_fields = hstore('') THEN
                    -- All changed fields are ignored. Skip this update.
                    RETURN NULL;
                END IF;
            ELSIF (TG_OP = 'DELETE' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(OLD.*) - excluded_cols;
            ELSIF (TG_OP = 'INSERT' AND TG_LEVEL = 'ROW') THEN
                audit_row.row_data = hstore(NEW.*) - excluded_cols;
            ELSIF (TG_LEVEL = 'STATEMENT' AND TG_OP IN ('INSERT','UPDATE','DELETE','TRUNCATE')) THEN
                audit_row.statement_only = 't';
            ELSE
                RAISE EXCEPTION '[audit.if_modified_func] - Trigger func added as trigger for unhandled case: %, %',TG_OP, TG_LEVEL;
                RETURN NULL;
            END IF;
            EXECUTE format('INSERT INTO audit.%1$s VALUES (audit_row.*)', TG_TABLE_NAME::text);

        RETURN null;
        END;
        $$
        LANGUAGE plpgsql;
        ALTER FUNCTION audit.if_modified_func()
        OWNER TO postgres;

Body:
TG_TABLE_NAME is a special, trigger variable, which is only available inside trigger functions. Your create_audit_table() is not a trigger function.

Also, you constantly redefining your real trigger function (if_modified_func()), which "invalidates" any earlier created triggers.

Create your trigger function without the dynamic SQL magic (dynamic SQL will only need to insert values to these audit tables). Then, you can add your audit logic to a table with:

CREATE TRIGGER audit_trigger_row
  AFTER INSERT OR UPDATE OR DELETE
  ON public.<your_table_name>
  FOR EACH ROW
  EXECUTE PROCEDURE <your_audit_trigger_function_name>();

You can put this (but only this -- maybe with drop if exists) inside a function, to allow attaching this audit logic more easily.

Notes:

Inside the trigger function, you cannot use a %ROWTYPE variable (because you don't know the exact table. you only have its name). The solution is simple: just use the RECORD type instead (you will need a cast upon inserting the values though).

Don't use single quotes for such long strings. Use the $your_keyword$<string_value>$your_keyword$ format instead. With possibly the format() function instead of just concatenating values. Your code will be much more readable.

Edit: to utilize your RECORD variable, you should either:

Initialize it with a structure. You can do this in your case with f.ex.

SELECT nextval('audit.'|| quote_ident(TG_TABLE_NAME) || '_event_id_seq') AS event_id,
       TG_TABLE_SCHEMA                        AS schema_name,
       TG_TABLE_NAME                          AS table_name,
       TG_RELID                               AS relid,
       session_user                           AS session_user_name,
       current_timestamp                      AS action_tstamp_tx,
       statement_timestamp()                  AS action_tstamp_stm,
       clock_timestamp()                      AS action_tstamp_clk,
       txid_current()                         AS transaction_id,
       current_setting('application_name')    AS application_name,
       inet_client_addr()                     AS client_addr,
       inet_client_port()                     AS client_port,
       current_query()                        AS client_query,
       substring(TG_OP, 1, 1)                 AS action,
       NULL::hstore                           AS row_data,
       NULL::hstore                           AS changed_fields,
       FALSE                                  AS statement_only
INTO   audit_row;

Use the predefined names of the ROW() constructor. The first column's name if f1, the second's is f2, etc.

audit_row.f15 = hstore(OLD.*) - excluded_cols;

After choosing one of the above methods, you should insert the row like:

EXECUTE format('INSERT INTO audit.%1$s VALUES (($1::text::audit.%1$s).*)', quote_ident(TG_TABLE_NAME)) USING audit_row;

Note: even the cast to text is required due to the fact that EXECUTE cannot know the actual structure of audit_row.

http://rextester.com/GUAJ1339


来源: stackexchange

问:
How to configure Redis caching in Spring Boot?
How can I configure Redis caching with Spring Boot. From what I have heard, it's just some changes in the application.properties file, but don't know exactly what.

答:
You can mention all the required properties that is hostname, port etc. in the application.properties file and then read from it.

```<code>@Configuration
@PropertySource("application.properties")
public class SpringSessionRedisConfiguration {

@Value("${redis.hostname}")
private String redisHostName;

@Value("${redis.port}")
private int redisPort;

@Bean
public static PropertySourcesPlaceholderConfigurer    propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    JedisConnectionFactory factory = new JedisConnectionFactory();
    factory.setHostName(redisHostName);
    factory.setPort(redisPort);
    factory.setUsePool(true);
    return factory;
}

@Bean
RedisTemplate<Object, Object> redisTemplate() {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
    redisTemplate.setConnectionFactory(jedisConnectionFactory());
    return redisTemplate;
}

@Bean
RedisCacheManager cacheManager() {
    RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
    return redisCacheManager;
}
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
You can mention all the required properties that is hostname, port etc. in the application.properties file and then read from it.

@Configuration
@PropertySource("application.properties")
public class SpringSessionRedisConfiguration {

@Value("${redis.hostname}")
private String redisHostName;

@Value("${redis.port}")
private int redisPort;

@Bean
public static PropertySourcesPlaceholderConfigurer    propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    JedisConnectionFactory factory = new JedisConnectionFactory();
    factory.setHostName(redisHostName);
    factory.setPort(redisPort);
    factory.setUsePool(true);
    return factory;
}

@Bean
RedisTemplate<Object, Object> redisTemplate() {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
    redisTemplate.setConnectionFactory(jedisConnectionFactory());
    return redisTemplate;
}

@Bean
RedisCacheManager cacheManager() {
    RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
    return redisCacheManager;
}

}


问:
print out all combinations of index
I set a vector list, for example :

```<code>vector<VectorXi> Test;
Test.push_back(VectorXi(0,1));
Test.push_back(VectorXi(0,1,2));
Test.push_back(VectorXi(0));
Test.push_back(VectorXi(0,1));
Test.push_back(VectorXi(0,1,2,3));
PrintAllCombins(Test)
</code>```

And now I want to get all combinations of indexes :

```<code>0, 0, 0, 0, 0
0, 0, 0, 0, 1
0, 0, 0, 0, 2
0, 0, 0, 0, 3

0, 0, 0, 1, 0
0, 0, 0, 1, 1
0, 0, 0, 1, 2
0, 0, 0, 1, 3

0, 0, 1, 0, 0
0, 0, 1, 0, 1
0, 0, 1, 0, 2
0, 0, 1, 0, 3

... and so on
</code>```

If i use for or while loop suitably, then it works I guess, but I encounter limitation. Is there any idea? I'm writing code in c and c++

--------------------- code : this is an example code that im using.

```<code>vector<VectorXi> Test;
VectorXi a0(2); a0[0] = 0; a0[1] = 1;
VectorXi a1(3); a1[0] = 0; a1[1] = 1; a1[2] = 2;
VectorXi a2(2); a2[0] = 0; a2[1] = 1;
VectorXi a3(4); a3[0] = 0; a3[1] = 1; a3[2] = 2; a3[3] = 3;
VectorXi a5(1); a5[0] = 0;
Test.push_back(a0);
Test.push_back(a1);
Test.push_back(a5);
Test.push_back(a2);
Test.push_back(a3);

VectorXi index(5);
for (int i = 0; i < 5; i++)
    index[i] = 0;

int IndexTemp = Test.size()-1;
vector<VectorXi> result;
bool c = true;
while (c == true)
{
    if (index[IndexTemp] < Test[IndexTemp].size()-1)
    {
        VectorXi T;
        T.resize(Test.size());
        for (int j = 0; j<Test.size(); j++)
        {
            T[j] = Test[j](index[j]);
        }
        result.push_back(T);
        index[IndexTemp] ++;
    }
    else if (index[IndexTemp] == Test[IndexTemp].size()-1)
    {
        VectorXi T;
        T.resize(Test.size());
        for (int j = 0; j<Test.size(); j++)
        {
            T[j] = Test[j](index[j]);
        }
        result.push_back(T);
        IndexTemp--;
        if (IndexTemp < 0)
            break;
        index[IndexTemp] ++;
    }

}

for (unsigned int i = 0; i < result.size(); i++)
{
    cout << i << " : ";
    for (unsigned int j = 0; j < result[i].size(); j++)
    {
        cout << result[i](j) << " ";
    }
    cout << endl;
}
</code>```

It does not show all combinations now..

If I make code to work only to this example (Test.size() == 5)
I just use for loop five times like :

```<code>for(Test[0].size())
    for(Test[1].size())
        for(Test[2].size())
            for(Test[3].size())
                for(Test[4].size())
                    cout << ~~~~~
</code>```

Then it gives all combinations.
However if the Test.size() increased, I cannot write all for loops manually.

答:
You may do:

```<code>bool increase(const std::vector<std::vector<int>>& v, std::vector<std::size_t>& it)
{
    for (std::size_t i = 0, size = it.size(); i != size; ++i) {
        const std::size_t index = size - 1 - i;
        ++it[index];
        if (it[index] >= v[index].size()) {
            it[index] = 0;
        } else {
            return true;
        }
    }
    return false;
}

void do_job(const std::vector<std::vector<int>>& v,
            const std::vector<std::size_t>& it)
{
    for (std::size_t i = 0; i != it.size(); ++i) {
        // TODO: manage case where v[i] is empty if relevant.
        std::cout << v[i][it[i]] << " ";
    }
    std::cout << std::endl;
}

void iterate(const std::vector<std::vector<int>>& v)
{
    std::vector<std::size_t> it(v.size(), 0u);

    do {
        do_job(v, it);
    } while (increase(v, it));
}
</code>```

Live Demo

Title: print out all combinations of index

Body:
I set a vector list, for example :

vector<VectorXi> Test;
Test.push_back(VectorXi(0,1));
Test.push_back(VectorXi(0,1,2));
Test.push_back(VectorXi(0));
Test.push_back(VectorXi(0,1));
Test.push_back(VectorXi(0,1,2,3));
PrintAllCombins(Test)

And now I want to get all combinations of indexes :

0, 0, 0, 0, 0
0, 0, 0, 0, 1
0, 0, 0, 0, 2
0, 0, 0, 0, 3

0, 0, 0, 1, 0
0, 0, 0, 1, 1
0, 0, 0, 1, 2
0, 0, 0, 1, 3

0, 0, 1, 0, 0
0, 0, 1, 0, 1
0, 0, 1, 0, 2
0, 0, 1, 0, 3

... and so on

If i use for or while loop suitably, then it works I guess, but I encounter limitation. Is there any idea? I'm writing code in c and c++

--------------------- code : this is an example code that im using.

vector<VectorXi> Test;
VectorXi a0(2); a0[0] = 0; a0[1] = 1;
VectorXi a1(3); a1[0] = 0; a1[1] = 1; a1[2] = 2;
VectorXi a2(2); a2[0] = 0; a2[1] = 1;
VectorXi a3(4); a3[0] = 0; a3[1] = 1; a3[2] = 2; a3[3] = 3;
VectorXi a5(1); a5[0] = 0;
Test.push_back(a0);
Test.push_back(a1);
Test.push_back(a5);
Test.push_back(a2);
Test.push_back(a3);

VectorXi index(5);
for (int i = 0; i < 5; i++)
    index[i] = 0;

int IndexTemp = Test.size()-1;
vector<VectorXi> result;
bool c = true;
while (c == true)
{
    if (index[IndexTemp] < Test[IndexTemp].size()-1)
    {
        VectorXi T;
        T.resize(Test.size());
        for (int j = 0; j<Test.size(); j++)
        {
            T[j] = Test[j](index[j]);
        }
        result.push_back(T);
        index[IndexTemp] ++;
    }
    else if (index[IndexTemp] == Test[IndexTemp].size()-1)
    {
        VectorXi T;
        T.resize(Test.size());
        for (int j = 0; j<Test.size(); j++)
        {
            T[j] = Test[j](index[j]);
        }
        result.push_back(T);
        IndexTemp--;
        if (IndexTemp < 0)
            break;
        index[IndexTemp] ++;
    }

}

for (unsigned int i = 0; i < result.size(); i++)
{
    cout << i << " : ";
    for (unsigned int j = 0; j < result[i].size(); j++)
    {
        cout << result[i](j) << " ";
    }
    cout << endl;
}

It does not show all combinations now..

If I make code to work only to this example (Test.size() == 5)
I just use for loop five times like :

for(Test[0].size())
    for(Test[1].size())
        for(Test[2].size())
            for(Test[3].size())
                for(Test[4].size())
                    cout << ~~~~~

Then it gives all combinations.
However if the Test.size() increased, I cannot write all for loops manually.

Body:
You may do:

bool increase(const std::vector<std::vector<int>>& v, std::vector<std::size_t>& it)
{
    for (std::size_t i = 0, size = it.size(); i != size; ++i) {
        const std::size_t index = size - 1 - i;
        ++it[index];
        if (it[index] >= v[index].size()) {
            it[index] = 0;
        } else {
            return true;
        }
    }
    return false;
}

void do_job(const std::vector<std::vector<int>>& v,
            const std::vector<std::size_t>& it)
{
    for (std::size_t i = 0; i != it.size(); ++i) {
        // TODO: manage case where v[i] is empty if relevant.
        std::cout << v[i][it[i]] << " ";
    }
    std::cout << std::endl;
}

void iterate(const std::vector<std::vector<int>>& v)
{
    std::vector<std::size_t> it(v.size(), 0u);

    do {
        do_job(v, it);
    } while (increase(v, it));
}

Live Demo


问:
PHP MySQL - Access denied for user
I know that there are a tons of related threads but none of them fixes my problem. i'm having a problem connecting to my database. I get the following error:
Access denied for user ''@'localhost' (using password: NO)

My code for register.php is the following:

```<code><?php
require 'config.php';

if(isset($_POST['submit'])){
    //does verification
    $mail1 = $_POST['email1'];
    $mail2 = $_POST['email2'];
    $pass1 = $_POST['pass1'];
    $pass2 = $_POST['pass2'];

    if(($mail1 == $mail2) && ($pass1 == $pass2)){
        //everything is k
        $name = mysql_escape_string($_POST['name']);
        $lname = mysql_escape_string($_POST['lname']);
        $uname = mysql_escape_string($_POST['uname']);
        $email1 = mysql_escape_string($_POST['email1']);
        $pass1 = mysql_escape_string($_POST['pass1']);

        $pass1 = md5($pass1);

        //Checks if username is taken
        $check = mysql_query("SELECT * FROM users WHERE uname = '$uname'")or die(mysql_error());
        if (mysql_num_rows($check)>=1) {
            echo "Username already taken";
        } else {
        mysql_query("INSERT INTO `users` (`first_name`, `last_name`, `username`, `mail`, `password`, `id`) VALUES ('$name', '$lname', '$uname', '$email1', '$pass1', NULL)") or die(mysql_error());
        echo "Registration Successful";
    } }
    else {
        echo "sorry, something doesn't match.";
    }
} else {
    //displays form
    echo $form = <<<EOT
    <form action="register.php" method="POST">
    First Name: <input type="text" name="name" /><br />
    Last Name: <input type="text" name="lname" /><br />
    Username: <input type="text" name="uname" /><br />
    Email: <input type="text" name="email1" /><br />
    Confirm Email: <input type="text" name="email2" /><br />
    Password: <input type="password" name="pass1" /><br />
    Confirm Password: <input type="password" name="pass2" /><br />
    <input type="submit" value="Register" name="submit" />
EOT;
}

?>
</code>```

and my config.php is:

```<code><?php
mysql_connect("localhost", "root", "");
mysql_select_db("MyDB");
?>
</code>```

What to do? My PHP version is 5.6.27 and MySQL version is 5.6.33

答:
I'd recommend using mysqli. For your case, the config.php would look like:

```<code><?php
$mysqli = new mysqli("localhost", "root", "", "MyDB");

if(mysqli_connect_errno()){
    printf("Connection Failed %s\n", mysqli_connect_error());
    exit();
}

session_start();
if(isset($SESSION["REMOTE_ADDR"]) && $SESSION["REMOTE_ADDR"] !=     $SERVER["REMOTE_ADDR"]){
    session_destroy();
    session_start();
}
?>
</code>```

and instead of "require", you'd do:

```<code>include ("config.php");
</code>```

Hope this helped

Title: PHP MySQL - Access denied for user

Body:
I know that there are a tons of related threads but none of them fixes my problem. i'm having a problem connecting to my database. I get the following error:
Access denied for user ''@'localhost' (using password: NO)

My code for register.php is the following:

<?php
require 'config.php';

if(isset($_POST['submit'])){
    //does verification
    $mail1 = $_POST['email1'];
    $mail2 = $_POST['email2'];
    $pass1 = $_POST['pass1'];
    $pass2 = $_POST['pass2'];

    if(($mail1 == $mail2) && ($pass1 == $pass2)){
        //everything is k
        $name = mysql_escape_string($_POST['name']);
        $lname = mysql_escape_string($_POST['lname']);
        $uname = mysql_escape_string($_POST['uname']);
        $email1 = mysql_escape_string($_POST['email1']);
        $pass1 = mysql_escape_string($_POST['pass1']);

        $pass1 = md5($pass1);

        //Checks if username is taken
        $check = mysql_query("SELECT * FROM users WHERE uname = '$uname'")or die(mysql_error());
        if (mysql_num_rows($check)>=1) {
            echo "Username already taken";
        } else {
        mysql_query("INSERT INTO `users` (`first_name`, `last_name`, `username`, `mail`, `password`, `id`) VALUES ('$name', '$lname', '$uname', '$email1', '$pass1', NULL)") or die(mysql_error());
        echo "Registration Successful";
    } }
    else {
        echo "sorry, something doesn't match.";
    }
} else {
    //displays form
    echo $form = <<<EOT
    <form action="register.php" method="POST">
    First Name: <input type="text" name="name" />

    Last Name: <input type="text" name="lname" />

    Username: <input type="text" name="uname" />

    Email: <input type="text" name="email1" />

    Confirm Email: <input type="text" name="email2" />

    Password: <input type="password" name="pass1" />

    Confirm Password: <input type="password" name="pass2" />

    <input type="submit" value="Register" name="submit" />
EOT;
}

?>

and my config.php is:

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("MyDB");
?>

What to do? My PHP version is 5.6.27 and MySQL version is 5.6.33

Body:
I'd recommend using mysqli. For your case, the config.php would look like:

<?php
$mysqli = new mysqli("localhost", "root", "", "MyDB");

if(mysqli_connect_errno()){
    printf("Connection Failed %s\n", mysqli_connect_error());
    exit();
}

session_start();
if(isset($SESSION["REMOTE_ADDR"]) && $SESSION["REMOTE_ADDR"] !=     $SERVER["REMOTE_ADDR"]){
    session_destroy();
    session_start();
}
?>

and instead of "require", you'd do:

include ("config.php");

Hope this helped


问:
How to find the most recent partition in HIVE table
I have a partitioned table - with 201 partitions.
I need to find latest partition in this table and use it to post process my data. The query to find list of all partitions is :

```<code>use db;
show partitions table_name;
</code>```

I need a query to find the latest of these partitions. The partitions are in format

```<code>ingest_date=2016-03-09
</code>```

I tried using max() which gave me a wrong result. I do not want to traverse through entire table by doing

```<code>select max(ingest_date) from db.table_name;
</code>```

This would give me the expected output.. but kill the whole point of having partitions in the 1st place.

Is there a more efficient query to get the latest partition for HIve table ?

答:
You can use "show partitions":

```<code>hive -e "set hive.cli.print.header=false;show partitions table_name;" | tail -1 | cut -d'=' -f2
</code>```

This will give you "2016-03-09" as output.

Body:
I have a partitioned table - with 201 partitions.
I need to find latest partition in this table and use it to post process my data. The query to find list of all partitions is :

use db;
show partitions table_name;

I need a query to find the latest of these partitions. The partitions are in format

ingest_date=2016-03-09

I tried using max() which gave me a wrong result. I do not want to traverse through entire table by doing

select max(ingest_date) from db.table_name;

This would give me the expected output.. but kill the whole point of having partitions in the 1st place.

Is there a more efficient query to get the latest partition for HIve table ?

Body:
You can use "show partitions":

hive -e "set hive.cli.print.header=false;show partitions table_name;" | tail -1 | cut -d'=' -f2

This will give you "2016-03-09" as output.


问:
Libraries for pretty charts in SWT?
I know the following libraries for drawing charts in an SWT/Eclipse RCP application:

Eclipse BIRT Chart Engine (Links to an article on how to use it)

JFreeChart

Which other libraries are there for drawing pretty charts with SWT? Or charts in Java generally? After all, you can always display an image...

答:
I have not used BIRT or JGraph, however I use JFreeChart in my SWT application. I have found the best way to use JFreeChart in SWT is by making a composite an AWT frame and using the AWT functionality for JFreeChart. The way to do this is by creating a composite

```<code>Composite comp = new Composite(parent, SWT.NONE | SWT.EMBEDDED);
Frame frame = SWT_AWT.new_Frame(comp);
JFreeChart chart = createChart();
ChartPanel chartPanel = new ChartPanel(chart);
frame.add(chartPanel);
</code>```

There are several problems in regards to implementations across different platforms as well as the SWT code in it is very poor (in its defense Mr. Gilbert does not know SWT well and it is made for AWT). My two biggest problems are as AWT events bubble up through SWT there are some erroneous events fired and due to wrapping the AWT frame JFreeChart becomes substantially slower.

@zvikico

The idea of putting the chart into a web page is probably not a great way to go. There are a few problems first being how Eclipse handles integrating the web browser on different platforms is inconsistent. Also from my understanding of a few graphing packages for the web they are server side requiring that setup, also many companies including mine use proxy servers and sometimes this creates issues with the Eclipse web browsing.

OwnerDisplayName: Martin Klinke

ContentLicense: CC BY-SA 2.5

Title: Libraries for pretty charts in SWT?

Body:
I have not used BIRT or JGraph, however I use JFreeChart in my SWT application. I have found the best way to use JFreeChart in SWT is by making a composite an AWT frame and using the AWT functionality for JFreeChart. The way to do this is by creating a composite

Composite comp = new Composite(parent, SWT.NONE | SWT.EMBEDDED);
Frame frame = SWT_AWT.new_Frame(comp);
JFreeChart chart = createChart();
ChartPanel chartPanel = new ChartPanel(chart);
frame.add(chartPanel);

There are several problems in regards to implementations across different platforms as well as the SWT code in it is very poor (in its defense Mr. Gilbert does not know SWT well and it is made for AWT). My two biggest problems are as AWT events bubble up through SWT there are some erroneous events fired and due to wrapping the AWT frame JFreeChart becomes substantially slower.

@zvikico

The idea of putting the chart into a web page is probably not a great way to go. There are a few problems first being how Eclipse handles integrating the web browser on different platforms is inconsistent. Also from my understanding of a few graphing packages for the web they are server side requiring that setup, also many companies including mine use proxy servers and sometimes this creates issues with the Eclipse web browsing.

OwnerDisplayName: Ryan P

LastEditorDisplayName: Ryan P


问:
Any reason for a new project to use log4j instead of Logback?
I know that the common opinion is that Logback > log4j. Still, is there anything log4j does better than Logback? Any reason to use log4j over logback? How about the fact it only has 60 questions on stack overflow, so I presume a much smaller user base?</p>

答: Take a look at official opinion. log4j isn't under active development anymore, and since logback is being developed ground up by the same author as log4j, Ceki Gülcü, to correct some mistakes made in log4j's development, you can be pretty sure that using logback isn't a bad idea.</p>


问:
How to enable font ligatures in Android Studio 2.0?
I've been trying to use FiraCode with its awesome programming ligatures in Android Studio 2.0.

Upon looking on FiraCode's installation guide for IntelliJ IDEs, it said that I should enable a flag in the idea.properties file likewise:

```<code>editor.enable.optional.ligatures=true
</code>```

I've tried to look it up in IntelliJ's guide on how to achieve this. The guide states that I should be able to edit the file in question via the Help menu:

You can create an empty file idea.properties and open it in the editor by choosing the Help | Edit Custom Properties command on the main menu.

But I just can't find it in my setup. Is this achievable in Android Studio 2.0?

答:
```<code>Windows: %USERPROFILE%\.<CONFIGURATION_FOLDER>/
Mac: ~/Library/Preferences/<CONFIGURATION_FOLDER>/
Linux: ~/.<CONFIGURATION_FOLDER>/
</code>```

In my particular it's !/Library/Preferences/AndroidStudio2.2/

Reference: https://developer.android.com/studio/intro/studio-config.html

Body:
I've been trying to use FiraCode with its awesome programming ligatures in Android Studio 2.0.

Upon looking on FiraCode's installation guide for IntelliJ IDEs, it said that I should enable a flag in the idea.properties file likewise:

editor.enable.optional.ligatures=true

I've tried to look it up in IntelliJ's guide on how to achieve this. The guide states that I should be able to edit the file in question via the Help menu:

You can create an empty file idea.properties and open it in the editor by choosing the Help | Edit Custom Properties command on the main menu.

But I just can't find it in my setup. Is this achievable in Android Studio 2.0?

Body:
Windows: %USERPROFILE%\.<CONFIGURATION_FOLDER>/
Mac: ~/Library/Preferences/<CONFIGURATION_FOLDER>/
Linux: ~/.<CONFIGURATION_FOLDER>/

In my particular it's !/Library/Preferences/AndroidStudio2.2/

Reference: https://developer.android.com/studio/intro/studio-config.html


问:
How to get timestamps correspond to the current days date? With Microsoft SQL
The number of rows in the A table, where the date value of the timestamps in the [time_created] and / or [time_updated] fields correspond to the current day's date

答:
GETDATE() returns the current date as a datetime. You can use convert to extract the date part from it:

```<code>SELECT *
FROM   mytable
WHERE  CONVERT (DATE, GETDATE()) IN
       (CONVERT(DATE, time_created), CONVERT(DATE, time_updated))
</code>```

Body:
GETDATE() returns the current date as a datetime. You can use convert to extract the date part from it:

SELECT *
FROM   mytable
WHERE  CONVERT (DATE, GETDATE()) IN
       (CONVERT(DATE, time_created), CONVERT(DATE, time_updated))


问:
nested forms with capybara
I have a post model with

```<code>    accepts_nested_attributes_for :views, :allow_destroy => :true,
      :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
</code>```

And a views model with

```<code>    belongs_to :post, inverse_of: :views
</code>```

In posts/_forms.html.erb

```<code>    <%= post_form.fields_for :views do |builder| %>
    <%= render 'view_fields', f: builder %>
    <% end %>
    <%= link_to_add_fields "Add new View", post_form, :views %>
</code>```

In posts/_view_fields.html.erb

```<code>    <fieldset>
    <%= f.label :name, "View name:" %>
    <%= f.text_field :name %>
    <%= f.hidden_field :_destroy %>
    <%= link_to "remove", '#', class: "remove_fields" %>
    </fieldset>
</code>```

Now in my rspec, I want to fill the f.text_field with some value.

Tried the following:

```<code>  fill_in 'post_views_first_name', with: "I support"
  fill_in 'post_view_name', with: "I support"
  fill_in 'post_views_name', with: "I support"
</code>```

None of the them work. How do I call fill_in on this field?

答:
I'm using a the capybara screenshot gem (Which I highly suggest!). I have a nested form with projects belonging to users. And it accepts

fill_in 'user_projects_attributes_0_name', with: "Name"

So for you, I suggest grabbing the gem for sure. But also try this:

fill_in 'post_views_attributes_0_first_name', with: "I support"

Title: nested forms with capybara

Body:
I have a post model with

    accepts_nested_attributes_for :views, :allow_destroy => :true,
      :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }

And a views model with

    belongs_to :post, inverse_of: :views

In posts/_forms.html.erb

    <%= post_form.fields_for :views do |builder| %>
    <%= render 'view_fields', f: builder %>
    <% end %>
    <%= link_to_add_fields "Add new View", post_form, :views %>

In posts/_view_fields.html.erb

    <fieldset>
    <%= f.label :name, "View name:" %>
    <%= f.text_field :name %>
    <%= f.hidden_field :_destroy %>
    <%= link_to "remove", '#', class: "remove_fields" %>
    </fieldset>

Now in my rspec, I want to fill the f.text_field with some value.

Tried the following:

  fill_in 'post_views_first_name', with: "I support"
  fill_in 'post_view_name', with: "I support"
  fill_in 'post_views_name', with: "I support"

None of the them work. How do I call fill_in on this field?


问:
Bootstrap glyphicons (fonts/****.woff) not loading
I am an error getting that looks like this in my Google chrome(56.0.2924.87) console while trying to use bootstrap glyphicons

Even though i have my .woff files and .ttf files located in my "public/css/fonts" folder.

Addtional Information

I am using Wampserver with apache(2.4.23)

I installed bootstrap.css with "npm install bootstrap"

This is what my font-face looks like

```<code>@font-face {
  font-family: 'Glyphicons Halflings';
  font-style: italic;
  src: url('/public/css/fonts/glyphicons-halflings-regular.eot');
  src: url('/public/css/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('/public/css/fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('/public/css/fonts/glyphicons-halflings-regular.woff') format('woff'), url('/public/css/fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('/public/css/fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
</code>```

}

I try to call the glyphicons like this:

```<code><i class="glyphicon glyphicon-chevron-left"></i>
</code>```

Does anyone have any idea where this problem might be located?

答: Double check @font-face location path and also the mime type.</p>

Body:
I am an error getting that looks like this in my Google chrome(56.0.2924.87) console while trying to use bootstrap glyphicons

Even though i have my .woff files and .ttf files located in my "public/css/fonts" folder.

Addtional Information

I am using Wampserver with apache(2.4.23)

I installed bootstrap.css with "npm install bootstrap"

This is what my font-face looks like

@font-face {
  font-family: 'Glyphicons Halflings';
  font-style: italic;
  src: url('/public/css/fonts/glyphicons-halflings-regular.eot');
  src: url('/public/css/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('/public/css/fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('/public/css/fonts/glyphicons-halflings-regular.woff') format('woff'), url('/public/css/fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('/public/css/fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');

}

I try to call the glyphicons like this:

Does anyone have any idea where this problem might be located?


问:
How to bind values using ng-model
I am working on an app where I am facing this similar issue. I am dynamically creating select boxes based on API response. I dont understand how to bind these values in controller. Code for reference is

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   // how to get values of input boxes here
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model= "What_Should_Go_Here" ng-repeat="x in [10,11,22,33]">
<option>aaa</option>
<option>bbb</option>
<option>ccc</option>
</select>
{{What_Should_Go_Here}}
</div></code>```

答:
Initialize an empty object selected = {}

Then, loop the select boxes using ng-repeat, and inside each select box, use ng-options to get the options for the select.

Now, for each selected value from every select, ng-model="selected[y]" pushes the current select value into selected object with the key of select tag.

So, after selecting all the selects, the selected object looks loke,

{"1":11,"2":10,"3":22,"4":22}

Please run the below Code

<!DOCTYPE html>

<select ng-model="selected[y]" ng-options="x for x in data" ng-repeat="y in selects" ng-change="selectedFunc(y)">
</select>

Selected Values: {{selected}}

```

Here is a working DEMO

Title: How to bind values using ng-model

Body:
I am working on an app where I am facing this similar issue. I am dynamically creating select boxes based on API response. I dont understand how to bind these values in controller. Code for reference is

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   // how to get values of input boxes here
});

<select ng-model= "What_Should_Go_Here" ng-repeat="x in [10,11,22,33]">
<option>aaa</option>
<option>bbb</option>
<option>ccc</option>
</select>
{{What_Should_Go_Here}}

Body:
Initialize an empty object selected = {}

Then, loop the select boxes using ng-repeat, and inside each select box, use ng-options to get the options for the select.

Now, for each selected value from every select, ng-model="selected[y]" pushes the current select value into selected object with the key of select tag.

So, after selecting all the selects, the selected object looks loke,

{"1":11,"2":10,"3":22,"4":22}

Please run the below Code

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="selected[y]" ng-options="x for x in data" ng-repeat="y in selects" ng-change="selectedFunc(y)">
</select>
<br><br>
Selected Values: {{selected}}
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.selected = {};
$scope.selects = [1,2,3,4]
$scope.data = [10,11,22,33]

$scope.selectedFunc = function(y)
{
 alert($scope.selected[y])
}

});
</script>

</body>
</html>

Here is a working DEMO


问:
Error while installing sentry `unable to execute 'clang': No such file or directory`
I am trying to install sentry by following the instruction from the link:
However when I try to execute command pip install -U sentry, I receive the error InstallationError: Command python setup.py egg_info failed with error code 1 in /webapps/sentry/env/build/symsynd

Here is the detail from log file:

```<code> self.run_setup(setup_script, setup_base, args)
      File "/webapps/sentry/env/local/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 1003, in run_setup
        raise DistutilsError("Setup script exited with %s" % (v.args[0],))
    distutils.errors.DistutilsError: Setup script exited with 1
    Complete output from command python setup.py egg_info:
    unable to execute 'clang': No such file or directory

unable to execute 'clang': No such file or directory

    No working compiler found, or bogus compiler options

    passed to the compiler from Python's distutils module.

    See the error messages above.
</code>```

It would be nice if someone can figure out what am I doing wrong.

Thank you,
Vady

答: It seems that specifying a C compiler will be ok, but not. In some packages clang is hard-coded. The only way is to install clang.</p>

Body:
I am trying to install sentry by following the instruction from the link:
However when I try to execute command pip install -U sentry, I receive the error InstallationError: Command python setup.py egg_info failed with error code 1 in /webapps/sentry/env/build/symsynd

Here is the detail from log file:

 self.run_setup(setup_script, setup_base, args)
      File "/webapps/sentry/env/local/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 1003, in run_setup
        raise DistutilsError("Setup script exited with %s" % (v.args[0],))
    distutils.errors.DistutilsError: Setup script exited with 1
    Complete output from command python setup.py egg_info:
    unable to execute 'clang': No such file or directory

unable to execute 'clang': No such file or directory

    No working compiler found, or bogus compiler options

    passed to the compiler from Python's distutils module.

    See the error messages above.

It would be nice if someone can figure out what am I doing wrong.

Thank you,
Vady


问:
List of macOS text editors and code editors
I searched for this and found Maudite's question about text editors but they were all for Windows.

As you have no doubt guessed, I am trying to find out if there are any text/code editors for the Mac besides what I know of. I'll edit my post to include editors listed.

Free

Textwrangler

Xcode

Mac Vim

Aquamacs and closer to the original EMacs

JEdit

Editra

Eclipse

NetBeans

Kod

TextMate2 - GPL

Brackets

Atom.io

Commercial

Textmate

BBEdit

SubEthaEdit

Coda

Sublime Text 2

Smultron

WebStorm

Peppermint

Articles related to the subject

Faceoff, which is the best text editor ever?

Maceditors.com, mac editors features compared

Thank you everybody that has added suggestions.

答: CotEditor is a Cocoa-based open source text editor. It is popular in Japan.</p>

OwnerDisplayName: Teifion

ContentLicense: CC BY-SA 4.0


问:
Transmit FTP ignore files
Is there an ignore or filter list in Transmit when ftping files?  I would like it to ignore uploading .svn files and such.</p>

答:
As mentioned go to Preferences > Rules. It should be noted that although the option says Skip Files I can confirm that it includes folders as well.

Here is an example set of rules that would be a good start that I use based on Transmit's defaults.

Title: Transmit FTP ignore files


问:
Golang byte array communication through channel loses data
I'm using a work-worker Queue implementation in my golang project.
The WorkRequest Struct is as below

```<code>type WorkRequest struct {
fields map[string] []byte }
</code>```

and the dipatcher is

```<code>go func() {
    for {
        select {
        case work := <-WorkQueue:
            go func() {
                worker := <-WorkerQueue
                worker.Work <- work
            }()
        }
    }
}()
</code>```

The worker.Work is channel for WorkRequest struct and WorkerQueue is channel of Worker struct.
Whenever there are many concurrent requests coming in WorkQueue it gets assigned to worker byt the dispatcher routine.

I'm observing issue when I send concurrent requests to WorkQueue, few of them miss out and few of them get executed multiple times.

e.g. If I've queued works with ID  1, 2, 3, 4, 5... then I see workers getting work with ID 1, 2, 4, 4, 5... here 4 is executed twice and 3 is missed. The same code works fine when I implement WorkRequest fields as map[string]string instead of []byte.

Am I missing something or is slice not thread safe and gets assigned same variable.

答:
In Go string is immutable, so it works fine but all slices are mutable. Moreover they can share the backing array. You are not showing the relevant code but I guess you are expecting the map to hold copy of a slice. A slice is just address in memory and length. You need to manually make a new slice and copy its contents.

To fix your code make a copy of slice when putting it into map.

Body:
I'm using a work-worker Queue implementation in my golang project.
The WorkRequest Struct is as below

type WorkRequest struct {
fields map[string] []byte }

and the dipatcher is

go func() {
    for {
        select {
        case work := <-WorkQueue:
            go func() {
                worker := <-WorkerQueue
                worker.Work <- work
            }()
        }
    }
}()

The worker.Work is channel for WorkRequest struct and WorkerQueue is channel of Worker struct.
Whenever there are many concurrent requests coming in WorkQueue it gets assigned to worker byt the dispatcher routine.

I'm observing issue when I send concurrent requests to WorkQueue, few of them miss out and few of them get executed multiple times.

e.g. If I've queued works with ID  1, 2, 3, 4, 5... then I see workers getting work with ID 1, 2, 4, 4, 5... here 4 is executed twice and 3 is missed. The same code works fine when I implement WorkRequest fields as map[string]string instead of []byte.

Am I missing something or is slice not thread safe and gets assigned same variable.


问:
How to group factors by product and display if a product has more than one factor-pair?
Using a predefined array of numbers, how can I use PHP to generate a multi-dimensional array which groups all factor-pairs by their product?

Input array:

```<code>$array = array(1,2,3,4,5,6,7,8);
</code>```

I want to display all factor-pairs for each product group that have more than one factor-pair.

In a case where there are no product groups that have more than one factor-pair, No pairs Found should be displayed.

Given the above input, this is my expected result:

```<code>1 6 and 2 3  // product group = 6
1 8 and 2 4  // product group = 8
2 6 and 3 4  // product group = 12
3 8 and 4 6  // product group = 24
</code>```

*note as the input array increases in size, the output will display more than two factor-pairs per group.

This is my code from C++:

```<code> void findPairs(int arr[], int n)
{
    bool found = false;
    unordered_map<int, pair < int, int > > H;
    for (int i=0; i<n; i++)
    {
        for (int j=i+1; j<n; j++)
        {
            // If product of pair is not in hash table,
            // then store it
            int prod = arr[i]*arr[j];
            if (H.find(prod) == H.end())
                H[prod] = make_pair(i,j);

            // If product of pair is also available in
            // then print current and previous pair
            else
            {
                pair<int,int> pp = H[prod];
                cout << arr[pp.first] << " " << arr[pp.second]
                     << " and " << arr[i]<<" "<<arr[j]<<endl;
                found = true;
            }
        }
    }
    // If no pair find then print not found
    if (found == false)
        cout << "No pairs Found" << endl;
}
</code>```

答:
PHP code demo</p>

```<code><?php
ini_set("display_errors", 1);
$result=array();
$array = array(1,2,3,4,5,6,7,8);
$counter=0;
$noOfPairs=3;
while (count($result)!=$noOfPairs)
{
    shuffle($array);
    getPair($array);
}
print_r($result);
function getPair($array)
{
    global $result;
    $product=$array[0]*$array[1];
    if(isset($result[$product]))
    {
        return false;
    }
    $result[$product][]=array($array[0],$array[1]);
    unset($array[0]);
    unset($array[1]);
    foreach($array as $key1 => $value1)
    {
        foreach($array as $key2 => $value2)
        {
            if($value1*$value2==$product)
            {
                $result[$product][]=array($value1,$value2);
                break;
            }
        }
         if(count($result[$product])==2)
        {
            break;
        }
    }
    if(count($result[$product])==1)
    {
        unset($result[$product]);
    }
}
</code>```

Body:
Using a predefined array of numbers, how can I use PHP to generate a multi-dimensional array which groups all factor-pairs by their product?

Input array:

$array = array(1,2,3,4,5,6,7,8);

I want to display all factor-pairs for each product group that have more than one factor-pair.

In a case where there are no product groups that have more than one factor-pair, No pairs Found should be displayed.

Given the above input, this is my expected result:

1 6 and 2 3  // product group = 6
1 8 and 2 4  // product group = 8
2 6 and 3 4  // product group = 12
3 8 and 4 6  // product group = 24

*note as the input array increases in size, the output will display more than two factor-pairs per group.

This is my code from C++:

 void findPairs(int arr[], int n)
{
    bool found = false;
    unordered_map<int, pair < int, int > > H;
    for (int i=0; i<n; i++)
    {
        for (int j=i+1; j<n; j++)
        {
            // If product of pair is not in hash table,
            // then store it
            int prod = arr[i]*arr[j];
            if (H.find(prod) == H.end())
                H[prod] = make_pair(i,j);

            // If product of pair is also available in
            // then print current and previous pair
            else
            {
                pair<int,int> pp = H[prod];
                cout << arr[pp.first] << " " << arr[pp.second]
                     << " and " << arr[i]<<" "<<arr[j]<<endl;
                found = true;
            }
        }
    }
    // If no pair find then print not found
    if (found == false)
        cout << "No pairs Found" << endl;
}

Body:
PHP code demo

<?php
ini_set("display_errors", 1);
$result=array();
$array = array(1,2,3,4,5,6,7,8);
$counter=0;
$noOfPairs=3;
while (count($result)!=$noOfPairs)
{
    shuffle($array);
    getPair($array);
}
print_r($result);
function getPair($array)
{
    global $result;
    $product=$array[0]*$array[1];
    if(isset($result[$product]))
    {
        return false;
    }
    $result[$product][]=array($array[0],$array[1]);
    unset($array[0]);
    unset($array[1]);
    foreach($array as $key1 => $value1)
    {
        foreach($array as $key2 => $value2)
        {
            if($value1*$value2==$product)
            {
                $result[$product][]=array($value1,$value2);
                break;
            }
        }
         if(count($result[$product])==2)
        {
            break;
        }
    }
    if(count($result[$product])==1)
    {
        unset($result[$product]);
    }
}


问:
How can I add condition in array on vue.js 2?
My vue component is like this :

```<code><a :href="baseUrl+'/message/inbox'"
   :class="{ 'active': currentPath === '/message/inbox' }"
 >
    Message
</a>
</code>```

If they meet the conditions then the message menu will be active

But, I want to make it like this :

```<code><a :href="baseUrl+'/message/inbox'"
   :class="{ 'active': currentPath in array ('/message/inbox', '/message/inbox/detail') }"
 >
    Message
</a>
</code>```

So it will check currentPath in the array

How can I do it?

Update :

If I have menu again like this :

```<code><a :href="baseUrl+'/store/sale'"
   :class="{ 'active': currentPath in array ('/store/sale', '/store/sale/detail') }"
 >
    Sale
</a>
</code>```

Or more menu

How to implement it?

Update 2

```<code><a :href="baseUrl+'/message/inbox'"
   :class="{ 'active': isActive }"
 >
    Message
</a>

<a :href="baseUrl+'/store/sale'"
   :class="{ 'active': isActiveSale }"
 >
    Message
</a>

computed: {
  isActive () {
    return ['/message/inbox', '/message/inbox/detail'].indexOf(this.currentPath) > -1
  },
  isActiveSale () {
    return ['/store/sale', '/store/sale/detail'].indexOf(this.currentPath) > -1
  }
}
</code>```

答:
Add a computed property.

```<code>computed: {
  isActive () {
    return ['/message/inbox', '/message/inbox/detail'].indexOf(this.currentPath) > -1
  }
}
</code>```

So you'll be able to use:

```<code><a :href="baseUrl+'/message/inbox'"
   :class="{ 'active': isActive }"
 >
    Message
</a>
</code>```

Body:
My vue component is like this :

    Message

If they meet the conditions then the message menu will be active

But, I want to make it like this :

    Message

So it will check currentPath in the array

How can I do it?

Update :

If I have menu again like this :

    Sale

Or more menu

How to implement it?

Update 2

    Message

    Message

computed: {
  isActive () {
    return ['/message/inbox', '/message/inbox/detail'].indexOf(this.currentPath) > -1
  },
  isActiveSale () {
    return ['/store/sale', '/store/sale/detail'].indexOf(this.currentPath) > -1
  }
}

Body:
Add a computed property.

computed: {
  isActive () {
    return ['/message/inbox', '/message/inbox/detail'].indexOf(this.currentPath) > -1
  }
}

So you'll be able to use:

<a :href="baseUrl+'/message/inbox'"
   :class="{ 'active': isActive }"
 >
    Message
</a>


问:
How to separate letters and digits from a string in php
I have a string which is combination of letters and digits. For my application i have to separate a string with letters and digits:  ex:If my string is "12jan" i hav to get "12" "jan" separately..</p>

答:
```<code>preg_match_all('/^(\d+)(\w+)$/', $str, $matches);

var_dump($matches);

$day = $matches[1][0];
$month = $matches[2][0];
</code>```

Of course, this only works when your strings are exactly as described "abc123" (with no whitespace appended or prepended).

If you want to get all numbers and characters, you can do it with one regex.

```<code>preg_match_all('/(\d)|(\w)/', $str, $matches);

$numbers = implode($matches[1]);
$letters = implode($matches[2]);

var_dump($numbers, $letters);
</code>```

See it!

Body:
preg_match_all('/^(\d+)(\w+)$/', $str, $matches);

var_dump($matches);

$day = $matches[1][0];
$month = $matches[2][0];

Of course, this only works when your strings are exactly as described "abc123" (with no whitespace appended or prepended).

If you want to get all numbers and characters, you can do it with one regex.

preg_match_all('/(\d)|(\w)/', $str, $matches);

$numbers = implode($matches[1]);
$letters = implode($matches[2]);

var_dump($numbers, $letters);

See it!


问:
For loop and see variable name as a string in R
I want to create a for loop in R, but it should depend on the last letter in 17 variables, and I have trouble finding out how to make the function see the variable name as a string.

The code I have now:

```<code>fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00a))
fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00b))
fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00c))
</code>```

As you can see, i just keep on repeating the code for each variable from the letter a to r, so i want to create a for loop, which can change the last letter of the variable q_81_SQ00a to the letters a-r.

```<code>for (i in c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r')) {

  fisher.test(data.family$proband.unrelated, data.family$q_81_SQ00'i'))

}
</code>```

I get the warning "unexpected symbol" for several places in the code.
Thanks in advance!

答:
You have to paste the letter to the variable name to get a character string, and then select the desired variable using the [] operator.
Another hint: the letters constant in R contains letters from a to z.

Here is a solution:

```<code>for (i in letters[1:18]) {
  fisher.test(data.family["proband.unrelated"],
              data.family[paste0("q_81_SQ00", i)])
}
</code>```

Body:
I want to create a for loop in R, but it should depend on the last letter in 17 variables, and I have trouble finding out how to make the function see the variable name as a string.

The code I have now:

fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00a))
fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00b))
fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00c))

As you can see, i just keep on repeating the code for each variable from the letter a to r, so i want to create a for loop, which can change the last letter of the variable q_81_SQ00a to the letters a-r.

for (i in c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r')) {

  fisher.test(data.family$proband.unrelated, data.family$q_81_SQ00'i'))

}

I get the warning "unexpected symbol" for several places in the code.
Thanks in advance!

Body:
You have to paste the letter to the variable name to get a character string, and then select the desired variable using the [] operator.
Another hint: the letters constant in R contains letters from a to z.

Here is a solution:

for (i in letters[1:18]) {
  fisher.test(data.family["proband.unrelated"],
              data.family[paste0("q_81_SQ00", i)])
}


问:
Universal certificate works for production but not development
I generated a universal push certificate ("Apple Push Notification service SSL (Sandbox & Production)"), which works correctly on production (enterprise distribution).

However, when I use it with a development app (when I install it from Xcode) it doesn't work, and I get the error "The credentials supplied to the package were not recognized" (a PushSharp error).

My old development-only certificate does work.

Any ideas?

答:
Solved it.

My problem was pretty silly - I had a check in the code if the certificate is production or development. It returned 'production' because universal certificate matches the condition there.

Then it tried to treat it as a production app when it wasn't.

My second problem was that PushSharp requires the .p12 file to be exported only from the private key (select only the private key in the KeyChain and select "Export"), while Apple instruct to select both the certificate and the private key to export the .p12.


问:
how to get a month and year from a column in database in laravel?
I have a table actionhistory have a column name actiondate which store the date, i want to get the month from actiondate as mon column and  year of actiondate as year

For example "select extract('month' from actiondate) as mon,extract('year' from actiondate) as year

how can i get the month and year in laravel?

答:
Consideration :

You have already created actionhistory model.

Store date is 30-03-2017 (day-month-year)

Note

    first() will return only one record. You can use ->get() for multiple record however you need to loop the result.

Method 1:

```<code>$result = actionhistory::select(DB::raw('MONTH(actiondate),YEAR(actiondate)'))->get();
</code>```

Method 2:

```<code>$result = DB::table('actionhistory')->select(DB::raw('MONTH(actiondate),YEAR(actiondate)'))->get();
</code>```

Method 3:

```<code>$actionhistory = new actionhistory();
$result = $actionhistory->select(DB::raw('MONTH(actiondate),YEAR(actiondate)'))->get();
</code>```

In all above methods (1,2,3) result will contain following

```<code>[MONTH(actiondate)] => 3
[YEAR(actiondate)] => 2017
</code>```

Method 4 : with Carbon instance

```<code>$result = actionhistory::first();
</code>```

OR

```<code>$result = DB::table('actionhistory')->first();
</code>```

OR

```<code>$result = $actionhistory->first();
</code>```

Now include carbon and use format

```<code>$month = Carbon::parse($sql->created_date)->format('m'); // month will be 3
$year = Carbon::parse($sql->created_date)->format('y');  // year will be 2017
</code>```

Body:
Consideration :

You have already created actionhistory model.

Store date is 30-03-2017 (day-month-year)

Note

    first() will return only one record. You can use ->get() for multiple record however you need to loop the result.

Method 1:

$result = actionhistory::select(DB::raw('MONTH(actiondate),YEAR(actiondate)'))->get();

Method 2:

$result = DB::table('actionhistory')->select(DB::raw('MONTH(actiondate),YEAR(actiondate)'))->get();

Method 3:

$actionhistory = new actionhistory();
$result = $actionhistory->select(DB::raw('MONTH(actiondate),YEAR(actiondate)'))->get();

In all above methods (1,2,3) result will contain following

[MONTH(actiondate)] => 3
[YEAR(actiondate)] => 2017

Method 4 : with Carbon instance

$result = actionhistory::first();

OR

$result = DB::table('actionhistory')->first();

OR

$result = $actionhistory->first();

Now include carbon and use format

$month = Carbon::parse($sql->created_date)->format('m'); // month will be 3
$year = Carbon::parse($sql->created_date)->format('y');  // year will be 2017


问:
Codenameone android build error manifest merger
I have been using the default codescanner cn1-lib but I got sick of the app having to download and external app to scan qr codes on android. So I downloaded the littlemonkey zbar cn1-lib and I added both .cn1lib files to my lib directory and then I started getting build errors. The first were about the minSdkVersion couldn't be lower than a library's sdk version so I changed the build hint android.min_sdkversion=15 then I started getting the error that the java version of the main project can't be lower than a library so I changed build.xml all 'target' and 'source' to 1.8 and I added the build hint java.version=8 however I am still getting a build error.
The log is giving me a Manifest merger failed with multiple errors, see logs

```<code>    Merging result:ERROR
/tmp/build5026335701129669511xxx/MyApplication/src/main/AndroidManifest.xml:43:149-325 Warning:
    Element activity#com.dm.zbar.android.scanner.ZBarScannerActivity at AndroidManifest.xml:43:149-325 duplicated with element declared at AndroidManifest.xml:43:3-149
/tmp/build5026335701129669511xxx/MyApplication/src/main/AndroidManifest.xml:43:114-146 Error:
    Attribute activity#com.dm.zbar.android.scanner.ZBarScannerActivity@label value=(@string/app_name) from AndroidManifest.xml:43:114-146
    is also present at [:ZBarScannerLibrary:] AndroidManifest.xml:18:13-36 value=(Scanner).
    Suggestion: add 'tools:replace="android:label"' to <activity> element at AndroidManifest.xml:43:3-149 to override.
</code>```

I paste binned the whole log: https://pastebin.com/tBJJvGkR

答:
Why don't you do, what exactly Manifest merger suggests you?

Suggestion: add 'tools:replace="android:label"' to  element at AndroidManifest.xml:43:3-149 to override.

In your AndroidManifest.xml's <activity> element add tools:replace="android:label".

Body:
I have been using the default codescanner cn1-lib but I got sick of the app having to download and external app to scan qr codes on android. So I downloaded the littlemonkey zbar cn1-lib and I added both .cn1lib files to my lib directory and then I started getting build errors. The first were about the minSdkVersion couldn't be lower than a library's sdk version so I changed the build hint android.min_sdkversion=15 then I started getting the error that the java version of the main project can't be lower than a library so I changed build.xml all 'target' and 'source' to 1.8 and I added the build hint java.version=8 however I am still getting a build error.
The log is giving me a Manifest merger failed with multiple errors, see logs

    Merging result:ERROR
/tmp/build5026335701129669511xxx/MyApplication/src/main/AndroidManifest.xml:43:149-325 Warning:
    Element activity#com.dm.zbar.android.scanner.ZBarScannerActivity at AndroidManifest.xml:43:149-325 duplicated with element declared at AndroidManifest.xml:43:3-149
/tmp/build5026335701129669511xxx/MyApplication/src/main/AndroidManifest.xml:43:114-146 Error:
    Attribute activity#com.dm.zbar.android.scanner.ZBarScannerActivity@label value=(@string/app_name) from AndroidManifest.xml:43:114-146
    is also present at [:ZBarScannerLibrary:] AndroidManifest.xml:18:13-36 value=(Scanner).
    Suggestion: add 'tools:replace="android:label"' to <activity> element at AndroidManifest.xml:43:3-149 to override.

I paste binned the whole log: https://pastebin.com/tBJJvGkR


问:
Incorrect pug/jade variable scope using jade4j
I am trying the following jade template. My expectation is that at the end of the loop the value of test should be 5

```<code>-test = 0
-var array = [1,2,3,4,5]

p before loop: #{test}
for element in array
  - test++
p after loop: #{test}
</code>```

And actually is working in the fiddle: http://jsfiddle.net/so5tqp35/ there the output is:

```<code>before loop: 0
after loop: 5
</code>```

In my local webserver that is not working and I have

```<code>before loop: 0
after loop: 0
</code>```

Without any errors appearing. I am using springboot with this plugin that takes care of the jade files.

```<code><dependency>
  <groupId>de.neuland-bfi</groupId>
  <artifactId>spring-jade4j</artifactId>
  <version>1.2.3</version>
</dependency>
</code>```

So it seems that there is something wrong in the workflow and the variable does not get overwritten. How can I find some hints on what is wrong?

答:
The problem lies in the plugin that I am using : de.neuland-bfi

There is already a bug report addressing the issue: https://github.com/neuland/jade4j/issues/153

Body:
I am trying the following jade template. My expectation is that at the end of the loop the value of test should be 5

-test = 0
-var array = [1,2,3,4,5]

p before loop: #{test}
for element in array
  - test++
p after loop: #{test}

And actually is working in the fiddle: http://jsfiddle.net/so5tqp35/ there the output is:

before loop: 0
after loop: 5

In my local webserver that is not working and I have

before loop: 0
after loop: 0

Without any errors appearing. I am using springboot with this plugin that takes care of the jade files.

<dependency>
  <groupId>de.neuland-bfi</groupId>
  <artifactId>spring-jade4j</artifactId>
  <version>1.2.3</version>
</dependency>

So it seems that there is something wrong in the workflow and the variable does not get overwritten. How can I find some hints on what is wrong?


问:
Prevent border clipping my image
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slideshow">
    <table>
      <tr>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px"  src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
      </tr>
    </table>
    <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
  </div></code>```

Images:

No-Clipping

Clipping

Winrar logo

答:
If you just remove the overflow:hidden: it should not clip, and you should change the html to have the class on the wrapping  element

.icon_circle {
    padding: 30px;
    border-radius: 90px;
    border: #000 5px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slideshow">
    <table>
      <tr>
        <td class="icon_circle" ><img width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td class="icon_circle"><img  width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td class="icon_circle"><img width="90px"  src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
      </tr>
    </table>
    <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
  </div></code>```

Title: Prevent border clipping my image

Body:
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}

Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.

Images:

No-Clipping

Clipping

Winrar logo

Body:
If you just remove the overflow:hidden: it should not clip, and you should change the html to have the class on the wrapping  element

.icon_circle {
    padding: 30px;
    border-radius: 90px;
    border: #000 5px solid;
}

  <div class="slideshow">
    <table>
      <tr>
        <td class="icon_circle" ><img width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td class="icon_circle"><img  width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td class="icon_circle"><img width="90px"  src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
      </tr>
    </table>
    <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
  </div>


问:
jquery hover div and show another div then keep that div open
I'd really appreciate if someone can help me.

i just want to hover a div and show another div then i want to hover that div but that div still open

Code snippet:

$(function(){
 $('.navigation li').hover(
   function(){
     $('.navigation-dropdown').toggleClass('visible');
    }
    );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navigation{
  color: #ffffff;
  background-color: #000000;
  height: 20px;
  width: 100%;
}
.navigation li{
  display: inline-block;
}
.navigation-dropdown{
  background-color:red;
  display: none;
}
.visible{
  display: block;
}</code>```

home

about

contact

```

https://jsfiddle.net/7okx2Lrx/7/

答:
The hover work only when the mouse is on the element.
Your should put your second element IN the first one, then when you will hover the second element, you will stay in the first one.

Working example:
https://jsfiddle.net/7okx2Lrx/8/
I removed the height and the vertical margins:

```<code>.navigation ul {
  margin-top: 0;
  margin-bottom: 0;
}
</code>```

Body:
I'd really appreciate if someone can help me.

i just want to hover a div and show another div then i want to hover that div but that div still open

Code snippet:

$(function(){
 $('.navigation li').hover(
   function(){
     $('.navigation-dropdown').toggleClass('visible');
    }
    );
});

.navigation{
  color: #ffffff;
  background-color: #000000;
  height: 20px;
  width: 100%;
}
.navigation li{
  display: inline-block;
}
.navigation-dropdown{
  background-color:red;
  display: none;
}
.visible{
  display: block;
}

home

about

contact

https://jsfiddle.net/7okx2Lrx/7/

Body:
The hover work only when the mouse is on the element.
Your should put your second element IN the first one, then when you will hover the second element, you will stay in the first one.

Working example:
https://jsfiddle.net/7okx2Lrx/8/
I removed the height and the vertical margins:

.navigation ul {
  margin-top: 0;
  margin-bottom: 0;
}


问:
Summing specific numbers in list as specified by another list
Okay so I have two lists. One of strings 'addition' or 'subtraction', and one of integers. like so

```<code>valueTypes = ['addition', 'subtraction', 'subtraction','addition', 'subtraction']

valueAmounts = [100, 52, 47, 734, 99]
</code>```

each index of the valueTypes list is associated with its respective index from the valueAmounts list. That is to say 100 is 'addition', 52 is 'subtraction'...ect.

How can I sum just the valueAmount numbers that are associated with just 'addition' strings or just 'subtraction' strings, from valueTypes?

答:
Use zip to connect the pairs, and use sum to add the relevant numbers together:

```<code>>>> valueTypes = ['addition', 'subtraction', 'subtraction','addition', 'subtraction']
>>> valueAmounts = [100, 52, 47, 734, 99]
>>> sum(b for a,b in zip(valueTypes, valueAmounts) if a=='addition')
834
</code>```

Body:
Okay so I have two lists. One of strings 'addition' or 'subtraction', and one of integers. like so

valueTypes = ['addition', 'subtraction', 'subtraction','addition', 'subtraction']

valueAmounts = [100, 52, 47, 734, 99]

each index of the valueTypes list is associated with its respective index from the valueAmounts list. That is to say 100 is 'addition', 52 is 'subtraction'...ect.

How can I sum just the valueAmount numbers that are associated with just 'addition' strings or just 'subtraction' strings, from valueTypes?

Body:
Use zip to connect the pairs, and use sum to add the relevant numbers together:

>>> valueTypes = ['addition', 'subtraction', 'subtraction','addition', 'subtraction']
>>> valueAmounts = [100, 52, 47, 734, 99]
>>> sum(b for a,b in zip(valueTypes, valueAmounts) if a=='addition')
834