问:
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError
Getting some very odd behaviour on my Google Play Pre-Launch report, and it's only just started occurring, but I can't pin it down to anything I have changed.   I also can't reproduce the issue myself.

Every test device seems to be failing in the pre-launch report (6/6 devices all fail the same way).  However repeating the steps on the same build on a real device, I can never recreate it.   The stack trace is as follows:

```<code>FATAL EXCEPTION: Thread-8
Process: uk.myapp.test, PID: 25312
java.lang.NoSuchMethodError: No static method createWithResource(Landroid/content/res/Resources;Ljava/lang/String;I)Landroidx/core/graphics/drawable/IconCompat; in class Landroidx/core/graphics/drawable/IconCompat; or its super classes (declaration of 'androidx.core.graphics.drawable.IconCompat' appears in base.apk)
    at androidx.core.app.NotificationCompat$Action.<init>(NotificationCompat.java:4572)
    at com.google.android.exoplayer2.ui.PlayerNotificationManager.createPlaybackActions(PlayerNotificationManager.java:1439)
    at com.google.android.exoplayer2.ui.PlayerNotificationManager.<init>(PlayerNotificationManager.java:757)
    at com.google.android.exoplayer2.ui.PlayerNotificationManager$Builder.build(PlayerNotificationManager.java:564)
    at uk.myapp.test.AudioPlayerService.onCreate(AudioPlayerService.java:96)
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3570)
    at android.app.ActivityThread.access$1300(ActivityThread.java:200)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1672)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at androidx.test.espresso.base.Interrogator.loopAndInterrogate(Interrogator.java:10)
    at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:7)
    at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:1)
    at androidx.test.espresso.base.UiControllerImpl.injectMotionEvent(UiControllerImpl.java:5)
    at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:6)
    at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:1)
    at androidx.test.espresso.action.Tap.sendSingleTap(Tap.java:5)
    at androidx.test.espresso.action.Tap.-$$Nest$smsendSingleTap(Unknown Source:0)
    at androidx.test.espresso.action.Tap$1.sendTap(Tap.java:1)
    at androidx.test.espresso.action.GeneralClickAction.perform(GeneralClickAction.java:4)
    at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:2)
    at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:21)
    at androidx.test.espresso.ViewInteraction.-$$Nest$mdoPerform(Unknown Source:0)
    at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:2)
    at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:1)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6718)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

答:
I implemented reverting the Firebase BOM version like the other answer suggested, but it didn't (or at least didn't fully resolve) the issue for me. Reverting this other dependency finished solving it for me:

Crashing version:

```<code>implementation 'com.google.android.gms:play-services-location:19.0.1'
</code>```

Working version:

```<code>implementation 'com.google.android.gms:play-services-location:18.0.0'
</code>```

Body:
Getting some very odd behaviour on my Google Play Pre-Launch report, and it's only just started occurring, but I can't pin it down to anything I have changed.   I also can't reproduce the issue myself.

Every test device seems to be failing in the pre-launch report (6/6 devices all fail the same way).  However repeating the steps on the same build on a real device, I can never recreate it.   The stack trace is as follows:

FATAL EXCEPTION: Thread-8
Process: uk.myapp.test, PID: 25312
java.lang.NoSuchMethodError: No static method createWithResource(Landroid/content/res/Resources;Ljava/lang/String;I)Landroidx/core/graphics/drawable/IconCompat; in class Landroidx/core/graphics/drawable/IconCompat; or its super classes (declaration of 'androidx.core.graphics.drawable.IconCompat' appears in base.apk)
    at androidx.core.app.NotificationCompat$Action.<init>(NotificationCompat.java:4572)
    at com.google.android.exoplayer2.ui.PlayerNotificationManager.createPlaybackActions(PlayerNotificationManager.java:1439)
    at com.google.android.exoplayer2.ui.PlayerNotificationManager.<init>(PlayerNotificationManager.java:757)
    at com.google.android.exoplayer2.ui.PlayerNotificationManager$Builder.build(PlayerNotificationManager.java:564)
    at uk.myapp.test.AudioPlayerService.onCreate(AudioPlayerService.java:96)
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3570)
    at android.app.ActivityThread.access$1300(ActivityThread.java:200)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1672)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at androidx.test.espresso.base.Interrogator.loopAndInterrogate(Interrogator.java:10)
    at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:7)
    at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:1)
    at androidx.test.espresso.base.UiControllerImpl.injectMotionEvent(UiControllerImpl.java:5)
    at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:6)
    at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:1)
    at androidx.test.espresso.action.Tap.sendSingleTap(Tap.java:5)
    at androidx.test.espresso.action.Tap.-$$Nest$smsendSingleTap(Unknown Source:0)
    at androidx.test.espresso.action.Tap$1.sendTap(Tap.java:1)
    at androidx.test.espresso.action.GeneralClickAction.perform(GeneralClickAction.java:4)
    at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:2)
    at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:21)
    at androidx.test.espresso.ViewInteraction.-$$Nest$mdoPerform(Unknown Source:0)
    at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:2)
    at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:1)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6718)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Body:
I implemented reverting the Firebase BOM version like the other answer suggested, but it didn't (or at least didn't fully resolve) the issue for me. Reverting this other dependency finished solving it for me:

Crashing version:

implementation 'com.google.android.gms:play-services-location:19.0.1'

Working version:

implementation 'com.google.android.gms:play-services-location:18.0.0'


来源: stackexchange

问:
Model objects that are not developer-defined?
Every SwiftUI tutorial/example uses model objects that are defined by me, the guy writing the app. However, what is the best practice when the model objects are not under my direct control? For example, the HomeKit framework has an API to get all the rooms in a given home. It returns an array of HMRoom objects:

```<code>open class HMRoom: NSObject
{
    open var name: String { get }
    open var accessories: [HMAccessory] { get }
    open var uniqueIdentifier: UUID { get }

    // Update the room's name in a HomeKit-compliant way that notifies all other HomeKit apps
    open func updateName(_ name: String) async throws
}
</code>```

When I receive an array of HMRoom objects from the HomeKit API, what should I do with them to power SwiftUI? Should I create my own class that looks like this:

```<code>final class Room: ObservableObject
{
    @Published var name: String
    @Published var accessories: [Accessory]
    @Published var uniqueIdentifier: UUID

    private var representedRoom: HMRoom

    init(homekitRoom: HMRoom)
    {
        // Copy properties from 'homekitRoom' to self, then set `representedRoom` to `homekitRoom` so we can use it to call the updateName(:) function
    }
}
</code>```

Is there, instead, a way for me to extend the HMRoom class directly to inform SwiftUI that name, accessories, and uniqueIdentifier are the properties we must watch for changes in order to reload views appropriately?

It's unclear to me what the best approach is to integrate @Published/@ObservableObject when I don't write the model classes/structs myself.

答:
If you read Apple's document Choosing Between Structures and Classes the Use Classes When You Need to Control Identity section makes you think use a class, however if you read the Use Structures When You Don't Control Identity section and notice that every HomeKit object contains a uniqueIdentifier it turns out we can use structs yay!

```<code>struct Room: Identifiable {
    let id: UUID
    var name: String
}

class HomeDelegate: NSObject, HMHomeDelegate {
    weak var homeManagerDelegate: HomeManagerDelegate?

    // HomeManagerDelegate sets the primaryHome.
    var home: HMHome? {
        didSet {
            oldValue?.delegate = nil
            home?.delegate = self
            reload()
        }
    }

    func reload() {
        let rooms: [Room]
        if let home = home {
            rooms = home.rooms.map { r in
                Room(id: r.uniqueIdentifier, name: r.name)
            }
        }else {
            rooms = []
        }
        homeManagerDelegate?.rooms = rooms
    }

