问:
How to make a derived table in Django?
We are developing a feature that selects from the main table and assembles with dynamic attributes through left outer join.

As an example, see the below snippet for filtering the QuerySet. We intend to filter the main table (transaction) and narrow the scope so that the rest operations only apply to a smaller subset of data.

transaction = Transaction.active_objects.filter(
    product_id=product_id
).order_by('-id').all()[27000:27020]
```
<p>However, Django places the <code>WHERE</code> clause at the rear of the SQL query. As a result, the <strong>MariaDB v10.5</strong> database performs all the <code>left outer join</code> operators on the comprehensive data set before it applies the filtering condition. So, the test took nearly 20 seconds running time.</p>
<p>We are not sure if the DBMS can optimize the execution plan. But with a hand-written improvement to the SQL query, we reduced the running time to instant.</p>
<p>The change was to explicitly make a <strong>"Derived"</strong> table. In this way, we forced the query to narrow the scope to one page worth of data before assembling the expensive <code>left outer join</code> parts. See the SQL snippet below for selecting the <strong>Derived</strong> table.</p>
<pre class="lang-sql prettyprint-override"><code>...
from
(
  select * from
  `app_transaction`
  where
    (not `app_transaction`.`rec_del`
      and `app_transaction`.`product_id` = __PRODUCT_ID__)
  order by
    `app_transaction`.`id` desc
  limit 20 OFFSET 27000
) as app_transaction
...
</code>```

Our Question:

How to implement the hand-written improvement within the Django framework, preferably not raw query? We highly appreciate any hints and suggestions.

Also, we want to narrow it down to a smaller data set before proceeding to the more expensive part of computing, so we are open to other ideas that can serve the same purpose. For example, sending a hint to the DBMS's optimization to move the filtering up, etc.

Technical Details:

The original SQL query generated by Django ORM, taking nearly 20 seconds on our test setting (including the computer and size of the data set):

select
  `app_transaction`.`id`,
  `app_transaction`.`product_id`,
  -- ... a few more native columns of the `transaction` table
  eav_firstname.`value_text` as `eav_firstname`,
  -- ... 20+ more EAV attributes assembled by the left outer join operations
from
  `app_transaction`
left outer join `eav_value` eav_firstname on
  (`app_transaction`.`id` = eav_firstname.`entity_id`
    and (eav_firstname.`entity_ct_id` = __CONTENTTYPE_ID__)
      and (eav_firstname.`attribute_id` = __ATTRIBUTE_ID_OF_FIRSTNAME__))
-- ... 20+ more left outer join operations to assemble the EAV attributes
where
  (not `app_transaction`.`rec_del`
    and `app_transaction`.`product_id` = __PRODUCT_ID__)
order by
  `app_transaction`.`id` desc
limit 20 OFFSET 27000
;
```
<ul>
<li>The hand-improved SQL query, taking less than one-second running time for the same setting as above:</li>
</ul>
<pre class="lang-sql prettyprint-override"><code>select
  `app_transaction`.`id`,
  `app_transaction`.`product_id`,
  -- ... a few more native columns of the `transaction` table
  eav_firstname.`value_text` as `eav_firstname`,
  -- ... 20+ more EAV attributes assembled by the left outer join operations
from
(
  select * from
  `app_transaction`
  where
    (not `app_transaction`.`rec_del`
      and `app_transaction`.`product_id` = __PRODUCT_ID__)
  order by
    `app_transaction`.`id` desc
  limit 20 OFFSET 27000
) as app_transaction
left outer join `eav_value` eav_firstname on
  (`app_transaction`.`id` = eav_firstname.`entity_id`
    and (eav_firstname.`entity_ct_id` = __CONTENTTYPE_ID__)
      and (eav_firstname.`attribute_id` = __ATTRIBUTE_ID_OF_FIRSTNAME__))
-- ... 20+ more left outer join operations to assemble the EAV attributes
;
</code>```

Tentative thoughts about SQL optimization:

We previously added the "mariadb-10.5" tag to this post but decided to remove the tag after analyzing the DBMS's optimization. So, please see a brief of the intuitions below.

In the application's context, an entity has one, and only one match on a specific attribute's EAV value, so we know it is logically safe to filter before the joins.

However, the database engine does not know the same details. As a general one-to-many relation, an entity can have none or multiple matches on the attribute's EAV value. So, without the number of joined rows, pagination will produce wrong results by limit 20 OFFSET 27000 on the entity table.

The database did not cause this performance issue, and the DBMS worked as expected in SQL optimization. Therefore, we removed the database tag to focus on the Python side.

The software configurations:

Component
Version

Python
v3.7

Django
v3.1

MariaDB
v10.5

Title: How to make a derived table in Django?

Body:
We are developing a feature that selects from the main table and assembles with dynamic attributes through left outer join.

As an example, see the below snippet for filtering the QuerySet. We intend to filter the main table (transaction) and narrow the scope so that the rest operations only apply to a smaller subset of data.

transaction = Transaction.active_objects.filter(
    product_id=product_id
).order_by('-id').all()[27000:27020]

However, Django places the WHERE clause at the rear of the SQL query. As a result, the MariaDB v10.5 database performs all the left outer join operators on the comprehensive data set before it applies the filtering condition. So, the test took nearly 20 seconds running time.

We are not sure if the DBMS can optimize the execution plan. But with a hand-written improvement to the SQL query, we reduced the running time to instant.

The change was to explicitly make a "Derived" table. In this way, we forced the query to narrow the scope to one page worth of data before assembling the expensive left outer join parts. See the SQL snippet below for selecting the Derived table.

...
from
(
  select * from
  `app_transaction`
  where
    (not `app_transaction`.`rec_del`
      and `app_transaction`.`product_id` = __PRODUCT_ID__)
  order by
    `app_transaction`.`id` desc
  limit 20 OFFSET 27000
) as app_transaction
...

Our Question:

How to implement the hand-written improvement within the Django framework, preferably not raw query? We highly appreciate any hints and suggestions.

Also, we want to narrow it down to a smaller data set before proceeding to the more expensive part of computing, so we are open to other ideas that can serve the same purpose. For example, sending a hint to the DBMS's optimization to move the filtering up, etc.

Technical Details:

The original SQL query generated by Django ORM, taking nearly 20 seconds on our test setting (including the computer and size of the data set):

select
  `app_transaction`.`id`,
  `app_transaction`.`product_id`,
  -- ... a few more native columns of the `transaction` table
  eav_firstname.`value_text` as `eav_firstname`,
  -- ... 20+ more EAV attributes assembled by the left outer join operations
from
  `app_transaction`
left outer join `eav_value` eav_firstname on
  (`app_transaction`.`id` = eav_firstname.`entity_id`
    and (eav_firstname.`entity_ct_id` = __CONTENTTYPE_ID__)
      and (eav_firstname.`attribute_id` = __ATTRIBUTE_ID_OF_FIRSTNAME__))
-- ... 20+ more left outer join operations to assemble the EAV attributes
where
  (not `app_transaction`.`rec_del`
    and `app_transaction`.`product_id` = __PRODUCT_ID__)
order by
  `app_transaction`.`id` desc
limit 20 OFFSET 27000
;

The hand-improved SQL query, taking less than one-second running time for the same setting as above:

select
  `app_transaction`.`id`,
  `app_transaction`.`product_id`,
  -- ... a few more native columns of the `transaction` table
  eav_firstname.`value_text` as `eav_firstname`,
  -- ... 20+ more EAV attributes assembled by the left outer join operations
from
(
  select * from
  `app_transaction`
  where
    (not `app_transaction`.`rec_del`
      and `app_transaction`.`product_id` = __PRODUCT_ID__)
  order by
    `app_transaction`.`id` desc
  limit 20 OFFSET 27000
) as app_transaction
left outer join `eav_value` eav_firstname on
  (`app_transaction`.`id` = eav_firstname.`entity_id`
    and (eav_firstname.`entity_ct_id` = __CONTENTTYPE_ID__)
      and (eav_firstname.`attribute_id` = __ATTRIBUTE_ID_OF_FIRSTNAME__))
-- ... 20+ more left outer join operations to assemble the EAV attributes
;

Tentative thoughts about SQL optimization:

We previously added the "mariadb-10.5" tag to this post but decided to remove the tag after analyzing the DBMS's optimization. So, please see a brief of the intuitions below.

In the application's context, an entity has one, and only one match on a specific attribute's EAV value, so we know it is logically safe to filter before the joins.

However, the database engine does not know the same details. As a general one-to-many relation, an entity can have none or multiple matches on the attribute's EAV value. So, without the number of joined rows, pagination will produce wrong results by limit 20 OFFSET 27000 on the entity table.

The database did not cause this performance issue, and the DBMS worked as expected in SQL optimization. Therefore, we removed the database tag to focus on the Python side.

The software configurations:

Component
Version

Python
v3.7

Django
v3.1

MariaDB
v10.5


来源: stackexchange

问:
Runtime Error: R_USER not defined (rpy2), even when it's defined in environment variable
I am a brand new Jupyter Notebook user. I've been trying to run R and Python from the same Notebook as I want to use some arcgis funtions through python and rest of the data analysis in R. I have followed all the steps mentioned here - How to program with Python and R in the same Jupyter notebook

After completing all the steps I went back and tried to run the following in Jupyter Notebook

```<code>%load_ext rpy2.ipython
</code>```

It throws a long error code that ends with "RuntimeError: R_USER not defined."

I have searched, and every result leads me to changing the environmental variable like this one -
How to set environment variable R_User? And how to get module winreg?

I have already done that. These are some screenshot

At this point, I'm not really sure what else I can do. Has anyone come across this? Any direction would be helpful.

The detailed error message if anyone is interested

