问:
DebounceTime after first value in RxJS
I need a specific behavior that I can't get with the RxJS operators. The closest would be to use DebounceTime only for values entered after the first one, but I can't find a way to do it. I have also tried with ThrottleTime but it is not exactly what I am looking for, since it launches intermediate calls, and I only want one at the beginning that is instantaneous, and another at the end, nothing else.

ThrottleTime

```<code>throttleTime(12 ticks, { leading: true, trailing: true })

source:             --0--1-----2--3----4--5-6---7------------8-------9---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~]--------
output:             --0-----------3-----------6-----------7-----------9--------

source_2:           --0--------1------------------2--------------3---4---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~]---[~~~~~~~~~~~]--[~~~~~~~~~~~I~
output_2:           --0-----------1---------------2--------------3-----------4-
</code>```

DebounceTime

```<code>debounceTime(500)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             -----------1--------3--------------------------------13---------
</code>```

What I want

```<code>debounceTimeAfterFirst(500) (?)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             --0--------1--3------------4-------------------------13---------
</code>```

As you see, the debounce time is activated when a new value is entered. If the debounce time passes and any new value has been entered, it stops the listening the debounceTime action and waits to start a new one.

Edit: I forgot to comment that this must be integrated with NgRx’s Effects, so it must be a continuous stream that mustn't be completed. Terminating it would probably cause it to stop listening for dispatched actions.

答:
I would use a throttle combined with a debounceTime:

throttle: from Documentation Emit value on the leading edge of an interval, but suppress new values until durationSelector has completed.

debounceTime: from Documentation Discard emitted values that take less than the specified time between output.

I would use a throttle stream to get the raising edge (the first emission) and then the debounce stream would give us the falling edge.

const source = fromEvent(document.getElementsByTagName('input'), 'keyup').pipe(
  pluck('target', 'value')
);

const debounced = source.pipe(
  debounceTime(4000),
  map((v) => `[d] ${v}`)
);

const effect = merge(
  source.pipe(
    throttle((val) => debounced),
    map((v) => `[t] ${v}`)
  ),
  debounced
);

effect.subscribe(console.log);
```
<p>See RxJS StackBlitz with the console open to see the values changing.</p>
<p>I prepared the setup to adapt it to <strong>NgRx</strong> which you mention. The effect I got working is:</p>
<pre class="lang-js prettyprint-override"><code>@Injectable({ providedIn: 'root' })
export class FooEffects {
  switchLight$ = createEffect(() => {
    const source = this.actions$.pipe(
      ofType('[App] Switch Light'),
      pluck('onOrOff'),
      share()
    );
    const debounced = source.pipe(debounceTime(1000), share());
    return merge(source.pipe(throttle((val) => debounced)), debounced).pipe(
      map((onOrOff) => SetLightStatus({ onOrOff }))
    );
  });

  constructor(private actions$: Actions) {}
}

</code>```

See NgRx StackBlitz with the proposed solution working in the context of an Angular NgRx application.

share: This operator prevents the downstream paths to simultaneously fetch the data from all the way up the chain, instead they grab it from the point where you place share.

I also tried to adapt @martin's connect() approach. But I don't know how @martin would "reset" the system so that after a long time if a new source value is emitted would not debounce it just in the same manner as you first run it, @martin, feel free to fork it and tweak it to make it work, I'm curious about your approach, which is very smart. I didn't know about connect().

@avicarpio give it a go on your application and let us know how it goes :)

Title: DebounceTime after first value in RxJS

Body:
I need a specific behavior that I can't get with the RxJS operators. The closest would be to use DebounceTime only for values entered after the first one, but I can't find a way to do it. I have also tried with ThrottleTime but it is not exactly what I am looking for, since it launches intermediate calls, and I only want one at the beginning that is instantaneous, and another at the end, nothing else.

ThrottleTime

throttleTime(12 ticks, { leading: true, trailing: true })

source:             --0--1-----2--3----4--5-6---7------------8-------9---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~]--------
output:             --0-----------3-----------6-----------7-----------9--------

source_2:           --0--------1------------------2--------------3---4---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~]---[~~~~~~~~~~~]--[~~~~~~~~~~~I~
output_2:           --0-----------1---------------2--------------3-----------4-

DebounceTime

debounceTime(500)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             -----------1--------3--------------------------------13---------

What I want

debounceTimeAfterFirst(500) (?)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             --0--------1--3------------4-------------------------13---------

As you see, the debounce time is activated when a new value is entered. If the debounce time passes and any new value has been entered, it stops the listening the debounceTime action and waits to start a new one.

Edit: I forgot to comment that this must be integrated with NgRx’s Effects, so it must be a continuous stream that mustn't be completed. Terminating it would probably cause it to stop listening for dispatched actions.

Body:
I would use a throttle combined with a debounceTime:

throttle: from Documentation Emit value on the leading edge of an interval, but suppress new values until durationSelector has completed.

debounceTime: from Documentation Discard emitted values that take less than the specified time between output.

I would use a throttle stream to get the raising edge (the first emission) and then the debounce stream would give us the falling edge.

const source = fromEvent(document.getElementsByTagName('input'), 'keyup').pipe(
  pluck('target', 'value')
);

const debounced = source.pipe(
  debounceTime(4000),
  map((v) => `[d] ${v}`)
);

const effect = merge(
  source.pipe(
    throttle((val) => debounced),
    map((v) => `[t] ${v}`)
  ),
  debounced
);

effect.subscribe(console.log);

See RxJS StackBlitz with the console open to see the values changing.

I prepared the setup to adapt it to NgRx which you mention. The effect I got working is:

@Injectable({ providedIn: 'root' })
export class FooEffects {
  switchLight$ = createEffect(() => {
    const source = this.actions$.pipe(
      ofType('[App] Switch Light'),
      pluck('onOrOff'),
      share()
    );
    const debounced = source.pipe(debounceTime(1000), share());
    return merge(source.pipe(throttle((val) => debounced)), debounced).pipe(
      map((onOrOff) => SetLightStatus({ onOrOff }))
    );
  });

  constructor(private actions$: Actions) {}
}

See NgRx StackBlitz with the proposed solution working in the context of an Angular NgRx application.

share: This operator prevents the downstream paths to simultaneously fetch the data from all the way up the chain, instead they grab it from the point where you place share.

I also tried to adapt @martin's connect() approach. But I don't know how @martin would "reset" the system so that after a long time if a new source value is emitted would not debounce it just in the same manner as you first run it, @martin, feel free to fork it and tweak it to make it work, I'm curious about your approach, which is very smart. I didn't know about connect().

@avicarpio give it a go on your application and let us know how it goes :)


来源: stackexchange

问:
Google Sheets - Show text in cell based on 3 other cells - 1: Not blank, 2+3: Yes/No
I'd like my output cell to show "Success" / "Not quite there" based on 3 cells:

Blank / not blank

Yes / No

Yes / No

My issue is with combining the "isblank" in the "IF".

The below formula is the closest I've gotten and it's not working -

```<code>=(if(and(E3<>,F3="Yes",G3="Yes"),"Success!","Not quite there"))
</code>```

Would love your advice!

答:
try:

```<code>=IF((E3="")*(F3="yes")*(G3="yes"); "Success!"; "Not quite there")
</code>```

or:

```<code>=IF((E3<>"")*(F3="yes")*(G3="yes"); "Success!"; "Not quite there")
</code>```

for array use:

```<code>=ARRAYFORMULA(IF((E3:E="")*(F3:F="yes")*(G3:G="yes"); "Success!"; "Not quite there"))
</code>```

if you need OR logic replace * with +

example:

```<code>=IF((E3="")*((F3="yes")+(G3="yes")); "Success!"; "Not quite there")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like my output cell to show "Success" / "Not quite there" based on 3 cells:

Blank / not blank

Yes / No

Yes / No

My issue is with combining the "isblank" in the "IF".

The below formula is the closest I've gotten and it's not working -

=(if(and(E3<>,F3="Yes",G3="Yes"),"Success!","Not quite there"))

Would love your advice!

Body:
try:

=IF((E3="")*(F3="yes")*(G3="yes"); "Success!"; "Not quite there")

or:

=IF((E3<>"")*(F3="yes")*(G3="yes"); "Success!"; "Not quite there")

for array use:

=ARRAYFORMULA(IF((E3:E="")*(F3:F="yes")*(G3:G="yes"); "Success!"; "Not quite there"))

if you need OR logic replace * with +

example:

=IF((E3="")*((F3="yes")+(G3="yes")); "Success!"; "Not quite there")


问:
C# get string out of DataTable and send it via tcp
im trying to get an string out of a PostgreSQL database and send it via TCP to another client.

```<code>string dataTable = Database.DtConvertToString(Database.SelectData("SELECT username FROM accounts WHERE user_id = 3"));
</code>```

should give me the actual username but it just gives me the name of the column "username"

The method :

```<code>public static string DtConvertToString(DataTable dt)
        {
            string rw = "";
            StringBuilder builder = new StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dr.Table.Columns)
                {
                    rw = dc.ToString();
                    if (rw.Contains(",")) rw = "\"" + rw + "\"";
                    builder.Append(rw + ",");
                }
                builder.Append(Environment.NewLine);
            }
            return builder.ToString();
        }