    func home(_ home: HMHome, didUpdateNameFor room: HMRoom) {
        if let index = homeManagerDelegate?.rooms.firstIndex(where: { $0.id == room.uniqueIdentifier } ) {
            homeManagerDelegate?.rooms[index].name = room.name
        }
     }
</code>```

Note: I'd recommend not using structs that mirror the home classes and instead create a struct that contains what you want to show in your UI. And in your model ObservableObject you could have several @Published arrays of different custom structs for different HomeKit related things. Apple's Fruta and Scrumdinger sample projects can help with that.

ContentLicense: CC BY-SA 4.0

Body:
Every SwiftUI tutorial/example uses model objects that are defined by me, the guy writing the app. However, what is the best practice when the model objects are not under my direct control? For example, the HomeKit framework has an API to get all the rooms in a given home. It returns an array of HMRoom objects:

open class HMRoom: NSObject
{
    open var name: String { get }
    open var accessories: [HMAccessory] { get }
    open var uniqueIdentifier: UUID { get }

    // Update the room's name in a HomeKit-compliant way that notifies all other HomeKit apps
    open func updateName(_ name: String) async throws
}

When I receive an array of HMRoom objects from the HomeKit API, what should I do with them to power SwiftUI? Should I create my own class that looks like this:

final class Room: ObservableObject
{
    @Published var name: String
    @Published var accessories: [Accessory]
    @Published var uniqueIdentifier: UUID

    private var representedRoom: HMRoom

    init(homekitRoom: HMRoom)
    {
        // Copy properties from 'homekitRoom' to self, then set `representedRoom` to `homekitRoom` so we can use it to call the updateName(:) function
    }
}

Is there, instead, a way for me to extend the HMRoom class directly to inform SwiftUI that name, accessories, and uniqueIdentifier are the properties we must watch for changes in order to reload views appropriately?

It's unclear to me what the best approach is to integrate @Published/@ObservableObject when I don't write the model classes/structs myself.

Body:
If you read Apple's document Choosing Between Structures and Classes the Use Classes When You Need to Control Identity section makes you think use a class, however if you read the Use Structures When You Don't Control Identity section and notice that every HomeKit object contains a uniqueIdentifier it turns out we can use structs yay!

struct Room: Identifiable {
    let id: UUID
    var name: String
}

class HomeDelegate: NSObject, HMHomeDelegate {
    weak var homeManagerDelegate: HomeManagerDelegate?

    // HomeManagerDelegate sets the primaryHome.
    var home: HMHome? {
        didSet {
            oldValue?.delegate = nil
            home?.delegate = self
            reload()
        }
    }

    func reload() {
        let rooms: [Room]
        if let home = home {
            rooms = home.rooms.map { r in
                Room(id: r.uniqueIdentifier, name: r.name)
            }
        }else {
            rooms = []
        }
        homeManagerDelegate?.rooms = rooms
    }

    func home(_ home: HMHome, didUpdateNameFor room: HMRoom) {
        if let index = homeManagerDelegate?.rooms.firstIndex(where: { $0.id == room.uniqueIdentifier } ) {
            homeManagerDelegate?.rooms[index].name = room.name
        }
     }

Note: I'd recommend not using structs that mirror the home classes and instead create a struct that contains what you want to show in your UI. And in your model ObservableObject you could have several @Published arrays of different custom structs for different HomeKit related things. Apple's Fruta and Scrumdinger sample projects can help with that.


问:
How to lazy load web font declared by @font-face?
What I've got is a font-family CSS declaration to use a stylised web font first, and fall back to system fonts. This works fine, but my web font is huge ~15MB (Chinese font) and even hosting this on CDN it takes over 5s to load.

The problem with this is that browsers handle the display differently. I think Firefox has the preferred way, which is to use whichever font is available first (system font) and progressively display in the web font when it is ready (loaded).

However, Chrome just tries to use the web font first (as this is listed first in the font-family) and just displays a blank space until the font is ready to render the text.

Is there a way to make Chrome behave the same as Firefox?

EDIT: Add font-family declaration.

```<code>font-family: "Noto Sans CJK TC", "Microsoft Yahei", "微软雅黑",
             SimHei, "黑体", STHeiti, "华文黑体", sans-serif;
</code>```

答:
the simple way to achieve this to add

```<code>@font-face {
    font-display: swap;
}
</code>```

for more information
https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display

ContentLicense: CC BY-SA 3.0

Body:
What I've got is a font-family CSS declaration to use a stylised web font first, and fall back to system fonts. This works fine, but my web font is huge ~15MB (Chinese font) and even hosting this on CDN it takes over 5s to load.

The problem with this is that browsers handle the display differently. I think Firefox has the preferred way, which is to use whichever font is available first (system font) and progressively display in the web font when it is ready (loaded).

However, Chrome just tries to use the web font first (as this is listed first in the font-family) and just displays a blank space until the font is ready to render the text.

Is there a way to make Chrome behave the same as Firefox?

EDIT: Add font-family declaration.

font-family: "Noto Sans CJK TC", "Microsoft Yahei", "微软雅黑",
             SimHei, "黑体", STHeiti, "华文黑体", sans-serif;

Body:
the simple way to achieve this to add

@font-face {
    font-display: swap;
}

for more information
https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display


问:
How to preview a Composable with non-null type parameters?
```<code>@Composable
fun VerifyScreen(
    email: String,
    navigator: DestinationsNavigator
) {
// ..

}

@Composable
@Preview
fun VerifyScreenPreview() {
    VerifyScreen("you@re.awesome", null)
}
</code>```

Null can not be a value of a non-null type DestinationsNavigator

Of course you can change the type by adding a question mark, but what if that is not an option?

```<code>navigator: DestinationsNavigator?
</code>```

答:
You can use This pattern</p>
```<code>@Composable
fun VerifyScreen(
    email: String,
    navigator: DestinationsNavigator
) {
    VerifyScreenContent(
        email = email,
        navigator = {
            //...
        },
        navigator2 = {
            //...
        },
        navigator3 = {
            //...
        },
    )
}

@Composable
fun VerifyScreenContent(
    email: String,
    navigator: () -> Unit,
    navigator2: () -> Unit,
    navigator3: () -> Unit,
) {
// ..

}

@Composable
@Preview
fun VerifyScreenContentPreview() {
    VerifyScreen("you@re.awesome", {}, {}, {})
}
</code>```

Body:
@Composable
fun VerifyScreen(
    email: String,
    navigator: DestinationsNavigator
) {
// ..

}

@Composable
@Preview
fun VerifyScreenPreview() {
    VerifyScreen("you@re.awesome", null)
}

Null can not be a value of a non-null type DestinationsNavigator

Of course you can change the type by adding a question mark, but what if that is not an option?

navigator: DestinationsNavigator?

Body:
You can use This pattern

@Composable
fun VerifyScreen(
    email: String,
    navigator: DestinationsNavigator
) {
    VerifyScreenContent(
        email = email,
        navigator = {
            //...
        },
        navigator2 = {
            //...
        },
        navigator3 = {
            //...
        },
    )
}

@Composable
fun VerifyScreenContent(
    email: String,
    navigator: () -> Unit,
    navigator2: () -> Unit,
    navigator3: () -> Unit,
) {
// ..

}

@Composable
@Preview
fun VerifyScreenContentPreview() {
    VerifyScreen("you@re.awesome", {}, {}, {})
}


问:
How to narrow type to object and exclude boolean type?
I am stuck in simple example, tried different tricks to narrow type but TS giving me errors.
Consider following example:

```<code>interface IObject {
    someField: string
}

interface ISomething {
    inner:  IObject | boolean
}

function returnValue(s: string, smth: ISomething): string {
    if (s === 'inner')
        return smth[s].someField
    else
        return ''
}
</code>```

Playground link

How would you tell TS that smth['inner'] is of type IObject, excluding boolean type so TS won't error: Property 'someField' does not exist on type 'boolean | IObject'.
Property 'someField' does not exist on type 'false'.(2339)

答:
Just add an extra condition statement:

interface IObject {
    someField: string
}

interface ISomething {
    inner: IObject | boolean
}

function returnValue(s: string, smth: ISomething) {
    if (s === 'inner') {
        const value = smth[s];
      // Or typeof value === 'object'
        if (typeof value !== 'boolean') {
            return value.someField
        }
    }

    return ''
}
```
<p>Playground</p>
<p>I think this is a good place to use function overloadings. COnsider this example:</p>
<pre class="lang-js prettyprint-override"><code>interface IObject<SomeField> {
    someField: SomeField
}

interface ISomething<T> {
    inner: IObject<T> | boolean
}

function returnValue(s: 'inner', smth: { inner: boolean }): ''
function returnValue<SomeField extends string>(s: 'inner', smth: ISomething<SomeField>): SomeField
function returnValue(s: string, smth: ISomething<string>): ''
function returnValue(s: string, smth: ISomething<string>) {
    if (s === 'inner') {
        const value = smth[s];
        if (typeof value !== 'boolean') {
            return value.someField
        }
    }

    return ''
}

const result1 = returnValue('inner', { inner: { someField: 'hello' } }) // "hello"
const result2 = returnValue('inner', { inner: true }) // ""
const result3 = returnValue('other', { inner: true }) // ""
</code>```

Playground

Body:
I am stuck in simple example, tried different tricks to narrow type but TS giving me errors.
Consider following example:

interface IObject {
    someField: string
}

interface ISomething {
    inner:  IObject | boolean
}

function returnValue(s: string, smth: ISomething): string {
    if (s === 'inner')
        return smth[s].someField
    else
        return ''
}

Playground link

How would you tell TS that smth['inner'] is of type IObject, excluding boolean type so TS won't error: Property 'someField' does not exist on type 'boolean | IObject'.
Property 'someField' does not exist on type 'false'.(2339)

Body:
Just add an extra condition statement:

interface IObject {
    someField: string
}

interface ISomething {
    inner: IObject | boolean
}

function returnValue(s: string, smth: ISomething) {
    if (s === 'inner') {
        const value = smth[s];
      // Or typeof value === 'object'
        if (typeof value !== 'boolean') {
            return value.someField
        }
    }

    return ''
}

Playground

I think this is a good place to use function overloadings. COnsider this example:

interface IObject<SomeField> {
    someField: SomeField
}

interface ISomething<T> {
    inner: IObject<T> | boolean
}

function returnValue(s: 'inner', smth: { inner: boolean }): ''
function returnValue<SomeField extends string>(s: 'inner', smth: ISomething<SomeField>): SomeField
function returnValue(s: string, smth: ISomething<string>): ''
function returnValue(s: string, smth: ISomething<string>) {
    if (s === 'inner') {
        const value = smth[s];
        if (typeof value !== 'boolean') {
            return value.someField
        }
    }

    return ''
}

const result1 = returnValue('inner', { inner: { someField: 'hello' } }) // "hello"
const result2 = returnValue('inner', { inner: true }) // ""
const result3 = returnValue('other', { inner: true }) // ""

Playground


问:
two question about python regular expressions
Q1. why we can not use word boundary and back reference without using r at start of regex?
e.g. '\b[a-z]{5}\d{3}\b' this not works but this r'\b[a-z]{5}\d{3}\b' works

Q2. why python does not support variable length negative look behind assertions while it supports variable length negative look ahead assertion, c# support both and i think it is an excellent feature to have also variable length negative look behind in python.

please clear these two concepts. thanks

答:
Almost all information you can find in tutorial - which is your the best friend:

Regular expressions use the backslash character ('\') to indicate
  special forms or to allow special characters to be used without
  invoking their special meaning. This collides with Python’s usage of
  the same character for the same purpose in string literals; for
  example, to match a literal backslash, one might have to write '\\'
  as the pattern string, because the regular expression must be \, and
  each backslash must be expressed as \ inside a regular Python string
  literal.

The solution is to use Python’s raw string notation for regular
  expression patterns; backslashes are not handled in any special way in
  a string literal prefixed with 'r'. So r"\n" is a two-character string
  containing '\' and 'n', while "\n" is a one-character string
  containing a newline. Usually patterns will be expressed in Python
  code using this raw string notation.

It is quite hard to answer on your second question - i think that authors are implementing only those features which they think are required. They try to add code that is useful for the most of user but it is impossible to implement all the features fast.


Title: Getting conditionally value on another variable

Body:
I have the following dataframe:

df <- tribble(~ id,  ~ year, ~ born, ~income,
                 1,    2015,     -1,    3005,
                 2,    2015,     -1,    3500,
                 3,    2015,     -1,    3090,
                 4,    2015,     -1,    3000,
                 5,    2015,     NA,     700,
                 1,    2016,      0,    2005,
                 2,    2016,      0,    2500,
                 3,    2016,      0,    2090,
                 4,    2016,      0,    2050,
                 5,    2005,     NA,     900,
                 1,    2017,      1,    1005,
                 2,    2017,      1,    1500,
                 3,    2017,      1,    1090,
                 4,    2017,      1,    1000,
                 5,    2017,     NA,    1500)

I want to create another variable (e.g., "pre_income" that only takes the value of the variable income when born is -1.

df_wanted <- tribble(~ id,  ~ year, ~ born, ~income, ~pre_income,
                        1,    2015,     -1,    3005,        3005,
                        2,    2015,     -1,    3500,        3500,
                        3,    2015,     -1,    3090,        3090,
                        4,    2015,     -1,    3000,        3000,
                        5,    2015,     NA,     700,          NA,
                        1,    2016,      0,    2005,        3005,
                        2,    2016,      0,    2500,        3500,
                        3,    2016,      0,    2090,        3090,
                        4,    2016,      0,    2050,        3000,
                        5,    2016,     NA,     900,          NA,
                        1,    2017,      1,    1005,        3005,
                        2,    2017,      1,    1500,        3500,
                        3,    2017,      1,    1090,        3090,
                        4,    2017,      1,    1000,        3000,
                        5,    2017,     NA,    1500,          NA)

Any help would be really appreciated!

The solution provided above does not work when there are NAs in the born variable.

Body:
You can group_by id and get the income value when born == -1.

library(dplyr)
df %>%
  group_by(id) %>%
  mutate(pre_income = income[born == -1]) %>%
  ungroup

# A tibble: 15 x 5
      id  year  born income pre_income
   <dbl> <dbl> <dbl>  <dbl>      <dbl>
 1     1  2015    -1   3005       3005
 2     2  2015    -1   3500       3500
 3     3  2015    -1   3090       3090
 4     4  2015    -1   3000       3000
 5     5  2015    NA    700         NA
 6     1  2016     0   2005       3005
 7     2  2016     0   2500       3500
 8     3  2016     0   2090       3090
 9     4  2016     0   2050       3000
10     5  2005    NA    900         NA
11     1  2017     1   1005       3005
12     2  2017     1   1500       3500
13     3  2017     1   1090       3090
14     4  2017     1   1000       3000
15     5  2017    NA   1500         NA

data

df <- tribble(~ id,  ~ year, ~ born, ~income,
              1,    2015,     -1,    3005,
              2,    2015,     -1,    3500,
              3,    2015,     -1,    3090,
              4,    2015,     -1,    3000,
              5,    2015,     NA,     700,
              1,    2016,      0,    2005,
              2,    2016,      0,    2500,
              3,    2016,      0,    2090,
              4,    2016,      0,    2050,
              5,    2005,     NA,     900,
              1,    2017,      1,    1005,
              2,    2017,      1,    1500,
              3,    2017,      1,    1090,
              4,    2017,      1,    1000,
              5,    2017,     NA,    1500)


问:
scrapy spider code not running because of syntax?
so my projects seem to keep failing for the same reason. I get syntax error. I'm using anaconda and visual code studio, I have the environment setup correctly, i think*.

The code i'm using is the following:

```<code>import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class BestMoviesSpider(CrawlSpider):
    name = 'best_movies'
    allowed_domains = ['imdb.com']
    start_urls = ['https://www.imdb.com/chart/top']

