问:
Detecting if headphones are connected without using dangerous permissions
I've been trying to look for a good solution to detect when headphones are connected in Android regardless of whether they are wired or wireless.

The case for wired headphones is fairly straight-forward. However, when detecting if a wireless headset is connected, the APIs I have been using require Manifest.permission.BLUETOOTH or Manifest.permission.BLUETOOTH_CONNECT.

For some time I've accepted that only if those permissions are granted will I know for sure if headphones are connected, but this is now increasingly becoming problematic.

Does anyone know of an alternative that would determine if a headset is connected without user-facing 'dangerous' permission prompts like the BluetoothHeadset solution does? Is there anything in the AudioManager that can be used instead?

Here is what I have today:

```<code>package ai.numbereight.sdk.platform.sensors

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothHeadset
import android.bluetooth.BluetoothProfile
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log

private val listener = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val connection = when (intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,
                BluetoothHeadset.STATE_DISCONNECTED)) {
            BluetoothHeadset.STATE_CONNECTED -> "Connected"
            BluetoothHeadset.STATE_DISCONNECTED -> "Disconnected"
            else -> "Unknown"
        }

        Log.d("Connection", connection)
    }
}

fun register(context: Context) {
    // Register for changes - events will only be received
    // if Manifest.permission.BLUETOOTH (< Android 10)
    // or Manifest.permission.BLUETOOTH_CONNECT (>= Android 10)
    // are granted.
    val filter = IntentFilter()
    filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)
    context.registerReceiver(listener, filter)

    // Fire initial event - this API call requires the above Bluetooth permissions
    // For brevity I assume that the default adapter is not null
    val currentState = BluetoothAdapter.getDefaultAdapter()!!.getProfileConnectionState(BluetoothProfile.HEADSET)
    val initialIntent = Intent(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)
    initialIntent.putExtra(BluetoothHeadset.EXTRA_STATE, currentState)
    listener.onReceive(context, initialIntent)
}
</code>```

Body:
I've been trying to look for a good solution to detect when headphones are connected in Android regardless of whether they are wired or wireless.

The case for wired headphones is fairly straight-forward. However, when detecting if a wireless headset is connected, the APIs I have been using require Manifest.permission.BLUETOOTH or Manifest.permission.BLUETOOTH_CONNECT.

For some time I've accepted that only if those permissions are granted will I know for sure if headphones are connected, but this is now increasingly becoming problematic.

Does anyone know of an alternative that would determine if a headset is connected without user-facing 'dangerous' permission prompts like the BluetoothHeadset solution does? Is there anything in the AudioManager that can be used instead?

Here is what I have today:

package ai.numbereight.sdk.platform.sensors

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothHeadset
import android.bluetooth.BluetoothProfile
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log

private val listener = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val connection = when (intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,
                BluetoothHeadset.STATE_DISCONNECTED)) {
            BluetoothHeadset.STATE_CONNECTED -> "Connected"
            BluetoothHeadset.STATE_DISCONNECTED -> "Disconnected"
            else -> "Unknown"
        }

        Log.d("Connection", connection)
    }
}

fun register(context: Context) {
    // Register for changes - events will only be received
    // if Manifest.permission.BLUETOOTH (< Android 10)
    // or Manifest.permission.BLUETOOTH_CONNECT (>= Android 10)
    // are granted.
    val filter = IntentFilter()
    filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)
    context.registerReceiver(listener, filter)

    // Fire initial event - this API call requires the above Bluetooth permissions
    // For brevity I assume that the default adapter is not null
    val currentState = BluetoothAdapter.getDefaultAdapter()!!.getProfileConnectionState(BluetoothProfile.HEADSET)
    val initialIntent = Intent(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)
    initialIntent.putExtra(BluetoothHeadset.EXTRA_STATE, currentState)
    listener.onReceive(context, initialIntent)
}


来源: stackexchange

问:
Compiler code error : 'a' was not declared
Ok. Trying to generate a code by displaying the stack contents after each instruction where we assume that the variables are initialized with the values: a=22, b=33 and c=44

Also, assume the following address environment:

```<code>ρ={a I→5,b I→6,cI→7}
</code>```

My background: 4th day of Compiler Design and Virtual Machines. New to this stuff and evidently this is not C++, but something else. Prog is VERY "hands off", especially current prof.

```<code>int main (void)  {
a = 22
b = 33`
c = 44
p = {'a' : 5, 'b' : 6, 'c' : 7}
for each instruction in the generated code:
if instruction.startswith ('a'):
p['a'] = instruction[1]
elif instruction.startswith ('b'):
p['b'] = instruction[1]
elif instruction.startswith ('c'):
p['c'] = instruction[1]
print (f'a = {p['a']},  b = {p['b']}, c = {p['c']}')
     }
</code>```

To be honest, I was expecting it to compile and return back a = 22, b = 33, and c = 44??

Got back a few errors:

main.cpp:12:9: warning: character constant too long for its type

12 | print (f'a = {p['a']},  b = {p['b']}, c = {p['c']}')

|         ^~~~~~~~~~

main.cpp: In function ‘int main()’:

main.cpp:2:1: error: ‘a’ was not declared in this scope

2 | a = 22

| ^

main.cpp: At global scope

6 | if instruction.startswith ('a'):

| ^~

main.cpp:13:6: error: expected declaration before ‘}’ token

13 |      }

|      ^

ContentLicense: CC BY-SA 4.0

Body:
Ok. Trying to generate a code by displaying the stack contents after each instruction where we assume that the variables are initialized with the values: a=22, b=33 and c=44

Also, assume the following address environment:

ρ={a I→5,b I→6,cI→7}

My background: 4th day of Compiler Design and Virtual Machines. New to this stuff and evidently this is not C++, but something else. Prog is VERY "hands off", especially current prof.

int main (void)  {
a = 22
b = 33`
c = 44
p = {'a' : 5, 'b' : 6, 'c' : 7}
for each instruction in the generated code:
if instruction.startswith ('a'):
p['a'] = instruction[1]
elif instruction.startswith ('b'):
p['b'] = instruction[1]
elif instruction.startswith ('c'):
p['c'] = instruction[1]
print (f'a = {p['a']},  b = {p['b']}, c = {p['c']}')
     }

To be honest, I was expecting it to compile and return back a = 22, b = 33, and c = 44??

Got back a few errors:

main.cpp:12:9: warning: character constant too long for its type

12 | print (f'a = {p['a']},  b = {p['b']}, c = {p['c']}')

|         ^~~~~~~~~~

main.cpp: In function ‘int main()’:

main.cpp:2:1: error: ‘a’ was not declared in this scope

2 | a = 22

| ^

main.cpp: At global scope

6 | if instruction.startswith ('a'):

| ^~

main.cpp:13:6: error: expected declaration before ‘}’ token

13 |      }

|      ^


问:
How to do so if parameters are passed, then use them, if not, then standard input.txt, output.txt in java
How to make sure that the name of the input file (input .txt)is not written in the program
but it could be changed using these type arguments (-Dinputfile)

I tried to figure it out myself, but nothing worked, I hope for your help...


问:
Android kotlin login button unresponsive after too many failed fingerprint attempts
I'm currently using a combination of FingerprintDialog with BiometricPrompt. I've run into an issue where I will repeatedly input the incorrect fingerprint to force failed fingerprint attempts, I receive my expected prompt saying that user exceeded fingerprint attempts, etc...

After I close the dialog, I proceed to login using password but for some reason the Login button is unresponsive and cannot login. The only solution has been restarting the app.

I assumed it was all due to the Biometric lockout which is 30 seconds, so I've tried waiting 30 seconds and still doesn't work. I've waited up to 10 minutes and never works. The only time it worked was when I let the device sleep and turn on after some time.

```<code>    private fun setFpView() {
        val context = context ?: return
        if (mTouchFailCount >= MAX_NUM_TOUCH_FAILS) {
            dismissFpDialog()
            setPasswordLoginInUserSettings()
            mUsernameInput.postDelayed(
                {
                    if (!isAdded || isStateSaved) {
                        return@postDelayed
                    }
                    showDialog(
                        "too many failed attempts"
                    )
                },
                ERROR_DIALOG_DELAY_MILLIS.toLong()
            )  dismissFpDialog()
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            if (fpDialog == null) {
                closeDialogIfShowing()
                showFpDialog()
            } else {
                fpDialog?.apply {
                    setDialogListener(this@BiometricFragment)
                    setFpListener(this@BiometricFragment)
                }
            }
        }
    }
</code>```

Sorry I've been stuck on this for a while and I tried searching all over but couldn't find anything that helped resolve this issue.

Body:
I'm currently using a combination of FingerprintDialog with BiometricPrompt. I've run into an issue where I will repeatedly input the incorrect fingerprint to force failed fingerprint attempts, I receive my expected prompt saying that user exceeded fingerprint attempts, etc...

After I close the dialog, I proceed to login using password but for some reason the Login button is unresponsive and cannot login. The only solution has been restarting the app.

I assumed it was all due to the Biometric lockout which is 30 seconds, so I've tried waiting 30 seconds and still doesn't work. I've waited up to 10 minutes and never works. The only time it worked was when I let the device sleep and turn on after some time.

    private fun setFpView() {
        val context = context ?: return
        if (mTouchFailCount >= MAX_NUM_TOUCH_FAILS) {
            dismissFpDialog()
            setPasswordLoginInUserSettings()
            mUsernameInput.postDelayed(
                {
                    if (!isAdded || isStateSaved) {
                        return@postDelayed
                    }
                    showDialog(
                        "too many failed attempts"
                    )
                },
                ERROR_DIALOG_DELAY_MILLIS.toLong()
            )  dismissFpDialog()
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            if (fpDialog == null) {
                closeDialogIfShowing()
                showFpDialog()
            } else {
                fpDialog?.apply {
                    setDialogListener(this@BiometricFragment)
                    setFpListener(this@BiometricFragment)
                }
            }
        }
    }

Sorry I've been stuck on this for a while and I tried searching all over but couldn't find anything that helped resolve this issue.


问:
Is it possible to run a "generate" block or other TG functions in a "before_hook" phase in Terragrunt?
I have a Terragrunt repo set up. The TG root config file has some generators in it, but the generators run after other functions are called by TG - There is a specific TG function running that depends on a specific "generate" block executing first (I am trying to call sops_decrypt_file, and the generator dynamically creates a .sops.yaml config file with relevant encryption key configuration depending on the TG tree path). However, sops_decrypt_file from the HCL is executed before the generate block runs, so SOPS doesn't find the config file.

