问:
Custom extension VS code- persistence state
I am tyring to keep the information in the sidebar in my vscode extention that I bulit, but I am not sure how to do that:

main code in the extention.js file:

```<code>    context.subscriptions.push(vscode.window.registerWebviewViewProvider(
        'viewId',
        sidebarProvider(context)
      ));
</code>```

main code in sidebarProvider.js:

```<code>const {sidebar} = require('./sidebar');

const sidebarProvider = (context) => {
  return {
    resolveWebviewView: (webviewView) => {
      sidebar(webviewView, context);
    },
  };
};

module.exports = sidebarProvider;
</code>```

main code in sidebar.js:

```<code>const vscode = require('vscode');

// severity, confidence, line number

const {handleMessageFromWebview} = require('./extenfuncs')

const fs = require('fs');

const sidebarhtml = String(fs.readFileSync(String(__dirname + "/siedbarwebviewhtml.html")))

const sidebar = function (webviewView, context) {

  webviewView.webview.onDidReceiveMessage(
    (message) => {

      handleMessageFromWebview(message, webviewView.webview)

    }, undefined,
    context.subscriptions)

  const html = sidebarhtml
  webviewView.webview.options = {
    enableScripts: true,
  };
  webviewView.webview.html = html;

};

module.exports = {sidebar}
</code>```

I tried to use getState and setState but it didn't work

Body:
I am tyring to keep the information in the sidebar in my vscode extention that I bulit, but I am not sure how to do that:

main code in the extention.js file:

    context.subscriptions.push(vscode.window.registerWebviewViewProvider(
        'viewId',
        sidebarProvider(context)
      ));

main code in sidebarProvider.js:

const {sidebar} = require('./sidebar');

const sidebarProvider = (context) => {
  return {
    resolveWebviewView: (webviewView) => {
      sidebar(webviewView, context);
    },
  };
};

module.exports = sidebarProvider;

main code in sidebar.js:

const vscode = require('vscode');

// severity, confidence, line number

const {handleMessageFromWebview} = require('./extenfuncs')

const fs = require('fs');

const sidebarhtml = String(fs.readFileSync(String(__dirname + "/siedbarwebviewhtml.html")))

const sidebar = function (webviewView, context) {

  webviewView.webview.onDidReceiveMessage(
    (message) => {

      handleMessageFromWebview(message, webviewView.webview)

    }, undefined,
    context.subscriptions)

  const html = sidebarhtml
  webviewView.webview.options = {
    enableScripts: true,
  };
  webviewView.webview.html = html;

};

module.exports = {sidebar}

I tried to use getState and setState but it didn't work


来源: stackexchange

问:
Get marked variable name as default value for propertyWrapper
Lets say I have a property Wrapper to fetch Feature Flag from a service and assign to a Boolean if it is enabled of not

```<code>@propertyWrapper final class FeatureToggle {

    var clientContainer: ConfigurableFeatureFlagClient
    private let key: String

    var wrappedValue: Bool {
       FeatureFlag(clientContainer: clientContainer).isEnabled(key: key)
     }

    init(key: String, container: ConfigurableRemoteConfigClient = RemoteConfigClient.shared) {
        self.clientContainer = container
        self.key = key
    }
}

// Test Class
class TestFeatureToggle {

  @FeatureToggle(key: "isFeatureEnabled")
  var isFeatureEnabled
}
</code>```

I'm trying to Make this FeatureToggle Property Wrapper to assume that key default value will be the variable name marked with the property Wrapper, so if @FeatureToggle is marking var isFeatureEnabled so the key will automatically be isFeatureEnabled

Currently I tried using the #function as default value to get the class and use Mirror reflection to get the variable name of the class marked with the property Wrapper

```<code>@propertyWrapper final class FeatureToggle {

var clientContainer: ConfigurableRemoteConfigClient
private let key: String

var wrappedValue: Bool {
    let factoryClass = Bundle.main.classNamed(key) as! NSObject.Type // Force Unwrap just to simplify the example
    let factory = factoryClass.init()
    let mirror = Mirror(reflecting: factory)
    for child in mirror.children {
        guard let featureToggle = child.value as? FeatureToggle else { continue }
        let formattedValue = child.label?.dropFirst() // Drop the _ inserted by OBJC
        return FeatureFlag(clientContainer: clientContainer).isEnabled(key: formattedValue)
    }
    return false
}

init(key: String = #function, container: ConfigurableRemoteConfigClient = RemoteConfigClient.shared) {
    self.clientContainer = container
    self.key = key
    print("Self.key == \(self.key)") // It will print "TestFeatureToggle" using my class in previous code
} }
</code>```

It works but i have to make the class TestFeatureToggle with @objc and makes it inherit from NSObject. Not to mention that this solution looks kind of ugly and hacky. My question is, is there an easier way without exposing to OBJC runtime or a more clean solution?

ContentLicense: CC BY-SA 4.0

Body:
Lets say I have a property Wrapper to fetch Feature Flag from a service and assign to a Boolean if it is enabled of not

@propertyWrapper final class FeatureToggle {

    var clientContainer: ConfigurableFeatureFlagClient
    private let key: String

    var wrappedValue: Bool {
       FeatureFlag(clientContainer: clientContainer).isEnabled(key: key)
     }

    init(key: String, container: ConfigurableRemoteConfigClient = RemoteConfigClient.shared) {
        self.clientContainer = container
        self.key = key
    }
}

// Test Class
class TestFeatureToggle {

  @FeatureToggle(key: "isFeatureEnabled")
  var isFeatureEnabled
}

I'm trying to Make this FeatureToggle Property Wrapper to assume that key default value will be the variable name marked with the property Wrapper, so if @FeatureToggle is marking var isFeatureEnabled so the key will automatically be isFeatureEnabled

Currently I tried using the #function as default value to get the class and use Mirror reflection to get the variable name of the class marked with the property Wrapper

@propertyWrapper final class FeatureToggle {

var clientContainer: ConfigurableRemoteConfigClient
private let key: String

var wrappedValue: Bool {
    let factoryClass = Bundle.main.classNamed(key) as! NSObject.Type // Force Unwrap just to simplify the example
    let factory = factoryClass.init()
    let mirror = Mirror(reflecting: factory)
    for child in mirror.children {
        guard let featureToggle = child.value as? FeatureToggle else { continue }
        let formattedValue = child.label?.dropFirst() // Drop the _ inserted by OBJC
        return FeatureFlag(clientContainer: clientContainer).isEnabled(key: formattedValue)
    }
    return false
}

init(key: String = #function, container: ConfigurableRemoteConfigClient = RemoteConfigClient.shared) {
    self.clientContainer = container
    self.key = key
    print("Self.key == \(self.key)") // It will print "TestFeatureToggle" using my class in previous code
} }

It works but i have to make the class TestFeatureToggle with @objc and makes it inherit from NSObject. Not to mention that this solution looks kind of ugly and hacky. My question is, is there an easier way without exposing to OBJC runtime or a more clean solution?


问:
What technologies can i use to implement this scroll effect?
What technologies should be used to create such accelerated scrolling? when lightly scrolling, the scrollbar slides for some more time

Example:
https://www.thecraftsmen.tech/


问:
How do I stream Product objects in object mode with the fetch API
I am processing data from a server which returns JSON objects. I read that it is possible to process data in different modes, byob and object mode. Unfortunately, I cannot seem to find any examples demonstrating that scenario.  I don't want to have to read a byte buffer, decode and then process the result JSON if there is a way to get the chunks as objects instead? I can see the data in my browser but when I assign it to a Product object in my UI, no products show.  Here is my sample code:

        interface Product {
          productId: string,
          productName: string,
          barcode: string,
          quantityOnHold: number
        }

```
<p>Here is how I am attempting to use the Fetch API. I'd like to use the highWaterMark that I read about but don't know how to use to return objects.</p>
<pre class="lang-js prettyprint-override"><code>
       const retrieveProducts = async () => {
           const products = [];
           const productBody ={
           category: 'fragrance',
           productCodes: [122222, 555555, 444444444]
          }

          const response = await fetch('/products', {
            method: 'POST',
            body: JSON.stringify(productBody)
          })

          const readableStream = response.body.pipeThrough(new TextDecoderStream());

          readableStream.pipeTo(new WritableStream({
           write(chunk) {
            console.log("Chunk received", chunk);
                products.push(JSON.parse(chunk)); // does not work!!
             // I want to be able add products
             // i.e. products.push(....)
           },
          close() {
            console.log("All products successfully processed!");
          },
          abort(e) {
            console.error("An error occurred!", e);
           }
         }));

        }

</code>```

Body:
I am processing data from a server which returns JSON objects. I read that it is possible to process data in different modes, byob and object mode. Unfortunately, I cannot seem to find any examples demonstrating that scenario.  I don't want to have to read a byte buffer, decode and then process the result JSON if there is a way to get the chunks as objects instead? I can see the data in my browser but when I assign it to a Product object in my UI, no products show.  Here is my sample code:

        interface Product {
          productId: string,
          productName: string,
          barcode: string,
          quantityOnHold: number
        }

Here is how I am attempting to use the Fetch API. I'd like to use the highWaterMark that I read about but don't know how to use to return objects.

       const retrieveProducts = async () => {
           const products = [];
           const productBody ={
           category: 'fragrance',
           productCodes: [122222, 555555, 444444444]
          }

          const response = await fetch('/products', {
            method: 'POST',
            body: JSON.stringify(productBody)
          })

          const readableStream = response.body.pipeThrough(new TextDecoderStream());

          readableStream.pipeTo(new WritableStream({
           write(chunk) {
            console.log("Chunk received", chunk);
                products.push(JSON.parse(chunk)); // does not work!!
             // I want to be able add products
             // i.e. products.push(....)
           },
          close() {
            console.log("All products successfully processed!");
          },
          abort(e) {
            console.error("An error occurred!", e);
           }
         }));

        }


问:
Apply a custom formula to only the visible cells after filtering
I want to apply the following formula to only filtered cells. I'm tracking attendance % and want to just see it by week and month when I filter.

```<code>=IFERROR((COUNTIF('Individual Absenteeism (Draft)'!$C$2:$C$225,"A")+(COUNTIF('Individual Absenteeism (Draft)'!$C$2:$C$225,"L")))/(COUNTIF('Individual Absenteeism (Draft)'!$C$2:$C$225,"P")+(COUNTIF('Individual Absenteeism (Draft)'!$C$2:$C$225,"A"))+(COUNTIF('Individual Absenteeism (Draft)'!$C$2:$C$225,"L"))),"")
</code>```

I built the formulas to measure attendance percentages from a spreadsheet that uses a "P" for present, "A" for absent and "L" for planned absence.

I was hoping to be able to filter the table or range by date (months and weeks) and have the formula update.

Body:
I want to apply the following formula to only filtered cells. I'm tracking attendance % and want to just see it by week and month when I filter.

=IFERROR((COUNTIF('Individual Absenteeism (Draft)'!$C$2:$C$225,"A")+(COUNTIF('Individual Absenteeism (Draft)'!$C$2:$C$225,"L")))/(COUNTIF('Individual Absenteeism (Draft)'!$C$2:$C$225,"P")+(COUNTIF('Individual Absenteeism (Draft)'!$C$2:$C$225,"A"))+(COUNTIF('Individual Absenteeism (Draft)'!$C$2:$C$225,"L"))),"")

I built the formulas to measure attendance percentages from a spreadsheet that uses a "P" for present, "A" for absent and "L" for planned absence.

I was hoping to be able to filter the table or range by date (months and weeks) and have the formula update.


问:
how can I send this nodeXml through a function and insert into XmlDocument from that function?
I have the following function :