```<code>---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-24-da667892317d> in <module>
----> 1 get_ipython().run_line_magic('load_ext', 'rpy2.ipython')
      2
      3 ##you only have to run it once. Takes a while to run. So, if this step has once been completed on your machine, feel free to comment out, or not run this cell

~\Anaconda3\envs\avenue\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2342                 kwargs['local_ns'] = self.get_local_scope(stack_depth)
   2343             with self.builtin_trap:
-> 2344                 result = fn(*args, **kwargs)
   2345             return result
   2346

~\Anaconda3\envs\avenue\lib\site-packages\decorator.py in fun(*args, **kw)
    230             if not kwsyntax:
    231                 args, kw = fix(args, kw, sig)
--> 232             return caller(func, *(extras + args), **kw)
    233     fun.__name__ = func.__name__
    234     fun.__doc__ = func.__doc__

~\Anaconda3\envs\avenue\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188
    189         if callable(arg):

~\Anaconda3\envs\avenue\lib\site-packages\IPython\core\magics\extension.py in load_ext(self, module_str)
     31         if not module_str:
     32             raise UsageError('Missing module name.')
---> 33         res = self.shell.extension_manager.load_extension(module_str)
     34
     35         if res == 'already loaded':

~\Anaconda3\envs\avenue\lib\site-packages\IPython\core\extensions.py in load_extension(self, module_str)
     78             if module_str not in sys.modules:
     79                 with prepended_to_syspath(self.ipython_extension_dir):
---> 80                     mod = import_module(module_str)
     81                     if mod.__file__.startswith(self.ipython_extension_dir):
     82                         print(("Loading extensions from {dir} is deprecated. "

~\Anaconda3\envs\avenue\lib\importlib\__init__.py in import_module(name, package)
    125                 break
    126             level += 1
--> 127     return _bootstrap._gcd_import(name[level:], package, level)
    128
    129

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap.py in _gcd_import(name, package, level)

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap.py in _find_and_load(name, import_)

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap.py in _find_and_load_unlocked(name, import_)

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap.py in _load_unlocked(spec)

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap_external.py in exec_module(self, module)

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)

~\Anaconda3\envs\avenue\lib\site-packages\rpy2\ipython\__init__.py in <module>
----> 1 from .rmagic import load_ipython_extension

~\Anaconda3\envs\avenue\lib\site-packages\rpy2\ipython\rmagic.py in <module>
     52
     53 import rpy2.rinterface as ri
---> 54 import rpy2.robjects as ro
     55 import rpy2.robjects.packages as rpacks
     56 from rpy2.robjects.conversion import (Converter,

~\Anaconda3\envs\avenue\lib\site-packages\rpy2\robjects\__init__.py in <module>
     17 import rpy2.rlike.container as rlc
     18
---> 19 from rpy2.robjects.robject import RObjectMixin, RObject
     20 from rpy2.robjects.vectors import (BoolVector,
     21                                    IntVector,

~\Anaconda3\envs\avenue\lib\site-packages\rpy2\robjects\robject.py in <module>
      4 import rpy2.rinterface
      5
----> 6 rpy2.rinterface.initr()
      7
      8 from . import conversion

~\Anaconda3\envs\avenue\lib\site-packages\rpy2\rinterface\__init__.py in initr(r_preservehash)
    206   """"Wrapper around rpy2.rinterface._rinterface.initr()."""
    207   atexit.register(endr, 0)
--> 208   _initr(r_preservehash=r_preservehash)
    209
    210 # def cleanUp(saveact, status, runlast):

RuntimeError: R_USER not defined.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am a brand new Jupyter Notebook user. I've been trying to run R and Python from the same Notebook as I want to use some arcgis funtions through python and rest of the data analysis in R. I have followed all the steps mentioned here - How to program with Python and R in the same Jupyter notebook

After completing all the steps I went back and tried to run the following in Jupyter Notebook

%load_ext rpy2.ipython

It throws a long error code that ends with "RuntimeError: R_USER not defined."

I have searched, and every result leads me to changing the environmental variable like this one -
How to set environment variable R_User? And how to get module winreg?

I have already done that. These are some screenshot

At this point, I'm not really sure what else I can do. Has anyone come across this? Any direction would be helpful.

The detailed error message if anyone is interested

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-24-da667892317d> in <module>
----> 1 get_ipython().run_line_magic('load_ext', 'rpy2.ipython')
      2
      3 ##you only have to run it once. Takes a while to run. So, if this step has once been completed on your machine, feel free to comment out, or not run this cell

~\Anaconda3\envs\avenue\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2342                 kwargs['local_ns'] = self.get_local_scope(stack_depth)
   2343             with self.builtin_trap:
-> 2344                 result = fn(*args, **kwargs)
   2345             return result
   2346

~\Anaconda3\envs\avenue\lib\site-packages\decorator.py in fun(*args, **kw)
    230             if not kwsyntax:
    231                 args, kw = fix(args, kw, sig)
--> 232             return caller(func, *(extras + args), **kw)
    233     fun.__name__ = func.__name__
    234     fun.__doc__ = func.__doc__

~\Anaconda3\envs\avenue\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188
    189         if callable(arg):

~\Anaconda3\envs\avenue\lib\site-packages\IPython\core\magics\extension.py in load_ext(self, module_str)
     31         if not module_str:
     32             raise UsageError('Missing module name.')
---> 33         res = self.shell.extension_manager.load_extension(module_str)
     34
     35         if res == 'already loaded':

~\Anaconda3\envs\avenue\lib\site-packages\IPython\core\extensions.py in load_extension(self, module_str)
     78             if module_str not in sys.modules:
     79                 with prepended_to_syspath(self.ipython_extension_dir):
---> 80                     mod = import_module(module_str)
     81                     if mod.__file__.startswith(self.ipython_extension_dir):
     82                         print(("Loading extensions from {dir} is deprecated. "

~\Anaconda3\envs\avenue\lib\importlib\__init__.py in import_module(name, package)
    125                 break
    126             level += 1
--> 127     return _bootstrap._gcd_import(name[level:], package, level)
    128
    129

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap.py in _gcd_import(name, package, level)

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap.py in _find_and_load(name, import_)

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap.py in _find_and_load_unlocked(name, import_)

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap.py in _load_unlocked(spec)

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap_external.py in exec_module(self, module)

~\Anaconda3\envs\avenue\lib\importlib\_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)

~\Anaconda3\envs\avenue\lib\site-packages\rpy2\ipython\__init__.py in <module>
----> 1 from .rmagic import load_ipython_extension

~\Anaconda3\envs\avenue\lib\site-packages\rpy2\ipython\rmagic.py in <module>
     52
     53 import rpy2.rinterface as ri
---> 54 import rpy2.robjects as ro
     55 import rpy2.robjects.packages as rpacks
     56 from rpy2.robjects.conversion import (Converter,

~\Anaconda3\envs\avenue\lib\site-packages\rpy2\robjects\__init__.py in <module>
     17 import rpy2.rlike.container as rlc
     18
---> 19 from rpy2.robjects.robject import RObjectMixin, RObject
     20 from rpy2.robjects.vectors import (BoolVector,
     21                                    IntVector,

~\Anaconda3\envs\avenue\lib\site-packages\rpy2\robjects\robject.py in <module>
      4 import rpy2.rinterface
      5
----> 6 rpy2.rinterface.initr()
      7
      8 from . import conversion

~\Anaconda3\envs\avenue\lib\site-packages\rpy2\rinterface\__init__.py in initr(r_preservehash)
    206   """"Wrapper around rpy2.rinterface._rinterface.initr()."""
    207   atexit.register(endr, 0)
--> 208   _initr(r_preservehash=r_preservehash)
    209
    210 # def cleanUp(saveact, status, runlast):

RuntimeError: R_USER not defined.


问:
I can't access to my port 3000 form browser to docker
I have a dockerized Application with laravel, nginx and mysql. These are the docker-compose and dockerfiles

docker-compose.yaml

```<code>version: '3.8'
services:

  # Application
  app:
    container_name: app
    build:
      context: .
      dockerfile: app.dockerfile
    working_dir: /var/www
    volumes:
      - ./:/var/www
    depends_on:
      - "db"

  # Web Server
  web:
    container_name: web
    build:
      context: .
      dockerfile: web.dockerfile
    working_dir: /var/www
    volumes:
      - ./:/var/www
    depends_on:
      - "app"
    ports:
      - "80:80"
      - "3000:3000"

  # Database
  db:
    container_name: db
    image: mysql:8.0
    volumes:
      - dbdata:/var/lib/mysql
    environment:
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
    ports:
      - "3306:3306"

volumes:
  dbdata:

</code>```

web.dockerfile

```<code>FROM nginx:1.21

COPY nginx/conf.d/app.conf /etc/nginx/conf.d/default.conf

RUN ln -sf /dev/stdout /var/log/nginx/access.log \
   && ln -sf /dev/stderr /var/log/nginx/error.log

EXPOSE 3000

</code>```

app.dockerfile

```<code>FROM php:8.1-fpm

# Set working directory
WORKDIR /var/www

RUN apt-get update && apt-get install -y  \
    libfreetype6-dev \
    libjpeg-dev \
    libpng-dev \
    libwebp-dev \
    git curl gnupg \
    --no-install-recommends \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install pdo_mysql -j$(nproc) gd

ENV NODE_VERSION=18.12.1
RUN apt install -y curl
ENV NVM_DIR=/root/.nvm
RUN mkdir "/root/.nvm"
RUN curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash
RUN . "$NVM_DIR/nvm.sh" && nvm install ${NODE_VERSION}
RUN . "$NVM_DIR/nvm.sh" && nvm use v${NODE_VERSION}
RUN . "$NVM_DIR/nvm.sh" && nvm alias default v${NODE_VERSION}
ENV PATH="/root/.nvm/versions/node/v${NODE_VERSION}/bin/:${PATH}"
RUN node --version
RUN npm --version

RUN npm install -g yarn

# Copy existing application directory contents
COPY . /var/www

COPY --from=composer /usr/bin/composer /usr/bin/composer

USER $user

RUN cd client && yarn

</code>```

When I run the docker-compose up -d and it finished I can access to localhost url. Now if I go to docker exec -it app bash and inside the container I change the directory cd client and run npm run dev it compiles and show me that the app is running in localhost:3000.

NOTE: In client I have a nextjs application

```<code>root@7ff9ccc2712e:/var/www/client# npm run dev