Is there a way to configure something like a before_hook to run the generate block (instead of using before_hook to run a system command) ?


问:
Creating a lexer and basic parser to extract class names, methods names, method parameters, etc
General task/idea

I'm currently trying to create a couple of lexers to extract functions/method names as well as class names and namespaces from different languages.

The goal is to be able to extract all defined classes, functions/methods, and namespaces to easily generate a overview for documentation and statistics.

As a starting point i chose PowerShell.

I created a basic lexer to tokenize my input.

I'm unsure where to go from here and if i'm doing it correctly.
Since I don't want to actually parse the language and generate code / interpret it, I won't really need to implement a full syntax analyzer and AST in my understanding.

My idea is to only check for certain pre-defined keywords like function, class, namespace, etc...

Question

Please help me stay in the correct direction as this is the first time I'm doing something like that and I'm really unsure how to proceed from now on.

Is my tokenizer correct, or did I mess up something?

Code

```<code>internal class TestLexer
{
    private int _pos;
    private string _input;

    public class Token
    {
        public TokenType TokenType { get; }
        public string Value { get; }

        public Token(TokenType tokenType, string value)
        {
            TokenType = tokenType;
            Value = value;
        }
    }

    public enum TokenType
    {
        Variable,
        OpenBrace,
        CloseBrace,
        Assignment,
        Identifier,
        Comment,
        Equals,
        NotEquals,
        MultiLineCommentStart,
        MultiLineCommentEnd,
        Type,
        Number
    }

    public IEnumerable<Token> Tokenize()
    {
        while (_pos < _input.Length)
        {
            var currentChar = _input[_pos];
            if (char.IsWhiteSpace(currentChar)) {
                _pos++;
                continue;
            }

            switch (currentChar)
            {
                case '$':
                    {
                        _pos++;
                        yield return new Token(TokenType.Variable, "$");
                        break;
                    }
                case '=':
                    {
                        _pos++;
                        yield return new Token(TokenType.Assignment, "=");
                        break;
                    }
                case '#':
                    {
                        if (currentChar + 1 < _input.Length) {
                            if (currentChar + 1 == '>') {
                                _pos++;
                                _pos++;
                                yield return new Token(TokenType.MultiLineCommentEnd, "#>");
                            }
                            else {
                                _pos++;
                                yield return new Token(TokenType.Comment, "#");
                            }
                        }
                        else {
                            _pos++;
                            yield return new Token(TokenType.Comment, "#");
                        }
                        break;
                    }
                case '{':
                    {
                        _pos++;
                        yield return new Token(TokenType.OpenBrace, "{");
                        break;
                    }
                case '}':
                    {
                        _pos++;
                        yield return new Token(TokenType.CloseBrace, "}");
                        break;
                    }
                case '[':
                    {
                        _pos++;
                        yield return new Token(TokenType.OpenBrace, "[");
                        break;
                    }
                case ']':
                    {
                        _pos++;
                        yield return new Token(TokenType.OpenBrace, "]");
                        break;
                    }
                case '(':
                    {
                        _pos++;
                        yield return new Token(TokenType.OpenBrace, "(");
                        break;
                    }
                case ')':
                    {
                        _pos++;
                        yield return new Token(TokenType.OpenBrace, ")");
                        break;
                    }
                case '<':
                    {
                        if (currentChar + 1 < _input.Length) {
                            if (currentChar + 1 == '#') {
                                _pos++;
                                _pos++;
                                yield return new Token(TokenType.MultiLineCommentStart, "<#");
                            }
                            else {
                                _pos++;
                            }
                        }
                        else {
                            _pos++;
                        }
                        break;
                    }
                default:
                    if (char.IsLetter(currentChar)) {
                        var identifierBuilder = new StringBuilder();
                        while (char.IsLetter(currentChar)) {
                            identifierBuilder.Append(currentChar);
                            _pos++;
                            if (_pos >= _input.Length) {
                                break;
                            }
                            currentChar = _input[_pos];
                        }
                        yield return new Token(TokenType.Identifier, identifierBuilder.ToString());
                    }
                    else if (char.IsDigit(currentChar)) {
                        var numericBuilder = new StringBuilder();
                        while (char.IsDigit(currentChar)) {
                            numericBuilder.Append(currentChar);
                            _pos++;
                            if (_pos >= _input.Length) {
                                break;
                            }
                            currentChar = _input[_pos];
                        }
                        decimal d;
                        if (decimal.TryParse(numericBuilder.ToString(), out d)) {
                            yield return new Token(TokenType.Number, numericBuilder.ToString());
                        }
                    }
                    _pos++;
                    break;
            };
        }
    }

    public TestLexer(string input)
    {
        _input = input;
        _pos = 0;
    }
}
</code>```

Body:
General task/idea

I'm currently trying to create a couple of lexers to extract functions/method names as well as class names and namespaces from different languages.

The goal is to be able to extract all defined classes, functions/methods, and namespaces to easily generate a overview for documentation and statistics.

As a starting point i chose PowerShell.

I created a basic lexer to tokenize my input.

I'm unsure where to go from here and if i'm doing it correctly.
Since I don't want to actually parse the language and generate code / interpret it, I won't really need to implement a full syntax analyzer and AST in my understanding.

My idea is to only check for certain pre-defined keywords like function, class, namespace, etc...

Question

Please help me stay in the correct direction as this is the first time I'm doing something like that and I'm really unsure how to proceed from now on.

Is my tokenizer correct, or did I mess up something?

Code

internal class TestLexer
{
    private int _pos;
    private string _input;

    public class Token
    {
        public TokenType TokenType { get; }
        public string Value { get; }

        public Token(TokenType tokenType, string value)
        {
            TokenType = tokenType;
            Value = value;
        }
    }

    public enum TokenType
    {
        Variable,
        OpenBrace,
        CloseBrace,
        Assignment,
        Identifier,
        Comment,
        Equals,
        NotEquals,
        MultiLineCommentStart,
        MultiLineCommentEnd,
        Type,
        Number
    }

    public IEnumerable<Token> Tokenize()
    {
        while (_pos < _input.Length)
        {
            var currentChar = _input[_pos];
            if (char.IsWhiteSpace(currentChar)) {
                _pos++;
                continue;
            }

            switch (currentChar)
            {
                case '$':
                    {
                        _pos++;
                        yield return new Token(TokenType.Variable, "$");
                        break;
                    }
                case '=':
                    {
                        _pos++;
                        yield return new Token(TokenType.Assignment, "=");
                        break;
                    }
                case '#':
                    {
                        if (currentChar + 1 < _input.Length) {
                            if (currentChar + 1 == '>') {
                                _pos++;
                                _pos++;
                                yield return new Token(TokenType.MultiLineCommentEnd, "#>");
                            }
                            else {
                                _pos++;
                                yield return new Token(TokenType.Comment, "#");
                            }
                        }
                        else {
                            _pos++;
                            yield return new Token(TokenType.Comment, "#");
                        }
                        break;
                    }
                case '{':
                    {
                        _pos++;
                        yield return new Token(TokenType.OpenBrace, "{");
                        break;
                    }
                case '}':
                    {
                        _pos++;
                        yield return new Token(TokenType.CloseBrace, "}");
                        break;
                    }
                case '[':
                    {
                        _pos++;
                        yield return new Token(TokenType.OpenBrace, "[");
                        break;
                    }
                case ']':
                    {
                        _pos++;
                        yield return new Token(TokenType.OpenBrace, "]");
                        break;
                    }
                case '(':
                    {
                        _pos++;
                        yield return new Token(TokenType.OpenBrace, "(");
                        break;
                    }
                case ')':
                    {
                        _pos++;
                        yield return new Token(TokenType.OpenBrace, ")");
                        break;
                    }
                case '<':
                    {
                        if (currentChar + 1 < _input.Length) {
                            if (currentChar + 1 == '#') {
                                _pos++;
                                _pos++;
                                yield return new Token(TokenType.MultiLineCommentStart, "<#");
                            }
                            else {
                                _pos++;
                            }
                        }
                        else {
                            _pos++;
                        }
                        break;
                    }
                default:
                    if (char.IsLetter(currentChar)) {
                        var identifierBuilder = new StringBuilder();
                        while (char.IsLetter(currentChar)) {
                            identifierBuilder.Append(currentChar);
                            _pos++;
                            if (_pos >= _input.Length) {
                                break;
                            }
                            currentChar = _input[_pos];
                        }
                        yield return new Token(TokenType.Identifier, identifierBuilder.ToString());
                    }
                    else if (char.IsDigit(currentChar)) {
                        var numericBuilder = new StringBuilder();
                        while (char.IsDigit(currentChar)) {
                            numericBuilder.Append(currentChar);
                            _pos++;
                            if (_pos >= _input.Length) {
                                break;
                            }
                            currentChar = _input[_pos];
                        }
                        decimal d;
                        if (decimal.TryParse(numericBuilder.ToString(), out d)) {
                            yield return new Token(TokenType.Number, numericBuilder.ToString());
                        }
                    }
                    _pos++;
                    break;
            };
        }
    }

    public TestLexer(string input)
    {
        _input = input;
        _pos = 0;
    }
}


问:
How to make a moving average of the bars in trade in Pine Script?
How can I make a moving average of the average number of bars that a trade is active for in Pine Script?

I tryed using if statements and incrementing when in a trade to the make a moving average from the days in the trade but this did not work

The Code so far:

```<code>//@version=5
indicator("My script")

//Create variable
tradein = "None"
nPastDays = 0.0
daysintradecount = 0.0

if (close > open)

    //Go long
    tradein := "Long"

else if (close <= open)

    //Go Short
    tradein := "Short"

if (tradein == "Long") or (tradein == "Short")
    nPastDays:=nPastDays+1

else if (tradein == "None")
    nPastDays:=0

daysintradecount := nPastDays

 ////
tradeinmovingaverage = ta.sma(daysintradecount, 7)

 ////
plot(tradeinmovingaverage, color=color.green)
</code>```

Body:
How can I make a moving average of the average number of bars that a trade is active for in Pine Script?

