问:
Nginx try_files not working for my Vue app
I currently have a Docker container using Nginx to serve up my Vue application. The configuration that I am using is as follows:

```<code>worker_processes 5;  ## Default: 1
error_log /usr/share/nginx/nginx_logs/error.log;
pid /usr/share/nginx/nginx_logs/nginx.pid;
worker_rlimit_nofile 8192;

events {
  worker_connections  4096;  ## Default: 1024
}

http {
  include /usr/share/nginx/conf/mime.types;
  include /usr/share/nginx/proxy.conf;
  index index.html index.htm;

  default_type application/octet-stream;
  log_format main '$remote_addr - $remote_user [$time_local]  $status '
    '"$request" $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';
  access_log /usr/share/nginx/nginx_logs/access.log main;
  sendfile on;
  tcp_nopush on;
  server_names_hash_bucket_size 128;

  server {
    listen 80;
    server_name spshub.org www.spshub.org;
    root /usr/share/nginx/html;
    access_log /usr/share/nginx/nginx_logs/spshub.access.log main;

    location / {
      try_files $uri $uri/ /index.html;
    }
  }
}

</code>```

I thought by including the try_files it would redirect back to the index.html on refresh, but all I am getting is the 404 error message. I am using a Vue Router with the history mode turned on and my base url set to '/'. When it hits the '/', it will redirect to '/home'. The the navigation works normally, but the refresh is when it errors. If I look at my logs, it is trying to look for 'home' in the root directory. Is there a way to fix this?

This is from the logs:

```<code>2019/05/28 19:39:07 [error] 6#6: *15 open() "/usr/share/nginx/html/home" failed (2: No such file or directory), client: <client-ip>, server: localhost, request: "GET /home HTTP/1.1", host: "<public-host-ip>"
<client-ip> - - [28/May/2019:19:39:07 +0000] "GET /home HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" "-"
2019/05/28 19:39:08 [error] 6#6: *15 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: <client-ip>, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "<public-host-ip>", referrer: "http://<public-host-ip>/home"
<client-ip> - - [28/May/2019:19:39:08 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://<public-host-ip>/home" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" "-"
</code>```

My Dockerfile is as follows:

```<code>FROM node:lts-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build:prod

# Production deployment
FROM nginx:stable-alpine as production
COPY --from=build /app/dist /usr/share/nginx/html
COPY /nginx /usr/share/nginx
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
</code>```

The dist folder which gets copied into the nginx/html folder looks like this:

```<code>dist\main.243ea19f.js.map
dist\main.243ea19f.js
dist\main.2bb2bbfa.css.map
dist\main.2bb2bbfa.css
dist\index.html
dist\assets\images\
</code>```

答:
From the looks of it, as stated in the comments. You need to change

COPY /nginx /usr/share/nginx

TO

COPY /nginx /etc/nginx/

This assumes that in your /nginx directory you have a nginx.config file.

Body:
I currently have a Docker container using Nginx to serve up my Vue application. The configuration that I am using is as follows:

worker_processes 5;  ## Default: 1
error_log /usr/share/nginx/nginx_logs/error.log;
pid /usr/share/nginx/nginx_logs/nginx.pid;
worker_rlimit_nofile 8192;

events {
  worker_connections  4096;  ## Default: 1024
}

http {
  include /usr/share/nginx/conf/mime.types;
  include /usr/share/nginx/proxy.conf;
  index index.html index.htm;

  default_type application/octet-stream;
  log_format main '$remote_addr - $remote_user [$time_local]  $status '
    '"$request" $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';
  access_log /usr/share/nginx/nginx_logs/access.log main;
  sendfile on;
  tcp_nopush on;
  server_names_hash_bucket_size 128;

  server {
    listen 80;
    server_name spshub.org www.spshub.org;
    root /usr/share/nginx/html;
    access_log /usr/share/nginx/nginx_logs/spshub.access.log main;

    location / {
      try_files $uri $uri/ /index.html;
    }
  }
}

I thought by including the try_files it would redirect back to the index.html on refresh, but all I am getting is the 404 error message. I am using a Vue Router with the history mode turned on and my base url set to '/'. When it hits the '/', it will redirect to '/home'. The the navigation works normally, but the refresh is when it errors. If I look at my logs, it is trying to look for 'home' in the root directory. Is there a way to fix this?

This is from the logs:

2019/05/28 19:39:07 [error] 6#6: *15 open() "/usr/share/nginx/html/home" failed (2: No such file or directory), client: <client-ip>, server: localhost, request: "GET /home HTTP/1.1", host: "<public-host-ip>"
<client-ip> - - [28/May/2019:19:39:07 +0000] "GET /home HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" "-"
2019/05/28 19:39:08 [error] 6#6: *15 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: <client-ip>, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "<public-host-ip>", referrer: "http://<public-host-ip>/home"
<client-ip> - - [28/May/2019:19:39:08 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://<public-host-ip>/home" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" "-"

My Dockerfile is as follows:

FROM node:lts-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build:prod

# Production deployment
FROM nginx:stable-alpine as production
COPY --from=build /app/dist /usr/share/nginx/html
COPY /nginx /usr/share/nginx
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

The dist folder which gets copied into the nginx/html folder looks like this:

dist\main.243ea19f.js.map
dist\main.243ea19f.js
dist\main.2bb2bbfa.css.map
dist\main.2bb2bbfa.css
dist\index.html
dist\assets\images\


来源: stackexchange

问:
Convert List<object> to JSON
I am using spring data jpa to fetch data from database.I written code for that in repository interface .But I am getting jpql output in below format:

```<code>[[21632,"Allfrey Laboratory","110060"],[21633,"Allis Laboratory","110070"]
</code>```

But i want this output in json format like:

```<code>[{"ndept_id":21632,"sdept_name":"Allfrey Laboratory","ninst_id":60,"bis_locked":false,"sclient_dept_id":"110060","nsurvey_method_id":1,"bis_jointuse":false,"ntemp_dept_id":4,"balternate_jointuse_percentage":false,"ndiv_id":null}]
</code>```

DepartmentRespository

```<code>@Repository
public interface DepartmentsRepository extends JpaRepository<Department, Integer>
{
    @Query("select d.ndept_id,d.sdept_name,d.sclient_dept_id from Department d")
    public List<Department> findColumns();
}
</code>```

DepartmentController

```<code> @RequestMapping(value="/findcolumn", method=RequestMethod.GET)
    @ResponseBody
    public List <Department> findColumnData()
    {
        return departmentservice.getColumns();
    }
</code>```

答:
I am using spring data jpa to fetch database data .For that i used jpa query in the repository interface .By using above query i am not able to get fetched output in proper format.I want that output in json.
For that i added new map in select statment. And i resolved my error.

Update:

```<code>@Repository
    public interface DepartmentsRepository extends JpaRepository<Department, Integer>
    {
        @Query("select new map(d.ndept_id,d.sdept_name,d.sclient_dept_id) from Department d")
        public List<Department> findColumns();
    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Convert List<object> to JSON

Body:
I am using spring data jpa to fetch data from database.I written code for that in repository interface .But I am getting jpql output in below format:

[[21632,"Allfrey Laboratory","110060"],[21633,"Allis Laboratory","110070"]

But i want this output in json format like:

[{"ndept_id":21632,"sdept_name":"Allfrey Laboratory","ninst_id":60,"bis_locked":false,"sclient_dept_id":"110060","nsurvey_method_id":1,"bis_jointuse":false,"ntemp_dept_id":4,"balternate_jointuse_percentage":false,"ndiv_id":null}]

DepartmentRespository

@Repository
public interface DepartmentsRepository extends JpaRepository<Department, Integer>
{
    @Query("select d.ndept_id,d.sdept_name,d.sclient_dept_id from Department d")
    public List<Department> findColumns();
}

DepartmentController

 @RequestMapping(value="/findcolumn", method=RequestMethod.GET)
    @ResponseBody
    public List <Department> findColumnData()
    {
        return departmentservice.getColumns();
    }

Body:
I am using spring data jpa to fetch database data .For that i used jpa query in the repository interface .By using above query i am not able to get fetched output in proper format.I want that output in json.
For that i added new map in select statment. And i resolved my error.

Update:

@Repository
    public interface DepartmentsRepository extends JpaRepository<Department, Integer>
    {
        @Query("select new map(d.ndept_id,d.sdept_name,d.sclient_dept_id) from Department d")
        public List<Department> findColumns();
    }


问:
Subtracting value from previous row sql by group
I have the following dataset:

```<code>DATA_FIM    CENTRO  C   M   ESTOQUE
2018-02-01  HD01    CD  70  539.000
2018-03-01  HD01    CD  70  511.000
2018-04-01  HD01    CD  70  468.000
2018-05-01  HD01    CD  70  447.000
2018-06-01  HD01    CD  70  382.000
2018-07-01  HD01    CD  70  348.000
2018-08-01  HD01    CD  70  285.000
2018-09-01  HD01    CD  70  245.000
2018-10-01  HD01    CD  70  221.000
2018-11-01  HD01    CD  70  207.000
2018-12-01  HD01    CD  70  122.000
2018-12-21  HD01    CD  70  101.000
2018-02-01  HD01    CD  71  164.000
2018-03-01  HD01    CD  71  147.000
2018-04-01  HD01    CD  71  124.000
2018-05-01  HD01    CD  71  107.000
2018-06-01  HD01    CD  71  78.000
</code>```

1- Considering the 2nd, 3rd, 4th columns as a group, I want to subtract the 5th column values from previous row of same column.

In order to create a new row.

[![Data][2]][2]

It's very similar with this problem: [Issue:13196190][3], however, in my case I have multiple index, and I am not sure how to solve.

UPDATED

I am using the suggested codes

```<code>select
ZBI_FAT_PRODUCT.DATA_FIM,
        ZBI_DIM_EMPRESA.CENTRO,
        ZBI_DIM_EMPRESA.CANAL,
        ZBI_DIM_PRODUCT.MATERIAL,
        ZBI_DIM_PRODUCT.TITULO,
        ZBI_FAT_PRODUCT.ESTOQUE_VENDA,
        LAG(ZBI_FAT_PRODUCT.ESTOQUE_VENDA, 1, ZBI_FAT_PRODUCT.ESTOQUE_VENDA) OVER (PARTITION BY ZBI_DIM_EMPRESA.CENTRO, ZBI_DIM_PRODUCT.MATERIAL, ZBI_DIM_PRODUCT.TITULO ORDER BY ZBI_FAT_PRODUCT.DATA_FIM) - ZBI_FAT_PRODUCT.ESTOQUE_VENDA AS NEW
FROM ZBI_DIM_EMPRESA INNER JOIN (ZBI_DIM_PRODUCT INNER JOIN ZBI_FAT_PRODUCT ON ZBI_DIM_PRODUCT.BK = ZBI_FAT_PRODUCT.BK_MATERIAL) ON ZBI_DIM_EMPRESA.BK = ZBI_FAT_PRODUCT.BK_EMPRESA;
</code>```

答:
For brevity, and to extract the solution from the comments -

The answer is to use the LAG() function:

```<code>SELECT *,
LAG(ESTOQUE, 1, ESTOQUE) OVER (PARTITION BY CENTRO, C, M ORDER BY DATA_FIM) - ESTOQUE AS New
FROM EnergyLog
</code>```

Here is an example of this working: SQLFiddle

Body:
I have the following dataset:

DATA_FIM    CENTRO  C   M   ESTOQUE
2018-02-01  HD01    CD  70  539.000
2018-03-01  HD01    CD  70  511.000
2018-04-01  HD01    CD  70  468.000
2018-05-01  HD01    CD  70  447.000
2018-06-01  HD01    CD  70  382.000
2018-07-01  HD01    CD  70  348.000
2018-08-01  HD01    CD  70  285.000
2018-09-01  HD01    CD  70  245.000
2018-10-01  HD01    CD  70  221.000
2018-11-01  HD01    CD  70  207.000
2018-12-01  HD01    CD  70  122.000
2018-12-21  HD01    CD  70  101.000
2018-02-01  HD01    CD  71  164.000
2018-03-01  HD01    CD  71  147.000
2018-04-01  HD01    CD  71  124.000
2018-05-01  HD01    CD  71  107.000
2018-06-01  HD01    CD  71  78.000

1- Considering the 2nd, 3rd, 4th columns as a group, I want to subtract the 5th column values from previous row of same column.

In order to create a new row.

[![Data][2]][2]

It's very similar with this problem: [Issue:13196190][3], however, in my case I have multiple index, and I am not sure how to solve.

UPDATED

I am using the suggested codes

select
ZBI_FAT_PRODUCT.DATA_FIM,
        ZBI_DIM_EMPRESA.CENTRO,
        ZBI_DIM_EMPRESA.CANAL,
        ZBI_DIM_PRODUCT.MATERIAL,
        ZBI_DIM_PRODUCT.TITULO,
        ZBI_FAT_PRODUCT.ESTOQUE_VENDA,
        LAG(ZBI_FAT_PRODUCT.ESTOQUE_VENDA, 1, ZBI_FAT_PRODUCT.ESTOQUE_VENDA) OVER (PARTITION BY ZBI_DIM_EMPRESA.CENTRO, ZBI_DIM_PRODUCT.MATERIAL, ZBI_DIM_PRODUCT.TITULO ORDER BY ZBI_FAT_PRODUCT.DATA_FIM) - ZBI_FAT_PRODUCT.ESTOQUE_VENDA AS NEW
FROM ZBI_DIM_EMPRESA INNER JOIN (ZBI_DIM_PRODUCT INNER JOIN ZBI_FAT_PRODUCT ON ZBI_DIM_PRODUCT.BK = ZBI_FAT_PRODUCT.BK_MATERIAL) ON ZBI_DIM_EMPRESA.BK = ZBI_FAT_PRODUCT.BK_EMPRESA;

Body:
For brevity, and to extract the solution from the comments -

The answer is to use the LAG() function:

SELECT *,
LAG(ESTOQUE, 1, ESTOQUE) OVER (PARTITION BY CENTRO, C, M ORDER BY DATA_FIM) - ESTOQUE AS New
FROM EnergyLog

Here is an example of this working: SQLFiddle


问:
How do I properly fade in and out using jQuery?
Can anyone help me with this simple bit of jQuery? I am building a carousel that features many sliding
s. Each one has a short description accompanying it, which I want to fade out when the carousel slides, and fade in when the carousel stops at another
. The problem is that when the carousel controls are clicked rapidly, the fades take a while to catch up. Also the current simple fadeIn/Out option doesn't work well when clicking to an
 much further through the carousel (from the small grey discs underneath infographic). I've tried a few options but I'm not really getting anywhere.

The page is here: http://weaver-wp.weavertest.com/radiation-infographic/

Thanks for any help :)

David

答: Use clearQueue before calling fadeIn/fadeOut </p>

ContentLicense: CC BY-SA 3.0


问:
Execute sphinx on a non-working Python script
I am trying to learn Docker.

I have a Python script that uses mod library which IS NOT installed on my system. The goal is to execute it inside a Docker container. I wrote the Dockerfile. I added this line inside it:

```<code>RUN pip install --trusted-host pypi.python.org -r requirements.txt
</code>```

And in requirements.txt i wrote mod.

It worked and inside the container it installs mod and the code works well.

Now, I want to generate Sphinx doc on the same script. I know how Sphinx works (the basics). I modified conf.py with sys.path.insert(0, os.path.abspath('..')) and it points to the directory that contains Script.py (alongside Dockerfile and requirements.txt) and then I added the following inside index.rst: Script.py is inside a folder named DockerPython:

```<code>.. automodule:: DockerPython.Script
   :members:
</code>```

When I launch make html (which works fine with other examples) I get the following:

```<code>Running Sphinx v2.0.1
making output directory... done
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 1 source files that are out of date
updating environment: 1 added, 0 changed, 0 removed
reading sources... [100%] index
WARNING: autodoc: failed to import module 'Script' from module 'DockerPython'; the following exception was raised:
No module named 'mod'
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index
generating indices... genindex
writing additional pages... search
copying static files... done
copying extra files... done
dumping search index in English (code: en) ... done
dumping object inventory... done
build succeeded, 1 warning.

The HTML pages are in build\html.
</code>```

And the page that I get is empty.

So, my question is: Can Sphinx be executed on a Script that doesn't compile and run well on local Python (because a lib is not installed locally)?

How do I get it to work on a script that works via Docker with specific settings? Thank you.

答:
After two hours of surfing I just figured it out.

I only had to add this line to conf.py:

```<code>autodoc_mock_imports = ['mod']
</code>```

Body:
I am trying to learn Docker.

I have a Python script that uses mod library which IS NOT installed on my system. The goal is to execute it inside a Docker container. I wrote the Dockerfile. I added this line inside it:

RUN pip install --trusted-host pypi.python.org -r requirements.txt

And in requirements.txt i wrote mod.

It worked and inside the container it installs mod and the code works well.

Now, I want to generate Sphinx doc on the same script. I know how Sphinx works (the basics). I modified conf.py with sys.path.insert(0, os.path.abspath('..')) and it points to the directory that contains Script.py (alongside Dockerfile and requirements.txt) and then I added the following inside index.rst: Script.py is inside a folder named DockerPython:

.. automodule:: DockerPython.Script
   :members:

When I launch make html (which works fine with other examples) I get the following:

Running Sphinx v2.0.1
making output directory... done
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 1 source files that are out of date
updating environment: 1 added, 0 changed, 0 removed
reading sources... [100%] index
WARNING: autodoc: failed to import module 'Script' from module 'DockerPython'; the following exception was raised:
No module named 'mod'
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index
generating indices... genindex
writing additional pages... search
copying static files... done
copying extra files... done
dumping search index in English (code: en) ... done
dumping object inventory... done
build succeeded, 1 warning.

The HTML pages are in build\html.

And the page that I get is empty.

So, my question is: Can Sphinx be executed on a Script that doesn't compile and run well on local Python (because a lib is not installed locally)?

How do I get it to work on a script that works via Docker with specific settings? Thank you.

Body:
After two hours of surfing I just figured it out.

I only had to add this line to conf.py:

autodoc_mock_imports = ['mod']


问:
Google Data Studio: How do you display the current date range?
I have a multi-page dashboard with a Data Range control which defaults to the "auto date range" (i.e. past seven days). I'd like to display those dates on the report, as the Data range control does not. </p>

答: Make a table with  Date as the dimension and allow 7 rows to be seen.  You can either use a general metric like pageviews in it, or no metric at all</p>


问:
How can I group MySQL Workbench connections?
During several years of activity, I accumulated dozens of Database Connections in MySQL Workbench. So many that finding the right one is becoming more and more a challenge. Is there a way to group connections, tidying up the home screen ?</p>

答: Sure, just right click on connection and choose Move to Group..., then you can create new group or select an existing one.


问:
How do I find the name of soccer players with same first name but different surnames?
I need to find the names of players from soccer team A that have the same first name but different surname as players from soccer team B. I need to produce the full names of all players from Team A, not just 'John'. I am able to use an additional column with Player IDs unique across all teams.

Basically table looks like this:

```<code>FirstName  LastName     Team
John       Snow         A
Batman     Dies         B
John       Dies         B
</code>```

I can produce a list of Team A names with the same first name as Team B players.

```<code>SELECT firstname, lastname FROM table
</code>```

Even though surname can't be used for one entry, it should be considered for other entries.

答:
You can use the following code:</p>

```<code>;WITH CTE AS
(
  SELECT *
  FROM Table
  WHERE Team = 'A'
),CTE1 AS
(
  SELECT *
  FROM Table
  WHERE Team = 'B'
)
SELECT *
FROM CTE R1
JOIN CTE1 R2 ON R1.FirstName = R2.FirstName
             AND R1.LastName <> R2.LastName
</code>```

Body:
I need to find the names of players from soccer team A that have the same first name but different surname as players from soccer team B. I need to produce the full names of all players from Team A, not just 'John'. I am able to use an additional column with Player IDs unique across all teams.

Basically table looks like this:

FirstName  LastName     Team
John       Snow         A
Batman     Dies         B
John       Dies         B

I can produce a list of Team A names with the same first name as Team B players.

SELECT firstname, lastname FROM table

Even though surname can't be used for one entry, it should be considered for other entries.

Body:
You can use the following code:

;WITH CTE AS
(
  SELECT *
  FROM Table
  WHERE Team = 'A'
),CTE1 AS
(
  SELECT *
  FROM Table
  WHERE Team = 'B'
)
SELECT *
FROM CTE R1
JOIN CTE1 R2 ON R1.FirstName = R2.FirstName
             AND R1.LastName <> R2.LastName


问:
Space considering as new line in html
We have two html files, by looks both look similar, but when we actually render, in one of them we have additional line breaks. May I know how to avoid it.

<feff><feff><feff><feff><feff><feff><feff><feff>Hi Mr. Calipjo,<o:p></o:p>

 <o:p></o:p>

Greetings!<o:p></o:p>

We apologize for the inconvenient
that this may have cause you.<o:p></o:p>

As of now we are still
coordinating this request to our support team, we are waiting for the feedback
from our support team.<o:p></o:p>

We will update you once we received
a feedback.<o:p></o:p>

<feff><feff><feff><feff><feff><feff><feff><feff>Hi Mr. Calipjo,<o:p></o:p>

 <o:p></o:p>

Greetings!<o:p></o:p>

We apologize for the inconvenient
that this may have cause you.<o:p></o:p>

As of now we are still
coordinating this request to our support team, we are waiting for the feedback
from our support team.<o:p></o:p>

We will update you once we received
a feedback.<o:p></o:p>

```

答:
In the first set of HTML I can see blank p tags with

```<code><p class="MsoNoSpacing"><span style="font-family: Calibri; font-size: 12px;"> </span></p>
</code>```

Whereas in the second set of HTML the   is not rendered.

Removing   from first HTML results in same output.

Hope this helps to debug further.

Title: Space considering as new line in html

Body:
In the first set of HTML I can see blank p tags with &nbsp;

<p class="MsoNoSpacing"><span style="font-family: Calibri; font-size: 12px;">&nbsp;</span></p>

Whereas in the second set of HTML the &nbsp; is not rendered.

Removing &nbsp; from first HTML results in same output.

Hope this helps to debug further.


问:
How to Switch Oracle jet Gantt chart RTL
I am setting gantt chart direction RTL.

Gantt chart hiding row axis lables and overlap lables in timeline bar

I used below gantt chart from oracle jet cookbook.

demo link

Here is screenshot of Switching OJET Gantt chart Direction LTR to RTL

Suggest me how to set direction?

I tried with refresh method

```<code>var a =document.getElementById('gantt');
a.dir="RTL";
a.refresh();
</code>```

Code from oracle jet Cookbook

答:
Without trying RTL I had a similar problem and the following fixed it....

in the html:

```<code><oj-gantt.....
row-axis.rendered="[[ax]]"
...</oj-gantt>
</code>```

In your viewModel define:

```<code>self.ax = ko.observable("off");
</code>```

When you switch to RTL try setting:

```<code>self.ax("on");
</code>```

Body:
I am setting gantt chart direction RTL.

Gantt chart hiding row axis lables and overlap lables in timeline bar

I used below gantt chart from oracle jet cookbook.

demo link

Here is screenshot of Switching OJET Gantt chart Direction LTR to RTL

Suggest me how to set direction?

I tried with refresh method

var a =document.getElementById('gantt');
a.dir="RTL";
a.refresh();

Code from oracle jet Cookbook

Body:
Without trying RTL I had a similar problem and the following fixed it....

in the html:

<oj-gantt.....
row-axis.rendered="[[ax]]"
...</oj-gantt>

In your viewModel define:

self.ax = ko.observable("off");

When you switch to RTL try setting:

self.ax("on");


问:
Crash when I convert PDF pages to PNG images
I need to convert each page of a PDF document to PNG images. These images are then displayed in a scrollView. I need to create two images per page: one at the screen dimension, and one 2.5 times bigger (it is used when the user zoom in the scrollView).

My problem is that I have sometimes memory warnings and crashes when I create big images.
The way  I do it is well-known:

```<code>
    CGRect pageRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
    float pdfScale = 2.5*self.view.frame.size.height/pageRect.size.height;
    pageRect.size = CGSizeMake(pageRect.size.width*pdfScale, pageRect.size.height*pdfScale);

    UIGraphicsBeginImageContext(pageRect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
    CGContextFillRect(context,pageRect);
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0.0, pageRect.size.height);
    CGContextScaleCTM(context, pdfScale,-pdfScale);
    CGContextDrawPDFPage(context, page);
    CGContextRestoreGState(context);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
</code>```

The problem occurs on iPhone 3G/3GS and iPod Touch.
How can I limit the memory consumption while still having a zoom scale of 2.5 ?

Thanks !

答: You could consider using a webview to display the PDF, that takes care of the zooming and memory issues. Basically rendering the vector format PDF to a bitmap PNG at a large size is possibly not the most appropriate design decision. Without knowing what your requirements for the PNG are though, it's hard to comment.</p>

Body:
I need to convert each page of a PDF document to PNG images. These images are then displayed in a scrollView. I need to create two images per page: one at the screen dimension, and one 2.5 times bigger (it is used when the user zoom in the scrollView).

My problem is that I have sometimes memory warnings and crashes when I create big images.
The way  I do it is well-known:

    CGRect pageRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
    float pdfScale = 2.5*self.view.frame.size.height/pageRect.size.height;
    pageRect.size = CGSizeMake(pageRect.size.width*pdfScale, pageRect.size.height*pdfScale);

    UIGraphicsBeginImageContext(pageRect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
    CGContextFillRect(context,pageRect);
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0.0, pageRect.size.height);
    CGContextScaleCTM(context, pdfScale,-pdfScale);
    CGContextDrawPDFPage(context, page);
    CGContextRestoreGState(context);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

The problem occurs on iPhone 3G/3GS and iPod Touch.
How can I limit the memory consumption while still having a zoom scale of 2.5 ?

Thanks !


问:
Receive input from command line with Spring Boot
So I have a really small Spring Boot command line application (There is no embedded tomcat server or anything that would make it a web application) with a single class where I try to use the Scanner class from java.util to read input from the user. This does not work at all. I thought it would be pretty basic stuff in Spring Boot, but all of my searches both on S.O or tutorials have yielded no results. What's the best way to go about it? or is Spring Boot just not for what I want to do?

Here's my class:

```<code>package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Scanner;

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory
        .getLogger(MyApplication.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("EXECUTING : command line runner");

        Scanner in = new Scanner(System.in);

        System.out.println("What is your name?");
        String name = in.next();
        System.out.println("Hello " + name + " welcome to spring boot" );
    }
}
</code>```

The exception being thrown is:

```<code>2019-05-29 11:31:29.116  INFO 4321 --- [           main] test.MyApplication  : EXECUTING : command line runner
2019-05-29 11:31:29.119  INFO 4321 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-29 11:31:29.124 ERROR 4321 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:816) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:324) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at com.jaletechs.png.PrimeNumberGeneratorApplication.main(MyApplication.java:19) [main/:na]
Caused by: java.util.NoSuchElementException: null
        at java.util.Scanner.throwFor(Scanner.java:862) ~[na:1.8.0_201]
        at java.util.Scanner.next(Scanner.java:1371) ~[na:1.8.0_201]
        at test.MyApplication.run(MyApplication.java:27) [main/:na]
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        ... 3 common frames omitted
</code>```

答:
So I discovered a way to make it work by trying out a normal gradle application (not spring boot). I ran into the same problem, and the solution was to add a line in my build.gradle file to wire up the default stdin

In a normal java gradle application:

```<code>run {
    standardInput = System.in
}
</code>```

but in the Spring Boot application, I added the following line:

```<code>bootRun {
    standardInput = System.in
}
</code>```

Turns out Spring Boot could handle a Command Line Application after all.

Body:
So I have a really small Spring Boot command line application (There is no embedded tomcat server or anything that would make it a web application) with a single class where I try to use the Scanner class from java.util to read input from the user. This does not work at all. I thought it would be pretty basic stuff in Spring Boot, but all of my searches both on S.O or tutorials have yielded no results. What's the best way to go about it? or is Spring Boot just not for what I want to do?

Here's my class:

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Scanner;

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory
        .getLogger(MyApplication.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("EXECUTING : command line runner");

        Scanner in = new Scanner(System.in);

        System.out.println("What is your name?");
        String name = in.next();
        System.out.println("Hello " + name + " welcome to spring boot" );
    }
}

