问:
Does the lightweight lock of java spin cas?
I have read many articles saying that lightweight locking in Java is a kind of spinlock, which will be upgraded to heavyweight locking after a certain number of attempts.

But I found that there seems to be only one cas operation in the openjdk source code and no spin.

https://github.com/openjdk/jdk/blob/9583e3657e43cc1c6f2101a64534564db2a9bd84/src/hotspot/share/runtime/synchronizer.cpp

```<code>// -----------------------------------------------------------------------------
// Monitor Enter/Exit
// The interpreter and compiler assembly code tries to lock using the fast path
// of this algorithm. Make sure to update that code if the following function is
// changed. The implementation is extremely sensitive to race condition. Be careful.

void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) {
  if (obj->klass()->is_value_based()) {
    handle_sync_on_value_based_class(obj, current);
  }

  if (!useHeavyMonitors()) {
    markWord mark = obj->mark();
    if (mark.is_neutral()) {
      // Anticipate successful CAS -- the ST of the displaced mark must
      // be visible <= the ST performed by the CAS.
      lock->set_displaced_header(mark);
      if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) {
        return;
      }
      // Fall through to inflate() ...
    } else if (mark.has_locker() &&
               current->is_lock_owned((address)mark.locker())) {
      assert(lock != mark.locker(), "must not re-lock the same lock");
      assert(lock != (BasicLock*)obj->mark().value(), "don't relock with same BasicLock");
      lock->set_displaced_header(markWord::from_pointer(NULL));
      return;
    }

    // The object header will never be displaced to this lock,
    // so it does not matter what the value is, except that it
    // must be non-zero to avoid looking like a re-entrant lock,
    // and must not look locked either.
    lock->set_displaced_header(markWord::unused_mark());
  } else if (VerifyHeavyMonitors) {
    guarantee(!obj->mark().has_locker(), "must not be stack-locked");
  }

  // An async deflation can race after the inflate() call and before
  // enter() can make the ObjectMonitor busy. enter() returns false if
  // we have lost the race to async deflation and we simply try again.
  while (true) {
    ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_monitor_enter);
    if (monitor->enter(current)) {
      return;
    }
  }
}
</code>```

In my opinion, the only cas attempt was:

```<code>  if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) {
        return;
      }
</code>```

Sorry, I'm not very familiar with C++. Did I find the wrong code? Or who can tell me where the relevant code of lightweight lock spin is?

Body:
I have read many articles saying that lightweight locking in Java is a kind of spinlock, which will be upgraded to heavyweight locking after a certain number of attempts.

But I found that there seems to be only one cas operation in the openjdk source code and no spin.

https://github.com/openjdk/jdk/blob/9583e3657e43cc1c6f2101a64534564db2a9bd84/src/hotspot/share/runtime/synchronizer.cpp

// -----------------------------------------------------------------------------
// Monitor Enter/Exit
// The interpreter and compiler assembly code tries to lock using the fast path
// of this algorithm. Make sure to update that code if the following function is
// changed. The implementation is extremely sensitive to race condition. Be careful.

void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) {
  if (obj->klass()->is_value_based()) {
    handle_sync_on_value_based_class(obj, current);
  }

  if (!useHeavyMonitors()) {
    markWord mark = obj->mark();
    if (mark.is_neutral()) {
      // Anticipate successful CAS -- the ST of the displaced mark must
      // be visible <= the ST performed by the CAS.
      lock->set_displaced_header(mark);
      if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) {
        return;
      }
      // Fall through to inflate() ...
    } else if (mark.has_locker() &&
               current->is_lock_owned((address)mark.locker())) {
      assert(lock != mark.locker(), "must not re-lock the same lock");
      assert(lock != (BasicLock*)obj->mark().value(), "don't relock with same BasicLock");
      lock->set_displaced_header(markWord::from_pointer(NULL));
      return;
    }

    // The object header will never be displaced to this lock,
    // so it does not matter what the value is, except that it
    // must be non-zero to avoid looking like a re-entrant lock,
    // and must not look locked either.
    lock->set_displaced_header(markWord::unused_mark());
  } else if (VerifyHeavyMonitors) {
    guarantee(!obj->mark().has_locker(), "must not be stack-locked");
  }

  // An async deflation can race after the inflate() call and before
  // enter() can make the ObjectMonitor busy. enter() returns false if
  // we have lost the race to async deflation and we simply try again.
  while (true) {
    ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_monitor_enter);
    if (monitor->enter(current)) {
      return;
    }
  }
}

In my opinion, the only cas attempt was:

  if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) {
        return;
      }

Sorry, I'm not very familiar with C++. Did I find the wrong code? Or who can tell me where the relevant code of lightweight lock spin is?


来源: stackexchange

问:
I encountered an inter-package reference error when installing a specific python package (nonebot_plugin_mockingbird) in python 3.10
This is the repository address for this python package: nonebot_plugin_mockingbird.
Whether I go through either of the two options suggested by the author, I run into installing the wrong version of numpy. Even if I had installed the correct, referenced version of numpy in advance.

I asked the author about this in the original repository and he said that the version of numpy requested in the repository is capable of running in python3.10.

Please see this issue for details：Request to update numpy version to 1.23.3 to support python 3.10.X

I was even more confused after looking up the relevant information. Both the project itself and the MeetWq/MockingBirdForUse mentioned by the author of the project require a version of numpy that is python 3.10 compliant.

Here is part of the code from my installation (note that a higher version of numpy with python 3.10 support is already installed, but a lower version will still be installed)：

Collecting httpcore<0.15.0,>=0.14.5
  Using cached https://pypi.tuna.tsinghua.edu.cn/packages/e7/38/7b76d3d71c462dc936e333b358a3106e7af913e6c8c9dd5a45684fec08cc/httpcore-0.14.7-py3-none-any.whl (68 kB)
Requirement already satisfied: charset-normalizer in /home/vanthoff/.local/lib/python3.10/site-packages (from httpx<0.23.0,>=0.22.0->nonebot_plugin_mockingbird) (2.1.1)
Requirement already satisfied: certifi in /home/vanthoff/.local/lib/python3.10/site-packages (from httpx<0.23.0,>=0.22.0->nonebot_plugin_mockingbird) (2022.12.7)
Requirement already satisfied: numpy in /home/vanthoff/.local/lib/python3.10/site-packages (from langid<2.0.0,>=1.1.6->nonebot_plugin_mockingbird) (1.22.4)
Requirement already satisfied: pypinyin in /home/vanthoff/.local/lib/python3.10/site-packages (from mockingbirdonlyforuse<0.0.11,>=0.0.10->nonebot_plugin_mockingbird) (0.47.1)
Collecting numpy
  Using cached https://pypi.tuna.tsinghua.edu.cn/packages/c5/63/a48648ebc57711348420670bb074998f79828291f68aebfff1642be212ec/numpy-1.19.4.zip (7.3 MB)
  Installing build dependencies ...
```

ContentLicense: CC BY-SA 4.0


问:
Is there any secure way to automate google authenticator without using AeroGear java library
I was searching for how to automate two-factor authentication with Google Authenticator using Selenium. The most common way that I found is by using AeroGear java library.
Somebody guides me that this is not the secure way to test the Google Authenticator. Also, the version is not updated since 2013. I just want a guide should I continue with this library or there is any other way to automate this scenario?


问:
Upgrade Next 12 to 13 and React 17 to 18 - issue with Github build Deploy Next.js app - The root value has an unexpected property, target,
Github build failed:
- name: Deploy Next.js app
run: npx serverless@2.72.2

aNA
error:
Error: Command failed with exit code 1: node_modules/.bin/next build
warn  - Invalid next.config.js options detected:

The root value has an unexpected property, target, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, modularizeImports, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, skipMiddlewareUrlNormalize, skipTrailingSlashRedirect, staticPageGenerationTimeout, swcMinify, trailingSlash, transpilePackages, typescript, useFileSystemPublicRoutes, webpack).

next.config.js

```<code>/** @type {import('next').NextConfig} */
const headers = async () => {
    return [
        {
            source: '/:path*',
            headers: [
                {
                    key: 'X-Content-Type-Options',
                    value: 'nosniff'
                },
                {
                    key: 'X-Frame-Options',
                    value: 'SAMEORIGIN'
                },

            ]
        }
    ]

}
const nextConfig = {
reactStrictMode: true,
output: 'standalone',
transpilePackages: \['@ionic/react', '@ionic/core', '@stencil/core', 'ionicons'\],
async redirects() {
return \[
 {
    source: '/',
    destination: '/language',
    permanent: true
 }
\]
},
headers,
  images: {
    domains: \['media.graphcms.com', 'res.cloudinary.com',
   'images.unsplash.com', 'media.graphassets.com'\],
  unoptimized: true,
}
};
module.exports = nextConfig;
</code>```

Can anyone advice how to resolve this issue? trying to fix/rewrite all day and no luck... In case, local terminal: npm run build is passed.

Body:
Github build failed:
- name: Deploy Next.js app
run: npx serverless@2.72.2

aNA
error:
Error: Command failed with exit code 1: node_modules/.bin/next build
warn  - Invalid next.config.js options detected:

The root value has an unexpected property, target, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, modularizeImports, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, skipMiddlewareUrlNormalize, skipTrailingSlashRedirect, staticPageGenerationTimeout, swcMinify, trailingSlash, transpilePackages, typescript, useFileSystemPublicRoutes, webpack).

next.config.js

/** @type {import('next').NextConfig} */
const headers = async () => {
    return [
        {
            source: '/:path*',
            headers: [
                {
                    key: 'X-Content-Type-Options',
                    value: 'nosniff'
                },
                {
                    key: 'X-Frame-Options',
                    value: 'SAMEORIGIN'
                },

            ]
        }
    ]

}
const nextConfig = {
reactStrictMode: true,
output: 'standalone',
transpilePackages: \['@ionic/react', '@ionic/core', '@stencil/core', 'ionicons'\],
async redirects() {
return \[
 {
    source: '/',
    destination: '/language',
    permanent: true
 }
\]
},
headers,
  images: {
    domains: \['media.graphcms.com', 'res.cloudinary.com',
   'images.unsplash.com', 'media.graphassets.com'\],
  unoptimized: true,
}
};
module.exports = nextConfig;

Can anyone advice how to resolve this issue? trying to fix/rewrite all day and no luck... In case, local terminal: npm run build is passed.


问:
I have a problem. RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one
I'm learning torch, and having some problems.Now I'm working on this project.

https://github.com/jaywalnut310/vits.

Python3.7

torch        1.8.1+cu111

torchvision  0.9.1+cu111

```<code>Traceback (most recent call last):
File "train.py", line 332, in \<module\>
main()
File "train.py", line 67, in main
mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,))
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-      packages\\torch\\multiprocessing\\spawn.py", line 230, in spawn
return start_processes(fn, args, nprocs, join, daemon, start_method='spawn')
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-packages\\torch\\multiprocessing\\spawn.py", line 188, in start_processes
while not context.join():
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-packages\\torch\\multiprocessing\\spawn.py", line 150, in join
raise ProcessRaisedException(msg, error_index, failed_process.pid)
torch.multiprocessing.spawn.ProcessRaisedException:

\-- Process 0 terminated with the following error:
Traceback (most recent call last):
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-packages\\torch\\multiprocessing\\spawn.py", line 59, in \_wrap
fn(i, \*args)
File "C:\\Users\\mashi\\PycharmProjects\\voice_train\\vits\\train.py", line 148, in run
\[train_loader, eval_loader\], logger, \[writer, writer_eval\])
File "C:\\Users\\mashi\\PycharmProjects\\voice_train\\vits\\train.py", line 176, in train_and_evaluate
(z, z_p, m_p, logs_p, m_q, logs_q) = net_g(x, x_lengths, spec, spec_lengths)
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-packages\\torch\\nn\\modules\\module.py", line 889, in \_call_impl
result = self.forward(\*input, \*\*kwargs)
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-packages\\torch\\nn\\parallel\\distributed.py", line 692, in forward
if self.reducer.\_rebuild_buckets():
RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by (1) passing the keyword argument find_unused_parameters=True to torch.nn.parallel.DistributedDataParallel; (2) making sure all forward function outputs participate in calculating loss. If you already have done the above two steps, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's forward function. Please include the loss function and the structure of the return value of forward of your module when reporting this issue (e.g. list, dict, iterable).
</code>```

How do I solve this problem?

Body:
I'm learning torch, and having some problems.Now I'm working on this project.

https://github.com/jaywalnut310/vits.

Python3.7

torch        1.8.1+cu111

torchvision  0.9.1+cu111

Traceback (most recent call last):
File "train.py", line 332, in \<module\>
main()
File "train.py", line 67, in main
mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,))
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-      packages\\torch\\multiprocessing\\spawn.py", line 230, in spawn
return start_processes(fn, args, nprocs, join, daemon, start_method='spawn')
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-packages\\torch\\multiprocessing\\spawn.py", line 188, in start_processes
while not context.join():
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-packages\\torch\\multiprocessing\\spawn.py", line 150, in join
raise ProcessRaisedException(msg, error_index, failed_process.pid)
torch.multiprocessing.spawn.ProcessRaisedException:

\-- Process 0 terminated with the following error:
Traceback (most recent call last):
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-packages\\torch\\multiprocessing\\spawn.py", line 59, in \_wrap
fn(i, \*args)
File "C:\\Users\\mashi\\PycharmProjects\\voice_train\\vits\\train.py", line 148, in run
\[train_loader, eval_loader\], logger, \[writer, writer_eval\])
File "C:\\Users\\mashi\\PycharmProjects\\voice_train\\vits\\train.py", line 176, in train_and_evaluate
(z, z_p, m_p, logs_p, m_q, logs_q) = net_g(x, x_lengths, spec, spec_lengths)
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-packages\\torch\\nn\\modules\\module.py", line 889, in \_call_impl
result = self.forward(\*input, \*\*kwargs)
File "C:\\Users\\mashi\\anaconda3\\envs\\chat37\\lib\\site-packages\\torch\\nn\\parallel\\distributed.py", line 692, in forward
if self.reducer.\_rebuild_buckets():
RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by (1) passing the keyword argument find_unused_parameters=True to torch.nn.parallel.DistributedDataParallel; (2) making sure all forward function outputs participate in calculating loss. If you already have done the above two steps, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's forward function. Please include the loss function and the structure of the return value of forward of your module when reporting this issue (e.g. list, dict, iterable).

How do I solve this problem?


问:
How can I skip a field from being translated by react-18n?
I have some data I want to translate. Those data are being translated with locize and react-18n into different languages. However, I need some fields to be skipped but they are not. Image url and navigation links are expected to remain unchanged in other languges also but this is not happening.

Example:

"headerNavigation": [
    {
      "link": "/",
      "name": "Home"
    },
    {
      "link": "/about",
      "name": "About"
    },
    {
      "link": "/products-and-services",
      "name": "Products & Services"
    },
    {
      "link": "/buy-commodities",
      "name": "Buy Commodities"
    },
    {
      "link": "/contact",
      "name": "Contact"
    }
  ],
```
<p>Result in German:</p>
<pre class="lang-js prettyprint-override"><code>"headerNavigation": [
    {
      "link": "/",
      "name": "Heim"
    },
    {
      "link": "/Über",
      "name": "Über"
    },
    {
      "link": "/Produkte und Dienstleistungen",
      "name": "Produkte"
    },
    {
      "link": "/buy-commodities",
      "name": "Rohstoffe kaufen"
    },
    {
      "link": "/Kontakt",
      "name": "Kontakt"
    }
  ],
</code>```

Different corresponding json were generated and based on the route, the right json is being used to serve the content. For instance, if I am on http://localhost:3000/en, it will use the English translation and the German if I am on http://localhost:3000/de

I just need some translation to remain unchanged. For instance, what I am expecting for German translation should be:

"headerNavigation": [
    {
      "link": "/",
      "name": "Heim"
    },
    {
      "link": "/about",
      "name": "Über"
    },
    {
      "link": "/products-and-services",
      "name": "Produkte"
    },
    {
      "link": "/buy-commodities",
      "name": "Rohstoffe kaufen"
    },
    {
      "link": "/contact",
      "name": "Kontakt"
    }
  ],
```

I am mapping through the file with something like: https://locize.com/blog/next-13-app-dir-i18n/

Body:
I have some data I want to translate. Those data are being translated with locize and react-18n into different languages. However, I need some fields to be skipped but they are not. Image url and navigation links are expected to remain unchanged in other languges also but this is not happening.

Example:

"headerNavigation": [
    {
      "link": "/",
      "name": "Home"
    },
    {
      "link": "/about",
      "name": "About"
    },
    {
      "link": "/products-and-services",
      "name": "Products & Services"
    },
    {
      "link": "/buy-commodities",
      "name": "Buy Commodities"
    },
    {
      "link": "/contact",
      "name": "Contact"
    }
  ],

Result in German:

"headerNavigation": [
    {
      "link": "/",
      "name": "Heim"
    },
    {
      "link": "/Über",
      "name": "Über"
    },
    {
      "link": "/Produkte und Dienstleistungen",
      "name": "Produkte"
    },
    {
      "link": "/buy-commodities",
      "name": "Rohstoffe kaufen"
    },
    {
      "link": "/Kontakt",
      "name": "Kontakt"
    }
  ],

Different corresponding json were generated and based on the route, the right json is being used to serve the content. For instance, if I am on http://localhost:3000/en, it will use the English translation and the German if I am on http://localhost:3000/de

I just need some translation to remain unchanged. For instance, what I am expecting for German translation should be:

"headerNavigation": [
    {
      "link": "/",
      "name": "Heim"
    },
    {
      "link": "/about",
      "name": "Über"
    },
    {
      "link": "/products-and-services",
      "name": "Produkte"
    },
    {
      "link": "/buy-commodities",
      "name": "Rohstoffe kaufen"
    },
    {
      "link": "/contact",
      "name": "Kontakt"
    }
  ],

I am mapping through the file with something like: https://locize.com/blog/next-13-app-dir-i18n/


问:
Please advise on the error Traceback (most recent call last)
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\3\ipykernel_5356\2783521920.py in
1 age = 1006
2
----> 3 isinstance (age, str)

TypeError: isinstance() arg 2 must be a type or tuple of types

I tried to change the blanks, register, but it doesnot work.


问:
.htaccess file for Joomla! v.4.* - how to configure not to translate IDN into xn-- ... format?
I would like to ask, if there is any option to add to the htaccess file, for every URL in the site, either to translate IDN domains or not to translate. The issue I do have is, I have my site running CMS Joomla! on IDN domain. The site part generated by CMS only runs fine, and the part of the website generated by another component provides in the source code translated links. These actualy leads to 404 error, as the source page URL is IDN formated to visitor, and the link leads to the DNS like formated IDN  (xn--whatever06.com). I would expect somehow to make htaccess creating relative links only.

Thanks for your hints.
Michal

enabled and disabled htaccess redirection
enabled and disabled SEO component installed
used typing the correct URL to the browser


问:
A variable's update that is done by a different thread is not seen in a while(true) loop
I am working on a very simple Java code to get some experience on threads. shirt is a variable that has a color attribute.

```<code>while(true){
    if (shirt.isColorBlue()) {
        System.out.println("The shirt is finally blue.");
    }
}
</code>```

During the while loop above, a thread that is running in parallel updates the shirt's color. However, inside of the if block never executes. I did some alterations to see some other conditions:

```<code>while(true){
    if (shirt.isColorBlue()) {
        System.out.println("The shirt is finally blue.");
    }

    try {
        Thread.sleep(1000);
    }  catch (InterruptedException e) { }
}
</code>```

If I do it like above, the code works (inside the if block gets executed). From this, I understand that the other thread updates the shirt variable after the while starts to iterate. But shouldn't it be still okay since the ideal scenario is "the while looping many many times and the if block executing whenever the other thread updates the shirt variable"?

Body:
I am working on a very simple Java code to get some experience on threads. shirt is a variable that has a color attribute.

while(true){
    if (shirt.isColorBlue()) {
        System.out.println("The shirt is finally blue.");
    }
}

During the while loop above, a thread that is running in parallel updates the shirt's color. However, inside of the if block never executes. I did some alterations to see some other conditions:

while(true){
    if (shirt.isColorBlue()) {
        System.out.println("The shirt is finally blue.");
    }

    try {
        Thread.sleep(1000);
    }  catch (InterruptedException e) { }
}

If I do it like above, the code works (inside the if block gets executed). From this, I understand that the other thread updates the shirt variable after the while starts to iterate. But shouldn't it be still okay since the ideal scenario is "the while looping many many times and the if block executing whenever the other thread updates the shirt variable"?


问:
Node classification on Cora dataset-error with tensorflow
I am working with Graph Convolutional neural networks for node classification problem. I'm using this article https://towardsdatascience.com/graph-convolutional-networks-on-node-classification-2b6bbec1d042. I understood code very well. But I get following error:

```<code>ValueError: Input 1 of layer "model" is incompatible with the layer: expected shape=(None, 2708), found shape=(None, 1000)
</code>```

I get that this means that the model expects an input with shape (None, 2708) but the input data has shape (None, 1000). In this article tensorflow version was 2.2.0, but now latest is 2.11.0. When I try downgrading to version 2.2.0 it is not possible since it is not possible to install it. Also, downgrading to 2.8.0 or 2.10.0 is not helpful, I get same error. So I guess it has something to do with that, but really don't have any idea except this, and it didn't work. I will also show code below from article above.