I tryed using if statements and incrementing when in a trade to the make a moving average from the days in the trade but this did not work

The Code so far:

//@version=5
indicator("My script")

//Create variable
tradein = "None"
nPastDays = 0.0
daysintradecount = 0.0

if (close > open)

    //Go long
    tradein := "Long"

else if (close <= open)

    //Go Short
    tradein := "Short"

if (tradein == "Long") or (tradein == "Short")
    nPastDays:=nPastDays+1

else if (tradein == "None")
    nPastDays:=0

daysintradecount := nPastDays

 ////
tradeinmovingaverage = ta.sma(daysintradecount, 7)

 ////
plot(tradeinmovingaverage, color=color.green)


问:
How do you provide an API key to YouTube API in Google Sheets?
I have been following this documentation: https://developers.google.com/youtube/v3/quickstart/apps-script

I have successfully added the YouTube data service.

Upon using the YouTube.whatever method, it is supposed to login, but it does not.  Force refreshing I finally triggered it, but then Chrome blocks it.  I ignored the block, and accepted.

Calling my YouTube method states I did not provide an API key, because I didn't, and the documentation doesn't state how:

Confirmed OAuth Scopes exist and make sense:

I also ensured they exist in appscript.json:

I made a test function and ran it within the Apps Script editor, and it worked, but it does not work in a cell.

Wild Googling goose chase begins: https://console.cloud.google.com/  Create a project.  Attempt to reference project in Apps Script settings, but it says I need to configure the OAuth consent form, which sounds eerily similar to what I just did by logging in above.

Click on link to configure OAuth Consent, but says there is an error on loading.  Using their troubleshooter says I don't have permission to troubleshoot.

I'm out of ideas, and cannot find any mention of providing an API key in any fashion outside using third party apps.  Instructions seem clear, there is no mention of an API key, how to get one (I figured out how), or how to input it.

My ultimate goal is to simply trying to access subscriber counts of YouTube channels:

I compared my steps to https://www.youtube.com/watch?v=Xq7HKYRPweE, and found they are the same.  However, they are injecting the results into a spreadsheet, instead of calling from a cell.

I appreciate your assistance.


问:
How to use Webpack in an old Codeigniter project to compile vue components?
The title of the question can't explain it all, but bear with me, this is the situation I'm in.
I'm working in a 10+ year old Codeigniter project, I came to realize it's not making use of current technologies, doesn't make use of npm, doesn't have a package.json or even composer.json. All the libraries used are downloaded directly to the project and stored to an 'assets' folder, custom js is stored in php files with no minification and relying on jquery only, then injected to the main php file containing the html body.

I want to refactor everything but in a way that doesn't affect the project too much and doesn't take that much time, I'm planning on using Vue and Vuex, having their components compiled by Vue-compiler, I also wanna have a Sass compiler but that's another story and I'm sure with the knowledge I gain here for Webpack and Vue I can manage to apply it to Sass as well.

Ok, so how's the project structure right now: There's a folder called Packages, inside there's subfolders of modules, each one represent either one or more pages or a set of tools to be used by other modules. But lets focus on the page modules, this is how one looks:

So each one has it's routes, controllers, models, language packs, and views.
My idea to make use of vue is, for each one of these modules, add the main.js file on the js folder, create a components folder in that js folder, then do the html templates and javascript functionality in them.
My hope is to have a watcher that I run from a package.json I create and each time I perform a save on either the main.js or the .vue files in the components folder, it compiles these files and generates the usual minified file, Idk, in the same js folder or something.
Then what I do, is to load that in the view files (in this case buypackage.php and listing.php) and it should work, right?

The only issue I see is that buypackage and listing are two separate pages, so each one should have it's own minified file to load, so the solution above would only work if there was only one page per module, so maybe I need to create 2 subfolders in the views folder representing each page, then each one would have the same structure with the js/components folders? Idk.

So this is generally how I want it to work out, each module would work the same way.
I'm not really seasoned in Webpack and similar, I previously worked on a Laravel + Vue project that had everything set up for me so I tried looking at what it was doing exactly but didn't show me much, also tried looking at a vue project generated with their UI tool, but it's made so it compiles everything into a dist folder, it's substantially different to what I want.
Also weighed the option of just bringing the vuejs library and working in js files instead of components, but that defeats the purpose of trying to obfuscate the js code a little at least.

This is what I want to do, but I don't know how to set up everything right so vue-compiler knows what to compile and where to compile it.
And that's what I think it's the least intrusive and less harder solution to improve the frontend, but I'm also open to read better solutions.

Any help would be greatly appreciated.
Thanks in advance!


问:
<sys/io.h> missing when compiling emscripten
I tried compiling a game I made with glut using RakNet in C++. But whenever try to compile it for browser. I get this error:</p>
```<code>lib/RakNet/Source/FileList.cpp:24:10: fatal error: 'sys/io.h' file not found
#include <sys/io.h>
         ^~~~~~~~~~
1 error generated.
emcc: error: '/opt/emscripten-llvm/bin/clang++ -target wasm32-unknown-emscripten -fignore-exceptions -fvisibility=default -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr -DEMSCRIPTEN -I/home/bonii/.emscripten_cache/sysroot/include/SDL --sysroot=/home/bonii/.emscripten_cache/sysroot -Xclang -iwithsysroot/include/compat lib/RakNet/Source/FileList.cpp -c -o /tmp/emscripten_temp_krrz_u5e/FileList_29.o' failed (returned 1)
</code>```

Body:
I tried compiling a game I made with glut using RakNet in C++. But whenever try to compile it for browser. I get this error:

lib/RakNet/Source/FileList.cpp:24:10: fatal error: 'sys/io.h' file not found
#include <sys/io.h>
         ^~~~~~~~~~
1 error generated.
emcc: error: '/opt/emscripten-llvm/bin/clang++ -target wasm32-unknown-emscripten -fignore-exceptions -fvisibility=default -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr -DEMSCRIPTEN -I/home/bonii/.emscripten_cache/sysroot/include/SDL --sysroot=/home/bonii/.emscripten_cache/sysroot -Xclang -iwithsysroot/include/compat lib/RakNet/Source/FileList.cpp -c -o /tmp/emscripten_temp_krrz_u5e/FileList_29.o' failed (returned 1)


问:
NA created in estimates with categorical GLM
I have a data set which as a proportion as a response variable and two categorical variables (crest.flow and crest.type) as explanatory variables. The contingency table is below with an example dataset

```<code>Contingency table:
         control    inline    opposite
control      42       0          0
radial        0      28         21
slope         0      25         27

structure(list(prop.success = c(0.75, 0.9, 0.85, 0.75, 0.9, 0.7
), n = c(20L, 20L, 20L, 20L, 20L, 20L), crest.flow = c("control",
"inline", "opposite", "control", "inline", "opposite"), crest.type = c("control",
"slope", "radial", "control", "slope", "radial")), row.names = c(NA,
6L), class = "data.frame")
</code>```

I have run a simple glm but I am getting NA in my estimates and I'm not sure why.

```<code>m <- glm(prop.success ~ crest.type + crest.flow, family = binomial,
    data = dat, weights = n)

> summary(m)

Call:
glm(formula = prop.success ~ crest.type + crest.flow, family = binomial,
    data = dat, weights = n)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-4.5440  -1.7382   0.2984   1.5876   4.4935

Coefficients: (1 not defined because of singularities)
                   Estimate Std. Error z value Pr(>|z|)
(Intercept)        -0.33729    0.07007  -4.813 1.48e-06 ***
crest.typeradial    0.31484    0.10822   2.909  0.00362 **
crest.typeslope     0.78326    0.10494   7.464 8.42e-14 ***
crest.flowinline    0.03626    0.09140   0.397  0.69161
crest.flowopposite       NA         NA      NA       NA
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 740.47  on 141  degrees of freedom
Residual deviance: 666.28  on 138  degrees of freedom
AIC: 1118.2

Number of Fisher Scoring iterations: 4
</code>```

Any idea why this could be occurring? Is this an issue with study design? A full copy of the dataset can be found here if required

Body:
I have a data set which as a proportion as a response variable and two categorical variables (crest.flow and crest.type) as explanatory variables. The contingency table is below with an example dataset

Contingency table:
         control    inline    opposite
control      42       0          0
radial        0      28         21
slope         0      25         27

structure(list(prop.success = c(0.75, 0.9, 0.85, 0.75, 0.9, 0.7
), n = c(20L, 20L, 20L, 20L, 20L, 20L), crest.flow = c("control",
"inline", "opposite", "control", "inline", "opposite"), crest.type = c("control",
"slope", "radial", "control", "slope", "radial")), row.names = c(NA,
6L), class = "data.frame")

I have run a simple glm but I am getting NA in my estimates and I'm not sure why.

m <- glm(prop.success ~ crest.type + crest.flow, family = binomial,
    data = dat, weights = n)

> summary(m)

Call:
glm(formula = prop.success ~ crest.type + crest.flow, family = binomial,
    data = dat, weights = n)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-4.5440  -1.7382   0.2984   1.5876   4.4935

Coefficients: (1 not defined because of singularities)
                   Estimate Std. Error z value Pr(>|z|)
(Intercept)        -0.33729    0.07007  -4.813 1.48e-06 ***
crest.typeradial    0.31484    0.10822   2.909  0.00362 **
crest.typeslope     0.78326    0.10494   7.464 8.42e-14 ***
crest.flowinline    0.03626    0.09140   0.397  0.69161
crest.flowopposite       NA         NA      NA       NA
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 740.47  on 141  degrees of freedom
Residual deviance: 666.28  on 138  degrees of freedom
AIC: 1118.2

Number of Fisher Scoring iterations: 4

Any idea why this could be occurring? Is this an issue with study design? A full copy of the dataset can be found here if required


问:
Sampling through joint probability table
I'm trying to create a generated dataset through a joint probability table (for example 10% of the total dataset containing $10,000 salary and none for education). But also the distribution needs to include the probability from a second joint probability table

Table 1

Education\Salary
$10,000
$20,000

None
0.1
0.2

Hs
0.3
0.1

College
0.2
0.1

Table 2

Age\Salary
$10,000
$20,000

30
0.2
0.1

40
0.2
0.1

50
0.2
0.2

I was able to simulate the dataset for table 1, but have no idea how to do it simultaneously with table 2.