```<code>Public Function Salida(ByVal est As String, ByVal err As String, Optional node As Object = Nothing) As String
        Dim m_xmld = New XmlDocument
        Try
            m_xmld.LoadXml("<tx><estado></estado><info></info></tx>")
            m_xmld.SelectSingleNode("tx/estado").InnerText = est
            m_xmld.SelectSingleNode("tx/info").InnerText = err

            If Not node Is Nothing Then
                m_xmld.SelectSingleNode("//").AppendChild(node)
            End If

        Catch ex As Exception
            m_xmld.InnerText = "Error al cargar nodos de error"

        End Try
        Return m_xmld.InnerXml

    End Function
</code>```

and I need to send the following node from somewhere else :

```<code><Transport>
 <file>
    <name>test.txt</name>
    <size>1,52 Kb</size>
    <type>.txt</type>
    <data>test data</data>
    <option>ExactName</option>
  </file>
<Transport>
</code>```

so I get the node :

```<code>mvarXmlSalida = Util.Salida("0", "", xmldoc.SelectSingleNode("//file/"))
</code>```

I need to rescue the whole node and add it to the error xml of the function.

Body:
I have the following function :

Public Function Salida(ByVal est As String, ByVal err As String, Optional node As Object = Nothing) As String
        Dim m_xmld = New XmlDocument
        Try
            m_xmld.LoadXml("<tx><estado></estado><info></info></tx>")
            m_xmld.SelectSingleNode("tx/estado").InnerText = est
            m_xmld.SelectSingleNode("tx/info").InnerText = err

            If Not node Is Nothing Then
                m_xmld.SelectSingleNode("//").AppendChild(node)
            End If

        Catch ex As Exception
            m_xmld.InnerText = "Error al cargar nodos de error"

        End Try
        Return m_xmld.InnerXml

    End Function

and I need to send the following node from somewhere else :

<Transport>
 <file>
    <name>test.txt</name>
    <size>1,52 Kb</size>
    <type>.txt</type>
    <data>test data</data>
    <option>ExactName</option>
  </file>
<Transport>

so I get the node :

mvarXmlSalida = Util.Salida("0", "", xmldoc.SelectSingleNode("//file/"))

I need to rescue the whole node and add it to the error xml of the function.


问:
Link Excel Office.js with Powershell Dataverse (PSDataverse)
I have an excel instance in which I am authenticated and able to access Dataverse.  I would like to be able to use the credentials from my excel instance to be able to run the PSDataverse script to load a csv to Dataverse from my computer.  Is this possible ?</p>
```<code>Connect-Dataverse "authority=https://login.microsoftonline.com/<tenant-id>/oauth2/authorize;clientid=<client-id>;clientsecret=<client-secret>;resource=https://<environment>.crm4.dynamics.com/"
Import-Csv "Account.csv" | ForEach-Object {
    @{ Uri = "account", Method= "PATCH", Value = @{
        name = $_.AccountName,
        overridencreatedon = $_.CreationDate,
        ...}}} | ConvertTo-Json | Send-DataverseOperation
</code>```

Body:
I have an excel instance in which I am authenticated and able to access Dataverse.  I would like to be able to use the credentials from my excel instance to be able to run the PSDataverse script to load a csv to Dataverse from my computer.  Is this possible ?

Connect-Dataverse "authority=https://login.microsoftonline.com/<tenant-id>/oauth2/authorize;clientid=<client-id>;clientsecret=<client-secret>;resource=https://<environment>.crm4.dynamics.com/"
Import-Csv "Account.csv" | ForEach-Object {
    @{ Uri = "account", Method= "PATCH", Value = @{
        name = $_.AccountName,
        overridencreatedon = $_.CreationDate,
        ...}}} | ConvertTo-Json | Send-DataverseOperation


问:
Why can't my discord bot see chat messages?
I want to make a bot to listen to Lofi Girl streams with friends in discord, but I don't understand why the bot doesn't see messages.

```<code>import discord
import youtube_dl

intents = discord.Intents.default()
intents.dm_messages = True
intents.guild_messages = True
intents.messages = True
intents.message_content = True
intents.voice_states = True
intents.voice_states = True
intents.members = True
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.event
async def on_message(message):
    if message.content.startswith('!play'):
        print(message.content)
        youtube_url = message.content[7:]
        ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        }
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(youtube_url, download=False)
            audio_url = info['url']

        voice_channel = message.author.voice.channel
        vc = await voice_channel.connect()
        vc.play(discord.FFmpegPCMAudio(audio_url))

@client.event
async def on_message(message):
    if message.content.startswith('!pause'):
        vc = message.guild.voice_client
        if vc.is_playing():
            vc.pause()

@client.event
async def on_message(message):
    if message.content.startswith('!resume'):
        vc = message.guild.voice_client
        if vc.is_paused():
            vc.resume()

client.run('DISCORD_TOKEN')
</code>```

No matter what I do, nothing works, I even tried to add more intents, but that didn't help either

Body:
I want to make a bot to listen to Lofi Girl streams with friends in discord, but I don't understand why the bot doesn't see messages.

import discord
import youtube_dl

intents = discord.Intents.default()
intents.dm_messages = True
intents.guild_messages = True
intents.messages = True
intents.message_content = True
intents.voice_states = True
intents.voice_states = True
intents.members = True
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.event
async def on_message(message):
    if message.content.startswith('!play'):
        print(message.content)
        youtube_url = message.content[7:]
        ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        }
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(youtube_url, download=False)
            audio_url = info['url']

        voice_channel = message.author.voice.channel
        vc = await voice_channel.connect()
        vc.play(discord.FFmpegPCMAudio(audio_url))

@client.event
async def on_message(message):
    if message.content.startswith('!pause'):
        vc = message.guild.voice_client
        if vc.is_playing():
            vc.pause()

@client.event
async def on_message(message):
    if message.content.startswith('!resume'):
        vc = message.guild.voice_client
        if vc.is_paused():
            vc.resume()

client.run('DISCORD_TOKEN')

No matter what I do, nothing works, I even tried to add more intents, but that didn't help either


问:
Why does Kucoin spot order URL seem to be causing KeyError?
I tried to create a simple trading execution code for one-time spot market buy order in Python (using Pycharm).

The code is provided below. API key, API passphrase and API secret key are correct, as well as a signature encoded in base64. The problem seems to be with the order URL. I use this one (provided by Kucoin API documentation): api/v1/orders

The error I'm getting is:

Traceback (most recent call last):
  File "C:\Users\xxxx\PycharmProjects\pythonProject11\main 2.py", line 57, in <module>
    response = client.request('POST', url, body=body_str, headers=headers)
  File "C:\Users\xxxx\PycharmProjects\pythonProject11\venv\lib\site-packages\ccxt\base\exchange.py", line 2801, in request
    return self.fetch2(path, api, method, params, headers, body, config, context)
  File "C:\Users\xxxx\PycharmProjects\pythonProject11\venv\lib\site-packages\ccxt\base\exchange.py", line 2797, in fetch2
    request = self.sign(path, api, method, params, headers, body)
  File "C:\Users\xxxx\PycharmProjects\pythonProject11\venv\lib\site-packages\ccxt\kucoin.py", line 3259, in sign
    url = self.urls['api'][api]
KeyError: '/api/v1/orders'

Process finished with exit code 1
```
<p>Code:</p>
<pre class="lang-py prettyprint-override"><code>import ccxt
import base64
import hashlib
import hmac
import json
from datetime import datetime

# Replace these with your own API key, secret key, and passphrase
api_key = ''
api_secret = ''
api_passphrase = ''

# Set up the Kucoin client
client = ccxt.kucoin()
client.apiKey = api_key
client.secret = api_secret
client.version = 'v1'

# Set the request parameters -- I know there should be a specific token in place of XXXX
symbol = 'XXXX/USDT'
side = 'buy'
type = 'market'
amount = 1.0

# Generate the timestamp in ISO 8601 format
timestamp = datetime.utcnow().isoformat() + 'Z'

# Construct the request body
body = {
  'clientOid': 'YOUR_UNIQUE_ID',
  'size': amount,
  'side': side,
  'symbol': symbol,
  'type': type
}

# Encode the request body as a JSON string
body_str = json.dumps(body)

# Set the request URL
url = '/api/v1/orders'

# Construct the signature
message = timestamp + 'POST' + url + body_str
signature = base64.b64encode(hmac.new(bytes(api_secret, 'latin-1'), bytes(message, 'latin-1'), digestmod=hashlib.sha256).digest())

# Set the request headers
headers = {
  'KC-API-KEY': api_key,
  'KC-API-SIGN': signature,
  'KC-API-TIMESTAMP': timestamp,
  'KC-API-PASSPHRASE': api_passphrase,
  'Content-Type': 'application/json'
}

# Send the POST request to the "POST /api/v1/orders" URL
response = client.request('POST', url, body=body_str, headers=headers)

# Print the response
print(response)
</code>```

I tried various URLs but it doesn't seem to work. What is causing the problem?

Body:
I tried to create a simple trading execution code for one-time spot market buy order in Python (using Pycharm).

The code is provided below. API key, API passphrase and API secret key are correct, as well as a signature encoded in base64. The problem seems to be with the order URL. I use this one (provided by Kucoin API documentation): api/v1/orders

The error I'm getting is:

Traceback (most recent call last):
  File "C:\Users\xxxx\PycharmProjects\pythonProject11\main 2.py", line 57, in <module>
    response = client.request('POST', url, body=body_str, headers=headers)
  File "C:\Users\xxxx\PycharmProjects\pythonProject11\venv\lib\site-packages\ccxt\base\exchange.py", line 2801, in request
    return self.fetch2(path, api, method, params, headers, body, config, context)
  File "C:\Users\xxxx\PycharmProjects\pythonProject11\venv\lib\site-packages\ccxt\base\exchange.py", line 2797, in fetch2
    request = self.sign(path, api, method, params, headers, body)
  File "C:\Users\xxxx\PycharmProjects\pythonProject11\venv\lib\site-packages\ccxt\kucoin.py", line 3259, in sign
    url = self.urls['api'][api]
KeyError: '/api/v1/orders'

Process finished with exit code 1

Code:

import ccxt
import base64
import hashlib
import hmac
import json
from datetime import datetime

# Replace these with your own API key, secret key, and passphrase
api_key = ''
api_secret = ''
api_passphrase = ''

# Set up the Kucoin client
client = ccxt.kucoin()
client.apiKey = api_key
client.secret = api_secret
client.version = 'v1'

# Set the request parameters -- I know there should be a specific token in place of XXXX
symbol = 'XXXX/USDT'
side = 'buy'
type = 'market'
amount = 1.0

# Generate the timestamp in ISO 8601 format
timestamp = datetime.utcnow().isoformat() + 'Z'

# Construct the request body
body = {
  'clientOid': 'YOUR_UNIQUE_ID',
  'size': amount,
  'side': side,
  'symbol': symbol,
  'type': type
}

# Encode the request body as a JSON string
body_str = json.dumps(body)

# Set the request URL
url = '/api/v1/orders'

# Construct the signature
message = timestamp + 'POST' + url + body_str
signature = base64.b64encode(hmac.new(bytes(api_secret, 'latin-1'), bytes(message, 'latin-1'), digestmod=hashlib.sha256).digest())

# Set the request headers
headers = {
  'KC-API-KEY': api_key,
  'KC-API-SIGN': signature,
  'KC-API-TIMESTAMP': timestamp,
  'KC-API-PASSPHRASE': api_passphrase,
  'Content-Type': 'application/json'
}

# Send the POST request to the "POST /api/v1/orders" URL
response = client.request('POST', url, body=body_str, headers=headers)

# Print the response
print(response)

I tried various URLs but it doesn't seem to work. What is causing the problem?


问:
Running Notepad++ with NppExport from command line
I've been using the NppExport plugin of notepad++ to load a source code file and then manually export this to html using the menu Plugins->NppExport->"Export to HTML"

However I'd like to know if it is possible to automate this? Ultimately I'd like to be able to call notepad++ from the command line to silently output the result as a html file:

```<code>notepad++ source_file.cpp highlighted.html
</code>```

I've tried recording the steps as a macro but that did not do anything.

I've also googled many variations of this question have found nothing about how to call a plugins commands.