> next-file-now@0.1.0 dev
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Loaded env from /var/www/client/.env.local
event - compiled client and server successfully in 1794 ms (161 modules)
</code>```

But if I try to access from browser to http://localhost:3000 I can't access

I tried the EXPOSE 3000 Port, but it is still inaccessible. I'm expecting to access to the next js application

Body:
I have a dockerized Application with laravel, nginx and mysql. These are the docker-compose and dockerfiles

docker-compose.yaml

version: '3.8'
services:

  # Application
  app:
    container_name: app
    build:
      context: .
      dockerfile: app.dockerfile
    working_dir: /var/www
    volumes:
      - ./:/var/www
    depends_on:
      - "db"

  # Web Server
  web:
    container_name: web
    build:
      context: .
      dockerfile: web.dockerfile
    working_dir: /var/www
    volumes:
      - ./:/var/www
    depends_on:
      - "app"
    ports:
      - "80:80"
      - "3000:3000"

  # Database
  db:
    container_name: db
    image: mysql:8.0
    volumes:
      - dbdata:/var/lib/mysql
    environment:
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
    ports:
      - "3306:3306"

volumes:
  dbdata:

web.dockerfile

FROM nginx:1.21

COPY nginx/conf.d/app.conf /etc/nginx/conf.d/default.conf

RUN ln -sf /dev/stdout /var/log/nginx/access.log \
   && ln -sf /dev/stderr /var/log/nginx/error.log

EXPOSE 3000

app.dockerfile

FROM php:8.1-fpm

# Set working directory
WORKDIR /var/www

RUN apt-get update && apt-get install -y  \
    libfreetype6-dev \
    libjpeg-dev \
    libpng-dev \
    libwebp-dev \
    git curl gnupg \
    --no-install-recommends \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install pdo_mysql -j$(nproc) gd

ENV NODE_VERSION=18.12.1
RUN apt install -y curl
ENV NVM_DIR=/root/.nvm
RUN mkdir "/root/.nvm"
RUN curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash
RUN . "$NVM_DIR/nvm.sh" && nvm install ${NODE_VERSION}
RUN . "$NVM_DIR/nvm.sh" && nvm use v${NODE_VERSION}
RUN . "$NVM_DIR/nvm.sh" && nvm alias default v${NODE_VERSION}
ENV PATH="/root/.nvm/versions/node/v${NODE_VERSION}/bin/:${PATH}"
RUN node --version
RUN npm --version

RUN npm install -g yarn

# Copy existing application directory contents
COPY . /var/www

COPY --from=composer /usr/bin/composer /usr/bin/composer

USER $user

RUN cd client && yarn

When I run the docker-compose up -d and it finished I can access to localhost url. Now if I go to docker exec -it app bash and inside the container I change the directory cd client and run npm run dev it compiles and show me that the app is running in localhost:3000.

NOTE: In client I have a nextjs application

root@7ff9ccc2712e:/var/www/client# npm run dev

> next-file-now@0.1.0 dev
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Loaded env from /var/www/client/.env.local
event - compiled client and server successfully in 1794 ms (161 modules)

But if I try to access from browser to http://localhost:3000 I can't access

I tried the EXPOSE 3000 Port, but it is still inaccessible. I'm expecting to access to the next js application


问:
cocos 2d Problem with debugging helloworld project (visual studio)
I am new to cocos2d and visual studio as well, so I basically just wanna debug the helloWorld project and I get this message :
enter image description here

When I click yes I get this message:
enter image description here

the images might seem weird becasue I used an image translator because the messages are shown in french in my computerMy first try with debbuging HelloWorld went well, then i deleted the helloworld.cpp and helloworld.h and tried new code and debbuged and it showed this message now im trying to create new projects and still same problem. here are the steps I did to create the project:
command prompt → cd desktop → cocos new projectname -l cpp .p com.epicgames.
then when the folder got created in my desktop i noticed it has a win10 and a win32 (unlike my first try it only had win32) so I dont know if thats part of the problem.
then I typed cd in command prompt and dragged the win32 folder and wrote this
cmake … -G “Visual Studio 17 2022” -Awin32
I saw this from a tutorial of sonarsystems channel, when I open the game sln file I get this in my visual studio ( in the solution explorer):
enter image description here

the images might seem weird becasue I used an image translator because the messages are shown in french in my computerunlike sonarsystems they get this :

enter image description here

Please help im confused, thank you

(the images might seem weird becasue I used an image translator because the messages are shown in french in my computer)


问:
Special chars separate words for "suggestions"
Im new to VS Code and i would like to know if its possible to fix the problem i met.
It seems like special chars are separating words for "suggestions" and its really annoying.

Here u can see that it suggests me only the first part before - character.

Is it possible to ignore special chars for "suggestions"?


问:
Uncaught SyntaxError: "undefined" is not valid JSON
i learning react and the error "Uncaught SyntaxError: "undefined" is not valid JSON" appeared

this is the part of the code that involves JSON(two files):

1* file:

```<code>const register = async (data) => {

    const config = requestConfig("POST", data)

    try {

        const res = await fetch(api + "/users/register", config).then((res) => res.json()).catch((err) => err);

        if(res) {
            localStorage.setItem("user", JSON.stringify(res))

        };

    } catch (error) {
        console.log(error)
    };
};
</code>```

import 1* file in 2* and continue:

```<code>const user = JSON.parse(localStorage.getItem("user"))

const initialState = {
    user: user ? user : null,
    error: false,
    success: false,
    loading: false,
};
</code>```

...

I realized that the error is in the part "JSON.parse(localStorage.getItem("user"))"

with what I researched apparently the creation of the object "user" in trycatch isn't working,
as a beginner in both react and programming, I don't know what to do.

if necessary, analyze the 4 related files: https://codesandbox.io/s/error-bgudd2
(this project has a backend)

thanks, and sorry for the awful english :P

wezetti,

Body:
i learning react and the error "Uncaught SyntaxError: "undefined" is not valid JSON" appeared

this is the part of the code that involves JSON(two files):

1* file:

const register = async (data) => {

    const config = requestConfig("POST", data)

    try {

        const res = await fetch(api + "/users/register", config).then((res) => res.json()).catch((err) => err);

        if(res) {
            localStorage.setItem("user", JSON.stringify(res))

        };

    } catch (error) {
        console.log(error)
    };
};

import 1* file in 2* and continue:

const user = JSON.parse(localStorage.getItem("user"))

const initialState = {
    user: user ? user : null,
    error: false,
    success: false,
    loading: false,
};

...

I realized that the error is in the part "JSON.parse(localStorage.getItem("user"))"

with what I researched apparently the creation of the object "user" in trycatch isn't working,
as a beginner in both react and programming, I don't know what to do.

if necessary, analyze the 4 related files: https://codesandbox.io/s/error-bgudd2
(this project has a backend)

thanks, and sorry for the awful english :P

wezetti,


问:
SSO login fails occasionally
I have a spring boot app that is responsible for authenticating users through an external identity provider. After successful authentication the springboot app redirects the user through 2 redirects to the UI service with the access token (UI is run as a separate service). Now the springboot app responsible for performing backend authentication is running on a kubernetes cluster with 2 replica sets. Sometimes on login, after coming back from the external identity provider I run into a whitelabel error. I think this is because the login request may have been sent from one instance and then come back to another instance and login flow may have been disrupted. How to ensure that a request is sent from one instance and completed from the same instance in the kubernetes cluster?</p>

Title: SSO login fails occasionally


问:
Using pytest for Hardware in Loop Testing
I would like to use pytest for Hardware in Loop Testing.

Basically, with Python and Pytest hardware functionalities are going to be asserted.

My problem is with the structural implementation of the tests:
I would like every tests to be separate (so they can be tested individually), but also that they can be used in a pipeline manner. Example:

```<code>class TestCamera:
    def test_camera_start():
        pass

    def test_photo_captured():
        pass
</code>```

and

```<code>class TestAudio:
    # And so on
</code>```

Everything works fine. But now imagine I want to implement a system test with a runtime. I however want to use the old tests functions that I have written and use them in a pipeline manner. For example:

```<code># system_test.py
while phone_is_booted:
   user_input = get_user_input_over_simulated_screen()
   # Now pass over user input to a list of input testers that run all sequencialy and async in tasks or threads.
</code>```

Are there any frameworks for something like this?

Thanks.

Body:
I would like to use pytest for Hardware in Loop Testing.

Basically, with Python and Pytest hardware functionalities are going to be asserted.

My problem is with the structural implementation of the tests:
I would like every tests to be separate (so they can be tested individually), but also that they can be used in a pipeline manner. Example:

class TestCamera:
    def test_camera_start():
        pass

    def test_photo_captured():
        pass

and

class TestAudio:
    # And so on

Everything works fine. But now imagine I want to implement a system test with a runtime. I however want to use the old tests functions that I have written and use them in a pipeline manner. For example:

# system_test.py
while phone_is_booted:
   user_input = get_user_input_over_simulated_screen()
   # Now pass over user input to a list of input testers that run all sequencialy and async in tasks or threads.

Are there any frameworks for something like this?

Thanks.


问:
Problem with binding a Xamarin Forms iOS library with objective Sharpie
I am currently trying to bind the following iOS SDK to use it in a Xamarin project:
http://github.com/emartech/ios-emarsys-sdk

Android worked, but with iOS I have some issues.

What I have done so far:

I copied the source files into a Static Library Project, build with iOS Simulator and iOS Device was successful (arm64 and x86_64)

I combined the two a files to a Fat Library.

I run objective sharpie to generate the ApiDefinitions.

My problem now is, that the .a files are quite small (only 4kb each) and the ApiDefinition only have 1 header (the default one that was automatically created from the Static Library). All other headers are missing.

Do I have to add them somewhere explicitly? If yes, how?

Thanks in advance!

I tried to copy the files from the subfolders to the main folder but without success.


问:
How to remove error message "please check this box if you want to proceed" in react checkbox, in IE edge (win) with NVDA on?
I did some research on "please check this box if you want to proceed". It is a html5 validation message attached to input field e.g. checkbox

```<code><input
    required maxlength="255" id="information_name" minlength=1 name="information[name]"
    oninvalid="setCustomValidity('Should not be left empty.')"
    oninput="setCustomValidity('')" />
</code>```

we can use oninvalid and oninput to show or hide err

I have a react checkbox, when testing edge IE in windows, with NVDA turn on. When highlight the checkbox the msg: "please check this box if you want to proceed" appearing

edge IE mac and chrome mac, both not have msg "please check this box if you want to proceed"

extra:

Multiple Checkbox - Change Message "Please check this box if you want to proceed"

html5 oninvalid doesn't work after fixed the input field

https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity

Body:
I did some research on "please check this box if you want to proceed". It is a html5 validation message attached to input field e.g. checkbox

<input
    required maxlength="255" id="information_name" minlength=1 name="information[name]"
    oninvalid="setCustomValidity('Should not be left empty.')"
    oninput="setCustomValidity('')" />

we can use oninvalid and oninput to show or hide err

I have a react checkbox, when testing edge IE in windows, with NVDA turn on. When highlight the checkbox the msg: "please check this box if you want to proceed" appearing

edge IE mac and chrome mac, both not have msg "please check this box if you want to proceed"

extra:

Multiple Checkbox - Change Message "Please check this box if you want to proceed"

html5 oninvalid doesn't work after fixed the input field

https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity


问:
Read process output after kill it
I'm executing generate.py using subprocess. The problem is that after killing the process I iterate it but reads nothing. I tried all three solutions from link, but don't work:  https://bugs.python.org/issue3907. I'm assuming then that I'm missing something in generate.py.</p>
```<code># generate.py
while True:
    for id in ['a','b','c','d']:
        sys.stdout.write('%s\n' % id)

# run_process.py
    chars = set()
    process = subprocess.Popen(
        ["python", "generate.py"],
        stdout=subprocess.PIPE,
        env=env)
    time.sleep(2)
    process.kill()
    for char in process.stdout.readlines():
        chars.add(char)
    print(f'chars_set: {chars}')
</code>```

Title: Read process output after kill it

Body:
I'm executing generate.py using subprocess. The problem is that after killing the process I iterate it but reads nothing. I tried all three solutions from link, but don't work:  https://bugs.python.org/issue3907. I'm assuming then that I'm missing something in generate.py.

# generate.py
while True:
    for id in ['a','b','c','d']:
        sys.stdout.write('%s\n' % id)

# run_process.py
    chars = set()
    process = subprocess.Popen(
        ["python", "generate.py"],
        stdout=subprocess.PIPE,
        env=env)
    time.sleep(2)
    process.kill()
    for char in process.stdout.readlines():
        chars.add(char)
    print(f'chars_set: {chars}')


问:
Python issue in Visual Studio Code "TclError" could not open "name of file here" no such file or directory
the issue I'm having is running a script for a Blackjack game that pulls the image of a 52 deck of cards from a file called "cards". I am getting a TclError The file is in the same folder the blackjack.py file is in also. In the program I am importing tkinter. After running my code I get the following.
Blackjack can't find cards/1_heart.png
I looked at the output tab and followed the path to the file that points to a problem area. That did not work.
I found a site (https://jupyterlab-lsp.readthedocs.io/en/latest/Language%20Servers.html) that then said to install the PIL and pylsp. That did not work.
I thought that the script was looking for the cards file in the download folder instead of the relative path in vs code so I deleted that file closed vs code, then restarted my computer. That did not work.
I looked through my code and compared it to the version online, the difference is they are using IntelliJ. The code is the same.
And yes I did pip install the tk library. I verified that I had it.

OS: Windows 11
Program Language: Python 3.11
Framework: Visual Studio Code 1.74.1

Has anyone run into this issue before?


问:
High latency in dart UDP socket streaming
I'm trying to stream audio over a local network with a UDP socket. I have a simple implementation that works, but the latency is very high.
My use case involves speaking into one phone and it playing out another. Ideally, the streaming will be near instantaneous, but I know this is not possible.

Here is the sender side:

```<code> Stream<Uint8List>? stream = await MicStream.microphone(
      sampleRate: 32000,
      audioFormat: AudioFormat.ENCODING_PCM_16BIT,
    );
    RawDatagramSocket.bind(InternetAddress.anyIPv4, port).then((socket) {
      StreamSubscription<List<int>> listener = stream!.listen((sample) async {
        socket.send(sample, InternetAddress(address), port);
      });
    });