问:
How to add different decorators of the same interface for each assembly in Asp.Net Core?
I am creating idempotent domain event handler for event handlers and I would like to add decorator for each of my business assemblies.

Example:
If DomainEvent is from the ORDER module I would like to decorate this one:

services.Decorate(
         typeof(INotificationHandler<>),
         typeof(IdempotentORDERDomainEventHandle<>)
    );
```
<p>If <code>DomainEvent</code> is from the <code>CATALOG module</code> I would like then to start decorating with this one</p>
<pre class="lang-cs prettyprint-override"><code>services.Decorate(
         typeof(INotificationHandler<>),
         typeof(IdempotentCATALOGDomainEventHandle<>)
    );
</code>```

I would like to have a different decorator depending on the assembly.

Body:
I am creating idempotent domain event handler for event handlers and I would like to add decorator for each of my business assemblies.

Example:
If DomainEvent is from the ORDER module I would like to decorate this one:

services.Decorate(
         typeof(INotificationHandler<>),
         typeof(IdempotentORDERDomainEventHandle<>)
    );

If DomainEvent is from the CATALOG module I would like then to start decorating with this one

services.Decorate(
         typeof(INotificationHandler<>),
         typeof(IdempotentCATALOGDomainEventHandle<>)
    );

I would like to have a different decorator depending on the assembly.


问:
Postgres: GENERATED ALWAYS AS IDENTITY reusing deleted record's identity value
I have a following table:

```<code>CREATE TABLE IF NOT EXISTS segment
(
    id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1),
  )
</code>```

In a single transaction (in Spring JPA), I am deleting and inserting a new record. For new record though, it's using deleted records id value. How can I force postgres to always increment id value and not use deleted record's id value?

Here's my JPA entity :

```<code>@Entity
@Table(name = "segment", schema = "travel")
public class SegmentTblEntity {

  @Id
  @Basic
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", updatable = false)
  private Integer id;
}
</code>```

Body:
I have a following table:

CREATE TABLE IF NOT EXISTS segment
(
    id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1),
  )

In a single transaction (in Spring JPA), I am deleting and inserting a new record. For new record though, it's using deleted records id value. How can I force postgres to always increment id value and not use deleted record's id value?

Here's my JPA entity :

@Entity
@Table(name = "segment", schema = "travel")
public class SegmentTblEntity {

  @Id
  @Basic
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", updatable = false)
  private Integer id;
}


问:
Terraform Unable to Import multiple aws_s3_object keys using
I'm trying to import aws_s3_object keys which are created manually to Terraform but seems like there is no way to do this if you have more folders/keys in s3 bucket.

If anyone has experience the same issue and found a solution please help me out.


问:
MudBlazor - Searchable MudTextField with suggestions
I am trying to create a searchable textfield in MudBlazor with suggestions list.
However i am trying display the suggestions with MudList but the list seems to show the suggestions after a delay. Is there a better solutions other than MudList?
My solution can be accessed here

I would appreciate any feedback


问:
How to get an image from queued request body (Workbox PWA)
I am using Workbox in my PWA. If app is offline and image posting request fails - it is automatically added to IndexedDB.

```<code>    const post = (file: File) => {
        const formData = new FormData()
        formData.append("image", file);
        axios.post('http://some.com/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(...)
</code>```

I want to show user all images of queued requests in offline mode. How i get requests:

import { openDB } from 'idb';
const db = await openDB('workbox-background-sync');
const queuedRequests = await db.getAllFromIndex('requests', 'queueName');
```

<p>Body of request is ArrayBuffer (how request is stored in IndexedDB is showed on the picture). I don't understand how to "extract" image and pass it to
<code>createObjectURL( imageBlob )</code>.</p>
<p>If i decode body like this:</p>
```let view = new Uint8Array(body);
let bodyAsString = new TextDecoder().decode(view);
```
<p>I got post body which contains image bytes after <em>"image/png\r\n\r\n"</em>:</p>
```------WebKitFormBoundaryfc7IW9qvYqE2SdSm\r\nContent-Disposition: form-data; name="image"; filename="1.png"\r\nContent-Type: image/png\r\n\r\n�PNG\r\n\x1A\n\x00\...
```

I don't think that parsing payload using regexp, then encoding it is a good approach. How can this be done?

Body:
I am using Workbox in my PWA. If app is offline and image posting request fails - it is automatically added to IndexedDB.

    const post = (file: File) => {
        const formData = new FormData()
        formData.append("image", file);
        axios.post('http://some.com/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(...)

I want to show user all images of queued requests in offline mode. How i get requests:

import { openDB } from 'idb';
const db = await openDB('workbox-background-sync');
const queuedRequests = await db.getAllFromIndex('requests', 'queueName');

Body of request is ArrayBuffer (how request is stored in IndexedDB is showed on the picture). I don't understand how to "extract" image and pass it to
createObjectURL( imageBlob ).

If i decode body like this:

let view = new Uint8Array(body);
let bodyAsString = new TextDecoder().decode(view);

I got post body which contains image bytes after "image/png\r\n\r\n":

------WebKitFormBoundaryfc7IW9qvYqE2SdSm\r\nContent-Disposition: form-data; name="image"; filename="1.png"\r\nContent-Type: image/png\r\n\r\n�PNG\r\n\x1A\n\x00\...

I don't think that parsing payload using regexp, then encoding it is a good approach. How can this be done?


问:
output of quarto html format fails when saved on sharepoint
I have Quarto html document with the below yaml header and this renders and views just fine when I save on my local directory and open it or view in RStudio.

However, when I save saved output (an html file) on my Corporation's SharePoint site, the tab-set and cold-folding functionality fails (as well as some other polished formatting like the floating table of contents on the right side)

This didn't happen in rmarkdown so I'm unsure if I'm doing something wrong or need specific a format type option if I plan to send this by email.

```<code>format:
  html:
    fig-width: 12
    fig-height: 7
    code-overflow: wrap
    toc: true
    embed-resources: true