</code>```

Can you tell me what's wrong with my thinking?

答:
You're making this way too complicated:

```<code>string dataTable = Database.SelectData("SELECT username FROM accounts WHERE user_id = 3").Rows[0]["username"].ToString();
</code>```

If you really want to preserve the DtConvertToString() method, it should look more like this:

```<code>public static string DtConvertToString(DataTable dt, bool showHeaders = true)
{
    StringBuilder result = new StringBuilder();
    if (showHeaders)
    {
        var delimiter = "";
        foreach(var c in dt.Columns)
        {
           var colName = c.ColumnName;
           if (colName.Contains(","))  colName = $"\"{colName}\"";
           result.Append(delimiter).Append(colName);
           delimiter = ",";
        }
        result.AppendLine();
    }

    for (int r = 0;i<dt.Rows.Count;r++)
    {
        var row = dt.Rows[r].ItemArray;
        var delimiter = "";
        foreach(var col in row)
        {
            if (col.Contains(",")) col = $"\"{col}\"";
            result.Append(delimiter).Append(col);
            delimiter = ",";
        }
        result.AppendLine();
    }
    return result.ToString();
}
</code>```

Additionally, I'm very concerned about the SelectData() method. Code like this tends to force you to write code with HUGE GAPING SQL INJECTION VULNERABILITIES... the kind of thing where a year from now you finally find out your app was hacked six months ago, all your user data was leaked to the dark web, and your internal systems are now being held for a bitcoin ransom.

Body:
im trying to get an string out of a PostgreSQL database and send it via TCP to another client.

string dataTable = Database.DtConvertToString(Database.SelectData("SELECT username FROM accounts WHERE user_id = 3"));

should give me the actual username but it just gives me the name of the column "username"

The method :

public static string DtConvertToString(DataTable dt)
        {
            string rw = "";
            StringBuilder builder = new StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dr.Table.Columns)
                {
                    rw = dc.ToString();
                    if (rw.Contains(",")) rw = "\"" + rw + "\"";
                    builder.Append(rw + ",");
                }
                builder.Append(Environment.NewLine);
            }
            return builder.ToString();
        }

Can you tell me what's wrong with my thinking?

Body:
You're making this way too complicated:

string dataTable = Database.SelectData("SELECT username FROM accounts WHERE user_id = 3").Rows[0]["username"].ToString();

If you really want to preserve the DtConvertToString() method, it should look more like this:

public static string DtConvertToString(DataTable dt, bool showHeaders = true)
{
    StringBuilder result = new StringBuilder();
    if (showHeaders)
    {
        var delimiter = "";
        foreach(var c in dt.Columns)
        {
           var colName = c.ColumnName;
           if (colName.Contains(","))  colName = $"\"{colName}\"";
           result.Append(delimiter).Append(colName);
           delimiter = ",";
        }
        result.AppendLine();
    }

    for (int r = 0;i<dt.Rows.Count;r++)
    {
        var row = dt.Rows[r].ItemArray;
        var delimiter = "";
        foreach(var col in row)
        {
            if (col.Contains(",")) col = $"\"{col}\"";
            result.Append(delimiter).Append(col);
            delimiter = ",";
        }
        result.AppendLine();
    }
    return result.ToString();
}

Additionally, I'm very concerned about the SelectData() method. Code like this tends to force you to write code with HUGE GAPING SQL INJECTION VULNERABILITIES... the kind of thing where a year from now you finally find out your app was hacked six months ago, all your user data was leaked to the dark web, and your internal systems are now being held for a bitcoin ransom.


问:
How do I parameterize test cases in TypeScript unit tests?
I have a simple passing unit test:

```<code>describe("Example", () => {
    it("Return digits or empty string", () => {
        let actual = SmokeTest.ProblemOne("1");
        assert.equal(actual, "1");
    })
})
</code>```

I now wish to test many other cases (empty string, more complex inputs and edge-cases). I have read about how to implement fixtures in TypeScript but this seems like overkill for an array of test-input, expected-output values.

What is the idiomatic way to define such an array in TypeScript / Mocha?

答:
You can just make a function that you can reuse.

```<code>function assertProblemOne(input: string, expected: string): void {
    let actual = SmokeTest.ProblemOne(input);
    assert.equal(expected, actual);
}

