问:
How to make .mak file?
I have src of the project that was created in 1999 (actually it's MUD SoG '99). There are file SOG.MAK, but I couldn't find any data about how to make this project. Could somebody give me a hint how to make it?

The project's src link: http://www.ianshirm.net/index.php?option=com_remository&Itemid=53&func=fileinfo&id=1370

SOG.MAK content is below:

```<code>CC=cl.exe

CFLAGS=/nologo /ML /W3 /G4e /O2g /D "WIN32" /YX /c
INCLUDES= -I . -I ..\msgdb -I .\COMM -I .\COMPAT -I .\DB -I .\OLC -I .\COMPAT\regex-win32

LINK32=link.exe

LFLAGS=wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib\
 comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib\
 odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no\
 /machine:I386 /out:"sog.exe"

COMM_CFILES = comm\ban.c comm\charset.c comm\comm.c comm\comm_act.c\
              comm\comm_colors.c comm\comm_info.c comm\resolver.c
COMM_OFILES = comm\ban.obj comm\charset.obj comm\comm.obj comm\comm_act.obj\
              comm\comm_colors.obj comm\comm_info.obj comm\resolver.obj

DB_CFILES = db\cmd.c db\db.c db\db_area.c db\db_clan.c db\db_class.c\
            db\db_skills.c db\db_lang.c db\db_race.c\
            db\gsn.c db\lang.c db\msg.c db\resource.c db\spellfn.c db\word.c
DB_OFILES = db\cmd.obj db\db.obj db\db_area.obj db\db_clan.obj db\db_class.obj\
            db\db_skills.obj db\db_lang.obj db\db_race.obj db\gsn.obj\
            db\lang.obj db\msg.obj db\resource.obj db\spellfn.obj db\word.obj

OLC_CFILES = olc\olc.c olc\olc_area.c olc\olc_clan.c olc\olc_help.c\
             olc\olc_lang.c olc\olc_mob.c olc\olc_mpcode.c olc\olc_msg.c\
             olc\olc_room.c olc\olc_obj.c olc\olc_save.c olc\olc_word.c
OLC_OFILES = olc\olc.obj olc\olc_area.obj olc\olc_clan.obj olc\olc_help.obj\
             olc\olc_lang.obj olc\olc_mob.obj olc\olc_mpcode.obj\
             olc\olc_msg.obj olc\olc_room.obj olc\olc_obj.obj olc\olc_save.obj\
             olc\olc_word.obj

COMPAT_CFILES = compat\winstuff.c compat\strsep.c compat\strcasecmp.c\
                compat\regex-win32\regex_regcomp.c\
                compat\regex-win32\regex_regerror.c\
                compat\regex-win32\regex_regexec.c\
                compat\regex-win32\regex_regfree.c
COMPAT_OFILES = compat\winstuff.obj compat\strsep.obj compat\strcasecmp.obj\
                compat\regex-win32\regex_regcomp.obj\
                compat\regex-win32\regex_regerror.obj\
                compat\regex-win32\regex_regexec.obj\
                compat\regex-win32\regex_regfree.obj

CFILES = act_comm.c act_info.c act_move.c act_obj.c act_wiz.c auction.c\
         buffer.c clan.c class.c\
         effects.c fight.c flag.c handler.c healer.c help.c hometown.c\
         hunt.c interp.c log.c lookup.c magic.c magic2.c martial_art.c mem.c\
         mlstring.c mob_cmds.c mob_prog.c namedp.c note.c obj_prog.c quest.c\
         race.c raffects.c rating.c recycle.c religion.c repair.c\
         save.c skills.c special.c str.c string_edit.c\
         tables.c update.c util.c varr.c\
         $(COMM_CFILES) $(DB_CFILES) $(OLC_CFILES) $(COMPAT_CFILES)

OFILES = act_comm.obj act_info.obj act_move.obj act_obj.obj act_wiz.obj\
     auction.obj buffer.obj clan.obj class.obj effects.obj fight.obj flag.obj\
     handler.obj healer.obj help.obj hometown.obj hunt.obj interp.obj log.obj\
     lookup.obj magic.obj magic2.obj martial_art.obj mem.obj mlstring.obj\
     mob_cmds.obj mob_prog.obj namedp.obj note.obj obj_prog.obj quest.obj\
     race.obj raffects.obj rating.obj recycle.obj religion.obj repair.obj\
     save.obj skills.obj special.obj str.obj string_edit.obj tables.obj\
     update.obj util.obj varr.obj\
     $(COMM_OFILES) $(DB_OFILES) $(OLC_OFILES) $(COMPAT_OFILES)

ALL : "sog.exe"

CLEAN :
        -@erase "sog.exe"
        -@erase "*.obj"
        -@erase "COMM\*.obj"
        -@erase "COMPAT\*.obj"
        -@erase "COMPAT\regex-win32\*.obj"
        -@erase "DB\*.obj"
        -@erase "OLC\*.obj"

"sog.exe" : $(DEF_FILE) $(OFILES)
    $(LINK32) @<<
  $(LFLAGS) $(OFILES)
<<

.c.obj:
    $(CC) $(CFLAGS) $(INCLUDES) /Fo%|pfF.obj $<
</code>```

答: Wouldn't make -f SOG.MAK help?

Title: How to make .mak file?

Body:
I have src of the project that was created in 1999 (actually it's MUD SoG '99). There are file SOG.MAK, but I couldn't find any data about how to make this project. Could somebody give me a hint how to make it?

The project's src link: http://www.ianshirm.net/index.php?option=com_remository&Itemid=53&func=fileinfo&id=1370

SOG.MAK content is below:

CC=cl.exe

CFLAGS=/nologo /ML /W3 /G4e /O2g /D "WIN32" /YX /c
INCLUDES= -I . -I ..\msgdb -I .\COMM -I .\COMPAT -I .\DB -I .\OLC -I .\COMPAT\regex-win32

LINK32=link.exe

LFLAGS=wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib\
 comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib\
 odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no\
 /machine:I386 /out:"sog.exe"

COMM_CFILES = comm\ban.c comm\charset.c comm\comm.c comm\comm_act.c\
              comm\comm_colors.c comm\comm_info.c comm\resolver.c
COMM_OFILES = comm\ban.obj comm\charset.obj comm\comm.obj comm\comm_act.obj\
              comm\comm_colors.obj comm\comm_info.obj comm\resolver.obj

DB_CFILES = db\cmd.c db\db.c db\db_area.c db\db_clan.c db\db_class.c\
            db\db_skills.c db\db_lang.c db\db_race.c\
            db\gsn.c db\lang.c db\msg.c db\resource.c db\spellfn.c db\word.c
DB_OFILES = db\cmd.obj db\db.obj db\db_area.obj db\db_clan.obj db\db_class.obj\
            db\db_skills.obj db\db_lang.obj db\db_race.obj db\gsn.obj\
            db\lang.obj db\msg.obj db\resource.obj db\spellfn.obj db\word.obj

OLC_CFILES = olc\olc.c olc\olc_area.c olc\olc_clan.c olc\olc_help.c\
             olc\olc_lang.c olc\olc_mob.c olc\olc_mpcode.c olc\olc_msg.c\
             olc\olc_room.c olc\olc_obj.c olc\olc_save.c olc\olc_word.c
OLC_OFILES = olc\olc.obj olc\olc_area.obj olc\olc_clan.obj olc\olc_help.obj\
             olc\olc_lang.obj olc\olc_mob.obj olc\olc_mpcode.obj\
             olc\olc_msg.obj olc\olc_room.obj olc\olc_obj.obj olc\olc_save.obj\
             olc\olc_word.obj

COMPAT_CFILES = compat\winstuff.c compat\strsep.c compat\strcasecmp.c\
                compat\regex-win32\regex_regcomp.c\
                compat\regex-win32\regex_regerror.c\
                compat\regex-win32\regex_regexec.c\
                compat\regex-win32\regex_regfree.c
COMPAT_OFILES = compat\winstuff.obj compat\strsep.obj compat\strcasecmp.obj\
                compat\regex-win32\regex_regcomp.obj\
                compat\regex-win32\regex_regerror.obj\
                compat\regex-win32\regex_regexec.obj\
                compat\regex-win32\regex_regfree.obj

CFILES = act_comm.c act_info.c act_move.c act_obj.c act_wiz.c auction.c\
         buffer.c clan.c class.c\
         effects.c fight.c flag.c handler.c healer.c help.c hometown.c\
         hunt.c interp.c log.c lookup.c magic.c magic2.c martial_art.c mem.c\
         mlstring.c mob_cmds.c mob_prog.c namedp.c note.c obj_prog.c quest.c\
         race.c raffects.c rating.c recycle.c religion.c repair.c\
         save.c skills.c special.c str.c string_edit.c\
         tables.c update.c util.c varr.c\
         $(COMM_CFILES) $(DB_CFILES) $(OLC_CFILES) $(COMPAT_CFILES)

OFILES = act_comm.obj act_info.obj act_move.obj act_obj.obj act_wiz.obj\
     auction.obj buffer.obj clan.obj class.obj effects.obj fight.obj flag.obj\
     handler.obj healer.obj help.obj hometown.obj hunt.obj interp.obj log.obj\
     lookup.obj magic.obj magic2.obj martial_art.obj mem.obj mlstring.obj\
     mob_cmds.obj mob_prog.obj namedp.obj note.obj obj_prog.obj quest.obj\
     race.obj raffects.obj rating.obj recycle.obj religion.obj repair.obj\
     save.obj skills.obj special.obj str.obj string_edit.obj tables.obj\
     update.obj util.obj varr.obj\
     $(COMM_OFILES) $(DB_OFILES) $(OLC_OFILES) $(COMPAT_OFILES)

ALL : "sog.exe"

CLEAN :
        -@erase "sog.exe"
        -@erase "*.obj"
        -@erase "COMM\*.obj"
        -@erase "COMPAT\*.obj"
        -@erase "COMPAT\regex-win32\*.obj"
        -@erase "DB\*.obj"
        -@erase "OLC\*.obj"

"sog.exe" : $(DEF_FILE) $(OFILES)
    $(LINK32) @<<
  $(LFLAGS) $(OFILES)
<<

.c.obj:
    $(CC) $(CFLAGS) $(INCLUDES) /Fo%|pfF.obj $<

Body: Wouldn't make -f SOG.MAK help?


来源: stackexchange

问:
MySQL - Why is phpMyAdmin extremely slow with this query that is super fast in php/mysqli?
Edit: see also my answer, the main difference is the LIMIT that phpmyadmin adds, but I still don't understand and phpmyadmin is still slower than mysqli.

On our database (+web) server we have a huge difference in performance when doing a query in phpmyadmin vs doing it from php (mysqli) or directly on the mariadb server. 60 seconds vs < 0.01 seconds!

This query functions quite well:

```<code>SELECT * FROM `TitelDaggegevens`
WHERE `datum` > '2020-03-31' AND datum < '2020-05-02' AND `fondskosten` IS NULL
ORDER BY isbn;
</code>```

But, only in phpMyAdmin, the query becomes extremely slow when we change 2020-05-02 to 2020-05-01.

SHOW PROCESSLIST shows that the queryu is mainly Sending data whilst running.

Following mysql.rjweb.org/doc.php/index_cookbook_mysql#handler_counts I did the following query-series:

```<code>FLUSH STATUS;
SELECT-query above with one of the two dates;
SHOW SESSION STATUS LIKE 'Handler%';
</code>```

The differences are fascinating. (I left out all the values equal to 0 in all cases). And consistent over time.

```<code>|                        how:   |     server/MySqli       |      phpMyAdmin
|         date used in query:   | 2020-05-02 | 2020-05-01 | 2020-05-02 | 2020-05-01
|           records returned:   | 6912       | 1          | 6912       | 1
|                  avg speed:   | 0.27s      | 0.00s      | 0.52s      | 60s (!)
| Variable_name                 | Value      | Value      | Value      | Value
| Handler_icp_attempts          | 213197     | 206286     | 213197     | 0
| Handler_icp_match             | 6912       | 1          | 6912       | 0
| Handler_read_next             | 6912       | 1          | 26651      | 11728896 (!)
| Handler_read_key              | 1          | 1          | 151        | 4
| Handler_commit                | 1          | 1          | 152        | 5
| Handler_read_first            | 0          | 0          | 1          | 1
| Handler_read_rnd_next         | 0          | 0          | 82         | 83
| Handler_read_rnd              | 0          | 0          | 0          | 1
| Handler_tmp_write             | 0          | 0          | 67         | 67
</code>```

The EXPLAIN results are the same in all cases (phpmyadmin/mysqli/putty+mariadb).

```<code>    [select_type] => SIMPLE
    [table] => TitelDaggegevens
    [type] => range
    [possible_keys] => fondskosten,Datum+isbn+fondskosten
    [key] => Datum+isbn+fondskosten
    [key_len] => 3
    [ref] =>
    [Extra] => Using index condition; Using filesort
</code>```

The only difference is in rows:

```<code>    [rows] => 422796 for 2020-05-01
    [rows] => 450432 for 2020-05-02
</code>```

The question

Can you give us any directions in where we should could look to solve this problem? We've worked for a week to optimize the mariadb server (now optimal, except in phpmyadmin) and narrow some of our problems down to the example underneath. We use phpmyadmin a lot but have little to no experience with what is under the surface (like how it connects to the db).

About the indexing/ordering

In the slow query, if we change the ORDER BY from the indexed isbn field to a non-indexed field or leave out the ORDER BY altogether, everything has its normal lightning speed again. Changing the ORDER BY to the primary key id makes it slow too, but still 10x as fast as with the indexed isbn field.

We *know* we can solve this particular query by better indexing, which we already have ready to implement. However, we want to know what causes the different times within phpmyadmin vs mysqli/directly.

The details:

TitelDaggegevens contains < 11mln records, not even 3Gb, and has been OPTIMIZEd (rebuild)

The table structure:

```<code>CREATE TABLE `TitelDaggegevens` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `isbn` decimal(13,0) NOT NULL,
 `datum` date NOT NULL,
 `volgendeDatum` date DEFAULT NULL,
 `prijs` decimal(8,2) DEFAULT NULL,
 `prijsExclLaag` decimal(8,2) DEFAULT NULL,
 `prijsExclHoog` decimal(8,2) DEFAULT NULL,
 `stadiumDienstverlening` char(2) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `stadiumLevenscyclus` char(1) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `gewicht` double(7,3) DEFAULT NULL,
 `volume` double(7,3) DEFAULT NULL,
 `24uurs` tinyint(1) DEFAULT NULL,
 `UitgeverCode` varchar(4) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `imprintId` int(11) DEFAULT NULL,
 `distributievormId` tinyint(4) DEFAULT NULL,
 `boeksoort` char(1) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `publishingStatus` tinyint(4) DEFAULT NULL,
 `productAvailability` tinyint(4) DEFAULT NULL,
 `voorraadAlles` mediumint(8) unsigned DEFAULT NULL,
 `voorraadBeschikbaar` mediumint(8) unsigned DEFAULT NULL,
 `voorraadGeblokkeerdEigenaar` smallint(5) unsigned DEFAULT NULL,
 `voorraadGeblokkeerdCB` smallint(5) unsigned DEFAULT NULL,
 `voorraadGereserveerd` smallint(5) unsigned DEFAULT NULL,
 `fondskosten` enum('depot leverbaar','depot onleverbaar','POD','BOV','eBoek','geen') COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `ISBN+datum` (`isbn`,`datum`) USING BTREE,
 KEY `UitgeverCode` (`UitgeverCode`),
 KEY `Imprint` (`imprintId`),
 KEY `VolgendeDatum` (`volgendeDatum`),
 KEY `Index op voorraad om maxima snel te vinden` (`isbn`,`voorraadAlles`) USING BTREE,
 KEY `fondskosten` (`fondskosten`),
 KEY `Datum+isbn+fondskosten` (`datum`,`isbn`,`fondskosten`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=16519430 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci
</code>```

Configuration of our virtual web+database+mail server:

```<code>MariaDB 10.4
InnoDB
CentOs7
phpMyAdmin 4.9.5
php 5.6
Apache
</code>```

Some important mariadb configuration parameters that we changed from what our virtual webserver had as default:

```<code>[mysqld]
innodb_buffer_pool_size=2G
innodb_buffer_pool_instances=4
innodb_flush_log_at_trx_commit=2

tmp_table_size=64M
max_heap_table_size=64M

join_buffer_size=4M
sort_buffer_size=8M

optimizer_search_depth=5
</code>```