code-fold: true
</code>```

Body:
I have Quarto html document with the below yaml header and this renders and views just fine when I save on my local directory and open it or view in RStudio.

However, when I save saved output (an html file) on my Corporation's SharePoint site, the tab-set and cold-folding functionality fails (as well as some other polished formatting like the floating table of contents on the right side)

This didn't happen in rmarkdown so I'm unsure if I'm doing something wrong or need specific a format type option if I plan to send this by email.

format:
  html:
    fig-width: 12
    fig-height: 7
    code-overflow: wrap
    toc: true
    embed-resources: true
code-fold: true


问:
Tizen Web app iframe is in fullscreen instead of in a table
I'm currently coding a small web app for a tizen tv. It mainly consists of a table with 2x2 cells. every cell contains an Iframe to another website.

But when i ran it on my TV i noticed that instead of four websites, only one website was shown in fullscreen. I set the table's size to 100% height and width.
Thank you in advance

I tried using 100vh/vw for the size instead of percentages


问:
reportMissingImports Python. Problems with the interpreter and how to upgrade versions of Python on Windows
I'm learning Python and I've installed 2 versions of Python: 3.10.6 and 3.11.1 and I've both versions on Visual Studio Code.

How do I upgrade all to use just the version 3.11.1 in Visual Studio or what is the topic I have to learn to use different versions. 3.11.1WithProblem.

My problem is that I get the error reportMissingImports when I want to use a Library I already had installed in the interpreter 3.10. If I change to the interpreter 3.10 it works, but the thing is that I want to use the program I already created with the interpreter 3.11.1 having already installed python 3.11.1 3.10.6WithoutProblem


问:
how to open up docker-compose up when given these issues
```<code>docker-compose up has no configuration file provided: not found
</code>```

this is given that I am in the directory where the docker-compose-LocalExecutor.yml file is.

What should my next steps be to be able to open airflow in localhost:8080

Note: I am using windows

Looking at previous stackoverflow posts, I have also tried docker-compose -f .\docker-compose-LocalExecutor.yml up, but it returns:

```<code>Error response from daemon: driver failed programming external connectivity on endpoint docker-airflow-master-webserver-1 (f5311e617e9076840eeda2343df931c4716b9ae33817ba1ed91c10c272df9766): Bind for 0.0.0.0:8080 failed: port is already allocated
</code>```

Body:
docker-compose up has no configuration file provided: not found

this is given that I am in the directory where the docker-compose-LocalExecutor.yml file is.

What should my next steps be to be able to open airflow in localhost:8080

Note: I am using windows

Looking at previous stackoverflow posts, I have also tried docker-compose -f .\docker-compose-LocalExecutor.yml up, but it returns:

Error response from daemon: driver failed programming external connectivity on endpoint docker-airflow-master-webserver-1 (f5311e617e9076840eeda2343df931c4716b9ae33817ba1ed91c10c272df9766): Bind for 0.0.0.0:8080 failed: port is already allocated


问:
R Shiny breaking out of a while loop
Here is a simple issue that is been driving me crazy the past few days.

My dashboard has this while loop to wait for a file to become available before moving on:

while (!file.exists(fn)) { Sys.sleep(1) }

I need to be able to breakout if a Cancel button is triggered.

I have tried to put an observeEvent inside the loop but that didnt work out. I also tried to put a modalDialog box with an activeButton before or around the loop, still no go.

Any solution to this? Maybe the while loop is not the right way to go...

Title: R Shiny breaking out of a while loop


问:
How To Set Node.js Extension PATH in VS Code
I installed on a Slackware based (SALIX) VS Code via FlatPack and I tried to set up the JAVA environment. First time I tested a JavaScript sample file received a message (see attached).

```<code>Version: 1.74.2
Commit: e8a3071ea4344d9d48ef8a4df2c097372b0c5161
Date: 2022-12-20T10:27:19.253Z
Electron: 19.1.8
Chromium: 102.0.5005.167
Node.js: 16.14.2
V8: 10.2.154.15-electron.0
OS: Linux x64 5.15.63
Sandboxed: No
</code>```

Then I installed from package manager nodejs 17.9.0 and I export PATH=$PATH:/usr/bin/node

Then I tried to add node.js extension.
I followed:
[url]https://code.visualstudio.com/docs/nodejs/working-with-javascript[/url]

I tried to add to launch.json "runtimeExecutable": "node"

```<code>    {
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
    {
        "type": "node",
        "request": "launch",
        "name": "Launch Program",
        "skipFiles": [
            "<node_internals>/**"
        ],
        "program": "${workspaceFolder}/GettingStarted/jssample.js",
        "runtimeExecutable": "/usr/bin/node"
    }
]
</code>```

}

but still got the same message (attached).

```<code>brad@toshiba:~$ java -version
java version "19.0.1" 2022-10-18
Java(TM) SE Runtime Environment (build 19.0.1+10-21)
Java HotSpot(TM) 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing)
brad@toshiba:~$ npm version
{
  npm: '8.5.5',
  node: '17.9.0',
  v8: '9.6.180.15-node.16',
  uv: '1.43.0',
  zlib: '1.2.12',
  brotli: '1.0.9',
  ares: '1.18.1',
  modules: '102',
  nghttp2: '1.47.0',
  napi: '8',
  llhttp: '6.0.4',
  openssl: '3.0.2+quic',
  cldr: '40.0',
  icu: '70.1',
  tz: '2021a3',
  unicode: '14.0',m
  ngtcp2: '0.1.0-DEV',
  nghttp3: '0.1.0-DEV'
</code>```

I tried to install 19.3.0:

I can run the js file from CLI BUT not in VS Code environment.
Not to mention it works just fine on Debian based OSs.

Thanks!

I installed node 19.3.0 but does not make any difference.

I reinstalled VS Code upon node installation but does not make any difference.

I reinstalled from sources VS Code upon node installation and does not make any difference either.

Body:
I installed on a Slackware based (SALIX) VS Code via FlatPack and I tried to set up the JAVA environment. First time I tested a JavaScript sample file received a message (see attached).

Version: 1.74.2
Commit: e8a3071ea4344d9d48ef8a4df2c097372b0c5161
Date: 2022-12-20T10:27:19.253Z
Electron: 19.1.8
Chromium: 102.0.5005.167
Node.js: 16.14.2
V8: 10.2.154.15-electron.0
OS: Linux x64 5.15.63
Sandboxed: No

Then I installed from package manager nodejs 17.9.0 and I export PATH=$PATH:/usr/bin/node

Then I tried to add node.js extension.
I followed:
[url]https://code.visualstudio.com/docs/nodejs/working-with-javascript[/url]

I tried to add to launch.json "runtimeExecutable": "node"

    {
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
    {
        "type": "node",
        "request": "launch",
        "name": "Launch Program",
        "skipFiles": [
            "<node_internals>/**"
        ],
        "program": "${workspaceFolder}/GettingStarted/jssample.js",
        "runtimeExecutable": "/usr/bin/node"
    }
]

}

but still got the same message (attached).

brad@toshiba:~$ java -version
java version "19.0.1" 2022-10-18
Java(TM) SE Runtime Environment (build 19.0.1+10-21)
Java HotSpot(TM) 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing)
brad@toshiba:~$ npm version
{
  npm: '8.5.5',
  node: '17.9.0',
  v8: '9.6.180.15-node.16',
  uv: '1.43.0',
  zlib: '1.2.12',
  brotli: '1.0.9',
  ares: '1.18.1',
  modules: '102',
  nghttp2: '1.47.0',
  napi: '8',
  llhttp: '6.0.4',
  openssl: '3.0.2+quic',
  cldr: '40.0',
  icu: '70.1',
  tz: '2021a3',
  unicode: '14.0',m
  ngtcp2: '0.1.0-DEV',
  nghttp3: '0.1.0-DEV'

I tried to install 19.3.0:

I can run the js file from CLI BUT not in VS Code environment.
Not to mention it works just fine on Debian based OSs.

Thanks!

I installed node 19.3.0 but does not make any difference.

I reinstalled VS Code upon node installation but does not make any difference.

I reinstalled from sources VS Code upon node installation and does not make any difference either.


问:
Plot percentage in barplot instead of count plotly
I have a pandas df that looks like

```<code>df= { 'review_year' : [2021,2021,2021,2021,2020, 2020], 'sentiment' :['negative', 'negative', 'negative', 'positive', 'positive', 'positive']}
df= pd.DataFrame(df)
</code>```

when I run this

```<code>import pandas as pd
from matplotlib import pyplot as plt
import plotly
import plotly.express as px

df= { 'review_year' : [2021,2021,2021,2021,2020, 2020], 'sentiment' :['negative', 'negative', 'negative', 'positive', 'positive', 'positive']}
df= pd.DataFrame(df)

fig = px.bar(df, x="sentiment", color="sentiment",
  animation_frame="review_year")
fig.show()
</code>```

I get

In Y axis, instead of the count, I want to see the percentage of 'negative' and 'positive' sentiments for every year.
Can anyone help me?

Body:
I have a pandas df that looks like

df= { 'review_year' : [2021,2021,2021,2021,2020, 2020], 'sentiment' :['negative', 'negative', 'negative', 'positive', 'positive', 'positive']}
df= pd.DataFrame(df)

when I run this

import pandas as pd
from matplotlib import pyplot as plt
import plotly
import plotly.express as px

df= { 'review_year' : [2021,2021,2021,2021,2020, 2020], 'sentiment' :['negative', 'negative', 'negative', 'positive', 'positive', 'positive']}
df= pd.DataFrame(df)

fig = px.bar(df, x="sentiment", color="sentiment",
  animation_frame="review_year")
fig.show()

I get

In Y axis, instead of the count, I want to see the percentage of 'negative' and 'positive' sentiments for every year.
Can anyone help me?


问:
Do you necessarily have to use a method to use 'this' of an object
Why does this in x.prop2 returns Undefined but it works when trying to use it in x.prop3 through a method?

I have been told it's because of difference of scope between prop2 and prop3, but can anyone explain to me in detail the reason for that behavior?

let x = {
  prop1: 10,
  prop2: this.prop1,
  prop3: function () {
    return this.prop1
  }
};

console.log(x.prop2) // undefined
console.log(x.prop3()) // 10
```


问:
telegraf gives different results when testing
Running telegraf 1.24.0

```<code>telegraf -config ./telegraf.conf -test -once 1>output 2>err
</code>```

In my telegraf.conf I have

```<code>[[outputs.file]]
files=["stdout"] #staticfile

[[inputs.tail]]
files=["syslog"]
from_beginning=true
data_format="grok"
grok_patterns=['%{SYSLOGTIMESTAMP:timestamp} %{GREEDYDATA:message}']
</code>```

when I run

```<code>for i in $(seq 1 10); do
    telegraf -config ./telegraf.conf -test -once 1>output 2>err
    grep -c ^tail, output
  done
</code>```

I get different values for tail. Why is that? The "syslog" file is static, its not moving, so I am not sure why the values keep changing when running telegraf

Body:
Running telegraf 1.24.0

telegraf -config ./telegraf.conf -test -once 1>output 2>err

In my telegraf.conf I have

[[outputs.file]]
files=["stdout"] #staticfile

[[inputs.tail]]
files=["syslog"]
from_beginning=true
data_format="grok"
grok_patterns=['%{SYSLOGTIMESTAMP:timestamp} %{GREEDYDATA:message}']

when I run

for i in $(seq 1 10); do
    telegraf -config ./telegraf.conf -test -once 1>output 2>err
    grep -c ^tail, output
  done

I get different values for tail. Why is that? The "syslog" file is static, its not moving, so I am not sure why the values keep changing when running telegraf


问:
io.cucumber.junit.UndefinedStepException: The step ''.... are undefined
Been trying to learn/perform some automated testing using Selenium + JUnit + Cucumber and I've spent hours browsing through the internet trying to resolve this with no success. I've written my feature, steps and runner code and the 'glue' is mapped to the correct package too. However, I run into the topic error when I try to run my Runner.java file.

Project Structure

Feature file:

```<code>Feature: Admin login

Scenario: Logging into Fleet Portal
    Given user navigates to Fleet Portal
    When enter credentials
    Then user had logged
</code>```

Runner file:

```<code>package Runner;

import org.junit.runner.RunWith;
import io.cucumber.junit.*;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "Features"
        ,glue="Steps"
        )

public class TestRunner {}
</code>```

Step file:

```<code>package Steps;

import java.util.ArrayList;
import java.util.Scanner;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

class App {
    private static final WebDriver driver = new ChromeDriver();

    public void myMethod(String flag) {
      System.out.println(flag);
    }
    @Given("user navigates to Fleet Portal")
    public void user_navigates_to_fleet_portal() {
        throw new io.cucumber.java.PendingException();
    }

    @When("enter credentials")
    public void enter_credentials() throws InterruptedException {

        throw new io.cucumber.java.PendingException();
    }
    @Then("user had logged in successfully")
    public void user_had_logged_in_successfully() {
        myMethod("yes");
        throw new io.cucumber.java.PendingException();
        }
}
</code>```

I've tried to take JUnit out of the picture by simply running the feature file as a cucumber test but it still results in the same error, which is weird because the cucumber plugin confirms that the steps are mapped to the features -> feature mapping

POM file

Any and all help is appreciated.

Body:
Been trying to learn/perform some automated testing using Selenium + JUnit + Cucumber and I've spent hours browsing through the internet trying to resolve this with no success. I've written my feature, steps and runner code and the 'glue' is mapped to the correct package too. However, I run into the topic error when I try to run my Runner.java file.

Project Structure

Feature file:

Feature: Admin login

Scenario: Logging into Fleet Portal
    Given user navigates to Fleet Portal
    When enter credentials
    Then user had logged

Runner file:

package Runner;

import org.junit.runner.RunWith;
import io.cucumber.junit.*;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "Features"
        ,glue="Steps"
        )

public class TestRunner {}

Step file:

package Steps;

import java.util.ArrayList;
import java.util.Scanner;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

class App {
    private static final WebDriver driver = new ChromeDriver();

    public void myMethod(String flag) {
      System.out.println(flag);
    }
    @Given("user navigates to Fleet Portal")
    public void user_navigates_to_fleet_portal() {
        throw new io.cucumber.java.PendingException();
    }

    @When("enter credentials")
    public void enter_credentials() throws InterruptedException {

        throw new io.cucumber.java.PendingException();
    }
    @Then("user had logged in successfully")
    public void user_had_logged_in_successfully() {
        myMethod("yes");
        throw new io.cucumber.java.PendingException();
        }
}

I've tried to take JUnit out of the picture by simply running the feature file as a cucumber test but it still results in the same error, which is weird because the cucumber plugin confirms that the steps are mapped to the features -> feature mapping