```<code>import numpy as np
import os
import networkx as nx
from keras.utils import to_categorical
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import shuffle
from sklearn.metrics import classification_report

from spektral.layers import GCNConv

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dropout, Dense
from tensorflow.keras import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import TensorBoard, EarlyStopping
import tensorflow as tf
from tensorflow.keras.regularizers import l2

from collections import Counter
from sklearn.manifold import TSNE

import matplotlib.pyplot as plt

all_data = []
all_edges = []

for root, dirs, files in os.walk('./cora'):
    for file in files:
        if '.content' in file:
            with open(os.path.join(root, file), 'r') as f:
                all_data.extend(f.read().splitlines())
        elif 'cites' in file:
            with open(os.path.join(root, file), 'r') as f:
                all_edges.extend(f.read().splitlines())

# Shuffle the data because the raw data is ordered based on the label
random_state = 77
all_data = shuffle(all_data, random_state=random_state)

#parse the data
labels = []
nodes = []
X = []
for i,data in enumerate(all_data):
    elements = data.split('\t')
    labels.append(elements[-1])
    X.append(elements[1:-1])
    nodes.append(elements[0])

X = np.array(X,dtype=int)
N = X.shape[0] #the number of nodes
F = X.shape[1] #the size of node features
print('X shape: ', X.shape)

#parse the edge
edge_list=[]
for edge in all_edges:
    e = edge.split('\t')
    edge_list.append((e[0],e[1]))

print('\nNumber of nodes (N): ', N)
print('\nNumber of features (F) of each node: ', F)
print('\nCategories: ', set(labels))

num_classes = len(set(labels))
print('\nNumber of classes: ', num_classes)

def limit_data(labels, limit=20, val_num=500, test_num=1000):
    '''
    Get the index of train, validation, and test data
    '''
    label_counter = dict((l, 0) for l in labels)
    train_idx = []

    for i in range(len(labels)):
        label = labels[i]
        if label_counter[label] < limit:
            # add the example to the training data
            train_idx.append(i)
            label_counter[label] += 1

        # exit the loop once we found 20 examples for each class
        if all(count == limit for count in label_counter.values()):
            break

    # get the indices that do not go to traning data
    rest_idx = [x for x in range(len(labels)) if x not in train_idx]
    val_idx = rest_idx[:val_num]
    test_idx = rest_idx[val_num:(val_num + test_num)]
    return train_idx, val_idx, test_idx

train_idx, val_idx, test_idx = limit_data(labels)

# set the mask
train_mask = np.zeros((N,), dtype=bool)
train_mask[train_idx] = True

val_mask = np.zeros((N,), dtype=bool)
val_mask[val_idx] = True

test_mask = np.zeros((N,), dtype=bool)
test_mask[test_idx] = True
#build the graph
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edge_list)

#obtain the adjacency matrix (A)
A = nx.adjacency_matrix(G)
print('Graph info: ', nx.info(G))
def encode_label(labels):
    label_encoder = LabelEncoder()
    labels = label_encoder.fit_transform(labels)
    labels = to_categorical(labels)
    return labels, label_encoder.classes_

labels_encoded, classes = encode_label(labels)

# Parameters
channels = 16           # Number of channels in the first layer
dropout = 0.5           # Dropout rate for the features
l2_reg = 5e-4           # L2 regularization rate
learning_rate = 1e-2    # Learning rate
epochs = 200            # Number of training epochs
es_patience = 10        # Patience for early stopping

# Preprocessing operations
A = GCNConv.preprocess(A).astype('f4')

# Model definition
X_in = Input(shape=(F, ))
fltr_in = Input((N, ), sparse=True)

dropout_1 = Dropout(dropout)(X_in)
graph_conv_1 = GCNConv(channels,
                         activation='relu',
                         kernel_regularizer=l2(l2_reg),
                         use_bias=False)([dropout_1, fltr_in])

dropout_2 = Dropout(dropout)(graph_conv_1)
graph_conv_2 = GCNConv(num_classes,
                         activation='softmax',
                         use_bias=False)([dropout_2, fltr_in])

# Build model
model = Model(inputs=[X_in, fltr_in], outputs=graph_conv_2)
optimizer = Adam(lr=learning_rate)
model.compile(optimizer=optimizer,
              loss='categorical_crossentropy',
              weighted_metrics=['acc'])
model.summary()

tbCallBack_GCN = tf.keras.callbacks.TensorBoard(
    log_dir='./Tensorboard_GCN_cora',
)
callback_GCN = [tbCallBack_GCN]

# Train model
validation_data = ([X, A], labels_encoded, val_mask)
model.fit([X, A],
          labels_encoded,
          sample_weight=train_mask,
          epochs=epochs,
          batch_size=N,
          validation_data=validation_data,
          shuffle=False,
          callbacks=[
              EarlyStopping(patience=es_patience,  restore_best_weights=True),
              tbCallBack_GCN
          ])

# Evaluate model
X_te = X[test_mask]
A_te = A[test_mask,:][:,test_mask]
y_te = labels_encoded[test_mask]
y_pred = model.predict([X_te, A_te], batch_size=N)
report = classification_report(np.argmax(y_te,axis=1), np.argmax(y_pred,axis=1), target_names=classes)
print('GCN Classification Report: \n {}'.format(report))

# Get the hidden layer representation after the first GCN layer
layer_outputs = [layer.output for layer in model.layers]
activation_model = Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict([X, A], batch_size=N)

# Get t-SNE Representation
x_tsne = TSNE(n_components=2).fit_transform(activations[3])

def plot_tSNE(labels_encoded, x_tsne):
    color_map = np.argmax(labels_encoded, axis=1)
    plt.figure(figsize=(10, 10))
    for cl in range(num_classes):
        indices = np.where(color_map == cl)
        indices = indices[0]
        plt.scatter(x_tsne[indices, 0], x_tsne[indices, 1], label=cl)
    plt.legend()
    plt.show()

plot_tSNE(labels_encoded, x_tsne)

</code>```

Please, if anyone could solve this for me would be thankful, because code is okay. Thanks a lot!

Body:
I am working with Graph Convolutional neural networks for node classification problem. I'm using this article https://towardsdatascience.com/graph-convolutional-networks-on-node-classification-2b6bbec1d042. I understood code very well. But I get following error:

ValueError: Input 1 of layer "model" is incompatible with the layer: expected shape=(None, 2708), found shape=(None, 1000)

I get that this means that the model expects an input with shape (None, 2708) but the input data has shape (None, 1000). In this article tensorflow version was 2.2.0, but now latest is 2.11.0. When I try downgrading to version 2.2.0 it is not possible since it is not possible to install it. Also, downgrading to 2.8.0 or 2.10.0 is not helpful, I get same error. So I guess it has something to do with that, but really don't have any idea except this, and it didn't work. I will also show code below from article above.

import numpy as np
import os
import networkx as nx
from keras.utils import to_categorical
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import shuffle
from sklearn.metrics import classification_report

from spektral.layers import GCNConv

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dropout, Dense
from tensorflow.keras import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import TensorBoard, EarlyStopping
import tensorflow as tf
from tensorflow.keras.regularizers import l2

from collections import Counter
from sklearn.manifold import TSNE

import matplotlib.pyplot as plt

all_data = []
all_edges = []

for root, dirs, files in os.walk('./cora'):
    for file in files:
        if '.content' in file:
            with open(os.path.join(root, file), 'r') as f:
                all_data.extend(f.read().splitlines())
        elif 'cites' in file:
            with open(os.path.join(root, file), 'r') as f:
                all_edges.extend(f.read().splitlines())

# Shuffle the data because the raw data is ordered based on the label
random_state = 77
all_data = shuffle(all_data, random_state=random_state)

#parse the data
labels = []
nodes = []
X = []
for i,data in enumerate(all_data):
    elements = data.split('\t')
    labels.append(elements[-1])
    X.append(elements[1:-1])
    nodes.append(elements[0])

X = np.array(X,dtype=int)
N = X.shape[0] #the number of nodes
F = X.shape[1] #the size of node features
print('X shape: ', X.shape)

#parse the edge
edge_list=[]
for edge in all_edges:
    e = edge.split('\t')
    edge_list.append((e[0],e[1]))

print('\nNumber of nodes (N): ', N)
print('\nNumber of features (F) of each node: ', F)
print('\nCategories: ', set(labels))

num_classes = len(set(labels))
print('\nNumber of classes: ', num_classes)

def limit_data(labels, limit=20, val_num=500, test_num=1000):
    '''
    Get the index of train, validation, and test data
    '''
    label_counter = dict((l, 0) for l in labels)
    train_idx = []

    for i in range(len(labels)):
        label = labels[i]
        if label_counter[label] < limit:
            # add the example to the training data
            train_idx.append(i)
            label_counter[label] += 1

        # exit the loop once we found 20 examples for each class
        if all(count == limit for count in label_counter.values()):
            break

    # get the indices that do not go to traning data
    rest_idx = [x for x in range(len(labels)) if x not in train_idx]
    val_idx = rest_idx[:val_num]
    test_idx = rest_idx[val_num:(val_num + test_num)]
    return train_idx, val_idx, test_idx

train_idx, val_idx, test_idx = limit_data(labels)

# set the mask
train_mask = np.zeros((N,), dtype=bool)
train_mask[train_idx] = True

val_mask = np.zeros((N,), dtype=bool)
val_mask[val_idx] = True

test_mask = np.zeros((N,), dtype=bool)
test_mask[test_idx] = True
#build the graph
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edge_list)

#obtain the adjacency matrix (A)
A = nx.adjacency_matrix(G)
print('Graph info: ', nx.info(G))
def encode_label(labels):
    label_encoder = LabelEncoder()
    labels = label_encoder.fit_transform(labels)
    labels = to_categorical(labels)
    return labels, label_encoder.classes_

labels_encoded, classes = encode_label(labels)

# Parameters
channels = 16           # Number of channels in the first layer
dropout = 0.5           # Dropout rate for the features
l2_reg = 5e-4           # L2 regularization rate
learning_rate = 1e-2    # Learning rate
epochs = 200            # Number of training epochs
es_patience = 10        # Patience for early stopping

# Preprocessing operations
A = GCNConv.preprocess(A).astype('f4')

# Model definition
X_in = Input(shape=(F, ))
fltr_in = Input((N, ), sparse=True)

dropout_1 = Dropout(dropout)(X_in)
graph_conv_1 = GCNConv(channels,
                         activation='relu',
                         kernel_regularizer=l2(l2_reg),
                         use_bias=False)([dropout_1, fltr_in])

dropout_2 = Dropout(dropout)(graph_conv_1)
graph_conv_2 = GCNConv(num_classes,
                         activation='softmax',
                         use_bias=False)([dropout_2, fltr_in])

# Build model
model = Model(inputs=[X_in, fltr_in], outputs=graph_conv_2)
optimizer = Adam(lr=learning_rate)
model.compile(optimizer=optimizer,
              loss='categorical_crossentropy',
              weighted_metrics=['acc'])
model.summary()

tbCallBack_GCN = tf.keras.callbacks.TensorBoard(
    log_dir='./Tensorboard_GCN_cora',
)
callback_GCN = [tbCallBack_GCN]

# Train model
validation_data = ([X, A], labels_encoded, val_mask)
model.fit([X, A],
          labels_encoded,
          sample_weight=train_mask,
          epochs=epochs,
          batch_size=N,
          validation_data=validation_data,
          shuffle=False,
          callbacks=[
              EarlyStopping(patience=es_patience,  restore_best_weights=True),
              tbCallBack_GCN
          ])