答:
(I'm rather late weighing in.  Glad to see that you have "resolved" it.)

You found a strange one, and did a good job of investigating.

Is there a way to get EXPLAIN from phpmyadmin?  If so, that might give another clue.

The Handler numbers strongly imply a different EXPLAIN was used.

Clearly phpmyadmin modifies the query (at least by adding the LIMIT).  I wonder if it messed with the query accidentally.  Did you have the Slowlog or the General log turned on at that time?  Either should have the SQL as run.

Replacing the index on just (fondskosten) with INDEX(fondskosten, datum) should improve performance.

("Sending data", as always, is useless information provided by the engine.)

Suggest filing a bug with mariadb.com.

ContentLicense: CC BY-SA 4.0

Body:
Edit: see also my answer, the main difference is the LIMIT that phpmyadmin adds, but I still don't understand and phpmyadmin is still slower than mysqli.

On our database (+web) server we have a huge difference in performance when doing a query in phpmyadmin vs doing it from php (mysqli) or directly on the mariadb server. 60 seconds vs < 0.01 seconds!

This query functions quite well:

SELECT * FROM `TitelDaggegevens`
WHERE `datum` > '2020-03-31' AND datum < '2020-05-02' AND `fondskosten` IS NULL
ORDER BY isbn;

But, only in phpMyAdmin, the query becomes extremely slow when we change 2020-05-02 to 2020-05-01.

SHOW PROCESSLIST shows that the queryu is mainly Sending data whilst running.

Following mysql.rjweb.org/doc.php/index_cookbook_mysql#handler_counts I did the following query-series:

FLUSH STATUS;
SELECT-query above with one of the two dates;
SHOW SESSION STATUS LIKE 'Handler%';

The differences are fascinating. (I left out all the values equal to 0 in all cases). And consistent over time.

|                        how:   |     server/MySqli       |      phpMyAdmin
|         date used in query:   | 2020-05-02 | 2020-05-01 | 2020-05-02 | 2020-05-01
|           records returned:   | 6912       | 1          | 6912       | 1
|                  avg speed:   | 0.27s      | 0.00s      | 0.52s      | 60s (!)
| Variable_name                 | Value      | Value      | Value      | Value
| Handler_icp_attempts          | 213197     | 206286     | 213197     | 0
| Handler_icp_match             | 6912       | 1          | 6912       | 0
| Handler_read_next             | 6912       | 1          | 26651      | 11728896 (!)
| Handler_read_key              | 1          | 1          | 151        | 4
| Handler_commit                | 1          | 1          | 152        | 5
| Handler_read_first            | 0          | 0          | 1          | 1
| Handler_read_rnd_next         | 0          | 0          | 82         | 83
| Handler_read_rnd              | 0          | 0          | 0          | 1
| Handler_tmp_write             | 0          | 0          | 67         | 67

The EXPLAIN results are the same in all cases (phpmyadmin/mysqli/putty+mariadb).

    [select_type] => SIMPLE
    [table] => TitelDaggegevens
    [type] => range
    [possible_keys] => fondskosten,Datum+isbn+fondskosten
    [key] => Datum+isbn+fondskosten
    [key_len] => 3
    [ref] =>
    [Extra] => Using index condition; Using filesort

The only difference is in rows:

    [rows] => 422796 for 2020-05-01
    [rows] => 450432 for 2020-05-02

The question

Can you give us any directions in where we should could look to solve this problem? We've worked for a week to optimize the mariadb server (now optimal, except in phpmyadmin) and narrow some of our problems down to the example underneath. We use phpmyadmin a lot but have little to no experience with what is under the surface (like how it connects to the db).

About the indexing/ordering

In the slow query, if we change the ORDER BY from the indexed isbn field to a non-indexed field or leave out the ORDER BY altogether, everything has its normal lightning speed again. Changing the ORDER BY to the primary key id makes it slow too, but still 10x as fast as with the indexed isbn field.

We *know* we can solve this particular query by better indexing, which we already have ready to implement. However, we want to know what causes the different times within phpmyadmin vs mysqli/directly.

The details:

TitelDaggegevens contains < 11mln records, not even 3Gb, and has been OPTIMIZEd (rebuild)

The table structure:

CREATE TABLE `TitelDaggegevens` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `isbn` decimal(13,0) NOT NULL,
 `datum` date NOT NULL,
 `volgendeDatum` date DEFAULT NULL,
 `prijs` decimal(8,2) DEFAULT NULL,
 `prijsExclLaag` decimal(8,2) DEFAULT NULL,
 `prijsExclHoog` decimal(8,2) DEFAULT NULL,
 `stadiumDienstverlening` char(2) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `stadiumLevenscyclus` char(1) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `gewicht` double(7,3) DEFAULT NULL,
 `volume` double(7,3) DEFAULT NULL,
 `24uurs` tinyint(1) DEFAULT NULL,
 `UitgeverCode` varchar(4) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `imprintId` int(11) DEFAULT NULL,
 `distributievormId` tinyint(4) DEFAULT NULL,
 `boeksoort` char(1) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `publishingStatus` tinyint(4) DEFAULT NULL,
 `productAvailability` tinyint(4) DEFAULT NULL,
 `voorraadAlles` mediumint(8) unsigned DEFAULT NULL,
 `voorraadBeschikbaar` mediumint(8) unsigned DEFAULT NULL,
 `voorraadGeblokkeerdEigenaar` smallint(5) unsigned DEFAULT NULL,
 `voorraadGeblokkeerdCB` smallint(5) unsigned DEFAULT NULL,
 `voorraadGereserveerd` smallint(5) unsigned DEFAULT NULL,
 `fondskosten` enum('depot leverbaar','depot onleverbaar','POD','BOV','eBoek','geen') COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `ISBN+datum` (`isbn`,`datum`) USING BTREE,
 KEY `UitgeverCode` (`UitgeverCode`),
 KEY `Imprint` (`imprintId`),
 KEY `VolgendeDatum` (`volgendeDatum`),
 KEY `Index op voorraad om maxima snel te vinden` (`isbn`,`voorraadAlles`) USING BTREE,
 KEY `fondskosten` (`fondskosten`),
 KEY `Datum+isbn+fondskosten` (`datum`,`isbn`,`fondskosten`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=16519430 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci

Configuration of our virtual web+database+mail server:

MariaDB 10.4
InnoDB
CentOs7
phpMyAdmin 4.9.5
php 5.6
Apache

Some important mariadb configuration parameters that we changed from what our virtual webserver had as default:

[mysqld]
innodb_buffer_pool_size=2G
innodb_buffer_pool_instances=4
innodb_flush_log_at_trx_commit=2

tmp_table_size=64M
max_heap_table_size=64M

join_buffer_size=4M
sort_buffer_size=8M

optimizer_search_depth=5


问:
How to check if a string is a valid Json Schema?
If I have a string = "{}", which is not a valid Json Schema, how do I check it using jackson whether it is a valid Json Schema or not?</p>

答:
Draft 2019-09 defines some new keywords that allow you to declare that the contents of a string is JSON and conforms to a given schema. However, these keywords are informative only. No assertions are enforced. You would have to extract that information from the schema and do the validation separately.

It would look something like this.

```<code>{
  "type": "string",
  "contentMediaType": "application/schema+json",
  "contentSchema": { "$ref": "https://json-schema.org/draft/2019-09" }
}
</code>```

Also keep in mind that draft 2019-09 doesn't have a lot of implementations at this point, so you might have difficultly finding tools that understand the new keywords. We've seen quite a bit of progress on that front recently, so hopefully that won't be the case for too much longer.

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-02#section-8

Body:
Draft 2019-09 defines some new keywords that allow you to declare that the contents of a string is JSON and conforms to a given schema. However, these keywords are informative only. No assertions are enforced. You would have to extract that information from the schema and do the validation separately.

It would look something like this.

{
  "type": "string",
  "contentMediaType": "application/schema+json",
  "contentSchema": { "$ref": "https://json-schema.org/draft/2019-09" }
}

Also keep in mind that draft 2019-09 doesn't have a lot of implementations at this point, so you might have difficultly finding tools that understand the new keywords. We've seen quite a bit of progress on that front recently, so hopefully that won't be the case for too much longer.

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-02#section-8


问:
Getting error for differences in number of rows
I keep getting this error code "Error in [<-.data.frame(*tmp*, , x, value = c(16100, 14800, 13100,  :
  replacement has 163 rows, data has 182" and I'm not sure how to fix this. I know it has something to do with NAs but i've tried na.omit and couldn't get it to work. I've tried changing the number of rows in the dischange.data matrix but that doesn't work either. Please help!

```<code>library(waterData)

## List of start dates
start.dates <- c(
                 "2009-12-01", "2010-12-01", "2011-12-01", "2012-12-01",
                 "2013-12-01", "2014-12-01", "2015-12-01", "2016-12-01",
                 "2017-12-01", "2018-12-01")

## List of end dates
end.dates <- c(
               "2010-05-31", "2011-05-31", "2012-05-30", "2013-05-31",
               "2014-05-31", "2015-05-31", "2016-05-30", "2017-05-31",
               "2018-05-31", "2019-05-31")

## Bind start and end dates into a single dataframe
flow.dates <- as.data.frame(cbind(start.dates, end.dates))

## Empty dataframe for discharge data; nrow=no of days in each inverval,
#ncol=no invtervals
discharge.data <- as.data.frame(data.frame(matrix(0,
                                                  nrow = 182, ncol = 10)))

## Append data for all dates
for(x in 1:10){
  bin.1 <- importDVs(staid = "02198375", code = "00060", stat = "00003",
                     sdate = flow.dates[x, 1],
                     edate = flow.dates[x, 2])
  bin.2 <- cleanUp(bin.1, task = "fix", replace = 0.001)
  bin.3 <- fillMiss(bin.1, block = 2, pmiss = 5, model = "trend",
                    smooth = FALSE, log = "y")
  bin.4 <- bin.3[, c(2, 3)]
  colnames(bin.4) <- c(flow.dates[x, 3])
  discharge.data[, x] <- bin.4[, 1]
}

## Calculate season mean & convert from ft3 to m3
mean.discharge.ws <- sapply(discharge.data, mean)
met.shift.ws <- (mean.discharge.ws / 35.315)

## Create dataframe

met.winterspring.Year <- c( 2010, 2011, 2012, 2013, 2014,
                           2015, 2016, 2017, 2018, 2019)

df=data.frame(met.shift.ws, met.winterspring.Year)
my.formula = df$met.shift.ws ~ df$met.winterspring.Year

fit = lm(met.winterspring.Year ~  met.shift.ws ,data=df )
summary(fit)

library(ggplot2)
library(ggpmisc) # for dealing with stat equations
library (grid)

ggplot(df, aes(met.winterspring.Year, met.shift.ws)) +
  geom_line(group=1) +
  geom_smooth(method = "lm", se=FALSE) +
  stat_poly_eq(formula = my.formula,
               eq.with.lhs = "italic(hat(y))~`=`~",
               aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
               parse = TRUE)+
  theme_classic()+
  labs(x="", y=(expression(Discharge~(m^{3}~s^{-1}))))+
  theme_classic() +
  scale_x_continuous(breaks = breaks_width(2)) +
  annotate(geom = "text", x = 2017, y = 300, label = "Winter-Spring", hjust = "left")
</code>```

答:
I have no idea what water.data is or what half of the functions do, but I quickly downloaded the package, and if you add print(x) in your for loop where you append data for all dates, you'll immediately see that for x=7, there are 163 rows in bin.1, and not 182. I don't know what that means, but if its just a think where 1:182 is just a to hold the values, then you can just pad some NAs if the length of the vectors you are appending are too small. So maybe something like

```<code>discharge.data <- as.data.frame(data.frame(matrix(0,
                                                  nrow = 182, ncol = 10)))

## Append data for all dates
for(x in 1:10){
  bin.1 <- importDVs(staid = "02198375", code = "00060", stat = "00003",
                     sdate = flow.dates[x, 1],
                     edate = flow.dates[x, 2])
  bin.2 <- cleanUp(bin.1, task = "fix", replace = 0.001)
  bin.3 <- fillMiss(bin.1, block = 2, pmiss = 5, model = "trend",
                    smooth = FALSE, log = "y")
  bin.4 <- bin.3[, c(2, 3)]
  colnames(bin.4) <- c(flow.dates[x, 3])

  #pad some NAs if too short vector
  vec = bin.4[,1]
  len = length(vec)
  if (len < 182) {
    vec = c(vec,rep(NA,182-len))
  }

  discharge.data[, x] <- vec
}
</code>```

This should work. If the data.frame you want to append to has some more conditions that I don't understand, then you should probably use merge..

Body:
I keep getting this error code "Error in [<-.data.frame(*tmp*, , x, value = c(16100, 14800, 13100,  :
  replacement has 163 rows, data has 182" and I'm not sure how to fix this. I know it has something to do with NAs but i've tried na.omit and couldn't get it to work. I've tried changing the number of rows in the dischange.data matrix but that doesn't work either. Please help!

library(waterData)

## List of start dates
start.dates <- c(
                 "2009-12-01", "2010-12-01", "2011-12-01", "2012-12-01",
                 "2013-12-01", "2014-12-01", "2015-12-01", "2016-12-01",
                 "2017-12-01", "2018-12-01")

## List of end dates
end.dates <- c(
               "2010-05-31", "2011-05-31", "2012-05-30", "2013-05-31",
               "2014-05-31", "2015-05-31", "2016-05-30", "2017-05-31",
               "2018-05-31", "2019-05-31")

## Bind start and end dates into a single dataframe
flow.dates <- as.data.frame(cbind(start.dates, end.dates))

## Empty dataframe for discharge data; nrow=no of days in each inverval,
#ncol=no invtervals
discharge.data <- as.data.frame(data.frame(matrix(0,
                                                  nrow = 182, ncol = 10)))

## Append data for all dates
for(x in 1:10){
  bin.1 <- importDVs(staid = "02198375", code = "00060", stat = "00003",
                     sdate = flow.dates[x, 1],
                     edate = flow.dates[x, 2])
  bin.2 <- cleanUp(bin.1, task = "fix", replace = 0.001)
  bin.3 <- fillMiss(bin.1, block = 2, pmiss = 5, model = "trend",
                    smooth = FALSE, log = "y")
  bin.4 <- bin.3[, c(2, 3)]
  colnames(bin.4) <- c(flow.dates[x, 3])
  discharge.data[, x] <- bin.4[, 1]
}

## Calculate season mean & convert from ft3 to m3
mean.discharge.ws <- sapply(discharge.data, mean)
met.shift.ws <- (mean.discharge.ws / 35.315)

## Create dataframe

met.winterspring.Year <- c( 2010, 2011, 2012, 2013, 2014,
                           2015, 2016, 2017, 2018, 2019)

df=data.frame(met.shift.ws, met.winterspring.Year)
my.formula = df$met.shift.ws ~ df$met.winterspring.Year

fit = lm(met.winterspring.Year ~  met.shift.ws ,data=df )
summary(fit)

library(ggplot2)
library(ggpmisc) # for dealing with stat equations
library (grid)

ggplot(df, aes(met.winterspring.Year, met.shift.ws)) +
  geom_line(group=1) +
  geom_smooth(method = "lm", se=FALSE) +
  stat_poly_eq(formula = my.formula,
               eq.with.lhs = "italic(hat(y))~`=`~",
               aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
               parse = TRUE)+
  theme_classic()+
  labs(x="", y=(expression(Discharge~(m^{3}~s^{-1}))))+
  theme_classic() +
  scale_x_continuous(breaks = breaks_width(2)) +
  annotate(geom = "text", x = 2017, y = 300, label = "Winter-Spring", hjust = "left")

Body:
I have no idea what water.data is or what half of the functions do, but I quickly downloaded the package, and if you add print(x) in your for loop where you append data for all dates, you'll immediately see that for x=7, there are 163 rows in bin.1, and not 182. I don't know what that means, but if its just a think where 1:182 is just a to hold the values, then you can just pad some NAs if the length of the vectors you are appending are too small. So maybe something like

discharge.data <- as.data.frame(data.frame(matrix(0,
                                                  nrow = 182, ncol = 10)))

## Append data for all dates
for(x in 1:10){
  bin.1 <- importDVs(staid = "02198375", code = "00060", stat = "00003",
                     sdate = flow.dates[x, 1],
                     edate = flow.dates[x, 2])
  bin.2 <- cleanUp(bin.1, task = "fix", replace = 0.001)
  bin.3 <- fillMiss(bin.1, block = 2, pmiss = 5, model = "trend",
                    smooth = FALSE, log = "y")
  bin.4 <- bin.3[, c(2, 3)]
  colnames(bin.4) <- c(flow.dates[x, 3])

  #pad some NAs if too short vector
  vec = bin.4[,1]
  len = length(vec)
  if (len < 182) {
    vec = c(vec,rep(NA,182-len))
  }

  discharge.data[, x] <- vec
}

This should work. If the data.frame you want to append to has some more conditions that I don't understand, then you should probably use merge..


问:
how to set property using jasmine createSpyObj method in angular
In my angular service I have a property myPropertyOne: Observable<string> and I want to mock the property using jasmine.createSpyObj method. so, I tried spying like below

```<code>  const myServiceSpy: jasmine.SpyObj<myService> = jasmine.createSpyObj('myService', ['myMethodOne'], ['myPropertyOne'])
</code>```

I want to set value for my spied property 'myPropertyOne'. Also, this value should be changed for different test spec against to be tested. Appreciate if someone can suggest on this.

Note: I tried checking other threads and not getting clear idea on how to set and get property value using createSpyObj.

答:
At last, I tried like below and it worked

```<code>  const mySubject: ReplaySubject<string> = new ReplaySubject<string>(1)

  const myServiceSpy: jasmine.SpyObj<myService> = jasmine.createSpyObj('myService', ['myMethodOne'], ['myPropertyOne': {mySubject}])
</code>```

with this, in my test spec, I set string in my subject like below.

```<code>describe('my component', () => {
    it('some test check', () => {
        mySubject.next('some value')
        fixture.detectChanges()
        // some assertion
    })
})
</code>```

Body:
In my angular service I have a property myPropertyOne: Observable<string> and I want to mock the property using jasmine.createSpyObj method. so, I tried spying like below

  const myServiceSpy: jasmine.SpyObj<myService> = jasmine.createSpyObj('myService', ['myMethodOne'], ['myPropertyOne'])

I want to set value for my spied property 'myPropertyOne'. Also, this value should be changed for different test spec against to be tested. Appreciate if someone can suggest on this.

Note: I tried checking other threads and not getting clear idea on how to set and get property value using createSpyObj.

Body:
At last, I tried like below and it worked

  const mySubject: ReplaySubject<string> = new ReplaySubject<string>(1)

  const myServiceSpy: jasmine.SpyObj<myService> = jasmine.createSpyObj('myService', ['myMethodOne'], ['myPropertyOne': {mySubject}])

with this, in my test spec, I set string in my subject like below.

describe('my component', () => {
    it('some test check', () => {
        mySubject.next('some value')
        fixture.detectChanges()
        // some assertion
    })
})


问:
Security Impact of using strncmp()?
I've been doing a little research on the security of strncmp and I understand it's not null terminated. But I've also seen how some people are saying it is "not a secure replacement for strcmp()." Could anyone explain this to me please? I've been looking for a while but really the only place i can find that says that is here on SO on a few questions. Maybe someone could link me a few resources for looking into this?
Thanks.</p>

答:
I think this thread might help you - Is there any safe strcmp?

In short, even though you can send in the size of the strings to be compared, strncmp will still read garbage values if the string is shorter than size 'n' and it is not null terminated.

Similar to your question - Why should you use strncpy instead of strcpy?

Title: Security Impact of using strncmp()?


问:
Google Play rejected app because of it's uploading users' Contact information
App removed from google play store due to the following reason:

APK HAS A PROMINENT DISCLOSURE BUT THE DISCLOSURE IS NOT ADEQUATE Your app is uploading users' Contact information to
  https://domen.com without an adequate disclosure.

Because of application is for international call app we are using a lot of permissions

```<code><uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
</code>```

The application does not upload information about the user's contact ("Address Book").

In a not google mentioned that the Contact data is sent to our host.

答:
I feel your pain; Google Play rejection is often arbitrary and getting to the bottom of it (with an actual human on the other end) is next to impossible. That said, Google Play support is considered off-topic here. This question will probably be closed soon enough.

That said, extra permissions are not the reason. What you probably have is a genuine case of an HTTP request with some information that originates in the contact list. As far as I can tell, Google's screening robot uses some kind of data path analysis internally. Obfuscating the data path (by using reflection and such) might get you off the hook.

One more data point: my app was once delisted over an old version in the beta channel. The beta version from a couple of years ago had a behavior that Google once tolerated but then didn't (a direct link to an APK). Once I've replaced the version in the beta channel, Play was happy again. See if you have something like that. The takedown notice I've got from them didn't make it clear.

Body:
App removed from google play store due to the following reason:

APK HAS A PROMINENT DISCLOSURE BUT THE DISCLOSURE IS NOT ADEQUATE Your app is uploading users' Contact information to
  https://domen.com without an adequate disclosure.

Because of application is for international call app we are using a lot of permissions

<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />

The application does not upload information about the user's contact ("Address Book").

In a not google mentioned that the Contact data is sent to our host.


问:
"Jupyter package is not installed" error message in Pycharm (using Windows). How do I fix this?
I downloaded Pycharm 2019.3 and I am using it with the most recent Anaconda distribution for Python 3.

The Jupyter package is installed - I can see it in the Project Interpreter's list of packages and I can run the notebook from the Windows command line.

When I try to run a cell (or all cells) within Pycharm, a pop up error message says "Jupyter package is not installed".

My problem is similar to this one but I am running directly on Windows. Pycharm jupyter notebook wsl: Jupyter package is not installed

How can I make Pycharm recognise the Jupyter package?

答:
I had a similar problem, for me it was an issue with mismatched interpreters.

The python interpreter on my toolbar (which is the same as settings -> project -> project interpreter) didn't match the one selected for the jupyter server (settings -> build,execution,deployment -> jupyter -> jupyter servers.


问:
How can I update value in object with node.js and sequelize
I would like to update values (missions.status and missions.success) in the object,
but I don't know how to approach it.

"missions": {
   "missions": [
      {
       "week": 1,
       "status": "",
       "mission": "do something",
       "success": ""
      }
    ]
 }```
</div>
</div>
</p>

<p>I tried to like this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//success.js

router.put('/:id/result', async (req, res, next) => {
  const status = req.body.missions.missions[0].status;
  const success = req.body.missions.missions[0].success;
  try {
    const result = await models.User.findOne({
      attribute: ['missions'],
      where: {
        id: req.params.id,
      },
    });

    const data = {
      result: result,
    };
    let originalData = data.result.dataValues.missions.missions[0];
    let weekdata = { status: status, success: success };
    let resultData = Object.assign(originalData, weekdata);

    res.send({
      data: resultData,
      message: 'good status changed',
    });
  } catch (error) {
    console.log(error);
    res.sendStatus(400);
  }
});</code>```

It is req.body and response, looks like it works, but doesn't update in databases. I don't know how to save that.

//req.body
{
"missions": {
    "missions":[
  {
   "status": "no",
   "success":"success"
  }
   ]
    }
  }

// res.send
{
  "data": {
      "week": 1,
      "status": "no",
      "mission": "do something",
      "success": "success"
  },
  "message": "good status changed"
}```

答:
You didn't call update for your model so that's why you'll get no changes in a DB.
Try this:

```<code>await models.User.update(weekdata, {
      where: {
        id: req.params.id,
      },
    });
</code>```

Body:
I would like to update values (missions.status and missions.success) in the object,
but I don't know how to approach it.

"missions": {
   "missions": [
      {
       "week": 1,
       "status": "",
       "mission": "do something",
       "success": ""
      }
    ]
 }

I tried to like this.

//success.js

router.put('/:id/result', async (req, res, next) => {
  const status = req.body.missions.missions[0].status;
  const success = req.body.missions.missions[0].success;
  try {
    const result = await models.User.findOne({
      attribute: ['missions'],
      where: {
        id: req.params.id,
      },
    });

    const data = {
      result: result,
    };
    let originalData = data.result.dataValues.missions.missions[0];
    let weekdata = { status: status, success: success };
    let resultData = Object.assign(originalData, weekdata);

    res.send({
      data: resultData,
      message: 'good status changed',
    });
  } catch (error) {
    console.log(error);
    res.sendStatus(400);
  }
});

It is req.body and response, looks like it works, but doesn't update in databases. I don't know how to save that.

//req.body
{
"missions": {
    "missions":[
  {
   "status": "no",
   "success":"success"
  }
   ]
    }
  }

// res.send
{
  "data": {
      "week": 1,
      "status": "no",
      "mission": "do something",
      "success": "success"
  },
  "message": "good status changed"
}

Body:
You didn't call update for your model so that's why you'll get no changes in a DB.
Try this:

await models.User.update(weekdata, {
      where: {
        id: req.params.id,
      },
    });


问:
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null build failed
I have updated to the latest flutter update. When I want to start the project, it returns an error. The project depends on several repositories and I don't know if that is why. I have tried multiple solutions but they do not solve the error. Hope someone can help me. thanks.

Compiler message:

```<code>/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/mvvm-0.1.7/lib/view_context_helpers/logical.dart:151:25: Error: The function expression type 'Widget Function(BuildContext, Null, Widget) Function(TValue)' isn't of expected type 'Widget Function(BuildContext, TValue, Widget) Function(TValue)'.

 - 'Widget' is from 'package:flutter/src/widgets/framework.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/framework.dart').
 - 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/framework.dart').
Change the type of the function expression or the context in which it is used.
              selector: (TValue value) =>
                        ^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

* Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 780

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

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

* Get more help at https://help.gradle.org

BU�LD FAILED in 31s
Finished with error: Gradle task assembleDebug failed with exit code 1
</code>```

答:
Solution 1
1.Ensure compatible engines and frameworks.
2.Update flutter or install flutter to a newer version,

still issue persists,  Roll back flutter or engine to an older version.

Best solution to fix by time saving but not preferable, please follow

Solution 2
1. Download latest version flutter sdk and setup.
2. Fix it by creating a new project and copying the code from the old one. ```

For more details refer the below link

http://codekhichdi.com/flutter/target-kernel_snapshot-failed-exception-errors-during-snapshot-creation-null

Body:
I have updated to the latest flutter update. When I want to start the project, it returns an error. The project depends on several repositories and I don't know if that is why. I have tried multiple solutions but they do not solve the error. Hope someone can help me. thanks.

Compiler message:

/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/mvvm-0.1.7/lib/view_context_helpers/logical.dart:151:25: Error: The function expression type 'Widget Function(BuildContext, Null, Widget) Function(TValue)' isn't of expected type 'Widget Function(BuildContext, TValue, Widget) Function(TValue)'.

 - 'Widget' is from 'package:flutter/src/widgets/framework.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/framework.dart').
 - 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/framework.dart').