POM file

Any and all help is appreciated.


问:
python: strange behavior related to class function address, especially when using copy.deepcopy()
Consider the following code:

```<code>class class1:
    def __init__(self):
        self.var = None
        print('class1.__init__() at       %s'%str(hex(id(self))))

    def run(self):
        self.var = 1
        print("func1() address            %s->%s" % (str(hex(id(self))), str(hex(id(self.func1)))))
        self.func1(' directly ')
        dict1 = {
            "func1": self.func1,
        }
        print("func1() address in dict1   %s->%s" % (str(hex(id(self))), str(hex(id(dict1['func1'])))))
        self.var = 2
        dict1['func1']('via dict1 ')
        dict2 = copy.deepcopy(dict1)
        print("func1() address in dict2   %s->%s" % (str(hex(id(self))), str(hex(id(dict2['func1'])))))
        self.var = 3
        dict2['func1']('via dict2 ')

    def func1(self, context):
        print('called func1(%s)   %s->%s, var=%i'%(context, str(hex(id(self))), str(hex(id(self.func1))), self.var))
        print('called func1(%s)   %s->%s, var=%i'%(context, str(hex(id(self))), str(hex(id(self.func1))), self.var))

cl1 = class1()
cl1.run()

</code>```

and result in python 3.10:

```<code>class1.__init__() at       0x1c24355bf10
func1() address            0x1c24355bf10->0x1c24354bb40
called func1( directly )   0x1c24355bf10->0x1c24354bbc0, var=1
called func1( directly )   0x1c24355bf10->0x1c24354bb40, var=1
func1() address in dict1   0x1c24355bf10->0x1c24354bb40
called func1(via dict1 )   0x1c24355bf10->0x1c2435640c0, var=2
called func1(via dict1 )   0x1c24355bf10->0x1c2435640c0, var=2
func1() address in dict2   0x1c24355bf10->0x1c2435640c0
called func1(via dict2 )   0x1c24355bbe0->0x1c243564180, var=2
called func1(via dict2 )   0x1c24355bbe0->0x1c243564180, var=2
</code>```

There are several issues which I don't understand

In some cases getting function address/reference via id() give two different values pic1 though calling them indicates it's the same function in same class

Address of function in dictionary and address of called function differ pic2

Upon making a copy.deepcopy() of dictionary the address of function in new dictionary same as address of called function from bullet-point (2)  (orange on pic) but calling the function via pointer in dictionary indicates that deepcopy cloned the class object as well as dictionary with function pointer - it got different address (yellow on pic) and self.var contains the pre-deepcopy() state (blue on pic) pic3

Body:
Consider the following code:

class class1:
    def __init__(self):
        self.var = None
        print('class1.__init__() at       %s'%str(hex(id(self))))

    def run(self):
        self.var = 1
        print("func1() address            %s->%s" % (str(hex(id(self))), str(hex(id(self.func1)))))
        self.func1(' directly ')
        dict1 = {
            "func1": self.func1,
        }
        print("func1() address in dict1   %s->%s" % (str(hex(id(self))), str(hex(id(dict1['func1'])))))
        self.var = 2
        dict1['func1']('via dict1 ')
        dict2 = copy.deepcopy(dict1)
        print("func1() address in dict2   %s->%s" % (str(hex(id(self))), str(hex(id(dict2['func1'])))))
        self.var = 3
        dict2['func1']('via dict2 ')

    def func1(self, context):
        print('called func1(%s)   %s->%s, var=%i'%(context, str(hex(id(self))), str(hex(id(self.func1))), self.var))
        print('called func1(%s)   %s->%s, var=%i'%(context, str(hex(id(self))), str(hex(id(self.func1))), self.var))

cl1 = class1()
cl1.run()

and result in python 3.10:

class1.__init__() at       0x1c24355bf10
func1() address            0x1c24355bf10->0x1c24354bb40
called func1( directly )   0x1c24355bf10->0x1c24354bbc0, var=1
called func1( directly )   0x1c24355bf10->0x1c24354bb40, var=1
func1() address in dict1   0x1c24355bf10->0x1c24354bb40
called func1(via dict1 )   0x1c24355bf10->0x1c2435640c0, var=2
called func1(via dict1 )   0x1c24355bf10->0x1c2435640c0, var=2
func1() address in dict2   0x1c24355bf10->0x1c2435640c0
called func1(via dict2 )   0x1c24355bbe0->0x1c243564180, var=2
called func1(via dict2 )   0x1c24355bbe0->0x1c243564180, var=2

There are several issues which I don't understand

In some cases getting function address/reference via id() give two different values pic1 though calling them indicates it's the same function in same class

Address of function in dictionary and address of called function differ pic2

Upon making a copy.deepcopy() of dictionary the address of function in new dictionary same as address of called function from bullet-point (2)  (orange on pic) but calling the function via pointer in dictionary indicates that deepcopy cloned the class object as well as dictionary with function pointer - it got different address (yellow on pic) and self.var contains the pre-deepcopy() state (blue on pic) pic3


问:
Allow only Cloudflare IP into Netlify
We use Cloudflare DNS. We setup a CNAME record to Netlify website (mywebsite.netlify.app).
How to allow only cloudflare proxy to connect to mywebsite.netlify.app ?

I would like to avoid the Netlify domain to be requested directly (as we can't delete it).

Title: Allow only Cloudflare IP into Netlify


问:
Multiple CSS scroll-snapping css sliders using javascript
I would like to add multiple sliders using css scroll-snapping to one page of a website. I've been following a fantastic tutorial by Alex Clark, however, when I add more than one slider to a page, the navigation buttons stop working. Is there a way to loop over the sliders using javascript and add the navigation function to multiple sliders?

const slider = document.querySelector("[data-slider]");
const prevButton = document.querySelector("[data-prev]");
const nextButton = document.querySelector("[data-next]");

function slide(direction) {
  let left;
  const { scrollLeft, clientWidth } = slider;

  switch (direction) {
    case "prev":
      left = scrollLeft - clientWidth;
      break;
    case "next":
    default:
      left = scrollLeft + clientWidth;
      break;
  }

  slider.scroll({
    left,
    behavior: "smooth"
  });
}

if (slider && prevButton && nextButton) {
  prevButton.addEventListener("click", () => slide("prev"));
  nextButton.addEventListener("click", () => slide("next"));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Base */

.slider {
  display: flex;
  align-items: center;
  position: relative;
}

.slider__slides {
  max-height: 40vh;
  position: relative;
  display: flex;
  align-items: center;
  gap: 3rem;
  overflow-x: scroll;
  scroll-snap-type: x mandatory;
  overscroll-behavior-x: contain;
}

.slider__slide {
  scroll-snap-align: start;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
}

.slider__slide > img {
  max-width: 100%;
  height: 100%;
  object-fit: contain;
}

/* Navigation */
.slider__nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
  pointer-events: none;
}

.slider__nav > button {
  font-family: sans-serif;
  background: black;
  color: white;
  padding: 1rem;
  transition: all 0.2s ease-in-out;
  pointer-events: initial;
}

.slider__nav > button:hover {
  background: gray;
  cursor: pointer;
}

/* Modifiers */
.slider--fullscreen {
  height: 40vh;
}

.slider--fullscreen .slider__slides {
  max-height: 40vh;
  gap: 0;
}

.slider--fullscreen .slider__slide {
  height: 40vh;
}

.slider--fullscreen .slider__slide img {
  object-fit: cover;
  width: 100%;
  height: 100%;
}</code>```

    <button title="Go to the previous slide" data-prev>
      ←
    </button>
    <button title="Go to the next slide" data-next>
      →
    </button>

    <button title="Go to the previous slide" data-prev>
      ←
    </button>
    <button title="Go to the next slide" data-next>
      →
    </button>

```
</div>
</div>
</p>
``````

Body:
I would like to add multiple sliders using css scroll-snapping to one page of a website. I've been following a fantastic tutorial by Alex Clark, however, when I add more than one slider to a page, the navigation buttons stop working. Is there a way to loop over the sliders using javascript and add the navigation function to multiple sliders?

const slider = document.querySelector("[data-slider]");
const prevButton = document.querySelector("[data-prev]");
const nextButton = document.querySelector("[data-next]");

function slide(direction) {
  let left;
  const { scrollLeft, clientWidth } = slider;

  switch (direction) {
    case "prev":
      left = scrollLeft - clientWidth;
      break;
    case "next":
    default:
      left = scrollLeft + clientWidth;
      break;
  }

  slider.scroll({
    left,
    behavior: "smooth"
  });
}

if (slider && prevButton && nextButton) {
  prevButton.addEventListener("click", () => slide("prev"));
  nextButton.addEventListener("click", () => slide("next"));
}

/* Base */

.slider {
  display: flex;
  align-items: center;
  position: relative;
}

.slider__slides {
  max-height: 40vh;
  position: relative;
  display: flex;
  align-items: center;
  gap: 3rem;
  overflow-x: scroll;
  scroll-snap-type: x mandatory;
  overscroll-behavior-x: contain;
}

.slider__slide {
  scroll-snap-align: start;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
}

.slider__slide > img {
  max-width: 100%;
  height: 100%;
  object-fit: contain;
}

/* Navigation */
.slider__nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
  pointer-events: none;
}

.slider__nav > button {
  font-family: sans-serif;
  background: black;
  color: white;
  padding: 1rem;
  transition: all 0.2s ease-in-out;
  pointer-events: initial;
}

.slider__nav > button:hover {
  background: gray;
  cursor: pointer;
}

/* Modifiers */
.slider--fullscreen {
  height: 40vh;
}

.slider--fullscreen .slider__slides {
  max-height: 40vh;
  gap: 0;
}

.slider--fullscreen .slider__slide {
  height: 40vh;
}

.slider--fullscreen .slider__slide img {
  object-fit: cover;
  width: 100%;
  height: 100%;
}

    <button title="Go to the previous slide" data-prev>
      ←
    </button>
    <button title="Go to the next slide" data-next>
      →
    </button>

    <button title="Go to the previous slide" data-prev>
      ←
    </button>
    <button title="Go to the next slide" data-next>
      →
    </button>