</code>```

I grab the microphone data with the mic_stream package and send it over the UDP socket. Next, on the receiving smartphone that plays out the audio:

```<code> FlutterSoundPlayer player = FlutterSoundPlayer();
 await player.openPlayer();
 await player.startPlayerFromStream(
   codec: Codec.pcm16, numChannels: 1, sampleRate: 32000);
 final udpSocket = await RawDatagramSocket.bind(address, port);
 udpSocket.listen((RawSocketEvent event) {
   Uint8List? data = udpSocket.receive()?.data;
   if (data != null) {
     player.foodSink!.add(FoodData(data)); // this plays the audio
   } else {}
});
</code>```

in the player side, I use the flutter_sound package to play the audio.

The problem is that the delay between speaking into one phone and it playing out the other is much to high - sometimes modulating between 500 and 1000 milliseconds, or 0.5 or 1 second.
In my use case, this is MUCH to slow. What can I do to make the latency much better? I've tried researching improving the latency for UDP audio streaming and I haven't found anyone else that is doing it the way I am.

I've tried reducing the sample rate from 44100 to 32000 in hopes of reducing the data load on the socket, and that didn't make much of a difference.

I experimenting with using other audio codecs, but I couldn't find any pub.dev packages that could play from a Stream of data in a codec other than 16-bit PCM. flutter_sound only supports 16 bit PCM.

I even originally made a TCP implementation of this same thing, and the latency was just as bad and got progressively worse as the connection remained open.

As to why the latency is so bad I don't know. 16-bit PCM is a relatively simple codec isn't it?

Should I reduce the buffer size somehow? Currently, the buffer in this implementation is set to 1028. Would reducing the amount of data taken in per sample reduce the latency?

What can I do to make reduce the latency as much as possible? My use case requires more than just a simple VOIP call - think two smartphones in the same room/wifi network. I've been using the Agora SDK to do this, and the results are similar to my TCP implementation - half a second of latency that gets progressively worse. Are there any other alternatives to the Agora SDK that are even faster?

What can I do to improve the latency of sending audio data over a UDP socket in the way that I've done it?

Body:
I'm trying to stream audio over a local network with a UDP socket. I have a simple implementation that works, but the latency is very high.
My use case involves speaking into one phone and it playing out another. Ideally, the streaming will be near instantaneous, but I know this is not possible.

Here is the sender side:

 Stream<Uint8List>? stream = await MicStream.microphone(
      sampleRate: 32000,
      audioFormat: AudioFormat.ENCODING_PCM_16BIT,
    );
    RawDatagramSocket.bind(InternetAddress.anyIPv4, port).then((socket) {
      StreamSubscription<List<int>> listener = stream!.listen((sample) async {
        socket.send(sample, InternetAddress(address), port);
      });
    });

I grab the microphone data with the mic_stream package and send it over the UDP socket. Next, on the receiving smartphone that plays out the audio:

 FlutterSoundPlayer player = FlutterSoundPlayer();
 await player.openPlayer();
 await player.startPlayerFromStream(
   codec: Codec.pcm16, numChannels: 1, sampleRate: 32000);
 final udpSocket = await RawDatagramSocket.bind(address, port);
 udpSocket.listen((RawSocketEvent event) {
   Uint8List? data = udpSocket.receive()?.data;
   if (data != null) {
     player.foodSink!.add(FoodData(data)); // this plays the audio
   } else {}
});

in the player side, I use the flutter_sound package to play the audio.

The problem is that the delay between speaking into one phone and it playing out the other is much to high - sometimes modulating between 500 and 1000 milliseconds, or 0.5 or 1 second.
In my use case, this is MUCH to slow. What can I do to make the latency much better? I've tried researching improving the latency for UDP audio streaming and I haven't found anyone else that is doing it the way I am.

I've tried reducing the sample rate from 44100 to 32000 in hopes of reducing the data load on the socket, and that didn't make much of a difference.

I experimenting with using other audio codecs, but I couldn't find any pub.dev packages that could play from a Stream of data in a codec other than 16-bit PCM. flutter_sound only supports 16 bit PCM.

I even originally made a TCP implementation of this same thing, and the latency was just as bad and got progressively worse as the connection remained open.

As to why the latency is so bad I don't know. 16-bit PCM is a relatively simple codec isn't it?

Should I reduce the buffer size somehow? Currently, the buffer in this implementation is set to 1028. Would reducing the amount of data taken in per sample reduce the latency?

What can I do to make reduce the latency as much as possible? My use case requires more than just a simple VOIP call - think two smartphones in the same room/wifi network. I've been using the Agora SDK to do this, and the results are similar to my TCP implementation - half a second of latency that gets progressively worse. Are there any other alternatives to the Agora SDK that are even faster?

What can I do to improve the latency of sending audio data over a UDP socket in the way that I've done it?


问:
Rails: How to Update One Model from Another Controller (Unpermitted Parameters)
I have a Rails app where, when a new user is created with an email that matches the client_email field in an existing loan, the corresponding loan needs to be updated to belong to that user.

In concordance with SO posts like this and this I tried to implement this by having an update_client method in my loan.rb file like this:

```<code>  def update_client(client_id)
    self.update_attributes(client_id: client_id)
  end
</code>```

So in my registrations_controller.rb I can call the method from there:

```<code>def create
    super

    if @user.persisted?
      Loan.all.each do |loan|
        if @user.email == loan.client_email
          loan.update_client(@user.id)
        end
      end
    end

  end

  def edit
    super

    if @user.persisted?
      Loan.all.each do |loan|
        if @user.email == loan.client_email
          loan.update_client(@user.id)
        end
      end
    end

  end
</code>```

The problem is I'm still getting an unpermitted parameters error in my server log when it comes to the update of the loan:

Unpermitted parameters: :subtitle, :first_name, :last_name, :phone, :confirm_password, :current_client, :buyer, :seller

You can tell that this is after the user is successfully created, but it's still preventing things from running glitch-free.

Can anyone see where I'm going wrong here?

Body:
I have a Rails app where, when a new user is created with an email that matches the client_email field in an existing loan, the corresponding loan needs to be updated to belong to that user.

In concordance with SO posts like this and this I tried to implement this by having an update_client method in my loan.rb file like this:

  def update_client(client_id)
    self.update_attributes(client_id: client_id)
  end

So in my registrations_controller.rb I can call the method from there:

def create
    super

    if @user.persisted?
      Loan.all.each do |loan|
        if @user.email == loan.client_email
          loan.update_client(@user.id)
        end
      end
    end

  end

  def edit
    super

    if @user.persisted?
      Loan.all.each do |loan|
        if @user.email == loan.client_email
          loan.update_client(@user.id)
        end
      end
    end

  end

The problem is I'm still getting an unpermitted parameters error in my server log when it comes to the update of the loan:

Unpermitted parameters: :subtitle, :first_name, :last_name, :phone, :confirm_password, :current_client, :buyer, :seller

You can tell that this is after the user is successfully created, but it's still preventing things from running glitch-free.

Can anyone see where I'm going wrong here?


问:
How do I develop a video codec in C/C++?
How do I develop a video codec in C/C++? What do I need? I'm trying to understand how Video Codec Developers came up with video codecs, and honestly I'm getting nothing out of my reasonings, can someone help me by giving me an beginner-frendly explanation?

I have done some research on video codec development and have learned about some of the basic concepts and techniques involved, such as compression algorithms and video file formats. However, I am still not sure how to put these pieces together to create a functional video codec.

I have tried reading documentation and articles online, as well as studying existing video codecs to get a better understanding of how they work. I have also experimented with some basic coding exercises in C/C++ to improve my skills and get a feel for the language.

However, I am still struggling to understand the overall process and specific steps involved in developing a video codec. I am not sure how to approach the problem or what specific techniques and approaches are commonly used in video codec development.

I was expecting to find more detailed guidance or resources on how to develop a video codec in C/C++, but so far I have been unable to find anything that covers the topic in sufficient depth. I am hoping to get some help or guidance from the community to better understand how to proceed.


问:
onPress actions are not being recognized in Storybook with React Native Web
I have Storybook installed with React Native for Web and the onClick actions are showing up in the actions tab of my browser Storybook server page but the onPress events are not.

devDependencies:

```<code>"@storybook/addon-actions": "^6.5.14",
    "@storybook/addon-essentials": "^6.5.13",
    "@storybook/addon-interactions": "^6.5.13",
    "@storybook/addon-links": "^6.5.13",
    "@storybook/addon-react-native-web": "^0.0.19",
    "@storybook/builder-webpack5": "^6.5.13",
    "@storybook/manager-webpack5": "^6.5.13",
    "@storybook/react": "^6.5.13",
    "@storybook/testing-library": "^0.0.13",