# Evaluate model
X_te = X[test_mask]
A_te = A[test_mask,:][:,test_mask]
y_te = labels_encoded[test_mask]
y_pred = model.predict([X_te, A_te], batch_size=N)
report = classification_report(np.argmax(y_te,axis=1), np.argmax(y_pred,axis=1), target_names=classes)
print('GCN Classification Report: \n {}'.format(report))

# Get the hidden layer representation after the first GCN layer
layer_outputs = [layer.output for layer in model.layers]
activation_model = Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict([X, A], batch_size=N)

# Get t-SNE Representation
x_tsne = TSNE(n_components=2).fit_transform(activations[3])

def plot_tSNE(labels_encoded, x_tsne):
    color_map = np.argmax(labels_encoded, axis=1)
    plt.figure(figsize=(10, 10))
    for cl in range(num_classes):
        indices = np.where(color_map == cl)
        indices = indices[0]
        plt.scatter(x_tsne[indices, 0], x_tsne[indices, 1], label=cl)
    plt.legend()
    plt.show()

plot_tSNE(labels_encoded, x_tsne)

Please, if anyone could solve this for me would be thankful, because code is okay. Thanks a lot!


问:
HTML5 Video autoplay bug on iOS devices
I'm trying to autoplay video without sound and controls on my iPhone 14Pro. The video should also repeat so I have included a loop option. It seems like the video does not show at all on iOS devices. Everywhere else works. The iOS version I have is 16.2.

I have tried to add options like autoplay muted and playsinline but nothing seems to have an effect. Here is the code:

```<code> <video class="video" preload="none" muted loop autoplay playsinline>
    <source src="my-video.mp4" type="video/mp4" />
 </video>
</code>```

Is there any workaround how I can make this work on iOS devices without controls and autoplay?

Title: HTML5 Video autoplay bug on iOS devices

Body:
I'm trying to autoplay video without sound and controls on my iPhone 14Pro. The video should also repeat so I have included a loop option. It seems like the video does not show at all on iOS devices. Everywhere else works. The iOS version I have is 16.2.

I have tried to add options like autoplay muted and playsinline but nothing seems to have an effect. Here is the code:

 <video class="video" preload="none" muted loop autoplay playsinline>
    <source src="my-video.mp4" type="video/mp4" />
 </video>

Is there any workaround how I can make this work on iOS devices without controls and autoplay?


问:
Box with explanatory note not showing correctly when word is clicked
I am trying to implement a feature on my website allowing users to trigger a pop-up box with an explanatory note when they click on specific words in the text.

In this question I found a nice example of how I would like such informative boxes to work. My idea was:

I test the code in the example on my website as it is

I make some modification for my purposes

However I am stuck at the first point. Even if my explantory note is shown once the related word is clicked, the surrounding box does not appear. You can see here a screenshot of what happens when one of the red words is clicked. Even if the box is not shown, I can drag it around and close it through the little white circle on the right of the text.

At first, I supposed the problem was the versions of jquey (I use 2.1.4) and jquery ui, so I tried several versions of jquery ui to check if I got any change in the box behaviour, but the problem persists. All the above occurs in Firefox browser, but I noticed that the box does not show at all using Chrome browser. I wonder if there is a way to make this work or if it is better to implement something different to show explanatory boxes.

The code I tested is the following:

CSS

.content span {
    text-decoration: underline;
    color: #da2f47;
    cursor: pointer;
}
```
<p>HTML</p>
<pre class="lang-html prettyprint-override"><code><h4><b>Lorem</b></h4>
<div class="content">
<p style="text-align:left;">Lorem ipsum <span>dolor</span> sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut <span>labore</span> et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in <span>voluptate</span> velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div id="dialog" title=""></div>
</code>```

javascript

var explanations = {
    "dolor": "Explanation about dolor.",
    "labore": "Explanation about labore.",
    "voluptate": "Explanation about voluptate."
};

$(".content").on("click", "span", function(e) {
    e.stopPropagation();
    var $this = $( this ),
        _text = $this.text();

    var dialogContent = explanations[_text.toLowerCase()];
    if(dialogContent && dialogContent.length > 0) {
        $( "#dialog" ).dialog({
            "modal": true,
            "title": _text
        }).html(dialogContent);
    }
});
```

Body:
I am trying to implement a feature on my website allowing users to trigger a pop-up box with an explanatory note when they click on specific words in the text.

In this question I found a nice example of how I would like such informative boxes to work. My idea was:

I test the code in the example on my website as it is

I make some modification for my purposes

However I am stuck at the first point. Even if my explantory note is shown once the related word is clicked, the surrounding box does not appear. You can see here a screenshot of what happens when one of the red words is clicked. Even if the box is not shown, I can drag it around and close it through the little white circle on the right of the text.

At first, I supposed the problem was the versions of jquey (I use 2.1.4) and jquery ui, so I tried several versions of jquery ui to check if I got any change in the box behaviour, but the problem persists. All the above occurs in Firefox browser, but I noticed that the box does not show at all using Chrome browser. I wonder if there is a way to make this work or if it is better to implement something different to show explanatory boxes.

The code I tested is the following:

CSS

.content span {
    text-decoration: underline;
    color: #da2f47;
    cursor: pointer;
}

HTML

Lorem

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

javascript

var explanations = {
    "dolor": "Explanation about dolor.",
    "labore": "Explanation about labore.",
    "voluptate": "Explanation about voluptate."
};

$(".content").on("click", "span", function(e) {
    e.stopPropagation();
    var $this = $( this ),
        _text = $this.text();

    var dialogContent = explanations[_text.toLowerCase()];
    if(dialogContent && dialogContent.length > 0) {
        $( "#dialog" ).dialog({
            "modal": true,
            "title": _text
        }).html(dialogContent);
    }
});


问:
Vite + Vue 3 + AWS build
I'm trying to deploy a Vue 3 application that uses Vite, which locally works perfectly, but after deploy I get this error.

Uncaught TypeError: Cannot read properties of undefined (reading 'memoizedProperty')

I read that it could be from aws-sdk not collaborating well with Rollup, but it seems that the other solutions on the internet haven't worked.

Here are the relevant parts from vite.config.js:

```<code>resolve: {
      alias: {
        // vue: '@vue/compat'
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        path: 'path-browserify',
        // 'aws-sdk': 'aws-sdk/dist/aws-sdk.min.js',
        './runtimeConfig': './runtimeConfig.browser', // fix production build
      },
    },
</code>```

This is one of the threads I've been following: https://github.com/aws/aws-sdk-js/issues/1769

How can I make sure this works?

Title: Vite + Vue 3 + AWS build

Body:
I'm trying to deploy a Vue 3 application that uses Vite, which locally works perfectly, but after deploy I get this error.

Uncaught TypeError: Cannot read properties of undefined (reading 'memoizedProperty')

I read that it could be from aws-sdk not collaborating well with Rollup, but it seems that the other solutions on the internet haven't worked.

Here are the relevant parts from vite.config.js:

resolve: {
      alias: {
        // vue: '@vue/compat'
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        path: 'path-browserify',
        // 'aws-sdk': 'aws-sdk/dist/aws-sdk.min.js',
        './runtimeConfig': './runtimeConfig.browser', // fix production build
      },
    },

This is one of the threads I've been following: https://github.com/aws/aws-sdk-js/issues/1769

How can I make sure this works?


问:
Cannot read properties of null (reading 'play') and Cannot read properties of null (reading 'pause')
In the application, there are a video background and one button for start and stop (the button image should change from play to stop) simultaneously the video and the music,
but when I click the button, the sound starts but not the video, and then if I click it another time it stops.
The video doesn't start and the img of the button doesn't change.

This is the code.

const app = () => {
  const song = document.querySelector(".song");
  const play = document.querySelector(".play");
  const outline = document.querySelector(".moving-outline circle");
  const video = document.querySelector(".vid-container button");

  //sounds
  const sounds = document.querySelectorAll(".sound-picker button");

  //time display
  const timeDisplay = document.querySelector(".time-display");

  // get length of the outline
  const outlineLength = outline.getTotalLength();

  //duration
  let fakeDuration = 600;

  outline.style.strokeDasharray = outlineLength;
  outline.style.strokeDashoffset = outlineLength;

  //play sound
  play.addEventListener("click", () => {
    checkPlaying(song);
  });

  // func specific to stop and play the sounds

  const checkPlaying = (song) => {
    if (song.paused) {
      song.play();
      video.play();
      play.src = "./svg/pause.svg";
    } else {
      song.pause();
      video.pause();
      play.src = "./svg/play.svg";
    }
  };
};

app();```

Thanks for reading !!

Body:
In the application, there are a video background and one button for start and stop (the button image should change from play to stop) simultaneously the video and the music,
but when I click the button, the sound starts but not the video, and then if I click it another time it stops.
The video doesn't start and the img of the button doesn't change.

This is the code.

const app = () => {
  const song = document.querySelector(".song");
  const play = document.querySelector(".play");
  const outline = document.querySelector(".moving-outline circle");
  const video = document.querySelector(".vid-container button");

  //sounds
  const sounds = document.querySelectorAll(".sound-picker button");

  //time display
  const timeDisplay = document.querySelector(".time-display");

  // get length of the outline
  const outlineLength = outline.getTotalLength();

  //duration
  let fakeDuration = 600;

  outline.style.strokeDasharray = outlineLength;
  outline.style.strokeDashoffset = outlineLength;

  //play sound
  play.addEventListener("click", () => {
    checkPlaying(song);
  });

  // func specific to stop and play the sounds

  const checkPlaying = (song) => {
    if (song.paused) {
      song.play();
      video.play();
      play.src = "./svg/pause.svg";
    } else {
      song.pause();
      video.pause();
      play.src = "./svg/play.svg";
    }
  };
};

app();

Thanks for reading !!


问:
Oracle JDK 17 docker image vs openjdk:17-jdk-slim
I am developing a microservice application using java 17.Now for docker image I need to choose between following two options

FROM openjdk:17-oracle

FROM openjdk:17-jdk-slim

I understand that slim version will create a lightweight image.But I still want to understand the pros and cons of oracle provided version's.

Which one will be suitable in terms of performance  while deploying in azure cloud?


问:
Airflow: Confusion in execution_date & start_date
My airflow scheduled runs were running perfectly until it misbehaved on 31-12-2022. I'm unable to figure out what exactly happened but I'm sure it is related to exec_date and start_date. My start_date for the dag is determined by the below code.(I call the below function)

```<code>def derive_start_date(timezone='Australia/Melbourne') -> datetime:
        def current_year():
            return datetime.datetime.now().year
        local_tz = pendulum.timezone(timezone)
        _dt = datetime.datetime(current_year(), 1, 1, tzinfo=local_tz
        return _dt
</code>```

While the above function should be setting the start date to 01-01-2022 but for some reason in the Airflow UI the dags had the start_date as 31-12-2022 (unable to find why).
The dags run were running fine for months until 31-12-2022. Below are details of a sample run on 30/12/2022.