Change the type of the function expression or the context in which it is used.
              selector: (TValue value) =>
                        ^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

* Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 780

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

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

* Get more help at https://help.gradle.org

BU�LD FAILED in 31s
Finished with error: Gradle task assembleDebug failed with exit code 1

Body:
Solution 1
1.Ensure compatible engines and frameworks.
2.Update flutter or install flutter to a newer version,

still issue persists,  Roll back flutter or engine to an older version.

Best solution to fix by time saving but not preferable, please follow

Solution 2
1. Download latest version flutter sdk and setup.
2. Fix it by creating a new project and copying the code from the old one.

For more details refer the below link

http://codekhichdi.com/flutter/target-kernel_snapshot-failed-exception-errors-during-snapshot-creation-null


问:
Exclude URLs from Django REST Swagger
I have a few URLs that I want to exclude from my REST API documentation. I'm using Django REST Swagger and the only documentation I can find (https://github.com/marcgibbons/django-rest-swagger) doesn't really tell me much. There is the "exclude_namespaces" part of SWAGGER_SETTINGS in settings.py, but there is no real explanation or example of how to use this.

Simply put, I want to exclude any URLs from the docs that start with the following:

```<code>/api/jobs/status/
/api/jobs/parameters/
</code>```

How could I go about doing this?