</code>```

preview.js

```<code>export const parameters = {
  actions: { argTypesRegex: /(\w*[oO]nClick\w*)|(\w*[oO]nPress\w*)/ },
}
</code>```

I would just use onClick events but we need to use the same code for mobile devices as well and they can only handle onPress events.

Body:
I have Storybook installed with React Native for Web and the onClick actions are showing up in the actions tab of my browser Storybook server page but the onPress events are not.

devDependencies:

"@storybook/addon-actions": "^6.5.14",
    "@storybook/addon-essentials": "^6.5.13",
    "@storybook/addon-interactions": "^6.5.13",
    "@storybook/addon-links": "^6.5.13",
    "@storybook/addon-react-native-web": "^0.0.19",
    "@storybook/builder-webpack5": "^6.5.13",
    "@storybook/manager-webpack5": "^6.5.13",
    "@storybook/react": "^6.5.13",
    "@storybook/testing-library": "^0.0.13",

preview.js

export const parameters = {
  actions: { argTypesRegex: /(\w*[oO]nClick\w*)|(\w*[oO]nPress\w*)/ },
}

I would just use onClick events but we need to use the same code for mobile devices as well and they can only handle onPress events.


问:
Running Javascript Selenium Tests within a Node Container for Github Actions
I am trying to create a CI/CD automation flow where when code is pushed to github, my selenium based tests automatically run using Docker. I am having trouble getting each piece of my application to communicate to effectively run the tests as I have multiple containers running simultaiously.

Container 1: React application (localhost:8000)
Container 2: Rails backend (localhost:3000)
Container 3: postgres db (localhost:5432)
Container 4: webdriverio/selenium-standalone image (localhost:4444)

Since the React container will have the JS test I believe I need to include a "usingServer" flag to my builder within the test to reference the selenium-standalone image.

```<code>driver = await new webdriver.Builder().setChromeOptions(chromeOptions).forBrowser('chrome').usingServer("http://localhost:4444").build()
</code>```

before trying to reach the react at localhost:8000

```<code>driver.get("localhost:8000")
</code>```

When I try running the tests locally within the docker containers I am getting an ERRCONNREFUSED for 4444 and 3000.

```<code>docker exec react npm run test
</code>```

My main question is how can I create the connection between these containers such that the browser running in port 4444 can reach the react app in port 8000 and backend at port 3000. The ultimate goal is to then get this automation to run on a Github action.

I have exposed the port within the Docker compose file, tried running the tests within Github actions outside of a container, added additional chrome setting such as headless mode.

Body:
I am trying to create a CI/CD automation flow where when code is pushed to github, my selenium based tests automatically run using Docker. I am having trouble getting each piece of my application to communicate to effectively run the tests as I have multiple containers running simultaiously.

Container 1: React application (localhost:8000)
Container 2: Rails backend (localhost:3000)
Container 3: postgres db (localhost:5432)
Container 4: webdriverio/selenium-standalone image (localhost:4444)

Since the React container will have the JS test I believe I need to include a "usingServer" flag to my builder within the test to reference the selenium-standalone image.

driver = await new webdriver.Builder().setChromeOptions(chromeOptions).forBrowser('chrome').usingServer("http://localhost:4444").build()

before trying to reach the react at localhost:8000

driver.get("localhost:8000")

When I try running the tests locally within the docker containers I am getting an ERRCONNREFUSED for 4444 and 3000.

docker exec react npm run test

My main question is how can I create the connection between these containers such that the browser running in port 4444 can reach the react app in port 8000 and backend at port 3000. The ultimate goal is to then get this automation to run on a Github action.

I have exposed the port within the Docker compose file, tried running the tests within Github actions outside of a container, added additional chrome setting such as headless mode.


问:
How to run a batch of commands in parallel in Python (as opposed to run a single command)?
I've learned how to use the joblib package to run a single command in several independent threads as below ("learnIIR" is the function I want to parallelize):

```<code>from joblib import Parallel, delayed
import multiprocessing
from learnIIR import learnIIR # my custom function

num_cores  = multiprocessing.cpu_count() # number of available cores
resultados = Parallel(n_jobs=num_cores)(delayed(learnIIR)(xData[ens,], yData[ens,], \
           dData[ens,], mu, w, algorithm='NLMS') for ens in range(numEns))
</code>```

That's certainly useful but sometimes I need to print messages like "Running simulation number ..." right after starting a thread. In the example above, I need to print one of these messages before running an instance of "learnIIR".

The solution that I've idealized was to define a local function like this one:

```<code>def parLearnIIR (msg, xData, yData, dData, mu, wIni, algorithm='NLMS'):
    print(msg, flush=True)
    return learnIIR (xData, yData, dData, mu, w, algorithm='NLMS')
</code>```

And then run the following parallel code:

```<code>resultados = Parallel(n_jobs=num_cores)(delayed(parLearnIIR)\
           ("Running ensemble "+(str(ens+1))+" of "+str(numEns)+"...", xData[ens,], \
           yData[ens,], dData[ens,], mu, w, algorithm='NLMS') for ens in range(numEns))
</code>```

This obviously works, but I wonder if you could use the Parallel command to run two commands within the scope of each thread, i.e., something like the following pseudocode:

```<code>resultados = Parallel(n_jobs=num_cores)(delayed(parLearnIIR; \
                      print ("Running ensemble "+(str(ens+1))+" of "+str(numEns)+"...")\
           (xData[ens,], yData[ens,], dData[ens,], \
           mu, w, algorithm='NLMS') for ens in range(numEns))
</code>```

Is something like that possible, folks?

Body:
I've learned how to use the joblib package to run a single command in several independent threads as below ("learnIIR" is the function I want to parallelize):

from joblib import Parallel, delayed
import multiprocessing
from learnIIR import learnIIR # my custom function

num_cores  = multiprocessing.cpu_count() # number of available cores
resultados = Parallel(n_jobs=num_cores)(delayed(learnIIR)(xData[ens,], yData[ens,], \
           dData[ens,], mu, w, algorithm='NLMS') for ens in range(numEns))

That's certainly useful but sometimes I need to print messages like "Running simulation number ..." right after starting a thread. In the example above, I need to print one of these messages before running an instance of "learnIIR".

The solution that I've idealized was to define a local function like this one:

def parLearnIIR (msg, xData, yData, dData, mu, wIni, algorithm='NLMS'):
    print(msg, flush=True)
    return learnIIR (xData, yData, dData, mu, w, algorithm='NLMS')

And then run the following parallel code:

resultados = Parallel(n_jobs=num_cores)(delayed(parLearnIIR)\
           ("Running ensemble "+(str(ens+1))+" of "+str(numEns)+"...", xData[ens,], \
           yData[ens,], dData[ens,], mu, w, algorithm='NLMS') for ens in range(numEns))

This obviously works, but I wonder if you could use the Parallel command to run two commands within the scope of each thread, i.e., something like the following pseudocode:

resultados = Parallel(n_jobs=num_cores)(delayed(parLearnIIR; \
                      print ("Running ensemble "+(str(ens+1))+" of "+str(numEns)+"...")\
           (xData[ens,], yData[ens,], dData[ens,], \
           mu, w, algorithm='NLMS') for ens in range(numEns))

Is something like that possible, folks?


问:
Accumulating values without variable assignment
I have the following query that produces the correct result:

declare @out int = 0x00;

select @out |= i
from (
    values
        (1),
        (16),
        (17)
) as x(i);

select [AggregatedValue] = @out;
```

That is, it is an ersatz aggregate function using the bitwise OR operator to accumulate. My question is, is there any language construct that allows for that to be done without having to go through a variable?

Body:
I have the following query that produces the correct result:

declare @out int = 0x00;

select @out |= i
from (
    values
        (1),
        (16),
        (17)
) as x(i);

select [AggregatedValue] = @out;

That is, it is an ersatz aggregate function using the bitwise OR operator to accumulate. My question is, is there any language construct that allows for that to be done without having to go through a variable?


问:
How Shopify backend part in APP with VSCODE
I try to debug shopify backend part, for the frontend, there is no problem i follow

However for the backend part the endpoint remain "Unbound Breakpoint"

This link solutions work well for the frontend part, but not work for the backend!

```<code>https://community.shopify.com/c/shopify-apis-and-sdks/how-to-debug-shopify-react-app/td-p/601673
</code>```

How resolte it ?

Body:
I try to debug shopify backend part, for the frontend, there is no problem i follow

However for the backend part the endpoint remain "Unbound Breakpoint"

This link solutions work well for the frontend part, but not work for the backend!

https://community.shopify.com/c/shopify-apis-and-sdks/how-to-debug-shopify-react-app/td-p/601673

How resolte it ?


问:
Woocommerce - Custom folder per product upload based on ID/SKU
What would be the best method to manage product images so that each product has its own folder in the uploads directory based on either its post id or sku?

Attempted a few different methods via wp all import but feel I need to think outside of the box.


问:
how to suppress or not print this message in mssql
I want hide or suppress final message (stdout)

using ML-Service > Python

using ssms

using this script

```<code>EXECUTE sp_execute_external_script @language N'Python',
@Script = N'
'
</code>```

got a message

```<code>stdout message(s) from external script

Express Edition will continue to be enforced.
</code>```

i want suppress or hide [4. got a message]

what's problem?? and how to solve?? why this message appear?? Want disappear

It just my opinion.. It's not problem to Python maybe MSSQL ML-Service

I tried under case

Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call

https://docs.python.org/3/library/contextlib.html#contextlib.suppress

Body:
I want hide or suppress final message (stdout)

using ML-Service > Python

using ssms

using this script

EXECUTE sp_execute_external_script @language N'Python',
@Script = N'
'

got a message

stdout message(s) from external script

Express Edition will continue to be enforced.

i want suppress or hide [4. got a message]

what's problem?? and how to solve?? why this message appear?? Want disappear

It just my opinion.. It's not problem to Python maybe MSSQL ML-Service

I tried under case

Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call

https://docs.python.org/3/library/contextlib.html#contextlib.suppress


问:
How can I model multiple numerical variables using a mixture of numerical and non-numerical predictors?
I have a dataset that looks like this:

product_name
brand
price_change_percentage
release_year

Toy X
X
20
2001

Toy Y
Y
-12
2020

I would like to use Tensorflow to predict price_change_percentage based on product_name, brand, and release_year.

Which kind of Tensorflow model should I conduct and how can I change the non-numerical product_name and brand values into numerical values? Thank you very much!


问:
Python Pandas - Looking for efficient data reorganization support (MultiIndex)
I am looking for an efficient way to reorganize a larger Pandas DataFrame.

Suppose I have a large DF with data linked to two indexes, as shown below.

Value

Index A
Index B

A
Sample 1
2.3

Sample 2
3.1

B
Sample 1
5.2

Sample 2
1.2

How can I reorganize the data into a 2D array style that still takes into maintains the pairing from the initial multi-index without using a loop iteration and reassigning the values to a new DF?

Index A
Sample 1
Sample 2

A
2.3
5.2

B
3.1
1.2

I attempted to separate the DF by indexes. However due to incomplete and out of order data, transforming the row into column lost its association to the initial index A.

Currently, I am looping through the two indexes and reassociating the values in a new DF. However, the process is incredibly inefficient due to a large data set.

Thank you for your guidance.


问:
Odd behavior in RN trying to center an image
I have an image I wish to center in the display using React Native.  I have to use 'absolute' positioning for this particular image.  At first, to get the image dimensions I am using the following code:

```<code>import React, { Component } from "react";
import { Button, Dimensions, Image, Platform, SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native";  I

const halfWidth = Number((Dimensions.get("window").width) / 2);  //half the device Width
const halfHeight = Number((Dimensions.get("window").height) / 2);  //half the device Height

var logoImage = require('./images/logo_white_128.png');
var logoWidth = 0, logoHeight = 0, logo_X = 0, logo_Y = 0;

export default class Initial extends Component {
constructor(props) {
  super(props);

  this.state = {
  ...
  };
}

  getDims = async() => {

  var source = Image.resolveAssetSource(logoImage);
    //source.width, source.height`

  logoWidth = source.width;
  logoHeight = source.height;
  logo_X = halfWidth - (logoWidth / 2);
  logo_Y = halfHeight - (logoHeight / 2);

  console.log("logoWidth is: " + source.width);
  console.log("logoHeight is: " + source.height);
  console.log("logo_X is: " + logo_X);
  console.log("logo_Y is: " + logo_Y);

  }  //getDims

 componentDidMount() {
 this.getDims();  //call to determine dimension of logo image...
 }  //componentDidMount