    rules = (
        Rule(LinkExtractor(restrict_xpaths="//td[@class='titleColumn']/a"), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
       yield {
           'title': response.xpath("//h1/text()").get(),
            'year': response.xpath("//li[@class="ipc-inline-list__item"]/span/text()").get(),
           'duration': response.xpath("(//li[@class="ipc-inline-list__item"])[3]/text()").get(),
           'genre': response.xpath("//span[@class="ipc-chip__text"]/text()").get(),
           'rating': response.xpath("//span[@class="AggregateRatingButton__RatingScore-sc-1ll29m0-1 iTLWoV"]/text()").get(),
           'movie_url': response.url,
       }
</code>```

The error I'm getting is : line 18
'year': response.xpath("//li[@class="ipc-inline-list__item"]/span/text()").get(),
^
SyntaxError: invalid syntax

Also, I have 2 errors on VSC regarding { and ( not being closed but I think that's because my code isn't running.

Thank you in advance!

答:
The issue is in the string definition of the xpaths.

You can just use single quotes and you should be fine:

```<code># not
'year': response.xpath("//li[@class="ipc-inline-list__item"]/span/text()").get(),

# Instead use
'year': response.xpath('//li[@class="ipc-inline-list__item"]/span/text()').get(),
</code>```

Body:
so my projects seem to keep failing for the same reason. I get syntax error. I'm using anaconda and visual code studio, I have the environment setup correctly, i think*.

The code i'm using is the following:

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class BestMoviesSpider(CrawlSpider):
    name = 'best_movies'
    allowed_domains = ['imdb.com']
    start_urls = ['https://www.imdb.com/chart/top']

    rules = (
        Rule(LinkExtractor(restrict_xpaths="//td[@class='titleColumn']/a"), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
       yield {
           'title': response.xpath("//h1/text()").get(),
            'year': response.xpath("//li[@class="ipc-inline-list__item"]/span/text()").get(),
           'duration': response.xpath("(//li[@class="ipc-inline-list__item"])[3]/text()").get(),
           'genre': response.xpath("//span[@class="ipc-chip__text"]/text()").get(),
           'rating': response.xpath("//span[@class="AggregateRatingButton__RatingScore-sc-1ll29m0-1 iTLWoV"]/text()").get(),
           'movie_url': response.url,
       }

The error I'm getting is : line 18
'year': response.xpath("//li[@class="ipc-inline-list__item"]/span/text()").get(),
^
SyntaxError: invalid syntax

Also, I have 2 errors on VSC regarding { and ( not being closed but I think that's because my code isn't running.

Thank you in advance!

Body:
The issue is in the string definition of the xpaths.

You can just use single quotes and you should be fine:

# not
'year': response.xpath("//li[@class="ipc-inline-list__item"]/span/text()").get(),

# Instead use
'year': response.xpath('//li[@class="ipc-inline-list__item"]/span/text()').get(),


问:
How do I read an entire file into a std::string in C++?
How do I read a file into a std::string, i.e., read the whole file at once?

Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.

One way to do this would be to stat the filesize, resize the std::string and fread() into the std::string's const_cast<char*>()'ed data(). This requires the std::string's data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the std::string's size may not equal the file's size.

A fully correct, standard-compliant and portable solutions could be constructed using std::ifstream's rdbuf() into a std::ostringstream and from there into a std::string. However, this could copy the string data and/or needlessly reallocate memory.

Are all relevant standard library implementations smart enough to avoid all unnecessary overhead?

Is there another way to do it?

Did I miss some hidden Boost function that already provides the desired functionality?

```<code>void slurp(std::string& data, bool is_binary)
</code>```

答:
```<code>#include <string>
#include <fstream>

int main()
{
    std::string fileLocation = "C:\\Users\\User\\Desktop\\file.txt";
    std::ifstream file(fileLocation, std::ios::in | std::ios::binary);

    std::string data;

    if(file.is_open())
    {
        std::getline(file, data, '\0');

        file.close();
    }
}
</code>```

LastEditorDisplayName: Nils

Body:
How do I read a file into a std::string, i.e., read the whole file at once?

Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.

One way to do this would be to stat the filesize, resize the std::string and fread() into the std::string's const_cast<char*>()'ed data(). This requires the std::string's data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the std::string's size may not equal the file's size.

A fully correct, standard-compliant and portable solutions could be constructed using std::ifstream's rdbuf() into a std::ostringstream and from there into a std::string. However, this could copy the string data and/or needlessly reallocate memory.

Are all relevant standard library implementations smart enough to avoid all unnecessary overhead?

Is there another way to do it?

Did I miss some hidden Boost function that already provides the desired functionality?

void slurp(std::string& data, bool is_binary)


问:
Unable to cf push the Spring Boot 2.6.1 app, giving zip: not a valid zip file
I have created a simple Spring Boot App (2.6.1) with Gradle.

Created an endpoint which is running fine in local.

However when I tried to publish it to pcf using cf pushcommand it's giving zip: not a valid zip file error.

I am using following manifest file

```<code>---
applications:
  - timeout: 180
    name: SpringLatest
    instances: 1
    memory: 1G
    disk_quota: 1G
    health-check-type: port
    path: /build/libs/SpringLatest-1.0.0-LOCAL.jar
    buildpacks:
    - https://github.com/cloudfoundry/java-buildpack.git
    env:
      SPRING_PROFILES_ACTIVE: dev
      APP_ENVIRONMENT: dev
      JBP_CONFIG_OPEN_JDK_JRE: '{jre: { version: 11.0.7_10 }}'
      JBP_LOG_LEVEL: DEBUG
      CF_HEALTH_CHECK_TIMEOUT: 1200
      JAVA_OPTS: -Xms512M -Xmx512M
</code>```

答:
Had same problem while upgrading from Spring boot version 2.5.X to 2.6.X with Maven for dependency management. Resolved this error by excluding repackage goal in maven plugin executions.</p>
```<code>    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</code>```

Body:
I have created a simple Spring Boot App (2.6.1) with Gradle.

Created an endpoint which is running fine in local.

However when I tried to publish it to pcf using cf pushcommand it's giving zip: not a valid zip file error.

I am using following manifest file

---
applications:
  - timeout: 180
    name: SpringLatest
    instances: 1
    memory: 1G
    disk_quota: 1G
    health-check-type: port
    path: /build/libs/SpringLatest-1.0.0-LOCAL.jar
    buildpacks:
    - https://github.com/cloudfoundry/java-buildpack.git
    env:
      SPRING_PROFILES_ACTIVE: dev
      APP_ENVIRONMENT: dev
      JBP_CONFIG_OPEN_JDK_JRE: '{jre: { version: 11.0.7_10 }}'
      JBP_LOG_LEVEL: DEBUG
      CF_HEALTH_CHECK_TIMEOUT: 1200
      JAVA_OPTS: -Xms512M -Xmx512M

Body:
Had same problem while upgrading from Spring boot version 2.5.X to 2.6.X with Maven for dependency management. Resolved this error by excluding repackage goal in maven plugin executions.

    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>


问:
how to remove query string from url using htaccess
Once my friend help me to solve this issue, I have written code like that. Where example.com/blog-detail?slug=slugvalue it goes to blog-detail.php and this url example.com/project?slug=test goes to project.php.

```<code>RewriteEngine ON
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{THE_REQUEST} \s([^?]*)\?slug=(\S+)\s [NC]
RewriteRule ^ %1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  blog-detail.php?slug=$1 [QSA,L]
</code>```

I think it's work for only blog-detail page now i face the issue with this url
https://www.example.com/project?slug=test, it redirect me to 404 page, could you help me here.

答:
With your shown samples, attempts; please try following htaccess rules file. Please make sure to clear your browser cache before testing your URLs.

I have added 2 solutions here, so either use 1st rules set OR use 2nd rules set ONLY ONE at a time please.

1st solution: With 2 different rules set for each php file please try following rules.

```<code>RewriteEngine ON
###Rules for blog-detail.php redirect and rewrite.
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s(blog-detail)\?slug=(\S+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  blog-detail.php?slug=$1 [QSA,L]

###Rules for project.php redirect and rewrite.
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s(project)\?slug=(\S+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  project.php?slug=$1 [QSA,L]
</code>```

2nd solution: A Generic solution with capturing groups to deal with both kind of php files together.

```<code>RewriteEngine ON
###Rules for blog-detail.php OR project.php redirect and rewrite.
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s([^?]*)\?slug=(\S+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/(.*)/?$  /$1.php?slug=$2 [QSA,L]
</code>```

NOTE1: Please keep both your php files(project.php and blog-detail.php) should be kept along with your htaccess rules file.

NOTE2: For JS/CS rewrite/redirect:
You may need to use base tag to fix your js and other relative resources. If you are linking js files using a relative path then the file will obviously get a 404 because its looking for URL path. for example if the URL path is /file/ instead of file.html then your relative resources are loading from /file/ which is not a directory but rewritten html file. To fix this make your links absolute or use base tag. In the header of your webpage add this <base href="/"> so that your relative links can load from the correct location.

Body:
Once my friend help me to solve this issue, I have written code like that. Where example.com/blog-detail?slug=slugvalue it goes to blog-detail.php and this url example.com/project?slug=test goes to project.php.

RewriteEngine ON
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{THE_REQUEST} \s([^?]*)\?slug=(\S+)\s [NC]
RewriteRule ^ %1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  blog-detail.php?slug=$1 [QSA,L]

I think it's work for only blog-detail page now i face the issue with this url
https://www.example.com/project?slug=test, it redirect me to 404 page, could you help me here.

Body:
With your shown samples, attempts; please try following htaccess rules file. Please make sure to clear your browser cache before testing your URLs.

I have added 2 solutions here, so either use 1st rules set OR use 2nd rules set ONLY ONE at a time please.

1st solution: With 2 different rules set for each php file please try following rules.

RewriteEngine ON
###Rules for blog-detail.php redirect and rewrite.
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s(blog-detail)\?slug=(\S+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  blog-detail.php?slug=$1 [QSA,L]

###Rules for project.php redirect and rewrite.
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s(project)\?slug=(\S+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  project.php?slug=$1 [QSA,L]

2nd solution: A Generic solution with capturing groups to deal with both kind of php files together.

RewriteEngine ON
###Rules for blog-detail.php OR project.php redirect and rewrite.
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s([^?]*)\?slug=(\S+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/(.*)/?$  /$1.php?slug=$2 [QSA,L]

NOTE1: Please keep both your php files(project.php and blog-detail.php) should be kept along with your htaccess rules file.

NOTE2: For JS/CS rewrite/redirect:
You may need to use base tag to fix your js and other relative resources. If you are linking js files using a relative path then the file will obviously get a 404 because its looking for URL path. for example if the URL path is /file/ instead of file.html then your relative resources are loading from /file/ which is not a directory but rewritten html file. To fix this make your links absolute or use base tag. In the header of your webpage add this <base href="/"> so that your relative links can load from the correct location.


问:
LARAVEL8: Photo not uploading to database, but rest of the form does
This is my FileUploadController:

```<code>public function createFile(Request $request){
    $file = new File;
    $file->cursa=$request->cursa;
    $file->referinta=$request->referinta;
    $file->obs=$request->obs;

    if ($request->hasFile('photo')){
        $extension = $request->file('photo')->getClientOriginalExtension();
        $photoName = str_replace('','', $request->cursa). '_'. time(). '.' .$extension;
        $request->file('photo')->move(public_path('images'), $photoName);
        $file->photo = $photoName;
    }

    $file->save();
    return redirect()->back();
}
</code>```

This is the whole form:

```<code>@extends('admin.template')
@section('title', 'Add User')
@section('content')

<link href="{{ asset('/styles.css') }}" rel="stylesheet">
<div id="layoutSidenav_content">

        <form action="{{route('fileUpload')}}" method="post" enctype="multipart/form-data">
          <h3 class="text-center mb-5">Trimite Fisier</h3>
            @csrf
            @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <strong>{{ $message }}</strong>
            </div>
          @endif
          @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
          @endif
          <div class="form-group">
    <label for="exampleFormControlInput1">Nume Cursa</label>
    <input type="text" name="cursa" required  class="form-control @error('cursa') invalida @enderror" id="cursa"   placeholder="123456/1">
    <span class="text-danger">
      @error('cursa')
      {{$message}}
      @enderror
    </span>
  </div>
  <div class="form-group">
    <label for="exampleFormControlInput1">Referinta</label>
    <input type="text" name="referinta" class="form-control @error('referinta') invalida @enderror" id="referinta" placeholder="">
    <span class="text-danger">
      @error('referinta')
{{$message}}
@enderror
    </span>
  </div>
  <div class="form-group">
    <label for="obs">Observatii</label>
    <textarea class="form-control" name="obs" id="obs" rows="3"></textarea>
  </div>

          <div>
            <button id="start-camera">Start Camera</button>
<video name="photo" id="video" width="320" height="240" autoplay></video>
<button  name="photo" id="click-photo">Click Photo</button>
<canvas id="canvas" width="320" height="240"></canvas>
</div>
            <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
                Upload Files
            </button>

        </form>
        <script>
          let camera_button = document.querySelector("#start-camera");
let video = document.querySelector("#video");
let click_button = document.querySelector("#click-photo");
let canvas = document.querySelector("#canvas");

camera_button.addEventListener('click', async function() {
    let stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
    video.srcObject = stream;
});

click_button.addEventListener('click', function() {
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
    let image_data_url = canvas.toDataURL('image/jpeg/png');

    // data url of the image
    console.log(image_data_url);
});
        </script>
        <script type="text/javascript" src="{{ asset('/chart-area-demo.js') }}"></script>
            <script type="text/javascript" src="{{ asset('/chart-bar-demo.js') }}"></script>
            <script type="text/javascript" src="{{ asset('/datatables-demo.js') }}"></script>
            <script type="text/javascript" src="{{ asset('/datatables-simple-demo.js') }}"></script>
            <script type="text/javascript" src="{{ asset('/scripts.js') }}"></script>

@endsection
</code>```

And this is my part of the form with the javascript to take the picture and store it

```<code> <button id="start-camera">Start Camera</button>
<video name="photo" id="video" width="320" height="240" autoplay></video>
<button  name="photo" id="click-photo">Click Photo</button>
<canvas id="canvas" width="320" height="240"></canvas>
</div>
            <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
                Upload Files
            </button>

        </form>
        <script>
          let camera_button = document.querySelector("#start-camera");
let video = document.querySelector("#video");
let click_button = document.querySelector("#click-photo");
let canvas = document.querySelector("#canvas");

camera_button.addEventListener('click', async function() {
    let stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
    video.srcObject = stream;
});

click_button.addEventListener('click', function() {
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
    let image_data_url = canvas.toDataURL('image/jpeg/png');

    // data url of the image
    console.log(image_data_url);
});
</code>```

All the data excluding the actual photo is loaded to database, but the picture itself does not, any ideas? I've tried a lot of tutorials but really I can't understand what is not working. My guess is that it's probably a rookie mistake but really can't put my finger on it.
Also here is a picture of mysql structure for this

答:
I would add an input element and put the data url from your console.log into it.

let camera_button = document.querySelector("#start-camera");
let video = document.querySelector("#video");
let click_button = document.querySelector("#click-photo");
let canvas = document.querySelector("#canvas");

camera_button.addEventListener('click', async function() {
    let stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
    video.srcObject = stream;
});

click_button.addEventListener('click', function() {
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
    let image_data_url = canvas.toDataURL('image/jpeg/png');

    // data url of the image
    console.log(image_data_url);
    document.querySelector('input[name="photo"]').value = image_data_url; // this line
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="{{route('fileUpload')}}" method="post" enctype="multipart/form-data">
  <!-- ... -->
  <button id="start-camera">Start Camera</button>
  <video name="photo" id="video" width="320" height="240" autoplay></video>
  <input type="hidden" name="photo">
  <button  name="photo" id="click-photo">Click Photo</button>
  <canvas id="canvas" width="320" height="240"></canvas>
  </div>
  <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
      Upload Files
  </button>
</form></code>```

Body:
This is my FileUploadController:

public function createFile(Request $request){
    $file = new File;
    $file->cursa=$request->cursa;
    $file->referinta=$request->referinta;
    $file->obs=$request->obs;

    if ($request->hasFile('photo')){
        $extension = $request->file('photo')->getClientOriginalExtension();
        $photoName = str_replace('','', $request->cursa). '_'. time(). '.' .$extension;
        $request->file('photo')->move(public_path('images'), $photoName);
        $file->photo = $photoName;
    }

    $file->save();
    return redirect()->back();
}

This is the whole form:

@extends('admin.template')
@section('title', 'Add User')
@section('content')

<link href="{{ asset('/styles.css') }}" rel="stylesheet">

        <form action="{{route('fileUpload')}}" method="post" enctype="multipart/form-data">

Trimite Fisier

            @csrf
            @if ($message = Session::get('success'))

                {{ $message }}

          @endif
          @if (count($errors) > 0)

                    @foreach ($errors->all() as $error)

{{ $error }}

                    @endforeach

          @endif

    Nume Cursa
    <input type="text" name="cursa" required  class="form-control @error('cursa') invalida @enderror" id="cursa"   placeholder="123456/1">

      @error('cursa')
      {{$message}}
      @enderror

    Referinta
    <input type="text" name="referinta" class="form-control @error('referinta') invalida @enderror" id="referinta" placeholder="">

      @error('referinta')
{{$message}}
@enderror

    Observatii
    <textarea class="form-control" name="obs" id="obs" rows="3"></textarea>

            <button id="start-camera">Start Camera</button>
<video name="photo" id="video" width="320" height="240" autoplay></video>
<button  name="photo" id="click-photo">Click Photo</button>
<canvas id="canvas" width="320" height="240"></canvas>

            <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
                Upload Files
            </button>

        </form>

@endsection

And this is my part of the form with the javascript to take the picture and store it

 <button id="start-camera">Start Camera</button>
<video name="photo" id="video" width="320" height="240" autoplay></video>
<button  name="photo" id="click-photo">Click Photo</button>
<canvas id="canvas" width="320" height="240"></canvas>

            <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
                Upload Files
            </button>

        </form>

Body:
I would add an input element and put the data url from your console.log into it.

let camera_button = document.querySelector("#start-camera");
let video = document.querySelector("#video");
let click_button = document.querySelector("#click-photo");
let canvas = document.querySelector("#canvas");

camera_button.addEventListener('click', async function() {
    let stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
    video.srcObject = stream;
});

click_button.addEventListener('click', function() {
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
    let image_data_url = canvas.toDataURL('image/jpeg/png');

    // data url of the image
    console.log(image_data_url);
    document.querySelector('input[name="photo"]').value = image_data_url; // this line
});

<form action="{{route('fileUpload')}}" method="post" enctype="multipart/form-data">
  <!-- ... -->
  <button id="start-camera">Start Camera</button>
  <video name="photo" id="video" width="320" height="240" autoplay></video>
  <input type="hidden" name="photo">
  <button  name="photo" id="click-photo">Click Photo</button>
  <canvas id="canvas" width="320" height="240"></canvas>
  </div>
  <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
      Upload Files
  </button>
</form>


问:
Stripe Api Getting data from given date
How Can I get some data starting from the given Date, is there any query parameter for that just like "starting_after" for pagination??</p>

答:
Yep, there are date filters. For example, if you wanted to search for invoices in dotnet, you can use the "created" filter to find invoices created before or after a given date</p>
```<code>var filters = new InvoiceListOptions()
{
    Created = new DateRangeOptions
    {
        GreaterThan = startDate,
        LessThanOrEqual = endDate
    }
};
</code>```

Title: Stripe Api Getting data from given date

Body:
Yep, there are date filters. For example, if you wanted to search for invoices in dotnet, you can use the "created" filter to find invoices created before or after a given date

var filters = new InvoiceListOptions()
{
    Created = new DateRangeOptions
    {
        GreaterThan = startDate,
        LessThanOrEqual = endDate
    }
};


答:
It seems to be a problem of quotes:

Try to replace year: response.xpath("//li[@class="ipc-inline-list__item"]/span/text()").get()

by year: response.xpath('//li[@class="ipc-inline-list__item"]/span/text()').get()

Title: scrapy spider code not running because of syntax?


问:
App_Code folder is missing in VS 2010
I was trying to create a Dynamic Data Website using VS 2010 RC.  An attempt to create an App_Code folder where I would put a LINQ to SQL class, failed. When I selected 'Add ASP.NET Folder' to add the folder,  I had options to create only the following folders:

App_GlobalResources

App_LocalResources

App_Data

App_Browsers

Theme

What happened to the App_Code folder?

答: in VS 2010, you need to create a solution, then right-click -> add new website, then when you add classes, linq2sql etc, vs will create the app_code folder for you</p>

ContentLicense: CC BY-SA 2.5

Title: App_Code folder is missing in VS 2010


问:
Old version of Microsoft.NETCore.App cannot be found at release step
I have an error in my build pipeline on Azure DevOps. The project called DevPortalWeb fails in the Publish step.

The project is upgraded to netcore3.1 (it was created with earlier version).

```<code>  DevPortalWeb -> C:\agent\_work\13\s\Application\DevPortalWeb\bin\release\netcoreapp3.1\DevPortalWeb.dll
  DevPortalWeb -> C:\agent\_work\13\s\Application\DevPortalWeb\bin\release\netcoreapp3.1\DevPortalWeb.Views.dll
  It was not possible to find any compatible framework version
  The framework 'Microsoft.NETCore.App', version '2.0.0-preview1-002111-00' (x64) was not found.
    - The following frameworks were found:
        3.1.22 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
        5.0.13 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
        6.0.1 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

  You can resolve the problem by installing the specified framework and/or SDK.

  The specified framework can be found at:
    - https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=2.0.0-preview1-002111-00&arch=x64&rid=win10-x64
C:\agent\_work\13\s\Application\DevPortalWeb\DevPortalWeb.csproj(45,3): error MSB3073: The command "dotnet bundle" exited with code -2147450730.
##[error]Error: The process 'C:\Program Files\dotnet\dotnet.exe' failed with exit code 1
</code>```

What could be a reason, that the build pipeline requires previous version of the framework? There is no reference to version '2.0.0-preview1-002111-00' in the project now.

答:
The problem was, that project was migrated from .NET Core 2.2 to .NET Core 3.1.
Several packages, including this one, do not target this version anymore. This is already included in version 3.0.

The migration documentation lists which packages are obsolete:

https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-6.0&tabs=visual-studio#remove-obsolete-package-references

Body:
I have an error in my build pipeline on Azure DevOps. The project called DevPortalWeb fails in the Publish step.

The project is upgraded to netcore3.1 (it was created with earlier version).

  DevPortalWeb -> C:\agent\_work\13\s\Application\DevPortalWeb\bin\release\netcoreapp3.1\DevPortalWeb.dll
  DevPortalWeb -> C:\agent\_work\13\s\Application\DevPortalWeb\bin\release\netcoreapp3.1\DevPortalWeb.Views.dll
  It was not possible to find any compatible framework version
  The framework 'Microsoft.NETCore.App', version '2.0.0-preview1-002111-00' (x64) was not found.
    - The following frameworks were found:
        3.1.22 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
        5.0.13 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
        6.0.1 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

  You can resolve the problem by installing the specified framework and/or SDK.

  The specified framework can be found at:
    - https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=2.0.0-preview1-002111-00&arch=x64&rid=win10-x64
C:\agent\_work\13\s\Application\DevPortalWeb\DevPortalWeb.csproj(45,3): error MSB3073: The command "dotnet bundle" exited with code -2147450730.
##[error]Error: The process 'C:\Program Files\dotnet\dotnet.exe' failed with exit code 1

What could be a reason, that the build pipeline requires previous version of the framework? There is no reference to version '2.0.0-preview1-002111-00' in the project now.


问:
Event triggered definition of array elements gives wrong values
The purpose of this model is to provide the indexed elements of the "vector" array the values of the array "tester", which are increasing numbers from 1 to 12.

This shall happen every time the BooleanPulse is true. The arrays are indexed by the Integer counter, which increases by 1 every boolean pulse.

The model simulates but gives every "vector" element the value 0. Also the warning message is "Failed to solve linear system of equations (no. 21) at time 0.000000. Residual norm is 0.5."

```<code>model Array_Test_simple
  Real vector[12];
  Integer counter;
  Real tester[12]=1:1:12;
  Modelica.Blocks.Sources.BooleanPulse booleanPulse(period = 0.1);

initial algorithm
  counter:=1;
algorithm
  when booleanPulse.y then
    vector[counter]:=tester[counter];
    counter:=pre(counter)+1;
  end when;

equation

annotation(
    uses(Modelica(version = "4.0.0")));
end Array_Test_simple;
</code>```

答:
This is a known bug in OpenModelica and was recently fixed in PR #8541.
Try out the latest nightly-build of OpenModelica and check if that solves your issue.

But four your example it should also work to use equations and not algorithm equations. In general they are supported much better and the compiler can try to optimize them. Algorithms stay basically untouched.

Body:
The purpose of this model is to provide the indexed elements of the "vector" array the values of the array "tester", which are increasing numbers from 1 to 12.

This shall happen every time the BooleanPulse is true. The arrays are indexed by the Integer counter, which increases by 1 every boolean pulse.

The model simulates but gives every "vector" element the value 0. Also the warning message is "Failed to solve linear system of equations (no. 21) at time 0.000000. Residual norm is 0.5."

model Array_Test_simple
  Real vector[12];
  Integer counter;
  Real tester[12]=1:1:12;
  Modelica.Blocks.Sources.BooleanPulse booleanPulse(period = 0.1);

initial algorithm
  counter:=1;
algorithm
  when booleanPulse.y then
    vector[counter]:=tester[counter];
    counter:=pre(counter)+1;
  end when;

equation

annotation(
    uses(Modelica(version = "4.0.0")));
end Array_Test_simple;


问:
Loop R merge multiple data frames together
I am trying to merge multiple dataset (left_join) together inside a loop.

Here is what the data looks like:

```<code>Fr1 <- data.frame (v1  = c("a", "b", "c"),
                  period1 = c("Yes", "Yes", "Yes")
)

Fr2 <- data.frame (v1  = c("b", "d"),
                   period2 = c("Yes", "Yes")
)

Fr3 <- data.frame (v1  = c("c"),
                   period3 = c("Yes")
)

Be1 <- data.frame (v1  = c("a", "b", "c"),
                   period1 = c("Yes", "Yes", "Yes")
)

Be2 <- data.frame (v1  = c("b", "c"),
                   period2 = c("Yes", "Yes")
)

Be3 <- data.frame (v1  = c("d"),
                   period3 = c("Yes")
)

table_Fr <- data.frame (v1 = c("a", "b", "c", "d"))

table_Be <- data.frame (v1 = c("a", "b", "c", "d"))
</code>```

The idea is simple: Fr1, Fr2, and Fr3 go with table_Fr and Be1, Be2 and Be3 go with table_Be.

A simple way to do it dataframe by dataframe goes like this:

```<code>table_Fr <- left_join(table_Fr, Fr1, by="v1")
table_Fr <- left_join(table_Fr, Fr2, by="v1")
table_Fr <- left_join(table_Fr, Fr3, by="v1")
table_Fr <- table_Fr %>%
  mutate(period1 = ifelse(is.na(period1), "No", period1)) %>%
  mutate(period2 = ifelse(is.na(period2), "No", period2)) %>%
  mutate(period3 = ifelse(is.na(period3), "No", period3))
</code>```

However, I have a large number of data frames to merge together, hence I want to use a loop (I know loop are not best in R but I have to do it through a loop...). Unfortunately, I can't get it to work, does anyone can help?

```<code>countries <- c("Fr", "Be")

for(c in countries) {
  for(i in 1:6) {
p <- paste0("period", i)
cp <- paste0(c, i)
t <- paste0("table_", c)
a <- left_join(t, cp, by="v1") %>%
  mutate(!!p := ifelse(is.na(!!p), "No", !!p))
  assign(paste0("table_",c), a)
}
}
</code>```

答:
```<code>lapply(countries, function(cntry) {
  env=globalenv()
  Reduce(dplyr::full_join, mget(ls(pattern=cntry,env=env), env=env))
})
</code>```

Output:

```<code>[[1]]
  v1 period1 period2 period3
1  a     Yes    <NA>    <NA>
2  b     Yes     Yes    <NA>
3  c     Yes    <NA>     Yes
4  d    <NA>     Yes    <NA>

[[2]]
  v1 period1 period2 period3
1  a     Yes    <NA>    <NA>
2  b     Yes     Yes    <NA>
3  c     Yes     Yes    <NA>
4  d    <NA>    <NA>     Yes
</code>```

Body:
I am trying to merge multiple dataset (left_join) together inside a loop.

Here is what the data looks like:

Fr1 <- data.frame (v1  = c("a", "b", "c"),
                  period1 = c("Yes", "Yes", "Yes")
)

Fr2 <- data.frame (v1  = c("b", "d"),
                   period2 = c("Yes", "Yes")
)

Fr3 <- data.frame (v1  = c("c"),
                   period3 = c("Yes")
)

Be1 <- data.frame (v1  = c("a", "b", "c"),
                   period1 = c("Yes", "Yes", "Yes")
)

Be2 <- data.frame (v1  = c("b", "c"),
                   period2 = c("Yes", "Yes")
)

Be3 <- data.frame (v1  = c("d"),
                   period3 = c("Yes")
)

table_Fr <- data.frame (v1 = c("a", "b", "c", "d"))

table_Be <- data.frame (v1 = c("a", "b", "c", "d"))

The idea is simple: Fr1, Fr2, and Fr3 go with table_Fr and Be1, Be2 and Be3 go with table_Be.

A simple way to do it dataframe by dataframe goes like this:

table_Fr <- left_join(table_Fr, Fr1, by="v1")
table_Fr <- left_join(table_Fr, Fr2, by="v1")
table_Fr <- left_join(table_Fr, Fr3, by="v1")
table_Fr <- table_Fr %>%
  mutate(period1 = ifelse(is.na(period1), "No", period1)) %>%
  mutate(period2 = ifelse(is.na(period2), "No", period2)) %>%
  mutate(period3 = ifelse(is.na(period3), "No", period3))

However, I have a large number of data frames to merge together, hence I want to use a loop (I know loop are not best in R but I have to do it through a loop...). Unfortunately, I can't get it to work, does anyone can help?

countries <- c("Fr", "Be")

for(c in countries) {
  for(i in 1:6) {
p <- paste0("period", i)
cp <- paste0(c, i)
t <- paste0("table_", c)
a <- left_join(t, cp, by="v1") %>%
  mutate(!!p := ifelse(is.na(!!p), "No", !!p))
  assign(paste0("table_",c), a)
}
}

Body:
lapply(countries, function(cntry) {
  env=globalenv()
  Reduce(dplyr::full_join, mget(ls(pattern=cntry,env=env), env=env))
})

Output:

[[1]]
  v1 period1 period2 period3
1  a     Yes    <NA>    <NA>
2  b     Yes     Yes    <NA>
3  c     Yes    <NA>     Yes
4  d    <NA>     Yes    <NA>

[[2]]
  v1 period1 period2 period3
1  a     Yes    <NA>    <NA>
2  b     Yes     Yes    <NA>
3  c     Yes     Yes    <NA>
4  d    <NA>    <NA>     Yes


问:
How to disable time from now with time picker antd
I would like to know how I can disable the hour and minutes, taking into consideration from the current time and not from past hours.

  const disabledHours = () => {
    const hours = [];
    for (let i = 0; i < moment().hour(); i += 1) hours.push(i);
    return hours;
  };

  const disabledMinutes = (selectedHour) => {
    const minutes = [];
    if (selectedHour === moment().hour()) {
      for (let i = 0; i < moment().minute(); i += 1) minutes.push(i);
    }
    return minutes;
  };
```
<pre class="lang-js prettyprint-override"><code>   <TimePicker
       disabledHours={disabledHours}
       disabledMinutes={disabledMinutes}
       format="h:mm a"
       style={{ width: '100%' }}
       disabled={isLoading}
   />
</code>```

答:
If you want to disable future time:

```<code>const disabledHours = () => {
  const hours = [];
  const currentHour = moment().hour();

  for (let i = currentHour + 1; i <= 24; i++) {
    hours.push(i);
  }

  return hours;
};

const disabledMinutes = (selectedHour) => {
  const minutes = [];
  const currentMinute = moment().minute();
  if (selectedHour === moment().hour()) {
    for (let i = currentMinute; i <= 60; i++) {
      minutes.push(i);
    }
  }
  return minutes;
};
</code>```

DEMO: https://codesandbox.io/s/antd-reproduction-template-forked-uslk0?file=/index.js

To avoid problems with switching AM or PM you can write any logic about how your want to set max time reference to onSelect callback, for example:

```<code>const TimeComponent = () => {
  const [selectedTime, setSelectedTime] = useState(moment());
  const disabledHours = () => {
    const hours = [];
    const currentHour = moment().hour();

    for (let i = currentHour + 1; i <= 24; i++) {
      hours.push(i);
    }

    return hours;
  };

  const disabledMinutes = (selectedHour) => {
    const minutes = [];
    const currentMinute = moment().minute();
    if (selectedHour === moment().hour()) {
      for (let i = currentMinute + 1; i <= 60; i++) {
        minutes.push(i);
      }
    }
    return minutes;
  };

  const onSelect = (time) => {
    if (time.isAfter(moment())) {
      console.log("ping");
      setSelectedTime(moment());
      return;
    }

    setSelectedTime(time);
  };

  return (
    <TimePicker
      onSelect={onSelect}
      disabledHours={disabledHours}
      disabledMinutes={disabledMinutes}
      format="h:mm a"
      value={selectedTime}
      style={{ width: "100%" }}
      use12Hours={true}
    />
  );
};
</code>```

Body:
I would like to know how I can disable the hour and minutes, taking into consideration from the current time and not from past hours.

  const disabledHours = () => {
    const hours = [];
    for (let i = 0; i < moment().hour(); i += 1) hours.push(i);
    return hours;
  };

  const disabledMinutes = (selectedHour) => {
    const minutes = [];
    if (selectedHour === moment().hour()) {
      for (let i = 0; i < moment().minute(); i += 1) minutes.push(i);
    }
    return minutes;
  };

   <TimePicker
       disabledHours={disabledHours}
       disabledMinutes={disabledMinutes}
       format="h:mm a"
       style={{ width: '100%' }}
       disabled={isLoading}
   />

Body:
If you want to disable future time:

const disabledHours = () => {
  const hours = [];
  const currentHour = moment().hour();

  for (let i = currentHour + 1; i <= 24; i++) {
    hours.push(i);
  }

  return hours;
};

const disabledMinutes = (selectedHour) => {
  const minutes = [];
  const currentMinute = moment().minute();
  if (selectedHour === moment().hour()) {
    for (let i = currentMinute; i <= 60; i++) {
      minutes.push(i);
    }
  }
  return minutes;
};

DEMO: https://codesandbox.io/s/antd-reproduction-template-forked-uslk0?file=/index.js

To avoid problems with switching AM or PM you can write any logic about how your want to set max time reference to onSelect callback, for example:

const TimeComponent = () => {
  const [selectedTime, setSelectedTime] = useState(moment());
  const disabledHours = () => {
    const hours = [];
    const currentHour = moment().hour();

    for (let i = currentHour + 1; i <= 24; i++) {
      hours.push(i);
    }

    return hours;
  };

  const disabledMinutes = (selectedHour) => {
    const minutes = [];
    const currentMinute = moment().minute();
    if (selectedHour === moment().hour()) {
      for (let i = currentMinute + 1; i <= 60; i++) {
        minutes.push(i);
      }
    }
    return minutes;
  };

  const onSelect = (time) => {
    if (time.isAfter(moment())) {
      console.log("ping");
      setSelectedTime(moment());
      return;
    }

    setSelectedTime(time);
  };

  return (
    <TimePicker
      onSelect={onSelect}
      disabledHours={disabledHours}
      disabledMinutes={disabledMinutes}
      format="h:mm a"
      value={selectedTime}
      style={{ width: "100%" }}
      use12Hours={true}
    />
  );
};


答:
The problem is that you have double quotes in your XPath and then again you are using double quotes to surround the entire XPath.

Python interpreter and your VSCode linter can't figure out where your string is beginning and where it is ending.

If your XPath has " the use ' to surround the entire XPath, or the other way round.

Change this from:

```<code>'year': response.xpath("//li[@class="ipc-inline-list__item"]/span/text()").get(),
</code>```

to:

```<code>'year': response.xpath('//li[@class="ipc-inline-list__item"]/span/text()').get(),
</code>```

Here is your entire parse_item fixed:

```<code>def parse_item(self, response):
    yield {
        'title': response.xpath("//h1/text()").get(),
        'year': response.xpath('//li[@class="ipc-inline-list__item"]/span/text()').get(),
        'duration': response.xpath('(//li[@class="ipc-inline-list__item"])[3]/text()').get(),
        'genre': response.xpath('//span[@class="ipc-chip__text"]/text()').get(),
        'rating': response.xpath('//span[@class="AggregateRatingButton__RatingScore-sc-1ll29m0-1 iTLWoV"]/text()').get(),
        'movie_url': response.url,
    }
</code>```

Body:
The problem is that you have double quotes in your XPath and then again you are using double quotes to surround the entire XPath.

Python interpreter and your VSCode linter can't figure out where your string is beginning and where it is ending.

If your XPath has " the use ' to surround the entire XPath, or the other way round.

Change this from:

'year': response.xpath("//li[@class="ipc-inline-list__item"]/span/text()").get(),

to:

'year': response.xpath('//li[@class="ipc-inline-list__item"]/span/text()').get(),

Here is your entire parse_item fixed:

def parse_item(self, response):
    yield {
        'title': response.xpath("//h1/text()").get(),
        'year': response.xpath('//li[@class="ipc-inline-list__item"]/span/text()').get(),
        'duration': response.xpath('(//li[@class="ipc-inline-list__item"])[3]/text()').get(),
        'genre': response.xpath('//span[@class="ipc-chip__text"]/text()').get(),
        'rating': response.xpath('//span[@class="AggregateRatingButton__RatingScore-sc-1ll29m0-1 iTLWoV"]/text()').get(),
        'movie_url': response.url,
    }


问:
POSTMAN: Extracting Values from body
I'm trying to recreate a scenario with the postman and there is a _csrf value in the previous GET request response body to be passed with the next POST request.

I Can't find a way to extract the value from POSTMAN.

NOTE: What I want is something similar to Regular Expression Extractor in Jmeter.If you have any Idea about extracting a value form the response body and setting it to a variable. Please let me know.

Cheers,
Muditha

答:
Just made this JS in post man to parse Without a REGEx. Hope it will help people in the futur

Text to parse : Json : Extract data-id :

```<code>{
    "code": "OK",
    "response": {
        "append": {
            "html": {
                "< .folders": "<a class=\"folder\" href=\"/foobarfoo\" data-id=\"ToExtract\"><div><i class=\"far fa-fw fa-folder\"></i></div><div class=\"folder-name\">blabla</div><div><div class=\"badge\">0</div></div></a>"
            }
        }
    }
}
</code>```
```<code>console.log(responseBody.response);

var jsonData = JSON.parse(responseBody);
var iStart = responseBody.indexOf("response\":")+10;
var scenarioId = responseBody.substr(iStart,10);
var iEnd = scenarioId.indexOf("}");
var scenarioId = scenarioId.substr(0,iEnd);

console.log("scenarioId:" + scenarioId + "iStart: "+ iStart + " scenarioId : " + scenarioId);
pm.environment.set("scenario", scenarioId);

</code>```

Title: POSTMAN: Extracting Values from body

Body:
Just made this JS in post man to parse Without a REGEx. Hope it will help people in the futur

Text to parse : Json : Extract data-id :

{
    "code": "OK",
    "response": {
        "append": {
            "html": {
                "< .folders": "<a class=\"folder\" href=\"/foobarfoo\" data-id=\"ToExtract\"><div><i class=\"far fa-fw fa-folder\"></i></div><div class=\"folder-name\">blabla</div><div><div class=\"badge\">0</div></div></a>"
            }
        }
    }
}

console.log(responseBody.response);

var jsonData = JSON.parse(responseBody);
var iStart = responseBody.indexOf("response\":")+10;
var scenarioId = responseBody.substr(iStart,10);
var iEnd = scenarioId.indexOf("}");
var scenarioId = scenarioId.substr(0,iEnd);

console.log("scenarioId:" + scenarioId + "iStart: "+ iStart + " scenarioId : " + scenarioId);
pm.environment.set("scenario", scenarioId);


问:
What's wrong with Rails assets:precompile and production environment?
Trying to finally deploy a rails 6 app - works well in development, but not in production. Here's the error from production.log:

```<code>F, [2022-02-09T18:03:53.317145 #1] FATAL -- : [6d02bb29-feb6-4fac-a7df-af9ff0d0ed74]
[6d02bb29-feb6-4fac-a7df-af9ff0d0ed74] ActionView::Template::Error (Webpacker can't find application.css in /app/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
</code>```

Dockerfile:

```<code>FROM ruby:3.0.0

ENV APP_HOME /app
RUN mkdir $APP_HOME
WORKDIR $APP_HOME

RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list
RUN apt-get update -qq
RUN apt-get install -y build-essential nodejs yarn imagemagick

RUN gem install bundler:2.2.3
ADD Gemfile* $APP_HOME/
RUN bundle install
ADD . $APP_HOME

RUN bundle exec rake assets:precompile

RUN yarn install --check-files

EXPOSE 3000
CMD ["rails","server","-b","0.0.0.0"]
</code>```

I can run everything properly via docker-compose with RAILS_ENV set to 'development'. But as soon as I change RAILS_ENV to 'production', the above error happens.

I also checked config/environments/production.rb.
I have this line in but whether or not it's in doesn't change the error (I tried to run the whole thing with both this line active and commented out - error stays the same).

```<code>config.assets.compile = true
</code>```

I don't know where to look for answers...

答:
I found out what needs to be done. I spent a whole evening googling even more, and as my question comes up quite high now, here's the answer for others that run into the same problem.
There were two things I needed to do:

In the Dockerfile, I needed to run rake asset:precompile with RAILS_ENV set to production - to the corresponding line in the Dockerfile now looks like this:

RUN RAILS_ENV=production bundle exec rake assets:precompile

And then I ALSO realized that I need to set the environment variable RAILS_SERVE_STATIC_FILES to.. well something (config/environments/production.rb checks whether it exists).
So now my moviedb services of the docker-compose file looks like this:

```<code>  moviedb:
    image: tkhobbes/moviedb
    restart: unless-stopped
    depends_on:
      - mariamovie
    environment:
      MYSQL_ROOT_PASSWORD: redacted
      RAILS_ENV: production
      NEWMOVIEDB_DATABASE_PASSWORD: redacted
      RAILS_SERVE_STATIC_FILES: "yes"
    ports:
      - 3001:3000
</code>```

With these two things fixed - rails PUMA now serves production!

Body:
Trying to finally deploy a rails 6 app - works well in development, but not in production. Here's the error from production.log:

F, [2022-02-09T18:03:53.317145 #1] FATAL -- : [6d02bb29-feb6-4fac-a7df-af9ff0d0ed74]
[6d02bb29-feb6-4fac-a7df-af9ff0d0ed74] ActionView::Template::Error (Webpacker can't find application.css in /app/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.

Dockerfile:

FROM ruby:3.0.0

ENV APP_HOME /app
RUN mkdir $APP_HOME
WORKDIR $APP_HOME

RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list
RUN apt-get update -qq
RUN apt-get install -y build-essential nodejs yarn imagemagick

RUN gem install bundler:2.2.3
ADD Gemfile* $APP_HOME/
RUN bundle install
ADD . $APP_HOME

RUN bundle exec rake assets:precompile

RUN yarn install --check-files

EXPOSE 3000
CMD ["rails","server","-b","0.0.0.0"]

I can run everything properly via docker-compose with RAILS_ENV set to 'development'. But as soon as I change RAILS_ENV to 'production', the above error happens.

I also checked config/environments/production.rb.
I have this line in but whether or not it's in doesn't change the error (I tried to run the whole thing with both this line active and commented out - error stays the same).

config.assets.compile = true

I don't know where to look for answers...

Body:
I found out what needs to be done. I spent a whole evening googling even more, and as my question comes up quite high now, here's the answer for others that run into the same problem.
There were two things I needed to do:

In the Dockerfile, I needed to run rake asset:precompile with RAILS_ENV set to production - to the corresponding line in the Dockerfile now looks like this:

RUN RAILS_ENV=production bundle exec rake assets:precompile

And then I ALSO realized that I need to set the environment variable RAILS_SERVE_STATIC_FILES to.. well something (config/environments/production.rb checks whether it exists).
So now my moviedb services of the docker-compose file looks like this:

  moviedb:
    image: tkhobbes/moviedb
    restart: unless-stopped
    depends_on:
      - mariamovie
    environment:
      MYSQL_ROOT_PASSWORD: redacted
      RAILS_ENV: production
      NEWMOVIEDB_DATABASE_PASSWORD: redacted
      RAILS_SERVE_STATIC_FILES: "yes"
    ports:
      - 3001:3000

With these two things fixed - rails PUMA now serves production!


问:
SSL error when open jupyter notebook in Microsoft Edge
I'm opening a jupyter notebook in an Ubantu with MobaXterm.
At first , everything worked well and jupyter notebook can be open normally.
Suddenly one day when I open it in Microsoft Edge by typing "jupyter notebook", it gives the following message and the web page gives the error "ERR_SSL_VERSION_OR_CIPHER_MISMATCH"

```<code>[W 21:16:49.329 NotebookApp] SSL Error on 9 ('10.21.144.80', 56849): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.459 NotebookApp] SSL Error on 9 ('10.21.144.80', 56850): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.555 NotebookApp] SSL Error on 9 ('10.21.144.80', 56851): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.719 NotebookApp] SSL Error on 9 ('10.21.144.80', 56852): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:55.935 NotebookApp] SSL Error on 9 ('10.21.144.80', 56854): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)

</code>```

Try again with https, it gives

```<code>[W 21:55:56.774 NotebookApp] SSL Error on 9 ('10.21.144.80', 57721): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.777 NotebookApp] SSL Error on 10 ('10.21.144.80', 57722): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.940 NotebookApp] SSL Error on 9 ('10.21.144.80', 57723): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.958 NotebookApp] SSL Error on 10 ('10.21.144.80', 57724): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.134 NotebookApp] SSL Error on 9 ('10.21.144.80', 57727): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.142 NotebookApp] SSL Error on 10 ('10.21.144.80', 57728): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.322 NotebookApp] SSL Error on 9 ('10.21.144.80', 57729): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.323 NotebookApp] SSL Error on 10 ('10.21.144.80', 57730): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)

</code>```

But surprsingly it can be open in IE browser with a warning "DLG_FLAGS_INVALID_CADLG_FLAGS_SEC_CERT_CN_INVALID"
I also tried Chrome, just the same mistake.
I also tried most solutions I can find, just nothing happened.(;o;)

What's wrong with my computer? Thanks for your solutions.

答: Why dont you try it on other explorer? like Chrome?</p>

Body:
I'm opening a jupyter notebook in an Ubantu with MobaXterm.
At first , everything worked well and jupyter notebook can be open normally.
Suddenly one day when I open it in Microsoft Edge by typing "jupyter notebook", it gives the following message and the web page gives the error "ERR_SSL_VERSION_OR_CIPHER_MISMATCH"

[W 21:16:49.329 NotebookApp] SSL Error on 9 ('10.21.144.80', 56849): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.459 NotebookApp] SSL Error on 9 ('10.21.144.80', 56850): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.555 NotebookApp] SSL Error on 9 ('10.21.144.80', 56851): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:50.719 NotebookApp] SSL Error on 9 ('10.21.144.80', 56852): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)
[W 21:16:55.935 NotebookApp] SSL Error on 9 ('10.21.144.80', 56854): [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:726)

Try again with https, it gives

[W 21:55:56.774 NotebookApp] SSL Error on 9 ('10.21.144.80', 57721): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.777 NotebookApp] SSL Error on 10 ('10.21.144.80', 57722): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.940 NotebookApp] SSL Error on 9 ('10.21.144.80', 57723): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:55:56.958 NotebookApp] SSL Error on 10 ('10.21.144.80', 57724): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.134 NotebookApp] SSL Error on 9 ('10.21.144.80', 57727): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.142 NotebookApp] SSL Error on 10 ('10.21.144.80', 57728): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.322 NotebookApp] SSL Error on 9 ('10.21.144.80', 57729): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)
[W 21:56:02.323 NotebookApp] SSL Error on 10 ('10.21.144.80', 57730): [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:726)