Body:
I've been using the NppExport plugin of notepad++ to load a source code file and then manually export this to html using the menu Plugins->NppExport->"Export to HTML"

However I'd like to know if it is possible to automate this? Ultimately I'd like to be able to call notepad++ from the command line to silently output the result as a html file:

notepad++ source_file.cpp highlighted.html

I've tried recording the steps as a macro but that did not do anything.

I've also googled many variations of this question have found nothing about how to call a plugins commands.


问:
Google API not always returning profile data
Using django-allauth, I am allowing users to log in through their Google profiles using the all of the following settings:

```<code>SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
            'https://www.googleapis.com/auth/gmail.labels',
            'https://www.googleapis.com/auth/gmail.modify'
        ],
        'AUTH_PARAMS': {
            'access_type': 'offline',
        }
    }
}

SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
    'profile',
    'email',
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
]

SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
SOCIALACCOUNT_EMAIL_REQUIRED = False
SOCIALACCOUNT_STORE_TOKENS = True
SOCIALACCOUNT_AUTO_SIGNUP = True
</code>```

For some reason, the extra data I am receiving is inconsistent. Sometimes, I receive all of the profile data. Sometimes, I don't get the user's name. Sometimes I don't even get the user's email. The only thing I seem to consistently get is an id and a link to a avatar photo.

The accounts I am testing are all my own and I am able to verify that they all have their publicly available names saved correctly. Google seems to only sometimes return the full set of permissible data from the profile scope. I should note that the data it returns is consistent per each account. I never get different data for an account. Has anyone had an experience like this?

Body:
Using django-allauth, I am allowing users to log in through their Google profiles using the all of the following settings:

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
            'https://www.googleapis.com/auth/gmail.labels',
            'https://www.googleapis.com/auth/gmail.modify'
        ],
        'AUTH_PARAMS': {
            'access_type': 'offline',
        }
    }
}

SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
    'profile',
    'email',
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
]

SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
SOCIALACCOUNT_EMAIL_REQUIRED = False
SOCIALACCOUNT_STORE_TOKENS = True
SOCIALACCOUNT_AUTO_SIGNUP = True

For some reason, the extra data I am receiving is inconsistent. Sometimes, I receive all of the profile data. Sometimes, I don't get the user's name. Sometimes I don't even get the user's email. The only thing I seem to consistently get is an id and a link to a avatar photo.

The accounts I am testing are all my own and I am able to verify that they all have their publicly available names saved correctly. Google seems to only sometimes return the full set of permissible data from the profile scope. I should note that the data it returns is consistent per each account. I never get different data for an account. Has anyone had an experience like this?


问:
fgets doesn't wait for input in parent process but it does in the child one
This is an external function that sets environment variables

```<code>int mini_read(char ** variables){
    if(variables[1] == NULL){
        fprintf(stderr, "error\n");
        return 1;
    }
    char buf[100];
    fgets(buf, 100, stdin);

        //I doubt the bug is below here
    buf[strcspn(buf, "\n")] = 0;
    char ** valores = NULL;
    char * valor = strtok(buf, " \t");
    valores[0] = valor;
    int i = 1;
    // Guardar valores en array
    while(valor != NULL){
        valor = strtok(NULL, " \t");
        valores[i] = valor;
        i++;
    }
    for(int i = 1; ; i++){
        if(valores[i-1] == NULL) break;
        //printf("variables[%d]: %s\n valor[%d]: %c\n", i, variables[i], i, valor[i]);
        if(variables[i] == NULL){
            char*fin = NULL;
            //Si hay más valores que variables, concatenar valores
            for(int j = i-1; valores[j] != NULL; j++){
                printf("%s\n", fin);
                strcat(fin, valores[j]);
            }
            printf("%s\n", fin);
            setenv(variables[i-1], fin, 1);
            break;
        }
        setenv(variables[i], valores[i-1], 1);
    }
    return 0;
</code>```

Then I want to call the function in the parent process because if I call it from the child process the environment variables don't get set "globally".
If I call it from the child process it works just fine; however, if I call it from the parent process, fgets() doesn't wait for input.

```<code>int main(void){

pid = fork();

    if(pid == 0){
        //Option 1
        if(strcmp(argv[0], "read") == 0) mini_read(argv);
    }

    else{
        //Option 2
        if(strcmp(argv[0], "read") == 0) mini_read(argv);

        waitpid(pid, &wstatus, 0);
    }
}
</code>```

Body:
This is an external function that sets environment variables