Thanks in advance for any help offered :P

答:
A more flexible solution would be:

```<code>from django.contrib import admin
from django.urls import include, path
from rest_framework_swagger.views import get_swagger_view
urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('user.urls', namespace="user")),
    path('locations/', include('location.urls')),
    path('departments/', include('department.urls', namespace="department")),
    path('my_secret_api/', include('secret.urls', namespace="secret_api")),
]

to_exclude = ['secret_api',] # some more namespaces here
swagger_urls = [item for item in urlpatterns if hasattr(item,"namespace") and item.namespace not in to_exclude]
schema_view = get_swagger_view(title='Highky', patterns=swagger_urls)
urlpatterns += [
        path('api/docs/', schema_view),
]
</code>```

urlpatterns will have all five paths, but swagger_urls will have four paths excluding secret_api.

All of your URLs and includes will continue to work as they were, except we are now passing our modified urlpatterns that we want to show in the Swagger docs. The checks will also cover the include where you don't specify a namespace (like in our case, where the namespace is not defined in the location).

ContentLicense: CC BY-SA 3.0

Title: Exclude URLs from Django REST Swagger

Body:
I have a few URLs that I want to exclude from my REST API documentation. I'm using Django REST Swagger and the only documentation I can find (https://github.com/marcgibbons/django-rest-swagger) doesn't really tell me much. There is the "exclude_namespaces" part of SWAGGER_SETTINGS in settings.py, but there is no real explanation or example of how to use this.

Simply put, I want to exclude any URLs from the docs that start with the following:

/api/jobs/status/
/api/jobs/parameters/

How could I go about doing this?

Thanks in advance for any help offered :P

Body:
A more flexible solution would be:

from django.contrib import admin
from django.urls import include, path
from rest_framework_swagger.views import get_swagger_view
urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('user.urls', namespace="user")),
    path('locations/', include('location.urls')),
    path('departments/', include('department.urls', namespace="department")),
    path('my_secret_api/', include('secret.urls', namespace="secret_api")),
]

to_exclude = ['secret_api',] # some more namespaces here
swagger_urls = [item for item in urlpatterns if hasattr(item,"namespace") and item.namespace not in to_exclude]
schema_view = get_swagger_view(title='Highky', patterns=swagger_urls)
urlpatterns += [
        path('api/docs/', schema_view),
]

urlpatterns will have all five paths, but swagger_urls will have four paths excluding secret_api.

All of your URLs and includes will continue to work as they were, except we are now passing our modified urlpatterns that we want to show in the Swagger docs. The checks will also cover the include where you don't specify a namespace (like in our case, where the namespace is not defined in the location).


问:
How to bind the useState() in React to dynamically generated
 elements?
I am trying to create a widget in React which has a drop down in each block. I need to show a drop down on the click of a button in each respective list. But what is happening is, when i click the button all the drop down are showing up (of all the dynamically repeated elements).

```<code>class App extends Component {
  render() {
    return (
      <div className="wrapper">
        <div className="widget">
          <h2>whats happeing</h2>
          <Block data={mock} /> //sub component which has the dropdown
        </div>
      </div>
    );
  }
}

const Block = props => {
  let blocks = [];
  let [showDropdown, setShowDropdown] = useState(false); //currently i am trying to get this done with useState()

  if (props.data.length) {
    blocks = props.data.map(function(item) {
      return (
        <div key={item.id} className="block">
          <span
            className="dropdown-btn"
            onClick={() => setShowDropdown(!showDropdown)}
          >
            ▼
          </span>
          <div className="left-col">
            <p>{item.category}</p>
            <h3>
              <a href="#">{item.title}</a>
            </h3>
          </div>
          {showDropdown && <Dropdown />}
        </div>
      );
    });
  }
  return <div>{blocks}</div>;
};
</code>```

This is the sandbox link to the code. Could you please let me know how to handle this in React ?
https://codesandbox.io/s/widget-with-drodown-kjovc

答:
If you want the dropdown will be controlled seperatly, then you need to keep in state only the id's you want to render a dropdown to. So, a way for doing it will be:</p>

```<code>import React, { useState } from "react";
import Dropdown from "./dropdown";

const Block = props => {
  let blocks = [];
  let [showDropdown, setShowDropdown] = useState([]);

  const clickHandle = item => {
    let idIndex = showDropdown.indexOf(item);
    if (idIndex !== -1) {
      let newArray = [...showDropdown];
      newArray.splice(idIndex, 1);
      setShowDropdown(newArray);
    } else setShowDropdown([...showDropdown, item]);
  };

  if (props.data.length) {
    blocks = props.data.map(function(item) {
      return (
        <div key={item.id} className="block">
          <span className="dropdown-btn" onClick={() => clickHandle(item.id)}>
            ▼
          </span>
          <div className="left-col">
            <p>{item.category}</p>
            <h3>
              <a href="#">{item.title}</a>
            </h3>
          </div>
          {showDropdown.includes(item.id) && <Dropdown />}
        </div>
      );
    });
  }
  console.log(showDropdown);
  return <div>{blocks}</div>;
};
export default Block;
</code>```

Title: How to bind the useState() in React to dynamically generated <div> elements?

Body:
I am trying to create a widget in React which has a drop down in each block. I need to show a drop down on the click of a button in each respective list. But what is happening is, when i click the button all the drop down are showing up (of all the dynamically repeated elements).

class App extends Component {
  render() {
    return (

whats happeing

          <Block data={mock} /> //sub component which has the dropdown

    );
  }
}

const Block = props => {
  let blocks = [];
  let [showDropdown, setShowDropdown] = useState(false); //currently i am trying to get this done with useState()

  if (props.data.length) {
    blocks = props.data.map(function(item) {
      return (

           setShowDropdown(!showDropdown)}
          >
            ▼

{item.category}

              {item.title}

          {showDropdown && <Dropdown />}

      );
    });
  }
  return
{blocks}
;
};

This is the sandbox link to the code. Could you please let me know how to handle this in React ?
https://codesandbox.io/s/widget-with-drodown-kjovc

Body:
If you want the dropdown will be controlled seperatly, then you need to keep in state only the id's you want to render a dropdown to. So, a way for doing it will be:

import React, { useState } from "react";
import Dropdown from "./dropdown";

const Block = props => {
  let blocks = [];
  let [showDropdown, setShowDropdown] = useState([]);

  const clickHandle = item => {
    let idIndex = showDropdown.indexOf(item);
    if (idIndex !== -1) {
      let newArray = [...showDropdown];
      newArray.splice(idIndex, 1);
      setShowDropdown(newArray);
    } else setShowDropdown([...showDropdown, item]);
  };

  if (props.data.length) {
    blocks = props.data.map(function(item) {
      return (
        <div key={item.id} className="block">
          <span className="dropdown-btn" onClick={() => clickHandle(item.id)}>
            ▼
          </span>
          <div className="left-col">
            <p>{item.category}</p>
            <h3>
              <a href="#">{item.title}</a>
            </h3>
          </div>
          {showDropdown.includes(item.id) && <Dropdown />}
        </div>
      );
    });
  }
  console.log(showDropdown);
  return <div>{blocks}</div>;
};
export default Block;


问:
SCP copy from another host if file not found in one host
I know the name of the file and the host machines on which it could be. I also know that only one of the hosts has that file. So based on this reply I created the following script.

```<code>if scp "username@host1:/tmp/$1*" ~/$1;
then echo "done";
else scp "username@host2:/tmp/$1*" ~/$1;
fi
</code>```

I have put the above code in a file name file_copy.sh and then invoke the file from the terminal as follows $ ./file_copy.sh filename, that is where the $1 argument comes from. I am not sure of the entire file name, but only the prefix in this case, so there is a wild card of * but that part can be ignored for this question.

In the above case, I know there are two hosts, and one of them will have my file, so I just do an if else switch, but it feels way too hacky and not elegant enough.

Question:

Is there a better solution to if then else above to doing the SCP?

In both the if and else branch I use SCP, which requires me to type the password twice. On both the hosts, the user name and password are the same. Is there any way, in the shell file, that I do not have to enter the password again on the terminal.

The above case has two hosts, but if I have n hosts and a similar situation. That is one file, in one host, but not sure which one, but all hosts have the same user name and password credentials. How the above script can be generalized. Is there a way to make a switch case in shell script.

Thanks

答:
You could use rsync instead. rsync -r -z -c will return better error codes.

You could use sshpass to automatically enter a password

Then you could..

```<code>if sshpass PA55WORD rsync -r -z -c "username@host1:/tmp/$1*" ~/$1;
then echo "done";
else sshpass PASSWORD rsync -r -z -c "username@host2:/tmp/$1*" ~/$1;
fi
</code>```

I would personally recommend against typing a password in plain text. ssh private keys are useful for this exact problem. You could use sshpass -f FILE_PATH or some other clever encryption method of getting the password in, but sshpass is your friend here.