问:
How to add a class to the outermost div tag of my popup modal?
I have created a modal with a parent id of "abandon-cart-message" . The two ways I want someone to dismiss the popup is clicking outside the modal, and clicking the "x" on the top right of the modal. I created an array of those two selectors, and on click i want to add a class of "hidden". However it's not adding the class and I can't understand WHY!

```<code>
        //popup dismissal
        const dismissSelectors = ["#abandon-cart-message .evg-overlay", "#abandon-cart-message .evg-btn-dismissal"];
        Evergage.cashDom(dismissSelectors.join(",")).on("click", () => {
            console.log("I HAVE BEEN CLICKED.");
            const dismissPopup = document.querySelector("#abandon-cart-message");
            dismissPopup.classList.add("hidden");
        });
    }
</code>```

On click, i tried to add class "hidden" on the parent ID of my modal but it is not showing up.

Body:
I have created a modal with a parent id of "abandon-cart-message" . The two ways I want someone to dismiss the popup is clicking outside the modal, and clicking the "x" on the top right of the modal. I created an array of those two selectors, and on click i want to add a class of "hidden". However it's not adding the class and I can't understand WHY!

        //popup dismissal
        const dismissSelectors = ["#abandon-cart-message .evg-overlay", "#abandon-cart-message .evg-btn-dismissal"];
        Evergage.cashDom(dismissSelectors.join(",")).on("click", () => {
            console.log("I HAVE BEEN CLICKED.");
            const dismissPopup = document.querySelector("#abandon-cart-message");
            dismissPopup.classList.add("hidden");
        });
    }

On click, i tried to add class "hidden" on the parent ID of my modal but it is not showing up.


问:
How can I access the Internet through ssh tunnel to flutter app on an Android device?
I had a question about connecting app flutter to ubuntu server through ssh tunnel, how can I establish user internet through this tunnel?

My connection to Ubuntu server is done through the ssh2 package in Flutter, session connection is success


问:
I am trying to implement a substitute teacher in react for a time table it's not working as expected
I have a react app named timetable and in that I have 3 components App.js, timetable.js and substitute-form.js,

//Expected

The basic idea is when I enter the name of a teacher that is absent and select a substitute teacher from the drop down and click create time table I want the new timetable to be created as substitute teacher in place of absent teacher.

//Actual

When I add a name in absent teacher and select a name from substitute teacher drop down and select create time table it's not updating the time table.

```<code>//App.js

import React, { useState } from "react";
import Timetable from "./timetable";
import SubstituteForm from "./substitute-form";

const App = () => {
  const [timetable, setTimetable] = useState([
    {
      time: "8:00 AM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "9:00 AM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "10:00 AM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "11:00 AM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "12:00 PM",
      monday: "Lunch",
      tuesday: "Lunch",
      wednesday: "Lunch",
      thursday: "Lunch",
      friday: "Lunch",
    },
    {
      time: "1:00 PM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "2:00 PM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "3:00 PM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
  ]);

  return (
    <div>
      <Timetable timetable={timetable} />
      <br />
      <SubstituteForm timetable={timetable} setTimetable={setTimetable} />
    </div>
  );
};

export default App;`
</code>```
```<code>//Substitute-form.js

import React from "react";

const SubstituteForm = ({ timetable, setTimetable }) => {
  const handleSubmit = (e) => {
    e.preventDefault();
    const absentTeacher = e.target.absentTeacher.value;
    const substituteTeacher = e.target.substituteTeacher.value;
    setTimetable(
      timetable.map((classPeriod) => {
        const updatedClassPeriod = { ...classPeriod };
        Object.keys(updatedClassPeriod).forEach((key) => {
          if (updatedClassPeriod[key] === absentTeacher) {
            updatedClassPeriod[key] = substituteTeacher;
          }
        });
        return updatedClassPeriod;
      })
    );
  };

  return (
    <form onSubmit={handleSubmit}>
      <label for="absent-teacher">Absent Teacher:</label>
      <input type="text" id="absent-teacher" />
      <br />
      <label for="substitute-teacher">Substitute Teacher:</label>
      <select id="substitute-teacher">
        <option value="Mrs. Smith">Mrs. Smith</option>
        <option value="Mr. Jones">Mr. Jones</option>
        <option value="Ms. Williams">Ms. Williams</option>
      </select>
      <br />
      <button type="submit">Create Timetable</button>
    </form>
  );
};

export default SubstituteForm;

</code>```
```<code>//timetable.js

import React from "react";

const Timetable = ({ timetable }) => {
  return (
    <table>
      <tr>
        <th>Time</th>
        <th>Monday</th>
        <th>Tuesday</th>
        <th>Wednesday</th>
        <th>Thursday</th>
        <th>Friday</th>
      </tr>
      {timetable.map((classPeriod) => (
        <tr>
          <td>{classPeriod.time}</td>
          <td>{classPeriod.monday}</td>
          <td>{classPeriod.tuesday}</td>
          <td>{classPeriod.wednesday}</td>
          <td>{classPeriod.thursday}</td>
          <td>{classPeriod.friday}</td>
        </tr>
      ))}
    </table>
  );
};

export default Timetable;
</code>```

Body:
I have a react app named timetable and in that I have 3 components App.js, timetable.js and substitute-form.js,

//Expected

The basic idea is when I enter the name of a teacher that is absent and select a substitute teacher from the drop down and click create time table I want the new timetable to be created as substitute teacher in place of absent teacher.

//Actual

When I add a name in absent teacher and select a name from substitute teacher drop down and select create time table it's not updating the time table.

//App.js

import React, { useState } from "react";
import Timetable from "./timetable";
import SubstituteForm from "./substitute-form";

const App = () => {
  const [timetable, setTimetable] = useState([
    {
      time: "8:00 AM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "9:00 AM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "10:00 AM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "11:00 AM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "12:00 PM",
      monday: "Lunch",
      tuesday: "Lunch",
      wednesday: "Lunch",
      thursday: "Lunch",
      friday: "Lunch",
    },
    {
      time: "1:00 PM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "2:00 PM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
    {
      time: "3:00 PM",
      monday: "Math",
      tuesday: "Science",
      wednesday: "English",
      thursday: "History",
      friday: "PE",
    },
  ]);

  return (

      <Timetable timetable={timetable} />

      <SubstituteForm timetable={timetable} setTimetable={setTimetable} />

  );
};

export default App;`

//Substitute-form.js

import React from "react";

const SubstituteForm = ({ timetable, setTimetable }) => {
  const handleSubmit = (e) => {
    e.preventDefault();
    const absentTeacher = e.target.absentTeacher.value;
    const substituteTeacher = e.target.substituteTeacher.value;
    setTimetable(
      timetable.map((classPeriod) => {
        const updatedClassPeriod = { ...classPeriod };
        Object.keys(updatedClassPeriod).forEach((key) => {
          if (updatedClassPeriod[key] === absentTeacher) {
            updatedClassPeriod[key] = substituteTeacher;
          }
        });
        return updatedClassPeriod;
      })
    );
  };

  return (
    <form onSubmit={handleSubmit}>
      Absent Teacher:
      <input type="text" id="absent-teacher" />

      Substitute Teacher:
      <select id="substitute-teacher">
        <option value="Mrs. Smith">Mrs. Smith</option>
        <option value="Mr. Jones">Mr. Jones</option>
        <option value="Ms. Williams">Ms. Williams</option>
      </select>

      <button type="submit">Create Timetable</button>
    </form>
  );
};

export default SubstituteForm;

//timetable.js

import React from "react";

const Timetable = ({ timetable }) => {
  return (

        Time
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday

      {timetable.map((classPeriod) => (

          {classPeriod.time}
          {classPeriod.monday}
          {classPeriod.tuesday}
          {classPeriod.wednesday}
          {classPeriod.thursday}
          {classPeriod.friday}

      ))}

  );
};

export default Timetable;


问:
Datatable individual column searching mixing input and select
Referring to the Individual column searching (text inputs) and Individual column searching (select inputs) to use multiple filters on jQuery DataTable, I mixed them up in order to allow text inputs searches on some columns and select inputs searching on others.
It almost works, but select inputs don't work correctly: the first select input on the third column shows values of the first column, the second select input shows the second column, and so on.</p>
```<code>$( document ).ready(function() {
   $('#wbe_table tfoot th.search_th').each( function () {
     var title = $(this).text();
     $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
 } );

  var oTable = $('#wbe_table').DataTable( {
    orderCellsTop: true,
    fixedHeader: true,
    responsive: true,
    lengthChange: true,
    autoWidth: true,
    pageLength: 50,
    order: [[7, "desc"]],
    columnDefs: [
      {
      targets: [4],
      orderable: false
      },
      {
      type: "currency",
      targets: [7,8,9,10]
      },
    ],
    dom: 'Bfrtip',
    buttons: [
      'copy', 'csv', 'excel', 'pdf', 'print'
    ] ,
    //Select input search
    initComplete: function () {
      var api = this.api();
      $('.filterhead', api.table().footer()).each( function (i) {
        var column = api.column(i);
        var select = $('<select><option value=""></option></select>')
          .appendTo( $(this).empty() )
          .on( 'change', function () {
            var val = $.fn.dataTable.util.escapeRegex(
              $(this).val()
            );

            column
              .search( val ? '^'+val+'$' : '', true, false )
              .draw();
          } );

        column.data().unique().sort().each( function ( d, j ) {
          select.append( '<option value="'+d+'">'+d+'</option>' );
        } );
      } );
    }
  });
 // Text input search
 oTable.columns().every( function () {
   var that = this;
   $( 'input', this.footer() ).on( 'keyup change', function () {
     if ( that.search() !== this.value ) {
       that
         .search( this.value )
         .draw();
     }
   } );
 } );
});
</code>```

Body:
Referring to the Individual column searching (text inputs) and Individual column searching (select inputs) to use multiple filters on jQuery DataTable, I mixed them up in order to allow text inputs searches on some columns and select inputs searching on others.
It almost works, but select inputs don't work correctly: the first select input on the third column shows values of the first column, the second select input shows the second column, and so on.