</code>```

As can be seen, I am using the 'compoinentDidMount' to call a function which uses the 'Image.resolveAssetSource' to determine the dimensions of the image.  I am also setting the positioning of the X and Y coordinate values in global variables so as properly 'center' the image in the screen display.

In the 'rendering' part:

```<code>  render() {
   return (
   <>

      <SafeAreaView style={styles.container}>
        <ScrollView style={styles.scrollView}>

        ...
        <Image style={styles.img} source={require('./images/logo_white_128.png')} />
        ...

        </ScrollView>
      </SafeAreaView>

   </>
  )

 }  //render

}  //class 'Initial' Component

const styles = StyleSheet.create({
  img: {
    position: "absolute",
    top: logo_X,
    left: logo_Y
  }
});
</code>```

For whatever reason the image is rendered in the 'top left' corner of the screen.  It is not centered as it should be.  Obviously it seems to be setting the image at the "0" position on the X and Y axis.  Therefore for some reason the global variables I stated in the 'getDims' function did not properly reset the variable values.  All of the 'math' is correct.  The console.log statements indicate both the X and Y dimensions for the image are determined correctly...and the 'positioning' variables I set ('logo_X' and 'logo_Y') also seem correct.  If anybody has an idea where the error may be please make a suggestion, it would be greatly appreciated!

Body:
I have an image I wish to center in the display using React Native.  I have to use 'absolute' positioning for this particular image.  At first, to get the image dimensions I am using the following code:

import React, { Component } from "react";
import { Button, Dimensions, Image, Platform, SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native";  I

const halfWidth = Number((Dimensions.get("window").width) / 2);  //half the device Width
const halfHeight = Number((Dimensions.get("window").height) / 2);  //half the device Height

var logoImage = require('./images/logo_white_128.png');
var logoWidth = 0, logoHeight = 0, logo_X = 0, logo_Y = 0;

export default class Initial extends Component {
constructor(props) {
  super(props);

  this.state = {
  ...
  };
}

  getDims = async() => {

  var source = Image.resolveAssetSource(logoImage);
    //source.width, source.height`

  logoWidth = source.width;
  logoHeight = source.height;
  logo_X = halfWidth - (logoWidth / 2);
  logo_Y = halfHeight - (logoHeight / 2);

  console.log("logoWidth is: " + source.width);
  console.log("logoHeight is: " + source.height);
  console.log("logo_X is: " + logo_X);
  console.log("logo_Y is: " + logo_Y);

  }  //getDims

 componentDidMount() {
 this.getDims();  //call to determine dimension of logo image...
 }  //componentDidMount

As can be seen, I am using the 'compoinentDidMount' to call a function which uses the 'Image.resolveAssetSource' to determine the dimensions of the image.  I am also setting the positioning of the X and Y coordinate values in global variables so as properly 'center' the image in the screen display.

In the 'rendering' part:

  render() {
   return (
   <>

      <SafeAreaView style={styles.container}>
        <ScrollView style={styles.scrollView}>

        ...
        <Image style={styles.img} source={require('./images/logo_white_128.png')} />
        ...

        </ScrollView>
      </SafeAreaView>

   </>
  )

 }  //render

}  //class 'Initial' Component

const styles = StyleSheet.create({
  img: {
    position: "absolute",
    top: logo_X,
    left: logo_Y
  }
});

For whatever reason the image is rendered in the 'top left' corner of the screen.  It is not centered as it should be.  Obviously it seems to be setting the image at the "0" position on the X and Y axis.  Therefore for some reason the global variables I stated in the 'getDims' function did not properly reset the variable values.  All of the 'math' is correct.  The console.log statements indicate both the X and Y dimensions for the image are determined correctly...and the 'positioning' variables I set ('logo_X' and 'logo_Y') also seem correct.  If anybody has an idea where the error may be please make a suggestion, it would be greatly appreciated!


问:
How can I update an excel file in sharepoint after read?
Originally I want to use data in one excel file to update data in another excel file in sharepoint, while is split 3 steps.

implemented read excel file in sharepoint site.

implement writing changes to the excel file in sharepoint site.

need to implement reading from an excel and get data then use data to update anther excel.(not in the code below)

I know I should use Office365 API to read excel file in sharepoint.   When I want to use openpyxl to do wb.save (), I got error:OSError: [Errno 22] Invalid argument. I don't know how to put absolute web url in save(). This is different with saving an excel in local drive. frustrated, appreciate it.

```<code>
SP_SITE_URL ='https://companyname.sharepoint.com/sites/SiteName'
relative_url = "/sites/SiteName/Shared Documents/FolderName"

# 1. Create a ClientContext object and use the user’s credentials for authentication
ctx = ClientContext(SP_SITE_URL).with_user_credentials(USERNAME, PASSWORD)
ClientFolder = ctx.web.get_folder_by_server_relative_path(relative_url)
ctx.load(ClientFolder)
ctx.execute_query()

#if you want to get the files in the folder
files = ClientFolder.files
print(files)
ctx.load(files)
ctx.execute_query()

newest_file_url = ''
for myfile in files:

    if myfile.properties["Name"] == 'Filename.xlsx':
        newest_file_url = myfile.properties["ServerRelativeUrl"]
# Get Excel File by newest_file_url identified above
response= File.open_binary(ctx, newest_file_url)
    # save data to BytesIO stream
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0)  # set file object to start

# load Excel file from BytesIO stream
wb = openpyxl.load_workbook(bytes_file_obj)
worksheet= wb['Sheet1']

# updates
row_count = worksheet.max_row
col_count = worksheet.max_column
for i in range(2,row_count+1):
    for j in range(4,col_count + 1):
        cellref=worksheet.cell(i, j)
        cellref.value=datetime.today().strftime('%Y-%m-%d')
# save update to the file
wb.save('https://companyname.sharepoint.com/:x:/r/sites/SiteName/Shared%20Documents/FolderName/Filename.xlsx?d=xxxxx&csf=1&web=1&e=xxx')

</code>```

Body:
Originally I want to use data in one excel file to update data in another excel file in sharepoint, while is split 3 steps.

implemented read excel file in sharepoint site.

implement writing changes to the excel file in sharepoint site.

need to implement reading from an excel and get data then use data to update anther excel.(not in the code below)

I know I should use Office365 API to read excel file in sharepoint.   When I want to use openpyxl to do wb.save (), I got error:OSError: [Errno 22] Invalid argument. I don't know how to put absolute web url in save(). This is different with saving an excel in local drive. frustrated, appreciate it.

SP_SITE_URL ='https://companyname.sharepoint.com/sites/SiteName'
relative_url = "/sites/SiteName/Shared Documents/FolderName"

# 1. Create a ClientContext object and use the user’s credentials for authentication
ctx = ClientContext(SP_SITE_URL).with_user_credentials(USERNAME, PASSWORD)
ClientFolder = ctx.web.get_folder_by_server_relative_path(relative_url)
ctx.load(ClientFolder)
ctx.execute_query()

#if you want to get the files in the folder
files = ClientFolder.files
print(files)
ctx.load(files)
ctx.execute_query()

newest_file_url = ''
for myfile in files:

    if myfile.properties["Name"] == 'Filename.xlsx':
        newest_file_url = myfile.properties["ServerRelativeUrl"]
# Get Excel File by newest_file_url identified above
response= File.open_binary(ctx, newest_file_url)
    # save data to BytesIO stream
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0)  # set file object to start

# load Excel file from BytesIO stream
wb = openpyxl.load_workbook(bytes_file_obj)
worksheet= wb['Sheet1']

# updates
row_count = worksheet.max_row
col_count = worksheet.max_column
for i in range(2,row_count+1):
    for j in range(4,col_count + 1):
        cellref=worksheet.cell(i, j)
        cellref.value=datetime.today().strftime('%Y-%m-%d')
# save update to the file
wb.save('https://companyname.sharepoint.com/:x:/r/sites/SiteName/Shared%20Documents/FolderName/Filename.xlsx?d=xxxxx&csf=1&web=1&e=xxx')


问:
How to convert to BCNF
I am confused on how to convert to BCNF. I believe i have all of my tables in 2NF:

Library (ID, location_name, location_address, phone)

Patron (ID,
first_name, last_name, email, phone, joindate)

Book (ID, genre_id,
name, author_id, ISBN, edition, copynr)

Author(ID,first_name,last_name) Card (cardID, patronId, issue date)

Checkouts(ID, cardID, bookID, patronID, libraryID, date)

Checkins(ID,
cardID, bookID, patronID, libraryID, date)

Im thinking i can elimate the joindate and issuedate

Title: How to convert to BCNF


问:
Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it
hello excuse me sir/ma'am, when i tried to run "python manage.py runserver" on cmd i got this error, but the error appeared since i changed the access data in my python from read_csv into requests from django api, here's the detail: enter image description here

and i can access the data from django by requests already, the problem is when i tried to use the function in my views.py, i got that "Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it" and here's the detail of my views:
enter image description here

the only way that i know how to get rid of the error is, i tried turn off the windows defender firewall, change back the access data in my python from requests django api into the read_csv, or i change the import into comment but it means i can't use the function:
enter image description here

and here's the detail of this error:
enter image description here

i tried make the import into comment, and runserver for check the port and it says "Starting development server at http://127.0.0.1:8000/"
and i checked the requests url in my python, and here's the details:

"rating_url = 'http://127.0.0.1:8000/api/ratings/"
"smartphone_url = 'http://127.0.0.1:8000/api/smartphone/"
i use the both url to retrieve the data from django api into my python ML

i don't know how to solve this error, and i want to make my python can be run into django api views.py, and thanks before guys.


问:
Inserting dynamic HTML table to sqlite database with flask
I am trying to insert a dynamic table built with JS into my HTML document, and the JS adds rows based on the inputs. Is it possible to loop this table into my sqlite database through flask?
`

```<code>    <table id="sampleTable">
      <thead>
        <tbody id="tbody">
          <tr id="trow">
            <td id="sample1"></td>
            <td id="sample2"></td>
            <td id="sample3"></td>
            <td id="sample4"></td>
          </tr>
        </tbody>
      </thead>
    </table>
    <form action="/page/" method="POST">
        <button type="submit">Submit</button>
</code>```

My flask code is:

```<code>@app.route('/page/', methods=['POST','GET'])
if request.method == 'POST':
    connection = sqlite3.connect('sample.db')
    with connection:
sample1 = session['sample1']
sample2 = session['sample2']
sample3 = session['sample3']
sample4 = session['sample4']
cursor.execute("""
insert into sample_table (
sample1, sample2, sample3, sample4)value(?,?,?,?)""",
(sample1, sample2, sample3, sample4))
connection.commit()

</code>```

`

I seem to just get KeyError each time I try.

Body:
I am trying to insert a dynamic table built with JS into my HTML document, and the JS adds rows based on the inputs. Is it possible to loop this table into my sqlite database through flask?
`

    <form action="/page/" method="POST">
        <button type="submit">Submit</button>

My flask code is:

@app.route('/page/', methods=['POST','GET'])
if request.method == 'POST':
    connection = sqlite3.connect('sample.db')
    with connection:
sample1 = session['sample1']
sample2 = session['sample2']
sample3 = session['sample3']
sample4 = session['sample4']
cursor.execute("""
insert into sample_table (
sample1, sample2, sample3, sample4)value(?,?,?,?)""",
(sample1, sample2, sample3, sample4))
connection.commit()

`