The exception being thrown is:

2019-05-29 11:31:29.116  INFO 4321 --- [           main] test.MyApplication  : EXECUTING : command line runner
2019-05-29 11:31:29.119  INFO 4321 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-29 11:31:29.124 ERROR 4321 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:816) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:324) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at com.jaletechs.png.PrimeNumberGeneratorApplication.main(MyApplication.java:19) [main/:na]
Caused by: java.util.NoSuchElementException: null
        at java.util.Scanner.throwFor(Scanner.java:862) ~[na:1.8.0_201]
        at java.util.Scanner.next(Scanner.java:1371) ~[na:1.8.0_201]
        at test.MyApplication.run(MyApplication.java:27) [main/:na]
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        ... 3 common frames omitted

Body:
So I discovered a way to make it work by trying out a normal gradle application (not spring boot). I ran into the same problem, and the solution was to add a line in my build.gradle file to wire up the default stdin

In a normal java gradle application:

run {
    standardInput = System.in
}

but in the Spring Boot application, I added the following line:

bootRun {
    standardInput = System.in
}

Turns out Spring Boot could handle a Command Line Application after all.


问:
Why template specialization doesn't work in gcc
I'd like to write typelist methods to operate with microcontrollers GPIO's.

I'd like to create list of GPIO's and select only pins of specific port.
So, GetPinWithPort template has specialisation which checks provided type.

template <typename... Ts>
struct tlist
{
    using type = tlist;
};

template <typename T> class debug_t;

#define MAKE_PORT(NAME, ID)\
    class NAME\
    {\
        public:\
        static void Set(uint32_t v) { };\
        static void Reset(uint32_t v) { };\
        enum { id = ID };\
    };

MAKE_PORT(Porta, 'A');
MAKE_PORT(Portb, 'B');

template <class PORT, uint8_t PIN>
class TPin
{
public:
    static void Set() { PORT::Set(1 << PIN); }
    static void Reset() { PORT::Reset(1 << PIN); }

    typedef PORT port;
    enum { pin = PIN };
};

template <class TPort, class T>
struct GetPinWithPort {
    using type = tlist<>;
};