```<code>30/12/22:
Schedule interval: (30 19 * * *)
Execution Date: 2022-12-30 08:30:00+00:00
DAG Start date: 2022-12-31T13:00:00+00:00
Task start date: 2022-12-31, 8:30
</code>```
```<code>31/12/2022:
Schedule interval: (30 19 * * *)
Execution Date: 2022-12-31T13:00:00+00:00
DAG Start date: 2022-12-31T13:00:00+00:00
Task start date: 2023-01-01, 12:13
</code>```
```<code>01/01/2023:
Schedule interval: (30 19 * * *)
Execution Date: 2023-01-01 08:30:00+00:00
DAG Start date: 2022-12-31T13:00:00+00:00
Task start date: 2023-01-02, 8:30
</code>```

As you can see on 31 December the execution dates have changed automatically and I'm unable figure out what could have happened. Can anyone point out which part of the puzzle am I missing here? They are back to normal from 1st January onwards.

Body:
My airflow scheduled runs were running perfectly until it misbehaved on 31-12-2022. I'm unable to figure out what exactly happened but I'm sure it is related to exec_date and start_date. My start_date for the dag is determined by the below code.(I call the below function)

def derive_start_date(timezone='Australia/Melbourne') -> datetime:
        def current_year():
            return datetime.datetime.now().year
        local_tz = pendulum.timezone(timezone)
        _dt = datetime.datetime(current_year(), 1, 1, tzinfo=local_tz
        return _dt

While the above function should be setting the start date to 01-01-2022 but for some reason in the Airflow UI the dags had the start_date as 31-12-2022 (unable to find why).
The dags run were running fine for months until 31-12-2022. Below are details of a sample run on 30/12/2022.

30/12/22:
Schedule interval: (30 19 * * *)
Execution Date: 2022-12-30 08:30:00+00:00
DAG Start date: 2022-12-31T13:00:00+00:00
Task start date: 2022-12-31, 8:30

31/12/2022:
Schedule interval: (30 19 * * *)
Execution Date: 2022-12-31T13:00:00+00:00
DAG Start date: 2022-12-31T13:00:00+00:00
Task start date: 2023-01-01, 12:13

01/01/2023:
Schedule interval: (30 19 * * *)
Execution Date: 2023-01-01 08:30:00+00:00
DAG Start date: 2022-12-31T13:00:00+00:00
Task start date: 2023-01-02, 8:30

As you can see on 31 December the execution dates have changed automatically and I'm unable figure out what could have happened. Can anyone point out which part of the puzzle am I missing here? They are back to normal from 1st January onwards.


问:
Extract a min value and corresponding row information based on date time index
Im unable to filter my dataframe to give me the details i need. Im trying to obtain the min value for any given 24 hour period but keep the detail in the filtered rows like the day name

below is the head of df dataframe. It has t datetimeindex format and ive pulled the hour column as an integer from the index time information and the low is a float. when i run the code between the two dataframes below the df2 is the second dataframe i get returned

```<code>df = pd.read_csv(r'C:/Users/Oliver/Documents/Data/eurusd1hr.csv')
df.drop(columns=(['Close', 'Open', 'High', 'Volume']), inplace=True)
df['t'] = (df['Date'] + ' ' + df['Time'])
df.drop(columns = ['Date', 'Time'], inplace=True)
df['t'] = pd.DatetimeIndex(df.t)
df.set_index('t', inplace=True)
df['hour'] = df.index.hour
df['day'] = df.index.day_name()

                        Low  hour     day
t
2003-05-05 03:00:00  1.12154     3  Monday
2003-05-05 04:00:00  1.12099     4  Monday
2003-05-05 05:00:00  1.12085     5  Monday
2003-05-05 06:00:00  1.12049     6  Monday
2003-05-05 07:00:00  1.12079     7  Monday```

```df2 = df.between_time('00:00', '23:00').groupby(pd.Grouper(freq='d')).min()```

```                Low  hour        day
t
2003-05-05  1.12014   3.0     Monday
2003-05-06  1.12723   0.0    Tuesday
2003-05-07  1.13265   0.0  Wednesday
2003-05-08  1.13006   0.0   Thursday
2003-05-09  1.14346   0.0     Friday```

I want to keep the corresponding hour in the hour column and also the hour information in the original index like the day name has been maintained

i was expecting the index and hour column to keep the information

ive tried add a 2nd grouper method but failed. I have also tried to reset the index. any help would be gratefully received. thanks
```

Body:
Im unable to filter my dataframe to give me the details i need. Im trying to obtain the min value for any given 24 hour period but keep the detail in the filtered rows like the day name

below is the head of df dataframe. It has t datetimeindex format and ive pulled the hour column as an integer from the index time information and the low is a float. when i run the code between the two dataframes below the df2 is the second dataframe i get returned

df = pd.read_csv(r'C:/Users/Oliver/Documents/Data/eurusd1hr.csv')
df.drop(columns=(['Close', 'Open', 'High', 'Volume']), inplace=True)
df['t'] = (df['Date'] + ' ' + df['Time'])
df.drop(columns = ['Date', 'Time'], inplace=True)
df['t'] = pd.DatetimeIndex(df.t)
df.set_index('t', inplace=True)
df['hour'] = df.index.hour
df['day'] = df.index.day_name()

                        Low  hour     day
t
2003-05-05 03:00:00  1.12154     3  Monday
2003-05-05 04:00:00  1.12099     4  Monday
2003-05-05 05:00:00  1.12085     5  Monday
2003-05-05 06:00:00  1.12049     6  Monday
2003-05-05 07:00:00  1.12079     7  Monday```

```df2 = df.between_time('00:00', '23:00').groupby(pd.Grouper(freq='d')).min()```

```                Low  hour        day
t
2003-05-05  1.12014   3.0     Monday
2003-05-06  1.12723   0.0    Tuesday
2003-05-07  1.13265   0.0  Wednesday
2003-05-08  1.13006   0.0   Thursday
2003-05-09  1.14346   0.0     Friday```

I want to keep the corresponding hour in the hour column and also the hour information in the original index like the day name has been maintained

i was expecting the index and hour column to keep the information

ive tried add a 2nd grouper method but failed. I have also tried to reset the index. any help would be gratefully received. thanks


问:
Docker dotnet restore failing with private NuGet repo behind proxy - GSSAPI operation failed with error - An invalid name was supplied
I am trying to do a docker build with a private nuget repository that sits behind a proxy, but I am getting this error during the dotnet restore:

```<code>Determining projects to restore...
  Retrying 'FindPackagesByIdAsyncCore' for source 'http://myprivaterepo/nuget/FindPackagesById()?id='System.Security.Cryptography.ProtectedData'&semVerLevel=2.0.0'.
  GSSAPI operation failed with error - An invalid name was supplied (Configuration file does not specify default realm).
/usr/share/dotnet/sdk/5.0.404/NuGet.targets(131,5): error : Failed to retrieve information about 'Microsoft.Data.SqlClient' from remote source 'http://myprivaterepo/nuget/FindP
ackagesById()?id='Microsoft.Data.SqlClient''&semVerLevel=2.0.0'. [/src/MyProject/MyProject.csproj]
/usr/share/dotnet/sdk/5.0.404/NuGet.targets(131,5): error :   GSSAPI operation failed with error - An invalid name was supplied (Configuration file does not specify default realm). [/src/MyProject/MyProject.csproj]
</code>```

Here are my dockerfile and nuget.config

DockerFile

```<code>FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base
WORKDIR /app
ENV http_proxy {...}
ENV https_proxy {...}
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["NuGet.Config", ""]
COPY ["MyProject/MyProject.csproj", "MyProject/"]
COPY ["MyProject.Repo/MyProject.Repo.csproj", "MyProject.Repo/"]
RUN dotnet restore "MyProject/MyProject.csproj"

COPY ..
WORKDIR "/src/MyProject"
RUN dotnet build "MyProject.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MyProject.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyProject.dll"]
</code>```

NuGet.Config

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <add key="Private Repo" value="http://myprivaterepo/nuget" />
        <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    </packageSources>
    <activePackageSource>
        <add key="All" value="(Aggregate source)" />
    </activePackageSource>
</configuration>
</code>```

I've tried messing with the nuget.config by adding the proxy addresses there and using the IP address of my private repo instead of the FQDN, as suggested by others, but still get the same error.

Body:
I am trying to do a docker build with a private nuget repository that sits behind a proxy, but I am getting this error during the dotnet restore:

Determining projects to restore...
  Retrying 'FindPackagesByIdAsyncCore' for source 'http://myprivaterepo/nuget/FindPackagesById()?id='System.Security.Cryptography.ProtectedData'&semVerLevel=2.0.0'.
  GSSAPI operation failed with error - An invalid name was supplied (Configuration file does not specify default realm).
/usr/share/dotnet/sdk/5.0.404/NuGet.targets(131,5): error : Failed to retrieve information about 'Microsoft.Data.SqlClient' from remote source 'http://myprivaterepo/nuget/FindP
ackagesById()?id='Microsoft.Data.SqlClient''&semVerLevel=2.0.0'. [/src/MyProject/MyProject.csproj]
/usr/share/dotnet/sdk/5.0.404/NuGet.targets(131,5): error :   GSSAPI operation failed with error - An invalid name was supplied (Configuration file does not specify default realm). [/src/MyProject/MyProject.csproj]

Here are my dockerfile and nuget.config

DockerFile

FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base
WORKDIR /app
ENV http_proxy {...}
ENV https_proxy {...}
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["NuGet.Config", ""]
COPY ["MyProject/MyProject.csproj", "MyProject/"]
COPY ["MyProject.Repo/MyProject.Repo.csproj", "MyProject.Repo/"]
RUN dotnet restore "MyProject/MyProject.csproj"

COPY ..
WORKDIR "/src/MyProject"
RUN dotnet build "MyProject.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MyProject.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyProject.dll"]

NuGet.Config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <add key="Private Repo" value="http://myprivaterepo/nuget" />
        <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    </packageSources>
    <activePackageSource>
        <add key="All" value="(Aggregate source)" />
    </activePackageSource>
</configuration>

I've tried messing with the nuget.config by adding the proxy addresses there and using the IP address of my private repo instead of the FQDN, as suggested by others, but still get the same error.


问:
Ming SWF markup and swfrender not giving correct output
I'm working on an application that uses Ming through the PHP extension to generate SWF files. This works great until someone needs to print something, so we create a PDF that uses a static image instead of flash. Currently we're using a custom solution that turns Flash into another format via Quicktime, but we want to get rid of needing a special box just for conversion.

I found SWFTools which looks like the perfect solution. I installed it on the web server and can call it from my app, but it's not generating the exact same output as the Flash version. I'm getting 33 errors with my test file, with two errors that repeat quite a bit:

```<code>array
  0 => string 'Error: ID 5 unknown' (length=19)
  ...
  3 => string 'Warning: Shape doesn't start with a moveTo' (length=42)
  ...
  33 => string 'Error: ID 133 unknown' (length=21)
</code>```

The resulting file ends up with a few missing shapes if I run swfrender with -l (but overall not bad), but without -l I seem to get the correct number of shapes but rendered incorrectly (for example, a square might have 3 sides correct, and then fill from the 4th side to a random corner of the image).

Is there a known incompatibility between ming and SWFTools or is there something I can do to clear up these errors?

I'm using ming 0.4.4 and swftools-2011-01-23-1815 on CentOS 5.5, and PHP 5.3.6 (custom compiled).

ContentLicense: CC BY-SA 3.0

Body:
I'm working on an application that uses Ming through the PHP extension to generate SWF files. This works great until someone needs to print something, so we create a PDF that uses a static image instead of flash. Currently we're using a custom solution that turns Flash into another format via Quicktime, but we want to get rid of needing a special box just for conversion.

I found SWFTools which looks like the perfect solution. I installed it on the web server and can call it from my app, but it's not generating the exact same output as the Flash version. I'm getting 33 errors with my test file, with two errors that repeat quite a bit:

array
  0 => string 'Error: ID 5 unknown' (length=19)
  ...
  3 => string 'Warning: Shape doesn't start with a moveTo' (length=42)
  ...
  33 => string 'Error: ID 133 unknown' (length=21)

The resulting file ends up with a few missing shapes if I run swfrender with -l (but overall not bad), but without -l I seem to get the correct number of shapes but rendered incorrectly (for example, a square might have 3 sides correct, and then fill from the 4th side to a random corner of the image).

Is there a known incompatibility between ming and SWFTools or is there something I can do to clear up these errors?

I'm using ming 0.4.4 and swftools-2011-01-23-1815 on CentOS 5.5, and PHP 5.3.6 (custom compiled).


问:
AWS Secrets Manager Canonical Request AWS Signature
I'd like to ask if any of u guys knows if my Canonical Request to calculate the AWS Signature V4 is really correct. I made a canonical request to the Secrets Manager service in AWS to retrieve the key vault credentials.

`POST
/GetSecretValue

content-type:application/x-amz-json-1.1
host:secretsmanager.sa-east-1.amazonaws.com
x-amz-content-sha256:032a33e004a673c7bd8 01e6d81c6e470fc18432ed60bd0bb484c5d39573581b4
x-amz-date:%vDt_DateTime_CMT%
x-amz-target:secretsmanager.getsecretvalue

accept-encoding;content-type;host;x-amz-content-sha256;x-amz-date;x-amz-target
032a33e004a673c7bd801e6d81c6e470fc18432ed60bd0bb484c5d39573581b4`


问:
next js run script right after page load / nextjs 13 app / only works if there is an error / react
I deliberately simplified the task to make it easier for you to understand.

My goal - is when the page loads (useEffect) the JavaScript code changes the color of the text. I shouldn't be able to see the default color since useEffect runs instantly. I have to instantly see blue

```<code>'use client';
import React, { useEffect, useRef } from 'react';

  export default function index() {
  const ref = useRef();

  useEffect(() => {
    ref.current.style.color = 'blue'
  }, []);

  return <h1 ref={ref}>12345</h1>;
}
</code>```

https://stackblitz.com/edit/nextjs-nzjwdb?file=app%2Fpage.js - example

In practice - all JavaScript code in Next js runs with a delay. Because of this, I see the text in the default color for a second.

In an article with a similar problem, it was proposed to create a custom hook useIsomorphicLayoutEffect. My code should be like this:

```<code>'use client';
import React, { useRef,useEffect,useLayoutEffect } from 'react';

const useIsomorphicLayoutEffect =
  typeof window !== 'undefined' ? useLayoutEffect : useEffect;

export default function index() {
  const ref = useRef();
  useIsomorphicLayoutEffect(() => {
    ref.current.style.color = 'blue'
  }, []);

  return <h1 ref={ref}>12345</h1>;
}
</code>```

https://stackblitz.com/edit/nextjs-2dc5z4?file=app%2Fpage.js - example, custom hook, behavior unchanged

It didn't work. I still saw the default color at the beginning.

Then I made a mistake! If it's wrong to write "useEffect" in a custom hook, the script works as I want! When the page loads, the color is instantly blue!!!

```<code>const useIsomorphicLayoutEffect =
  typeof window !== 'undefined' ? useLayoutEffect : useEffectBlaBlaBlaRandomText;
</code>```

https://stackblitz.com/edit/nextjs-ofguvu?file=app%2Fpage.js - example, expected behavior with error in console

I don't know why it works like this. The code works correctly only on error

But I am getting an error in the console that "useEffectBlaBlaBlaRandomText is not defined"
What can I do to make everything work and there are no errors in the console?

Body:
I deliberately simplified the task to make it easier for you to understand.

My goal - is when the page loads (useEffect) the JavaScript code changes the color of the text. I shouldn't be able to see the default color since useEffect runs instantly. I have to instantly see blue

'use client';
import React, { useEffect, useRef } from 'react';

  export default function index() {
  const ref = useRef();

  useEffect(() => {
    ref.current.style.color = 'blue'
  }, []);

  return
12345
;
}

https://stackblitz.com/edit/nextjs-nzjwdb?file=app%2Fpage.js - example

In practice - all JavaScript code in Next js runs with a delay. Because of this, I see the text in the default color for a second.

In an article with a similar problem, it was proposed to create a custom hook useIsomorphicLayoutEffect. My code should be like this:

'use client';
import React, { useRef,useEffect,useLayoutEffect } from 'react';

const useIsomorphicLayoutEffect =
  typeof window !== 'undefined' ? useLayoutEffect : useEffect;

export default function index() {
  const ref = useRef();
  useIsomorphicLayoutEffect(() => {
    ref.current.style.color = 'blue'
  }, []);

  return
12345
;
}

https://stackblitz.com/edit/nextjs-2dc5z4?file=app%2Fpage.js - example, custom hook, behavior unchanged

It didn't work. I still saw the default color at the beginning.

Then I made a mistake! If it's wrong to write "useEffect" in a custom hook, the script works as I want! When the page loads, the color is instantly blue!!!

const useIsomorphicLayoutEffect =
  typeof window !== 'undefined' ? useLayoutEffect : useEffectBlaBlaBlaRandomText;

https://stackblitz.com/edit/nextjs-ofguvu?file=app%2Fpage.js - example, expected behavior with error in console

I don't know why it works like this. The code works correctly only on error

But I am getting an error in the console that "useEffectBlaBlaBlaRandomText is not defined"
What can I do to make everything work and there are no errors in the console?


问:
awk adds undesired newline at the end of last detected parameter
I wrote an awk script designed to inject a function in certain definition files. It looks for lines containing a two word phrase, when found it adds a paragraph after that line, in which the second parameter is used at one point. In this example: If file.txt contains the words "foo bar" on a line, we want to add after it the lines "{" followed by "func(bar)" followed by "}", awk should see $1 as "foo" (static identifier) and $2 as "bar" (can be anything so we read it):

```<code>awk '{
    print $0
    if($1 == "foo" && $2 != "") {
        print "{"
        print "func(" $2 ")"
        print "}"
    }
}' file.txt > file_new.txt
</code>```

The issue is that $2 gains an unwanted newline at the end. This particularly seems to happen if there's nothing else on the line after it. Therefore the result in the produced file ends up being this:

```<code>foo bar
{
func(bar
)
}
</code>```

Instead of the correct format:

```<code>foo bar
{
func(bar)
}
</code>```

Everything else works fine, only problem is this newline getting stored in the second parameter for a strange reason. What do you suggest to get rid of it?

Regarding separators: It's worth noting the detected line can contain any mixture of spaces and tabs, either before after or between the two words. This means something like "    foo    bar    " should still ensure $1 is foo and $2 is bar.

Edit: With the provided example below, the file.txt would be something among the following lines. For different tests try adding spaces or tabs before / between / after foo and bar, as well as the empty line under it:

```<code>abc xyz
foo bar