But surprsingly it can be open in IE browser with a warning "DLG_FLAGS_INVALID_CADLG_FLAGS_SEC_CERT_CN_INVALID"
I also tried Chrome, just the same mistake.
I also tried most solutions I can find, just nothing happened.(;o;)

What's wrong with my computer? Thanks for your solutions.


问:
Cors error with axios using authentication
I am having some trouble with axios once I add authentication.

My api.ts file:

```<code>import axios from "axios"

export default axios.create({
  baseUrl: "https://someUrl"
})
</code>```

In App.ts i am setting authentication header:

```<code>import api from api.ts

function App(){
  api.default.header.common["Authorization"] = `Bearer ${token}`
}
</code>```

And in my apiHooks.ts

```<code>import api from api.ts
import {useQuery} from "react-query"
const GetSomething = () => {
  const {data, isLoading = useQuery("key", () => {
    return api.get("/api")
  });
  return data?.data
};
export default GetSomething;
</code>```

So when I'm using the hook, I get a Cors error ONLY when turning on authentication.
The error is the following:

cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at "url"

答:
Try putting "/" at the end of url.
If it doesn't work, please comment.

```<code>import api from api.ts
import {useQuery} from "react-query"
const GetSomething = () => {
  const {data, isLoading = useQuery("key", () => {
    return api.get("/api/")
  });
  return data?.data
};
export default GetSomething;
</code>```