template <typename TPort, uint32_t N>
struct GetPinWithPort<TPort, TPin<TPort, N>>
{
    using type = TPin<TPort, N>;
};

int main()
{

    using pina = GetPinWithPort<Porta, TPin<Porta, 1> >::type;

    // std::cout << typeid(pina).name() << std::endl;  //Visual Studio gives: class TPin<class Porta,1>
    debug_t<pina> d; //gcc output: tlist<>

}
```

Visual Studio gives expected result. But gcc - empty list.
What is wrong here?

答:
It should be

```<code>template <typename TPort, uint8_t N>  // or auto
struct GetPinWithPort<TPort, TPin<TPort, N>>
</code>```

not

```<code>template <typename TPort, uint32_t N>
struct GetPinWithPort<TPort, TPin<TPort, N>>
</code>```

because (I am not a language lawer, it's just how I understand i):

```<code>template <class PORT, uint8_t PIN>
class TPin {}
// and
using pina = GetPinWithPort<Porta, TPin<Porta, 1> >::type;
</code>```

In the specialisation gcc have to choose between:

```<code>class T
</code>```

and

```<code>TPin<TPort, uint32_t>
</code>```

and the type it have is:

```<code>TPin<Porta, 1>
</code>```

So may be gcc resolve the TPin<Porta, 1> to TPin<Porta, uint8_t> then fail the specialisation.

Body:
I'd like to write typelist methods to operate with microcontrollers GPIO's.

I'd like to create list of GPIO's and select only pins of specific port.
So, GetPinWithPort template has specialisation which checks provided type.

template <typename... Ts>
struct tlist
{
    using type = tlist;
};

template <typename T> class debug_t;

#define MAKE_PORT(NAME, ID)\
    class NAME\
    {\
        public:\
        static void Set(uint32_t v) { };\
        static void Reset(uint32_t v) { };\
        enum { id = ID };\
    };

MAKE_PORT(Porta, 'A');
MAKE_PORT(Portb, 'B');

template <class PORT, uint8_t PIN>
class TPin
{
public:
    static void Set() { PORT::Set(1 << PIN); }
    static void Reset() { PORT::Reset(1 << PIN); }

    typedef PORT port;
    enum { pin = PIN };
};

template <class TPort, class T>
struct GetPinWithPort {
    using type = tlist<>;
};

template <typename TPort, uint32_t N>
struct GetPinWithPort<TPort, TPin<TPort, N>>
{
    using type = TPin<TPort, N>;
};

int main()
{

    using pina = GetPinWithPort<Porta, TPin<Porta, 1> >::type;

    // std::cout << typeid(pina).name() << std::endl;  //Visual Studio gives: class TPin<class Porta,1>
    debug_t<pina> d; //gcc output: tlist<>

}

Visual Studio gives expected result. But gcc - empty list.
What is wrong here?

Body:
It should be

template <typename TPort, uint8_t N>  // or auto
struct GetPinWithPort<TPort, TPin<TPort, N>>

not

template <typename TPort, uint32_t N>
struct GetPinWithPort<TPort, TPin<TPort, N>>

because (I am not a language lawer, it's just how I understand i):

template <class PORT, uint8_t PIN>
class TPin {}
// and
using pina = GetPinWithPort<Porta, TPin<Porta, 1> >::type;

In the specialisation gcc have to choose between:

class T

and

TPin<TPort, uint32_t>

and the type it have is:

TPin<Porta, 1>

So may be gcc resolve the TPin<Porta, 1> to TPin<Porta, uint8_t> then fail the specialisation.


问:
is there an function that draw an edge with arrow in the middle of the edge?
I want to draw an edge with an arrow in its middle.
I am using networkx with python 3.6 and mathblotlib for showing the figure.

I have tried many ways but I just received this result.

predecesseur={'1': nan, '2': nan, '3': '1', '4': '1,2', '5': '3,4'}
tachdu={'1': '2', '2': '4', '3': '4', '4': '5', '5': '6'}
G=nx.DiGraph()
G.add_node('Début',type ='0')
G.add_node('Fin',type ='0')
for key in predecesseur.keys():
    G.add_node(key,type =tachdu[key])
    ch=predecesseur[key]
    if type(ch)!=type(0.0):
        for i in range(len(ch)):
            if (ch[i]!=',' and ch[i]!=';'):
                G.add_edge(ch[i],key)
    else:
        G.add_edge('Début',key)

for nod in G:
    if list(G.successors(nod))==[]:
        G.add_edge(nod,'Fin')

pos_nodes = nx.spring_layout(G)
nx.draw(G, pos_nodes, with_labels=True)
color_map = ['green']
nx.draw_networkx_nodes(G, pos_nodes, node_size=500, nodelist=['Fin'],node_color=color_map)
nx.draw_networkx_nodes(G, pos_nodes, node_size=1400, nodelist=['Début'],node_color=color_map)
node_attrs = nx.get_node_attributes(G, 'type')
pos_attrs = {}
for node, coords in pos_nodes.items():
    pos_attrs[node] = (coords[0], coords[1] + 0.08)
custom_node_attrs = {}
for node, attr in node_attrs.items():
    custom_node_attrs[node] = "{" + attr + "}"
nx.draw_networkx_labels(G, pos_attrs, labels=custom_node_attrs)
plt.show()
```

答:
Networkx uses Matplotlib to draw graphs. For edges, it uses ArrowStyle. Here are possible types of edges:

So no, networkx can't draw arrow heads in the middle of the edge. You can try to convert it to a DOT format (or any another format) and try to visualize it with another tool.


问:
ARM Cortex-M interrupt handler in C++
Is it possible to write an interrupt handler in C++ for ARM Cortex chips like those of ST and NXP.

Currently I develop a lot of code in C++ for ARM cortex chips. I am a bit fed up with having to call a static/global/singleton C++ object from a C callback function. Is there a way to not having to through the C function.

Is there a way to directly call a C++ object functions when a interrupt occurs?

答:
Is away to directly call a C++ object function when a interrupt occurs?

In a short, no. Even if you declare your non-static method as void (void), it still has an implicit argument - this. Interrupt handler on the other hand, has no arguments at all.

Title: ARM Cortex-M interrupt handler in C++


问:
Missing attributes in layout editor in Android Studio
I've got a problem with Android Studio version 3.2.1. I do not see in layout editor  most of attributes like for example id. I have got this bug probably after Android Studio's update.

答: Down of the activity_main.xml window there is "Design" tab and "Text" tab. Click on design tab, select an item and voila: attributes window is on the right</p>


问:
How to apply own build function on groupby
I couldnt find a thread, that fitted my question... In case this is not true, please don't hesitate to post the link to the thread.

I have the following dataframe, which I have to analyze. This is the head of it:

```<code>

                     EMBieding  AeolisBieding  ...  Diff_EM  Diff_Aeolis
StartTime                                      ...
2019-09-01 00:00:00    3058.24         3494.0  ... -3126.24      -3562.0
2019-09-01 01:00:00    2906.01         3480.0  ... -2974.01      -3548.0
2019-09-01 02:00:00    2836.22         3470.0  ... -2903.22      -3537.0
2019-09-01 03:00:00    2805.66         3448.0  ... -2848.66      -3491.0
2019-09-01 04:00:00    2541.54         3413.0  ... -2606.54      -3478.0
</code>```

Next to overall error measures, I also want to find out the error per hour.
This means, the hours from 0 - 23 have to be aggregated.
Using the following code, it is easy to find the mean:

```<code>data= importdata('871687110001543570.csv')
data_perhour = data.groupby(data.index.hour).mean()
data_perhour.drop
print(data_perhour)
</code>```

I can easily find the mean for each column.

```<code>             EMBieding  AeolisBieding  ...     Diff_EM  Diff_Aeolis
StartTime                              ...
0          1175.862033    1279.577236  ... -253.707561  -357.422764
1          1153.947724    1264.723577  ... -309.435528  -420.211382
2          1146.239016    1259.459016  ... -336.763607  -449.983607
3          1133.350976    1251.268293  ... -390.928211  -508.845528
4          1127.061789    1251.300813  ... -405.411382  -529.650407
</code>```

The error measures I use are NBIAS, NMAE and NRMSE. I calculate this with the following

```<code># statistic calculates the different errormeasurements: NBIAS,NMAE,NRMSE. Input arguments are: data; this is the output from the
# importdata function. parksize; which is just the installed power of the respective farm, for normalization. filename
# is needed to produce a unique new filename.
def statistic(data,park_size,filename):
    def NBIAS(Diff_forecaster,park_size):
        return data[Diff_forecaster].mean()/park_size

    def NMAE(Bied_forecaster,park_size):
        return mean_absolute_error(data['Production'], data[Bied_forecaster]) /park_size

    def NRMSE(Bied_forecaster,park_size):
        return (sqrt(mean_squared_error(data['Production'], data[Bied_forecaster])) /np.square(park_size))

# Calculate the overall errormeasure and save it directly in a external .csv
    ErrorMeasure = {'EM':[NBIAS('Diff_EM',park_size),NMAE('EMBieding',park_size),NRMSE('EMBieding',park_size)],
                    'Aeolis':[NBIAS('Diff_Aeolis',park_size),NMAE('Bied',park_size ),NRMSE('Bied',park_size)]}
    df_ErrorMeasure = pd.DataFrame(ErrorMeasure,index=['NBIAS','NMAE','NRMSE'])
    df_ErrorMeasure.to_csv('errormeasure'+filename)

    data_perhour=data.groupby(data.index.hour).apply(NBIAS('EMBieding',park_size))

    print(data_perhour)
</code>```

The last two lines are a attempt to get the NBIAS for each hour. However, I get this error:

```<code>TypeError: 'numpy.float64' object is not callable
</code>```

How can I get the error measures for each hour? This means, can I use a own function (like.NBIAS) to replace the .mean after data.groupby(data.index.hour).

Anyone suggestions?`

答:
Pandas groupby apply accepts a callable that receives as parameter the subset of the dataframe corresponding to the group. Your problem is that the NBIAS function has no parameter for that and acts on the original dataframe.

In order to use it in your groupby, you will need to adapt it:

```<code>def statistic(data,park_size,filename):
    def NBIAS(Diff_forecaster,park_size, df=data):
        return df[Diff_forecaster].mean()/park_size
