问:
Raise Error 404 using django-hosts in Django
I have the following problem. I'm using django-hosts for subdomains like blog.example.com, es.example.com.

The problem is that there are urls where I manage id, such as: blog.example.com/url/id

And suppose the user doesn't touch anything, because everything is an OK 200 but if the user goes from clever and touches the id to one that doesn't exist, the site returns a 404.

But here comes the problem, when using django-hosts if I do a handler404 in the urls of the subdomain. It throws me an Error 500 and if I then do a handler500 in the urls of the subdomain, literally, it breaks the server, since then apache tells me that there is a problem in the server.

Here I leave my url.py of the subdomain.

```<code>from django.urls import path
from django.views.generic.base import TemplateView
from django.conf.urls import handler404, handler500
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.sitemaps.views import sitemap

# MODULO PROPIO
from . import views
from .sitemaps import MapaDeSitio

sitemaps = {
    'blog': MapaDeSitio
}

urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
    # SITIO
    path('', views.indexView, name='IndexView'),
    path('articulo/<str:url>/<int:id>', views.ArticuloView, name="ArticuloView"),

    # SEO
    path('robots.txt', views.RobotsView.as_view()),
    path('BingSiteAuth.xml', TemplateView.as_view(template_name="blog/BingSiteAuth.xml", content_type="text/xml")),
    path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
]

# MANEJO DE ERRORES HTTP
handler404 = views.Error404 # Error 404
handler500 = views.Error500 # Error 500
</code>```

Here I leave the code of the hosts.py of the django-hosts:

```<code>from django.conf import settings

from django_hosts import patterns, host

host_patterns = patterns(
    '',
    host(r'www', settings.ROOT_URLCONF, name="www"),
    host(r'blog', 'blog.urls', name="blog"),

)
</code>```

If anyone can help me, I will thank you.

I now tried to remove the codes to see if it fixed apache2 error 500:
'handler404 = views. Error404 # Error 404
handler500 = views. Error500#Error 500'

And if you solve them. Half time you place some handlerX throws the error. But always in the url file of the subdomain.

Body:
I have the following problem. I'm using django-hosts for subdomains like blog.example.com, es.example.com.

The problem is that there are urls where I manage id, such as: blog.example.com/url/id

And suppose the user doesn't touch anything, because everything is an OK 200 but if the user goes from clever and touches the id to one that doesn't exist, the site returns a 404.

But here comes the problem, when using django-hosts if I do a handler404 in the urls of the subdomain. It throws me an Error 500 and if I then do a handler500 in the urls of the subdomain, literally, it breaks the server, since then apache tells me that there is a problem in the server.

Here I leave my url.py of the subdomain.

from django.urls import path
from django.views.generic.base import TemplateView
from django.conf.urls import handler404, handler500
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.sitemaps.views import sitemap

# MODULO PROPIO
from . import views
from .sitemaps import MapaDeSitio

sitemaps = {
    'blog': MapaDeSitio
}

urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
    # SITIO
    path('', views.indexView, name='IndexView'),
    path('articulo/<str:url>/<int:id>', views.ArticuloView, name="ArticuloView"),

    # SEO
    path('robots.txt', views.RobotsView.as_view()),
    path('BingSiteAuth.xml', TemplateView.as_view(template_name="blog/BingSiteAuth.xml", content_type="text/xml")),
    path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
]

# MANEJO DE ERRORES HTTP
handler404 = views.Error404 # Error 404
handler500 = views.Error500 # Error 500

Here I leave the code of the hosts.py of the django-hosts:

from django.conf import settings

from django_hosts import patterns, host

host_patterns = patterns(
    '',
    host(r'www', settings.ROOT_URLCONF, name="www"),
    host(r'blog', 'blog.urls', name="blog"),

)

If anyone can help me, I will thank you.

I now tried to remove the codes to see if it fixed apache2 error 500:
'handler404 = views. Error404 # Error 404
handler500 = views. Error500#Error 500'

And if you solve them. Half time you place some handlerX throws the error. But always in the url file of the subdomain.


来源: stackexchange

问:
Injecting commands into a background task
I'll try to explain as much as I can my issue.
So I have an Ubuntu machine set up which I use to host my Minecraft Server. It uses Java 8.
To start it, I usually use the command java -Xmx10G -jar server.jar nogui. But as I am going on vacation and my friends still want to sometimes play on it, I wanted to make an option to start it without having to enter this command. I created a .sh file, put it as crontask and put this in it :

nohup sudo java -Xmx10G -jar server.jar nogui >> minecraft_logs.txt &

This line works fine, and my server is running in background, printing its output in "minecraft_logs.txt". However, I realized I couldn't have access to its console anymore. I however wanted to be able to send commands on it (inputs), such as tellraws or give commands.

How could I "inject" commands into my Minecraft Server task running in the background ? Thank you.

I tried using screen or using this syntax :
nohup sudo java -Xmx10G -jar server.jar nogui < input.txt >> minecraft_logs.txt &
but it didn't work at all. I couldn't find anything that worked for me.

ContentLicense: CC BY-SA 4.0


问:
I can't properly distribute the data by periods
I have the range with dates `

```<code>
let range = [
  '2022-11-19',
  '2022-11-26',
  '2022-12-03',
  '2022-12-10',
  '2022-12-17',
  '2022-12-19'
]
</code>```

 and i have the data from database

```<code>let result = [
  {
    total: 1,
    color: '#000000',
    name: 'UX',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a74",
        dateString: '2022-11-29'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'Database',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a77",
        dateString: '2022-11-29'
      }
    }
  },
  {
    total: 1,
    color: '#FFDD65',
    name: 'Ghosts',
    data: {
      dateString: {
        _id: "6261ca05480cf0cd1540c23b",
        dateString: '2022-11-29'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'Front-end Engineer',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a52",
        dateString: '2022-11-22'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'Database Developer',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a78",
        dateString: '2022-11-29'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'QA developer',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a86",
        dateString: '2022-11-29'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'UX',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a74",
        dateString: '2022-11-29'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'Graphic Designer',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a70",
        dateString: '2022-11-29'
      }
    },
  }
]
</code>```

`

I need to process the data so that in each of the periods there are groups and the sum of the total, like that
`

```<code>{
    date: '2022-11-19 - 2022-11-26',
    teams: [
      {
        total: 12,
        color: '#FFDD65',
        name: 'Graphic Design Team',
        _id: '1'
      },
      {
        total: 45,
        color: '#ACE6CA',
        name: 'Designer',
        _id: '2'
      },
      {
        total: 93,
        color: '#d91919',
        name: 'Front-end Engineer',
        _id: '3'
      }
    ]
  }, {
   date: '2022-11-26 - 2022-12-03',
   teams: [...]
}
</code>```

`

the dates themselves are thrown in 'data.dateString.dateString'.
I tried different ways, but it turns out not that. If you want you can use moment.js

Previously, I distributed in this way, but now I need to distribute it into groups, including, and I don`t know how to do this

```<code>result = result
            .reduce((acc, {data, total, color, name}) => {
                const range = acc.find(n => n[0] <= data.dateString && data.dateString <= n[1]);

                if (range) {
                    range[2] += total;
                    range.push(color);
                    range.push(name);
                }

                return acc;
            }, range.slice(1).map((n, i) => [range[i], n, 0]))
            .map(n => ({
                date: `${n[0]} - ${n[1]}`,
                total: n[2],
                color: n[3],
                name: n[4]
            }))
</code>```

Body:
I have the range with dates `

let range = [
  '2022-11-19',
  '2022-11-26',
  '2022-12-03',
  '2022-12-10',
  '2022-12-17',
  '2022-12-19'
]

 and i have the data from database

let result = [
  {
    total: 1,
    color: '#000000',
    name: 'UX',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a74",
        dateString: '2022-11-29'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'Database',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a77",
        dateString: '2022-11-29'
      }
    }
  },
  {
    total: 1,
    color: '#FFDD65',
    name: 'Ghosts',
    data: {
      dateString: {
        _id: "6261ca05480cf0cd1540c23b",
        dateString: '2022-11-29'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'Front-end Engineer',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a52",
        dateString: '2022-11-22'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'Database Developer',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a78",
        dateString: '2022-11-29'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'QA developer',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a86",
        dateString: '2022-11-29'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'UX',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a74",
        dateString: '2022-11-29'
      }
    },
  },
  {
    total: 1,
    color: '#000000',
    name: 'Graphic Designer',
    data: {
      dateString: {
        _id: "62d9e0d37bf7c410c0622a70",
        dateString: '2022-11-29'
      }
    },
  }
]

`

I need to process the data so that in each of the periods there are groups and the sum of the total, like that
`

{
    date: '2022-11-19 - 2022-11-26',
    teams: [
      {
        total: 12,
        color: '#FFDD65',
        name: 'Graphic Design Team',
        _id: '1'
      },
      {
        total: 45,
        color: '#ACE6CA',
        name: 'Designer',
        _id: '2'
      },
      {
        total: 93,
        color: '#d91919',
        name: 'Front-end Engineer',
        _id: '3'
      }
    ]
  }, {
   date: '2022-11-26 - 2022-12-03',
   teams: [...]
}

`

the dates themselves are thrown in 'data.dateString.dateString'.
I tried different ways, but it turns out not that. If you want you can use moment.js

Previously, I distributed in this way, but now I need to distribute it into groups, including, and I don`t know how to do this

result = result
            .reduce((acc, {data, total, color, name}) => {
                const range = acc.find(n => n[0] <= data.dateString && data.dateString <= n[1]);

                if (range) {
                    range[2] += total;
                    range.push(color);
                    range.push(name);
                }

                return acc;
            }, range.slice(1).map((n, i) => [range[i], n, 0]))
            .map(n => ({
                date: `${n[0]} - ${n[1]}`,
                total: n[2],
                color: n[3],
                name: n[4]
            }))


问:
How to show a customize page in Shopify that fetch and show specific dynamic data based on user input
I want to have a page in my Shopify store, where users can upload an "image or voice" and I send it to another 3rd party API, which does some changes to the image or voice and get some result. So then I can use Printful to print the resulting picture on some stuff. The thing is that my resulting picture is coming from a 3rd party API based on user input (dynamic images like a QRCode for example).

user input -> process in 3rd-API -> result image -> user confirm the output -> pass image to printful -> printful process ...

In brief, I want to fetch data to a third-party API, based on user input. How should I implement it? What should I use in order to implement it? How can I call an API and show the result on the Shopify page?


问:
restricting access to phpmyadmin to any public ip address except my own
How do I go about restricting access to my phpmyadmin login via the web? I do not want the login to be available to any public ip address except my own.

I tried a handful of different things, but none worked.


问:
Download Mail in PDF format (i.e. print the mail)
I'm aware of the possibility to download mails:

as .eml via .../messages/{id}/$value (although I don't know how that is made in Java SDK yet)

as HTML/Text file via .../messages/{id} and then by using the body attribute

My desired resulting file type is PDF. Until now my approach for this was a relatively complicated workflow, that worked with a .eml file and printed it with headless browsers etc.

Now I'm wondering if there is a possibility to avoid doing that conversion step from .eml to .pdf myself and let MS Graph do it.
E.g., when I download a DriveItem (e.g. a Word document) I can set the QueryOption "format" to "pdf" to let MS Graph convert it to PDF before downloading it.

Is there something similar for mails? I didn't find any information in the documentation regarding that topic.

Also, I tried uploading some .html and .eml files and downloading their DriveItems as PDF and surprisingly that worked, although according to the doc this seems to be not supported officially.

Unfortunately, this reuploading way seems a bit buggy to me when using the files received by the methods described above. Is there a more direct way?

Edit:

I created a feature idea in the Microsoft feedback portal to support directly downloading mails via MS Graph. If you are interested in it, upvoting could help.

Edit:

As pointed out in the feature idea, the option to download .eml/.msg source files as PDF exists at the Beta endpoint (see doc). What still seems to be missing is a feature to download mails directly as PDF without uploading them as DriveItems before.


问:
How to add an array of "rooms" to a "house" model in Django (SQlite)
I'am new to Django and I'am trying to write an API to send some data from my SQLite DB.

I want the API to output something like this :

```<code>{
    "name":"Yellow apartment",
    "rooms":["kitchen","bathroom","bedroom"]
}
</code>```

I am not sure how to handle the rooms field, since you can not store an array in SQLite DB.

Should I create a new room table for each room in the house and then set a foreign key to the house or is there any other way to handle this situation ?

```<code>class House(models.Model):
    name = models.CharField(max_length=150, unique=True)

class Rooms(models.Model):
    property = models.ForeignKey(House, on_delete=models.CASCADE)
    KITCHEN = 'kitchen'
    BATHROOM = 'bathroom'
    BEDROOM = 'bedroom'
    LIVING_ROOM = 'living-room'
    ROOM_CHOICES = (
        (KITCHEN, 'Kitchen'),
        (BATHROOM, 'Bathroom'),
        (BEDROOM, 'Bedroom'),
        (LIVING_ROOM, 'Living Room'),
    )
    room_type = models.CharField(max_length=20, choices=ROOM_CHOICES)
</code>```

Body:
I'am new to Django and I'am trying to write an API to send some data from my SQLite DB.

I want the API to output something like this :

{
    "name":"Yellow apartment",
    "rooms":["kitchen","bathroom","bedroom"]
}

I am not sure how to handle the rooms field, since you can not store an array in SQLite DB.

Should I create a new room table for each room in the house and then set a foreign key to the house or is there any other way to handle this situation ?

class House(models.Model):
    name = models.CharField(max_length=150, unique=True)

class Rooms(models.Model):
    property = models.ForeignKey(House, on_delete=models.CASCADE)
    KITCHEN = 'kitchen'
    BATHROOM = 'bathroom'
    BEDROOM = 'bedroom'
    LIVING_ROOM = 'living-room'
    ROOM_CHOICES = (
        (KITCHEN, 'Kitchen'),
        (BATHROOM, 'Bathroom'),
        (BEDROOM, 'Bedroom'),
        (LIVING_ROOM, 'Living Room'),
    )
    room_type = models.CharField(max_length=20, choices=ROOM_CHOICES)


问:
Loop over DataFrame and use it's column values to create columns in new New DataFrame
I have a dataframe sorted_df which has 3 Columns CarNumber, Sightcode and Sightdate,currentcity I want to loop over this DF and use column values to create different columns in a new DF, I am trying to do something like this, this is not the complete snippet:

```<code>df_new = pd.DataFrame()
for index,row in sorted_df.iterrows():
    if row['CarNumber'] == 'GACX470159' and row['Sightcode'] == 'ACTUAL_PLACEMENT':
        df_new['AP_TS'] = row['Sightdate']
    elif row['railcarnumber'] == 'GACX470159' and row['Sightcode'] == 'PULL':
        df_new['PULL_TS'] = row['Sightdate']
        df_new['PULL_CITY'] = row['currentcity']
    elif row['railcarnumber'] == 'GACX470159' and row['Sightcode'] == 'ARRIVAL_AT_DESTINATION':
        df_new['ARRIVAL_TS'] = row['Sightdate']
        df_new['ARRIVAL_CITY'] = row['currentcity']`
</code>```

The idea is for 1 Car number I want to get 1 row in the df_new, which would have multiple column based on what sight code is.
If Sightcode is equal to ACTUAL_PLACEMENT, in the df_new a new column df_new[AP_TS] is filled with the value of Sightdate.
If Sightcode is equal to PULL, in the df_new a new column df_new[PULL_TS] is filled with the value of the Sighdate.

Once I do this correctly, I would revamp the logic to loop through all the car numbers that i have in the sorted_df.

Can someone please help me rewrite this?
Below is what I am trying:
I am trying to create new column timestamp columns in df_new with the value of Sightdate i get using  the loop, But this doesn't do anything for me, In the end, the desired columns are created in the df_new but have 0 rows.

Body:
I have a dataframe sorted_df which has 3 Columns CarNumber, Sightcode and Sightdate,currentcity I want to loop over this DF and use column values to create different columns in a new DF, I am trying to do something like this, this is not the complete snippet:

df_new = pd.DataFrame()
for index,row in sorted_df.iterrows():
    if row['CarNumber'] == 'GACX470159' and row['Sightcode'] == 'ACTUAL_PLACEMENT':
        df_new['AP_TS'] = row['Sightdate']
    elif row['railcarnumber'] == 'GACX470159' and row['Sightcode'] == 'PULL':
        df_new['PULL_TS'] = row['Sightdate']
        df_new['PULL_CITY'] = row['currentcity']
    elif row['railcarnumber'] == 'GACX470159' and row['Sightcode'] == 'ARRIVAL_AT_DESTINATION':
        df_new['ARRIVAL_TS'] = row['Sightdate']
        df_new['ARRIVAL_CITY'] = row['currentcity']`

The idea is for 1 Car number I want to get 1 row in the df_new, which would have multiple column based on what sight code is.
If Sightcode is equal to ACTUAL_PLACEMENT, in the df_new a new column df_new[AP_TS] is filled with the value of Sightdate.
If Sightcode is equal to PULL, in the df_new a new column df_new[PULL_TS] is filled with the value of the Sighdate.

Once I do this correctly, I would revamp the logic to loop through all the car numbers that i have in the sorted_df.

Can someone please help me rewrite this?
Below is what I am trying:
I am trying to create new column timestamp columns in df_new with the value of Sightdate i get using  the loop, But this doesn't do anything for me, In the end, the desired columns are created in the df_new but have 0 rows.


问:
Javascript still runs even though I have removed it from my application - Blazor WebAssembly
So Im working with an application in Blazor WebAssembly. I had a script in the index.html file, but when I removed the script and ran the program the script was still running. It's like I havent removed it or managed to save my changes. Does anyone know how to fix this or can tell my why this happens?</p>


问:
My service is not recognizing the file names contained in directory with Java 8
I am creating a service and I am using java 8, I want to retrieve the file names as a list, those are in a folder into resources/ and when I am running locally is working but when I deployed my application into DEV/QA environment is getting empty, is not recognizing those files, and I have some considerations:

In the full path, in one folder is hidden folder (.cache), that
could affect it?, this is the path:
file:/newarch/apps/project-1/servers/project-service-1/workarea/org.eclipse.osgi/55/data/cache/com.ibm.ws.app.manager_723/.cache/project-service-ser.jar!/services

I gave rights on the folder as reader and writer.

This is the structure of the folder that I wanna retrieve the names:

```<code>resources/
    services/
        service-host1.js
        service-host2.js
        service-host3.js
        service-host4.js
</code>```

This is my code to read:

```<code>public List<String> getFilesFromDirectory(String dirName) throws IOException {
        dirName = dirName + "/";
        try (Stream<Path> pathStream = Files.list(Paths.get(dirName))) {
            return pathStream.filter(Files::isRegularFile)
                    .map(Path::getFileName)
                    .map(Path::toString)
                    .collect(Collectors.toList());
        }
    }
</code>```

this is the way how I am getting the full path:

```<code>Thread.currentThread().getContextClassLoader().getResource("service").getPath()
</code>```

Could you give any advice what could be the problem?

Body:
I am creating a service and I am using java 8, I want to retrieve the file names as a list, those are in a folder into resources/ and when I am running locally is working but when I deployed my application into DEV/QA environment is getting empty, is not recognizing those files, and I have some considerations:

In the full path, in one folder is hidden folder (.cache), that
could affect it?, this is the path:
file:/newarch/apps/project-1/servers/project-service-1/workarea/org.eclipse.osgi/55/data/cache/com.ibm.ws.app.manager_723/.cache/project-service-ser.jar!/services

I gave rights on the folder as reader and writer.

This is the structure of the folder that I wanna retrieve the names:

resources/
    services/
        service-host1.js
        service-host2.js
        service-host3.js
        service-host4.js

This is my code to read:

public List<String> getFilesFromDirectory(String dirName) throws IOException {
        dirName = dirName + "/";
        try (Stream<Path> pathStream = Files.list(Paths.get(dirName))) {
            return pathStream.filter(Files::isRegularFile)
                    .map(Path::getFileName)
                    .map(Path::toString)
                    .collect(Collectors.toList());
        }
    }

this is the way how I am getting the full path:

Thread.currentThread().getContextClassLoader().getResource("service").getPath()

Could you give any advice what could be the problem?


问:
How to best compress videos using PHP-FFMpeg?
I'm using the PHP-FFMpeg v1.1.0 library to compress videos sent from a variety of mobile devices into 480p (640x480) MP4 videos.

Everything is working great, but I'm wondering how to reach an optimal compression level. It looks like I'm already using the recommended video bitrate for 480p, as well as a fairly low quality audio (64Kbps).

Am I missing any best practices/options here?

My code:

```<code>$videoFile = '/tmp/source.avi';
$destVideoFile = '/tmp/'.uniqid().'.mp4';
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($videoFile);
$video->filters()->resize(new FFMpeg\Coordinate\Dimension(640, 480), 'width')->synchronize();
$codec = new FFMpeg\Format\Video\X264();
$codec->setKiloBitrate(960)->setAudioKiloBitrate(64);
$video->save($codec, $destVideoFile);
</code>```

Body:
I'm using the PHP-FFMpeg v1.1.0 library to compress videos sent from a variety of mobile devices into 480p (640x480) MP4 videos.

Everything is working great, but I'm wondering how to reach an optimal compression level. It looks like I'm already using the recommended video bitrate for 480p, as well as a fairly low quality audio (64Kbps).

Am I missing any best practices/options here?

My code:

$videoFile = '/tmp/source.avi';
$destVideoFile = '/tmp/'.uniqid().'.mp4';
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($videoFile);
$video->filters()->resize(new FFMpeg\Coordinate\Dimension(640, 480), 'width')->synchronize();
$codec = new FFMpeg\Format\Video\X264();
$codec->setKiloBitrate(960)->setAudioKiloBitrate(64);
$video->save($codec, $destVideoFile);


问:
how to Disable click on btn after first or do not send action
I have tried different solutions but what I want to achivie is:

When you press the button (a tag / h:commandlink ) I want to disable the button or do no action at the second click because the first one is loading. Right now I have a issue that you can double click on the button and it can give me error.

I have this code:

```<code> <h:commandLink id="btn" styleClass="link"
  onclick="test()"
  action="#{use.enterAgentMode(user, myBean.guardEnum)}">
</h:commandLink>
</code>```

for example is it possible to create a variable and set it to true/false and set condition inside of action=... if true do the code else nothing

I also tried with JQuery and document.getElement to set attr.disabled true but did not work.
I saw it disabled with inspect  but it was still clickable

I have tried different stuff, tried to add some debounce on the button..
any advices please

Body:
I have tried different solutions but what I want to achivie is:

When you press the button (a tag / h:commandlink ) I want to disable the button or do no action at the second click because the first one is loading. Right now I have a issue that you can double click on the button and it can give me error.

I have this code:

 <h:commandLink id="btn" styleClass="link"
  onclick="test()"
  action="#{use.enterAgentMode(user, myBean.guardEnum)}">
</h:commandLink>

for example is it possible to create a variable and set it to true/false and set condition inside of action=... if true do the code else nothing

I also tried with JQuery and document.getElement to set attr.disabled true but did not work.
I saw it disabled with inspect  but it was still clickable

I have tried different stuff, tried to add some debounce on the button..
any advices please


问:
500 internal server error when trying to get data from gmb
i am new to gmb and i am trying to learn from trying and i don't know if this is the right approach to get data,
i am trying to get data data from gmb but i am getting 500 error

```<code><?php
include_once '../../google-api-php-client-2.4.0/vendor/autoload.php'; // or wherever autoload.php is located
include_once './MyBusiness.php';
ini_set('max_execution_time', '0');
include_once "../../includes/config.php";
$client = new Google_Client();
if (isset($_SERVER['HTTP_HOST']) && ($_SERVER['HTTP_HOST'] == "localhost")) {
    $client->setAuthConfig('../client_secret_for_Google_my_bussniss.json');
    $json = json_decode(file_get_contents('../Google-My-Business-tokens.json'));

}else{
    $client->setAuthConfig('/home/eblatech/insights-secrets/client_secret_for_Google_my_bussniss.json');
    $json = json_decode(file_get_contents('/home/eblatech/insights-secrets/Google-My-Business-tokens.json'));
}

$client->addScope('https://www.googleapis.com/auth/business.manage');
$refreshToken = $json->refreshToken;
$_SESSION['access_token']=$json->access_token;

// echo '```'; print_r($refreshToken); echo '```';exit;
if (isset($refreshToken) && $refreshToken)  {
    $client->refreshToken($refreshToken);
    $mybusinessService = new Google_Service_Mybusiness($client);
    $posts = $mybusinessService->accounts_locations_localPosts;
    $x=$posts->get("BlackSwanLimos");
     echo '```'; print_r($x); echo '```';
</code>```

update:
i just opened error log and found this

```<code>19-Dec-2022 23:39:03 UTC] PHP Fatal error:  Uncaught Google_Service_Exception
[20-Dec-2022 00:00:02 UTC] PHP Notice:  Undefined index: HTTP_HOST in /home/eblatech/insights.ebla-tech.com/admin/includes/config.php on line 9
[20-Dec-2022 00:00:02 UTC] PHP Notice:  Undefined index: REQUEST_URI in /home/eblatech/insights.ebla-tech.com/admin/includes/config.php on line 9
</code>```

that is the config.php

```<code><?php
session_set_cookie_params(2*3600,"/");
session_start();
$APP_ROOT = "/insights-dashboard/admin/";
$FILES_ROOT = "/insights-dashboard/admin/files/";
$MODEL_ROOT = realpath(dirname(__FILE__) . '/../../');
$actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
define("SESSION", "insightEbla");
define("DEFAULT_LANGUAGE", "en");
// var_dump($_SESSION);
// exit;
if (!isset($_SESSION[SESSION]['lang']) || empty($_SESSION[SESSION]['lang'])) {
    $_SESSION[SESSION]['lang'] = DEFAULT_LANGUAGE;
};
$current_lang = $_SESSION[SESSION]['lang'];
if ($_SESSION[SESSION]['lang'] == 'ar') {
    require_once "lang/ar.php";
} else {
    require_once "lang/en.php";
}
require_once "page_names.php";
require_once "enum.php";
require_once  $MODEL_ROOT . '/model/db_endpoint.php';
require_once "authentication.php";
require_once "functions.php";
require_once "authorization.php";
require_once "pages_includes.php";
</code>```

Body:
i am new to gmb and i am trying to learn from trying and i don't know if this is the right approach to get data,
i am trying to get data data from gmb but i am getting 500 error

<?php
include_once '../../google-api-php-client-2.4.0/vendor/autoload.php'; // or wherever autoload.php is located
include_once './MyBusiness.php';
ini_set('max_execution_time', '0');
include_once "../../includes/config.php";
$client = new Google_Client();
if (isset($_SERVER['HTTP_HOST']) && ($_SERVER['HTTP_HOST'] == "localhost")) {
    $client->setAuthConfig('../client_secret_for_Google_my_bussniss.json');
    $json = json_decode(file_get_contents('../Google-My-Business-tokens.json'));

}else{
    $client->setAuthConfig('/home/eblatech/insights-secrets/client_secret_for_Google_my_bussniss.json');
    $json = json_decode(file_get_contents('/home/eblatech/insights-secrets/Google-My-Business-tokens.json'));
}

$client->addScope('https://www.googleapis.com/auth/business.manage');
$refreshToken = $json->refreshToken;
$_SESSION['access_token']=$json->access_token;

// echo '
'; print_r($refreshToken); echo '
';exit;
if (isset($refreshToken) && $refreshToken)  {
    $client->refreshToken($refreshToken);
    $mybusinessService = new Google_Service_Mybusiness($client);
    $posts = $mybusinessService->accounts_locations_localPosts;
    $x=$posts->get("BlackSwanLimos");
     echo '
'; print_r($x); echo '
';

update:
i just opened error log and found this

19-Dec-2022 23:39:03 UTC] PHP Fatal error:  Uncaught Google_Service_Exception
[20-Dec-2022 00:00:02 UTC] PHP Notice:  Undefined index: HTTP_HOST in /home/eblatech/insights.ebla-tech.com/admin/includes/config.php on line 9
[20-Dec-2022 00:00:02 UTC] PHP Notice:  Undefined index: REQUEST_URI in /home/eblatech/insights.ebla-tech.com/admin/includes/config.php on line 9

that is the config.php

<?php
session_set_cookie_params(2*3600,"/");
session_start();
$APP_ROOT = "/insights-dashboard/admin/";
$FILES_ROOT = "/insights-dashboard/admin/files/";
$MODEL_ROOT = realpath(dirname(__FILE__) . '/../../');
$actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
define("SESSION", "insightEbla");
define("DEFAULT_LANGUAGE", "en");
// var_dump($_SESSION);
// exit;
if (!isset($_SESSION[SESSION]['lang']) || empty($_SESSION[SESSION]['lang'])) {
    $_SESSION[SESSION]['lang'] = DEFAULT_LANGUAGE;
};
$current_lang = $_SESSION[SESSION]['lang'];
if ($_SESSION[SESSION]['lang'] == 'ar') {
    require_once "lang/ar.php";
} else {
    require_once "lang/en.php";
}
require_once "page_names.php";
require_once "enum.php";
require_once  $MODEL_ROOT . '/model/db_endpoint.php';
require_once "authentication.php";
require_once "functions.php";
require_once "authorization.php";
require_once "pages_includes.php";


问:
Wagtail localize 'NoneType' object has no attribute 'block'
When trying to translate my homepage with wagtail-localize, I get the error:

AttributeError at /admin/localize/submit/page/3/
'NoneType' object has no attribute 'block'

I copied my homepage and tested. I noted that some embed blocks were blank and added a value. I could translate the copy. However when I did the same on the homepage, I had the same error message.
I then deleted fields from my homepage to check which is the problematic entry. this message keeps appearing even when my homepage is empty and I try to translate only the current page (i.e. without the children)

I also deleted my previous translated homepage and recreated and new one. The error persists.

I don't really get what to do next and would highly appreciate any input on the issue.

the traceback prints:

Environment:

Request Method: POST
Request URL: https://www.fommes.org/admin/localize/submit/page/3/

Django Version: 4.0.5
Python Version: 3.9.5
Installed Applications:
['search',
 'cms',
 'fictionary',
 'streams',
 'site_settings',
 'mangos',
 'wagtail_localize',
 'wagtail_localize.locales',
 'wagtail.contrib.forms',
 'wagtail.contrib.redirects',
 'wagtail.embeds',
 'wagtail.sites',
 'wagtail.users',
 'wagtail.snippets',
 'wagtail.documents',
 'wagtail.images',
 'wagtail.search',
 'wagtail.admin',
 'wagtail',
 'wagtail.contrib.routable_page',
 'wagtail.contrib.settings',
 'wagtail.contrib.table_block',
 'wagtail_link_block',
 'wagtailmarkdown',
 'wagtail.contrib.sitemaps',
 'django.contrib.sitemaps',
 'modelcluster',
 'taggit',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'userauth',
 'django_countries',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'django_comments_xtd',
 'django_comments',
 'widget_tweaks',
 'django_extensions',
 'compressor',
 'dbbackup',
 'wagtailcodeblock',
 'captcha',
 'wagtailcaptcha',
 'wagtailfontawesome',
 'django_jsonfield_backport']
Installed Middleware:
['django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'wagtail.contrib.redirects.middleware.RedirectMiddleware']

Traceback (most recent call last):
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail/admin/urls/__init__.py", line 161, in wrapper
    return view_func(request, *args, **kwargs)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail/admin/auth.py", line 182, in decorated_view
    response = view_func(request, *args, **kwargs)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/django/views/generic/base.py", line 84, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail_localize/views/submit_translations.py", line 175, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/django/views/generic/base.py", line 119, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail_localize/views/submit_translations.py", line 119, in post
    return self.form_valid(form)
  File "/usr/local/lib/python3.9/contextlib.py", line 79, in inner
    return func(*args, **kwds)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail_localize/views/submit_translations.py", line 126, in form_valid
    translate_object(
  File "/usr/local/lib/python3.9/contextlib.py", line 79, in inner
    return func(*args, **kwds)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail_localize/operations.py", line 90, in translate_object
    translator.create_translations(instance)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail_localize/operations.py", line 79, in create_translations
    translation.save_target(user=self.user, publish=publish)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail_localize/models.py", line 1334, in save_target
    self.source.create_or_update_translation(
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail_localize/models.py", line 763, in create_or_update_translation
    ingest_segments(original, translation, self.locale, locale, segments)
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail_localize/segments/ingest.py", line 268, in ingest_segments
    StreamFieldSegmentsWriter(
  File "/home/teki/.virtualenvs/fommenv/lib/python3.9/site-packages/wagtail_localize/segments/ingest.py", line 235, in handle_stream_block
    block.value = self.handle_block(block.block, block.value, segments)

Exception Type: AttributeError at /admin/localize/submit/page/3/
Exception Value: 'NoneType' object has no attribute 'block'```


问:
Access child class variable in parent class with no instances
I have a class that other classes herit from:

class BaseManager:
    model = Base

    @classmethod
    def get_by_id(cls, db: Session, id: int):
        return db.query(cls.model).filter(cls.model.id == id).one()

class UserManager(BaseManager):
    model = User

```
<p>And it is used this way:</p>
<pre class="lang-py prettyprint-override"><code>user = UserManager.get_by_id(db=db, id=user_id)
</code>```

But the UserManager is ignoring the model defined in it, using the Base defined on BaseManager. How can I proceed?

I have already saw implementations such as django forms using metaclass and for example this question over here Access child class variable in parent class but I think that they don't apply to this context, i tried and did not succeed.

Body:
I have a class that other classes herit from:

class BaseManager:
    model = Base

    @classmethod
    def get_by_id(cls, db: Session, id: int):
        return db.query(cls.model).filter(cls.model.id == id).one()

class UserManager(BaseManager):
    model = User

And it is used this way:

user = UserManager.get_by_id(db=db, id=user_id)

But the UserManager is ignoring the model defined in it, using the Base defined on BaseManager. How can I proceed?

I have already saw implementations such as django forms using metaclass and for example this question over here Access child class variable in parent class but I think that they don't apply to this context, i tried and did not succeed.


问:
Projections of points from 3D to 2D using Hololens 2
I used PhotoCapture to obtain an object of type PhotoCaptureFrame from which I was able to extract the extrinsic matrix.  Everything works when I hold the Hololens completely still, but if I try to rotate or translate it I can't get good results.  Has anyone ever projected points from 3D to 2D with Hololens 2?

I'm using Unity version 2022.1.17f1 and the code I used to get the extrinsic matrix and the intrinsic matrix is as follows:

void OnCapturedPhotoToMemory(PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame)
    {
        if (result.success)
        {
            Debug.Log("Saved Photo to disk!");

            if (photoCaptureFrame.TryGetProjectionMatrix(out Matrix4x4 projectionMatrix))
            {
                StreamWriter sw = new StreamWriter(
                    Application.persistentDataPath +
                    string.Format("/ProjectionMatrix{0}.txt", count)
                );

                sw.WriteLine(projectionMatrix.ToString());
                sw.Close();
            }
            else
            {
                Debug.Log("Failed to save camera matrix");
            }

            if (photoCaptureFrame.TryGetCameraToWorldMatrix(out Matrix4x4 cameraMatrix))
            {
                StreamWriter sw = new StreamWriter(
                    Application.persistentDataPath +
                    string.Format("/WorldMatrix{0}.txt", count)
                );

                sw.WriteLine(cameraMatrix.inverse.ToString());
                sw.Close();
            }
            else
            {
                Debug.Log("Failed to save world matrix");
            }

            StreamWriter s = new StreamWriter(
                Application.persistentDataPath +
                string.Format("/worldToCameraMatrix{0}.txt", count++)
            );

            s.WriteLine(cam.worldToCameraMatrix.inverse.ToString());
            s.Close();

            photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
        }
        else
        {
            Debug.Log("Failed to save Photo to disk");
        }
    }
```
<p>An instance of image is the following one:</p>
<p>Example 1</p>
<p>The red dots were created with Unity and the world coordinates of these dots were saved in appropriate CSV files.</p>
<p>The main goal is to use the intrinsic matrix and the extrinsic matrix to project the points from 3D to 2D and in order to do this I used this code in Python:</p>
<pre class="lang-py prettyprint-override"><code>
# readMatrix() is a function used to read the Matrix4x4 obtained by PhotoCaptureFrame in Unity

extrinsic_matrix = readMatrix(f"{WorldMatrices[image_index]}")

# I extract the rotation matrix

rotation_matrix = np.array([row[0:-1] for row in extrinsic_matrix[0:-1]]).copy()

rotation_matrix_ = rotation_matrix.copy()

###########################################################

print("Unity Matrix4x4: ")

print(rotation_matrix_)

# I change the coordinate system axes from OpenGL to OpenCV

rotation_matrix_[1][0] *= -1

rotation_matrix_[1][2] *= -1

rotation_matrix_[1][2] *= -1

rotation_matrix_[2][0] *= -1

rotation_matrix_[2][3] *= -1

rotation_matrix_[2][2] *= -1

###########################################################

print("Rotation Matrix: ")

print(rotation_matrix_)

# I extract the translation vector

translation_vector = np.array([row[-1] for row in extrinsic_matrix[0:-1]]).copy()

translation_vector[1] *= -1

translation_vector[2] *= -1

###########################################################

print("Translation Vector:")

print(translation_vector)

# I read the 3D coordinates of the 3D red points and I use the cv2.projectPoints

for key in vertices.keys():

    points, _ = cv2.projectPoints(

        np.float32(vertices[key]),

        rotation_matrix_,

        translation_vector,

        camera_matrix_,

        None)

    for point in points:

        x, y = (point[0][0], point[0][4])

        x = int(x * width/2 +  width/2)

        y = int(y * height/2 +  height/2)

        cv2.circle(image, (x, y), radius=20, color=(255, 0, 0), thickness=-1)

###########################################################

plt.imshow(image[...,::-1])

plt.show()

</code>```

The elements of the extrinsic matrix and the translation vector that have been multiplied by -1 are needed to go from a coordinate system defined on OpenGL to a coordinate system based on OpenCV.

An instance of output is the following one:

Example 2

I expected the blue dots to coincide with the red dots, but that doesn't happen. This is what I meant by "can't get good results".

Body:
I used PhotoCapture to obtain an object of type PhotoCaptureFrame from which I was able to extract the extrinsic matrix.  Everything works when I hold the Hololens completely still, but if I try to rotate or translate it I can't get good results.  Has anyone ever projected points from 3D to 2D with Hololens 2?

I'm using Unity version 2022.1.17f1 and the code I used to get the extrinsic matrix and the intrinsic matrix is as follows:

void OnCapturedPhotoToMemory(PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame)
    {
        if (result.success)
        {
            Debug.Log("Saved Photo to disk!");

            if (photoCaptureFrame.TryGetProjectionMatrix(out Matrix4x4 projectionMatrix))
            {
                StreamWriter sw = new StreamWriter(
                    Application.persistentDataPath +
                    string.Format("/ProjectionMatrix{0}.txt", count)
                );

                sw.WriteLine(projectionMatrix.ToString());
                sw.Close();
            }
            else
            {
                Debug.Log("Failed to save camera matrix");
            }

            if (photoCaptureFrame.TryGetCameraToWorldMatrix(out Matrix4x4 cameraMatrix))
            {
                StreamWriter sw = new StreamWriter(
                    Application.persistentDataPath +
                    string.Format("/WorldMatrix{0}.txt", count)
                );

                sw.WriteLine(cameraMatrix.inverse.ToString());
                sw.Close();
            }
            else
            {
                Debug.Log("Failed to save world matrix");
            }

            StreamWriter s = new StreamWriter(
                Application.persistentDataPath +
                string.Format("/worldToCameraMatrix{0}.txt", count++)
            );

            s.WriteLine(cam.worldToCameraMatrix.inverse.ToString());
            s.Close();

            photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
        }
        else
        {
            Debug.Log("Failed to save Photo to disk");
        }
    }

An instance of image is the following one:

Example 1

The red dots were created with Unity and the world coordinates of these dots were saved in appropriate CSV files.

The main goal is to use the intrinsic matrix and the extrinsic matrix to project the points from 3D to 2D and in order to do this I used this code in Python:

# readMatrix() is a function used to read the Matrix4x4 obtained by PhotoCaptureFrame in Unity

extrinsic_matrix = readMatrix(f"{WorldMatrices[image_index]}")

# I extract the rotation matrix

rotation_matrix = np.array([row[0:-1] for row in extrinsic_matrix[0:-1]]).copy()

rotation_matrix_ = rotation_matrix.copy()

###########################################################

print("Unity Matrix4x4: ")

print(rotation_matrix_)

# I change the coordinate system axes from OpenGL to OpenCV

rotation_matrix_[1][0] *= -1

rotation_matrix_[1][2] *= -1

rotation_matrix_[1][2] *= -1

rotation_matrix_[2][0] *= -1

rotation_matrix_[2][3] *= -1

rotation_matrix_[2][2] *= -1

###########################################################

print("Rotation Matrix: ")

print(rotation_matrix_)

# I extract the translation vector

translation_vector = np.array([row[-1] for row in extrinsic_matrix[0:-1]]).copy()

translation_vector[1] *= -1

translation_vector[2] *= -1

###########################################################

print("Translation Vector:")

print(translation_vector)

# I read the 3D coordinates of the 3D red points and I use the cv2.projectPoints

for key in vertices.keys():

    points, _ = cv2.projectPoints(

        np.float32(vertices[key]),

        rotation_matrix_,

        translation_vector,

        camera_matrix_,

        None)

    for point in points:

        x, y = (point[0][0], point[0][4])

        x = int(x * width/2 +  width/2)

        y = int(y * height/2 +  height/2)

        cv2.circle(image, (x, y), radius=20, color=(255, 0, 0), thickness=-1)

###########################################################

plt.imshow(image[...,::-1])

plt.show()

The elements of the extrinsic matrix and the translation vector that have been multiplied by -1 are needed to go from a coordinate system defined on OpenGL to a coordinate system based on OpenCV.

An instance of output is the following one:

Example 2

I expected the blue dots to coincide with the red dots, but that doesn't happen. This is what I meant by "can't get good results".


问:
ROS: Display sensor_msgs/Image image form a custom topic
I have a problem with debugging my ROS code. I can't display an image to verify proper tracking.

Is there an easy way to display images from a custom message using a terminal, or do I have to write a new node that will display the image?

My message:

std_msgs/Header header

uint64[] object_ids

uint16[] class_ids

float32[] confs

int16[] x_coords

int16[] y_coords

int16[] bb_width

int16[] bb_hight

sensor_msgs/Image source_image

I want to display source_image coming from a topic /tracker_topic.

I tried using topic_tools relay_field, but I'm using python 3 which doesn't use Unicode, and I'm getting errors because of that.


问:
The application could not be installed: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
I am trying to upgrade the targetSdkVersion of the APP I am in charge of from 30 to 31.

I keep getting this error when I try to install it on my test cell phone:

I looked through the logcat by referring to other articles with similar symptoms, but there is no 271rd line in my manifests.

Below is my logcat error part.

I added android, exported to all items in manifest, upgraded Gradle Version to 6.1.1 and Gradle plugin to 4.0.1 but I still get this error.

There are no capital letters in the path.


问:
Recurrent neural network LSTM problem solved using 1 epoch
Looking at a solved problem on which the goal is to make predictions of stock price I've found that only 1 epoch is used to solve it. The data is composed of little less than 1500 points each corresponding to a daily closing price. So we have a dataset of dates (days) and prices.

Using LSTM approach the X_train training set is generated as:

Original dataset:

```<code>    Date     Price
    1-1-2010 100
    2-1-2010 80
    3-1-2010 50
    4-1-2010 40
    5-1-2010 70
    ...
    30-10-2012 130
    ...
</code>```

X_train:

```<code>[[100, 80, 50, 40, 70, ...],
[80, 50, 40, 70, 90, ...],
[50, 40, 70, 90, 95, ...],
...
[..., 78, 85, 72, 60, 105],
[..., 85, 72, 60, 105, 130]]
</code>```

The training set is 60 in length and shifted by one day everytime until a fraction of the total dataframe is reached (training set). Please don't consider things like normalization, etc. This is just an example.

The thing is that in the training part of the problem the epochs are set to 1, this is the first time I see this approach of considering just one pass through the data to train the model. I've searched about it but to no avail.

Does anyone knows how this technique is called (if it has a name) so I can search more about it?

Body:
Looking at a solved problem on which the goal is to make predictions of stock price I've found that only 1 epoch is used to solve it. The data is composed of little less than 1500 points each corresponding to a daily closing price. So we have a dataset of dates (days) and prices.

Using LSTM approach the X_train training set is generated as:

Original dataset:

    Date     Price
    1-1-2010 100
    2-1-2010 80
    3-1-2010 50
    4-1-2010 40
    5-1-2010 70
    ...
    30-10-2012 130
    ...

X_train:

[[100, 80, 50, 40, 70, ...],
[80, 50, 40, 70, 90, ...],
[50, 40, 70, 90, 95, ...],
...
[..., 78, 85, 72, 60, 105],
[..., 85, 72, 60, 105, 130]]

The training set is 60 in length and shifted by one day everytime until a fraction of the total dataframe is reached (training set). Please don't consider things like normalization, etc. This is just an example.

The thing is that in the training part of the problem the epochs are set to 1, this is the first time I see this approach of considering just one pass through the data to train the model. I've searched about it but to no avail.

Does anyone knows how this technique is called (if it has a name) so I can search more about it?


问:
Webfleet .connect API not available for Webfleet LITE subscriptions?
is that true? Webfleet .connect API is not available for Webfleet Lite subscriptions?

BR, Rene


问:
Replicate shadertoy example in SFML?
I would like to replicate this in SFML, so I wrote this:

Main.cpp

```<code>#include <SFML/Graphics.hpp>

#define WIDTH 800
int main() {
    sf::RenderWindow window(sf::VideoMode(WIDTH, WIDTH), "Test");

    sf::Shader shader, buffer;
    shader.loadFromFile("shader.frag", sf::Shader::Fragment);
    buffer.loadFromFile("buffer.frag", sf::Shader::Fragment);

    sf::Shader *shaders[] = {&shader, &buffer};
    sf::Texture texture;
    texture.create(WIDTH, WIDTH);

    sf::RenderTexture renderTexture;

    sf::Vector2f mousePos = sf::Vector2f(-1.f, -1.f);
    for(auto &shader : shaders) {
        shader->setUniform("iChannel0", texture);
        shader->setUniform("iResolution", sf::Glsl::Vec2(WIDTH, WIDTH));
    }
    auto time = sf::Clock();

    sf::Sprite sprite(texture);
    while(window.isOpen()) {
        sf::Event currEvent;
        while(window.pollEvent(currEvent)) {
            switch(currEvent.type) {
                case(sf::Event::Closed): window.close(); break;
                case(sf::Event::MouseMoved):
                    mousePos = sf::Vector2f(
                        currEvent.mouseMove.x, currEvent.mouseMove.y);
                    break;
            }
        }

        buffer.setUniform("iTime", time.getElapsedTime().asSeconds());
        buffer.setUniform("iMouse", sf::Glsl::Vec2(
            mousePos.x, WIDTH - mousePos.y));

        sf::RenderStates states;
        states.blendMode = sf::BlendAdd;
        states.shader = &buffer;
        renderTexture.clear(sf::Color::Transparent);
        renderTexture.draw(sf::Sprite(texture), states);
        renderTexture.display();
        sprite.setTexture(renderTexture.getTexture());

        window.clear(sf::Color::Black);
        window.draw(sprite, &shader);
        window.display();
    }
}
</code>```

Buffer.frag

```<code>#version 140
out vec4 out_Colour;

uniform sampler2D iChannel0;
uniform vec2 iResolution;
uniform vec2 iMouse;
uniform float iTime;

void main(void){
    vec2 mouse = iMouse.xy;
    if(mouse.x <= 0.)
        mouse = vec2(iResolution.x * (sin(iTime)+1.)/2., iResolution.y/2.);
    vec3 blob = vec3(.11-clamp(
        length((
            gl_FragCoord.xy-mouse.xy)/iResolution.x),0.,.11))*2.;
    vec3 stack = texture(
        iChannel0,gl_FragCoord.xy/iResolution.xy).xyz * vec3(0.99,.982,.93);
    out_Colour = vec4(stack + blob, 1.0);
}
</code>```

Shader.frag

```<code>#version 140
out vec4 out_Colour;

uniform sampler2D iChannel0;
uniform vec2 iResolution;

void main(void){
    out_Colour = vec4(texture(
        iChannel0, gl_FragCoord.xy / iResolution.xy).xyz, 1.0);
}
</code>```

I am probably missing something with the buffers.

Similar questions without clear answer:

shadertoy to SFML

Title: Replicate shadertoy example in SFML?

Body:
I would like to replicate this in SFML, so I wrote this:

Main.cpp

#include <SFML/Graphics.hpp>

#define WIDTH 800
int main() {
    sf::RenderWindow window(sf::VideoMode(WIDTH, WIDTH), "Test");

    sf::Shader shader, buffer;
    shader.loadFromFile("shader.frag", sf::Shader::Fragment);
    buffer.loadFromFile("buffer.frag", sf::Shader::Fragment);

    sf::Shader *shaders[] = {&shader, &buffer};
    sf::Texture texture;
    texture.create(WIDTH, WIDTH);

    sf::RenderTexture renderTexture;

    sf::Vector2f mousePos = sf::Vector2f(-1.f, -1.f);
    for(auto &shader : shaders) {
        shader->setUniform("iChannel0", texture);
        shader->setUniform("iResolution", sf::Glsl::Vec2(WIDTH, WIDTH));
    }
    auto time = sf::Clock();

    sf::Sprite sprite(texture);
    while(window.isOpen()) {
        sf::Event currEvent;
        while(window.pollEvent(currEvent)) {
            switch(currEvent.type) {
                case(sf::Event::Closed): window.close(); break;
                case(sf::Event::MouseMoved):
                    mousePos = sf::Vector2f(
                        currEvent.mouseMove.x, currEvent.mouseMove.y);
                    break;
            }
        }

        buffer.setUniform("iTime", time.getElapsedTime().asSeconds());
        buffer.setUniform("iMouse", sf::Glsl::Vec2(
            mousePos.x, WIDTH - mousePos.y));

        sf::RenderStates states;
        states.blendMode = sf::BlendAdd;
        states.shader = &buffer;
        renderTexture.clear(sf::Color::Transparent);
        renderTexture.draw(sf::Sprite(texture), states);
        renderTexture.display();
        sprite.setTexture(renderTexture.getTexture());

        window.clear(sf::Color::Black);
        window.draw(sprite, &shader);
        window.display();
    }
}

Buffer.frag

#version 140
out vec4 out_Colour;

uniform sampler2D iChannel0;
uniform vec2 iResolution;
uniform vec2 iMouse;
uniform float iTime;

void main(void){
    vec2 mouse = iMouse.xy;
    if(mouse.x <= 0.)
        mouse = vec2(iResolution.x * (sin(iTime)+1.)/2., iResolution.y/2.);
    vec3 blob = vec3(.11-clamp(
        length((
            gl_FragCoord.xy-mouse.xy)/iResolution.x),0.,.11))*2.;
    vec3 stack = texture(
        iChannel0,gl_FragCoord.xy/iResolution.xy).xyz * vec3(0.99,.982,.93);
    out_Colour = vec4(stack + blob, 1.0);
}

Shader.frag

#version 140
out vec4 out_Colour;

uniform sampler2D iChannel0;
uniform vec2 iResolution;

void main(void){
    out_Colour = vec4(texture(
        iChannel0, gl_FragCoord.xy / iResolution.xy).xyz, 1.0);
}

I am probably missing something with the buffers.

Similar questions without clear answer:

shadertoy to SFML


问:
Why do I get the error "'T' could be instantiated with a different subtype of constraint" for the this value of T?
In the code below, I get an error and don't understand why the error applies.

class A {
    boop(): this {
        return this;
    }
}

class B {
    boop(): this {
        return this;
    }
}

function boopSnoot<T extends A | B>(snoot: T): T {
    return snoot.boop(); // error
}

function identity<T extends A | B>(snoot: T): T {
    return snoot; // no error
}
```
<p>yields the error</p>
```'A | B' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A | B'.
  Type 'A' is not assignable to type 'T'.
    'A' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A | B'.
```

Not only is T guaranteed to be the exact same type that was passed in, no matter the subclass, it also returns the same exact object. Why does the error apply?

Body:
In the code below, I get an error and don't understand why the error applies.

class A {
    boop(): this {
        return this;
    }
}

class B {
    boop(): this {
        return this;
    }
}

function boopSnoot<T extends A | B>(snoot: T): T {
    return snoot.boop(); // error
}

function identity<T extends A | B>(snoot: T): T {
    return snoot; // no error
}

yields the error

'A | B' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A | B'.
  Type 'A' is not assignable to type 'T'.
    'A' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A | B'.

Not only is T guaranteed to be the exact same type that was passed in, no matter the subclass, it also returns the same exact object. Why does the error apply?


问:
How to return the value using tkinter oop?
At the below code , I had the variable done, minute and second. When the button on tkinter   clicked ,  the variable done will pass the value 1 to set_timer_counter_process()  function to run the clock. While , the minute and second variable are passing the minute value and second value to the set _timer_counter_process() parameters which are minute and second . For example, will the button on GUI press, the done allow counter automatically run . At the same time , the variable minute and second will pass the value 1 minute zero second to the timer counter.

Problem:

I try to pass the value when the button pressed. However, the done variable seem to be always 1 . It should only equal to 1 after the button is pressed. While, the minute and second variable not passed to the set_timer_counter_process() function

code :

```<code>import tkinter as tk
from tkinter import ttk

class graphic(tk.Tk):
    def __init__(self):
        super().__init__()
        self.done = 0
        self.minute = 0
        self.second = 0
        self.title('Automation Cleaning Process')
        self.geometry('1000x800+100+100')
        self.resizable(False, False)
        self.set_button()
        self.set_text_gui()
        self.set_timer_counter_process(self.minute,self.second)

    def set_button(self):
        self.button_2 = ttk.Button(self, text='Automation Process',command=self.button_2_clicked_clock_counting_down, width = 50)
        self.button_2.place(x=380,y=300)

    def button_2_clicked_clock_counting_down(self):
     self.done = 1
     self.minute = 1
     self.second = 0
     self.button_2_value = 2
     print (self.button_2_value)
     print ("button 2 click ")
     return self.done, self.minute , self.second

    def set_text_gui(self):
        self.time_title = tk.Label(self, text = "Time Process:", font=("Arial",30))
        self.time_colon= tk.Label(self, text = ":", font=("Arial",30))
        self.min_label= tk.Label(self, text = "min", font=("Arial",30))
        self.second_label=tk.Label(self, text = "sec", font=("Arial",30))
        self.label_minute = tk.Label(self,font=("Arial",30))
        self.label_second = tk.Label (self,font=("Arial",30))
        self.label_minute_zero_add = tk.Label(self,font=("Arial",30))
        self.label_second_zero_add = tk.Label(self,font=("Arial",30))
        # position label

        self.time_title.place(x=80,y=630)
        self.time_colon.place(x = 230 , y = 700)
        self.min_label.place(x=150,y=700)
        self.second_label.place(x=335,y=700)
        self.label_minute.place(x = 120 , y = 700)
        self.label_second.place(x=  278 , y = 700)
        self.label_minute_zero_add.place(x=  90 ,y=700)
        self.label_second_zero_add.place(x = 250 ,y= 700)

    def set_timer_counter_process(self,minute,second):
        self.label_minute['text'] = minute
        self.label_second['text'] = second
        check_minute_length = len(str(minute))
        check_second_length = len(str(second))
        print(check_second_length)
        if check_minute_length == 1:
            self.label_minute_zero_add['text'] = 0
        else:
            self.label_minute_zero_add['text'] =''

        if check_second_length == 1:
            self.label_second_zero_add['text'] = 0
        else:
            self.label_second_zero_add['text'] =''

        if self.done == 1:
            if second  > 0 :
                second = second - 1
            elif second >= 0 :
                if minute > 0:
                    minute  = minute - 1
                    second  = 60
                else:
                    self.done = 0
        self.after(1000, self.set_timer_counter_process, minute , second)

User_graphic = graphic()
User_graphic.mainloop()

</code>```

Body:
At the below code , I had the variable done, minute and second. When the button on tkinter   clicked ,  the variable done will pass the value 1 to set_timer_counter_process()  function to run the clock. While , the minute and second variable are passing the minute value and second value to the set _timer_counter_process() parameters which are minute and second . For example, will the button on GUI press, the done allow counter automatically run . At the same time , the variable minute and second will pass the value 1 minute zero second to the timer counter.

Problem:

I try to pass the value when the button pressed. However, the done variable seem to be always 1 . It should only equal to 1 after the button is pressed. While, the minute and second variable not passed to the set_timer_counter_process() function

code :

import tkinter as tk
from tkinter import ttk

class graphic(tk.Tk):
    def __init__(self):
        super().__init__()
        self.done = 0
        self.minute = 0
        self.second = 0
        self.title('Automation Cleaning Process')
        self.geometry('1000x800+100+100')
        self.resizable(False, False)
        self.set_button()
        self.set_text_gui()
        self.set_timer_counter_process(self.minute,self.second)

    def set_button(self):
        self.button_2 = ttk.Button(self, text='Automation Process',command=self.button_2_clicked_clock_counting_down, width = 50)
        self.button_2.place(x=380,y=300)

    def button_2_clicked_clock_counting_down(self):
     self.done = 1
     self.minute = 1
     self.second = 0
     self.button_2_value = 2
     print (self.button_2_value)
     print ("button 2 click ")
     return self.done, self.minute , self.second

    def set_text_gui(self):
        self.time_title = tk.Label(self, text = "Time Process:", font=("Arial",30))
        self.time_colon= tk.Label(self, text = ":", font=("Arial",30))
        self.min_label= tk.Label(self, text = "min", font=("Arial",30))
        self.second_label=tk.Label(self, text = "sec", font=("Arial",30))
        self.label_minute = tk.Label(self,font=("Arial",30))
        self.label_second = tk.Label (self,font=("Arial",30))
        self.label_minute_zero_add = tk.Label(self,font=("Arial",30))
        self.label_second_zero_add = tk.Label(self,font=("Arial",30))
        # position label

        self.time_title.place(x=80,y=630)
        self.time_colon.place(x = 230 , y = 700)
        self.min_label.place(x=150,y=700)
        self.second_label.place(x=335,y=700)
        self.label_minute.place(x = 120 , y = 700)
        self.label_second.place(x=  278 , y = 700)
        self.label_minute_zero_add.place(x=  90 ,y=700)
        self.label_second_zero_add.place(x = 250 ,y= 700)

    def set_timer_counter_process(self,minute,second):
        self.label_minute['text'] = minute
        self.label_second['text'] = second
        check_minute_length = len(str(minute))
        check_second_length = len(str(second))
        print(check_second_length)
        if check_minute_length == 1:
            self.label_minute_zero_add['text'] = 0
        else:
            self.label_minute_zero_add['text'] =''

        if check_second_length == 1:
            self.label_second_zero_add['text'] = 0
        else:
            self.label_second_zero_add['text'] =''

        if self.done == 1:
            if second  > 0 :
                second = second - 1
            elif second >= 0 :
                if minute > 0:
                    minute  = minute - 1
                    second  = 60
                else:
                    self.done = 0
        self.after(1000, self.set_timer_counter_process, minute , second)

User_graphic = graphic()
User_graphic.mainloop()


问:
Contact Form 7 - Text indented - Can't adjust
I am seeking assistance with this extra space in front of my message field on the contact form.

When you click to start typing in the message field, it will begin where it says the word "Message." The following lines are in the exact placement.

I hope this is enough for a resolution. Please let me know if there is any additional information I can provide.

Image of contact form: https://imgur.com/a/SFfwREA

```<code>.wpcf7-form-control {
    width: 300px;
    height: 90px;
    font-size: 24px;
    float:left;
    margin: 0;
  padding: 0px;
}

/*
.wpcf7-form-control-wrap textarea {
    text-indent: -30px;

}

*/

/*CF7*/
.wpcf7-form input {
border-radius:26px;

    /* Makes the edges rounded */
}
.wpcf7-form textarea {
border-radius:6px;          /* Makes the edges rounded */
}

.wpcf7 .wpcf7-text,
.wpcf7 .wpcf7-textarea{
  padding-left:50px;
}
.wpcf7 input[type="checkbox"]{
    margin:0 !important;
        background-color: red !important
}
.wpcf7 p{ position: relative; }
.wpcf7 p .fa{
  position: absolute;
  color: #152135 ;
  z-index: 100;
  font-size: 18px;
  top: 28%;
  left: 3%;
}
.wpcf7 p .fa-pencil{ top: 5%; left: 1.5%}
.wpcf7 label{
    font-size: 25px !important;
    margin-bottom:5% !important;
}

#responsive-form{
    max-width:80%;
    margin:0 auto;
    width:100%;
    padding: 20px 0 20px 0;

}

.column-full{
float: left;
position: relative;
padding: 0.65rem;
width:100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}

.column-half{
    float: left;
    position: relative;
    padding: 0.65rem;
    width:50%;

    -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
}
.clearfix:after {
    content: "";
    display: table;
    clear: both;
}
/**---- Media query -**/
@media only screen and (max-width: 799px) {
    .column-half{
        width: 100%;
    }
}

.wpcf7 input[type="text"], .wpcf7 input[type="email"], .wpcf7 input[type="tel"] {
    height:57px;

}

.wpcf7 input[type="text"], .wpcf7 input[type="email"], .wpcf7 textarea, .wpcf7 input[type="tel"] {
    width: 85%;

    border: 1px solid #ccc;
    -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
    border: 1px solid #cacaca;
    font-size: 14px;
    color: #3e4644 !important;

    background-color: #f0f0f0;
    font-weight: 200;
}

/* Contact Form 7 Submit Button
 -------------------------------*/
 .wpcf7 input[type="submit"] {
     color: #ffffff;
     font-size: 13px;
     font-weight: 700;
     background: #E2272E;
     padding: 15px 25px 15px 25px;
     border: none;
     border-radius: 5px;
     width: auto;
       text-transform: uppercase;
     letter-spacing: 5px;
 }
 .wpcf7 input:hover[type="submit"] {
     background: #494949;
     transition: all 0.4s ease 0s;
 }
 .wpcf7 input:active[type="submit"] {
     background: #000000;
 }

</code>```

So far I tried to use the text-indent, padding, and margin to adjust it but have had no luck.

The text-indent worked the best because I was able to get the first line to look normal and type normal but when I got to the second line it started doing the same ident. Maybe if there is a way I can get the text-indent to apply to all the lines in the text box?

Lastly, thank you in advance for any help, solution, or suggestion that is provided on this post.

Body:
I am seeking assistance with this extra space in front of my message field on the contact form.

When you click to start typing in the message field, it will begin where it says the word "Message." The following lines are in the exact placement.

I hope this is enough for a resolution. Please let me know if there is any additional information I can provide.

Image of contact form: https://imgur.com/a/SFfwREA

.wpcf7-form-control {
    width: 300px;
    height: 90px;
    font-size: 24px;
    float:left;
    margin: 0;
  padding: 0px;
}

/*
.wpcf7-form-control-wrap textarea {
    text-indent: -30px;

}

*/

/*CF7*/
.wpcf7-form input {
border-radius:26px;

    /* Makes the edges rounded */
}
.wpcf7-form textarea {
border-radius:6px;          /* Makes the edges rounded */
}

.wpcf7 .wpcf7-text,
.wpcf7 .wpcf7-textarea{
  padding-left:50px;
}
.wpcf7 input[type="checkbox"]{
    margin:0 !important;
        background-color: red !important
}
.wpcf7 p{ position: relative; }
.wpcf7 p .fa{
  position: absolute;
  color: #152135 ;
  z-index: 100;
  font-size: 18px;
  top: 28%;
  left: 3%;
}
.wpcf7 p .fa-pencil{ top: 5%; left: 1.5%}
.wpcf7 label{
    font-size: 25px !important;
    margin-bottom:5% !important;
}

#responsive-form{
    max-width:80%;
    margin:0 auto;
    width:100%;
    padding: 20px 0 20px 0;

}

.column-full{
float: left;
position: relative;
padding: 0.65rem;
width:100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}

.column-half{
    float: left;
    position: relative;
    padding: 0.65rem;
    width:50%;

    -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
}
.clearfix:after {
    content: "";
    display: table;
    clear: both;
}
/**---- Media query -**/
@media only screen and (max-width: 799px) {
    .column-half{
        width: 100%;
    }
}

.wpcf7 input[type="text"], .wpcf7 input[type="email"], .wpcf7 input[type="tel"] {
    height:57px;

}

.wpcf7 input[type="text"], .wpcf7 input[type="email"], .wpcf7 textarea, .wpcf7 input[type="tel"] {
    width: 85%;

    border: 1px solid #ccc;
    -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
    border: 1px solid #cacaca;
    font-size: 14px;
    color: #3e4644 !important;

    background-color: #f0f0f0;
    font-weight: 200;
}

/* Contact Form 7 Submit Button
 -------------------------------*/
 .wpcf7 input[type="submit"] {
     color: #ffffff;
     font-size: 13px;
     font-weight: 700;
     background: #E2272E;
     padding: 15px 25px 15px 25px;
     border: none;
     border-radius: 5px;
     width: auto;
       text-transform: uppercase;
     letter-spacing: 5px;
 }
 .wpcf7 input:hover[type="submit"] {
     background: #494949;
     transition: all 0.4s ease 0s;
 }
 .wpcf7 input:active[type="submit"] {
     background: #000000;
 }

So far I tried to use the text-indent, padding, and margin to adjust it but have had no luck.

The text-indent worked the best because I was able to get the first line to look normal and type normal but when I got to the second line it started doing the same ident. Maybe if there is a way I can get the text-indent to apply to all the lines in the text box?

Lastly, thank you in advance for any help, solution, or suggestion that is provided on this post.


问:
Reading old Pre-existing discord messages with the use of custom bot
I am making a bot with the goal of reading in messages from a specific server channel and having the bot store it in a list for later use in another function. I currently do not know how to do this. I am making the bot in java script, also with the aided use of node and discord.js

help is much appreciated
Thanks

```<code>// there doesn't need to be any code here really but I am new to JS

if(!message?.author.bot && message === '/quote') {
        message.author.send(//I wish to call the function in here to print )
    }

//this likes within the

client.on("messageCreate", async (message) =>

//method
</code>```

Body:
I am making a bot with the goal of reading in messages from a specific server channel and having the bot store it in a list for later use in another function. I currently do not know how to do this. I am making the bot in java script, also with the aided use of node and discord.js

help is much appreciated
Thanks

// there doesn't need to be any code here really but I am new to JS

if(!message?.author.bot && message === '/quote') {
        message.author.send(//I wish to call the function in here to print )
    }

//this likes within the

client.on("messageCreate", async (message) =>

//method


问:
Add onesignal push notification to better message buddypress plugin
I've already set all on my webview on mobile I've just to hook the onesignal message create function to the better message function to send message, the message will be sent to external user id that will be the same as the wordpress username of the receiver, I'm not able to execute the function when the message is sent, are few weeks that I'm trying, I've set it in JavaScript so that when the user press the sent button the function get triggered but is client-side and has a lot of problem, i need to do that server side when the message is created, if you can help me it will be very helpful thank you so much</p>


问:
docker compose version 3 restart on-failure
I was looking for delay start of last service in my docker-compose.yml but dont see a sleep option as it needs a restart if it fails on first time including depends_on

for using below restart : on-failure in version 3

version: '3'
restart: on-failure

from releases here  see only 2.x but no 3.x ?
https://github.com/docker/compose/releases


问:
Clicking on unmute does not unmute html video player
I am trying to figure out why clicking on the unmute icon does not unmute the audio. Instead the user would have to drag the volume bar in order for the audio to unmute itself. Basically the image below:

Does anyone know why that is behaving that way? Any help is appreciated. Thanks!


问:
I can't pass the information in the firestore to the properties of the object in kotlin
There is data in the following structure in Firestore:

link1 i.stack.imgur.com/jUwPE.png

```<code>collection: Cards
Document: albus
field : resim
</code>```

I want to save all of this data in the object I created in kotlin as follows:

```<code>    lateinit var decoded_cardBackground : Bitmap
    lateinit var decoded_card1: Bitmap

    init{

        var collection = Firebase.firestore.collection("Cards")

        collection.document("albus").get()
            .addOnSuccessListener{ document->

            val base64 = document.data!!["resim"].toString()
            val imageBytes = Base64.decode(base64, Base64.DEFAULT)
            decoded_card1 = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
            }
        }
</code>```

Then I want to use this data in another activity:

```<code>val card = CardsFromFirebase()
CardsBackground = card.decoded_cardBackground
card1 = card.decoded_card1
card2 = card.decoded_card1
</code>```

I tried to adapt my code using Picasso library. but I can't use it because of the structure I'm     using.

Body:
There is data in the following structure in Firestore:

link1 i.stack.imgur.com/jUwPE.png

collection: Cards
Document: albus
field : resim

I want to save all of this data in the object I created in kotlin as follows:

    lateinit var decoded_cardBackground : Bitmap
    lateinit var decoded_card1: Bitmap

    init{

        var collection = Firebase.firestore.collection("Cards")

        collection.document("albus").get()
            .addOnSuccessListener{ document->

            val base64 = document.data!!["resim"].toString()
            val imageBytes = Base64.decode(base64, Base64.DEFAULT)
            decoded_card1 = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
            }
        }

Then I want to use this data in another activity:

val card = CardsFromFirebase()
CardsBackground = card.decoded_cardBackground
card1 = card.decoded_card1
card2 = card.decoded_card1

I tried to adapt my code using Picasso library. but I can't use it because of the structure I'm     using.


问:
Creating a function that returns a new dataframe that can be saved- but will not rewrite the new dataframe each time it runs
I want to create a function that takes a dataframe, makes changes, and creates a new dataframe. I want to apply this code to 200+ datasets. How do I apply a function that will save a new dataframe- but not continuously overwrite it?

Here is my code:

```<code>for (i in KO_AFEPSI) {
  i <- i[i$AFEPSI != 1,]
  i <- separate(i,exon,into=c("chromosome", "start", "end"))
  i_plus <- subset(i, strand == "+")
  i_plus <- i_plus[order(i_plus$start),]
  i_plus <-  transform(i_plus, Order = ave(1:nrow(i_plus), gene,FUN = seq_along))
  i_minus <- subset(i, strand == "-")
  i_minus <- i_minus[order(i_minus$start, decreasing = TRUE),]
  i_minus <-  transform(i_minus, Order = ave(1:nrow(i_minus), gene,FUN = seq_along))
  i <- bind_rows(i_plus, i_minus)
  i_upstream_exon <- i %>% group_by(gene)  %>% slice_min(Order)
  i_downstream_exon <- i %>% group_by(gene)  %>% slice_max(Order)
  data <- merge(i_upstream_exon, i_downstream_exon, by = "gene", all = FALSE)
}
</code>```

I basically want to save a new "data" for each dataframe I run through the function. How should i go about this??

Should I be using lapply?

Body:
I want to create a function that takes a dataframe, makes changes, and creates a new dataframe. I want to apply this code to 200+ datasets. How do I apply a function that will save a new dataframe- but not continuously overwrite it?

Here is my code:

for (i in KO_AFEPSI) {
  i <- i[i$AFEPSI != 1,]
  i <- separate(i,exon,into=c("chromosome", "start", "end"))
  i_plus <- subset(i, strand == "+")
  i_plus <- i_plus[order(i_plus$start),]
  i_plus <-  transform(i_plus, Order = ave(1:nrow(i_plus), gene,FUN = seq_along))
  i_minus <- subset(i, strand == "-")
  i_minus <- i_minus[order(i_minus$start, decreasing = TRUE),]
  i_minus <-  transform(i_minus, Order = ave(1:nrow(i_minus), gene,FUN = seq_along))
  i <- bind_rows(i_plus, i_minus)
  i_upstream_exon <- i %>% group_by(gene)  %>% slice_min(Order)
  i_downstream_exon <- i %>% group_by(gene)  %>% slice_max(Order)
  data <- merge(i_upstream_exon, i_downstream_exon, by = "gene", all = FALSE)
}

I basically want to save a new "data" for each dataframe I run through the function. How should i go about this??

Should I be using lapply?


问:
in Visual Studio 2022, Break point is not working
When i put a break point on code line in visual studio 2022 it didn't stop on that line.

I'm trying to develop an Asp.Net Core Mvc project. I had a more project too. And break point is not working in that project too. But when i try to type code in Console Application and i want to put a break point it's working.

I watched videos on youtube.
I visited Microsoft Web Site.


问:
Whole project resets to default in Unreal
Pretty much; i open a new premade project in Unreal, i modify simple things, such as : place new objects, create simple blueprint in Level Blueprint (so it affects the level) and then save and close.

Problem is, next time i open that project, EVERYTHING is reset to default, like i haven't touched anything and I'm forced to redo everything, thing that is annoying when you followed a course.

Any help on how to actually save my changes? This is severely impacting my studies.

I tried to save the project and set the map i used as default map when opening the project.

I tried to save layout (might not be useful at all, but I'm still green in Unreal)

Tried to save the blueprint of the level but still nothing, even compiling doesn't seem do do anything to lock it and save it.


问:
How do I remote invoke a windows command from a docker container?
I need to remotely run a command on my window's workstation from my osx workstation using docker.

Works locally:

```<code>docker run -it  mcr.microsoft.com/powershell pwsh -c "Write-Host 'Hello, World'"`
Hello, World
</code>```

Doesn't work remote:

```<code>docker run -it  mcr.microsoft.com/powershell pwsh -c Invoke-Command -ComputerName VM-CHIP -ScriptBlock { Write-Host 'Hello, World' }
Invoke-Command: This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system.
</code>```

When I try within the container

```<code>docker run -it  mcr.microsoft.com/powershell
PowerShell 7.2.8
Copyright (c) Microsoft Corporation.

https://aka.ms/powershell
Type 'help' to get help.

PS /> Install-Module -Name PSWSMan

Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from 'PSGallery'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): A
PS /> Install-WSMan
WARNING: WSMan libs have been installed, please restart your PowerShell session to enable it in PowerShell
PS /> Invoke-Command -ComputerName VM-CHIP -ScriptBlock { Write-Host 'Hello, World' }
</code>```

it fails with

```<code>OpenError: [VM-CHIP] Connecting to remote server VM-CHIP failed with the following error message : MI_RESULT_FAILED For more information, see the about_Remote_Troubleshooting Help topic.
</code>```

I'm confused what the structure is to run this within a single command intead of having to open interactive, and more importantly what am I missing to successfully execute the command on the remote machine instead of this MI_RESULT_FAILED error. Or is this not possible/supported?

Body:
I need to remotely run a command on my window's workstation from my osx workstation using docker.

Works locally:

docker run -it  mcr.microsoft.com/powershell pwsh -c "Write-Host 'Hello, World'"`
Hello, World

Doesn't work remote:

docker run -it  mcr.microsoft.com/powershell pwsh -c Invoke-Command -ComputerName VM-CHIP -ScriptBlock { Write-Host 'Hello, World' }
Invoke-Command: This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system.

When I try within the container

docker run -it  mcr.microsoft.com/powershell
PowerShell 7.2.8
Copyright (c) Microsoft Corporation.

https://aka.ms/powershell
Type 'help' to get help.

PS /> Install-Module -Name PSWSMan

Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from 'PSGallery'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): A
PS /> Install-WSMan
WARNING: WSMan libs have been installed, please restart your PowerShell session to enable it in PowerShell
PS /> Invoke-Command -ComputerName VM-CHIP -ScriptBlock { Write-Host 'Hello, World' }

it fails with

OpenError: [VM-CHIP] Connecting to remote server VM-CHIP failed with the following error message : MI_RESULT_FAILED For more information, see the about_Remote_Troubleshooting Help topic.

I'm confused what the structure is to run this within a single command intead of having to open interactive, and more importantly what am I missing to successfully execute the command on the remote machine instead of this MI_RESULT_FAILED error. Or is this not possible/supported?


问:
Percentage of each small multiple in power bi?
There is a relatively recent feature in power bi called small multiple. Basically it allows you to segment a variable into several subcategories. See image:

The thing is that this functionality does not perform the percentage of each subcategory but takes into account other categories. There is an option that would be to create different variables and perform a calculation like the one shown below, however, in my case I would have to work with many variables and when trying to do so I am limited.

Any alternative to this?

```<code>Hourcounts_f = VAR Total_eu = CALCULATE ([HourCounts],ALL ( df[Destination] = "Europe") VAR Total_af= CALCULATE ([HourCounts],ALL ( df),df[Destination] = "Africa")

RETURN SWITCH (true(),
        SELECTEDVALUE ( df[Destination] )=
        "Europe", DIVIDE ( [HourCounts], Total_eu, 0 )*100

</code>```

I found some posts of similar issues but this case in particular did not work for me: Small multiples: % of Total of every single multiple

Body:
There is a relatively recent feature in power bi called small multiple. Basically it allows you to segment a variable into several subcategories. See image:

The thing is that this functionality does not perform the percentage of each subcategory but takes into account other categories. There is an option that would be to create different variables and perform a calculation like the one shown below, however, in my case I would have to work with many variables and when trying to do so I am limited.

Any alternative to this?

Hourcounts_f = VAR Total_eu = CALCULATE ([HourCounts],ALL ( df[Destination] = "Europe") VAR Total_af= CALCULATE ([HourCounts],ALL ( df),df[Destination] = "Africa")

RETURN SWITCH (true(),
        SELECTEDVALUE ( df[Destination] )=
        "Europe", DIVIDE ( [HourCounts], Total_eu, 0 )*100

I found some posts of similar issues but this case in particular did not work for me: Small multiples: % of Total of every single multiple


问:
Overwriting a global variable in a function and then calling it
I'm new to programming and I need a help. So, I'm trying to make a typing game using pygame. What I want to do is let the user choose the timer the user wants for the game. What I'm trying to do is if the function the_time is called, It will overwrite the variables necessary for controlling the time.

How do I make the values inside the button conditional statement, be accessed in another function?

This is my code:

```<code>def the_time(Timer):
    while True:
        global usertime, cc, wh, w, h
        win.fill(bg)
#BUTTONS
        MENU_MOUSE_POS = pg.mouse.get_pos()

        MENU_TEXT = text_font.render("SELECT TIME", True, text_correct)
        MENU_RECT = MENU_TEXT.get_rect(center=(720, 100))
        TIME1 = Button(image=pg.image.load("button.png"), pos=(720, 250),
                               text_input="30", font=text_font, base_color=text_color, hovering_color="White")
        TIME2 = Button(image=pg.image.load("button.png"), pos=(720, 400),
                               text_input="60", font=text_font, base_color=text_color, hovering_color="White")
        BACK= Button(image=pg.image.load("button.png"), pos=(720, 540),
                             text_input="BACK", font=text_font, base_color=text_color, hovering_color="White")

        win.blit(MENU_TEXT, MENU_RECT)
        for button in [TIME1, TIME2, BACK]:
            button.changeColor(MENU_MOUSE_POS)
            button.update(win)

        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
                sys.exit()
            if event.type == pg.MOUSEBUTTONDOWN:
                if TIME1.checkForInput(MENU_MOUSE_POS):
                    cc = 2.5
                    wh = 2
                    w = 2
                    h = 2.5
                    user_time = 30
                    return Timer
                play()
                if TIME2.checkForInput(MENU_MOUSE_POS):
                    cc = 5
                    wh = 4
                    w = 4
                    h = 5
                    user_time = 60
                    return Timer
                play()
                if BACK.checkForInput(MENU_MOUSE_POS):
                    options()
        pg.display.update()
</code>```

and I'm hoping the data would go here in my function play():

```<code> if int(end-start) == the_time(Timer):
        run = False
        wpm(correct_char)
    end = time.time()
    draw_board(type_list, correct_st, start, end)
play()
</code>```

and my function draw_board()

```<code>if end-start <= user_time:
    time = time_font.render(str(user_time-int(end-start)), 1, timer_color)
    win.blit(time, (width / 5, height / 2 - 50))
pg.display.update()
</code>```

and if the time were changed, the WPM values would also change:

```<code>def wpm(correct_char):
    run = True
    while run:
        win.fill(bg)
        wpm = time_font.render('WPM:' + str(correct_char / cc), 1, timer_color)
        wid = wpm.get_width()
        win.blit(wpm, ((width//wh) - (wid//w), height/h))
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.display.quit()
                sys.exit()
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_TAB:
                    play()
        pg.display.update()
</code>```

I hope you can help me. Thankss

I tried changing everything related to the timer etc. but I still failed.

Body:
I'm new to programming and I need a help. So, I'm trying to make a typing game using pygame. What I want to do is let the user choose the timer the user wants for the game. What I'm trying to do is if the function the_time is called, It will overwrite the variables necessary for controlling the time.

How do I make the values inside the button conditional statement, be accessed in another function?

This is my code:

def the_time(Timer):
    while True:
        global usertime, cc, wh, w, h
        win.fill(bg)
#BUTTONS
        MENU_MOUSE_POS = pg.mouse.get_pos()

        MENU_TEXT = text_font.render("SELECT TIME", True, text_correct)
        MENU_RECT = MENU_TEXT.get_rect(center=(720, 100))
        TIME1 = Button(image=pg.image.load("button.png"), pos=(720, 250),
                               text_input="30", font=text_font, base_color=text_color, hovering_color="White")
        TIME2 = Button(image=pg.image.load("button.png"), pos=(720, 400),
                               text_input="60", font=text_font, base_color=text_color, hovering_color="White")
        BACK= Button(image=pg.image.load("button.png"), pos=(720, 540),
                             text_input="BACK", font=text_font, base_color=text_color, hovering_color="White")

        win.blit(MENU_TEXT, MENU_RECT)
        for button in [TIME1, TIME2, BACK]:
            button.changeColor(MENU_MOUSE_POS)
            button.update(win)

        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
                sys.exit()
            if event.type == pg.MOUSEBUTTONDOWN:
                if TIME1.checkForInput(MENU_MOUSE_POS):
                    cc = 2.5
                    wh = 2
                    w = 2
                    h = 2.5
                    user_time = 30
                    return Timer
                play()
                if TIME2.checkForInput(MENU_MOUSE_POS):
                    cc = 5
                    wh = 4
                    w = 4
                    h = 5
                    user_time = 60
                    return Timer
                play()
                if BACK.checkForInput(MENU_MOUSE_POS):
                    options()
        pg.display.update()

and I'm hoping the data would go here in my function play():

 if int(end-start) == the_time(Timer):
        run = False
        wpm(correct_char)
    end = time.time()
    draw_board(type_list, correct_st, start, end)
play()

and my function draw_board()

if end-start <= user_time:
    time = time_font.render(str(user_time-int(end-start)), 1, timer_color)
    win.blit(time, (width / 5, height / 2 - 50))
pg.display.update()

and if the time were changed, the WPM values would also change:

def wpm(correct_char):
    run = True
    while run:
        win.fill(bg)
        wpm = time_font.render('WPM:' + str(correct_char / cc), 1, timer_color)
        wid = wpm.get_width()
        win.blit(wpm, ((width//wh) - (wid//w), height/h))
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.display.quit()
                sys.exit()
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_TAB:
                    play()
        pg.display.update()

I hope you can help me. Thankss

I tried changing everything related to the timer etc. but I still failed.


问:
Apple Touch Icon in a NextJS application
I'm having trouble getting the apple-touch-icon to work in my NextJS app.  I have an image called apple-touch-icon.png at the root of my project and I am using next/Head in my application's app component (React app, but not CRA) using the following:

```<code>  function App({ Component, pageProps }) {
    return (
      ...
      <Head>
        <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
      </Head>
      ...
  )
</code>```

When I inspect my application I can see the  tag in the , but dragging from the url bar to my desktop from localhost still shows:

I also see the <link> in the  in a deployed instance of my application as well, but the touch icon image is not downloaded to the desktop.

Thoughts?

Body:
I'm having trouble getting the apple-touch-icon to work in my NextJS app.  I have an image called apple-touch-icon.png at the root of my project and I am using next/Head in my application's app component (React app, but not CRA) using the following:

  function App({ Component, pageProps }) {
    return (
      ...

        <link rel="apple-touch-icon" href="/apple-touch-icon.png" />

      ...
  )

When I inspect my application I can see the  tag in the , but dragging from the url bar to my desktop from localhost still shows:

I also see the <link> in the  in a deployed instance of my application as well, but the touch icon image is not downloaded to the desktop.

Thoughts?


问:
'TypeError: express_jwt__WEBPACK_IMPORTED_MODULE_2___default(...) is not a function' when trying to leverage express.jwt to auth required sign-in
Hope the holidays are treating everyone well. I'm a beginning coder working on a full stack application. Currently I'm trying to build a back end skeleton leveraging MongoDB, Express, and Node.js. Everything seems to be going well but for using an express json web token to authenticate  a required sign-in method. What's odd to me is the error references '. . . Webpack imported module 2 . . .' . I am using Webpack and Babel as compilers etc. but don't have the experience to connect the relationship between Webpack and express-JWT. My guess is that one of the modules I'm working with is out of date and thus not compatible with the others but am not sure which one. Of course, there could be an error in my code but I've tried to debug based on the error message to no avail. Would greatly appreciate your insights and help - thank you!

As mentioned, I'm a beginning coder but have tried the following: a) the two stack overflow threads below seemed to point me to documentation or updated syntax and I've tried variations of both but to no avail.

express-jwt got TypeError: express_jwt__WEBPACK_IMPORTED_MODULE_2___default(...) is not a function

and

TypeError: Webpack imported module is not a function.

Given the suggestions to review documentation I reviewed Webpack, Express, and even React (plan to use react on the front end) documentation but again, I didn't see, what in my mind, could be related subject matter. I think someone with more experience would prob know exactly where to look in the documentation but I don't seem to be able to put the pieces together given the little coding experience I have. Guidance on where to look in the documentation would be great as I'm eager to get more comfortable reviewing primary reference material. Regardless, appreciate the help and plan to pay it forward one day soon - thanks again!

Screenshots below: respective code truncated for relevance, package.json file

[respective code truncated for relevance] (https://i.stack.imgur.com/iOwVK.png)

package.json file