describe("Example", () => {
    it("Return digits or empty string", () => {
        assertProblemOne("input here", "expected result here")
    })
})
</code>```

However, I'm not sure that's really much better than simply.

```<code>assert.equal(SmokeTest.ProblemOne("1"), "1");
</code>```

The only thing worse than debugging your code is debugging your tests. So unless there is a large amount of code that is shared between tests, I would recommend keep the code that runs in each tests as structurally simple as possible.

Body:
I have a simple passing unit test:

describe("Example", () => {
    it("Return digits or empty string", () => {
        let actual = SmokeTest.ProblemOne("1");
        assert.equal(actual, "1");
    })
})

I now wish to test many other cases (empty string, more complex inputs and edge-cases). I have read about how to implement fixtures in TypeScript but this seems like overkill for an array of test-input, expected-output values.

What is the idiomatic way to define such an array in TypeScript / Mocha?

Body:
You can just make a function that you can reuse.

function assertProblemOne(input: string, expected: string): void {
    let actual = SmokeTest.ProblemOne(input);
    assert.equal(expected, actual);
}

describe("Example", () => {
    it("Return digits or empty string", () => {
        assertProblemOne("input here", "expected result here")
    })
})

However, I'm not sure that's really much better than simply.

assert.equal(SmokeTest.ProblemOne("1"), "1");

The only thing worse than debugging your code is debugging your tests. So unless there is a large amount of code that is shared between tests, I would recommend keep the code that runs in each tests as structurally simple as possible.


问:
SETX set environment variables from a file
I want to set some environment variables that are specified in a file.
Using setx works fine for one environment at a time, but how can I pipe a file with the below contents

```<code>FOO bar
BAR foo
</code>```

I was thinking something like this

```<code>setx < cat envvars.txt
</code>```

but of course it doesn't work.

答:
Slight modification to the accepted answer if you created file.txt using:

SET >> file.txt

Get-Content file.txt | Foreach-Object {SETX $_.split("=")}

ContentLicense: CC BY-SA 3.0

Body:
I want to set some environment variables that are specified in a file.
Using setx works fine for one environment at a time, but how can I pipe a file with the below contents

FOO bar
BAR foo

I was thinking something like this

setx < cat envvars.txt

but of course it doesn't work.


问:
How to disable simultaneous clicks on multiple items in Jetpack Compose List / Column / Row (out of the box debounce?)
I have implemented a column of buttons in jetpack compose. We realized it is possible to click multiple items at once (with multiple fingers for example), and we would like to disable this feature.

Is there an out of the box way to disable multiple simultaneous clicks on children composables by using a parent column modifier?

Here is an example of the current state of my ui, notice there are two selected items and two unselected items.

Here is some code of how it is implemented (stripped down)

```<code>Column(
    modifier = modifier
            .fillMaxSize()
            .verticalScroll(nestedScrollParams.childScrollState),
    ) {
        viewDataList.forEachIndexed { index, viewData ->
            Row(modifier = modifier.fillMaxWidth()
                        .height(dimensionResource(id = 48.dp)
                        .background(colorResource(id = R.color.large_button_background))
                        .clickable { onClick(viewData) },
                              verticalAlignment = Alignment.CenterVertically
    ) {
        //Internal composables, etc
    }
}
</code>```

答:
Here is my solution.

It's based on https://stackoverflow.com/a/69914674/7011814
by I don't use GlobalScope (here is an explanation why) and I don't use MutableStateFlow as well (because its combination with GlobalScope may cause a potential memory leak).

Here is a head stone of the solution:

```<code>@OptIn(FlowPreview::class)
@Composable
fun <T>multipleEventsCutter(
    content: @Composable (MultipleEventsCutterManager) -> T
) : T {
    val debounceState = remember {
        MutableSharedFlow<() -> Unit>(
            replay = 0,
            extraBufferCapacity = 1,
            onBufferOverflow = BufferOverflow.DROP_OLDEST
        )
    }

    val result = content(
        object : MultipleEventsCutterManager {
            override fun processEvent(event: () -> Unit) {
                debounceState.tryEmit(event)
            }
        }
    )

    LaunchedEffect(true) {
        debounceState
            .debounce(CLICK_COLLAPSING_INTERVAL)
            .collect { onClick ->
                onClick.invoke()
            }
    }

    return result
}

@OptIn(FlowPreview::class)
@Composable
fun MultipleEventsCutter(
    content: @Composable (MultipleEventsCutterManager) -> Unit
) {
    multipleEventsCutter(content)
}
</code>```

The first function can be used as a wrapper around your code like this:

```<code>    MultipleEventsCutter { multipleEventsCutterManager ->
        Button(
            onClick = { multipleClicksCutter.processEvent(onClick) },
            ...
        ) {
           ...
        }
    }
</code>```

And you can use the second one to create your own modifier, like next one:

```<code>fun Modifier.clickableSingle(
    enabled: Boolean = true,
    onClickLabel: String? = null,
    role: Role? = null,
    onClick: () -> Unit
) = composed(
    inspectorInfo = debugInspectorInfo {
        name = "clickable"
        properties["enabled"] = enabled
        properties["onClickLabel"] = onClickLabel
        properties["role"] = role
        properties["onClick"] = onClick
    }
) {
    multipleEventsCutter { manager ->
        Modifier.clickable(
            enabled = enabled,
            onClickLabel = onClickLabel,
            onClick = { manager.processEvent { onClick() } },
            role = role,
            indication = LocalIndication.current,
            interactionSource = remember { MutableInteractionSource() }
        )
    }
}
</code>```

Body:
I have implemented a column of buttons in jetpack compose. We realized it is possible to click multiple items at once (with multiple fingers for example), and we would like to disable this feature.

Is there an out of the box way to disable multiple simultaneous clicks on children composables by using a parent column modifier?

Here is an example of the current state of my ui, notice there are two selected items and two unselected items.

Here is some code of how it is implemented (stripped down)

Column(
    modifier = modifier
            .fillMaxSize()
            .verticalScroll(nestedScrollParams.childScrollState),
    ) {
        viewDataList.forEachIndexed { index, viewData ->
            Row(modifier = modifier.fillMaxWidth()
                        .height(dimensionResource(id = 48.dp)
                        .background(colorResource(id = R.color.large_button_background))
                        .clickable { onClick(viewData) },
                              verticalAlignment = Alignment.CenterVertically
    ) {
        //Internal composables, etc
    }
}

Body:
Here is my solution.

It's based on https://stackoverflow.com/a/69914674/7011814
by I don't use GlobalScope (here is an explanation why) and I don't use MutableStateFlow as well (because its combination with GlobalScope may cause a potential memory leak).

Here is a head stone of the solution:

@OptIn(FlowPreview::class)
@Composable
fun <T>multipleEventsCutter(
    content: @Composable (MultipleEventsCutterManager) -> T
) : T {
    val debounceState = remember {
        MutableSharedFlow<() -> Unit>(
            replay = 0,
            extraBufferCapacity = 1,
            onBufferOverflow = BufferOverflow.DROP_OLDEST
        )
    }

    val result = content(
        object : MultipleEventsCutterManager {
            override fun processEvent(event: () -> Unit) {
                debounceState.tryEmit(event)
            }
        }
    )

    LaunchedEffect(true) {
        debounceState
            .debounce(CLICK_COLLAPSING_INTERVAL)
            .collect { onClick ->
                onClick.invoke()
            }
    }

    return result
}

@OptIn(FlowPreview::class)
@Composable
fun MultipleEventsCutter(
    content: @Composable (MultipleEventsCutterManager) -> Unit
) {
    multipleEventsCutter(content)
}

The first function can be used as a wrapper around your code like this:

    MultipleEventsCutter { multipleEventsCutterManager ->
        Button(
            onClick = { multipleClicksCutter.processEvent(onClick) },
            ...
        ) {
           ...
        }
    }

And you can use the second one to create your own modifier, like next one:

fun Modifier.clickableSingle(
    enabled: Boolean = true,
    onClickLabel: String? = null,
    role: Role? = null,
    onClick: () -> Unit
) = composed(
    inspectorInfo = debugInspectorInfo {
        name = "clickable"
        properties["enabled"] = enabled
        properties["onClickLabel"] = onClickLabel
        properties["role"] = role
        properties["onClick"] = onClick
    }
) {
    multipleEventsCutter { manager ->
        Modifier.clickable(
            enabled = enabled,
            onClickLabel = onClickLabel,
            onClick = { manager.processEvent { onClick() } },
            role = role,
            indication = LocalIndication.current,
            interactionSource = remember { MutableInteractionSource() }
        )
    }
}


问:
AttributeError: 'NoneType' object has no attribute 'clicked' again
Hi can anyone help me for this problem AttributeError: 'NoneType' object has no attribute 'clicked'

my code is :

```<code>import sys
from PyQt5.QtWidgets import *

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(500,250,300,400)
        self.setWindowTitle("SMURF")
        self.UI()
        self.show()
    def UI(self):
        self.text=QLabel("hi bitxg",self).move(150,100)
        b1=QPushButton("B1",self).move(130,120)
        b2=QPushButton("B2",self).move(170,120)
        b1.clicked.connect(self.b1f)
        b2.clicked.connect(self.b2f)
    def b1f(self):
        self.text.setText("FIRST")
    def b2f(self):
        self.text.setText("SECOND")

App=QApplication(sys.argv)
window=Window()
sys.exit(App.exec_())
</code>```

答:
You'll want to split this up:

```<code>b1=QPushButton("B1",self).move(130,120)
b2=QPushButton("B2",self).move(170,120)
</code>```

Becomes:

```<code>b1=QPushButton("B1",self)
b1.move(130,120)

b2=QPushButton("B2",self)
b2.move(170,120)
</code>```

Currently, you are instantiating an anonymous QPushButton object, and then binding the object returned by calling that anonymous object's move method to b1 and b2, which will be None.

Body:
Hi can anyone help me for this problem AttributeError: 'NoneType' object has no attribute 'clicked'

my code is :

import sys
from PyQt5.QtWidgets import *

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(500,250,300,400)
        self.setWindowTitle("SMURF")
        self.UI()
        self.show()
    def UI(self):
        self.text=QLabel("hi bitxg",self).move(150,100)
        b1=QPushButton("B1",self).move(130,120)
        b2=QPushButton("B2",self).move(170,120)
        b1.clicked.connect(self.b1f)
        b2.clicked.connect(self.b2f)
    def b1f(self):
        self.text.setText("FIRST")
    def b2f(self):
        self.text.setText("SECOND")

App=QApplication(sys.argv)
window=Window()
sys.exit(App.exec_())

Body:
You'll want to split this up:

b1=QPushButton("B1",self).move(130,120)
b2=QPushButton("B2",self).move(170,120)

Becomes:

b1=QPushButton("B1",self)
b1.move(130,120)

b2=QPushButton("B2",self)
b2.move(170,120)

Currently, you are instantiating an anonymous QPushButton object, and then binding the object returned by calling that anonymous object's move method to b1 and b2, which will be None.


问:
Using the lerp function (Processing) to change position
+++ EDIT +++

I have a grid of individual rectangles. Now I want to move each of the individual rectangles with the Lerp Function to a new position (currently MouseX, MouseY). So far I only manage to lerp the grid as a whole – with an unwanted distorsion... this is probably due to the translate(); and the bracket from PushMatrix(); PopMatrix();?

Would I have to build the grid completely differently to make each of the individual rectangles flow to the mouse pointer?
Or is lerp(); just the wrong function to do this?

This is how far I have come so far:

```<code>float size;
float pixel;
float lx;
float ly;

void setup() {
  size(600, 600);
  pixel = 100;
  size = width/pixel;
  rectMode(CENTER);
}

void draw() {
  background(0);
  //DRAW THE GRID

  lx = 0;
  ly = 0;

  for (int y = 0; y < pixel; y++) {
    ly = lerp(ly, mouseY, 0.05);
    for (int x = 0; x < pixel; x++) {
      lx = lerp(lx, mouseX, 0.05);
      pushMatrix();
      translate(size/2, size/2);
      translate(x*size, y*size);
      rotate(radians(45));
      fill(255);
      noStroke();
      rect(lx, ly, size, size);
      popMatrix();
    }
  }
}
</code>```

Is this even possible with the way I built the grid?

答:
Your lerp function is used to calculate steps between two positions, so you want the starting position and ending position for your transition, and you will be calling lerp multiple times to recalculate each step.  You can think of lerp as calculating the percentage of the distance between the source and destination as you change the last parameter from 0.0 to 1.0 in incremental steps.</p>
```<code>rectY=?;
rectX=?; // Replace the '?' marks with the left and top starting positions of your rectangle
for (int step=1; step<=20; step++) {
    lx = lerp(rectX, mouseX, 0.05 * step);
    ly = lerp(rectY, mouseY, 0.05 * step);
    ...
}
</code>```

Body:
+++ EDIT +++

I have a grid of individual rectangles. Now I want to move each of the individual rectangles with the Lerp Function to a new position (currently MouseX, MouseY). So far I only manage to lerp the grid as a whole – with an unwanted distorsion... this is probably due to the translate(); and the bracket from PushMatrix(); PopMatrix();?

Would I have to build the grid completely differently to make each of the individual rectangles flow to the mouse pointer?
Or is lerp(); just the wrong function to do this?

This is how far I have come so far:

float size;
float pixel;
float lx;
float ly;

void setup() {
  size(600, 600);
  pixel = 100;
  size = width/pixel;
  rectMode(CENTER);
}

void draw() {
  background(0);
  //DRAW THE GRID

  lx = 0;
  ly = 0;

  for (int y = 0; y < pixel; y++) {
    ly = lerp(ly, mouseY, 0.05);
    for (int x = 0; x < pixel; x++) {
      lx = lerp(lx, mouseX, 0.05);
      pushMatrix();
      translate(size/2, size/2);
      translate(x*size, y*size);
      rotate(radians(45));
      fill(255);
      noStroke();
      rect(lx, ly, size, size);
      popMatrix();
    }
  }
}

Is this even possible with the way I built the grid?

Body:
Your lerp function is used to calculate steps between two positions, so you want the starting position and ending position for your transition, and you will be calling lerp multiple times to recalculate each step.  You can think of lerp as calculating the percentage of the distance between the source and destination as you change the last parameter from 0.0 to 1.0 in incremental steps.

rectY=?;
rectX=?; // Replace the '?' marks with the left and top starting positions of your rectangle
for (int step=1; step<=20; step++) {
    lx = lerp(rectX, mouseX, 0.05 * step);
    ly = lerp(rectY, mouseY, 0.05 * step);
    ...
}


问:
Why is the scikit-learn SVM classifier running so long while using so little CPU?
I am executing the scikit-learn SVM classifier (SVC) from python 2.7.10 and it has been running for over 2 hours now. I have read the data using pandas.read_csv preprocessed it and then run

```<code>clf = SVC(C = 0.001, kernel = 'linear', cache_size = 7000, verbose = True)
clf.fit(X_train, y_train)
</code>```

I have experience in running classifiers (Random Forests and Deep Neural Networks) in H2O using R and they never take this long! The machine I am running on has 16 GB RAM and and i7 with 3.6 GHz on each core. The taskmonitor tells me that 8.6 Gb RAM are being used by python, however, only 13% of the CPU. I don't quite understand why it is so slow and not even using all resources.

The data I have has 12000000 rows and 22 columns and the only verbose sklearn is giving me is one line:

[LibSVM]

Is that normal behavior or should I see a lot more? Could anyone post the verbose of a svc that finished?
Also, can I do anything to speed things up besides lowering the C parameter? Using less rows is not really an option since I want to benchmark algorithms and they wouldn't be comparable if different training data was used. Finally, can anyone explain why so little of my resources are being used?

答:
You can try using accelerated implementations of algorithms - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

For SVM you for sure would be able to get higher compute efficiency, however for such large datasets this still would be noticeable.

First install package

pip install scikit-learn-intelex
```
<p>And then add in your python script</p>
<pre class="lang-py prettyprint-override"><code>from sklearnex import patch_sklearn
patch_sklearn()
</code>```

Body:
I am executing the scikit-learn SVM classifier (SVC) from python 2.7.10 and it has been running for over 2 hours now. I have read the data using pandas.read_csv preprocessed it and then run

clf = SVC(C = 0.001, kernel = 'linear', cache_size = 7000, verbose = True)
clf.fit(X_train, y_train)

I have experience in running classifiers (Random Forests and Deep Neural Networks) in H2O using R and they never take this long! The machine I am running on has 16 GB RAM and and i7 with 3.6 GHz on each core. The taskmonitor tells me that 8.6 Gb RAM are being used by python, however, only 13% of the CPU. I don't quite understand why it is so slow and not even using all resources.

The data I have has 12000000 rows and 22 columns and the only verbose sklearn is giving me is one line:

[LibSVM]

Is that normal behavior or should I see a lot more? Could anyone post the verbose of a svc that finished?
Also, can I do anything to speed things up besides lowering the C parameter? Using less rows is not really an option since I want to benchmark algorithms and they wouldn't be comparable if different training data was used. Finally, can anyone explain why so little of my resources are being used?

Body:
You can try using accelerated implementations of algorithms - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

For SVM you for sure would be able to get higher compute efficiency, however for such large datasets this still would be noticeable.

First install package

pip install scikit-learn-intelex

And then add in your python script

from sklearnex import patch_sklearn
patch_sklearn()


问:
C++ Win32 Padding zeros to an int via to_wstring
I am trying to learn C++ Win32. I built a timer class for a game environment. Typical game timer and it works well. I have this function that I would like to display the current game time with.

std::wstring Time::DisplayGameTime()
{
    std::wstring Label = L"Current Time: ";

    std::wstring daysText = L" " + std::to_wstring(Days()); //Returns int
    std::wstring monthsText = L", " + std::to_wstring(Months()); //Returns int
    std::wstring yearsText = L", " + std::to_wstring(Years()); // Returns int
    std::wstring hoursText = L" " + std::to_wstring(Hours()); // Returns int
    std::wstring minutesText = L" : " + std::to_wstring(Minutes()); // Returns int

    std::wstring message = Label + daysText + monthsText + yearsText + hoursText + minutesText;
    return message;
}
```

This works well too, except the minutes integer only prints one digit until it reaches 10. I would like to pad a leading zero to it like you would find in a normal time clock. Since I am using std::to_wstring, I cannot use format specifiers like in a swprintf_s buffer. I have tried to figure out how to use a wstringstream for this but none of what I've tried has worked.

The goal is to use this function to convert to LPCWSTR later on for DrawText to display to the Window.

答:
As you discovered, to_wstring doesn't allow you to provide formatting options. If you want to keep using to_wstring you'll have to apply the formatting yourself. There are many options to do so, so I'll just pick one at random:

Always prepend a "0"

Then return the right-most 2 digits

Something like this:

auto const minutesText = []() {
    // Always prepend a "0"
    auto const minute { L"0" + std::to_wstring(Minutes()) };
    // Return the right-most 2 digits
    return minute.substr(minute.length() - 2);
}();
```
<p>If you can use C++20 things are far easier, and usually a <em>lot</em> faster, too. C++20 introduced a formatting library that combines a succinct formatting description language (similar to Python's) with the type safety of C++' I/O streams.</p>
<p>It makes the following implementation possible:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <format>

std::wstring Time::DisplayGameTime()
{
    return std::format(L"Current Time:  {}, {}, {} {} : {:02}",
                       Days(), Months(), Years(),
                       Hours(), Minutes());
}
</code>```

std::format is similar to the printf family of functions in taking a formatting string, plus zero or more arguments to be interpolated. The formatting string describes the final output as well as where the arguments are placed and how they are formatted.

The first four placeholders do not contain any formatting specification, and produce results similar to what to_wstring would have. The final placeholder {:02} encodes both the field width (2) as well as the fill character (0) to use when the output doesn't produce enough characters. It could have been spelled {:0>2} to specify right-aligned text, but that is the default integer values so I omitted it.

Using the C++20 formatting library requires a C++20 compiler (that implements it). Visual Studio 2019 and Visual Studio 2022 do. Either one requires setting the /std:c++-latest compiler option. At this time, the C++20 formatting library does not appear under the /std:c++20 compiler option. The C++ Language Standard can be set from the IDE as well.

Bonus material: Why does std::format do that? - Charlie Barto - CppCon 2021: A look at Microsoft's implementation that—among other things—explains why std::format is orders of magnitude faster than I/O streams. This is not introductory material.

Body:
I am trying to learn C++ Win32. I built a timer class for a game environment. Typical game timer and it works well. I have this function that I would like to display the current game time with.

std::wstring Time::DisplayGameTime()
{
    std::wstring Label = L"Current Time: ";

    std::wstring daysText = L" " + std::to_wstring(Days()); //Returns int
    std::wstring monthsText = L", " + std::to_wstring(Months()); //Returns int
    std::wstring yearsText = L", " + std::to_wstring(Years()); // Returns int
    std::wstring hoursText = L" " + std::to_wstring(Hours()); // Returns int
    std::wstring minutesText = L" : " + std::to_wstring(Minutes()); // Returns int

    std::wstring message = Label + daysText + monthsText + yearsText + hoursText + minutesText;
    return message;
}

This works well too, except the minutes integer only prints one digit until it reaches 10. I would like to pad a leading zero to it like you would find in a normal time clock. Since I am using std::to_wstring, I cannot use format specifiers like in a swprintf_s buffer. I have tried to figure out how to use a wstringstream for this but none of what I've tried has worked.

The goal is to use this function to convert to LPCWSTR later on for DrawText to display to the Window.

Body:
As you discovered, to_wstring doesn't allow you to provide formatting options. If you want to keep using to_wstring you'll have to apply the formatting yourself. There are many options to do so, so I'll just pick one at random:

Always prepend a "0"

Then return the right-most 2 digits

Something like this:

auto const minutesText = []() {
    // Always prepend a "0"
    auto const minute { L"0" + std::to_wstring(Minutes()) };
    // Return the right-most 2 digits
    return minute.substr(minute.length() - 2);
}();

If you can use C++20 things are far easier, and usually a lot faster, too. C++20 introduced a formatting library that combines a succinct formatting description language (similar to Python's) with the type safety of C++' I/O streams.

It makes the following implementation possible:

#include <format>

std::wstring Time::DisplayGameTime()
{
    return std::format(L"Current Time:  {}, {}, {} {} : {:02}",
                       Days(), Months(), Years(),
                       Hours(), Minutes());
}

std::format is similar to the printf family of functions in taking a formatting string, plus zero or more arguments to be interpolated. The formatting string describes the final output as well as where the arguments are placed and how they are formatted.

The first four placeholders do not contain any formatting specification, and produce results similar to what to_wstring would have. The final placeholder {:02} encodes both the field width (2) as well as the fill character (0) to use when the output doesn't produce enough characters. It could have been spelled {:0>2} to specify right-aligned text, but that is the default integer values so I omitted it.

Using the C++20 formatting library requires a C++20 compiler (that implements it). Visual Studio 2019 and Visual Studio 2022 do. Either one requires setting the /std:c++-latest compiler option. At this time, the C++20 formatting library does not appear under the /std:c++20 compiler option. The C++ Language Standard can be set from the IDE as well.

Bonus material: Why does std::format do that? - Charlie Barto - CppCon 2021: A look at Microsoft's implementation that—among other things—explains why std::format is orders of magnitude faster than I/O streams. This is not introductory material.


问:
How to get the average temperature for N days prior to a specific date in R, accounting for differences in station data?
This question is part of a previous one that I had (How to get the average temperature for N days prior to a specific date in R?), however things have complicated a bit (at least for me).

I have two datasets: one dataset (A) has the temperatures for each day, and on the other dataset (B) I have the individuals id and the date of birth (dob). I need to get the average temperature for the last 3 days prior to the dob of each individual. For example: if individual 1 was born in 02/20/2021, I need the average temperature from 02/17/2021 to 02/19/2021. However, I also have data coming from different weather station id (in df A), that needs to correspond with the right farm (in df B).
Is there a way I could do that in R, so my output would be ind | dob | avg_temp, accounting for the right weather station. Here is one example data (in my real case, my data has a very large number of days, individuals, farms and station):

```<code>temp <- c(26,27,28,30,32,27,28,29)
date <- as.Date(c('02-15-2021', '02-16-2021', '02-17-2021', '02-18-2021', '02-19-2021', '02-20-2021', '02-21-2021',
                  '02-22-2021'), "%m-%d-%Y")
station <- c('A1', 'A2', 'A1', 'A2', 'A2', 'A1', 'A2', 'A1')
A <- data.frame(date, temp, station)
id <- c(1,2,3,4,5,6,7,8,9,10)
dob <- as.Date(c('02-18-2021', '02-17-2021', '02-20-2021', '02-23-2021', '02-25-2021', '02-23-2021', '02-17-2021',
                 '02-25-2021', '02-25-2021', '02-23-2021'), "%m-%d-%Y")
farm <- c('A1', 'A2', 'A1', 'A1', 'A1', 'A2', 'A2', 'A1', 'A1', 'A2')
B <- data.frame(id, dob, farm)
</code>```

答:
Thanks for the clarification. This extension of the function includes the location to calculate the average temperature. This assumes farm and station have corresponding values despite having different column names, as in your example. I've used mapply here to make sure the elements line up (i.e. x[1] goes with location[1], x[2] with location[2] and so on). That way if a particular date of birth only happens in one location it won't be calculated for all locations. I believe you could use lapply as well.

library(lubridate)

myfunc <- function(x, location){
  three_days <- as.Date(x - ddays(3))

  A <- A[A$date < x & A$date >= three_days & A$station %in% location, ]
  avg_temp <- mean(A$temp)
  dat <- data.frame(dob = x, avg_temp = avg_temp, farm = location)
  return(dat)
}

dobs <- unique(B[,c("dob", "farm")])

avg_temps <- mapply(myfunc, x = dobs$dob, location = dobs$farm, SIMPLIFY = FALSE)
avg_temps <- do.call(rbind, avg_temps)

B <- merge(B, avg_temps, by = c("dob", "farm"))

B
#>           dob farm id avg_temp
#> 1  2021-02-17   A2  2       27
#> 2  2021-02-17   A2  7       27
#> 3  2021-02-18   A1  1       27
#> 4  2021-02-20   A1  3       28
#> 5  2021-02-23   A1  4       28
#> 6  2021-02-23   A2  6       28
#> 7  2021-02-23   A2 10       28
#> 8  2021-02-25   A1  5       29
#> 9  2021-02-25   A1  8       29
#> 10 2021-02-25   A1  9       29
```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
This question is part of a previous one that I had (How to get the average temperature for N days prior to a specific date in R?), however things have complicated a bit (at least for me).

I have two datasets: one dataset (A) has the temperatures for each day, and on the other dataset (B) I have the individuals id and the date of birth (dob). I need to get the average temperature for the last 3 days prior to the dob of each individual. For example: if individual 1 was born in 02/20/2021, I need the average temperature from 02/17/2021 to 02/19/2021. However, I also have data coming from different weather station id (in df A), that needs to correspond with the right farm (in df B).
Is there a way I could do that in R, so my output would be ind | dob | avg_temp, accounting for the right weather station. Here is one example data (in my real case, my data has a very large number of days, individuals, farms and station):

temp <- c(26,27,28,30,32,27,28,29)
date <- as.Date(c('02-15-2021', '02-16-2021', '02-17-2021', '02-18-2021', '02-19-2021', '02-20-2021', '02-21-2021',
                  '02-22-2021'), "%m-%d-%Y")
station <- c('A1', 'A2', 'A1', 'A2', 'A2', 'A1', 'A2', 'A1')
A <- data.frame(date, temp, station)
id <- c(1,2,3,4,5,6,7,8,9,10)
dob <- as.Date(c('02-18-2021', '02-17-2021', '02-20-2021', '02-23-2021', '02-25-2021', '02-23-2021', '02-17-2021',
                 '02-25-2021', '02-25-2021', '02-23-2021'), "%m-%d-%Y")
farm <- c('A1', 'A2', 'A1', 'A1', 'A1', 'A2', 'A2', 'A1', 'A1', 'A2')
B <- data.frame(id, dob, farm)

Body:
Thanks for the clarification. This extension of the function includes the location to calculate the average temperature. This assumes farm and station have corresponding values despite having different column names, as in your example. I've used mapply here to make sure the elements line up (i.e. x[1] goes with location[1], x[2] with location[2] and so on). That way if a particular date of birth only happens in one location it won't be calculated for all locations. I believe you could use lapply as well.

library(lubridate)

myfunc <- function(x, location){
  three_days <- as.Date(x - ddays(3))

  A <- A[A$date < x & A$date >= three_days & A$station %in% location, ]
  avg_temp <- mean(A$temp)
  dat <- data.frame(dob = x, avg_temp = avg_temp, farm = location)
  return(dat)
}

dobs <- unique(B[,c("dob", "farm")])

avg_temps <- mapply(myfunc, x = dobs$dob, location = dobs$farm, SIMPLIFY = FALSE)
avg_temps <- do.call(rbind, avg_temps)

B <- merge(B, avg_temps, by = c("dob", "farm"))

B
#>           dob farm id avg_temp
#> 1  2021-02-17   A2  2       27
#> 2  2021-02-17   A2  7       27
#> 3  2021-02-18   A1  1       27
#> 4  2021-02-20   A1  3       28
#> 5  2021-02-23   A1  4       28
#> 6  2021-02-23   A2  6       28
#> 7  2021-02-23   A2 10       28
#> 8  2021-02-25   A1  5       29
#> 9  2021-02-25   A1  8       29
#> 10 2021-02-25   A1  9       29

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
How to solve migration problem in sugar crm?
There is a problem  i was using suagrcrm 5.5 version and when i upgrade the sugarcrm version to 6.2 then on the dashlets no delete, edit and refresh images occur.</p>

答: Check the option "Prevent user customizable Homepage layout:" under Admin >> System Settings.</p>


问:
How can I render time-series data on a geographic display in grafana?
My goal is to render time-series data from set locations on a map. Essentially, I have about 30 predefined (static) locations in Switzerland from which I will be receiving real-time data. The data itself is relatively simple, just the signal/noise ratio of the signal we're receiving, which should be updated every few seconds or every minute. I am using InfluxDB as my database. Are there any specific setups I should be using for this kind of visualization?

My first question is: is it best to use the worldmap panel or the geomap panel at this time? I seem to be finding more information/documentation on the worldmap panel even though i have also read that geomap is (or at least will be) its replacement.

Second, I assume that since I'm using time-series data, that I should be using the Time-Series format, and not the Table format. However, I have not been able to render any data points using the time-series feature, even by following the simplest of examples in your documentation. The best I can do is use the Table feature, and internally remove previous points from my database at every iteration (so that multiple points aren't rendered at the same time for each location). Here are two screenshots of when I'm able to render data on the geomap using the Table format, and then after switching to Time-Series format that the points are no longer there (note that I have the same problem with the Worldmap application as well).

I'm able to render data using the Table method:

...but not using time series:

Thanks for any help!

答:
For rendering timeseries data on the geomap, you must convert your lat/long fields to a single geohash field. You'll have to do that prior to inserting the lat/longs into influxDB

See this answer


问:
How do inactivate Brave Shields in a Selenium script?
I want to access websites including their ads with Selenium in my brave browser. But Brave has a built in adblocker (Brave Shields), which prevent Selenium from seeing ads. How can I start brave without Brave Shields?
Is there some options-argument, that I can pass to selenium, like options.add_argument("--no-adblock")?</p>

答:
I know it's late to add an answer but it might help someone in the future. This worked for me, hope it works for anyone out there.

options = webdriver.ChromeOptions()
options.binary_location = 'path to brave browser binary'
options.add_argument('--disable-brave-extension')  # this will disable brave browser shields
driver = webdriver.Chrome(options=options, executable_path=ChromeDriverManager().install())
```


问:
StructureMap Exception Code: 202 No Default Instance defined for PluginFamily
I am new to StructureMap. I have downloaded and am
using version 2.6.1.0. I keep getting the below
error:

StructureMap Exception Code:  202 No
  Default Instance defined for
  PluginFamily
  Company.ProjectCore.Core.IConfiguration,
  Company.ProjectCore, Version=1.0.0.0,
  Culture=neutral, PublicKeyToken=null

My Global.asax.cs looks like:

```<code>protected void Application_Start(object sender, EventArgs e)
{

    var container = new Container(x =>
                    {
                        x.For<ICache>().Use<Cache>();
                        x.For<IEmailService>().Use<EmailService>();
                        x.For<IUserSession>().Use<UserSession>();
                        x.For<IRedirector>().Use<Redirector>();
                        x.For<INavigation>().Use<Navigation>();
                    });

                container.AssertConfigurationIsValid();

}
</code>```

I changed from ObjectFactory.Initialize to "new Container" to debug.
When stepping through the AssertConfigurationIsValid() method, Cache
works but EmailService fails at the GetInstance method in the
following line:

```<code>[Pluggable("Default")]
public class EmailService : IEmailService

private readonly IConfiguration _configuration;

public EmailService()
{
    _configuration = ObjectFactory.GetInstance<IConfiguration>();
}
</code>```

If I remove IEmailService, the same 202 error is thrown at IUserSession.

Should I be adding something else in Application_Start or in my class files?

Thanks in advance...

答: I was seeing the same error. In my case, I had a typo in the implementation with the same name of another class in another project.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am new to StructureMap. I have downloaded and am
using version 2.6.1.0. I keep getting the below
error:

StructureMap Exception Code:  202 No
  Default Instance defined for
  PluginFamily
  Company.ProjectCore.Core.IConfiguration,
  Company.ProjectCore, Version=1.0.0.0,
  Culture=neutral, PublicKeyToken=null

My Global.asax.cs looks like:

protected void Application_Start(object sender, EventArgs e)
{

    var container = new Container(x =>
                    {
                        x.For<ICache>().Use<Cache>();
                        x.For<IEmailService>().Use<EmailService>();
                        x.For<IUserSession>().Use<UserSession>();
                        x.For<IRedirector>().Use<Redirector>();
                        x.For<INavigation>().Use<Navigation>();
                    });

                container.AssertConfigurationIsValid();

}

I changed from ObjectFactory.Initialize to "new Container" to debug.
When stepping through the AssertConfigurationIsValid() method, Cache
works but EmailService fails at the GetInstance method in the
following line:

[Pluggable("Default")]
public class EmailService : IEmailService

private readonly IConfiguration _configuration;

public EmailService()
{
    _configuration = ObjectFactory.GetInstance<IConfiguration>();
}

If I remove IEmailService, the same 202 error is thrown at IUserSession.

Should I be adding something else in Application_Start or in my class files?

Thanks in advance...


问:
Android Studio suddenly can't find ANY drawable components
Like the title suggests, all of a sudden, my Android Studio projects simply can't locate any of my drawable resources that I call when using android:background="@drawable/serving_editor_background" for example, it'll just give me this error code for every single drawable that has been called:

```<code>AAPT: error: resource drawable/serving_editor_background (aka com.example.poop123:drawable/serving_editor_background) not found.
</code>```
```<code>Execution failed for task ':app:mergeDebugResources'.
> com.android.build.gradle.tasks.ResourceException (no error message)
</code>```
```<code>ParseError at [row,col]:[2,6]
Message: The processing instruction target matching "[xX][mM][lL]" is not allowed.
</code>```

It literally does it for every single one (with their respective names and file path), all of the ones that used to work up until now, not a single one works, and I never changed anything in the gradle, but I'll still provide it:

```<code>plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.poop123"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    implementation 'com.ismaeldivita.chipnavigation:chip-navigation-bar:1.3.2'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.72'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.github.devlight.navigationtabstrip:navigationtabstrip:+'
    implementation 'com.google.firebase:firebase-database:20.0.2'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    implementation 'androidx.wear:wear:1.0.0'

    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    compileOnly 'com.google.android.wearable:wearable:2.6.0'
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.poop123">

    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Poop123">
        <activity android:name=".EditAddition"></activity>
        <activity android:name=".ConfirmAddition" />
        <activity android:name=".Goal" />
        <activity android:name=".ActivityLevel" />
        <activity android:name=".newFoodMenu" />
        <activity android:name=".foodLibrary" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

I'm getting really frustrated at this, because I changed absolutely nothing (just a specific XML code for a certain activity), and now none of the drawables can be found.
If any more info, let me know.

答:
Bascially, I loaded up an old version of the project, copy pasted all the new code into the current project, noticed that on one of the drawable's, I had an extra

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

And for some reason it completely clogged up the whole thing, and the exception messages it gave, had 0 to do with it in a sense, had to manually find the problem myself.

Body:
Like the title suggests, all of a sudden, my Android Studio projects simply can't locate any of my drawable resources that I call when using android:background="@drawable/serving_editor_background" for example, it'll just give me this error code for every single drawable that has been called:

AAPT: error: resource drawable/serving_editor_background (aka com.example.poop123:drawable/serving_editor_background) not found.

Execution failed for task ':app:mergeDebugResources'.
> com.android.build.gradle.tasks.ResourceException (no error message)

ParseError at [row,col]:[2,6]
Message: The processing instruction target matching "[xX][mM][lL]" is not allowed.

It literally does it for every single one (with their respective names and file path), all of the ones that used to work up until now, not a single one works, and I never changed anything in the gradle, but I'll still provide it:

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.poop123"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    implementation 'com.ismaeldivita.chipnavigation:chip-navigation-bar:1.3.2'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.72'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.github.devlight.navigationtabstrip:navigationtabstrip:+'
    implementation 'com.google.firebase:firebase-database:20.0.2'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    implementation 'androidx.wear:wear:1.0.0'

    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    compileOnly 'com.google.android.wearable:wearable:2.6.0'

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.poop123">

    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Poop123">
        <activity android:name=".EditAddition"></activity>
        <activity android:name=".ConfirmAddition" />
        <activity android:name=".Goal" />
        <activity android:name=".ActivityLevel" />
        <activity android:name=".newFoodMenu" />
        <activity android:name=".foodLibrary" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I'm getting really frustrated at this, because I changed absolutely nothing (just a specific XML code for a certain activity), and now none of the drawables can be found.
If any more info, let me know.

Body:
Bascially, I loaded up an old version of the project, copy pasted all the new code into the current project, noticed that on one of the drawable's, I had an extra

<?xml version="1.0" encoding="utf-8"?>

And for some reason it completely clogged up the whole thing, and the exception messages it gave, had 0 to do with it in a sense, had to manually find the problem myself.


问:
How can i add Button widget and TextInput widget to different screens?
In this program i have textinput and button in the same screen.i want to put the button in a separate screen from textinput.i tried sm.add_widget(self.b) or sm.add_widget(self.t) but it did not work.How can i put these widgets in different screens?

Code:

import kivy
from kivy.uix.button import Button
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen

class me (App):
    def __init__(self):
        super().__init__()
        screen = Screen(name='title1')
        sm=ScreenManager()

        self.b=Button(text='start',size_hint=(.13,.066), pos_hint= {'center_y': 0.5, 'center_x': 0.5})
        self.f=FloatLayout( )
        self.t=TextInput(size_hint=(1, .1), height=30,)
        self.f.add_widget(self.b)
        self.f.add_widget(self.t)

        sm.add_widget(screen)
        sm.current = 'title1'

    def build(self):
            return self.f

m=me()
m.run()
```

答:
First, you must create another Screen, then add widgets to whichever Screen you want. Here is a modified version of your me App that does that:

```<code>class me(App):

    def build(self):
        # create ScreenManager
        sm = ScreenManager()

        # create two Screens
        screen1 = Screen(name='title1')
        screen2 = Screen(name='title2')

        # configure screen1
        self.b = Button(text='start', size_hint=(.13, .066), pos_hint={'center_y': 0.5, 'center_x': 0.5})
        self.b.on_release = partial(setattr, sm, 'current', 'title2')
        self.f = FloatLayout()
        self.f.add_widget(self.b)
        screen1.add_widget(self.f)

        # configure screen2
        self.t = TextInput(size_hint=(1, .1), height=30, )
        screen2.add_widget(self.t)

        # add screens to ScreenManager
        sm.add_widget(screen1)
        sm.add_widget(screen2)

        # return root widget (the ScreenManager)
        return sm
</code>```

Note that this uses the build() method to build the GUI instead of a __init__() method. That is the recommended approach.

Body:
First, you must create another Screen, then add widgets to whichever Screen you want. Here is a modified version of your me App that does that:

class me(App):

    def build(self):
        # create ScreenManager
        sm = ScreenManager()

        # create two Screens
        screen1 = Screen(name='title1')
        screen2 = Screen(name='title2')

        # configure screen1
        self.b = Button(text='start', size_hint=(.13, .066), pos_hint={'center_y': 0.5, 'center_x': 0.5})
        self.b.on_release = partial(setattr, sm, 'current', 'title2')
        self.f = FloatLayout()
        self.f.add_widget(self.b)
        screen1.add_widget(self.f)

        # configure screen2
        self.t = TextInput(size_hint=(1, .1), height=30, )
        screen2.add_widget(self.t)

        # add screens to ScreenManager
        sm.add_widget(screen1)
        sm.add_widget(screen2)

        # return root widget (the ScreenManager)
        return sm

Note that this uses the build() method to build the GUI instead of a __init__() method. That is the recommended approach.


问:
How to write my_strchr() in C
Right now I hope to write my own my_strchr() in the C language.

I checked that the answer should be like this:

```<code>char *my_strchr(const char *src1, int c) {

    while (*src1 != '\0') { //when the string goes to the last, jump out
        if (c == *src1) {
            return src1;
        }
        src1++;
    }
    return NULL;
}
</code>```

I'm quite confused by:

why we use *src1  in the while loop condition (*src1 != '\0'), is *src1 a pointer to the const char*? Can we just use src1 instead?

When we return value and src1++, we do not have that *src1, why?

For this function, it in fact prints the whole string after the required characters, but why is that? Why does it not print only the character that we need to find?

答:
src1 is the pointer to the character, but we need the character itself. It's the same reason as in point 2, but the other way round.

If you write return *src1; you simply return the character you've found, that's always c, so your function would be pointless. You want to return the pointer to that char.

Because that's what the function is supposed to do. It returns the pointer to the first character c found. So printing the string pointed by that pointer prints the rest of the string.

Title: How to write my_strchr() in C

Body:
Right now I hope to write my own my_strchr() in the C language.

I checked that the answer should be like this:

char *my_strchr(const char *src1, int c) {

    while (*src1 != '\0') { //when the string goes to the last, jump out
        if (c == *src1) {
            return src1;
        }
        src1++;
    }
    return NULL;
}

I'm quite confused by:

why we use *src1  in the while loop condition (*src1 != '\0'), is *src1 a pointer to the const char*? Can we just use src1 instead?

When we return value and src1++, we do not have that *src1, why?

For this function, it in fact prints the whole string after the required characters, but why is that? Why does it not print only the character that we need to find?


问:
How do I make a python program keep going/restart?
I want my program to keep running even after I enter the first input. My program looks like this:

```<code>import os
import sys

print("Hello Officer. Let's get started!")
speed = int(input("Enter car's speed mph: "))
if 70<= speed <=75:
    print("Warning: speeding camera in process!")
elif 76<= speed < 100:
    print("Issue $50 Fine.")
elif speed >= 100:
    print("Issue $100 Fine and pull car over!")
else:
    print("No Action")

os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv)
</code>```

When I run the program, I get this:

```<code>================================ RESTART: Shell ================================
</code>```

and the program doesn't actually restart. How do I make it work?

答:
You should wrap the whole program in a while true loop.</p>
```<code>while True:
   print("Hello Officer. Let's get started!")
   speed = int(input("Enter car's speed mph: "))
   if 70<= speed <=75:
       print("Warning: speeding camera in process!")
   elif 76<= speed < 100:
       print("Issue $50 Fine.")
   elif speed >= 100:
       print("Issue $100 Fine and pull car over!")
   else:
       print("No Action")
</code>```

Body:
I want my program to keep running even after I enter the first input. My program looks like this:

import os
import sys

print("Hello Officer. Let's get started!")
speed = int(input("Enter car's speed mph: "))
if 70<= speed <=75:
    print("Warning: speeding camera in process!")
elif 76<= speed < 100:
    print("Issue $50 Fine.")
elif speed >= 100:
    print("Issue $100 Fine and pull car over!")
else:
    print("No Action")

os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv)

When I run the program, I get this:

================================ RESTART: Shell ================================

and the program doesn't actually restart. How do I make it work?

Body:
You should wrap the whole program in a while true loop.

while True:
   print("Hello Officer. Let's get started!")
   speed = int(input("Enter car's speed mph: "))
   if 70<= speed <=75:
       print("Warning: speeding camera in process!")
   elif 76<= speed < 100:
       print("Issue $50 Fine.")
   elif speed >= 100:
       print("Issue $100 Fine and pull car over!")
   else:
       print("No Action")


问:
What is the type alias rules in Scala?
So, just can't understand why does this compiles?

```<code>  type <=[B, A] = A => B
  type F[A] = Double <= A //why our alias <= is allowed here?
</code>```

What is the syntax rule of forming type aliases which allows constructions like these?
Can we free play only with the order => here like in this case?

答: There is a very simple rule that every type A B C is the same as B[A, C]. Evidently this only works for types with 2 type parameters.

Title: What is the type alias rules in Scala?

Body:
So, just can't understand why does this compiles?

  type <=[B, A] = A => B
  type F[A] = Double <= A //why our alias <= is allowed here?

What is the syntax rule of forming type aliases which allows constructions like these?
Can we free play only with the order => here like in this case?


问:
How to read textbox.Text value from another thread in WPF?
In my WPF form I have a textbox.

When a timer elapses, the content of the textbox needs to be fetched.

The timer elapsed is working in a different thread then the UI.

The question is kinda two-fold:

What is the easiest, most readable way to read the value from a GUI thread cross thread (I found several and they look too verbose for what should be something really basic)?

Can't I read the text in a non-blocking way? I don't care about thread safety in this case.

--EDIT--

I used the Dispatcher, but had a more verbose call then what John had:

```<code>originalTextBox.Dispatcher.Invoke(
    DispatcherPriority.Normal,
    (ThreadStart) delegate{text=originalTextBox.Text;}
);
</code>```

Wouldn't mind even terser though. Accessing a text property should be utterly basic.

答:
Oisin is right, you need to look at Dispatcher.  Something like this should work, and is not too verbose:</p>

```<code>System.Windows.Application.Current.Dispatcher.Invoke(
DispatcherPriority.Normal,
(ThreadStart)delegate { text = MyTextBox.Text; });
</code>```

OwnerDisplayName: boris callens

Body:
In my WPF form I have a textbox.

When a timer elapses, the content of the textbox needs to be fetched.

The timer elapsed is working in a different thread then the UI.

The question is kinda two-fold:

What is the easiest, most readable way to read the value from a GUI thread cross thread (I found several and they look too verbose for what should be something really basic)?

Can't I read the text in a non-blocking way? I don't care about thread safety in this case.

--EDIT--

I used the Dispatcher, but had a more verbose call then what John had:

originalTextBox.Dispatcher.Invoke(
    DispatcherPriority.Normal,
    (ThreadStart) delegate{text=originalTextBox.Text;}
);

Wouldn't mind even terser though. Accessing a text property should be utterly basic.

LastEditorDisplayName: boris callens

Body:
Oisin is right, you need to look at Dispatcher.  Something like this should work, and is not too verbose:

System.Windows.Application.Current.Dispatcher.Invoke(
DispatcherPriority.Normal,
(ThreadStart)delegate { text = MyTextBox.Text; });

OwnerDisplayName: John Myczek


问:
Why does click event handler fire immediately upon page load?
I playing around with a function that I want to bind to all the links. At the present the function fires when the page loads, instead of when I click on the link.

Here's my code. (I can post the function showDiv(), if you need to see it.) Can you tell if I'm doing something wrong or stupid here?

```<code>$(document).ready(function(){

    $('a.test').bind("click", showDiv());

});
</code>```

Thanks!

答:
You want to pass a reference to a function as a callback, and not the result of function execution:

showDiv() returns some value; if no return statement was used, undefined is returned.

showDiv is a reference to the function that should be executed.

This should work:

```<code>$(document).ready(function() {
  $('a.test').on("click", showDiv); // jQuery 1.7 and higher
  $('a.test').bind("click", showDiv); // jQuery 1.6 and lower
});
</code>```

Alternatively, you could use an anonymous function to perform a more advanced function:

```<code>// jQuery 1.7 and higher
el.on('click', function() {
  foo.showDiv(a, b, c);
  // more code...
});

// jQuery 1.6 and lower
el.bind('click', function() {
  foo.showDiv(a, b, c);
  // more code...
});
</code>```

In some circumstances you may want to use the value returned by a function as a callback:

```<code>function function foo(which) {
  function bar() {
    console.log('so very true');
  }

  function baz() {
    console.log('no way!');
  }

  return which ? bar : baz;
}

el.click(foo(fizz));
</code>```

In this example, foo is evaluated using fizz and returns a function that will be assigned as the callback for the click event.

Body:
I playing around with a function that I want to bind to all the links. At the present the function fires when the page loads, instead of when I click on the link.

Here's my code. (I can post the function showDiv(), if you need to see it.) Can you tell if I'm doing something wrong or stupid here?

$(document).ready(function(){

    $('a.test').bind("click", showDiv());

});

Thanks!

Body:
You want to pass a reference to a function as a callback, and not the result of function execution:

showDiv() returns some value; if no return statement was used, undefined is returned.

showDiv is a reference to the function that should be executed.

This should work:

$(document).ready(function() {
  $('a.test').on("click", showDiv); // jQuery 1.7 and higher
  $('a.test').bind("click", showDiv); // jQuery 1.6 and lower
});

Alternatively, you could use an anonymous function to perform a more advanced function:

// jQuery 1.7 and higher
el.on('click', function() {
  foo.showDiv(a, b, c);
  // more code...
});

// jQuery 1.6 and lower
el.bind('click', function() {
  foo.showDiv(a, b, c);
  // more code...
});

In some circumstances you may want to use the value returned by a function as a callback:

function function foo(which) {
  function bar() {
    console.log('so very true');
  }

  function baz() {
    console.log('no way!');
  }

  return which ? bar : baz;
}

el.click(foo(fizz));

In this example, foo is evaluated using fizz and returns a function that will be assigned as the callback for the click event.


问:
Range columns to fill combobox
I want to fill a ComboBox with column names.

For every option I try I get:

Error 380 Runtime RowSource.

In forums this seemed to work, but I need it for columns.

ComboBox1.Value = "Please Select an employee from the dropdown"
ComboBox1.RowSource = "Sheet1!A3:A" & Range("A" & Rows.Count).End(xlUp).Row
```

The blue headers are the ones I need in the comboBox, from A3:J3

答:
Have a look at this solution as a starting point for loading your data in a ComboBox: Populate a combo box with a string array in a user form

Ignore the UserForm part, as it might not be relevant in this scenario.

I recommend that you make a range object out of the column headings, load them into an array and then load them into a combo box, in the event that these headings might change at some moment.

Title: Range columns to fill combobox

Body:
I want to fill a ComboBox with column names.

For every option I try I get:

Error 380 Runtime RowSource.

In forums this seemed to work, but I need it for columns.

ComboBox1.Value = "Please Select an employee from the dropdown"
ComboBox1.RowSource = "Sheet1!A3:A" & Range("A" & Rows.Count).End(xlUp).Row

The blue headers are the ones I need in the comboBox, from A3:J3


问:
How can I check two arrays at the same index?
I want to determine how many of the items in these two arrays match, then store that in state as a number.

For example

const [score, setScore] = React.useState(0)

const selections = ["one", "two", "three"]
const allCorrectAnswers = ["four", "two", "three"]
// this should return 2
```
<p>I tried</p>
<pre class="lang-js prettyprint-override"><code>function checkSelectedAnswer(selections, allCorrectAnswers) {
  selections.map(eachChoice =>
    eachChoice === allCorrectAnswers.map(eachAnswer => eachAnswer)
      ? setScore(prevScore => prevScore + 1) : 0
  )
}
</code>```

Please explain why my code isn't working as well if you can.

答:
.map (either at the top level or the nested one) doesn't make sense, because you aren't trying to transform  each element of one array into another. If you want to use an array method, use .reduce instead, and use the index in the callback to access the associated element in the other array to see if it's equal.

const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];
const totalCorrect = selections.reduce(
  (correctSoFar, answer, i) => correctSoFar + (answer === allCorrectAnswers[i]),
  0
);
console.log(totalCorrect);
// setScore(totalCorrect);```
</div>
</div>
</p>
<p>or do</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];

let totalCorrect = 0;
selections.forEach((answer, i) => {
  if (answer === allCorrectAnswers[i]) {
    totalCorrect++;
  }
});
console.log(totalCorrect);
// setScore(totalCorrect);</code>```

Body:
I want to determine how many of the items in these two arrays match, then store that in state as a number.

For example

const [score, setScore] = React.useState(0)

const selections = ["one", "two", "three"]
const allCorrectAnswers = ["four", "two", "three"]
// this should return 2

I tried

function checkSelectedAnswer(selections, allCorrectAnswers) {
  selections.map(eachChoice =>
    eachChoice === allCorrectAnswers.map(eachAnswer => eachAnswer)
      ? setScore(prevScore => prevScore + 1) : 0
  )
}

Please explain why my code isn't working as well if you can.

Body:
.map (either at the top level or the nested one) doesn't make sense, because you aren't trying to transform  each element of one array into another. If you want to use an array method, use .reduce instead, and use the index in the callback to access the associated element in the other array to see if it's equal.

const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];
const totalCorrect = selections.reduce(
  (correctSoFar, answer, i) => correctSoFar + (answer === allCorrectAnswers[i]),
  0
);
console.log(totalCorrect);
// setScore(totalCorrect);