</code>```

Then you can use it that way:

```<code>data_perhour=data.groupby(data.index.hour).apply(lambda subdf: NBIAS('EMBieding',park_size, subdf))

print(data_perhour)
</code>```

Body:
I couldnt find a thread, that fitted my question... In case this is not true, please don't hesitate to post the link to the thread.

I have the following dataframe, which I have to analyze. This is the head of it:

                     EMBieding  AeolisBieding  ...  Diff_EM  Diff_Aeolis
StartTime                                      ...
2019-09-01 00:00:00    3058.24         3494.0  ... -3126.24      -3562.0
2019-09-01 01:00:00    2906.01         3480.0  ... -2974.01      -3548.0
2019-09-01 02:00:00    2836.22         3470.0  ... -2903.22      -3537.0
2019-09-01 03:00:00    2805.66         3448.0  ... -2848.66      -3491.0
2019-09-01 04:00:00    2541.54         3413.0  ... -2606.54      -3478.0

Next to overall error measures, I also want to find out the error per hour.
This means, the hours from 0 - 23 have to be aggregated.
Using the following code, it is easy to find the mean:

data= importdata('871687110001543570.csv')
data_perhour = data.groupby(data.index.hour).mean()
data_perhour.drop
print(data_perhour)

I can easily find the mean for each column.

             EMBieding  AeolisBieding  ...     Diff_EM  Diff_Aeolis
StartTime                              ...
0          1175.862033    1279.577236  ... -253.707561  -357.422764
1          1153.947724    1264.723577  ... -309.435528  -420.211382
2          1146.239016    1259.459016  ... -336.763607  -449.983607
3          1133.350976    1251.268293  ... -390.928211  -508.845528
4          1127.061789    1251.300813  ... -405.411382  -529.650407

The error measures I use are NBIAS, NMAE and NRMSE. I calculate this with the following

# statistic calculates the different errormeasurements: NBIAS,NMAE,NRMSE. Input arguments are: data; this is the output from the
# importdata function. parksize; which is just the installed power of the respective farm, for normalization. filename
# is needed to produce a unique new filename.
def statistic(data,park_size,filename):
    def NBIAS(Diff_forecaster,park_size):
        return data[Diff_forecaster].mean()/park_size

    def NMAE(Bied_forecaster,park_size):
        return mean_absolute_error(data['Production'], data[Bied_forecaster]) /park_size

    def NRMSE(Bied_forecaster,park_size):
        return (sqrt(mean_squared_error(data['Production'], data[Bied_forecaster])) /np.square(park_size))

# Calculate the overall errormeasure and save it directly in a external .csv
    ErrorMeasure = {'EM':[NBIAS('Diff_EM',park_size),NMAE('EMBieding',park_size),NRMSE('EMBieding',park_size)],
                    'Aeolis':[NBIAS('Diff_Aeolis',park_size),NMAE('Bied',park_size ),NRMSE('Bied',park_size)]}
    df_ErrorMeasure = pd.DataFrame(ErrorMeasure,index=['NBIAS','NMAE','NRMSE'])
    df_ErrorMeasure.to_csv('errormeasure'+filename)

    data_perhour=data.groupby(data.index.hour).apply(NBIAS('EMBieding',park_size))

    print(data_perhour)

The last two lines are a attempt to get the NBIAS for each hour. However, I get this error:

TypeError: 'numpy.float64' object is not callable

How can I get the error measures for each hour? This means, can I use a own function (like.NBIAS) to replace the .mean after data.groupby(data.index.hour).

Anyone suggestions?`

Body:
Pandas groupby apply accepts a callable that receives as parameter the subset of the dataframe corresponding to the group. Your problem is that the NBIAS function has no parameter for that and acts on the original dataframe.

In order to use it in your groupby, you will need to adapt it:

def statistic(data,park_size,filename):
    def NBIAS(Diff_forecaster,park_size, df=data):
        return df[Diff_forecaster].mean()/park_size

Then you can use it that way:

data_perhour=data.groupby(data.index.hour).apply(lambda subdf: NBIAS('EMBieding',park_size, subdf))

print(data_perhour)


问:
Empty Data Error when checking if CSV is empty
I got a CSV file which sometimes it's empty and sometimes got content in it. I am trying to check if the CSV is empty or not, so I could know if to append to it or recreate it.

I have tried this:

```<code>check_df = pd.read_csv(r'my file')
if check_df.empty:
    csvfile = open(r'my file', 'w', newline='')
    obj = csv.writer(csvfile)
    obj.writerow(["date", "bmo amc", "stock symbol","company name"])
    print("csv empty")
else:
    csvfile = open(r'my file', 'a', newline='')
    obj = csv.writer(csvfile)
    print("appending csv")
</code>```

this code gives me the error:

```pandas.errors.EmptyDataError: No columns to parse from file```

pretty new to python if you can please be clear with the answers thanks.

答:
You can also make use of python exception handling to avoid this error</p>

```<code>import csv
vFileName='tmp.csv'
try:
    check_df = pd.read_csv(vFileName)
except:
    with open(vFileName, 'w', newline='') as csvfile:
        obj = csv.writer(csvfile)
        obj.writerow(["dtest", "bmo amc", "stock symbol","company name"])
        print("csv empty")
else:
    with open(vFileName, 'a', newline='') as csvfile:
        obj = csv.writer(csvfile)
        obj.writerow(["dtest", "bmo amc", "stock symbol","company name"])
        print("appending csv")
</code>```

Body:
I got a CSV file which sometimes it's empty and sometimes got content in it. I am trying to check if the CSV is empty or not, so I could know if to append to it or recreate it.

I have tried this:

check_df = pd.read_csv(r'my file')
if check_df.empty:
    csvfile = open(r'my file', 'w', newline='')
    obj = csv.writer(csvfile)
    obj.writerow(["date", "bmo amc", "stock symbol","company name"])
    print("csv empty")
else:
    csvfile = open(r'my file', 'a', newline='')
    obj = csv.writer(csvfile)
    print("appending csv")

this code gives me the error:

pandas.errors.EmptyDataError: No columns to parse from file

pretty new to python if you can please be clear with the answers thanks.

Body:
You can also make use of python exception handling to avoid this error

import csv
vFileName='tmp.csv'
try:
    check_df = pd.read_csv(vFileName)
except:
    with open(vFileName, 'w', newline='') as csvfile:
        obj = csv.writer(csvfile)
        obj.writerow(["dtest", "bmo amc", "stock symbol","company name"])
        print("csv empty")
else:
    with open(vFileName, 'a', newline='') as csvfile:
        obj = csv.writer(csvfile)
        obj.writerow(["dtest", "bmo amc", "stock symbol","company name"])
        print("appending csv")


问:
Send learners reminder email and admin
Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"

I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.

the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.

I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.

```<code>    <?php
include 'db.php';

function check_emailaddress($email) {
    // First, we check that there is one @ symbol, and that the lengths are right
    if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email))
    {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++)
    {
        if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
        {
            return false;
        }
    }
    if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))  // Check if domain is IP. If not, it should be valid domain name
    {
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2)
        {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++)
        {
        if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
        {
            return false;
        }
        }
    }
    return true;
}

$extraParam = "";
if (isset($_GET["ex"]) ) {
  $extraParam = $_GET["ex"]."---";
}

//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail;    //"From: info@visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6@gmail.com";
$email_to = "" ;//"respite@safeguards-training.net";

$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;

if ($usetemplate == 0) exit;            // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info@visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;

$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
                  WHERE a01User=a04UserId AND a03CourseId=a04CourseId
                  AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
                  AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");

$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){

    $fn = $email_row->a01FirstName;
    $email = $email_row->a01Email;
    $password = $email_row->a002password;

    if ($pre_email == $email){
        $course .= "web url" . $email_row->a03CourseName . "</a><br>";
        $pre_email = $email;
        $pre_fn = $fn;
        $pre_password = $password;
    }else{
        $nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
        $course = "web url" . $email_row->a03CourseName . "</a><br>";
        $pre_email = $email;
        $pre_fn = $fn;
        $pre_password = $password;
    }

}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);

array_shift($nofinish);

set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;

foreach($nofinish as $no){
    $email_from = $from;
    $email_address = $no['email'];

//  $email_address = "lyan3000@gmail.com";
//  if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
    $email_subject = "Course Completion Reminder";

    $top = "<div style='font-family:Arial'>";
    $top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";

    $variable = array(
        '{$firstname}' => $no['firstname'],
        '{$course}' => $no['courses'],
        '{$password}'=> $no['password'],
        '{$email}'=> $no['email']
      );
    $email_body = strtr($eb1, $variable);

    $bottom = "<p><img src='cid:logoimg'></p>";
    $bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
    $email_message = $top . $email_body . $bottom;
/*
    echo $email_from . "<br>";
    echo $email_address . "<br>";
    echo $email_subject . "<br>";
    echo $email_message;
    echo "<hr>";
*/

    if (mail($email_address, $email_subject, $email_message, $email_from))
    {
        //echo "Reminder email sent to: " . $no['firstname'] . "<br>";
        echo "Yes. <br>";
    }else{
        //echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "<br>";
        echo "No. <br>";
    }

}

$file_name = "record_for_cron_expire_email.txt";

$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');

$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);

//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;

$variable = array(
    '{$learnerCourse}' => $learnercourse,
    '{$date}' => $date
  );
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);

//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
                    SET a04Status = 0
                    WHERE a04ExpirationDate <= '$expiredRightNow'
                    AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.<br>$strSQL_setExpire");
?>
</code>```

答:
below is the minimal code I can think of:
        $strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
                          WHERE a01User=a04UserId AND a03CourseId=a04CourseId
                          AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
                          AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";</p>