$( document ).ready(function() {
   $('#wbe_table tfoot th.search_th').each( function () {
     var title = $(this).text();
     $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
 } );

  var oTable = $('#wbe_table').DataTable( {
    orderCellsTop: true,
    fixedHeader: true,
    responsive: true,
    lengthChange: true,
    autoWidth: true,
    pageLength: 50,
    order: [[7, "desc"]],
    columnDefs: [
      {
      targets: [4],
      orderable: false
      },
      {
      type: "currency",
      targets: [7,8,9,10]
      },
    ],
    dom: 'Bfrtip',
    buttons: [
      'copy', 'csv', 'excel', 'pdf', 'print'
    ] ,
    //Select input search
    initComplete: function () {
      var api = this.api();
      $('.filterhead', api.table().footer()).each( function (i) {
        var column = api.column(i);
        var select = $('<select><option value=""></option></select>')
          .appendTo( $(this).empty() )
          .on( 'change', function () {
            var val = $.fn.dataTable.util.escapeRegex(
              $(this).val()
            );

            column
              .search( val ? '^'+val+'$' : '', true, false )
              .draw();
          } );

        column.data().unique().sort().each( function ( d, j ) {
          select.append( '<option value="'+d+'">'+d+'</option>' );
        } );
      } );
    }
  });
 // Text input search
 oTable.columns().every( function () {
   var that = this;
   $( 'input', this.footer() ).on( 'keyup change', function () {
     if ( that.search() !== this.value ) {
       that
         .search( this.value )
         .draw();
     }
   } );
 } );
});


问:
How can you control style of menuitem in tinymce 6
In prior versions the styles of menuitems could be adjusted in the creation, 'style' is not used in v6.

I am specifically trying to style menus in a custom plugin menubutton each with their own color.
How can this be adjusted in v6.

for example
{ type: 'menuitem', text: 'blue item', style: 'background:blue;', onAction: function() { ... }

style is ignored


问:
ARPACK error -9999: Could not build an Arnoldi factorization
I am trying to solve a generalized eigenvalue problem. For problem that I have in mind, I would like to use scipy.sparse.linalg.eigsh. I have written a MWE

```<code>import numpy as np

from scipy.linalg import eigh
from scipy.sparse.linalg import eigsh, LinearOperator

n = 3
v = np.random.random(n)
A = np.diag(np.arange(n))
M = np.eye(n)

Aop = LinearOperator((n,n), matvec=lambda v: A@v)
Mop = LinearOperator((n,n), matvec=lambda v: M@v)

eig, vec = eigh(A, M)
print(eig)
print(vec)
eig, vec = eigsh(Aop, k=1, M=Mop, v0=v, which="LA")
</code>```

The output when running the script

```<code>[0. 1. 2.]
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
Traceback (most recent call last):
  File "/home/anian/Documents/comb-efficient/mps_python/eig/gevp.py", line 17, in <module>
    eig, vec = eigsh(Aop, k=1, M=Mop, v0=v, which="LA")
  File "/usr/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/arpack.py", line 1689, in eigsh
    params.iterate()
  File "/usr/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/arpack.py", line 571, in iterate
    raise ArpackError(self.info, infodict=self.iterate_infodict)
scipy.sparse.linalg._eigen.arpack.arpack.ArpackError: ARPACK error -9999: Could not build an Arnoldi factorization. IPARAM(5) returns the size of the current Arnoldi factorization. The user is advised to check that enough workspace and array storage has been allocated.
</code>```

I am using Python 3.10.8 and Scipy 1.9.3. Any advice how to solve this? I know I can simply use scipy.linalg.eigh, but my actual problem requires the use of LinearOperator.
If I set M=None in the line of eigsh, the script runs fine.

EDIT

Interestingly, if I specify the sigma keyword, it seems to run:

```<code>eig, vec = eigsh(Aop, k=1, M=Mop, v0=v, which="LA", sigma=1.2)
</code>```

It is a bit unsatisfactory, though, as it requires having a good guess of an eigenvalue.

Body:
I am trying to solve a generalized eigenvalue problem. For problem that I have in mind, I would like to use scipy.sparse.linalg.eigsh. I have written a MWE

import numpy as np

from scipy.linalg import eigh
from scipy.sparse.linalg import eigsh, LinearOperator

n = 3
v = np.random.random(n)
A = np.diag(np.arange(n))
M = np.eye(n)

Aop = LinearOperator((n,n), matvec=lambda v: A@v)
Mop = LinearOperator((n,n), matvec=lambda v: M@v)

eig, vec = eigh(A, M)
print(eig)
print(vec)
eig, vec = eigsh(Aop, k=1, M=Mop, v0=v, which="LA")

The output when running the script

[0. 1. 2.]
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
Traceback (most recent call last):
  File "/home/anian/Documents/comb-efficient/mps_python/eig/gevp.py", line 17, in <module>
    eig, vec = eigsh(Aop, k=1, M=Mop, v0=v, which="LA")
  File "/usr/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/arpack.py", line 1689, in eigsh
    params.iterate()
  File "/usr/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/arpack.py", line 571, in iterate
    raise ArpackError(self.info, infodict=self.iterate_infodict)
scipy.sparse.linalg._eigen.arpack.arpack.ArpackError: ARPACK error -9999: Could not build an Arnoldi factorization. IPARAM(5) returns the size of the current Arnoldi factorization. The user is advised to check that enough workspace and array storage has been allocated.

I am using Python 3.10.8 and Scipy 1.9.3. Any advice how to solve this? I know I can simply use scipy.linalg.eigh, but my actual problem requires the use of LinearOperator.
If I set M=None in the line of eigsh, the script runs fine.

EDIT

Interestingly, if I specify the sigma keyword, it seems to run:

eig, vec = eigsh(Aop, k=1, M=Mop, v0=v, which="LA", sigma=1.2)

It is a bit unsatisfactory, though, as it requires having a good guess of an eigenvalue.


问:
Do I need a service principal for my MS when using Azure Openshift(ARO)?
Hello fellow Developers,

Our company is planning to use ARO. I'm searching for documents explaining how to deploy an microservice(MS) that will use resources from Azure, like Cosmos(pgsl, mysql, nosql), redis, key vault.. and so on.

For key vault I sort of figured out, I mean, we could use CSI Driver+Azure Provider together with a Service Principal(mainly because ARO does not support managed identity) to query for keys,secrets and certs from Azure.

But what about the other services. Do I need a SPN for each MS I will code or they will share the same SPN as ARO?

Or maybe I'm going too far, and maybe there's no such thing as SPN for MS(PODs running in the ARO cluster), only Key vault is an exception. I mean, I would only need a db user and password if using an cosmos db resource.

PS. Our company has strict policies, so the "Ensure Allow access to Azure services" is not an option. I believe we would be creating a DB with a private endpoint<->ARO then.

thx!


问:
Wordpress installing supabase and imports
I am trying to connect with my Supabase API and following the docs

Supabase DOCS

But everytime I write down:

```<code>import { createClient } from '@supabase/supabase-js'
</code>```

I get an error "import declarations may only appear at top level of a module"

So is it even possible to use the npm install @supabase/supabase-js in my child theme and then uploading it?

Or what else is going wrong here?

I tried typing type="module" when trying it with the CDN link but still the same error.

Body:
I am trying to connect with my Supabase API and following the docs

Supabase DOCS

But everytime I write down:

import { createClient } from '@supabase/supabase-js'

I get an error "import declarations may only appear at top level of a module"

So is it even possible to use the npm install @supabase/supabase-js in my child theme and then uploading it?

Or what else is going wrong here?

I tried typing type="module" when trying it with the CDN link but still the same error.


问:
Is there any way to reset a device's connection to APNS, so I can simulate the behavior of installing an app on a new device?
I would like to be able to test/debug my app as if a new user was just downloading the app. Moreover, I would like to do this on my device which is a device where I have installed the app to before.

Specifically, I encountered this issue when working with Firebase phone number authentication. After I uploaded a new build to TestFlight, new users who hadn't downloaded the app before were encountering the issue where firebase failed to send the OTP code. However, when I tried to reproduce this behavior on my phone or any phone that had downloaded the app before, the phone authentication worked seamlessly.

I believe this is an issue related to the APNS token that is used for each device. I'm assuming that once Firebase establishes a device's connection withs APNS, regardless if the app is deleted, the app won't try to re-establish connection with APNS as long as the app is on the same device. I have no idea how to reset this device connection to APNS. Moving forward, before uploading a build to the public, I would like to be able to test my app on my device acting like a new user/device.

What can I do to make this happen besides factory resetting my phone?

I tried deleting the app and reinstalling. I expected this to cause the "failed to send OTP code" bug in my device similar to what all the new device installs were seeing, but instead phone authentication worked seamlessly on my phone and I wasn't able to reproduce the bug on my end. I also tried deleting the account from the firebase console along with deleting the app from my phone. This also failed to reproduce the bug.


问:
react-hotkeys: How to ignore a keypress when another key is being held?
I'm using react-hotkeys, and one of my keys is the C key, which calls a function on the page.

If I use Ctrl-C to try to copy something off the page, the C function is called when I don't want it to be.

I can't find anything in the documentation that covers this scenario, unless I'm misinterpreting any of it. The git page recommends asking questions like these on their Gitter page, however nobody has answered a question there for almost 4 years!

Is it possible to only trigger the hotkey if the keypress is by itself?


问:
Split large flat file into multiple files with groupby particular field and store diff group of 500 records in diff files
I have a large flat file like

```<code>Name Id
Abc 123
Fgg 345
Ghj 123
Vhg 456
Fhh 678
Hjj 345
Hjf 456
Ijk 789
</code>```

For ex, I want to split above file into multiple flat files based on groupby Id and each file should contain only 2 groups of records I.etle

file1

```<code>Abc 123
Ghj 123
Fgg 345
Hjj 345
</code>```

file2

```<code>Vhg 456
Hjf 456
Fhh 678
</code>```

file3

```<code>Ijk 789
</code>```

And I need to send all above split files to camel file component

I am able to group records based on id using java8 but unable to store particular count of groups to diff files

Body:
I have a large flat file like

Name Id
Abc 123
Fgg 345
Ghj 123
Vhg 456
Fhh 678
Hjj 345
Hjf 456
Ijk 789

For ex, I want to split above file into multiple flat files based on groupby Id and each file should contain only 2 groups of records I.etle

file1

Abc 123
Ghj 123
Fgg 345
Hjj 345

file2

Vhg 456
Hjf 456
Fhh 678

file3

Ijk 789

And I need to send all above split files to camel file component

I am able to group records based on id using java8 but unable to store particular count of groups to diff files