Personally, I do it as follows

```<code>import axios from "axios";

const baseURL = "http://127.0.0.1:8080/api/";

// axios instance for making requests
export const axiosInstance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
  headers: {
    "Content-Type": "application/json",
    accept: "application/json",
  },
});

// request interceptor for adding token
axiosInstance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("access");
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
</code>```

and hook:

```<code>import { useQuery } from "react-query";
import { axiosInstance } from "../utils/axios";
const fetchData = () => {
  return axiosInstance.get("/item-list/");
};

export const useData = () => {
  return useQuery("item-list", fetchData);
};
</code>```

Body:
I am having some trouble with axios once I add authentication.

My api.ts file:

import axios from "axios"

export default axios.create({
  baseUrl: "https://someUrl"
})

In App.ts i am setting authentication header:

import api from api.ts

function App(){
  api.default.header.common["Authorization"] = `Bearer ${token}`
}

And in my apiHooks.ts

import api from api.ts
import {useQuery} from "react-query"
const GetSomething = () => {
  const {data, isLoading = useQuery("key", () => {
    return api.get("/api")
  });
  return data?.data
};
export default GetSomething;

So when I'm using the hook, I get a Cors error ONLY when turning on authentication.
The error is the following:

cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at "url"

Body:
Try putting "/" at the end of url.
If it doesn't work, please comment.

import api from api.ts
import {useQuery} from "react-query"
const GetSomething = () => {
  const {data, isLoading = useQuery("key", () => {
    return api.get("/api/")
  });
  return data?.data
};
export default GetSomething;

Personally, I do it as follows

import axios from "axios";

const baseURL = "http://127.0.0.1:8080/api/";

// axios instance for making requests
export const axiosInstance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
  headers: {
    "Content-Type": "application/json",
    accept: "application/json",
  },
});