```<code>    $query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");

    $nofinish = array();
    $course = "";
    $pre_email = "";
    $pre_fn = "";
    $n = 0;
    while($email_row=$query->fetch(PDO::FETCH_OBJ)){
        $fn = $email_row->a01FirstName;
        $email = $email_row->a01Email;
        $password = $email_row->a002password;

        if ($pre_email == $email){
            $course .= "web url" . $email_row->a03CourseName . "</a><br>";
            $pre_email = $email;
            $pre_fn = $fn;
            $pre_password = $password;
        }else{
            $nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
            $course = "web url" . $email_row->a03CourseName . "</a><br>";
            $pre_email = $email;
            $pre_fn = $fn;
            $pre_password = $password;
        }
    }
    $nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);

    array_shift($nofinish);

    set_time_limit(600);
    $eb1 = nl2br($eb);
    $i = 0;

    foreach($nofinish as $no){
        $email_from = $from;
        $email_address = $no['email'];

        $email_subject = "Course Completion Reminder";

        $top = "<div style='font-family:Arial'>";
        $top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";

        $variable = array(
            '{$firstname}' => $no['firstname'],
            '{$course}' => $no['courses'],
            '{$password}'=> $no['password'],
            '{$email}'=> $no['email']
          );
        $email_body = strtr($eb1, $variable);

        $bottom = "<p><img src='cid:logoimg'></p>";
        $bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
        $email_message = $top . $email_body . $bottom;

        if (mail($email_address, $email_subject, $email_message, $email_from))
        {
            echo "Yes. <br>";
        }else{
            echo "No. <br>";
        }
    }
</code>```

Title: Send learners reminder email and admin

Body:
Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"

I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.

the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.

I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.

    <?php
include 'db.php';

function check_emailaddress($email) {
    // First, we check that there is one @ symbol, and that the lengths are right
    if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email))
    {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++)
    {
        if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
        {
            return false;
        }
    }
    if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))  // Check if domain is IP. If not, it should be valid domain name
    {
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2)
        {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++)
        {
        if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
        {
            return false;
        }
        }
    }
    return true;
}

$extraParam = "";
if (isset($_GET["ex"]) ) {
  $extraParam = $_GET["ex"]."---";
}

//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail;    //"From: info@visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6@gmail.com";
$email_to = "" ;//"respite@safeguards-training.net";

$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;

if ($usetemplate == 0) exit;            // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info@visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;

$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
                  WHERE a01User=a04UserId AND a03CourseId=a04CourseId
                  AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
                  AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.
$strSQL_expire");

$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){

    $fn = $email_row->a01FirstName;
    $email = $email_row->a01Email;
    $password = $email_row->a002password;

    if ($pre_email == $email){
        $course .= "web url" . $email_row->a03CourseName . "
";
        $pre_email = $email;
        $pre_fn = $fn;
        $pre_password = $password;
    }else{
        $nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
        $course = "web url" . $email_row->a03CourseName . "
";
        $pre_email = $email;
        $pre_fn = $fn;
        $pre_password = $password;
    }

}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);

array_shift($nofinish);

set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;

foreach($nofinish as $no){
    $email_from = $from;
    $email_address = $no['email'];

//  $email_address = "lyan3000@gmail.com";
//  if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
    $email_subject = "Course Completion Reminder";

    $top = "
";
    $top .= "

Service Centre

";

    $variable = array(
        '{$firstname}' => $no['firstname'],
        '{$course}' => $no['courses'],
        '{$password}'=> $no['password'],
        '{$email}'=> $no['email']
      );
    $email_body = strtr($eb1, $variable);

    $bottom = "

";
    $bottom .="

";
    $email_message = $top . $email_body . $bottom;
/*
    echo $email_from . "
";
    echo $email_address . "
";
    echo $email_subject . "
";
    echo $email_message;
    echo "
";
*/

    if (mail($email_address, $email_subject, $email_message, $email_from))
    {
        //echo "Reminder email sent to: " . $no['firstname'] . "
";
        echo "Yes.
";
    }else{
        //echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "
";
        echo "No.
";
    }

}

$file_name = "record_for_cron_expire_email.txt";

$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');

$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);

//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;

$variable = array(
    '{$learnerCourse}' => $learnercourse,
    '{$date}' => $date
  );
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);

//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
                    SET a04Status = 0
                    WHERE a04ExpirationDate <= '$expiredRightNow'
                    AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.
$strSQL_setExpire");
?>

Body:
below is the minimal code I can think of:
        $strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
                          WHERE a01User=a04UserId AND a03CourseId=a04CourseId
                          AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
                          AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";

    $query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");

    $nofinish = array();
    $course = "";
    $pre_email = "";
    $pre_fn = "";
    $n = 0;
    while($email_row=$query->fetch(PDO::FETCH_OBJ)){
        $fn = $email_row->a01FirstName;
        $email = $email_row->a01Email;
        $password = $email_row->a002password;

        if ($pre_email == $email){
            $course .= "web url" . $email_row->a03CourseName . "</a><br>";
            $pre_email = $email;
            $pre_fn = $fn;
            $pre_password = $password;
        }else{
            $nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
            $course = "web url" . $email_row->a03CourseName . "</a><br>";
            $pre_email = $email;
            $pre_fn = $fn;
            $pre_password = $password;
        }
    }
    $nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);

    array_shift($nofinish);

    set_time_limit(600);
    $eb1 = nl2br($eb);
    $i = 0;

    foreach($nofinish as $no){
        $email_from = $from;
        $email_address = $no['email'];

        $email_subject = "Course Completion Reminder";

        $top = "<div style='font-family:Arial'>";
        $top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";

        $variable = array(
            '{$firstname}' => $no['firstname'],
            '{$course}' => $no['courses'],
            '{$password}'=> $no['password'],
            '{$email}'=> $no['email']
          );
        $email_body = strtr($eb1, $variable);

        $bottom = "<p><img src='cid:logoimg'></p>";
        $bottom .="<div style='background-color:#045FB4; height:25px;width:100%'>&nbsp;</div></div>";
        $email_message = $top . $email_body . $bottom;

        if (mail($email_address, $email_subject, $email_message, $email_from))
        {
            echo "Yes. <br>";
        }else{
            echo "No. <br>";
        }
    }


问:
not a valid l-value - verilog compiler error
```<code>module fronter ( arc, length, clinic ) ;
 input [7:0] arc;
 output reg [7:0] length ;

 input [1:0] clinic;
 input en0, en1, en2, en3; // 11

 // clock generator  is here

 g_cal A( en0) ;
 g_cal B( en1) ;
 g_cal C( en2) ;
 g_cal D( en3) ;

always @( negedge arc, posedge clk )
  case ( clinic )
    2'b00 : { en3, en2, en1, en0 } = 4'b0001;    // 23
    2'b01 : { en3, en2, en1, en0 } = 4'b0010;    // 24
    2'b10 : { en3, en2, en1, en0 } = 4'b0100;    // 25
    2'b11 : { en3, en2, en1, en0 } = 4'b1000;    // 26
    default : { en3, en2, en1, en0 } = 4'bxxxx;  // 27
  endcase

// I am trying to change value of en to call corresponding intance with that
//corresponding en value

endmodule

module g_cal ( en ) ;

 input en ;
 // some other jobs, calling another instances after making some job

endmodule
</code>```

when I compile, compiler gives me ;

```<code>verilog.v:23: error: en0 is not a valid l-value in Numerator.
verilog.v:11:      : en0 is declared here as wire.
verilog.v:24: error: en1 is not a valid l-value in Numerator.
verilog.v:11:      : en1 is declared here as wire.
verilog.v:25: error: en2 is not a valid l-value in Numerator.
verilog.v:11:      : en2 is declared here as wire.
verilog.v:26: error: en3 is not a valid l-value in Numerator.
verilog.v:11:      : en3 is declared here as wire.
verilog.v:27: error: en3 is not a valid l-value in Numerator.
verilog.v:11:      : en3 is declared here as wire.
segmentation fault
</code>```

How can I fix it ?
Why it gives error?

EDIT:
    I have solved problem as ;

```<code>   // I erased that line "input en0, en1, en2, en3; // 11"

 // clock generator  is here

 g_cal A(  1'b0) ;
 g_cal B(  1'b0) ;
 g_cal C(  1'b0) ;
 g_cal D(  1'b0) ;

always @( negedge arc, posedge clk )
/* erasing all those line
 case ( clinic )
    2'b00 : { en3, en2, en1, en0 } = 4'b0001;    // 23
    2'b01 : { en3, en2, en1, en0 } = 4'b0010;    // 24
    2'b10 : { en3, en2, en1, en0 } = 4'b0100;    // 25
    2'b11 : { en3, en2, en1, en0 } = 4'b1000;    // 26
    default : { en3, en2, en1, en0 } = 4'bxxxx;  // 27
  endcase
</code>```

I will use if and else structure, and calling corresponding instance with 1'b1*/

```<code> // I am trying to change value of en to call corresponding intance with that
//corresponding en value

endmodule
</code>```

答:
You're trying assign to an input (which is bad). Change input en0, en1, en2, en3; to output reg en0, en1, en2, en3;. The reg is necessary since you are assigning to that variable within a procedural block (ie, an always or initial). The "not a valid l-value" message is trying to tell you this.

Also, I'm assuming that the 11, 23, 24, etc are stray line numbers from a copy-paste...

Body:
module fronter ( arc, length, clinic ) ;
 input [7:0] arc;
 output reg [7:0] length ;

 input [1:0] clinic;
 input en0, en1, en2, en3; // 11

 // clock generator  is here

 g_cal A( en0) ;
 g_cal B( en1) ;
 g_cal C( en2) ;
 g_cal D( en3) ;

always @( negedge arc, posedge clk )
  case ( clinic )
    2'b00 : { en3, en2, en1, en0 } = 4'b0001;    // 23
    2'b01 : { en3, en2, en1, en0 } = 4'b0010;    // 24
    2'b10 : { en3, en2, en1, en0 } = 4'b0100;    // 25
    2'b11 : { en3, en2, en1, en0 } = 4'b1000;    // 26
    default : { en3, en2, en1, en0 } = 4'bxxxx;  // 27
  endcase

// I am trying to change value of en to call corresponding intance with that
//corresponding en value

endmodule

module g_cal ( en ) ;

 input en ;
 // some other jobs, calling another instances after making some job

endmodule

when I compile, compiler gives me ;

verilog.v:23: error: en0 is not a valid l-value in Numerator.
verilog.v:11:      : en0 is declared here as wire.
verilog.v:24: error: en1 is not a valid l-value in Numerator.
verilog.v:11:      : en1 is declared here as wire.
verilog.v:25: error: en2 is not a valid l-value in Numerator.
verilog.v:11:      : en2 is declared here as wire.
verilog.v:26: error: en3 is not a valid l-value in Numerator.
verilog.v:11:      : en3 is declared here as wire.
verilog.v:27: error: en3 is not a valid l-value in Numerator.
verilog.v:11:      : en3 is declared here as wire.
segmentation fault