For multiple hosts, all with the same username and password:

```<code>HOSTS=( "host1" "host2" "host3" )

for H in ${HOSTS[@]}
do
  sshpass -p PASSWORD rsync -r -z -c "username@${H}:/tmp/$1*" ~/$1 && break
done
</code>```

For multiple hosts, all with different usernames and passwords

```<code>HOSTS=( "host1" "host2" "host3" )
USERS=( "user1" "user2" "user3" )
PASSS=( "pass1" "pass2" "pass3" )

for i in ${!HOSTS[@]}
do
  sshpass -p ${PASSS[$i]} rsync -r -z -c "${USERS[$i]}@${HOSTS[$i]}:/tmp/$1*" ~/$1 && break
done
</code>```

Body:
I know the name of the file and the host machines on which it could be. I also know that only one of the hosts has that file. So based on this reply I created the following script.

if scp "username@host1:/tmp/$1*" ~/$1;
then echo "done";
else scp "username@host2:/tmp/$1*" ~/$1;
fi

I have put the above code in a file name file_copy.sh and then invoke the file from the terminal as follows $ ./file_copy.sh filename, that is where the $1 argument comes from. I am not sure of the entire file name, but only the prefix in this case, so there is a wild card of * but that part can be ignored for this question.

In the above case, I know there are two hosts, and one of them will have my file, so I just do an if else switch, but it feels way too hacky and not elegant enough.

Question:

Is there a better solution to if then else above to doing the SCP?

In both the if and else branch I use SCP, which requires me to type the password twice. On both the hosts, the user name and password are the same. Is there any way, in the shell file, that I do not have to enter the password again on the terminal.

The above case has two hosts, but if I have n hosts and a similar situation. That is one file, in one host, but not sure which one, but all hosts have the same user name and password credentials. How the above script can be generalized. Is there a way to make a switch case in shell script.

Thanks

Body:
You could use rsync instead. rsync -r -z -c will return better error codes.

You could use sshpass to automatically enter a password

Then you could..

if sshpass PA55WORD rsync -r -z -c "username@host1:/tmp/$1*" ~/$1;
then echo "done";
else sshpass PASSWORD rsync -r -z -c "username@host2:/tmp/$1*" ~/$1;
fi

I would personally recommend against typing a password in plain text. ssh private keys are useful for this exact problem. You could use sshpass -f FILE_PATH or some other clever encryption method of getting the password in, but sshpass is your friend here.

For multiple hosts, all with the same username and password:

HOSTS=( "host1" "host2" "host3" )

for H in ${HOSTS[@]}
do
  sshpass -p PASSWORD rsync -r -z -c "username@${H}:/tmp/$1*" ~/$1 && break
done

For multiple hosts, all with different usernames and passwords

HOSTS=( "host1" "host2" "host3" )
USERS=( "user1" "user2" "user3" )
PASSS=( "pass1" "pass2" "pass3" )

for i in ${!HOSTS[@]}
do
  sshpass -p ${PASSS[$i]} rsync -r -z -c "${USERS[$i]}@${HOSTS[$i]}:/tmp/$1*" ~/$1 && break
done


问:
how can I overcome "ValueError: Shapes (None, 1) and (None, 7) are incompatible"
I am new to Keras and CNN. I am working on an assignment to build a CNN for predicting face emotions. I built the model as per the assignment but while compiling the model I get "ValueError: Shapes (None, 1) and (None, 7) are incompatible". Can someone help me how to resolve this?

Pasting my code below for reference:

'''

```<code>model = Sequential()

model.add(Conv2D(filters = 64, kernel_size = 5,input_shape = (48,48,1)))
model.add(Conv2D(filters=64, kernel_size=5,strides=(1, 1), padding='valid'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2),strides=1, padding='valid'))
model.add(Activation('relu'))

model.add(Conv2D(filters = 128, kernel_size = 5))
model.add(Conv2D(filters = 128, kernel_size=5))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Activation('relu'))

model.add(Conv2D(filters = 256, kernel_size = 5))
model.add(Conv2D(filters = 256, kernel_size=5))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Activation('relu'))

model.add(Flatten())
model.add(Dense(128))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(7,activation='softmax'))
</code>```

'''
'Then tried to compile'
'''

```<code>model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(input_array, output_array, batch_size = 64, epochs= 20, validation_split=0.10,)
</code>```

'''
'This gives the error'
'ValueError: Shapes (None, 1) and (None, 7) are incompatible'
'I am using google colab for this'

答:
If you use one-hot-encoded for the label like [0, 0, 0, 0, 0, 0, 1] you need to use categorical_crossentropy
but if you use sparse label like [1, 2, 3, 4, 5, 6, 7] you need to use sparse_categorical_crossentropy.

Body:
I am new to Keras and CNN. I am working on an assignment to build a CNN for predicting face emotions. I built the model as per the assignment but while compiling the model I get "ValueError: Shapes (None, 1) and (None, 7) are incompatible". Can someone help me how to resolve this?

Pasting my code below for reference:

'''

model = Sequential()

model.add(Conv2D(filters = 64, kernel_size = 5,input_shape = (48,48,1)))
model.add(Conv2D(filters=64, kernel_size=5,strides=(1, 1), padding='valid'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2),strides=1, padding='valid'))
model.add(Activation('relu'))

model.add(Conv2D(filters = 128, kernel_size = 5))
model.add(Conv2D(filters = 128, kernel_size=5))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Activation('relu'))

model.add(Conv2D(filters = 256, kernel_size = 5))
model.add(Conv2D(filters = 256, kernel_size=5))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Activation('relu'))

model.add(Flatten())
model.add(Dense(128))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(7,activation='softmax'))

'''
'Then tried to compile'
'''

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(input_array, output_array, batch_size = 64, epochs= 20, validation_split=0.10,)

'''
'This gives the error'
'ValueError: Shapes (None, 1) and (None, 7) are incompatible'
'I am using google colab for this'


问:
CSS animation keyframe percentage issue
I have posted before about CSS Keyframe animation and tried a different way of using delays.

I had css continous slider of 5 divs which worked fine. However I needed to remove two of the divs so there is only three.

.wrapper{
    position: relative;
    height: 330px;
    display: grid;
    overflow: hidden;
    width:600px;
    background:#f1f1f1;
}

.slide {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  animation: slider 9s cubic-bezier(0.5, 1, 0.5, 1) infinite;
  color:#fff;
  font-size:30px;
  text-align:center;
  padding-top:25%;
}

.slide:first-of-type {
  animation-delay: -9s;
  background:red;
}
.slide:nth-of-type(2) {
  animation-delay: -6s;
  background:blue;
}
.slide:last-of-type {
  animation-delay: -3s;
  background:black;
}