int mini_read(char ** variables){
    if(variables[1] == NULL){
        fprintf(stderr, "error\n");
        return 1;
    }
    char buf[100];
    fgets(buf, 100, stdin);

        //I doubt the bug is below here
    buf[strcspn(buf, "\n")] = 0;
    char ** valores = NULL;
    char * valor = strtok(buf, " \t");
    valores[0] = valor;
    int i = 1;
    // Guardar valores en array
    while(valor != NULL){
        valor = strtok(NULL, " \t");
        valores[i] = valor;
        i++;
    }
    for(int i = 1; ; i++){
        if(valores[i-1] == NULL) break;
        //printf("variables[%d]: %s\n valor[%d]: %c\n", i, variables[i], i, valor[i]);
        if(variables[i] == NULL){
            char*fin = NULL;
            //Si hay más valores que variables, concatenar valores
            for(int j = i-1; valores[j] != NULL; j++){
                printf("%s\n", fin);
                strcat(fin, valores[j]);
            }
            printf("%s\n", fin);
            setenv(variables[i-1], fin, 1);
            break;
        }
        setenv(variables[i], valores[i-1], 1);
    }
    return 0;

Then I want to call the function in the parent process because if I call it from the child process the environment variables don't get set "globally".
If I call it from the child process it works just fine; however, if I call it from the parent process, fgets() doesn't wait for input.

int main(void){

pid = fork();

    if(pid == 0){
        //Option 1
        if(strcmp(argv[0], "read") == 0) mini_read(argv);
    }

    else{
        //Option 2
        if(strcmp(argv[0], "read") == 0) mini_read(argv);

        waitpid(pid, &wstatus, 0);
    }
}


问:
Angular app shows blank page on github pages and 404 errors on JS console
I am trying to deploy my angular app on Github pages but I keep getting the 404 file not found errors.
I have tried using various approaches:

Using /AISearchSimulator/docs/ as the base for URL

Using /AISearchSimulator/ as the base for URL

Using /docs/ as the base for URL

Using https://github.com/jeetendragan/AISearchSimulator/ as the base for URL
etc.

but no options seem to work.

Here is my repository - https://github.com/jeetendragan/AISearchSimulator
Index File: https://github.com/jeetendragan/AISearchSimulator/blob/master/docs/index.html


问:
InvalidArgumentError: Graph execution error:
I am new to the machine learning concept, I am following a video from Udacity and I run into some problems.

I am trying to create a Transfer Learning model. When I try to 'fit' it it returns an error:

```<code>InvalidArgumentError: Graph execution error:
</code>```

I don't know what I am doing wrong... I am following step by step (only changed some "outdated" code)

here is my code, if someone can help me solve this and explain a bit it'd be very helpful

```<code>!pip install -q -U "tensorflow-gpu==2.2.0"
!pip install -q -U tensorflow_hub
!pip install -q -U tensorflow_datasets

import time
import numpy as np
import matplotlib.pylab as plt

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
tfds.disable_progress_bar()

from tensorflow.keras import layers

#Here was supposed to be a split function to split the data 80% (train), 20% (validation), I don't know what I did but in the line below I did "split=['train[:80%]', 'train[20%:]']" is it ok? or should I change something there?
splits, info = tfds.load('cats_vs_dogs', with_info=True, as_supervised=True, split=['train[:80%]', 'train[20%:]'])

(train_examples, validation_examples) = splits

def format_image(image, label):
    images = tf.image.resize(image, (IMAGE_RES, IMAGE_RES))//255.0
    return image, label

num_examples = info.splits['train'].num_examples

BATCH_SIZE = 32
IMAGE_RES = 224

train_batches      = train_examples.cache().shuffle(num_examples//4).map(format_image).batch(BATCH_SIZE).prefetch(1)
validation_batches = validation_examples.cache().map(format_image).batch(BATCH_SIZE).prefetch(1)

URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
feature_extractor = hub.KerasLayer(URL, input_shape=(IMAGE_RES,IMAGE_RES,3))

feature_extractor.trainable = False

model = tf.keras.Sequential([
    feature_extractor,
    layers.Dense(2, activation='softmax')
])

model.summary()

model.compile(
    optimizer='adam',
    loss=tf.losses.SparseCategoricalCrossentropy(),
    metrics=['accuracy'])

EPOCHS = 2
history = model.fit(train_batches,
                    epochs=EPOCHS,
                    validation_data=validation_batches) #From here I get the problem
</code>```

Body:
I am new to the machine learning concept, I am following a video from Udacity and I run into some problems.

I am trying to create a Transfer Learning model. When I try to 'fit' it it returns an error:

InvalidArgumentError: Graph execution error:

I don't know what I am doing wrong... I am following step by step (only changed some "outdated" code)

here is my code, if someone can help me solve this and explain a bit it'd be very helpful

!pip install -q -U "tensorflow-gpu==2.2.0"
!pip install -q -U tensorflow_hub
!pip install -q -U tensorflow_datasets

import time
import numpy as np
import matplotlib.pylab as plt

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
tfds.disable_progress_bar()

from tensorflow.keras import layers

#Here was supposed to be a split function to split the data 80% (train), 20% (validation), I don't know what I did but in the line below I did "split=['train[:80%]', 'train[20%:]']" is it ok? or should I change something there?
splits, info = tfds.load('cats_vs_dogs', with_info=True, as_supervised=True, split=['train[:80%]', 'train[20%:]'])

(train_examples, validation_examples) = splits

def format_image(image, label):
    images = tf.image.resize(image, (IMAGE_RES, IMAGE_RES))//255.0
    return image, label

num_examples = info.splits['train'].num_examples

BATCH_SIZE = 32
IMAGE_RES = 224

train_batches      = train_examples.cache().shuffle(num_examples//4).map(format_image).batch(BATCH_SIZE).prefetch(1)
validation_batches = validation_examples.cache().map(format_image).batch(BATCH_SIZE).prefetch(1)

URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
feature_extractor = hub.KerasLayer(URL, input_shape=(IMAGE_RES,IMAGE_RES,3))

feature_extractor.trainable = False

model = tf.keras.Sequential([
    feature_extractor,
    layers.Dense(2, activation='softmax')
])

model.summary()

model.compile(
    optimizer='adam',
    loss=tf.losses.SparseCategoricalCrossentropy(),
    metrics=['accuracy'])

EPOCHS = 2
history = model.fit(train_batches,
                    epochs=EPOCHS,
                    validation_data=validation_batches) #From here I get the problem


问:
What is the best video live streaming service/API for a Rails app?
What I'm looking for:

live streaming video - broadcast, 1:1

ability to record streams

up to 10 video streams at the same time

I've tested OpenTok but the quality isn't there for larger videos. Any alternatives or should I write my own?

ContentLicense: CC BY-SA 3.0


问:
Is there a way to prevent rust compiler from rearranging my code?
After inspecting a disassembly of my binary, I realised that compiler turned

```<code>expensive_function();
let t1 = Instant::now();
let ptr = get_mut_ptr::<AtomicUsize>();
(ptr).store(some_value, Ordering::Relaxed);
let t2 = Instant::now();
</code>```

into

```<code>let t1 = Instant::now();
expensive_function();
let ptr = get_mut_ptr::<AtomicUsize>();
(ptr).store(some_value, Ordering::Relaxed);
let t2 = Instant::now();
</code>```

And completely screwed my performance measurements.

Is there a way to prevent this?

Body:
After inspecting a disassembly of my binary, I realised that compiler turned

expensive_function();
let t1 = Instant::now();
let ptr = get_mut_ptr::<AtomicUsize>();
(ptr).store(some_value, Ordering::Relaxed);
let t2 = Instant::now();

into

let t1 = Instant::now();
expensive_function();
let ptr = get_mut_ptr::<AtomicUsize>();
(ptr).store(some_value, Ordering::Relaxed);
let t2 = Instant::now();

And completely screwed my performance measurements.

Is there a way to prevent this?


问:
Aliasing "struct T" as "T" with typedef
I found this in SDL 2.0 source code. The SDL_Texture is repeated twice. It seems that we are aliasing "struct SDL_Texture" as "SDL_Texture". How is this useful? Can someone elaborate?</p>
```<code>/**
 * An efficient driver-specific representation of pixel data
 */
struct SDL_Texture;
typedef struct SDL_Texture SDL_Texture;
</code>```

Title: Aliasing "struct T" as "T" with typedef

Body:
I found this in SDL 2.0 source code. The SDL_Texture is repeated twice. It seems that we are aliasing "struct SDL_Texture" as "SDL_Texture". How is this useful? Can someone elaborate?

/**
 * An efficient driver-specific representation of pixel data
 */
struct SDL_Texture;
typedef struct SDL_Texture SDL_Texture;


问:
In STS, server up error : org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class
In STS after converting from Java 11 to Java 17. While making the server up, getting the following error.

{"@timestamp":"2022-12-21T11:09:36.129-08:00","@version":"1","message":"Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.package.name]","logger_name":"org.springframework.context.annotation.AnnotationConfigApplicationContext","thread_name":"main","level":"WARN"}
{"@timestamp":"2022-12-21T11:09:36.147-08:00","@version":"1","message":"\r\n\r\nError starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.","logger_name":"org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLogger","thread_name":"main","level":"INFO"}
{"@timestamp":"2022-12-21T11:09:36.193-08:00","@version":"1","message":"Application run failed","logger_name":"org.springframework.boot.SpringApplication","thread_name":"main","level":"ERROR","stack_trace":"org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class

Build is successfull. But unable to up the server. Is any config or dependency are missing ? Converting from java 11 to Java 17 in STS.


问:
Junit for Spring Application and skip original configuration file

My Spring class Class

```<code>public class DemoDAO{

    public Map<String, Object> getQuery(String quer) {
            ApplicationContext context = new ClassPathXmlApplicationContext("myConfig.xml");
    SessionFactory sessionFactoryFacility = (SessionFactory) context.getBean("myBean");
            Session session = sessionFactoryFacility.openSession();
            Transaction tx = session.beginTransaction();
            //--------------------

    }
}
</code>```

Now when I was trying to write Junit for the above class,

```<code>@ContextConfiguration
@ExtendWith(org.mockito.junit.jupiter.MockitoExtension.class)
@TransactionConfiguration(defaultRollback = true)
public class DemoTest {

    @InjectMocks
    DemoDAO demo;

    @Test
    public void getQueryTest() {

        Map<String, Object> response = demo.getQuery("query");
    }
}
</code>```

Now when i try to debug this application, giving errors saying unknown host and other errors , Because it is always connecting to "myConfig.xml" and  trying to fetch the details, but in my "myConfig.xml" all are configured PRODUCTION DB details. I don't want to connect Production DB while testing my DAO class. Please suggest how to test this application

Body:
My Spring class Class

public class DemoDAO{

    public Map<String, Object> getQuery(String quer) {
            ApplicationContext context = new ClassPathXmlApplicationContext("myConfig.xml");
    SessionFactory sessionFactoryFacility = (SessionFactory) context.getBean("myBean");
            Session session = sessionFactoryFacility.openSession();
            Transaction tx = session.beginTransaction();
            //--------------------

    }
}

Now when I was trying to write Junit for the above class,

@ContextConfiguration
@ExtendWith(org.mockito.junit.jupiter.MockitoExtension.class)
@TransactionConfiguration(defaultRollback = true)
public class DemoTest {

    @InjectMocks
    DemoDAO demo;

    @Test
    public void getQueryTest() {

        Map<String, Object> response = demo.getQuery("query");
    }
}

Now when i try to debug this application, giving errors saying unknown host and other errors , Because it is always connecting to "myConfig.xml" and  trying to fetch the details, but in my "myConfig.xml" all are configured PRODUCTION DB details. I don't want to connect Production DB while testing my DAO class. Please suggest how to test this application


问:
Heatmap/densitymap from weighted scatterpoints

```<code>xy = np.random.random((50,3))
x = xy[:,0]
y = xy[:,1]
z = xy[:,2]*100

plt.scatter(x,y,c=z, cmap="Reds")
</code>```

I have the above data, as can be seen they all have a x and y position along with a value this being conveyed by the colour of the data dot.

From this i want to create a heatmap / density map where the areas near dots are effected by it.

I have tried making heatmaps with  ax.histogram2d() but the problem I have is to make the values affect "nearby areas"
Example of what it looks like now so I would need the bins to effect their nearby bins

```<code>heatmap, xedges, yedges = np.histogram2d(x, y, weights=z, bins=(50,50))
extent = [0, 1, 0, 1]
</code>```

Body:
xy = np.random.random((50,3))
x = xy[:,0]
y = xy[:,1]
z = xy[:,2]*100

plt.scatter(x,y,c=z, cmap="Reds")

I have the above data, as can be seen they all have a x and y position along with a value this being conveyed by the colour of the data dot.

From this i want to create a heatmap / density map where the areas near dots are effected by it.

I have tried making heatmaps with  ax.histogram2d() but the problem I have is to make the values affect "nearby areas"
Example of what it looks like now so I would need the bins to effect their nearby bins

heatmap, xedges, yedges = np.histogram2d(x, y, weights=z, bins=(50,50))
extent = [0, 1, 0, 1]


问:
Finding the max terms in documents by elasticsearch
My question is to know which terms are most present among the highest rated articles and then the lowest ones in a separate queries?

I am going to share a preview of the document:

```<code>},
  "hits" : {
   "total" : {
    "value" : 10000,
    "relation" : "gte"
},
"max_score" : 1.0,
"hits" : [
  {
    "_index" : "eval_new",
    "_id" : "3e_SH4UB2ObC5e1B9eV9",
    "_score" : 1.0,
    "_source" : {
      "Clothing ID" : "767",
      "Age" : "33",
      "Title" : "",
      "Review Text" : "Absolutely wonderful - silky and sexy and comfortable",
      "Rating" : "4",
      "Recommended IND" : "1",
      "Positive Feedback Count" : "0",
      "Division Name" : "Initmates",
      "Department Name" : "Intimate",
      "Class Name" : "Intimates"
    }
  },
</code>```

I have created a request as follow, But I dont think it's the right one:

```<code>GET eval/_search
{
  "size": 0,
  "aggs": {
    "maxGroup": {
      "terms": {
        "field": "Class Name.keyword",
        "size": 10
      },
      "aggs": {
        "theMax": {
          "max": {
           "field": "Rating"
         }
       }
     }
   }
 }
}
</code>```

the result of this query is as follow:

```<code>},
  "aggregations" : {
   "maxGroup" : {
  "doc_count_error_upper_bound" : 0,
  "sum_other_doc_count" : 1824,
  "buckets" : [
    {
      "key" : "Dresses",
      "doc_count" : 6319,
      "theMax" : {
        "value" : 5.0
      }
    },
    {
      "key" : "Knits",
      "doc_count" : 4843,
      "theMax" : {
        "value" : 5.0
      }
    },
    {
      "key" : "Blouses",
      "doc_count" : 3097,
      "theMax" : {
        "value" : 5.0
</code>```

the problem is when I change the max by the min the only thing it changes is the ("value" : 5.0) from 5 to 1 and the quantity for examples for the dresses remains the same. Any idea and thanks in advance

Body:
My question is to know which terms are most present among the highest rated articles and then the lowest ones in a separate queries?

I am going to share a preview of the document:

},
  "hits" : {
   "total" : {
    "value" : 10000,
    "relation" : "gte"
},
"max_score" : 1.0,
"hits" : [
  {
    "_index" : "eval_new",
    "_id" : "3e_SH4UB2ObC5e1B9eV9",
    "_score" : 1.0,
    "_source" : {
      "Clothing ID" : "767",
      "Age" : "33",
      "Title" : "",
      "Review Text" : "Absolutely wonderful - silky and sexy and comfortable",
      "Rating" : "4",
      "Recommended IND" : "1",
      "Positive Feedback Count" : "0",
      "Division Name" : "Initmates",
      "Department Name" : "Intimate",
      "Class Name" : "Intimates"
    }
  },

I have created a request as follow, But I dont think it's the right one:

GET eval/_search
{
  "size": 0,
  "aggs": {
    "maxGroup": {
      "terms": {
        "field": "Class Name.keyword",
        "size": 10
      },
      "aggs": {
        "theMax": {
          "max": {
           "field": "Rating"
         }
       }
     }
   }
 }
}

the result of this query is as follow:

},
  "aggregations" : {
   "maxGroup" : {
  "doc_count_error_upper_bound" : 0,
  "sum_other_doc_count" : 1824,
  "buckets" : [
    {
      "key" : "Dresses",
      "doc_count" : 6319,
      "theMax" : {
        "value" : 5.0
      }
    },
    {
      "key" : "Knits",
      "doc_count" : 4843,
      "theMax" : {
        "value" : 5.0
      }
    },
    {
      "key" : "Blouses",
      "doc_count" : 3097,
      "theMax" : {
        "value" : 5.0

the problem is when I change the max by the min the only thing it changes is the ("value" : 5.0) from 5 to 1 and the quantity for examples for the dresses remains the same. Any idea and thanks in advance


问:
Cannot Change Value for Fluent UI React Picker With Jest and RTL
I'm trying to write a jest test for this Fluent UI picker:
https://developer.microsoft.com/en-us/fluentui#/controls/web/peoplepicker

Trying to just click and type in a some text. I can see that it renders in the screen but I cannot get the value to change. What am I doing wrong?

```<code> it('Changes value', async () => {
        render(<PersonPicker setPerson={() => jest.fn()} />);
        const personComboBox: HTMLInputElement = screen.findByRole('combobox');

        screen.debug(personComboBox);

        fireEvent.click(personComboBox);

        await waitFor(() => {
            fireEvent.change(personComboBox, { target: { value: 'John Doe' } });
        });

        expect(personComboBox.value).toBe('John Doe');

    });
</code>```

Appreciate if anyone can provide some guidance.
Thank you!

Body:
I'm trying to write a jest test for this Fluent UI picker:
https://developer.microsoft.com/en-us/fluentui#/controls/web/peoplepicker

Trying to just click and type in a some text. I can see that it renders in the screen but I cannot get the value to change. What am I doing wrong?

 it('Changes value', async () => {
        render(<PersonPicker setPerson={() => jest.fn()} />);
        const personComboBox: HTMLInputElement = screen.findByRole('combobox');

        screen.debug(personComboBox);

        fireEvent.click(personComboBox);

        await waitFor(() => {
            fireEvent.change(personComboBox, { target: { value: 'John Doe' } });
        });

        expect(personComboBox.value).toBe('John Doe');

    });

Appreciate if anyone can provide some guidance.
Thank you!


问:
Secret Imagage Steganography - python
I have been stuck on this program for a while and I am completely lost as to what is wrong and what I need to fix. I am trying to use steganography to encrypt a secret image inside of a cover image, and then decrypt the secret image. I am given part of the code and I have to implement the encode_pixel and decode_pixel functions, as well as the "helper functions".

When I run the program, the resulting image is completely grey instead of the secret image. I do not know where my error is, and if it is in the encode or decode function, or if it is in the helper functions.

These are the functions that I have implemented:

```<code>ORIGINAL_URL = "https://codehs.com/uploads/c709d869e62686611c1ac849367b3245"

SECRET_URL = "https://codehs.com/uploads/e07cd01271cac589cc9ef1bf012c6a0c"

IMAGE_LOAD_WAIT_TIME = 1000

# Constants for pixel indices
RED = 0
GREEN = 1
BLUE = 2

# Constants for colors
MAX_COLOR_VALUE = 255
MIN_COLOR_VALUE = 0
COLOR_THRESHOLD = 128

# Constants for spacing
X_GAP = 100
Y_GAP = 50
TEXT_Y_GAP = 4
IMAGE_WIDTH = 100
IMAGE_HEIGHT = 100
IMAGE_X = 25
IMAGE_Y = 25

# Set Canvas size
set_size(400, 480)

# Encodes the given secret pixel into the low bits of the
# RGB values of the given cover pixel
# Returns the modified cover pixel

def encode_pixel(cover_pixel, secret_pixel):
    # Implement this function
    # return a temporary value.  Change this!!
    return_pixel = [0,0,0]
    if secret_pixel[RED]>= COLOR_THRESHOLD:
        return_pixel[RED] = set_lowest_bit(cover_pixel[RED], 1)
    else:
        return_pixel[RED] = set_lowest_bit(cover_pixel[RED], 0)
    if secret_pixel[GREEN] >= COLOR_THRESHOLD:
        return_pixel[GREEN] = set_lowest_bit(cover_pixel[GREEN], 1)
    else:
        return_pixel[GREEN] = set_lowest_bit(cover_pixel[GREEN], 0)
    if secret_pixel[BLUE] >= COLOR_THRESHOLD:
        return_pixel[BLUE] = set_lowest_bit(cover_pixel[BLUE], 1)
    else:
        return_pixel[BLUE] = set_lowest_bit(cover_pixel[BLUE], 0)
    return return_pixel

# Extracts the RGB values for a secret pixel from the low bits
# of the given cover pixel
# Input is an array of RGB values for a pixel.
# Returns a tuple of RGB values for the decoded pixel

def decode_pixel(cover_pixel):
    secret_pixel = [0, 0, 0]
    red_bit = get_lowest_bit(cover_pixel[RED])
    green_bit = get_lowest_bit(cover_pixel[GREEN])
    blue_bit = get_lowest_bit(cover_pixel[BLUE])

    if red_bit == 1:
        secret_pixel[RED] = MAX_COLOR_VALUE
    else:
        secret_pixel[RED] = COLOR_THRESHOLD
    if green_bit == 1:
        secret_pixel[GREEN] = MAX_COLOR_VALUE
    else:
        secret_pixel[GREEN] = COLOR_THRESHOLD
    if blue_bit == 1:
        secret_pixel[BLUE] = MAX_COLOR_VALUE
    else:
        secret_pixel[BLUE] = COLOR_THRESHOLD
    return secret_pixel

# Returns true if the given value is even, false otherwise
def is_even(value):
    return value % 2 == 0

# Given a number, return the lowest bit in the binary representation
# of the number.
# Returns either a 0 or a 1

def get_lowest_bit(value):
    if is_even:
        return 0
    else:
        return 1

# Given a number, return a new number with the same underlying bits
# except the lowest bit is set to the given bit_value.

def set_lowest_bit(value, bit_value):
    if bit_value == 0:
        if is_even:
            return value
        else:
            return value -1
    else:
        if not is_even:
            return value
        else:
            return value +1

**# We don't have to change this code:**

def encrypt(cover, secret):
    # Loop over each pixel in the image
    for x in range(IMAGE_WIDTH):
        for y in range(IMAGE_HEIGHT):
            pass
            # Get the pixels at this location for both images
            cover_pixel = cover.get_pixel(x, y)
            secret_pixel = secret.get_pixel(x, y)

            # Modify the cover pixel to encode the secret pixel
            new_cover_color = encode_pixel(cover_pixel, secret_pixel)

            # Update this pixel in the cover image to have the
            # secret bit encoded
            cover.set_red(x, y, new_cover_color[RED])
            cover.set_green(x, y, new_cover_color[GREEN])
            cover.set_blue(x, y, new_cover_color[BLUE])
    print("Done encrypting")
    return cover

"""

 Decrypts a secret image from an encoded cover image.
 Returns an Image

"""
def decrypt(cover_image, result):
    # secret image will start off with the cover pixels
    # As we loop over the coverImage to discover the secret embedded image,
    # we will update secretImage pixel by pixel
    # Loop over each pixel in the image
    for x in range(IMAGE_WIDTH):
        for y in range(IMAGE_HEIGHT):
            #Get the current pixel of the cover image
            cover_pixel = cover_image.get_pixel(x, y)

            # Compute the secret_pixel from this cover pixel
            secret_pixel_color = decode_pixel(cover_pixel)
            result.set_red(x, y, secret_pixel_color[RED])
            result.set_green(x, y, secret_pixel_color[GREEN])
            result.set_blue(x, y, secret_pixel_color[BLUE])

    print("Done decrypting")
    return result

# Image width cannot be odd, it messes up the math of the encoding
if IMAGE_WIDTH % 2 == 1:
    IMAGE_WIDTH -= 1

#Set up original image
#Image(x, y, filename, width=50, height=50, rotation=0) // x,y top left corner
original = Image(ORIGINAL_URL, IMAGE_X, IMAGE_Y, IMAGE_WIDTH, IMAGE_HEIGHT)

# Set up secret image
secret = Image(SECRET_URL, IMAGE_X + original.get_width() + X_GAP, IMAGE_Y,
     IMAGE_WIDTH, IMAGE_HEIGHT)

# Set up the cover image
# (identical to original, but will be modified to encode the secret image)
cover_x = IMAGE_X + IMAGE_WIDTH
cover_y = IMAGE_Y + Y_GAP + IMAGE_HEIGHT
cover = Image(ORIGINAL_URL, cover_x, cover_y, IMAGE_WIDTH, IMAGE_HEIGHT)

# Set up result image
result = Image(ORIGINAL_URL, cover_x, cover_y + Y_GAP + IMAGE_HEIGHT,
                 IMAGE_WIDTH, IMAGE_HEIGHT)

# Add originals
add(original)
add(secret)

# Add cover and result
add(cover)
add(result)

# Add labels for each image
font = "11pt Arial"
def make_label(text, x, y, font):
    label = Text(text)
    label.set_position(x,y)
    label.set_font(font)
    add(label)

# Text(label, x=0, y=0, color=None,font=None) // x,y is
# original label
x_pos = original.get_x()
y_pos = original.get_y() - TEXT_Y_GAP
make_label("Original Cover Image", x_pos, y_pos, font)

#secret label
x_pos = secret.get_x()
y_pos = secret.get_y() - TEXT_Y_GAP
make_label("Original Secret Image", x_pos, y_pos, font)

# cover label
x_pos = IMAGE_X
y_pos = cover.get_y() - TEXT_Y_GAP
make_label("Cover Image with Secret Image encoded inside", x_pos, y_pos, font)

# result label
x_pos = IMAGE_X
y_pos = cover.get_y() + IMAGE_HEIGHT + Y_GAP - TEXT_Y_GAP
make_label("Resulting Secret Image decoded from Cover Image", x_pos, y_pos, font)

# Encrypt and decrypt the image
# Displays the changed images
def run_encryption():
    encrypt(cover, secret)
    print("Decrypting .........")
    timer.set_timeout(lambda: decrypt(cover, result), IMAGE_LOAD_WAIT_TIME)

# Wait for images to load before encrypting and decrypting
print("Encrypting ............")
timer.set_timeout(run_encryption, IMAGE_LOAD_WAIT_TIME)
</code>```

How do I have to change the code? I only get a grey picture on the decoded picture place.

Title: Secret Imagage Steganography - python

Body:
I have been stuck on this program for a while and I am completely lost as to what is wrong and what I need to fix. I am trying to use steganography to encrypt a secret image inside of a cover image, and then decrypt the secret image. I am given part of the code and I have to implement the encode_pixel and decode_pixel functions, as well as the "helper functions".

When I run the program, the resulting image is completely grey instead of the secret image. I do not know where my error is, and if it is in the encode or decode function, or if it is in the helper functions.

These are the functions that I have implemented:

ORIGINAL_URL = "https://codehs.com/uploads/c709d869e62686611c1ac849367b3245"

SECRET_URL = "https://codehs.com/uploads/e07cd01271cac589cc9ef1bf012c6a0c"

IMAGE_LOAD_WAIT_TIME = 1000

# Constants for pixel indices
RED = 0
GREEN = 1
BLUE = 2

# Constants for colors
MAX_COLOR_VALUE = 255
MIN_COLOR_VALUE = 0
COLOR_THRESHOLD = 128

# Constants for spacing
X_GAP = 100
Y_GAP = 50
TEXT_Y_GAP = 4
IMAGE_WIDTH = 100
IMAGE_HEIGHT = 100
IMAGE_X = 25
IMAGE_Y = 25

# Set Canvas size
set_size(400, 480)

# Encodes the given secret pixel into the low bits of the
# RGB values of the given cover pixel
# Returns the modified cover pixel

def encode_pixel(cover_pixel, secret_pixel):
    # Implement this function
    # return a temporary value.  Change this!!
    return_pixel = [0,0,0]
    if secret_pixel[RED]>= COLOR_THRESHOLD:
        return_pixel[RED] = set_lowest_bit(cover_pixel[RED], 1)
    else:
        return_pixel[RED] = set_lowest_bit(cover_pixel[RED], 0)
    if secret_pixel[GREEN] >= COLOR_THRESHOLD:
        return_pixel[GREEN] = set_lowest_bit(cover_pixel[GREEN], 1)
    else:
        return_pixel[GREEN] = set_lowest_bit(cover_pixel[GREEN], 0)
    if secret_pixel[BLUE] >= COLOR_THRESHOLD:
        return_pixel[BLUE] = set_lowest_bit(cover_pixel[BLUE], 1)
    else:
        return_pixel[BLUE] = set_lowest_bit(cover_pixel[BLUE], 0)
    return return_pixel

# Extracts the RGB values for a secret pixel from the low bits
# of the given cover pixel
# Input is an array of RGB values for a pixel.
# Returns a tuple of RGB values for the decoded pixel

def decode_pixel(cover_pixel):
    secret_pixel = [0, 0, 0]
    red_bit = get_lowest_bit(cover_pixel[RED])
    green_bit = get_lowest_bit(cover_pixel[GREEN])
    blue_bit = get_lowest_bit(cover_pixel[BLUE])

    if red_bit == 1:
        secret_pixel[RED] = MAX_COLOR_VALUE
    else:
        secret_pixel[RED] = COLOR_THRESHOLD
    if green_bit == 1:
        secret_pixel[GREEN] = MAX_COLOR_VALUE
    else:
        secret_pixel[GREEN] = COLOR_THRESHOLD
    if blue_bit == 1:
        secret_pixel[BLUE] = MAX_COLOR_VALUE
    else:
        secret_pixel[BLUE] = COLOR_THRESHOLD
    return secret_pixel

# Returns true if the given value is even, false otherwise
def is_even(value):
    return value % 2 == 0

# Given a number, return the lowest bit in the binary representation
# of the number.
# Returns either a 0 or a 1

def get_lowest_bit(value):
    if is_even:
        return 0
    else:
        return 1

# Given a number, return a new number with the same underlying bits
# except the lowest bit is set to the given bit_value.

def set_lowest_bit(value, bit_value):
    if bit_value == 0:
        if is_even:
            return value
        else:
            return value -1
    else:
        if not is_even:
            return value
        else:
            return value +1

**# We don't have to change this code:**

def encrypt(cover, secret):
    # Loop over each pixel in the image
    for x in range(IMAGE_WIDTH):
        for y in range(IMAGE_HEIGHT):
            pass
            # Get the pixels at this location for both images
            cover_pixel = cover.get_pixel(x, y)
            secret_pixel = secret.get_pixel(x, y)

            # Modify the cover pixel to encode the secret pixel
            new_cover_color = encode_pixel(cover_pixel, secret_pixel)

            # Update this pixel in the cover image to have the
            # secret bit encoded
            cover.set_red(x, y, new_cover_color[RED])
            cover.set_green(x, y, new_cover_color[GREEN])
            cover.set_blue(x, y, new_cover_color[BLUE])
    print("Done encrypting")
    return cover

"""

 Decrypts a secret image from an encoded cover image.
 Returns an Image

"""
def decrypt(cover_image, result):
    # secret image will start off with the cover pixels
    # As we loop over the coverImage to discover the secret embedded image,
    # we will update secretImage pixel by pixel
    # Loop over each pixel in the image
    for x in range(IMAGE_WIDTH):
        for y in range(IMAGE_HEIGHT):
            #Get the current pixel of the cover image
            cover_pixel = cover_image.get_pixel(x, y)

            # Compute the secret_pixel from this cover pixel
            secret_pixel_color = decode_pixel(cover_pixel)
            result.set_red(x, y, secret_pixel_color[RED])
            result.set_green(x, y, secret_pixel_color[GREEN])
            result.set_blue(x, y, secret_pixel_color[BLUE])

    print("Done decrypting")
    return result

# Image width cannot be odd, it messes up the math of the encoding
if IMAGE_WIDTH % 2 == 1:
    IMAGE_WIDTH -= 1

#Set up original image
#Image(x, y, filename, width=50, height=50, rotation=0) // x,y top left corner
original = Image(ORIGINAL_URL, IMAGE_X, IMAGE_Y, IMAGE_WIDTH, IMAGE_HEIGHT)

# Set up secret image
secret = Image(SECRET_URL, IMAGE_X + original.get_width() + X_GAP, IMAGE_Y,
     IMAGE_WIDTH, IMAGE_HEIGHT)

# Set up the cover image
# (identical to original, but will be modified to encode the secret image)
cover_x = IMAGE_X + IMAGE_WIDTH
cover_y = IMAGE_Y + Y_GAP + IMAGE_HEIGHT
cover = Image(ORIGINAL_URL, cover_x, cover_y, IMAGE_WIDTH, IMAGE_HEIGHT)

# Set up result image
result = Image(ORIGINAL_URL, cover_x, cover_y + Y_GAP + IMAGE_HEIGHT,
                 IMAGE_WIDTH, IMAGE_HEIGHT)

# Add originals
add(original)
add(secret)

# Add cover and result
add(cover)
add(result)

# Add labels for each image
font = "11pt Arial"
def make_label(text, x, y, font):
    label = Text(text)
    label.set_position(x,y)
    label.set_font(font)
    add(label)

# Text(label, x=0, y=0, color=None,font=None) // x,y is
# original label
x_pos = original.get_x()
y_pos = original.get_y() - TEXT_Y_GAP
make_label("Original Cover Image", x_pos, y_pos, font)

#secret label
x_pos = secret.get_x()
y_pos = secret.get_y() - TEXT_Y_GAP
make_label("Original Secret Image", x_pos, y_pos, font)

# cover label
x_pos = IMAGE_X
y_pos = cover.get_y() - TEXT_Y_GAP
make_label("Cover Image with Secret Image encoded inside", x_pos, y_pos, font)

# result label
x_pos = IMAGE_X
y_pos = cover.get_y() + IMAGE_HEIGHT + Y_GAP - TEXT_Y_GAP
make_label("Resulting Secret Image decoded from Cover Image", x_pos, y_pos, font)

# Encrypt and decrypt the image
# Displays the changed images
def run_encryption():
    encrypt(cover, secret)
    print("Decrypting .........")
    timer.set_timeout(lambda: decrypt(cover, result), IMAGE_LOAD_WAIT_TIME)

# Wait for images to load before encrypting and decrypting
print("Encrypting ............")
timer.set_timeout(run_encryption, IMAGE_LOAD_WAIT_TIME)

How do I have to change the code? I only get a grey picture on the decoded picture place.


问:
Camel: return result from rest call
I have two routes as follows:

```<code>from("rest:get:hello/{user}")
   .transform().simple("Hello ${header.user}");

from("rest:get:bye")
    .to("http://localhost:8080/hello/quitter?bridgeEndpoint=true");
</code>```

The first route works great. And returns "Hello friend" when invoked with /hello/friend.
I want the second call to basically call the first API with "quitter" as path param.
However, when i make the second call nothing is returned. There is no error and there is no error message returned.

What is the best way to make the second invocation? In fact, my generation question is how do I get the a rest route to call another rest endpoint and return results.

Title: Camel: return result from rest call

Body:
I have two routes as follows:

from("rest:get:hello/{user}")
   .transform().simple("Hello ${header.user}");

from("rest:get:bye")
    .to("http://localhost:8080/hello/quitter?bridgeEndpoint=true");

The first route works great. And returns "Hello friend" when invoked with /hello/friend.
I want the second call to basically call the first API with "quitter" as path param.
However, when i make the second call nothing is returned. There is no error and there is no error message returned.

What is the best way to make the second invocation? In fact, my generation question is how do I get the a rest route to call another rest endpoint and return results.


问:
Why the intent is not working in android?
I have this intent
`

```<code>intent://mojapp.in/favicon.ico/#Intent;scheme=mojapp;package=in.mohalla.video;S.browser_fallback_url=https://play.google.com/store/apps/details?id=in.mohalla.video&referrer=utm_source%3DPWA%26utm_medium%3DPWA%26utm_campaign%3DPWA;end
</code>```

`
In case of app installed It's working fine.
If not then it's not redirecting to play-store.

Getting this

```<code>Navigation is unreachable: intent://mojapp.in/moj-spot/faqs/#Intentscheme=mojapppackage=in.mohalla.videoS.browser_fallback_url=https3A2F2Fplay.google.com2Fstore2Fapps2Fdetails3Fid3Din.mohalla.video26referrer3Dutm_source253DPWA2526utm_medium253DPWA2526utm_campaign253DPWAend
</code>```

Body:
I have this intent
`

intent://mojapp.in/favicon.ico/#Intent;scheme=mojapp;package=in.mohalla.video;S.browser_fallback_url=https://play.google.com/store/apps/details?id=in.mohalla.video&referrer=utm_source%3DPWA%26utm_medium%3DPWA%26utm_campaign%3DPWA;end

`
In case of app installed It's working fine.
If not then it's not redirecting to play-store.

Getting this

Navigation is unreachable: intent://mojapp.in/moj-spot/faqs/#Intentscheme=mojapppackage=in.mohalla.videoS.browser_fallback_url=https3A2F2Fplay.google.com2Fstore2Fapps2Fdetails3Fid3Din.mohalla.video26referrer3Dutm_source253DPWA2526utm_medium253DPWA2526utm_campaign253DPWAend


问:
Load SSAS Tabular from Multiple Sources
I have many customer databases for our product that have the same schema. Is there a way to loop through these databases and load a SSAS Tabular cube with data from all of them?

Hopefully this can be done.

Title: Load SSAS Tabular from Multiple Sources


问:
Accounts returned from API endpoint are different than the Xero GUI while creating invoice
i am working on developer API's in Xero, but i got almost 8 more items in "https://api.xero.com/api.xro/2.0/Accounts" endpoint than the Xero GUI dropdown. Xero is not adding system accounts in dropdown except (960, 820,840,860, and 499). how can I achieve same result like Xero GUI dropdown.

called "https://api.xero.com/api.xro/2.0/Accounts" endpoint but got 8 more items than the Xero GUI dropdown.


问:
how to send notification email from composer using sendgrid
I'm trying to send notification email from cloud composer, thus, I followed the officiel documentation, here is what I done until now :

I created sendgrid account

I defined a sender (a gmail account), that I verified

however, I run the test nothing happened.

Is there something that I'm missing ?


问:
How to sync or copy only modified and newly added files to GCS bucket using gsutil rsync from local folder?
I am trying to copy or sync newly added or modified files only from local folder to GCS bucket using rsync, It looks like rsync is copying all the files again to gcs buckets instead of copying updated or newly added files.

The command I am using right now :
gsutil -m rsync -r -d ./data/ gs://bucket/data/

Any help would be appreciated.


问:
How to edit css files of SweetAlert 2
Hello I am using sweetalert 2 to show some alerts to a project.

It supposed to look like this

but it does like this

And it because of this style. The style is set to auto. When i uncheck the css value on Inspect/Styles the swal works fine.

```<code>body.swal2-height-auto {
    height: auto !important;
}
</code>```

I tried to edit this line on the plugins css file sweetalert2.css to set the height to 100%

```<code>body.swal2-height-auto {
  height: 100% !important;
}
</code>```

or add a showClass on ts function

```<code>const steps = ['1', '2', '3']
        const swalQueueStep = Swal.mixin({
          customClass: {
            container: 'container--modifier',
          },
          confirmButtonText: 'Forward',
          cancelButtonText: 'Back',
          progressSteps: steps,
          input: 'text',
          reverseButtons: true,
          validationMessage: 'This field is required'
        })
</code>```

global.scss

```<code>.container--modifier{
    height:100%!important
  }
</code>```

i saved the file but changes are not commited. Any help?

Title: How to edit css files of SweetAlert 2

Body:
Hello I am using sweetalert 2 to show some alerts to a project.

It supposed to look like this

but it does like this

And it because of this style. The style is set to auto. When i uncheck the css value on Inspect/Styles the swal works fine.

body.swal2-height-auto {
    height: auto !important;
}

I tried to edit this line on the plugins css file sweetalert2.css to set the height to 100%

body.swal2-height-auto {
  height: 100% !important;
}

or add a showClass on ts function

const steps = ['1', '2', '3']
        const swalQueueStep = Swal.mixin({
          customClass: {
            container: 'container--modifier',
          },
          confirmButtonText: 'Forward',
          cancelButtonText: 'Back',
          progressSteps: steps,
          input: 'text',
          reverseButtons: true,
          validationMessage: 'This field is required'
        })

global.scss

.container--modifier{
    height:100%!important
  }

i saved the file but changes are not commited. Any help?


问:
BigQuery - how to decrease slot time of Coalesce execution step?
I have a pretty complex query, with about 70 execution steps. The query was somewhat optimized for performance, so most of the steps in the execution plan run pretty fast - except Coalesce steps, which take about 10 to 100 times more slot time, compared to the others. As far as I understand, it prepares data for the following Join step, but why does it take so long even if actual nuber of records processed by this step is low? The most extreme case I saw looks like this (ZERO records processed by this step, but still takes 8 seconds! ):

```<code>S46: Coalesce
Slot time: 8223 ms
Duration: 92 ms
Bytes Shuffled: 0 B
</code>```

I wasn't able to find any hints regarding this "Coalesce" step and ways to optimize it in Google documentation, so perhaps you can give me some advice about it or point to actual documentation that explains it.

Body:
I have a pretty complex query, with about 70 execution steps. The query was somewhat optimized for performance, so most of the steps in the execution plan run pretty fast - except Coalesce steps, which take about 10 to 100 times more slot time, compared to the others. As far as I understand, it prepares data for the following Join step, but why does it take so long even if actual nuber of records processed by this step is low? The most extreme case I saw looks like this (ZERO records processed by this step, but still takes 8 seconds! ):

S46: Coalesce
Slot time: 8223 ms
Duration: 92 ms
Bytes Shuffled: 0 B

I wasn't able to find any hints regarding this "Coalesce" step and ways to optimize it in Google documentation, so perhaps you can give me some advice about it or point to actual documentation that explains it.


问:
Docker + Sveltekit, cant access localhost:3000
After building I start the image and see in the terminal:

```<code>*Executing task: docker run --rm -it -p 3000:3000/tcp bamdock:latest
Listening on 0.0.0.0:3000*
</code>```

However when trying to reach http://localhost:3000/ in browser I see:

```<code>*The connection was reset*

*The connection to the server was reset while the page was loading.
    The site could be temporarily unavailable or too busy. Try again in a few moments.
    If you are unable to load any pages, check your computer’s network connection.
    If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the web.*
</code>```

This is my Dockerfile:

```<code>FROM node:19 as builder
RUN npm install -g pnpm

WORKDIR /usr/src/app

COPY package*.json ./

RUN pnpm install

COPY prisma ./prisma/

COPY .env ./

RUN npx prisma generate

COPY . .

RUN pnpm run build

FROM node:19-alpine3.16

WORKDIR /app

COPY --from=builder /usr/src/app/build .
COPY --from=builder /usr/src/app/package.json .
COPY --from=builder /usr/src/app/node_modules ./node_modules

EXPOSE 3000

CMD ["node", "index.js"]
</code>```

Any ideas what I'm missing?

My first time trying to get Docker working ...

Body:
After building I start the image and see in the terminal:

*Executing task: docker run --rm -it -p 3000:3000/tcp bamdock:latest
Listening on 0.0.0.0:3000*

However when trying to reach http://localhost:3000/ in browser I see:

*The connection was reset*

*The connection to the server was reset while the page was loading.
    The site could be temporarily unavailable or too busy. Try again in a few moments.
    If you are unable to load any pages, check your computer’s network connection.
    If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the web.*

This is my Dockerfile:

FROM node:19 as builder
RUN npm install -g pnpm

WORKDIR /usr/src/app

COPY package*.json ./

RUN pnpm install

COPY prisma ./prisma/

COPY .env ./

RUN npx prisma generate

COPY . .

RUN pnpm run build

FROM node:19-alpine3.16

WORKDIR /app

COPY --from=builder /usr/src/app/build .
COPY --from=builder /usr/src/app/package.json .
COPY --from=builder /usr/src/app/node_modules ./node_modules

EXPOSE 3000

CMD ["node", "index.js"]

Any ideas what I'm missing?

My first time trying to get Docker working ...


问:
Apache2 cannot find modules in user site-packages
When I run pip3 install ... the packages are installed in ./.local/lib/python3.7/site-packages however when running my app Apache cannot import these modules.  It can only import base python packages or if the packages are inside the /usr/lib/python3.7 directory.  Not sure what do here.  Did a lot of complicated SO and Google searching on permission and www-data user but everything fails.  This is a GCP LAMPs distribution.

I tried:

setting PYTHONPATH in ~/.bashrc

adding to /etc/apache2/sites-enabled/lamp-server.conf

```<code><VirtualHost *:80>
  ServerAdmin webmaster@localhost
  ServerName myproject
  WSGIDaemonProcess myproject python-path=./.local/lib:./.local/lib/python3.7/site-packages/
</code>```

Adding to path in cgi script

```<code>import cgi, cgitb
import sys
import site
import cgitb.enable()
sys.path.append(['./.local/lib/python3.7','./.local/lib/python3.7/site-packages'])

try:
   import rdkit
   import chembl_webresource_client
   # import sklearn
except ImportError as error:
   # Output expected ImportErrors.
   print(error)
</code>```

This give me:
No module named 'chembl_webresource_client' because I copied the rdkit folders to /usr/lib/python3.7 folder manually

Body:
When I run pip3 install ... the packages are installed in ./.local/lib/python3.7/site-packages however when running my app Apache cannot import these modules.  It can only import base python packages or if the packages are inside the /usr/lib/python3.7 directory.  Not sure what do here.  Did a lot of complicated SO and Google searching on permission and www-data user but everything fails.  This is a GCP LAMPs distribution.

I tried:

setting PYTHONPATH in ~/.bashrc

adding to /etc/apache2/sites-enabled/lamp-server.conf

<VirtualHost *:80>
  ServerAdmin webmaster@localhost
  ServerName myproject
  WSGIDaemonProcess myproject python-path=./.local/lib:./.local/lib/python3.7/site-packages/

Adding to path in cgi script

import cgi, cgitb
import sys
import site
import cgitb.enable()
sys.path.append(['./.local/lib/python3.7','./.local/lib/python3.7/site-packages'])

try:
   import rdkit
   import chembl_webresource_client
   # import sklearn
except ImportError as error:
   # Output expected ImportErrors.
   print(error)

This give me:
No module named 'chembl_webresource_client' because I copied the rdkit folders to /usr/lib/python3.7 folder manually


问:
Blit is not detecting my Player classes self.pos
My code:

```<code>import pgzrun, pgzero, pygame, math, time, random, os
from pgzero.builtins import Actor, animate, keyboard
screen = pgzero.screen.Screen

# screen
WIDTH = 800
HEIGHT = 600

pygame.init()
pygame.mouse.set_visible(False)
os.chdir("c:/Users/carter.breshears/Documents/CSPVSC/Final/Images")
font = pygame.font.Font("Minecraft.ttf", 30)

# player images
playerIdle = pygame.image.load("playerIdle.png")
playerWalkImages = [pygame.image.load("playerRun1.png"), pygame.image.load("playerRun2.png"), pygame.image.load("playerRun3.png"), pygame.image.load("playerRun4.png")]

#variables
    # gameloop
gameover = False

# classes
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.animationCount = 0
        self.movingRight = False
        self.movingLeft = False
        self.movingUp = False
        self.movingDown = False
    def main(self, screen):
        if self.animationCount + 1 >= 24:
            self.animationCount = 0
        self.animationCount += 1

        if self.movingRight or self.movingUp or self.movingDown:
            screen.blit(pygame.transform.scale(playerWalkImages[self.animationCount//6], (40,74)), (self.x, self.y))
        elif self.movingLeft:
            screen.blit(pygame.transform.scale(pygame.transform.flip(playerWalkImages[self.animationCount//6], True, False), (40,74)), (self.x, self.y))
        else:
            screen.blit(pygame.transform.scale(playerIdle, (40,74)), (self.x, self.y)) ##### This line!
        self.movingRight = False
        self.movingLeft = False
        self.movingUp = False
        self.movingDown = False

class PlayerBullet:
    def __init__(self, x, y, mouseX, mouseY):
        self.x = x
        self.y = y
        self.mouseX = mouseX
        self.mouseY = mouseY
        speed = 6
        self.angle = math.atan2(y - mouseY, x - mouseX)
        self.x_vel = math.cos(self.angle) * speed
        self.y_vel = math.sin(self.angle) * speed
    def main(self, screen):
        self.x -= int(self.x_vel)
        self.y -= int(self.y_vel)
        print("bang")

        pygame.draw.circle(screen, "yellow", (self.x+16, self.y+16), 5)

class InvaderEnemy:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.greenAnimationImages = [pygame.image.load("virus g.png"), pygame.image.load("virus g2.png")]
        self.yellowAnimationImages = [pygame.image.load("virus y.png"), pygame.image.load("virus y2.png")]
        self.blueAnimationImages = [pygame.image.load("virus b.png"), pygame.image.load("virus b2.png")]
        self.redAnimationImages = [pygame.image.load("virus r.png"), pygame.image.load("virus r2.png")]
        self.animationCount = 0
        self.velocity = 1
        self.lerpFactor = 0.05

    def main(self, screen):
        if self.animationCount + 1 == 8:
            self.animationCount = 0
        self.animationCount += 1

        spawnPos = (random.randint(-1000, 1000), random.randint(-1000, 1000))

        targetVector = pygame.math.Vector2(player.x, player.y)
        enemyVector = pygame.math.Vector2(spawnPos.x, spawnPos.y)
        newEnemyVector = pygame.math.Vector2(spawnPos.x, spawnPos.y)

        distance = enemyVector.distance_to(targetVector)
        minDistance = 25
        maxDistance = 1000

        if distance > minDistance:
            directionVector = (targetVector - enemyVector)/2
            self.minStep = max(0, distance - maxDistance)
            self.maxStep = distance - minDistance
            self.stepDistance = self.minStep + (self.maxStep - self.minStep) * self.lerpFactor
            newEnemyVector = enemyVector + directionVector * self.stepDistance

        return(newEnemyVector.x, newEnemyVector.y)

# player
player = Player(400,300)
displayScroll = [0,0]
# shooting
playerBullets = []
# invader
invaders = []
invaderEnemy = InvaderEnemy(100,100)
invaderSpawnRate = 1

# functions
def update():
    # movement
    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        displayScroll[0] -= 2
        player.movingLeft = True
        for bullet in playerBullets:
            bullet.x += 2

    if keys[pygame.K_d]:
        displayScroll[0] += 2
        player.movingRight = True
        for bullet in playerBullets:
            bullet.x -= 2

    if keys[pygame.K_w]:
        displayScroll[1] -= 2
        player.movingUp = True
        for bullet in playerBullets:
            bullet.y += 2

    if keys[pygame.K_s]:
        displayScroll[1] += 2
        player.movingDown = True
        for bullet in playerBullets:
            bullet.y -= 2

    player.main(screen)

    # shooting
    mouseX, mouseY = pygame.mouse.get_pos()

    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                playerBullets.append(PlayerBullet(player.x, player.y, mouseX, mouseY))

    for bullet in playerBullets:
        PlayerBullet.main(screen)

    #enemies
    global spawnPos
    if time.perf_counter() - invaderSpawnRate > 1:
        invaders.append(InvaderEnemy(spawnPos.x, spawnPos.y))
    for invader in invaders:
        InvaderEnemy.main(screen)

# run
pgzrun.go()
</code>```

I've tried everything I know of, Im new to this. I know that it worked before because I tested this on my home computer but whenever I downloaded the file on my school computer it stopped working so something must have changed between python versions.

Body:
My code:

import pgzrun, pgzero, pygame, math, time, random, os
from pgzero.builtins import Actor, animate, keyboard
screen = pgzero.screen.Screen

# screen
WIDTH = 800
HEIGHT = 600

pygame.init()
pygame.mouse.set_visible(False)
os.chdir("c:/Users/carter.breshears/Documents/CSPVSC/Final/Images")
font = pygame.font.Font("Minecraft.ttf", 30)

# player images
playerIdle = pygame.image.load("playerIdle.png")
playerWalkImages = [pygame.image.load("playerRun1.png"), pygame.image.load("playerRun2.png"), pygame.image.load("playerRun3.png"), pygame.image.load("playerRun4.png")]

#variables
    # gameloop
gameover = False

# classes
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.animationCount = 0
        self.movingRight = False
        self.movingLeft = False
        self.movingUp = False
        self.movingDown = False
    def main(self, screen):
        if self.animationCount + 1 >= 24:
            self.animationCount = 0
        self.animationCount += 1

        if self.movingRight or self.movingUp or self.movingDown:
            screen.blit(pygame.transform.scale(playerWalkImages[self.animationCount//6], (40,74)), (self.x, self.y))
        elif self.movingLeft:
            screen.blit(pygame.transform.scale(pygame.transform.flip(playerWalkImages[self.animationCount//6], True, False), (40,74)), (self.x, self.y))
        else:
            screen.blit(pygame.transform.scale(playerIdle, (40,74)), (self.x, self.y)) ##### This line!
        self.movingRight = False
        self.movingLeft = False
        self.movingUp = False
        self.movingDown = False

class PlayerBullet:
    def __init__(self, x, y, mouseX, mouseY):
        self.x = x
        self.y = y
        self.mouseX = mouseX
        self.mouseY = mouseY
        speed = 6
        self.angle = math.atan2(y - mouseY, x - mouseX)
        self.x_vel = math.cos(self.angle) * speed
        self.y_vel = math.sin(self.angle) * speed
    def main(self, screen):
        self.x -= int(self.x_vel)
        self.y -= int(self.y_vel)
        print("bang")

        pygame.draw.circle(screen, "yellow", (self.x+16, self.y+16), 5)

class InvaderEnemy:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.greenAnimationImages = [pygame.image.load("virus g.png"), pygame.image.load("virus g2.png")]
        self.yellowAnimationImages = [pygame.image.load("virus y.png"), pygame.image.load("virus y2.png")]
        self.blueAnimationImages = [pygame.image.load("virus b.png"), pygame.image.load("virus b2.png")]
        self.redAnimationImages = [pygame.image.load("virus r.png"), pygame.image.load("virus r2.png")]
        self.animationCount = 0
        self.velocity = 1
        self.lerpFactor = 0.05

    def main(self, screen):
        if self.animationCount + 1 == 8:
            self.animationCount = 0
        self.animationCount += 1

        spawnPos = (random.randint(-1000, 1000), random.randint(-1000, 1000))

        targetVector = pygame.math.Vector2(player.x, player.y)
        enemyVector = pygame.math.Vector2(spawnPos.x, spawnPos.y)
        newEnemyVector = pygame.math.Vector2(spawnPos.x, spawnPos.y)

        distance = enemyVector.distance_to(targetVector)
        minDistance = 25
        maxDistance = 1000

        if distance > minDistance:
            directionVector = (targetVector - enemyVector)/2
            self.minStep = max(0, distance - maxDistance)
            self.maxStep = distance - minDistance
            self.stepDistance = self.minStep + (self.maxStep - self.minStep) * self.lerpFactor
            newEnemyVector = enemyVector + directionVector * self.stepDistance

        return(newEnemyVector.x, newEnemyVector.y)

# player
player = Player(400,300)
displayScroll = [0,0]
# shooting
playerBullets = []
# invader
invaders = []
invaderEnemy = InvaderEnemy(100,100)
invaderSpawnRate = 1

# functions
def update():
    # movement
    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        displayScroll[0] -= 2
        player.movingLeft = True
        for bullet in playerBullets:
            bullet.x += 2

    if keys[pygame.K_d]:
        displayScroll[0] += 2
        player.movingRight = True
        for bullet in playerBullets:
            bullet.x -= 2

    if keys[pygame.K_w]:
        displayScroll[1] -= 2
        player.movingUp = True
        for bullet in playerBullets:
            bullet.y += 2

    if keys[pygame.K_s]:
        displayScroll[1] += 2
        player.movingDown = True
        for bullet in playerBullets:
            bullet.y -= 2

    player.main(screen)

    # shooting
    mouseX, mouseY = pygame.mouse.get_pos()

    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                playerBullets.append(PlayerBullet(player.x, player.y, mouseX, mouseY))

    for bullet in playerBullets:
        PlayerBullet.main(screen)

    #enemies
    global spawnPos
    if time.perf_counter() - invaderSpawnRate > 1:
        invaders.append(InvaderEnemy(spawnPos.x, spawnPos.y))
    for invader in invaders:
        InvaderEnemy.main(screen)

# run
pgzrun.go()

I've tried everything I know of, Im new to this. I know that it worked before because I tested this on my home computer but whenever I downloaded the file on my school computer it stopped working so something must have changed between python versions.


问:
Can't install pyenchant
I need installing pyenchant v1.6.7 on MacBook with Apple Silicon (M1 Pro) for Python 2.7.18.

This package is a wrapper for C-library enchant, so it requires to the enchant was installed firstly. Well, I've installed the enchant by: brew install enchant.

However, when I try to install pyenchant using PIP I got the next error:

```<code>         cwd: /private/var/folders/8t/b2kn5tm162s614gvsfrdcbhm0000gn/T/pip-install-8FO32O/pyenchant/
    Complete output (9 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/8t/b2kn5tm162s614gvsfrdcbhm0000gn/T/pip-install-8FO32O/pyenchant/setup.py", line 210, in <module>
        import enchant
      File "enchant/__init__.py", line 92, in <module>
        from enchant import _enchant as _e
      File "enchant/_enchant.py", line 145, in <module>
        raise ImportError(msg)
    ImportError: The 'enchant' C library was not found. Please install it via your OS package manager, or use a pre-built binary wheel from PyPI.
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
</code>```

Also I have tried to specify LDFLAGS and CFLAGS:

```<code>LDFLAGS='-L/opt/homebrew/Cellar/enchant/2.3.3/lib' CFLAGS="-I/opt/homebrew/Cellar/enchant/2.3.3/include" ~/.pyenv/versions/2.7.18/bin/pip install --no-cache-dir pyenchant==1.6.7
</code>```

But it doesn't work, I still get the same error.

How to specify the enchant library for the pyenchant module?

Title: Can't install pyenchant

Body:
I need installing pyenchant v1.6.7 on MacBook with Apple Silicon (M1 Pro) for Python 2.7.18.

This package is a wrapper for C-library enchant, so it requires to the enchant was installed firstly. Well, I've installed the enchant by: brew install enchant.

However, when I try to install pyenchant using PIP I got the next error:

         cwd: /private/var/folders/8t/b2kn5tm162s614gvsfrdcbhm0000gn/T/pip-install-8FO32O/pyenchant/
    Complete output (9 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/8t/b2kn5tm162s614gvsfrdcbhm0000gn/T/pip-install-8FO32O/pyenchant/setup.py", line 210, in <module>
        import enchant
      File "enchant/__init__.py", line 92, in <module>
        from enchant import _enchant as _e
      File "enchant/_enchant.py", line 145, in <module>
        raise ImportError(msg)
    ImportError: The 'enchant' C library was not found. Please install it via your OS package manager, or use a pre-built binary wheel from PyPI.
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Also I have tried to specify LDFLAGS and CFLAGS:

LDFLAGS='-L/opt/homebrew/Cellar/enchant/2.3.3/lib' CFLAGS="-I/opt/homebrew/Cellar/enchant/2.3.3/include" ~/.pyenv/versions/2.7.18/bin/pip install --no-cache-dir pyenchant==1.6.7

But it doesn't work, I still get the same error.

How to specify the enchant library for the pyenchant module?


问:
Delphi DBEdit OnExit primary key validation
I am using Delphi 10.4, when connecting a DBEdit to a table from a database which contains a primary key (eg: student_num). What I want to do is to perform a search on the key the user types in that DBEdit when the user exits or moves to the next DBEdit and not after filling all the fields then hitting a submit button.

Can someone help me with that?
Much gratitude.

I used DBEditChange, but that didn't work as expected. The code I'm trying to write should show a message in case the entered key already exists in the database, immediately after exiting DBEdit field.


问:
Keras Embedding values assigned to None
I am currently following a model with requires me to do the following on my embedding layer for my model:

```<code>Embedding Layer Input: (None,100) Output: (None,200,50)
</code>```

However, from the documentation I have read on keras' embedding layer, it only takes integers. How can I possibly recreate this model?

Title: Keras Embedding values assigned to None

Body:
I am currently following a model with requires me to do the following on my embedding layer for my model:

Embedding Layer Input: (None,100) Output: (None,200,50)

However, from the documentation I have read on keras' embedding layer, it only takes integers. How can I possibly recreate this model?


问:
Is there any way to find from a binary file means from assembly code that whether in a function, an array parameter has been passed or not?
I am doing binary ananlysis and I hav many objectives like to know the types of function paramter whether its an array or pointer or char or int type. Also, my objctive is to find whether an array has been passed as a function parameter.
Here is my C program.

```<code>#include<stdio.h>
#include<string.h>

void concat(char s1[], char s2[]) {
    int i, j;
    i = strlen(s1);
    for (j = 0; s2[j] != '\0'; i++, j++) {
        s1[i] = s2[j];
    }
    s1[i] = '\0';
}
int main() {
    char a[] = "Hello";
    char b[] = "World";
    concat(a, b);
    return (0);
}

</code>```

Here is my assembly code

```<code>0000000000001169 <concat>:
    1169:   endbr64
    116d:   pushq  %rbp
    116e:   movq   %rsp,%rbp
    1171:   subq   $0x20,%rsp
    1175:   movq   %rdi,-0x18(%rbp)
    1179:   movq   %rsi,-0x20(%rbp)
    117d:   movq   -0x18(%rbp),%rax
    1181:   movq   %rax,%rdi
    1184:   callq  1060 <strlen@plt> //since calls destination is eax //
    1189:   movl   %eax,-0x8(%rbp)
    118c:   movl   $0x0,-0x4(%rbp) //local argument
    1193:   jmp    11bc <concat+0x53>
    1195:   movl   -0x4(%rbp),%eax
    1198:   movslq %eax,%rdx //hint that 32bit source moved to 64 bit sign extended
    119b:   movq   -0x20(%rbp),%rax
    119f:   addq   %rdx,%rax
    11a2:   movl   -0x8(%rbp),%edx
    11a5:   movslq %edx,%rcx
    11a8:   movq   -0x18(%rbp),%rdx
    11ac:   addq   %rcx,%rdx
    11af:   movzbl (%rax),%eax
    11b2:   movb   %al,(%rdx)
    11b4:   addl   $0x1,-0x8(%rbp)
    11b8:   addl   $0x1,-0x4(%rbp)
    11bc:   movl   -0x4(%rbp),%eax
    11bf:   movslq %eax,%rdx
    11c2:   movq   -0x20(%rbp),%rax
    11c6:   addq   %rdx,%rax
    11c9:   movzbl (%rax),%eax
    11cc:   testb  %al,%al
    11ce:   jne    1195 <concat+0x2c>
    11d0:   movl   -0x8(%rbp),%eax
    11d3:   movslq %eax,%rdx
    11d6:   movq   -0x18(%rbp),%rax
    11da:   addq   %rdx,%rax
    11dd:   movb   $0x0,(%rax)
    11e0:   nop
    11e1:   leaveq
    11e2:   retq
</code>```

From the assembly code how can I tell whether an array has been passed or not in a function?

I am trying to understand the reverse enginnering tools.

Body:
I am doing binary ananlysis and I hav many objectives like to know the types of function paramter whether its an array or pointer or char or int type. Also, my objctive is to find whether an array has been passed as a function parameter.
Here is my C program.

#include<stdio.h>
#include<string.h>

void concat(char s1[], char s2[]) {
    int i, j;
    i = strlen(s1);
    for (j = 0; s2[j] != '\0'; i++, j++) {
        s1[i] = s2[j];
    }
    s1[i] = '\0';
}
int main() {
    char a[] = "Hello";
    char b[] = "World";
    concat(a, b);
    return (0);
}

Here is my assembly code

0000000000001169 <concat>:
    1169:   endbr64
    116d:   pushq  %rbp
    116e:   movq   %rsp,%rbp
    1171:   subq   $0x20,%rsp
    1175:   movq   %rdi,-0x18(%rbp)
    1179:   movq   %rsi,-0x20(%rbp)
    117d:   movq   -0x18(%rbp),%rax
    1181:   movq   %rax,%rdi
    1184:   callq  1060 <strlen@plt> //since calls destination is eax //
    1189:   movl   %eax,-0x8(%rbp)
    118c:   movl   $0x0,-0x4(%rbp) //local argument
    1193:   jmp    11bc <concat+0x53>
    1195:   movl   -0x4(%rbp),%eax
    1198:   movslq %eax,%rdx //hint that 32bit source moved to 64 bit sign extended
    119b:   movq   -0x20(%rbp),%rax
    119f:   addq   %rdx,%rax
    11a2:   movl   -0x8(%rbp),%edx
    11a5:   movslq %edx,%rcx
    11a8:   movq   -0x18(%rbp),%rdx
    11ac:   addq   %rcx,%rdx
    11af:   movzbl (%rax),%eax
    11b2:   movb   %al,(%rdx)
    11b4:   addl   $0x1,-0x8(%rbp)
    11b8:   addl   $0x1,-0x4(%rbp)
    11bc:   movl   -0x4(%rbp),%eax
    11bf:   movslq %eax,%rdx
    11c2:   movq   -0x20(%rbp),%rax
    11c6:   addq   %rdx,%rax
    11c9:   movzbl (%rax),%eax
    11cc:   testb  %al,%al
    11ce:   jne    1195 <concat+0x2c>
    11d0:   movl   -0x8(%rbp),%eax
    11d3:   movslq %eax,%rdx
    11d6:   movq   -0x18(%rbp),%rax
    11da:   addq   %rdx,%rax
    11dd:   movb   $0x0,(%rax)
    11e0:   nop
    11e1:   leaveq
    11e2:   retq

From the assembly code how can I tell whether an array has been passed or not in a function?

I am trying to understand the reverse enginnering tools.