How can I fix it ?
Why it gives error?

EDIT:
    I have solved problem as ;

   // I erased that line "input en0, en1, en2, en3; // 11"

 // clock generator  is here

 g_cal A(  1'b0) ;
 g_cal B(  1'b0) ;
 g_cal C(  1'b0) ;
 g_cal D(  1'b0) ;

always @( negedge arc, posedge clk )
/* erasing all those line
 case ( clinic )
    2'b00 : { en3, en2, en1, en0 } = 4'b0001;    // 23
    2'b01 : { en3, en2, en1, en0 } = 4'b0010;    // 24
    2'b10 : { en3, en2, en1, en0 } = 4'b0100;    // 25
    2'b11 : { en3, en2, en1, en0 } = 4'b1000;    // 26
    default : { en3, en2, en1, en0 } = 4'bxxxx;  // 27
  endcase

I will use if and else structure, and calling corresponding instance with 1'b1*/

 // I am trying to change value of en to call corresponding intance with that
//corresponding en value

endmodule


问:
PHP - Compress Image to Meet File Size Limit
I have to upload image files that meet a max width dimension and max file size.

I have the code that checks width size and resizes the image to meet the max image width.

However, when I am saving the file I can set the quality

```<code>imagejpeg( $imgObject , 'resized/50.jpg' , 50 ); //save image and set quality
</code>```

What I would like to do is avoid setting a standard quality, as the images being submitted vary highly from quality and may be low to begin with.

The quality of the image should be set as high as possible without going over the max file size limit.

The only solution I have is to save several versions of the image at varying qualities, check each file size and pick the best one. This works but is very slow and process intensive.

Any suggestions on how this could be done better?

Thanks

答:
Here is a way to achieve that. It does not save a file until it is satisfied that the file size will be lower than the specified maximum.

```<code>$original_file = 'original.jpg';
$resized_file = 'resized.jpg';
$max_file_size = '30000'; // maximum file size, in bytes

$original_image = imagecreatefromjpeg($original_file);

$image_quality = 100;

do {
    $temp_stream = fopen('php://temp', 'w+');
    $saved = imagejpeg($original_image, $temp_stream, $image_quality--);
    rewind($temp_stream);
    $fstat = fstat($temp_stream);
    fclose($temp_stream);

    $file_size = $fstat['size'];
}
while (($file_size > $max_file_size) && ($image_quality >= 0));

if (-1 == $image_quality) {
    echo "Unable to get the file that small. Best I could do was $file_size bytes at image quality 0.\n";
}
else {
    echo "Successfully resized $original_file to $file_size bytes using image quality $image_quality. Resized file saved as $resized_file.\n";
    imagejpeg($original_image, $resized_file, $image_quality + 1);
}
</code>```

This requires no file to be written until you've successfully found the ideal compression ratio.

This loop starts with an $image_quality of 100, then counts downward trying each new value on a temporary in-memory buffer. If gets down to trying 0 and the file would still be too big, it returns an error message. Otherwise, if it gets to a value that works, it reports that and saves the new file using that image quality setting.

If you're feeling adventurous, you could implement a binary search algorithm to find the ideal compression ratio more quickly, but this quick-fix gives the same result, albeit possibly a tad slower.

Body:
I have to upload image files that meet a max width dimension and max file size.

I have the code that checks width size and resizes the image to meet the max image width.

However, when I am saving the file I can set the quality

imagejpeg( $imgObject , 'resized/50.jpg' , 50 ); //save image and set quality

What I would like to do is avoid setting a standard quality, as the images being submitted vary highly from quality and may be low to begin with.

The quality of the image should be set as high as possible without going over the max file size limit.

The only solution I have is to save several versions of the image at varying qualities, check each file size and pick the best one. This works but is very slow and process intensive.

Any suggestions on how this could be done better?

Thanks

Body:
Here is a way to achieve that. It does not save a file until it is satisfied that the file size will be lower than the specified maximum.

$original_file = 'original.jpg';
$resized_file = 'resized.jpg';
$max_file_size = '30000'; // maximum file size, in bytes

$original_image = imagecreatefromjpeg($original_file);

$image_quality = 100;

do {
    $temp_stream = fopen('php://temp', 'w+');
    $saved = imagejpeg($original_image, $temp_stream, $image_quality--);
    rewind($temp_stream);
    $fstat = fstat($temp_stream);
    fclose($temp_stream);

    $file_size = $fstat['size'];
}
while (($file_size > $max_file_size) && ($image_quality >= 0));

if (-1 == $image_quality) {
    echo "Unable to get the file that small. Best I could do was $file_size bytes at image quality 0.\n";
}
else {
    echo "Successfully resized $original_file to $file_size bytes using image quality $image_quality. Resized file saved as $resized_file.\n";
    imagejpeg($original_image, $resized_file, $image_quality + 1);
}

This requires no file to be written until you've successfully found the ideal compression ratio.

This loop starts with an $image_quality of 100, then counts downward trying each new value on a temporary in-memory buffer. If gets down to trying 0 and the file would still be too big, it returns an error message. Otherwise, if it gets to a value that works, it reports that and saves the new file using that image quality setting.

If you're feeling adventurous, you could implement a binary search algorithm to find the ideal compression ratio more quickly, but this quick-fix gives the same result, albeit possibly a tad slower.


问:
Hyperledger Composer - I have a problem starting my business network
I'm trying to start up my business networt. It worked fine before but, after failing to upgrade my network, it doesn't seem to work...

I deleted all the cards that I have and started again from generating the business network but, still doesn't work.

When I try to import the bna file on playground, I get this saying that it is an unsupported file type.

composer network start --networkName medrec --networkVersion 0.0.1 --networkAdmin admin --networkAdminEnrollSecret adminpw --card PeerAdmin@hlfv1 --file networkadmin.card

✖ Starting business network definition. This may take a minute...
  Error: Error trying to start business network. Error: No valid
  responses from any peers. Response from attempted peer comms was an
  error: Error: transaction returned with failure: ReferenceError:
  require is not defined Command failed

答:
Delete all cards and restart Hyperledger Fabric.

This worked for me most of the time, fixing the issue.

Hope this helps.


问:
Matplotlib heatmap for multiple timeseries to show distribution over time
I have n_series recordings with the same frames 0, 1, 2, 3,... and would like to make a 2D contour out of it.

I've found that I can very easily do the following:

```<code>import matplotlib.pyplot as plt
import numpy as np

series_len = 1000
n_series = 10

y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xbins, ybins = np.histogram2d(x, y, bins=20)

plt.contourf(heatmap.T)
plt.show()
</code>```

But since this just gives a 20x20 histogram, I have no idea how my intensities are distributed in the outputted plot (e.g. roughly zero-centered), nor how to fix the ticks.

What I'd like is this ('shopped):

答:
IIUC, did you want something like this:

```<code>import matplotlib.pyplot as plt
import numpy as np

series_len = 1000
n_series = 10

y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xlabels, ylabels = np.histogram2d(x, y, bins=20)

plt.contourf(xlabels[:-1], ylabels[:-1], heatmap.T)
plt.colorbar()
plt.show()
</code>```

Output:

Body:
I have n_series recordings with the same frames 0, 1, 2, 3,... and would like to make a 2D contour out of it.

I've found that I can very easily do the following:

import matplotlib.pyplot as plt
import numpy as np

series_len = 1000
n_series = 10

y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xbins, ybins = np.histogram2d(x, y, bins=20)

plt.contourf(heatmap.T)
plt.show()

But since this just gives a 20x20 histogram, I have no idea how my intensities are distributed in the outputted plot (e.g. roughly zero-centered), nor how to fix the ticks.

What I'd like is this ('shopped):

Body:
IIUC, did you want something like this:

import matplotlib.pyplot as plt
import numpy as np

series_len = 1000
n_series = 10

y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xlabels, ylabels = np.histogram2d(x, y, bins=20)

plt.contourf(xlabels[:-1], ylabels[:-1], heatmap.T)
plt.colorbar()
plt.show()

Output:


问:
SQL Query: Only include PAIRS of rows in query
Im looking to find pairs of rows in a table like below

MS SQL 2012(maybe 2014)

```<code>Ref, Split
1, A
1, B
2, B
3, A
3, B
</code>```

Results

```<code>Ref, Split
1, A
1, B
3, A
3, B
</code>```

pairs of rows are partitioned by 'Ref' ie, 1 and 3 need to be returned, but 2 does not have a pair so should not be returned

I would by default use OVER but i believe this is overkill and not the most effective way of handling this.

What are the alternatives

答:
Why not use a self-join and put the results in one row?

```<code>select t1.ref, t1.split, t2.split
from t t1 join
     t t2
     on t1.ref = t2.ref;
</code>```

Or if you want the original rows use exists:

```<code>select t.*
from t
where exists (select 1 from t t2 where t2.ref = t.ref and t2.split <> t.split);
</code>```

Body:
Im looking to find pairs of rows in a table like below

MS SQL 2012(maybe 2014)

Ref, Split
1, A
1, B
2, B
3, A
3, B

Results

Ref, Split
1, A
1, B
3, A
3, B

pairs of rows are partitioned by 'Ref' ie, 1 and 3 need to be returned, but 2 does not have a pair so should not be returned

I would by default use OVER but i believe this is overkill and not the most effective way of handling this.

What are the alternatives

Body:
Why not use a self-join and put the results in one row?

select t1.ref, t1.split, t2.split
from t t1 join
     t t2
     on t1.ref = t2.ref;

Or if you want the original rows use exists:

select t.*
from t
where exists (select 1 from t t2 where t2.ref = t.ref and t2.split <> t.split);


问:
Download video from s3, works in Android and Desktop, but not in iOS
My website creates "presigned-url" to download files from Amazon S3.
In Desktop and Android this URL starts download perfectly using Chrome or other browser.

```<code>https://s3.sa-east-1.amazonaws.com/videos.cinemedsite.com.br/888888/888888_00000000000_20180808_235040.mp4?AWSAccessKeyId=AKIAJQCURENNFPNNGK6A&Expires=1609383840&Signature=4lYLxgkAIt3xMer%2FPcL%2FAepwbkY%3D
</code>```

But with this same URL on iOS (iPad and iPhone tested), the video just plays in any browser and there's no way to download.
I've tried to download directly from aws console too, no success.

Metadata is already configured as :

```<code>content-disposition: attachment;filename=lixo.mp4
content-type: video/mp4 (already tried application/octet-stream also).
</code>```

Any ideas ?

Thanks in advance!

Marcello

答:
On iOS there is not a user accesable file systems with default download 'folder' as you have on a PC or MAC - i.e. you can't just click a link in the browser and have the file download to it.

With Apps like dropbox you van open a PDF file, for example, in your browser and then click the Share button and choose Dropbox to download to your device. 'Documents', another app available on the appstore, has a built in browser so is worth looking at also.

You can create your own application which will accept a URL, download it and then provide a list or directory of downloaded files. These files will only be visible by the app unless you add some functionality to save them to, for example, the gallery.

There is an AWS SDK available on Github which would be a good place to start if you are using your own app: https://github.com/awslabs/aws-sdk-ios-samples

Body:
My website creates "presigned-url" to download files from Amazon S3.
In Desktop and Android this URL starts download perfectly using Chrome or other browser.

https://s3.sa-east-1.amazonaws.com/videos.cinemedsite.com.br/888888/888888_00000000000_20180808_235040.mp4?AWSAccessKeyId=AKIAJQCURENNFPNNGK6A&Expires=1609383840&Signature=4lYLxgkAIt3xMer%2FPcL%2FAepwbkY%3D

But with this same URL on iOS (iPad and iPhone tested), the video just plays in any browser and there's no way to download.
I've tried to download directly from aws console too, no success.

Metadata is already configured as :

content-disposition: attachment;filename=lixo.mp4
content-type: video/mp4 (already tried application/octet-stream also).

Any ideas ?

Thanks in advance!

Marcello


问:
Openwhisk - passing environment variables to action
Im using NodeJS action in openwhisk.
Is there any way to pass environment variables into whisk so I can read them in my NodeJS action using process.env ?</p>

答:
This is possible but you need to use a custom Docker runtime. The default built-in Node.js runtime does not support this. Apache OpenWhisk uses default action parameters, rather than environment parameters, to pass things like credentials and other application configuration to action code.

If you extend the existing Node.js Docker runtime for Apache OpenWhisk, you can set environment parameters in the build file for the image. This can then be used as the --docker parameter value when creating the action.


问:
Efficiently add multiple lines to file by index
Given an input file data.dat like this one:

```<code># Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9
</code>```

I need to add different comments above each line that starts with an "# aaa" so it looks like this:

```<code># Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9
</code>```

I know a priori the number of "# aaa" comments present in the data.dat file,  but not their positions.

I have a way to do it (see code below) but it is quite complicated and not at all efficient. I need to apply this code to hundreds of large files, so I'm looking for an efficient way to do this.

```<code># Read file
with open("data.dat", mode="r") as f:
    data = f.readlines()

# Indexes of "# aaa" comments
idx = []
for i, line in enumerate(data):
    if line.startswith("# aaa"):
        idx.append(i)

# Insert new comments in their proper positions
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
for i, j in enumerate(idx):
    data.insert(j + i, add_data[i])

# Write final data to file
with open("data_final.dat", mode="w") as f:
    for item in data:
        f.write("{}".format(item))
</code>```

答:
According to Jan-Philip Gehrcke's response here, you should reduce the number of write calls.

To do so you could maybe simply change :

with open("data_final.dat", mode="w") as f:
    for item in data:
        f.write("{}".format(item))
```

<p>to :</p>

<pre class="lang-py prettyprint-override"><code>with open("data_final.dat", mode="w") as f:
    f.write("".join(data))
</code>```

Body:
Given an input file data.dat like this one:

# Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9

I need to add different comments above each line that starts with an "# aaa" so it looks like this:

# Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9

I know a priori the number of "# aaa" comments present in the data.dat file,  but not their positions.

I have a way to do it (see code below) but it is quite complicated and not at all efficient. I need to apply this code to hundreds of large files, so I'm looking for an efficient way to do this.

# Read file
with open("data.dat", mode="r") as f:
    data = f.readlines()

# Indexes of "# aaa" comments
idx = []
for i, line in enumerate(data):
    if line.startswith("# aaa"):
        idx.append(i)

# Insert new comments in their proper positions
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
for i, j in enumerate(idx):
    data.insert(j + i, add_data[i])

# Write final data to file
with open("data_final.dat", mode="w") as f:
    for item in data:
        f.write("{}".format(item))

Body:
According to Jan-Philip Gehrcke's response here, you should reduce the number of write calls.

To do so you could maybe simply change :

with open("data_final.dat", mode="w") as f:
    for item in data:
        f.write("{}".format(item))

to :

with open("data_final.dat", mode="w") as f:
    f.write("".join(data))


问:
How to receive KeyDown events in winforms
I want to receive KeyDown events when a specific keyboard key is pressed to drive an arduino based rc vehicle using a winforms application. The vehicle is supposed to move when I press specific buttons on keyboard such as W,A,S,D but I am unable to do so and am looking for some advice.

I have tried driving the vehicle by pressing a Button control in and it worked fine but its difficult to control by clicking on buttons so I thought of using keyboard keys for driving it but I am unable to do so. the code I am using is attached.

```<code>  private void connect_Click(object sender, EventArgs e)
  {
        comPort = new SerialPort();
        comPort.PortName = "COM3";
        comPort.BaudRate = 9600;
        comPort.DataBits = 8;
        comPort.StopBits = StopBits.One;
        comPort.Parity = Parity.None;
        comPort.Open();
        textBox1.Text = "Connected";
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode.ToString() == "W")
        {
            pictureBox1.Visible = true;
            if (!forward)
            {
                forward = true;
                comPort.WriteLine("F");

            }
        }
        else if (e.KeyCode.ToString() == "S")
        {
            pictureBox2.Visible = true;
            if (!backward)
            {
                backward = true;
                comPort.WriteLine("B");

            }
        }
        ...
    }
</code>```

I expect that when I press a key on the keyboard, an image box with an arrow image should appear on screen and the vehicle should move, but it doesn't happens.

答:
You need to set the KeyPreview property of the form to true. You can do this with the designer or by code:

```<code>this.KeyPreview = true;
</code>```

Explanation: KeyPreview indicats if the form will receive key events before the event is passed to the control that has focus (source).

Note: If you press a keyboard key when a control has focus (e.g. a TextBox), the key press will be sent to the form (if KeyPreview is set to true) and to the control. If you want to prevent the control from receiving the key press, you can set e.SuppressKeyPress to true in the KeyDown event:

```<code>private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    e.SuppressKeyPress = true;
}
</code>```

Body:
I want to receive KeyDown events when a specific keyboard key is pressed to drive an arduino based rc vehicle using a winforms application. The vehicle is supposed to move when I press specific buttons on keyboard such as W,A,S,D but I am unable to do so and am looking for some advice.

I have tried driving the vehicle by pressing a Button control in and it worked fine but its difficult to control by clicking on buttons so I thought of using keyboard keys for driving it but I am unable to do so. the code I am using is attached.

  private void connect_Click(object sender, EventArgs e)
  {
        comPort = new SerialPort();
        comPort.PortName = "COM3";
        comPort.BaudRate = 9600;
        comPort.DataBits = 8;
        comPort.StopBits = StopBits.One;
        comPort.Parity = Parity.None;
        comPort.Open();
        textBox1.Text = "Connected";
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode.ToString() == "W")
        {
            pictureBox1.Visible = true;
            if (!forward)
            {
                forward = true;
                comPort.WriteLine("F");

            }
        }
        else if (e.KeyCode.ToString() == "S")
        {
            pictureBox2.Visible = true;
            if (!backward)
            {
                backward = true;
                comPort.WriteLine("B");

            }
        }
        ...
    }

I expect that when I press a key on the keyboard, an image box with an arrow image should appear on screen and the vehicle should move, but it doesn't happens.

Body:
You need to set the KeyPreview property of the form to true. You can do this with the designer or by code:

this.KeyPreview = true;

Explanation: KeyPreview indicats if the form will receive key events before the event is passed to the control that has focus (source).

Note: If you press a keyboard key when a control has focus (e.g. a TextBox), the key press will be sent to the form (if KeyPreview is set to true) and to the control. If you want to prevent the control from receiving the key press, you can set e.SuppressKeyPress to true in the KeyDown event:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    e.SuppressKeyPress = true;
}