I seem to just get KeyError each time I try.


问:
How to plot daily data in seperate chart based on year using altair python
I have daily based data for 5 years as follows.

I want to create one plot containing 5 charts of line using vconcat in altair where each chart indicates the data from each year. for example, chart one conatins two line plot of abc and xyz category of daily data of year 2001, chart two contains daily data of 2002 and so on. I could plot  vconcat of mutiple graph based on items instead of year.

I am not able to subplot based on year. Can anybody help me to achieve it using altair?


问:
Embed a web based application into a react website
I have a web based chat application(using Firebase and javascript) currently running on localhost:5000.I also have a MERN stack website. I want to embed/integrate the chat website into the mern website. Which steps can I follow?</p>


问:
Disconected session Rad Studio XE2
I have a problem when running a project on XE2 it sends me a "Session disconnected" error, this happens when I try to run the project on 64 bit. Does anyone know how to fix it?

Running the project without debugging runs it normally, but running with debugging is when it shows the error

Tried to install the IDE, update the IDE and it does not work

Error Message

[20372E20]{dbkdebugide160.bpl} Debug.TDebugKernel.msgBox (Line 5902, "Debug.pas" + 30) + $0

[04216EB3]{bordbk160.dll} Unknown function at DllUnregisterServer + $5037

[0428B8A8]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $619D0

[0428B927]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $61A4F

[0428C36D]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $62495

[0428C5BD]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $626E5

[042BC3E3]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $9250B

[04229D72]{bordbk160.dll} Unknown function at DllUnregisterServer + $17EF6

[042BCEE2]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $9300A

[042BCBFB]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $92D23

[042BCAD6]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $92BFE

[042CF92B]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $A5A53

[042BC19A]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $922C2

[0428C7FC]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $62924

[0428CCCE]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $62DF6

[042ADA44]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $83B6C

[04235E88]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $BFB0

[042CF92B]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $A5A53

[042C215A]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $98282

[042C2AB4]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $98BDC

[042C2043]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $9816B

[042C19A9]{bordbk160.dll} Unknown function at @isDbkLoggingOn$qv + $97AD1

[04217CAE]{bordbk160.dll} Unknown function at DllUnregisterServer + $5E32

[20371B1B]{dbkdebugide160.bpl} Debug.TDebugKernel.CreateProcess (Line 5427, "Debug.pas" + 17) + $63

[2037F6AD]{dbkdebugide160.bpl} Debug.TDebugger.DoCreateProcess (Line 11628, "Debug.pas" + 74) + $3C

[2037F820]{dbkdebugide160.bpl} Debug.TDebugger.CreateProcess (Line 11655, "Debug.pas" + 6) + $2F

[20380373]{dbkdebugide160.bpl} Debug.TDebugger.Run (Line 12064, "Debug.pas" + 23) + $33

[20380DEA]{dbkdebugide160.bpl} Debug.TDebugger.Run (Line 12389, "Debug.pas" + 129) + $43

[2037AFE6]{dbkdebugide160.bpl} Debug.TDebugger.Run (Line 10045, "Debug.pas" + 0) + $2

[2078C66D]{coreide160.bpl} DebuggerMgr.TDebuggerMgr.Run (Line 1913, "DebuggerMgr.pas" + 3) + $B

[500B5B9B]{rtl160.bpl  } System.Classes.TBasicAction.Execute (Line 13372, "System.Classes.pas" + 3) + $7

[5031B86D]{vcl160.bpl  } Vcl.ActnList.TContainedAction.Execute (Line 448, "Vcl.ActnList.pas" + 8) + $2C

[5031C658]{vcl160.bpl  } Vcl.ActnList.TCustomAction.Execute (Line 1094, "Vcl.ActnList.pas" + 7) + $8

[500B5A5F]{rtl160.bpl  } System.Classes.TBasicActionLink.Execute (Line 13301, "System.Classes.pas" + 2) + $7

[21714E79]{vclactnband160.bpl} Vcl.ActnMenus.TCustomActionMenuBar.ExecAction (Line 1076, "Vcl.ActnMenus.pas" + 6) + $D

[217166F0]{vclactnband160.bpl} Vcl.ActnMenus.TCustomActionMenuBar.TrackMenu (Line 1842, "Vcl.ActnMenus.pas" + 19) + $15

[2171A062]{vclactnband160.bpl} Vcl.ActnMenus.TCustomActionMainMenuBar.TrackMenu (Line 3636, "Vcl.ActnMenus.pas" + 5) + $3

[21714A39]{vclactnband160.bpl} Vcl.ActnMenus.TCustomActionMenuBar.CMItemClicked (Line 955, "Vcl.ActnMenus.pas" + 3) + $4

[50332995]{vcl160.bpl  } Vcl.Controls.TControl.WndProc (Line 7204, "Vcl.Controls.pas" + 91) + $6

[503372F3]{vcl160.bpl  } Vcl.Controls.TWinControl.WndProc (Line 9976, "Vcl.Controls.pas" + 152) + $6

[21716806]{vclactnband160.bpl} Vcl.ActnMenus.TCustomActionMenuBar.WndProc (Line 1881, "Vcl.ActnMenus.pas" + 25) + $4

[50336948]{vcl160.bpl  } Vcl.Controls.TWinControl.MainWndProc (Line 9689, "Vcl.Controls.pas" + 3) + $6

[500B6890]{rtl160.bpl  } System.Classes.StdWndProc (Line 13878, "System.Classes.pas" + 8) + $0

[50453213]{vcl160.bpl  } Vcl.Forms.TApplication.ProcessMessage (Line 10164, "Vcl.Forms.pas" + 23) + $1

[50453256]{vcl160.bpl  } Vcl.Forms.TApplication.HandleMessage (Line 10194, "Vcl.Forms.pas" + 1) + $4

[50453595]{vcl160.bpl  } Vcl.Forms.TApplication.Run (Line 10332, "Vcl.Forms.pas" + 26) + $3

Title: Disconected session Rad Studio XE2


问:
Extension entry point for both testing and deployment
I'm closing in on the development of a VS Code extension, so I started to experiment with packaging and publishing. With webpack set up, my package.json now points to

```<code>"main": "./dist/extension",
</code>```

as the packed-minified delopyment file is in the dist folder. Yet, to keep testing the extension, it should be

```<code>"main": "./out/extension",
</code>```

And I don't mean unit testing and similar, just running with debugging from VS Code. How can I reconcile the difference without manually changing back and forth every time?

Body:
I'm closing in on the development of a VS Code extension, so I started to experiment with packaging and publishing. With webpack set up, my package.json now points to

"main": "./dist/extension",

as the packed-minified delopyment file is in the dist folder. Yet, to keep testing the extension, it should be

"main": "./out/extension",

And I don't mean unit testing and similar, just running with debugging from VS Code. How can I reconcile the difference without manually changing back and forth every time?


问:
Is there a way to define restrictions/constraints to fields when defining GraphQL schema for AWS AppSync?
When designing schema for AppSync, like
https://docs.amplify.aws/cli/graphql/data-modeling/
Is it possible to define constraints in addition to types? We can do:

```<code>type Todo {
    id: ID!
    name: String
    description: String
    priority: Int
}
</code>```

But can we do something like

```<code>    id: ID!
    name: String @restrictions (maxLength: 64)
    description: String @restrictions (maxLength: 255)
    priority: Int @restrictions (min:0, max: 4)
}
</code>```

Otherwise, authorized user will be able to send the data of any length, even megabytes of data to be set into 'string' field if it has no length limit, and this data will go directly into DynamoDB unless there is a lambda function for every field.

Body:
When designing schema for AppSync, like
https://docs.amplify.aws/cli/graphql/data-modeling/
Is it possible to define constraints in addition to types? We can do:

type Todo {
    id: ID!
    name: String
    description: String
    priority: Int
}

But can we do something like

    id: ID!
    name: String @restrictions (maxLength: 64)
    description: String @restrictions (maxLength: 255)
    priority: Int @restrictions (min:0, max: 4)
}

Otherwise, authorized user will be able to send the data of any length, even megabytes of data to be set into 'string' field if it has no length limit, and this data will go directly into DynamoDB unless there is a lambda function for every field.


问:
How can I update cache rows within the flask-cache (FileSystemCache)
I am using flask-cache (FileSystemCache)to store an entire table worth of data (to prevent constant database IO)

This works great, and really speeds up the reading of the records, but my app also allows users to "update rows" in the database.

I am fine with the IO in this case, however I would also like to update the local cache of the row in this situation (because if the user revisits the last updated row, the cache will be what was previously fetched from the database and will not reflect the most recent user update).

I can see the cache is generated and it is stored in some binary way (pickle?), which I can see contains all the rows (and as mentioned, the cache is working as expected for "reads"). I don't know how to either "get" or "set" specific rows within the cache file though.

Below is the simplified code of what I am doing:

```<code>@cache.cached(timeout=500, key_prefix='all_docs')
def cache_all_db_rows(table_name):
    engine = create_sql_alchemy_engine()
    connection = engine.connect()
    results = connection.execute(stmt).fetchall()
    return [row for row in results]

@site.route('/display/<doc_id>', methods=["GET", "POST"])
@login_required
def display(doc_id):
    form = CommentForm(request.form)
    results = cache_all_db_rows(table_name)
    if request.method == "POST":
        if form.validate_on_submit():
            comments = form.comment.data
            relevant = form.relevant.data
            database_rate_or_add_comment(comments=comments, relevant_flag=relevant, doc_id=doc_id)

            # Ideally I would set the update to the cache here (after a successful db update)
            cache.set("foo", comments)

    return render_template("display.html", form = form)

</code>```

I tried a few things, but can't seem to query the cache (pickle file?)...  I tried adding code to query what is actually in the cache file by doing this:

```<code>            obj = []
            file_name = "./cache/dfaec33f482d83493ed6ae7e87ace5f9"
            with open(file_name,"rb") as fileOpener:
                while True:
                    try:
                        obj.append(pickle.load(fileOpener))
                    except EOFError:
                        break
            app.logger.info(str(obj))
</code>```

but I am receiving an error: _pickle.UnpicklingError: invalid load key, '\xfb'.

I am not sure how to interact with the flask-cache.

Body:
I am using flask-cache (FileSystemCache)to store an entire table worth of data (to prevent constant database IO)

This works great, and really speeds up the reading of the records, but my app also allows users to "update rows" in the database.

I am fine with the IO in this case, however I would also like to update the local cache of the row in this situation (because if the user revisits the last updated row, the cache will be what was previously fetched from the database and will not reflect the most recent user update).

I can see the cache is generated and it is stored in some binary way (pickle?), which I can see contains all the rows (and as mentioned, the cache is working as expected for "reads"). I don't know how to either "get" or "set" specific rows within the cache file though.

Below is the simplified code of what I am doing:

@cache.cached(timeout=500, key_prefix='all_docs')
def cache_all_db_rows(table_name):
    engine = create_sql_alchemy_engine()
    connection = engine.connect()
    results = connection.execute(stmt).fetchall()
    return [row for row in results]

@site.route('/display/<doc_id>', methods=["GET", "POST"])
@login_required
def display(doc_id):
    form = CommentForm(request.form)
    results = cache_all_db_rows(table_name)
    if request.method == "POST":
        if form.validate_on_submit():
            comments = form.comment.data
            relevant = form.relevant.data
            database_rate_or_add_comment(comments=comments, relevant_flag=relevant, doc_id=doc_id)

            # Ideally I would set the update to the cache here (after a successful db update)
            cache.set("foo", comments)

    return render_template("display.html", form = form)

I tried a few things, but can't seem to query the cache (pickle file?)...  I tried adding code to query what is actually in the cache file by doing this:

            obj = []
            file_name = "./cache/dfaec33f482d83493ed6ae7e87ace5f9"
            with open(file_name,"rb") as fileOpener:
                while True:
                    try:
                        obj.append(pickle.load(fileOpener))
                    except EOFError:
                        break
            app.logger.info(str(obj))

but I am receiving an error: _pickle.UnpicklingError: invalid load key, '\xfb'.

I am not sure how to interact with the flask-cache.


问:
Why is there a an error in this information criterion simulation in R?
I'm trying to run the code below but I keep getting the following error when it comes the ggplot4 line near the end. How can I fix this so that I can compare the AIC against the other criterions?</p>
```<code>Warning: no non-missing arguments to min; returning InfWarning: no non-missing arguments to max; returning -InfWarning: no non-missing arguments to min; returning InfWarning: no non-missing arguments to max; returning -InfError in plot.window(...) : need finite 'xlim' values
</code>```
```<code>set.seed(1)
X <- rnorm(100)
X2<-rnorm(100)
X3<-rnorm(100)

noise <- rnorm(100)
Y <- 3 + 1*X + 4*X2 + 5*X3 + noise

df <- data.frame(Y, X, X2, X3)
fit <- leaps::regsubsets(Y~., data = df, nvmax = 10)
reg.summary <-summary(fit)

par(mfrow = c(2, 2))

gg<-plot(reg.summary$cp, xlab = "Number of variables", ylab = "C_p", type = "l")
points(which.min(reg.summary$cp), reg.summary$cp[which.min(reg.summary$cp)], col = "red", cex = 2, pch = 20)
gg

gg2<-plot(reg.summary$bic, xlab = "Number of variables", ylab = "BIC", type = "l")
points(which.min(reg.summary$bic), reg.summary$bic[which.min(reg.summary$bic)], col = "red", cex = 2, pch = 20)
gg2

gg3<-plot(reg.summary$adjr2, xlab = "Number of variables", ylab = "Adjusted R^2", type = "l")
points(which.max(reg.summary$adjr2), reg.summary$adjr2[which.max(reg.summary$adjr2)], col = "red", cex = 2, pch = 20)
gg3

gg4<-plot(reg.summary$aic, xlab = "Number of variables", ylab = "AIC", type = "l")
points(which.min(reg.summary$aic), reg.summary$cp[which.min(reg.summary$aic)], col = "red", cex = 2, pch = 20)
gg4

coef(reg.summary, which.max(reg.summary$adjr2))

</code>```

Body:
I'm trying to run the code below but I keep getting the following error when it comes the ggplot4 line near the end. How can I fix this so that I can compare the AIC against the other criterions?

Warning: no non-missing arguments to min; returning InfWarning: no non-missing arguments to max; returning -InfWarning: no non-missing arguments to min; returning InfWarning: no non-missing arguments to max; returning -InfError in plot.window(...) : need finite 'xlim' values

set.seed(1)
X <- rnorm(100)
X2<-rnorm(100)
X3<-rnorm(100)

noise <- rnorm(100)
Y <- 3 + 1*X + 4*X2 + 5*X3 + noise

df <- data.frame(Y, X, X2, X3)
fit <- leaps::regsubsets(Y~., data = df, nvmax = 10)
reg.summary <-summary(fit)

par(mfrow = c(2, 2))

gg<-plot(reg.summary$cp, xlab = "Number of variables", ylab = "C_p", type = "l")
points(which.min(reg.summary$cp), reg.summary$cp[which.min(reg.summary$cp)], col = "red", cex = 2, pch = 20)
gg

gg2<-plot(reg.summary$bic, xlab = "Number of variables", ylab = "BIC", type = "l")
points(which.min(reg.summary$bic), reg.summary$bic[which.min(reg.summary$bic)], col = "red", cex = 2, pch = 20)
gg2

gg3<-plot(reg.summary$adjr2, xlab = "Number of variables", ylab = "Adjusted R^2", type = "l")
points(which.max(reg.summary$adjr2), reg.summary$adjr2[which.max(reg.summary$adjr2)], col = "red", cex = 2, pch = 20)
gg3

gg4<-plot(reg.summary$aic, xlab = "Number of variables", ylab = "AIC", type = "l")
points(which.min(reg.summary$aic), reg.summary$cp[which.min(reg.summary$aic)], col = "red", cex = 2, pch = 20)
gg4

coef(reg.summary, which.max(reg.summary$adjr2))


问:
Security techniques to identify the client, when there is no login function
I'm working on my own "Auto update service", to support automatic updates for every desktop application I create.

Below is my basic idea.

Client

A program that can be run as an independent process that included in every products I make.

When my product runs, it runs first and queries the server for a newer version of my product.

If there is a new version, it downloads the binary file from the server and replaces it to my product.

All of the above processes should not require any user input other than choosing whether or not to proceed with the update.

Server

Product-id are stored in database.

For each product, binary files and release information of each version are stored.

Support querying product and version with REST-style http request and send binary file.

On the server, I need to do something to check that the requesting client is a valid one. So I came up with a way to issue a secret key to each distribution of my product, just like a game CD key, and check it in header of http request. This is the best I've come up with, but I'm still concerned:

On server-side, is it safe to store secret keys in database? If not, how the server stores and remember them?

On client-side, is it safe to store secret keys in client? What if an attacker tries to decompile the client program?

Any other better ideas?

I am new to develop web services so I don't have much knowledge. please understand.


问:
unable to FillRect with transparent brush when double buffering
As the title says I'm unable to FillRect bitmap to be transparent. I know when creating the bitmap it is not monochrome as gray brush works fine but I have no way (that I'm aware of) to check if it is colored or grayscale. I also am aware that by default the bitmap is black hence why I'm trying to change it to transparent. I am also aware that I'm likely not cleaning up the dc's correctly however that is not the main issue. I'm trying to solve the black background by making it transparent.

```<code>#include<windows.h>
#include<iostream>

int main()
{
    // Init DC
    HWND Wnd = GetDesktopWindow();//GetConsoleWindow();
    HDC ScreenDC = GetDC(Wnd);

    // Init Rectangle
    RECT ClientRect;
    GetClientRect(Wnd, &ClientRect);

    // Init Double Buffer
    HDC MemDC = CreateCompatibleDC(ScreenDC);
    HBITMAP MemBM = CreateCompatibleBitmap(ScreenDC, ClientRect.right - ClientRect.left, ClientRect.bottom - ClientRect.top);
    HBITMAP OldBM = (HBITMAP)SelectObject(MemDC, MemBM);

    // Create Brush and Pen
    HPEN Pen = CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
    HBRUSH ClearBrush = (HBRUSH)GetStockObject(GRAY_BRUSH);

    // Set Brush and Pen
    SelectObject(MemDC, Pen);
    SelectObject(MemDC, ClearBrush);

    POINT p;

    while(!GetAsyncKeyState(VK_RETURN))
    {
        // Clear and Draw
        GetCursorPos(&p);
        FillRect(MemDC, &ClientRect, ClearBrush);
        Rectangle(MemDC, p.x, p.y, p.x+20, p.y+20);
        BitBlt(ScreenDC, 0, 0, ClientRect.right - ClientRect.left, ClientRect.bottom + ClientRect.left, MemDC, 0, 0, SRCCOPY);
    }

    SelectObject(MemDC, OldBM);
    DeleteObject(ClearBrush);
    DeleteObject(Pen);
    DeleteObject(OldBM);
    DeleteObject(MemBM);
    DeleteDC(MemDC);
    ReleaseDC(Wnd, ScreenDC);

    return 0;
}
</code>```

I've tried many different ways of setting transparent background to no avail. The end result is a rectangle appearing over the mouse and following it across the screen however the background shouldn't be black I should be able to see other windows.

Body:
As the title says I'm unable to FillRect bitmap to be transparent. I know when creating the bitmap it is not monochrome as gray brush works fine but I have no way (that I'm aware of) to check if it is colored or grayscale. I also am aware that by default the bitmap is black hence why I'm trying to change it to transparent. I am also aware that I'm likely not cleaning up the dc's correctly however that is not the main issue. I'm trying to solve the black background by making it transparent.

#include<windows.h>
#include<iostream>

int main()
{
    // Init DC
    HWND Wnd = GetDesktopWindow();//GetConsoleWindow();
    HDC ScreenDC = GetDC(Wnd);

    // Init Rectangle
    RECT ClientRect;
    GetClientRect(Wnd, &ClientRect);

    // Init Double Buffer
    HDC MemDC = CreateCompatibleDC(ScreenDC);
    HBITMAP MemBM = CreateCompatibleBitmap(ScreenDC, ClientRect.right - ClientRect.left, ClientRect.bottom - ClientRect.top);
    HBITMAP OldBM = (HBITMAP)SelectObject(MemDC, MemBM);

    // Create Brush and Pen
    HPEN Pen = CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
    HBRUSH ClearBrush = (HBRUSH)GetStockObject(GRAY_BRUSH);

    // Set Brush and Pen
    SelectObject(MemDC, Pen);
    SelectObject(MemDC, ClearBrush);

    POINT p;

    while(!GetAsyncKeyState(VK_RETURN))
    {
        // Clear and Draw
        GetCursorPos(&p);
        FillRect(MemDC, &ClientRect, ClearBrush);
        Rectangle(MemDC, p.x, p.y, p.x+20, p.y+20);
        BitBlt(ScreenDC, 0, 0, ClientRect.right - ClientRect.left, ClientRect.bottom + ClientRect.left, MemDC, 0, 0, SRCCOPY);
    }

    SelectObject(MemDC, OldBM);
    DeleteObject(ClearBrush);
    DeleteObject(Pen);
    DeleteObject(OldBM);
    DeleteObject(MemBM);
    DeleteDC(MemDC);
    ReleaseDC(Wnd, ScreenDC);

    return 0;
}

I've tried many different ways of setting transparent background to no avail. The end result is a rectangle appearing over the mouse and following it across the screen however the background shouldn't be black I should be able to see other windows.


问:
How to make android always on display on Android Studio?
I want to create an AOD for my device, my device has a similar feature (Moto display) but is an ambient display so it shuts the screen off after a certain amount of time. I want an AOD that stays on all the time and displays time and notifications. I also want it to be customizable, I basically want to know how to code an AOD on android studio. Any help would be appreciated!</p>