or do

const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];

let totalCorrect = 0;
selections.forEach((answer, i) => {
  if (answer === allCorrectAnswers[i]) {
    totalCorrect++;
  }
});
console.log(totalCorrect);
// setScore(totalCorrect);


问:
Git won't accept PAT and thinks it's a password
I want to clone my repository and got a prompt that I could no longer use passwords, and had to instead use a Personal Access Token.

But whenever I try to enter it (either in the popup window or the CMD directly) it keeps telling me I can't use passwords anymore and need a PAT. I'm putting it in the password field both times.

The PAT has the highest possible rights I could give it.

答: I randomly tried GIT BASH instead of the CMD and the second prompt did accept the PAT for the password field. I'd still like to know why this is the case.</p>


答:
I could not find the definition of =>

Yeah, it is embedded in the compiler implementation / language specification.

But, as you just show, it is quite easy to reimplement in on userland; it would look like this:

type =>[+A, +B] = Function1[A, B]
```

how Scala compiler parse an alias expression like sequence of types Type1 Type2 Type3

The language specs say that it supports infix types, so things like: A OP B are equivalent to OP[A, B]

Title: What is the type alias rules in Scala?

Body:
I could not find the definition of =>

Yeah, it is embedded in the compiler implementation / language specification.

But, as you just show, it is quite easy to reimplement in on userland; it would look like this:

type =>[+A, +B] = Function1[A, B]

how Scala compiler parse an alias expression like sequence of types Type1 Type2 Type3

The language specs say that it supports infix types, so things like: A OP B are equivalent to OP[A, B]


问:
Can't set HTTP-Only cookie from Java backend to NextJS app
I'm having a hard time with cookies. I'm sending and Http-Only cookie in the response when my NextJS app does a /login request to my backend, I thought that it was going to be saved on the Cookie storage and it would be available on req.headers.cookie on ServerSideProps on my NextJS app, but my cookies are never set, even though they appear in the /login response from my backend.

I do a request to my Gateway Microservice which then redirects it to my Security microservice, in that security microservice I write the cookies like this and save a JWT in it:

```<code>        Cookie cookie = new Cookie("Authentication", token);
        cookie.setMaxAge(28800);
        cookie.setSecure(false); //TODO: Change this to false or true depending on dev or prod
        cookie.setPath("/");
        cookie.setHttpOnly(true);

        response.addCookie(cookie);
        response.addHeader(AUTH_HEADER_KEY, TOKEN_PREFIX + token);