// request interceptor for adding token
axiosInstance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("access");
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

and hook:

import { useQuery } from "react-query";
import { axiosInstance } from "../utils/axios";
const fetchData = () => {
  return axiosInstance.get("/item-list/");
};

export const useData = () => {
  return useQuery("item-list", fetchData);
};


问:
Lazy load tabs next to selected tab
I would like to lazy load/preload the one or two tabs next to the selected one to avoid a laggy animation on tab changing. Is there a way to do that with flutter ? I am actually using a defaultTabController</p>

```<code>home: DefaultTabController(
    initialIndex: 0,
    length: 5,
    child: Scaffold(
      appBar: AppBar(
        bottom: TabBar(

          labelStyle: TextStyle(fontSize: 9.0, fontWeight: FontWeight.bold),
          tabs: [
            Tab(text: 'HARDWARE'),
            Tab(text: 'SCHEDULE'),
            Tab(text: 'ANALYTICS'),
            Tab(text: 'TEMP'),
            Tab(text: 'SETTINGS'),
          ],
        ),
        title: Text('${widget.title}'),
      ),
      body: TabBarView(
        children: [
          TheGridView().build(),
          TimePicker(),
          ChartPage(),
          TempPage(),
</code>```

答: There's not much details on what you're trying to load on your tabs. If the tab page stutters during tab change, the elements being rendered on the page might be blocked in the main thread. If you're using Future callbacks before Widget build(), you may want to consider modifying where it's called.