@keyframes slider {
  0% {
    transform: translateX(0);
    opacity: 1;
  }
  16% {
    transform: translateX(0);
    opacity: 1;
  }
  20% {
    transform: translateX(100%);
    opacity: 1;
  }
  75% {
    transform: translateX(100%);
    opacity: 0;
  }
  76% {
    transform: translateX(-100%);
    opacity: 0;
  }
  96% {
    transform: translateX(-100%);
    opacity: 1;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="slide">
    1
  </div>
    <div class="slide">
    2
  </div>
    <div class="slide">
    3
  </div>
</div></code>```

Link to my on going codepen.

So I have tried changing the animation to 9s, 3 seconds per div.
I have changed the delay on the divs to -9s, -6s, -3s respectively but I have a pause in between each div sliding in.

I have tried to alter the percentages which is where I believe I am going wrong.

I am wondering if anyone can give me some help on the percentages I need to change or if there is a formula to use so I can switch up the amount of divs in the future if need be?

答:
The keyframe percentages relate to your animation duration. For example: with a 10 second animation, 10% is the 1 second mark, 50% the 5 second mark, and 100% the 10 second mark.

If your entire animation is 9 seconds long and you have 3 slides that all start with an offset of 3 seconds, then you'll want to make sure that your slides do their thing in the first 33.33% (3 seconds) of the key-frame animation and stay hidden for the remaining 66.66% (6 seconds).

Now in your case the slide transitions aren't instant, so you'll have to go slightly beyond 33.33% to ensure that your animations overlap nicely without a gap. The delay you were seeing are these gaps.

So with that in mind you can simplify them like so:

```<code>@keyframes slider {
  /* Start left off screen */
  0% {
    transform: translateX(-100%);
  }
  /* Move to visible position within 8% of 9 seconds (less than a second). */
  8% {
    transform: translateX(0);
  }
  /* Stay until at least 3 second mark (33% of 9s). */
  33.33% {
    transform: translateX(0);
  }
  /* Move offscreen to the right while
     the next slide is moving in.
     Same duration as slide-in (8%), but starting at 33.33%,
     so 33.33% + 8% = 41.33%.
  */
  41.33% {
    transform: translateX(100%);
  }
  /* Stay there until the end. */
  100% {
    transform: translateX(100%);
  }
}
</code>```

Here a snippet:

.wrapper{
    position: relative;
    height: 330px;
    display: block;
    overflow: hidden;
    width:600px;
    background:#f1f1f1;
}

.slide {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  animation: slider 9s cubic-bezier(0.5, 1, 0.5, 1) infinite;
  color:#fff;
  font-size:30px;
  text-align:center;
  padding-top:25%;
}

.slide:first-of-type {
  animation-delay: -9s;
  background:red;
}
.slide:nth-of-type(2) {
  animation-delay: -6s;
  background:blue;
}
.slide:last-of-type {
  animation-delay: -3s;
  background:black;
}

.wrapper{
position: relative;
height: 330px;
display: block;
overflow: hidden;
width:600px;
background:#f1f1f1;
}

.slide {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  animation: slider 9s cubic-bezier(0.5, 1, 0.5, 1) infinite;
  color:#fff;
  font-size:30px;
  text-align:center;
  padding-top:25%;
}

.slide:first-of-type {
  animation-delay: -9s;
  background:red;
}
.slide:nth-of-type(2) {
  animation-delay: -6s;
  background:blue;
}
.slide:last-of-type {
  animation-delay: -3s;
  background:black;
}

@keyframes slider {
  /* Start left off screen */
  0% {
    transform: translateX(-100%);
  }
  /* Move to visible position within 8% of 9 seconds (less than a second). */
  8% {
    transform: translateX(0);
  }
  /* Stay until at least 3 second mark (33% of 9s). */
  33.33% {
    transform: translateX(0);
  }
  /* Move offscreen to the right while
     the next slide is moving in.
     Same duration as slide-in (8%), but starting at 33.33%,
     so 33.33% + 8% = 41.33%.
  */
  41.33% {
    transform: translateX(100%);
  }
  /* Stay there until the end. */
  100% {
    transform: translateX(100%);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="slide">
    1
  </div>
    <div class="slide">
    2
  </div>
    <div class="slide">
    3
  </div>
</div></code>```

I do not think that you need the opacity changes, so I removed them.

You can, of course, change the percentages to increase/decrease the pause and speed of animation... just remember to make sure that the keyframes that show the slide have the same duration as the keyframes that hide it (in the example above 8%).

To add or remove slides in the future you can simply recalculate the percentages for that number of slides. So if you add 1 slide for a total of 4 you can work with 25% instead of 33.33%.

Title: CSS animation keyframe percentage issue

Body:
I have posted before about CSS Keyframe animation and tried a different way of using delays.

I had css continous slider of 5 divs which worked fine. However I needed to remove two of the divs so there is only three.

.wrapper{
    position: relative;
    height: 330px;
    display: grid;
    overflow: hidden;
    width:600px;
    background:#f1f1f1;
}

.slide {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  animation: slider 9s cubic-bezier(0.5, 1, 0.5, 1) infinite;
  color:#fff;
  font-size:30px;
  text-align:center;
  padding-top:25%;
}

.slide:first-of-type {
  animation-delay: -9s;
  background:red;
}
.slide:nth-of-type(2) {
  animation-delay: -6s;
  background:blue;
}
.slide:last-of-type {
  animation-delay: -3s;
  background:black;
}

@keyframes slider {
  0% {
    transform: translateX(0);
    opacity: 1;
  }
  16% {
    transform: translateX(0);
    opacity: 1;
  }
  20% {
    transform: translateX(100%);
    opacity: 1;
  }
  75% {
    transform: translateX(100%);
    opacity: 0;
  }
  76% {
    transform: translateX(-100%);
    opacity: 0;
  }
  96% {
    transform: translateX(-100%);
    opacity: 1;
  }
}

    1

    2

    3

Link to my on going codepen.

So I have tried changing the animation to 9s, 3 seconds per div.
I have changed the delay on the divs to -9s, -6s, -3s respectively but I have a pause in between each div sliding in.

I have tried to alter the percentages which is where I believe I am going wrong.

I am wondering if anyone can give me some help on the percentages I need to change or if there is a formula to use so I can switch up the amount of divs in the future if need be?

Body:
The keyframe percentages relate to your animation duration. For example: with a 10 second animation, 10% is the 1 second mark, 50% the 5 second mark, and 100% the 10 second mark.

If your entire animation is 9 seconds long and you have 3 slides that all start with an offset of 3 seconds, then you'll want to make sure that your slides do their thing in the first 33.33% (3 seconds) of the key-frame animation and stay hidden for the remaining 66.66% (6 seconds).

Now in your case the slide transitions aren't instant, so you'll have to go slightly beyond 33.33% to ensure that your animations overlap nicely without a gap. The delay you were seeing are these gaps.

So with that in mind you can simplify them like so:

@keyframes slider {
  /* Start left off screen */
  0% {
    transform: translateX(-100%);
  }
  /* Move to visible position within 8% of 9 seconds (less than a second). */
  8% {
    transform: translateX(0);
  }
  /* Stay until at least 3 second mark (33% of 9s). */
  33.33% {
    transform: translateX(0);
  }
  /* Move offscreen to the right while
     the next slide is moving in.
     Same duration as slide-in (8%), but starting at 33.33%,
     so 33.33% + 8% = 41.33%.
  */
  41.33% {
    transform: translateX(100%);
  }
  /* Stay there until the end. */
  100% {
    transform: translateX(100%);
  }
}

Here a snippet:

.wrapper{
    position: relative;
    height: 330px;
    display: block;
    overflow: hidden;
    width:600px;
    background:#f1f1f1;
}

.slide {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  animation: slider 9s cubic-bezier(0.5, 1, 0.5, 1) infinite;
  color:#fff;
  font-size:30px;
  text-align:center;
  padding-top:25%;
}

.slide:first-of-type {
  animation-delay: -9s;
  background:red;
}
.slide:nth-of-type(2) {
  animation-delay: -6s;
  background:blue;
}
.slide:last-of-type {
  animation-delay: -3s;
  background:black;
}

.wrapper{
position: relative;
height: 330px;
display: block;
overflow: hidden;
width:600px;
background:#f1f1f1;
}

.slide {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  animation: slider 9s cubic-bezier(0.5, 1, 0.5, 1) infinite;
  color:#fff;
  font-size:30px;
  text-align:center;
  padding-top:25%;
}

.slide:first-of-type {
  animation-delay: -9s;
  background:red;
}
.slide:nth-of-type(2) {
  animation-delay: -6s;
  background:blue;
}
.slide:last-of-type {
  animation-delay: -3s;
  background:black;
}

@keyframes slider {
  /* Start left off screen */
  0% {
    transform: translateX(-100%);
  }
  /* Move to visible position within 8% of 9 seconds (less than a second). */
  8% {
    transform: translateX(0);
  }
  /* Stay until at least 3 second mark (33% of 9s). */
  33.33% {
    transform: translateX(0);
  }
  /* Move offscreen to the right while
     the next slide is moving in.
     Same duration as slide-in (8%), but starting at 33.33%,
     so 33.33% + 8% = 41.33%.
  */
  41.33% {
    transform: translateX(100%);
  }
  /* Stay there until the end. */
  100% {
    transform: translateX(100%);
  }
}

<div class="wrapper">
  <div class="slide">
    1
  </div>
    <div class="slide">
    2
  </div>
    <div class="slide">
    3
  </div>
</div>

I do not think that you need the opacity changes, so I removed them.

You can, of course, change the percentages to increase/decrease the pause and speed of animation... just remember to make sure that the keyframes that show the slide have the same duration as the keyframes that hide it (in the example above 8%).

To add or remove slides in the future you can simply recalculate the percentages for that number of slides. So if you add 1 slide for a total of 4 you can work with 25% instead of 33.33%.


问:
Problem importing modul OpenCV in Anaconda
I am a beginner in terms of using python. Currently, I got python 3.7 and I am using anaconda as IDE. For my project, I need to detect the location and brightness of points/dots in an external imported picture. I figure I could use the modul OpenCV. Unfortunately, I am stuck right now with the problem to import the module cv2. I already successfully installed the package using

```<code>python -m pip install OpenCV-python
</code>```

on command prompt. OpenCV  Version which was installed is 4.2.0.34. While compiling the test script of OpenCV on Spyder

```<code>import cv2
print(cv2.__version__)
</code>```

I got this message

```<code>"ImportError : DLL load failed : The Modul was not found."
</code>```

Can somebody let me know please how to fix this problem? Is somehow the version of OpenCV I got not compatible with the Python version? I already watched and followed many tutorial videos on Youtube, but I couldn't find the solution. I tried to copy the cv2.pyd to the site-packages folder in

```<code>C:/user/Anaconda3/Lib/site-packages directory
</code>```

still it didn't fix the problem...

I would appreciate any answers and help I could get here. Thank you!

答:
Try conda install opencv
or conda install -c menpo opencv

Body:
I am a beginner in terms of using python. Currently, I got python 3.7 and I am using anaconda as IDE. For my project, I need to detect the location and brightness of points/dots in an external imported picture. I figure I could use the modul OpenCV. Unfortunately, I am stuck right now with the problem to import the module cv2. I already successfully installed the package using

python -m pip install OpenCV-python

on command prompt. OpenCV  Version which was installed is 4.2.0.34. While compiling the test script of OpenCV on Spyder

import cv2
print(cv2.__version__)

I got this message

"ImportError : DLL load failed : The Modul was not found."

Can somebody let me know please how to fix this problem? Is somehow the version of OpenCV I got not compatible with the Python version? I already watched and followed many tutorial videos on Youtube, but I couldn't find the solution. I tried to copy the cv2.pyd to the site-packages folder in

C:/user/Anaconda3/Lib/site-packages directory

still it didn't fix the problem...

I would appreciate any answers and help I could get here. Thank you!


问:
How to Translate "10:10" to epoch format
I am parsing a .json and plotting it using qt custom plot but for the x axis I need to translate "10:10" to secSinceEpoch, does anyone know the easiest way about going about this? I also have the date in ISODate format(2020-05-26) so I need to basically do the "date: 2020-05-26" + "minute: 10:10" to get the correct x axis value for that point correct? I am just stuck on figuring out how to get the epoch time of "10:10"

For some reason when i output the year after translating 2020-05-26 it says 1950, any idea why that is too?

Here is my current code

```<code>            time.push_back(chartData[i]["date"].asString());
            minute.push_back(chartData[i]["minute"].asString());
            timeInEpoch.push_back(QDateTime::fromString(time[i].c_str(), Qt::ISODate).toSecsSinceEpoch() + QDateTime::fromString(minute[i].c_str(), "hh:mm").toSecsSinceEpoch());
</code>```

Edit: Full Code

```<code>    //Retrieves json format of data
    Json::Value chartData = IEX::stocks::chartRange(symbolSearchedStd, "5dm");

    //Stores x and y values
    QVector<double> value, timeInEpoch;
    QVector<string>time, minute;
    setupLineChart("yyyy, MMM d", 8);

    int  n = chartData.size();

    //Finds max and min for range
    float maxAvg = chartData[0]["average"].asDouble();
    float minAvg = chartData[0]["average"].asDouble();

    //Reads in data from json(historical data 1 day delayed)
    for(int i = 0 ; i < n; i++)
    {
            value.push_back(chartData[i]["average"].asDouble());
            time.push_back(chartData[i]["date"].asString());
            minute.push_back(chartData[i]["minute"].asString());
            timeInEpoch.push_back(QDateTime::fromString(time[i].c_str(), Qt::ISODate).toSecsSinceEpoch() + QDateTime::fromString(minute[i].c_str(), "hh:mm").toSecsSinceEpoch());

            if((value[i] == 0) && (i != n - 1))
            {
                value[i] = value[i-1];
            }

            if(value[i] > maxAvg)
            {
                maxAvg = value[i];
            }

            else if(value[i] < minAvg)
            {
                minAvg = value[i];
            }
    }

    stockData(value[n-1], value[n-2]);

    //Assigns data to graph
    ui->stockGraph->graph(0)->setData(timeInEpoch, value);
</code>```

答:
I think you can parse date and time separately:</p>

```<code>const char * date = "2020-05-26";
const char * time = "10:10";

auto d = QDate::fromString(date, Qt::ISODate);
auto t = QTime::fromString(time, "hh:mm");

auto dt = QDateTime(d, t);

qDebug() << "d = " << d << " t = " << t << " dt = " << dt << " secs = " << dt.toSecsSinceEpoch();

//d =  QDate("2020-05-26")  t =  QTime("10:10:00.000")  dt =  QDateTime(2020-05-26 10:10:00.000 +07 Qt::LocalTime)  secs =  1590462600
</code>```

Body:
I am parsing a .json and plotting it using qt custom plot but for the x axis I need to translate "10:10" to secSinceEpoch, does anyone know the easiest way about going about this? I also have the date in ISODate format(2020-05-26) so I need to basically do the "date: 2020-05-26" + "minute: 10:10" to get the correct x axis value for that point correct? I am just stuck on figuring out how to get the epoch time of "10:10"

For some reason when i output the year after translating 2020-05-26 it says 1950, any idea why that is too?

Here is my current code

            time.push_back(chartData[i]["date"].asString());
            minute.push_back(chartData[i]["minute"].asString());
            timeInEpoch.push_back(QDateTime::fromString(time[i].c_str(), Qt::ISODate).toSecsSinceEpoch() + QDateTime::fromString(minute[i].c_str(), "hh:mm").toSecsSinceEpoch());

Edit: Full Code

    //Retrieves json format of data
    Json::Value chartData = IEX::stocks::chartRange(symbolSearchedStd, "5dm");

    //Stores x and y values
    QVector<double> value, timeInEpoch;
    QVector<string>time, minute;
    setupLineChart("yyyy, MMM d", 8);

    int  n = chartData.size();

    //Finds max and min for range
    float maxAvg = chartData[0]["average"].asDouble();
    float minAvg = chartData[0]["average"].asDouble();

    //Reads in data from json(historical data 1 day delayed)
    for(int i = 0 ; i < n; i++)
    {
            value.push_back(chartData[i]["average"].asDouble());
            time.push_back(chartData[i]["date"].asString());
            minute.push_back(chartData[i]["minute"].asString());
            timeInEpoch.push_back(QDateTime::fromString(time[i].c_str(), Qt::ISODate).toSecsSinceEpoch() + QDateTime::fromString(minute[i].c_str(), "hh:mm").toSecsSinceEpoch());

            if((value[i] == 0) && (i != n - 1))
            {
                value[i] = value[i-1];
            }

            if(value[i] > maxAvg)
            {
                maxAvg = value[i];
            }

            else if(value[i] < minAvg)
            {
                minAvg = value[i];
            }
    }

    stockData(value[n-1], value[n-2]);

    //Assigns data to graph
    ui->stockGraph->graph(0)->setData(timeInEpoch, value);

Body:
I think you can parse date and time separately:

const char * date = "2020-05-26";
const char * time = "10:10";

auto d = QDate::fromString(date, Qt::ISODate);
auto t = QTime::fromString(time, "hh:mm");

auto dt = QDateTime(d, t);

qDebug() << "d = " << d << " t = " << t << " dt = " << dt << " secs = " << dt.toSecsSinceEpoch();

//d =  QDate("2020-05-26")  t =  QTime("10:10:00.000")  dt =  QDateTime(2020-05-26 10:10:00.000 +07 Qt::LocalTime)  secs =  1590462600


问:
Trying to create a pivot chart
For reasons that are too long to explain here I need to create a custom chart out of an existing pivot table (which already has another chart attached to it).

The number of columns in the displayed range changes depending on the slicer settings.

What happens is that if I manually delete the created chart, select the new region and recreate the chart, everything is fine.

If I do the same thing with VBA (recorded the steps) it works sometimes
(especially if I delete the chart manually before running the code) but most of the time it will create a different chart and then errors out.

Here is what happens:

I find the chart from the last run (it's always shape[3]):

```<code>Dim ch As Shape
Dim i As Integer

  For i = 1 To ActiveSheet.Shapes.Count
    Set ch = ActiveSheet.Shapes(i)

' any newly created chart will be called Chart XXXX and the shape index
' will be higher than my two initial (static shapes) on the sheet:

   If InStr(1, ch.Name, "Chart", 1) > 0 And i > 2 Then

     ActiveSheet.ChartObjects(ch.Name).Activate
     ActiveChart.Parent.Delete   ' this will actually visibly always
                                 ' delete the sheet correctly!

     'I tried this also out of desperation with the same result:
     ActiveChart.Parent.Cut
     Application.CutCopyMode = False

   End If

    Next
</code>```

So far so good, the chart has been deleted, now I find the range in that pivot that will have a different size depending on the slicers:

```<code>

    Dim PRange As Range
    Dim lLastRow, lFirstCol, lLastCol As Long

   Set PRange = ActiveSheet.PivotTables("Full Chart").TableRange2
   lLastRow = PRange(PRange.Rows.Count, 1).Row
   lFirstCol = PRange.Column
   lLastCol = PRange(1, PRange.Columns.Count).Column

Dim ValueRange As Range
Dim XRange As Range
Set ValueRange = ActiveSheet.Range(Cells(lLastRow, lFirstCol + 1), Cells(lLastRow, lLastCol - 1))
Set XRange = ActiveSheet.Range(Cells(lLastRow - 1, lFirstCol + 1), Cells(lLastRow - 1, lLastCol - 1))

</code>```

At this time I have all I need and can create the Chart:
(I tested that the ranges are correct, and when the code works it does show the correct values indeed.)

```<code>
    Application.CutCopyMode = False
    ActiveSheet.Shapes.AddChart2(227, xlColumnClustered).Select
    '*****
    ActiveChart.ChartArea.Select
    Application.CutCopyMode = False
    ActiveChart.SeriesCollection.NewSeries
    'xxxxx
    ActiveChart.FullSeriesCollection(1).Name = "='Year over year'!$AE$5"
    ActiveChart.FullSeriesCollection(1).Values = ValueRange
    ActiveChart.FullSeriesCollection(1).XValues = XRange

</code>```

What happens is that at **** sometimes a duplicate of my existing chart is created instead of an empty container (that's why I try the delete the clipboard there)
which causes the code to crash at xxxx because the ActiveChart.FullSeriesCollection(1) already exists.

It's just weird that it does not happen consistently.

I think the

```<code>ActiveSheet.Shapes.AddChart2(227, xlColumnClustered).Select
</code>```

is the culprit, why would it insert a complete chart with data?

Any ideas are appreciated.

答:
Try assigning directly to a variable and working with that.</p>

```<code>Dim myChart as Shape
Set myChart = ActiveSheet.Shapes.AddChart2(227, xlColumnClustered) 'even better to explicitly declare worksheet

With myChart
    .SeriesCollection.NewSeries
    .FullSeriesCollection(1).Name = "='Year over year'!$AE$5"
    .FullSeriesCollection(1).Values = ValueRange
    .FullSeriesCollection(1).XValues = XRange
End With
</code>```

Title: Trying to create a pivot chart

Body:
For reasons that are too long to explain here I need to create a custom chart out of an existing pivot table (which already has another chart attached to it).

The number of columns in the displayed range changes depending on the slicer settings.

What happens is that if I manually delete the created chart, select the new region and recreate the chart, everything is fine.

If I do the same thing with VBA (recorded the steps) it works sometimes
(especially if I delete the chart manually before running the code) but most of the time it will create a different chart and then errors out.

Here is what happens:

I find the chart from the last run (it's always shape[3]):

Dim ch As Shape
Dim i As Integer

  For i = 1 To ActiveSheet.Shapes.Count
    Set ch = ActiveSheet.Shapes(i)

' any newly created chart will be called Chart XXXX and the shape index
' will be higher than my two initial (static shapes) on the sheet:

   If InStr(1, ch.Name, "Chart", 1) > 0 And i > 2 Then

     ActiveSheet.ChartObjects(ch.Name).Activate
     ActiveChart.Parent.Delete   ' this will actually visibly always
                                 ' delete the sheet correctly!

     'I tried this also out of desperation with the same result:
     ActiveChart.Parent.Cut
     Application.CutCopyMode = False

   End If

    Next

So far so good, the chart has been deleted, now I find the range in that pivot that will have a different size depending on the slicers:

    Dim PRange As Range
    Dim lLastRow, lFirstCol, lLastCol As Long

   Set PRange = ActiveSheet.PivotTables("Full Chart").TableRange2
   lLastRow = PRange(PRange.Rows.Count, 1).Row
   lFirstCol = PRange.Column
   lLastCol = PRange(1, PRange.Columns.Count).Column

Dim ValueRange As Range
Dim XRange As Range
Set ValueRange = ActiveSheet.Range(Cells(lLastRow, lFirstCol + 1), Cells(lLastRow, lLastCol - 1))
Set XRange = ActiveSheet.Range(Cells(lLastRow - 1, lFirstCol + 1), Cells(lLastRow - 1, lLastCol - 1))

At this time I have all I need and can create the Chart:
(I tested that the ranges are correct, and when the code works it does show the correct values indeed.)

    Application.CutCopyMode = False
    ActiveSheet.Shapes.AddChart2(227, xlColumnClustered).Select
    '*****
    ActiveChart.ChartArea.Select
    Application.CutCopyMode = False
    ActiveChart.SeriesCollection.NewSeries
    'xxxxx
    ActiveChart.FullSeriesCollection(1).Name = "='Year over year'!$AE$5"
    ActiveChart.FullSeriesCollection(1).Values = ValueRange
    ActiveChart.FullSeriesCollection(1).XValues = XRange

What happens is that at **** sometimes a duplicate of my existing chart is created instead of an empty container (that's why I try the delete the clipboard there)
which causes the code to crash at xxxx because the ActiveChart.FullSeriesCollection(1) already exists.

It's just weird that it does not happen consistently.

I think the

ActiveSheet.Shapes.AddChart2(227, xlColumnClustered).Select

is the culprit, why would it insert a complete chart with data?

Any ideas are appreciated.

Body:
Try assigning directly to a variable and working with that.

Dim myChart as Shape
Set myChart = ActiveSheet.Shapes.AddChart2(227, xlColumnClustered) 'even better to explicitly declare worksheet

With myChart
    .SeriesCollection.NewSeries
    .FullSeriesCollection(1).Name = "='Year over year'!$AE$5"
    .FullSeriesCollection(1).Values = ValueRange
    .FullSeriesCollection(1).XValues = XRange
End With


问:
How can I get access to he absolute URL in Symfony and go one level up?
My absolute URL is linked to my public folder:

```<code><img src="{{ absolute_url(asset('img/logo/image.jpg')) }}" alt="image"/>
</code>```

It works fine like this, but in one case I need to load an image with an absolute URL but not to the public folder, instead, the image is in another folder that is on the same level then my public folder. I tried something like this:

```<code><img src="{{ absolute_url(asset('../myfolder/private/image.jpg')) }}" alt="image"/>
</code>```

But it is not working.

答:
public is your webroot, you can't access anything outside public directly in your browser (and for good reasons, this means you can't read the source code of any application!)

If you want to make something from outside the public directory available, either move it (or symlink) it into the public directory, create a new webroot, or write a custom Symfony controller to show the assets to your clients (make sure to have proper caching with the latter solution).

Body:
My absolute URL is linked to my public folder:

It works fine like this, but in one case I need to load an image with an absolute URL but not to the public folder, instead, the image is in another folder that is on the same level then my public folder. I tried something like this:

But it is not working.