</code>```

Then the response from my backend when my frontend does a /login POST request is like this:

But is never saved in storage in my browser as shown by this:

And neither when requesting them on my ServerSideProps Next function:

```<code>export const getServerSideProps: GetServerSideProps = async ({
  locale,
  req,
}) => {
  const cookies = req.headers.cookie;
  console.log('Cookies: ', cookies);
  return {
    props: {
      ...(await serverSideTranslations(locale ? locale : 'es', ['dashboard'])),
    },
  };
};
</code>```

My request for /login looks like this on the frontend:

```<code>const loginUserMutation = useMutation(
    ({ email, password }: UserLogin) => {
      return axios.post(process.env.NEXT_PUBLIC_DEV_DOMAIN_URL + '/login', {
        email,
        password,
      });
    },
    {
      onSuccess: (data) => {
        const loggedUser: LoggedUser = {
          role: data.data.role,
          email: data.data.email,
          token: data.headers.authorization,
        };
        saveUserInContext(loggedUser);
        router.push('/');
      },
    }
  );
</code>```

What else can I do? My NextJS app is on localhost:3000 and my gateway is on localhost:4010 and my security microservice is on localhost:4020

EDIT:

Found out that if in my CORS Configuration I add this lines it will work and also by using allowCredentials on my frontend. BUT beware, my Spring Cloud Gateway microservice is thrashing my headers, so I have to still look into it, but if you got this same problem try using directly your endpoint.

```<code> @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final var source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        source.registerCorsConfiguration("/**", corsConfiguration.applyPermitDefaultValues());
        corsConfiguration.setExposedHeaders(List.of("Authorization", "Set-Cookie"));
        corsConfiguration.setAllowedOrigins(List.of("http://localhost:3000"));
        corsConfiguration.setAllowCredentials(true);

        return source;
    }