问:
Find mismatching files in two folders with bash
I have two folders - FolderA and FolderB - each containing thousands of files that should be named exactly the same before the extension.  One folder contains files with .jpg extension and the other with .txt extension.

My objective is to find any files that are in one but not in the other.  So for example if FolderA contains:

```<code>foo.jpg
bar.jpg
baz.jpg
</code>```

and FolderB contains:

```<code>foo.txt
baz.txt
qux.txt
</code>```

The script should return:

```<code>FolderA/bar.jpg
FolderB/qux.txt
</code>```

How would it be possible with bash to create such an output by inputting two separate directories ?  I was hoping to somehow modify the diff command which would give the Only in ... output but in this case since the extensions are different, diff would output all files

```<code>diff -rq FolderA FolderB
</code>```

答:
If your output of diff -rq is good, but you just want it formatted differently, you can use sed to change the output:

```<code>diff -rq dir1 dir2 | sed 's/Only in //;s/: /\//' | sort
</code>```

That is assuming your directories do'nt have : (colon-space) in their name.

Body:
I have two folders - FolderA and FolderB - each containing thousands of files that should be named exactly the same before the extension.  One folder contains files with .jpg extension and the other with .txt extension.

My objective is to find any files that are in one but not in the other.  So for example if FolderA contains:

foo.jpg
bar.jpg
baz.jpg

and FolderB contains:

foo.txt
baz.txt
qux.txt

The script should return:

FolderA/bar.jpg
FolderB/qux.txt

How would it be possible with bash to create such an output by inputting two separate directories ?  I was hoping to somehow modify the diff command which would give the Only in ... output but in this case since the extensions are different, diff would output all files

diff -rq FolderA FolderB

Body:
If your output of diff -rq is good, but you just want it formatted differently, you can use sed to change the output:

diff -rq dir1 dir2 | sed 's/Only in //;s/: /\//' | sort

That is assuming your directories do'nt have : (colon-space) in their name.