123 789
</code>```

This is the output of grep foo file.txt | od -c on the original file I'm getting an issue with, it's larger and contains different words but is the exact same functionality as simplified here:

```<code>0000000  \t   s   p   e   c   u   l   a   r   m   a   p  \t
0000020       t   e   x   t   u   r   e   s   /   d   a   r   k   m   o
0000040   d   /   m   e   t   a   l   /   f   l   a   t   /   g   e   n
0000060   _   s   m   o   o   t   h   _   g   o   l   d   0   1   _   s
0000100   _   t   i   l   i   n   g   _   1   d  \n                   s
0000120   p   e   c   u   l   a   r   m   a   p  \t                   t
0000140   e   x   t   u   r   e   s   /   d   a   r   k   m   o   d   /
0000160   m   e   t   a   l   /   f   l   a   t   /   g   e   n   _   s
0000200   m   o   o   t   h   _   g   o   l   d   0   1   _   s   _   t
0000220   i   l   i   n   g   _   2   d  \n
0000231
</code>```

Body:
I wrote an awk script designed to inject a function in certain definition files. It looks for lines containing a two word phrase, when found it adds a paragraph after that line, in which the second parameter is used at one point. In this example: If file.txt contains the words "foo bar" on a line, we want to add after it the lines "{" followed by "func(bar)" followed by "}", awk should see $1 as "foo" (static identifier) and $2 as "bar" (can be anything so we read it):

awk '{
    print $0
    if($1 == "foo" && $2 != "") {
        print "{"
        print "func(" $2 ")"
        print "}"
    }
}' file.txt > file_new.txt

The issue is that $2 gains an unwanted newline at the end. This particularly seems to happen if there's nothing else on the line after it. Therefore the result in the produced file ends up being this:

foo bar
{
func(bar
)
}

Instead of the correct format:

foo bar
{
func(bar)
}

Everything else works fine, only problem is this newline getting stored in the second parameter for a strange reason. What do you suggest to get rid of it?

Regarding separators: It's worth noting the detected line can contain any mixture of spaces and tabs, either before after or between the two words. This means something like "    foo    bar    " should still ensure $1 is foo and $2 is bar.

Edit: With the provided example below, the file.txt would be something among the following lines. For different tests try adding spaces or tabs before / between / after foo and bar, as well as the empty line under it:

abc xyz
foo bar

123 789

This is the output of grep foo file.txt | od -c on the original file I'm getting an issue with, it's larger and contains different words but is the exact same functionality as simplified here:

0000000  \t   s   p   e   c   u   l   a   r   m   a   p  \t
0000020       t   e   x   t   u   r   e   s   /   d   a   r   k   m   o
0000040   d   /   m   e   t   a   l   /   f   l   a   t   /   g   e   n
0000060   _   s   m   o   o   t   h   _   g   o   l   d   0   1   _   s
0000100   _   t   i   l   i   n   g   _   1   d  \n                   s
0000120   p   e   c   u   l   a   r   m   a   p  \t                   t
0000140   e   x   t   u   r   e   s   /   d   a   r   k   m   o   d   /
0000160   m   e   t   a   l   /   f   l   a   t   /   g   e   n   _   s
0000200   m   o   o   t   h   _   g   o   l   d   0   1   _   s   _   t
0000220   i   l   i   n   g   _   2   d  \n
0000231


问:
sharing data across pages in quarto when loading from source file in R
I have an index.qmd page in quarto that loads a dataset

```<code>```{r}
test <- TRUE
source(paste0(getwd(),"/loading.R"))
```
</code>```

I have another page page1.qmd that needs to use the datasets loaded by the index page

```<code>```{r}
print(check)
print(test)
```
</code>```

the loading.R file contains code to create check

```<code>check <- TRUE
</code>```

Rendering using quarto render gives the following error:

```<code>←[1m←[34m[ 1/20] about.qmd←[39m←[22m
←[1m←[34m[ 2/20] page1.qmd←[39m←[22m
?[31m

processing file: page1.rmarkdown
  |...................................                                   |  50%
label: unnamed-chunk-1
?[31mQuitting from lines 2-7 (page1.rmarkdown)
?[39m?[31mError in print(check) : object 'check' not found
</code>```

It seems that the source load doesn't put things into global memory. How can I go about doing this?

Body:
I have an index.qmd page in quarto that loads a dataset

```{r}
test <- TRUE
source(paste0(getwd(),"/loading.R"))
```

I have another page page1.qmd that needs to use the datasets loaded by the index page

```{r}
print(check)
print(test)
```

the loading.R file contains code to create check

check <- TRUE

Rendering using quarto render gives the following error:

←[1m←[34m[ 1/20] about.qmd←[39m←[22m
←[1m←[34m[ 2/20] page1.qmd←[39m←[22m
?[31m

processing file: page1.rmarkdown
  |...................................                                   |  50%
label: unnamed-chunk-1
?[31mQuitting from lines 2-7 (page1.rmarkdown)
?[39m?[31mError in print(check) : object 'check' not found

It seems that the source load doesn't put things into global memory. How can I go about doing this?


问:
Reshaping a Pandas dataframe (column values to a new merged row)
I have a dataframe:
DF (https://i.stack.imgur.com/5e1J2.png)

Is there a way to reshape it like this?:
DF (https://i.stack.imgur.com/FOqYR.png)

Looking forward to any solutions.


问:
Hilt migration from dagger failing AndroidInjector.Factory<?>>> cannot be provided without an @Provides-annotated method
I am new to dagger/Hilt and trying to convert a legacy dagger application over to hilt, the app is much to large to convert in a single go so I am using https://dagger.dev/hilt/migration-guide#daggerandroid the dagger.android section

Following what little it says

```<code>@HiltAndroidApp
class MyApplication : HasAndroidInjector {
  @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Object>

  override fun androidInjector() = dispatchingAndroidInjector
}
</code>```

here is the application

```<code>
@HiltAndroidApp
class TestApplication : Application(), HasAndroidInjector {

    @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Any>

    override fun androidInjector() = dispatchingAndroidInjector

"other code"
</code>```

here is the appComponent

```<code>
@Singleton
@Component(
    modules = [
        AndroidInjectionModule::class,
        AppModule::class,
        ImageLoaderModule::class,
        ViewModelFactoryModule::class,
        // Activity Bindings
        SplashActivityBindingModule::class,
        WelcomeActivityBindingModule::class,
        MainActivityBindingModule::class,
        DevSettingsActivityBindingModule::class,
        CustomizeBindingModule::class,
        // Service Bindings
        NotificationsServiceBindingModule::class
    ]
)

interface AppComponent {

    fun inject(application: TestApplication)

    @Component.Builder
    interface Builder {

        fun build(): AppComponent

        @BindsInstance
        fun forApplication(application: Application): Builder
    }
}
</code>```

here is the app module

```<code>@Module
object AppModule {

    @Provides
    fun provideAppContext(application: Application): Context = application.baseContext

    @Provides
    fun provideAppUpdateManager(context: Context): AppUpdateManager =
        AppUpdateManagerFactory.create(context)

    @Provides
    fun provideAuthStateManager(): AuthStateManager = AuthStateManager

    @Provides
    fun provideSharedPreferencesManager(): SharedPreferencesManager = SharedPreferencesManager

    @Provides
    fun Manager(): Manager = Manager

    @Provides
    fun provideIOCoroutineDispatcher(): CoroutineDispatcher = Dispatchers.IO
}
</code>```

I have been searching around for answers with no luck on this specific issue.

Body:
I am new to dagger/Hilt and trying to convert a legacy dagger application over to hilt, the app is much to large to convert in a single go so I am using https://dagger.dev/hilt/migration-guide#daggerandroid the dagger.android section

Following what little it says

@HiltAndroidApp
class MyApplication : HasAndroidInjector {
  @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Object>

  override fun androidInjector() = dispatchingAndroidInjector
}

here is the application

@HiltAndroidApp
class TestApplication : Application(), HasAndroidInjector {

    @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Any>

    override fun androidInjector() = dispatchingAndroidInjector

"other code"

here is the appComponent

@Singleton
@Component(
    modules = [
        AndroidInjectionModule::class,
        AppModule::class,
        ImageLoaderModule::class,
        ViewModelFactoryModule::class,
        // Activity Bindings
        SplashActivityBindingModule::class,
        WelcomeActivityBindingModule::class,
        MainActivityBindingModule::class,
        DevSettingsActivityBindingModule::class,
        CustomizeBindingModule::class,
        // Service Bindings
        NotificationsServiceBindingModule::class
    ]
)

interface AppComponent {

    fun inject(application: TestApplication)

    @Component.Builder
    interface Builder {

        fun build(): AppComponent

        @BindsInstance
        fun forApplication(application: Application): Builder
    }
}

here is the app module

@Module
object AppModule {

    @Provides
    fun provideAppContext(application: Application): Context = application.baseContext

    @Provides
    fun provideAppUpdateManager(context: Context): AppUpdateManager =
        AppUpdateManagerFactory.create(context)

    @Provides
    fun provideAuthStateManager(): AuthStateManager = AuthStateManager

    @Provides
    fun provideSharedPreferencesManager(): SharedPreferencesManager = SharedPreferencesManager

    @Provides
    fun Manager(): Manager = Manager

    @Provides
    fun provideIOCoroutineDispatcher(): CoroutineDispatcher = Dispatchers.IO
}

I have been searching around for answers with no luck on this specific issue.


问:
downgrading to tensorflow = 2.4.0 conflicts with pixellib
I am running pixellib version 0.7.1 on Macos M1. It fails badly in image segmentation showing strange results. Some forums suggest downgrading tensorflow to 2.4.0. Here are the details from conda info:

```<code>    active environment : mlp
    active env location : /Users/saman/miniforge3/envs/mlp
            shell level : 1
       user config file : /Users/saman/.condarc
 populated config files : /Users/saman/miniforge3/.condarc
                          /Users/saman/.condarc
          conda version : 22.9.0
    conda-build version : not installed
         python version : 3.10.6.final.0
       virtual packages : __osx=13.0.1=0
                          __unix=0=0
                          __archspec=1=arm64
       base environment : /Users/saman/miniforge3  (writable)
      conda av data dir : /Users/saman/miniforge3/etc/conda
  conda av metadata url : None
           channel URLs : https://conda.anaconda.org/conda-forge/osx-arm64
                          https://conda.anaconda.org/conda-forge/noarch
          package cache : /Users/saman/miniforge3/pkgs
                          /Users/saman/.conda/pkgs
       envs directories : /Users/saman/miniforge3/envs
                          /Users/saman/.conda/envs
               platform : osx-arm64
             user-agent : conda/22.9.0 requests/2.28.1 CPython/3.10.6 Darwin/22.1.0 OSX/13.0.1
                UID:GID : 501:20
             netrc file : None
           offline mode : False
</code>```

right now

```<code>conda install tensorflow = 2.4.0
</code>```

Finds a million conflicts (guessing with all the pixellib packages)
pip install also somehow fails

```<code>(mlp) saman@Samanss-MacBook-Air opencv-python-4.5.3.56 % pip install tensorflow==2.4.0
ERROR: Could not find a version that satisfies the requirement tensorflow==2.4.0 (from versions: none)
ERROR: No matching distribution found for tensorflow==2.4.0
</code>```

I highly appriciate anyone helping me out of this.

Body:
I am running pixellib version 0.7.1 on Macos M1. It fails badly in image segmentation showing strange results. Some forums suggest downgrading tensorflow to 2.4.0. Here are the details from conda info:

    active environment : mlp
    active env location : /Users/saman/miniforge3/envs/mlp
            shell level : 1
       user config file : /Users/saman/.condarc
 populated config files : /Users/saman/miniforge3/.condarc
                          /Users/saman/.condarc
          conda version : 22.9.0
    conda-build version : not installed
         python version : 3.10.6.final.0
       virtual packages : __osx=13.0.1=0
                          __unix=0=0
                          __archspec=1=arm64
       base environment : /Users/saman/miniforge3  (writable)
      conda av data dir : /Users/saman/miniforge3/etc/conda
  conda av metadata url : None
           channel URLs : https://conda.anaconda.org/conda-forge/osx-arm64
                          https://conda.anaconda.org/conda-forge/noarch
          package cache : /Users/saman/miniforge3/pkgs
                          /Users/saman/.conda/pkgs
       envs directories : /Users/saman/miniforge3/envs
                          /Users/saman/.conda/envs
               platform : osx-arm64
             user-agent : conda/22.9.0 requests/2.28.1 CPython/3.10.6 Darwin/22.1.0 OSX/13.0.1
                UID:GID : 501:20
             netrc file : None
           offline mode : False

right now

conda install tensorflow = 2.4.0

Finds a million conflicts (guessing with all the pixellib packages)
pip install also somehow fails

(mlp) saman@Samanss-MacBook-Air opencv-python-4.5.3.56 % pip install tensorflow==2.4.0
ERROR: Could not find a version that satisfies the requirement tensorflow==2.4.0 (from versions: none)
ERROR: No matching distribution found for tensorflow==2.4.0

I highly appriciate anyone helping me out of this.


问:
Escape double quotes inside single quoted text
With spring boot 3.0.1 and thymeleaf 3.1 in the below expression:

```<code><a th:replace="~{fragments/paging :: paging(${totalPages}, ' Last >>', 'Last Page')}"></a>
</code>```

I am trying to replace ' Last >>' with ' ' and hence need to escape double-quotes.

I tried the suggestions and solutions suggested here, here and other SO threads but none of them seem working.

When I try using  " the text appears as it while for other options I get parsing error. What I am missing? After trying so many options I am feeling clueless. Any suggestion will be helpful.

Body:
With spring boot 3.0.1 and thymeleaf 3.1 in the below expression:

>', 'Last Page')}">

I am trying to replace ' Last >>' with ' ' and hence need to escape double-quotes.

I tried the suggestions and solutions suggested here, here and other SO threads but none of them seem working.

When I try using  " the text appears as it while for other options I get parsing error. What I am missing? After trying so many options I am feeling clueless. Any suggestion will be helpful.


问:
R plotting max values for weekdays
I have this data frame. It is an hourly data and I found max value for each day. I am trying to get every daily maximum values for the week of the day for each Site_Name. So for example maximum values of every Monday,Tueaday etc. within the data for each Site Name.

```<code>Site_Name              Date            x1     x2   x3
Aldergrove       2022-01-01 00:00      10     12   14
Aldergtove       2022-01-02 01:00       8     11    5
Aldergtove       2022-01-03 02:00       5      9    8
Aldergtove       2022-01-04 03:00      15     10   13
Aldergtove       2022-01-05 04:00      10     10   10
Aldergtove       2022-01-06 05:00       9      5    9
Heathrow         2022-01-01 00:00      14     19    5
Heathrow         2022-01-02 01:00      12     17   11
Heathrow         2022-01-03 02:00       7     12    0
...
</code>```

I have tried doing this. Although it is plotting 1 maximum value for each day of the week per site.

```<code>wday_summary <- df %>%
  group_by(Site_Name, wday(date, label = TRUE)) %>%
  summarise(across(x1:x3,  list(mean = ~ mean(.x, na.rm = TRUE),
                                                min = ~ min(.x, na.rm = TRUE),
                                                max = ~ max(.x, na.rm = TRUE)))) %>%
  rename(Week_Day = 'wday(Date, label = TRUE)')

wday_summary %>%
  filter(Site_Name %in% c("Aldergrove","Heathrow","Leuchars","Shawbury")) %>%
  ggplot(aes(Week_Day, x1_max, col = Site_Name)) +
  geom_point()
</code>```

Although I need my plot to show the maximum value of all days falling into the weekday category looking like this;

Title: R plotting max values for weekdays

Body:
I have this data frame. It is an hourly data and I found max value for each day. I am trying to get every daily maximum values for the week of the day for each Site_Name. So for example maximum values of every Monday,Tueaday etc. within the data for each Site Name.

Site_Name              Date            x1     x2   x3
Aldergrove       2022-01-01 00:00      10     12   14
Aldergtove       2022-01-02 01:00       8     11    5
Aldergtove       2022-01-03 02:00       5      9    8
Aldergtove       2022-01-04 03:00      15     10   13
Aldergtove       2022-01-05 04:00      10     10   10
Aldergtove       2022-01-06 05:00       9      5    9
Heathrow         2022-01-01 00:00      14     19    5
Heathrow         2022-01-02 01:00      12     17   11
Heathrow         2022-01-03 02:00       7     12    0
...

I have tried doing this. Although it is plotting 1 maximum value for each day of the week per site.

wday_summary <- df %>%
  group_by(Site_Name, wday(date, label = TRUE)) %>%
  summarise(across(x1:x3,  list(mean = ~ mean(.x, na.rm = TRUE),
                                                min = ~ min(.x, na.rm = TRUE),
                                                max = ~ max(.x, na.rm = TRUE)))) %>%
  rename(Week_Day = 'wday(Date, label = TRUE)')

wday_summary %>%
  filter(Site_Name %in% c("Aldergrove","Heathrow","Leuchars","Shawbury")) %>%
  ggplot(aes(Week_Day, x1_max, col = Site_Name)) +
  geom_point()

Although I need my plot to show the maximum value of all days falling into the weekday category looking like this;


问:
How to aceess Kafka running inside Docker from a python client running locally in a different machine
I am very new to Docker and currently I am trying to connect to Kafka which is running inside docker container to a python client that is running separately in a different PC.
The python client is running locally on a different PC and is not inside docker container.

When I try to produce and consume messages, I receive nothing on my client side, neither do I observe any error logs. The producer could not produce any messages on the topic and the consumer hence is not able to consume it.

Please find my docker compose file below:

```<code>version: '3.9'

services:

 zookeeper:
   image: wurstmeister/zookeeper
   container_name: zookeeper
   ports:
    - "2181:2181"

 kafka:
   image: wurstmeister/kafka
   container_name: kafka
   ports:
    - "9092:9092"
   depends_on:
     - zookeeper
   environment:
     KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
     KAFKA_ADVERTISED_HOST_NAME: "route -n | awk '/UG[ \t]/{print $$2}'"
     KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
</code>```

I have also tried changing the KAFKA_ADVERTISED_HOST_NAME to localhost but It also didn't help.

Kafka Logs:

```<code>[2023-01-10 15:04:08,711] INFO [SocketServer listenerType=ZK_BROKER, nodeId=1007] Starting socket server acceptors and processors (kafka.network.SocketServer)

[2023-01-10 15:04:08,766] INFO [SocketServer listenerType=ZK_BROKER, nodeId=1007] Started data-plane acceptor and processor(s) for endpoint : ListenerName(PLAINTEXT) (kafka.network.SocketServer)

[2023-01-10 15:04:08,767] INFO [SocketServer listenerType=ZK_BROKER, nodeId=1007] Started socket server acceptors and processors (kafka.network.SocketServer)

[2023-01-10 15:04:08,787] INFO Kafka version: 2.8.1 (org.apache.kafka.common.utils.AppInfoParser)

[2023-01-10 15:04:08,787] INFO Kafka commitId: 839b886f9b732b15 (org.apache.kafka.common.utils.AppInfoParser)

[2023-01-10 15:04:08,788] INFO Kafka startTimeMs: 1673363048767 (org.apache.kafka.common.utils.AppInfoParser)

[2023-01-10 15:04:08,801] INFO [KafkaServer id=1007] started (kafka.server.KafkaServer)

[2023-01-10 15:04:09,025] INFO [broker-1007-to-controller-send-thread]: Recorded new controller, from now on will use broker kafka:9092 (id: 1007 rack: null) (kafka.server.BrokerToControllerRequestThread)
</code>```

I tried running changing the compose file of Kafka and tried to change KAFKA_ADVERTISED_LISTENERS value to my host machine running kafka but this also didn't help.

Body:
I am very new to Docker and currently I am trying to connect to Kafka which is running inside docker container to a python client that is running separately in a different PC.
The python client is running locally on a different PC and is not inside docker container.

When I try to produce and consume messages, I receive nothing on my client side, neither do I observe any error logs. The producer could not produce any messages on the topic and the consumer hence is not able to consume it.

Please find my docker compose file below:

version: '3.9'

services:

 zookeeper:
   image: wurstmeister/zookeeper
   container_name: zookeeper
   ports:
    - "2181:2181"

 kafka:
   image: wurstmeister/kafka
   container_name: kafka
   ports:
    - "9092:9092"
   depends_on:
     - zookeeper
   environment:
     KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
     KAFKA_ADVERTISED_HOST_NAME: "route -n | awk '/UG[ \t]/{print $$2}'"
     KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092

I have also tried changing the KAFKA_ADVERTISED_HOST_NAME to localhost but It also didn't help.

Kafka Logs:

[2023-01-10 15:04:08,711] INFO [SocketServer listenerType=ZK_BROKER, nodeId=1007] Starting socket server acceptors and processors (kafka.network.SocketServer)

[2023-01-10 15:04:08,766] INFO [SocketServer listenerType=ZK_BROKER, nodeId=1007] Started data-plane acceptor and processor(s) for endpoint : ListenerName(PLAINTEXT) (kafka.network.SocketServer)

[2023-01-10 15:04:08,767] INFO [SocketServer listenerType=ZK_BROKER, nodeId=1007] Started socket server acceptors and processors (kafka.network.SocketServer)

[2023-01-10 15:04:08,787] INFO Kafka version: 2.8.1 (org.apache.kafka.common.utils.AppInfoParser)

[2023-01-10 15:04:08,787] INFO Kafka commitId: 839b886f9b732b15 (org.apache.kafka.common.utils.AppInfoParser)

[2023-01-10 15:04:08,788] INFO Kafka startTimeMs: 1673363048767 (org.apache.kafka.common.utils.AppInfoParser)

[2023-01-10 15:04:08,801] INFO [KafkaServer id=1007] started (kafka.server.KafkaServer)

[2023-01-10 15:04:09,025] INFO [broker-1007-to-controller-send-thread]: Recorded new controller, from now on will use broker kafka:9092 (id: 1007 rack: null) (kafka.server.BrokerToControllerRequestThread)

I tried running changing the compose file of Kafka and tried to change KAFKA_ADVERTISED_LISTENERS value to my host machine running kafka but this also didn't help.


问:
How to compute a 2-D embedding from a distance matrix?
I would like to draw a map of NYC where the distances between neighborhoods are scaled by transit time. I computed a distance matrix using the Google Maps Distance Matrix API for public transit.

To visualize it, I tried embedding using sklearn.manifold.MDS (metric MDS) and then making a scatter plot. This works kind of ok. Unfortunately, the axes are rescaled as part of this process, and I would like to provide a scale that reflects the raw transit time. In addition, the orientation of the points does not influence the fit, but for drawing a map, it would be nice if I could specify the orientation.

Does anyone have other methods that would be a better fit for my problem? I thought about fixing some reference points and using them to triangulate the remaining points on a map, but I don't know of an off-the-shelf way to do this.


问:
Are Package-Lock Vulnerabilities an Issue When Using No Packages?
Apologies if this is really simple, I really don't understand the fundamentals involved here.

I recently got a string of emails from GitHub letting me know that there were security vulnerabilities in my package-lock.json files, but since I do not actually have any packages in my package.json files (except parcel bundler, which was auto generated?), I wasn't sure if that was an issue. The only reason either file exists is because I used the Webstorm HTML5-Boilerplate template for the project, which auto generated them.

This is the entirety of my package.json file.

```<code>{
  "name": " ",
  "version": "0.0.1",
  "description": "",
  "keywords": "",
  "license": "",
  "author": "",
  "scripts": {
    "build": "parcel build index.html",
    "dev": "parcel index.html --open",
    "start": "npm run build && npm run dev",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "parcel-bundler": "^1.12.4"
  }
}
</code>```

To the best of my knowledge the only other external code used is jsdelivr and two research scripts, jquery and proliferate; none of these are raising any flags on GitHub.

Are there vulnerabilities simply by virtue of having outdated packages in package-lock.json even if they are never used? Should I just delete the files or is there a better solution?

The only real bug fix I've tried so far is generating a new HTML5-Boilerplate template using Webstorm to see if it had updated the package-lock, but that didn't do anything.

Body:
Apologies if this is really simple, I really don't understand the fundamentals involved here.

I recently got a string of emails from GitHub letting me know that there were security vulnerabilities in my package-lock.json files, but since I do not actually have any packages in my package.json files (except parcel bundler, which was auto generated?), I wasn't sure if that was an issue. The only reason either file exists is because I used the Webstorm HTML5-Boilerplate template for the project, which auto generated them.

This is the entirety of my package.json file.

{
  "name": " ",
  "version": "0.0.1",
  "description": "",
  "keywords": "",
  "license": "",
  "author": "",
  "scripts": {
    "build": "parcel build index.html",
    "dev": "parcel index.html --open",
    "start": "npm run build && npm run dev",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "parcel-bundler": "^1.12.4"
  }
}

To the best of my knowledge the only other external code used is jsdelivr and two research scripts, jquery and proliferate; none of these are raising any flags on GitHub.

Are there vulnerabilities simply by virtue of having outdated packages in package-lock.json even if they are never used? Should I just delete the files or is there a better solution?

The only real bug fix I've tried so far is generating a new HTML5-Boilerplate template using Webstorm to see if it had updated the package-lock, but that didn't do anything.