</code>```

答: Try adding Set-Cookie to the Access-Control-Expose-Headers header.

Body:
I'm having a hard time with cookies. I'm sending and Http-Only cookie in the response when my NextJS app does a /login request to my backend, I thought that it was going to be saved on the Cookie storage and it would be available on req.headers.cookie on ServerSideProps on my NextJS app, but my cookies are never set, even though they appear in the /login response from my backend.

I do a request to my Gateway Microservice which then redirects it to my Security microservice, in that security microservice I write the cookies like this and save a JWT in it:

        Cookie cookie = new Cookie("Authentication", token);
        cookie.setMaxAge(28800);
        cookie.setSecure(false); //TODO: Change this to false or true depending on dev or prod
        cookie.setPath("/");
        cookie.setHttpOnly(true);

        response.addCookie(cookie);
        response.addHeader(AUTH_HEADER_KEY, TOKEN_PREFIX + token);

Then the response from my backend when my frontend does a /login POST request is like this:

But is never saved in storage in my browser as shown by this:

And neither when requesting them on my ServerSideProps Next function:

export const getServerSideProps: GetServerSideProps = async ({
  locale,
  req,
}) => {
  const cookies = req.headers.cookie;
  console.log('Cookies: ', cookies);
  return {
    props: {
      ...(await serverSideTranslations(locale ? locale : 'es', ['dashboard'])),
    },
  };
};

My request for /login looks like this on the frontend:

const loginUserMutation = useMutation(
    ({ email, password }: UserLogin) => {
      return axios.post(process.env.NEXT_PUBLIC_DEV_DOMAIN_URL + '/login', {
        email,
        password,
      });
    },
    {
      onSuccess: (data) => {
        const loggedUser: LoggedUser = {
          role: data.data.role,
          email: data.data.email,
          token: data.headers.authorization,
        };
        saveUserInContext(loggedUser);
        router.push('/');
      },
    }
  );

What else can I do? My NextJS app is on localhost:3000 and my gateway is on localhost:4010 and my security microservice is on localhost:4020

EDIT:

Found out that if in my CORS Configuration I add this lines it will work and also by using allowCredentials on my frontend. BUT beware, my Spring Cloud Gateway microservice is thrashing my headers, so I have to still look into it, but if you got this same problem try using directly your endpoint.

 @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final var source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        source.registerCorsConfiguration("/**", corsConfiguration.applyPermitDefaultValues());
        corsConfiguration.setExposedHeaders(List.of("Authorization", "Set-Cookie"));
        corsConfiguration.setAllowedOrigins(List.of("http://localhost:3000"));
        corsConfiguration.setAllowCredentials(true);

        return source;
    }