Title: Lazy load tabs next to selected tab

Body:
I would like to lazy load/preload the one or two tabs next to the selected one to avoid a laggy animation on tab changing. Is there a way to do that with flutter ? I am actually using a defaultTabController

home: DefaultTabController(
    initialIndex: 0,
    length: 5,
    child: Scaffold(
      appBar: AppBar(
        bottom: TabBar(

          labelStyle: TextStyle(fontSize: 9.0, fontWeight: FontWeight.bold),
          tabs: [
            Tab(text: 'HARDWARE'),
            Tab(text: 'SCHEDULE'),
            Tab(text: 'ANALYTICS'),
            Tab(text: 'TEMP'),
            Tab(text: 'SETTINGS'),
          ],
        ),
        title: Text('${widget.title}'),
      ),
      body: TabBarView(
        children: [
          TheGridView().build(),
          TimePicker(),
          ChartPage(),
          TempPage(),


问:
Move button when clicked
How do I move the button from the div with id of two to the div with id of one when I click the button?

  <button onclick="moveMe"></button>

```
<pre class="lang-js prettyprint-override"><code>function moveMe() {
 // ??
}
</code>```

答:
You can try this:</p>
```<code>// select the elements
const button = document.querySelector('button');
const firstDiv = document.getElementById('one');

// add eventListener
button.addEventListener('click', moveButton);

// move the button
function moveButton() {
  firstDiv.append(button);
}
</code>```

Title: Move button when clicked

Body:
How do I move the button from the div with id of two to the div with id of one when I click the button?

  <button onclick="moveMe"></button>

function moveMe() {
 // ??
}

Body:
You can try this:

// select the elements
const button = document.querySelector('button');
const firstDiv = document.getElementById('one');

// add eventListener
button.addEventListener('click', moveButton);

// move the button
function moveButton() {
  firstDiv.append(button);
}