问:
Why is it returning as ‘send’ of undefined?
I set up the code below just like my guildMemberAdd, that is working fine however the code below doesn’t.

It give me

TypeError: Cannot read property 'send' of undefined

when I have the correct channel defined. I’m not sure why.

```<code>client.on("guildMemberRemove", function(message) {
  let guild = message.guild;
  let member = message;
  let memberCount = message.guild.memberCount
    let memmChannel = message.guild.channels.cache.find(channel => channel.name === "logs");
    const embed = new MessageEmbed()
      .setColor("#da7272")
      .setThumbnail(member.user.displayAvatarURL({ format: 'png', dynamic: true }))
      .setDescription(`${member.user} just left the lobby.\n\nMember Count: \`#${message.guild.memberCount}\``);

    memmChannel.send(embed);
});
</code>```

答:
It means the bot could not find any channel with name "logs".
I think this is due to the fact that the member is no longer in the guild.

You should try to log your message.guild, analyze the output, and adapt your code using the results. For example, using the guild id, if it exists to run a const guild = client.guilds.cache.get(GuildID).

If you could send what the output of console.log(message.guild) is like, I think I should be able to help you to resolve your problem :)

Body:
I set up the code below just like my guildMemberAdd, that is working fine however the code below doesn’t.

It give me

TypeError: Cannot read property 'send' of undefined

when I have the correct channel defined. I’m not sure why.

client.on("guildMemberRemove", function(message) {
  let guild = message.guild;
  let member = message;
  let memberCount = message.guild.memberCount
    let memmChannel = message.guild.channels.cache.find(channel => channel.name === "logs");
    const embed = new MessageEmbed()
      .setColor("#da7272")
      .setThumbnail(member.user.displayAvatarURL({ format: 'png', dynamic: true }))
      .setDescription(`${member.user} just left the lobby.\n\nMember Count: \`#${message.guild.memberCount}\``);

    memmChannel.send(embed);
});


来源: stackexchange

问:
feathersjs/nodejs sequelize
I am using feathers js and sequelize. I already have existing models like users .

Now my question is if I wanted to add a new column to user model/database for example user_firstname should I directly add that to the model.js ? or I need to create migrations for that ?

How does it affect locally and on stating or production ? Thank you.

Sample models.user , snippet

```<code>module.exports = function (app) {
  const sequelizeClient = app.get('sequelizeClient');
  const users = sequelizeClient.define('users', {
    username: {
      type: DataTypes.STRING(320),
      allowNull: false,
      unique: true,
    },
    password: {
      type: DataTypes.STRING,
      allowNull: true,
    },
</code>```

答: If you don't use sequelize.sync() then you should create a migration, modify a model, build the app, deploy the app, run migrations on a DB that is related to the deployed app to make sure that the app is corresponding to a DB (a structure and data).

ContentLicense: CC BY-SA 4.0

Title: feathersjs/nodejs sequelize

Body:
I am using feathers js and sequelize. I already have existing models like users .

Now my question is if I wanted to add a new column to user model/database for example user_firstname should I directly add that to the model.js ? or I need to create migrations for that ?

How does it affect locally and on stating or production ? Thank you.

Sample models.user , snippet

module.exports = function (app) {
  const sequelizeClient = app.get('sequelizeClient');
  const users = sequelizeClient.define('users', {
    username: {
      type: DataTypes.STRING(320),
      allowNull: false,
      unique: true,
    },
    password: {
      type: DataTypes.STRING,
      allowNull: true,
    },


问:
QIcon not shown on Ubuntu, works on Windows
Hi
I have a problem in multiple applications which were all developed on a Windows machine. When I build the same apps on Ubuntu and run them, no icons are shown at the File Menu bar alone .
Works perfectly in windows. Any suggestion

```<code> LoadAction = new QAction(tr("&Open file"), this);
 LoadAction->setIcon(QIcon(Dir +"/images/Load.png"));
 LoadAction->setShortcut(QKeySequence::Open);
</code>```

I doubled checked the path ,everything is fine ...

答:
split that second line , first create the QIcon,then use
bool QIcon::isNull () const -method to check if the Icon is loadede
and finally set the icon.
If it fails to load from that file, then try creating the path first

```<code>QString path=Dir+"/images/Load.png";
</code>```

and check if that path is correct

Also remember that for some image formats you need the plugins(but png will work without those,just if you use other formats like jpg,svg)

ContentLicense: CC BY-SA 3.0

Body:
Hi
I have a problem in multiple applications which were all developed on a Windows machine. When I build the same apps on Ubuntu and run them, no icons are shown at the File Menu bar alone .
Works perfectly in windows. Any suggestion

 LoadAction = new QAction(tr("&Open file"), this);
 LoadAction->setIcon(QIcon(Dir +"/images/Load.png"));
 LoadAction->setShortcut(QKeySequence::Open);

I doubled checked the path ,everything is fine ...

Body:
split that second line , first create the QIcon,then use
bool QIcon::isNull () const -method to check if the Icon is loadede
and finally set the icon.
If it fails to load from that file, then try creating the path first

QString path=Dir+"/images/Load.png";

and check if that path is correct

Also remember that for some image formats you need the plugins(but png will work without those,just if you use other formats like jpg,svg)


问:
How to install MariaDB on RHEL 7 server?
Given cat /etc/yum.repos.d/MariaDB.repo is:

```<code># MariaDB 10.3 RedHat repository list - created 2018-08-29 05:52 UTC
# http://downloads.mariadb.org/mariadb/repositories/
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.3/rhel7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
</code>```

When I do

```<code>sudo yum install MariaDB-server MariaDB-client
</code>```

I got:

```<code>Loaded plugins: search-disabled-repos
No package MariaDB-server available.
  * Maybe you meant: mariadb-server
No package MariaDB-client available.
Error: Nothing to do
</code>```

I'm using https://downloads.mariadb.org/mariadb/repositories/#mirror=digital-pacific&distro=RedHat&distro_release=rhel7-amd64--rhel7&version=10.3

Why am I not able to install mariadb on my RHEL7 server?

Note:

```<code>yum list mariadb
Loaded plugins: search-disabled-repos
Available Packages
mariadb.x86_64                                      1:5.5.60-1.el7_5                                      uofa_repos
</code>```

Is this because i'm only looking at uofa_repos repository somehow? How do I install mariadb correctly?

答:
If you got this error: No package MariaDB-server and No package MariaDB-client. Just comment this line in /etc/yum.conf (add # at the beginning...)

```<code>#exclude=ansible1.9,mysql,mariadb,mariadb-,Percona-XtraDB-,Percona--55,Percona--56,Percona--51,Percona--50
</code>```

Body:
Given cat /etc/yum.repos.d/MariaDB.repo is:

# MariaDB 10.3 RedHat repository list - created 2018-08-29 05:52 UTC
# http://downloads.mariadb.org/mariadb/repositories/
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.3/rhel7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

When I do

sudo yum install MariaDB-server MariaDB-client

I got:

Loaded plugins: search-disabled-repos
No package MariaDB-server available.
  * Maybe you meant: mariadb-server
No package MariaDB-client available.
Error: Nothing to do

I'm using https://downloads.mariadb.org/mariadb/repositories/#mirror=digital-pacific&distro=RedHat&distro_release=rhel7-amd64--rhel7&version=10.3

Why am I not able to install mariadb on my RHEL7 server?

Note:

yum list mariadb
Loaded plugins: search-disabled-repos
Available Packages
mariadb.x86_64                                      1:5.5.60-1.el7_5                                      uofa_repos

Is this because i'm only looking at uofa_repos repository somehow? How do I install mariadb correctly?

Body:
If you got this error: No package MariaDB-server and No package MariaDB-client. Just comment this line in /etc/yum.conf (add # at the beginning...)

#exclude=ansible1.9,mysql,mariadb,mariadb-,Percona-XtraDB-,Percona--55,Percona--56,Percona--51,Percona--50


问:
Change Class-Binded Shadow Colour WPF
I was looking on how to replicate a Google button's shadow on hover effect in my WPF document and came across this: https://stackoverflow.com/a/53031057/12299798, which answers my problem exactly, but the only issue I have is that I normally do all the frontend things in XAML and so I am not quite experienced in the styling in C#. My problem is that I want to 'Bind' my foreground colour to the shadow colour, this is because in the code it only sets it to a greyish colour which would mean I would have to do a whole other class for each colour that I want to set it for. Here is my code now:

MainWindow.xaml:

```<code><Button Content="shadow">
        <Button.Style>
            <Style TargetType="Button">
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="local:UI.Elevation" Value="10"/>
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="False">
                        <Setter Property="local:UI.Elevation" Value="0"/>

                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
</Button>
</code>```

UI.cs:

```<code>public static class UI
{

    public static readonly DependencyProperty ElevationProperty = DependencyProperty.RegisterAttached("Elevation", typeof(double), typeof(UI), new FrameworkPropertyMetadata(default(double), FrameworkPropertyMetadataOptions.AffectsRender, null, OnRedElevationChanged));

    public static double GetElevation(this UIElement element) => element.GetValue(ElevationProperty) as double? ?? default;

    public static void SetElevation(this UIElement element, double elevation) => element.SetValue(ElevationProperty, elevation);

    private static object OnRedElevationChanged(DependencyObject d, object value)
    {
        if (d is UIElement element && value is double elevation)
            if (elevation == 0)
                element.Effect = null;
            else
            {
                Effect e = CreateElevation(elevation, element.Effect);
                if (e != null)
                    element.Effect = e;
            }
        return value;
    }

    private static Effect CreateElevation(double elevation, Effect source)
    {
        void MixShadows(DropShadowEffect nearest, DropShadowEffect matched, double balance)
        {
            matched.BlurRadius = matched.BlurRadius * (1 - balance) + nearest.BlurRadius * balance;
            matched.ShadowDepth = matched.ShadowDepth * (1 - balance) + nearest.ShadowDepth * balance;
        }
        DropShadowEffect[] shadows = new DropShadowEffect[]
        {
        new DropShadowEffect()
        {
            BlurRadius = 5,
            ShadowDepth = 1
        },
        new DropShadowEffect()
        {
            BlurRadius = 8,
            ShadowDepth = 1.5
        },
        new DropShadowEffect()
        {
            BlurRadius = 14,
            ShadowDepth = 4.5
        },
        new DropShadowEffect()
        {
            BlurRadius = 25,
            ShadowDepth = 8
        },
        new DropShadowEffect()
        {
            BlurRadius = 35,
            ShadowDepth = 13
        }
        };
        elevation = Math.Max(0, elevation / 12 * shadows.Length - 1);
        int prevIndex = (int)Math.Floor(elevation), index = (int)elevation, nextIndex = (int)Math.Ceiling(elevation);
        double approx = elevation - index;
        DropShadowEffect shadow = shadows[index];
        if (approx != 0)
            MixShadows(approx < 0 ? shadows[prevIndex] : shadows[nextIndex], shadow, Math.Abs(approx));
        bool modify = false;
        if (source is DropShadowEffect sourceShadow)
        {
            sourceShadow.BlurRadius = shadow.BlurRadius;
            sourceShadow.ShadowDepth = shadow.ShadowDepth;
            shadow = sourceShadow;
            modify = true;
        }
        shadow.Direction = 270;
        shadow.Color = Colors.Red;
        shadow.Opacity = .42;
        shadow.RenderingBias = RenderingBias.Performance;
        return modify ? null : shadow;
    }
}
</code>```

And to get what I want in XAML I would do something like this:

```<code><Button Content="shadow">
        <Button.Style>
            <Style TargetType="Button">
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="local:UI.Elevation" Value="10"/>
                        <Setter Property="local:UI.Elevation.Foreground" Value="Blue"/>
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="False">
                        <Setter Property="local:UI.Elevation" Value="0"/>
                        <Setter Property="local:UI.Elevation.Foreground" Value="Blue"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
</Button>
</code>```

But I don't quite know how to link up the local:UI.Elevation.Foreground to change the shadow colour, I would have to change this line here from UI.cs: shadow.Color = Colors.Red; and bind it to the Elevation.Foreground, but I am having difficulties. Can anyone help?

答:
All you need to do is updated the UI class with a new attached property named something like Color of type Color and give it a default color you like.

Then, in its OnColorChanged handler, call OnElevationChanged so that the shadow gets recreated.

```<code>#region Color (Attached Property)
public static readonly DependencyProperty ColorProperty =
    DependencyProperty.RegisterAttached(
        "Color",
        typeof(Color),
        typeof(UI),
        new PropertyMetadata(Colors.Black, OnColorChanged));

public static Color GetColor(DependencyObject obj)
{
    return (Color)obj.GetValue(ColorProperty);
}

public static void SetColor(DependencyObject obj, Color value)
{
    obj.SetValue(ColorProperty, value);
}

private static void OnColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    OnElevationChanged(d, GetElevation((UIElement)d));
}
#endregion
</code>```

In the CreateElevation method, add a new parameter for the color, so you can set it.

```<code>private static Effect CreateElevation(double elevation, Effect source, Color color)
{
    ...
    shadow.Color = color;
    ...
}
</code>```

Finally, in OnElevationChanged update it so it to call GetColor so it can pass in the new Color property.

```<code>private static object OnElevationChanged(DependencyObject d, object value)
{
    if (d is UIElement element && value is double elevation)
        if (elevation == 0)
            element.Effect = null;
        else
        {
            Effect e = CreateElevation(elevation, element.Effect, GetColor(element));
            if (e != null)
                element.Effect = e;
        }
    return value;
}
</code>```

Example XAML

```<code><Button
    Width="100"
    Height="20"
    Content="shadow">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="local:UI.Elevation" Value="10" />
                    <Setter Property="local:UI.Color" Value="Blue" />
                </Trigger>
                <Trigger Property="IsMouseOver" Value="False">
                    <Setter Property="local:UI.Elevation" Value="5" />
                    <Setter Property="local:UI.Color" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

NOTE: There is some refactoring you could do to make all this cleaner, but hopefully this will get your started.

Title: Change Class-Binded Shadow Colour WPF

Body:
I was looking on how to replicate a Google button's shadow on hover effect in my WPF document and came across this: https://stackoverflow.com/a/53031057/12299798, which answers my problem exactly, but the only issue I have is that I normally do all the frontend things in XAML and so I am not quite experienced in the styling in C#. My problem is that I want to 'Bind' my foreground colour to the shadow colour, this is because in the code it only sets it to a greyish colour which would mean I would have to do a whole other class for each colour that I want to set it for. Here is my code now:

MainWindow.xaml:

<Button Content="shadow">
        <Button.Style>

            </Style>
        </Button.Style>
</Button>

UI.cs:

public static class UI
{

    public static readonly DependencyProperty ElevationProperty = DependencyProperty.RegisterAttached("Elevation", typeof(double), typeof(UI), new FrameworkPropertyMetadata(default(double), FrameworkPropertyMetadataOptions.AffectsRender, null, OnRedElevationChanged));

    public static double GetElevation(this UIElement element) => element.GetValue(ElevationProperty) as double? ?? default;

    public static void SetElevation(this UIElement element, double elevation) => element.SetValue(ElevationProperty, elevation);

    private static object OnRedElevationChanged(DependencyObject d, object value)
    {
        if (d is UIElement element && value is double elevation)
            if (elevation == 0)
                element.Effect = null;
            else
            {
                Effect e = CreateElevation(elevation, element.Effect);
                if (e != null)
                    element.Effect = e;
            }
        return value;
    }

    private static Effect CreateElevation(double elevation, Effect source)
    {
        void MixShadows(DropShadowEffect nearest, DropShadowEffect matched, double balance)
        {
            matched.BlurRadius = matched.BlurRadius * (1 - balance) + nearest.BlurRadius * balance;
            matched.ShadowDepth = matched.ShadowDepth * (1 - balance) + nearest.ShadowDepth * balance;
        }
        DropShadowEffect[] shadows = new DropShadowEffect[]
        {
        new DropShadowEffect()
        {
            BlurRadius = 5,
            ShadowDepth = 1
        },
        new DropShadowEffect()
        {
            BlurRadius = 8,
            ShadowDepth = 1.5
        },
        new DropShadowEffect()
        {
            BlurRadius = 14,
            ShadowDepth = 4.5
        },
        new DropShadowEffect()
        {
            BlurRadius = 25,
            ShadowDepth = 8
        },
        new DropShadowEffect()
        {
            BlurRadius = 35,
            ShadowDepth = 13
        }
        };
        elevation = Math.Max(0, elevation / 12 * shadows.Length - 1);
        int prevIndex = (int)Math.Floor(elevation), index = (int)elevation, nextIndex = (int)Math.Ceiling(elevation);
        double approx = elevation - index;
        DropShadowEffect shadow = shadows[index];
        if (approx != 0)
            MixShadows(approx < 0 ? shadows[prevIndex] : shadows[nextIndex], shadow, Math.Abs(approx));
        bool modify = false;
        if (source is DropShadowEffect sourceShadow)
        {
            sourceShadow.BlurRadius = shadow.BlurRadius;
            sourceShadow.ShadowDepth = shadow.ShadowDepth;
            shadow = sourceShadow;
            modify = true;
        }
        shadow.Direction = 270;
        shadow.Color = Colors.Red;
        shadow.Opacity = .42;
        shadow.RenderingBias = RenderingBias.Performance;
        return modify ? null : shadow;
    }
}

And to get what I want in XAML I would do something like this:

<Button Content="shadow">
        <Button.Style>

            </Style>
        </Button.Style>
</Button>

But I don't quite know how to link up the local:UI.Elevation.Foreground to change the shadow colour, I would have to change this line here from UI.cs: shadow.Color = Colors.Red; and bind it to the Elevation.Foreground, but I am having difficulties. Can anyone help?

Body:
All you need to do is updated the UI class with a new attached property named something like Color of type Color and give it a default color you like.

Then, in its OnColorChanged handler, call OnElevationChanged so that the shadow gets recreated.

#region Color (Attached Property)
public static readonly DependencyProperty ColorProperty =
    DependencyProperty.RegisterAttached(
        "Color",
        typeof(Color),
        typeof(UI),
        new PropertyMetadata(Colors.Black, OnColorChanged));

public static Color GetColor(DependencyObject obj)
{
    return (Color)obj.GetValue(ColorProperty);
}

public static void SetColor(DependencyObject obj, Color value)
{
    obj.SetValue(ColorProperty, value);
}

private static void OnColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    OnElevationChanged(d, GetElevation((UIElement)d));
}
#endregion

In the CreateElevation method, add a new parameter for the color, so you can set it.

private static Effect CreateElevation(double elevation, Effect source, Color color)
{
    ...
    shadow.Color = color;
    ...
}

Finally, in OnElevationChanged update it so it to call GetColor so it can pass in the new Color property.

private static object OnElevationChanged(DependencyObject d, object value)
{
    if (d is UIElement element && value is double elevation)
        if (elevation == 0)
            element.Effect = null;
        else
        {
            Effect e = CreateElevation(elevation, element.Effect, GetColor(element));
            if (e != null)
                element.Effect = e;
        }
    return value;
}

Example XAML

<Button
    Width="100"
    Height="20"
    Content="shadow">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="local:UI.Elevation" Value="10" />
                    <Setter Property="local:UI.Color" Value="Blue" />
                </Trigger>
                <Trigger Property="IsMouseOver" Value="False">
                    <Setter Property="local:UI.Elevation" Value="5" />
                    <Setter Property="local:UI.Color" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

NOTE: There is some refactoring you could do to make all this cleaner, but hopefully this will get your started.


问:
Why OAuth2 Not Use Access_Token & Secret
I don't understand the necessity of authorization_code, all the answers are because of the URL is not safe. But now use code & secret to get access_token, then get user sources. Why not get access_token from client, then use access_token & secret to get user sources on backend server. Even the attacker get the access_token， secret in the backend server, attacker can't get it.

答:
The Authorization Code Grant type is the most commonly used because it is optimized for server-side applications, where source code is not publicly exposed, and Client Secret confidentiality can be maintained.

This is a redirection-based flow, which means that the application must be capable of interacting with the user-agent (i.e. the user's web browser) and receiving API authorization codes that are routed through the user-agent.

This is 2 steps authorization process:

The user's web browser will initiate authentication/authorization. After authentication/authorization, the authorization server will send the authrorization_code to the client server (backend server) using redirect_url callback.

Now backend server can use authrorization_code to get the access_token and refresh_token without exposing the token to the external world.


问:
Codeigniter 4 - Naming Convention & Style Guide
I have found contradictory rules about Codeigniter 4 naming conventions & style guide. For example following are two guides about class names:
Controller class names MUST start with an uppercase letter and ONLY the first character can be uppercase.

Class names and namespaces SHOULD be declared in UpperCamelCase, also called StudlyCaps, unless another form is functionally required.

Can somebody clarify about method & class naming convention and whether we have different requirements for controllers, models,helpers, etc?

Can I use following convention:

All Classes: Any_class

Methods:     any_method

As URL should always be in lowercase so I think camelCase method names should not be used. What is your opinion?

I know its a matter of personal choice but I want to follow best practices.

答:
The first link is about Controllers, they have a functional requirement for UC-first style. This is needed to accommodate CI's direct mapping of URL segments to controller/method/parameter.

Not documented is that if a route is defined for any given controller then the UC first rule is not required. In that case, UpperCamelCase style SHOULD be used as it says in the second of the referenced links.

Keep in mind that UpperCamelCase refers to class naming. So that style does not apply to helpers. Those should use a "procedural" coding style.

The second link is otherwise the coding standard to follow.

Please keep in mind that the coding standard as found at the second link is about contributing code to the framework. For your own projects feel free to write code with any "style" you like. The only exception to that thought is the needs of Controller naming.


问:
How to get the Enum Index value in C#
In C, enums, internally equates to an integer. Therefore we can treat data types of enum as integer also.

How to achieve the same with C#?

答:
Use a cast:</p>

```<code>public enum MyEnum : int    {
    A = 0,
    B = 1,
    AB = 2,
}

int val = (int)MyEnum.A;
</code>```

Title: How to get the Enum Index value in C#

Body:
Use a cast:

public enum MyEnum : int    {
    A = 0,
    B = 1,
    AB = 2,
}

int val = (int)MyEnum.A;


问:
How do I convert an float to an integer in Elixir
Given a float, say (2.0), I want to convert it to an Integer type. It looks like Integer.parse only works for strings as far as I can tell.</p>

```<code>Integer.parse(2.0)
(FunctionClauseError) no function clause matching in Integer.count_digits/2
</code>```

答:
To summarize the different answers listed on this question, there are good four options as of writing this: trunc/1, round/1, floor/1, and ceil/1. All accept both floats and integers.

trunc/1

Removes the decimal part of a float.

```<code>iex> trunc(2.3)
2
iex> trunc(-2.3)
-2
</code>```

round/1

Rounds to the nearest integer.

```<code>iex> round(2.3)
2
iex> round(2.7)
3
iex> round(-2.3)
-2
iex> round(-2.7)
-3
</code>```

floor/1

Always rounds down. Available as of Elixir 1.8.0.

```<code>iex> floor(2.3)
2
iex> floor(-2.3)
-3
</code>```

ceil/1

Always rounds up. Available as of Elixir 1.8.0.

```<code>iex> ceil(2.3)
3
iex> ceil(-2.3)
-2
</code>```

Body:
Given a float, say (2.0), I want to convert it to an Integer type. It looks like Integer.parse only works for strings as far as I can tell.

Integer.parse(2.0)
(FunctionClauseError) no function clause matching in Integer.count_digits/2

Body:
To summarize the different answers listed on this question, there are good four options as of writing this: trunc/1, round/1, floor/1, and ceil/1. All accept both floats and integers.

trunc/1

Removes the decimal part of a float.

iex> trunc(2.3)
2
iex> trunc(-2.3)
-2

round/1

Rounds to the nearest integer.

iex> round(2.3)
2
iex> round(2.7)
3
iex> round(-2.3)
-2
iex> round(-2.7)
-3

floor/1

Always rounds down. Available as of Elixir 1.8.0.

iex> floor(2.3)
2
iex> floor(-2.3)
-3

ceil/1

Always rounds up. Available as of Elixir 1.8.0.

iex> ceil(2.3)
3
iex> ceil(-2.3)
-2


问:
importing in prop array values in React?
I have been working on creating a small music player program in React. I was wondering if there is a way to import all these values at once as a single import statement?

I noticed when I tried hardcoding in the values into the props array it will not work because the files are actually fetched from a /static/media directory.

Sample Code:

```<code>// Lightweight library for audio playing
import ReactAudioPlayer from 'react-audio-player';
import LikeBtn from './LikeBtn';
import Shuffle from '../img/shuffle_bg.jpg';
// Imports from music audio files
import track1 from '../music/Arc North - Catch Me When I Fall (ft. Sarah de Warren) [Magic Release].mp3';
import track2 from '../music/Ellis - Clear My Head.mp3';
import track3 from '../music/Jim Yosef & Alex Skrindo - Ruby [NCS Release].mp3';

// Import music covers
import bg1 from '../img/song_covers/42388294_800_800.jpg';
import bg2 from '../img/song_covers/clearhead.jpg';
import bg3 from '../img/song_covers/000377402250.jpg';

class Player2 extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      playlist: [
      // This would work because it fetches the imported value.
      {id: 1, name:'Catch Me When I Fall', author: 'Arc North ft. Sarah de Warren', img: bg1, audio: track1},
      // Does not work because it doesn't actually fetch the data from relative path.
      {id: 2, name:'Clear My Head', author: 'Ellis', img: '../img/song_covers/clearhead.jpg', audio:'../music/Ellis - Clear My Head.mp3},

</code>```

答:
You could create a file "mediaFiles.js" like below and import only that file

```<code> export default {
  img1: require('../Assets/img/shuffle_bg.jpg'),
  track1: require('../music/Ellis - Clear My Head.mp3'),
  }
</code>```

And in your Player2 file, import with the following line:

```<code>import mediaFiles from '../Utils/mediaFiles';
</code>```

And you should be able to use it like this,

```<code>this.state = {
          playlist: [
          {id: 1, name:'Catch Me When I Fall', author: 'Arc North ft. Sarah de Warren', img: mediaFiles.img1, audio: mediaFiles.track1}]
</code>```

FYI: update your paths accordingly

Body:
I have been working on creating a small music player program in React. I was wondering if there is a way to import all these values at once as a single import statement?

I noticed when I tried hardcoding in the values into the props array it will not work because the files are actually fetched from a /static/media directory.

Sample Code:

// Lightweight library for audio playing
import ReactAudioPlayer from 'react-audio-player';
import LikeBtn from './LikeBtn';
import Shuffle from '../img/shuffle_bg.jpg';
// Imports from music audio files
import track1 from '../music/Arc North - Catch Me When I Fall (ft. Sarah de Warren) [Magic Release].mp3';
import track2 from '../music/Ellis - Clear My Head.mp3';
import track3 from '../music/Jim Yosef & Alex Skrindo - Ruby [NCS Release].mp3';

// Import music covers
import bg1 from '../img/song_covers/42388294_800_800.jpg';
import bg2 from '../img/song_covers/clearhead.jpg';
import bg3 from '../img/song_covers/000377402250.jpg';

class Player2 extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      playlist: [
      // This would work because it fetches the imported value.
      {id: 1, name:'Catch Me When I Fall', author: 'Arc North ft. Sarah de Warren', img: bg1, audio: track1},
      // Does not work because it doesn't actually fetch the data from relative path.
      {id: 2, name:'Clear My Head', author: 'Ellis', img: '../img/song_covers/clearhead.jpg', audio:'../music/Ellis - Clear My Head.mp3},

Body:
You could create a file "mediaFiles.js" like below and import only that file

 export default {
  img1: require('../Assets/img/shuffle_bg.jpg'),
  track1: require('../music/Ellis - Clear My Head.mp3'),
  }

And in your Player2 file, import with the following line:

import mediaFiles from '../Utils/mediaFiles';

And you should be able to use it like this,

this.state = {
          playlist: [
          {id: 1, name:'Catch Me When I Fall', author: 'Arc North ft. Sarah de Warren', img: mediaFiles.img1, audio: mediaFiles.track1}]

FYI: update your paths accordingly


问:
How can I make the letters stop moving when I hover over them?
What happens when I hover over the numbers:

https://gyazo.com/20b6426d435551c5ee238241d3f96b4d

Basically when I hover over the pagination numbers they move to the right and I don't know what I have done wrong in my code for them to do that. At the very bottom of the post I'll add an HTML that is basically only pagination but doesn't have this problem.

The Code:

```<code><!-- Scripts -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
      // Collapsible
            var coll = document.getElementsByClassName("collapsible");
            var i;

            for (i = 0; i < coll.length; i++) {
                coll[i].addEventListener("click", function() {
                    this.classList.toggle("active");
                    var content = this.nextElementSibling;
                    if (content.style.maxHeight){
                        content.style.maxHeight = null;
                    } else {
                        content.style.maxHeight = content.scrollHeight + "px";
                    }
                });
            }
        </script>
    <script>
      // Pagination
      pageSize = 20;

      var pageCount =  $(".line-content").length / pageSize;

         for(var i = 0 ; i<pageCount;i++){

           $("#pagin").append('<li><a href="#">'+(i+1)+'</a></li> ');
         }
            $("#pagin li").first().find("a").addClass("current")
        showPage = function(page) {
          $(".line-content").hide();
          $(".line-content").each(function(n) {
              if (n >= pageSize * (page - 1) && n < pageSize * page)
                  $(this).show();
          });
      }

      showPage(1);

      $("#pagin li a").click(function() {
          $("#pagin li a").removeClass("current");
          $(this).addClass("current");
          showPage(parseInt($(this).text()))
      });
    </script>
</code>```

```<code>/* main.css */
body {
    background-color: #333;
    color: #999;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    line-height: 1.6em;
    margin: 0;
}
::-webkit-scrollbar {
    width: 10px;
}
::-webkit-scrollbar-track {
    box-shadow: inset 0 0 2px #000;
    border-radius: 5px;
    background: #999999;
}
::-webkit-scrollbar-thumb {
    border-radius: 5px;
    background: #686868;
}
::-webkit-scrollbar-thumb:hover {
    background: #4a4a4a;
}
.container {
    width: 80%;
    margin: auto;
    overflow: hidden;
}
#main-header {
    background-color: #444;
    color: #fff;
}
#navbar {
    background-color: #333;
    color: #fff;
}
#navbar ul {
    padding: 0;
    list-style: none;
}
#navbar li {
    display: inline;
}
#navbar a {
    color: #fff;
    text-decoration: none;
    font-size: 18px;
    padding-right: 15px;
}
#showcase {
    background-image: url('../images/background.jpg');
    background-position: center right;
    min-height: 300px;
    margin-bottom: 30px;
    text-align: center;
}
#showcase h1 {
    color: #fff;
    font-size: 50px;
    line-height: 1.6em;
    padding-top: 30px;
}
#main {
    float: left;
    width: 70%;
    padding: 0 30px;
    box-sizing: border-box;
}
#sidebar {
    border-radius: 10px;
    float: right;
    width: 30%;
    background: #444;
    color: #999;
    padding: 0px 15px;
  padding-bottom: 15px;
    box-sizing: border-box;
}
#main-footer {
    background: #222;
    color: #fff;
    text-align: center;
    padding: 20px;
    margin-top: 40px;
}
@media(max-width:600px) {
    #main {
        width: 100%;
        float: none;
    }
    #sidebar {
        width: 100%;
        float: none;
    }
}
</code>```

```<code>/* songscollapsible.css */
.current {
  color: inherit;
}
#pagin li {
  display: inline-block;
}
.collapsible {
  background-color: #444;
  color: #999;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 17px;
}
.active, .collapsible:hover {
  background-color: #555;
}
.content {
  max-height: 0;
  padding: 0px 15px 0px 15px;
  overflow: hidden;
  background-color: #666;
  color: #999;
  border-radius: 15px;
  transition: max-height 0.7s ease-out;
}
.button {
  box-shadow: 0px 2px 4px #555;
  border-radius: 15px;
}
/* .limg -> left image */
.limg {
  float: left;
  padding-right: 5px;
  max-width: 20px;
  max-height: 20px;
}
/* .fimg -> front image */
.fimg {
  float: left;
  padding-bottom: 15px;
  max-width: 20%;
}
.pl5 {
  padding-left: 5px;
}
.pl40 {
  padding-left: 40%;
}
.lh1-4 {
  line-height: 1.4;
}
.dli {
  max-width: 17px;
  max-height: 17px;
  padding-right: 5px;
}
a:link {
  text-decoration: none;
  color: #999;
}
a:visited {
  text-decoration: none;
  color: #999;
}
a:hover {
  text-decoration: none;
  color: #999;
}
a:active {
  text-decoration: none;
  color: #999;
}
</code>```

```<code><html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>test</title>
    <style>
      .current {
        color: inherit;
      }
      #pagin li {
        display: inline-block;
      }
    </style>
  </head>
  <body>
    <div class="line-content">test1</div>
    <div class="line-content">test2</div>
    <div class="line-content">test3</div>
    <div class="line-content">test4</div>
    <div class="line-content">test5</div>
    <div class="line-content">test6</div>
    <ul id="pagin"></ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script>
      // Pagination
      pageSize = 2;

      var pageCount =  $(".line-content").length / pageSize;

         for(var i = 0 ; i<pageCount;i++){

           $("#pagin").append('<li><a href="#">'+(i+1)+'</a></li> ');
         }
            $("#pagin li").first().find("a").addClass("current")
        showPage = function(page) {
          $(".line-content").hide();
          $(".line-content").each(function(n) {
              if (n >= pageSize * (page - 1) && n < pageSize * page)
                  $(this).show();
          });
      }

      showPage(1);

      $("#pagin li a").click(function() {
          $("#pagin li a").removeClass("current");
          $(this).addClass("current");
          showPage(parseInt($(this).text()))
      });
    </script>
  </body>
</html>
</code>```

答:
Try using the position:fixed method, this should make the numbers cease to move if you hover over the numbers.

```

Body:
What happens when I hover over the numbers:

https://gyazo.com/20b6426d435551c5ee238241d3f96b4d

Basically when I hover over the pagination numbers they move to the right and I don't know what I have done wrong in my code for them to do that. At the very bottom of the post I'll add an HTML that is basically only pagination but doesn't have this problem.

The Code:

/* main.css */
body {
    background-color: #333;
    color: #999;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    line-height: 1.6em;
    margin: 0;
}
::-webkit-scrollbar {
    width: 10px;
}
::-webkit-scrollbar-track {
    box-shadow: inset 0 0 2px #000;
    border-radius: 5px;
    background: #999999;
}
::-webkit-scrollbar-thumb {
    border-radius: 5px;
    background: #686868;
}
::-webkit-scrollbar-thumb:hover {
    background: #4a4a4a;
}
.container {
    width: 80%;
    margin: auto;
    overflow: hidden;
}
#main-header {
    background-color: #444;
    color: #fff;
}
#navbar {
    background-color: #333;
    color: #fff;
}
#navbar ul {
    padding: 0;
    list-style: none;
}
#navbar li {
    display: inline;
}
#navbar a {
    color: #fff;
    text-decoration: none;
    font-size: 18px;
    padding-right: 15px;
}
#showcase {
    background-image: url('../images/background.jpg');
    background-position: center right;
    min-height: 300px;
    margin-bottom: 30px;
    text-align: center;
}
#showcase h1 {
    color: #fff;
    font-size: 50px;
    line-height: 1.6em;
    padding-top: 30px;
}
#main {
    float: left;
    width: 70%;
    padding: 0 30px;
    box-sizing: border-box;
}
#sidebar {
    border-radius: 10px;
    float: right;
    width: 30%;
    background: #444;
    color: #999;
    padding: 0px 15px;
  padding-bottom: 15px;
    box-sizing: border-box;
}
#main-footer {
    background: #222;
    color: #fff;
    text-align: center;
    padding: 20px;
    margin-top: 40px;
}
@media(max-width:600px) {
    #main {
        width: 100%;
        float: none;
    }
    #sidebar {
        width: 100%;
        float: none;
    }
}

/* songscollapsible.css */
.current {
  color: inherit;
}
#pagin li {
  display: inline-block;
}
.collapsible {
  background-color: #444;
  color: #999;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 17px;
}
.active, .collapsible:hover {
  background-color: #555;
}
.content {
  max-height: 0;
  padding: 0px 15px 0px 15px;
  overflow: hidden;
  background-color: #666;
  color: #999;
  border-radius: 15px;
  transition: max-height 0.7s ease-out;
}
.button {
  box-shadow: 0px 2px 4px #555;
  border-radius: 15px;
}
/* .limg -> left image */
.limg {
  float: left;
  padding-right: 5px;
  max-width: 20px;
  max-height: 20px;
}
/* .fimg -> front image */
.fimg {
  float: left;
  padding-bottom: 15px;
  max-width: 20%;
}
.pl5 {
  padding-left: 5px;
}
.pl40 {
  padding-left: 40%;
}
.lh1-4 {
  line-height: 1.4;
}
.dli {
  max-width: 17px;
  max-height: 17px;
  padding-right: 5px;
}
a:link {
  text-decoration: none;
  color: #999;
}
a:visited {
  text-decoration: none;
  color: #999;
}
a:hover {
  text-decoration: none;
  color: #999;
}
a:active {
  text-decoration: none;
  color: #999;
}

    <meta charset="utf-8">
    <title>test</title>

test1

test2

test3

test4

test5

test6

Body:
Try using the position:fixed method, this should make the numbers cease to move if you hover over the numbers.

<style>
a:hover {
  position:fixed;
}
</style>


问:
How to assign date value for schema type Date in mongoose
Trying to set date like dd/mm/yyyy format for date type schema in mongoose but not working.How to set it?
Here my code.

```<code>Getting errer like string is not supporting Date type.
</code>```

model.js:

```<code>let customModel = new Schema({
    firstName: String,
    lastName: String,
    today: Date,
    afterfivedays: Date
});
</code>```

data.controller.js:

```<code>const data = [
{
    firstName: :"S",
    lastName: "Michel",
    today: "01/06/2020",
    afterfivedays: "06/06/2020",
}
]
</code>```

答:
Mongoose recognizes default JS format to parse it.
so convert date into default JS date format.
Or more info about working with dates visit Mongoose Date pattern

```<code>const data = [
  {
   firstName: :"S",
   lastName: "Michel",
   today: "2020-06-01",
   afterfivedays: "2020-06-06",
}
</code>```

]

Body:
Trying to set date like dd/mm/yyyy format for date type schema in mongoose but not working.How to set it?
Here my code.

Getting errer like string is not supporting Date type.

model.js:

let customModel = new Schema({
    firstName: String,
    lastName: String,
    today: Date,
    afterfivedays: Date
});

data.controller.js:

const data = [
{
    firstName: :"S",
    lastName: "Michel",
    today: "01/06/2020",
    afterfivedays: "06/06/2020",
}
]

Body:
Mongoose recognizes default JS format to parse it.
so convert date into default JS date format.
Or more info about working with dates visit Mongoose Date pattern

const data = [
  {
   firstName: :"S",
   lastName: "Michel",
   today: "2020-06-01",
   afterfivedays: "2020-06-06",
}

]


问:
"undefined reference to `__stat_time64'" when cross-compiling rust project on musl 1.2.0
I'm trying to cross-compile a rust project for arm-linux-musleabihf and am hitting a linker error when using musl-cross-make. The rust project has a dependency on libgit2 and this is the dependency that seems to be causing the problem.

Using:

the latest rust (1.43.1 via rustup)

the arm-unknown-linux-musleabihf target

the latest musl-cross-make with TARGET=arm-linux-musleabihf

pointing TARGET_CC_linux_arm-unknown-linux-musleabihf and CARGO_TARGET_ARM_UNKNOWN_LINUX_MUSLEABIHF_LINKER at /opt/musl-cross-make/output/bin/arm-linux-musleabihf-gcc

I get an error when building:

```<code>error: linking with `/opt/musl-cross-make/output/bin/arm-linux-musleabihf-gcc` failed: exit code: 1
...
  = note: /opt/musl-cross-make/output/bin/../lib/gcc/arm-linux-musleabihf/9.2.0/../../../../arm-linux-musleabihf/bin/ld: /tmp/rustcvSvGAJ/liblibgit2_sys-e56c2f9bd024a0a9.rlib(odb.o): in function `git_odb__add_default_backends':
          odb.c:(.text.git_odb__add_default_backends+0x24): undefined reference to `__stat_time64'
          /opt/musl-cross-make/output/bin/../lib/gcc/arm-linux-musleabihf/9.2.0/../../../../arm-linux-musleabihf/bin/ld: /tmp/rustcvSvGAJ/liblibgit2_sys-e56c2f9bd024a0a9.rlib(config.o): in function `git_config_add_file_ondisk':
          config.c:(.text.git_config_add_file_ondisk+0x34): undefined reference to `__stat_time64'
          /opt/musl-cross-make/output/bin/../lib/gcc/arm-linux-musleabihf/9.2.0/../../../../arm-linux-musleabihf/bin/ld: /tmp/rustcvSvGAJ/liblibgit2_sys-e56c2f9bd024a0a9.rlib(config_file.o): in function `config_file_read':
          config_file.c:(.text.config_file_read+0x48): undefined reference to `__stat_time64'
...etc...
</code>```

It looks like the linker is having difficulty resolving the musl-specific time64 symbols, and it's not clear why.

This works fine if:

I use the x86_64-linux-musl target on both rust and musl-cross-make

I build musl-cross-make with MUSL_VER=1.1.24

I also wrote a little C program that uses both time and stat, and this builds on musl 1.2.0 on the cross compiler without any issue.

What's going on here? What's special about libgit2 which means that it can't find the right __time64 symbols?

答:
You could try the instructions listed in https://github.com/richfelker/libcompat_time32:

Add -Wl,--whole-archive -lcompat_time32 -Wl,--no-whole-archive to the link command line. Special hacks (like prepending -Wl, to -lcompat_time32) may be needed if libtool is intercepting and mangling the command line.

Body:
I'm trying to cross-compile a rust project for arm-linux-musleabihf and am hitting a linker error when using musl-cross-make. The rust project has a dependency on libgit2 and this is the dependency that seems to be causing the problem.

Using:

the latest rust (1.43.1 via rustup)

the arm-unknown-linux-musleabihf target

the latest musl-cross-make with TARGET=arm-linux-musleabihf

pointing TARGET_CC_linux_arm-unknown-linux-musleabihf and CARGO_TARGET_ARM_UNKNOWN_LINUX_MUSLEABIHF_LINKER at /opt/musl-cross-make/output/bin/arm-linux-musleabihf-gcc

I get an error when building:

error: linking with `/opt/musl-cross-make/output/bin/arm-linux-musleabihf-gcc` failed: exit code: 1
...
  = note: /opt/musl-cross-make/output/bin/../lib/gcc/arm-linux-musleabihf/9.2.0/../../../../arm-linux-musleabihf/bin/ld: /tmp/rustcvSvGAJ/liblibgit2_sys-e56c2f9bd024a0a9.rlib(odb.o): in function `git_odb__add_default_backends':
          odb.c:(.text.git_odb__add_default_backends+0x24): undefined reference to `__stat_time64'
          /opt/musl-cross-make/output/bin/../lib/gcc/arm-linux-musleabihf/9.2.0/../../../../arm-linux-musleabihf/bin/ld: /tmp/rustcvSvGAJ/liblibgit2_sys-e56c2f9bd024a0a9.rlib(config.o): in function `git_config_add_file_ondisk':
          config.c:(.text.git_config_add_file_ondisk+0x34): undefined reference to `__stat_time64'
          /opt/musl-cross-make/output/bin/../lib/gcc/arm-linux-musleabihf/9.2.0/../../../../arm-linux-musleabihf/bin/ld: /tmp/rustcvSvGAJ/liblibgit2_sys-e56c2f9bd024a0a9.rlib(config_file.o): in function `config_file_read':
          config_file.c:(.text.config_file_read+0x48): undefined reference to `__stat_time64'
...etc...

It looks like the linker is having difficulty resolving the musl-specific time64 symbols, and it's not clear why.

This works fine if:

I use the x86_64-linux-musl target on both rust and musl-cross-make

I build musl-cross-make with MUSL_VER=1.1.24

I also wrote a little C program that uses both time and stat, and this builds on musl 1.2.0 on the cross compiler without any issue.

What's going on here? What's special about libgit2 which means that it can't find the right __time64 symbols?


问:
Get the Path of a .mp3 raw resource from URI
I'm trying to send an audio file to Dialogflow from an Android app.

In order to do that I need the Path of the audio file. According to the documentation, it goes like this:

```<code>val videouri: URI = URI.create("android.resource://$packageName/raw/tts")
val videopath: Path = Paths.get(videouri)
val inputAudio: ByteArray = Files.readAllBytes(videopath)
</code>```

However, on the second line, when obtaining the Path I get the following exception:

```<code>java.nio.file.filesystemnotfoundexception provider android.resource not installed
</code>```

The audio file is located in res > raw > tts.mp3

答:
First, raw resources are not files on the filesystem of the device.

Second, a URI is not a file.

Use Resources and openRawResource() to get an InputStream on the resource. IIRC, there is a readBytes() extension function in Kotlin that you can use to read in the contents.

Body:
I'm trying to send an audio file to Dialogflow from an Android app.

In order to do that I need the Path of the audio file. According to the documentation, it goes like this:

val videouri: URI = URI.create("android.resource://$packageName/raw/tts")
val videopath: Path = Paths.get(videouri)
val inputAudio: ByteArray = Files.readAllBytes(videopath)

However, on the second line, when obtaining the Path I get the following exception:

java.nio.file.filesystemnotfoundexception provider android.resource not installed

The audio file is located in res > raw > tts.mp3


问:
How to append inputs with formik in react
So this may be something simple but I'm hitting a roadblock. I want to take in a form input but can't seem to figure out how to append the value correctly so its appending string is captured.

I'm using Formik with yup in react.

```<code><InputGroup>
    <Field
      id="appended-input"
      name="domain_url"
      type="text"
      value={values.domain_url}
      className={
        "form-control" +
        (errors.domain_url && touched.domain_url
          ? " is-invalid"
          : "")
      }
    />
    <ErrorMessage
      name="domain_url"
      component="div"
      className="invalid-feedback"
    />
    <InputGroupAddon addonType="append">
      .localhost
    </InputGroupAddon>
</InputGroup>
</code>```

Any help would be appreciated. I just want to get the .localhost to be automatically added to the input items. for this field. I thought I could do something like value=({values.domain_url} + ".localhost") but that didn't seem to work and as you may already tell I am very new to javascript.

Thank you!

Full code below, I'm also having issues with datepicker displaying within the formik state, and then there's how to even get the values to push to my getTenant(function) to be passed to my api.

```<code>static propTypes = {
    addTenant: PropTypes.func.isRequired,
  };

  onSubmit = (values) => {
    values.preventDefault();

    this.props.addTenant(values);
  };

  render() {
    const {
      domain_url,
      schema_name,
      name,
      config,
    } = this.state;

    const TenantSchema = Yup.object().shape({
      domain_url: Yup.string()
        .max(255, "Must be shorter than 255 characters")
        .required("Client URL header is required"),
      schema_name: Yup.string()
        .max(255, "Must be shorter than 255 characters")
        .required("Client db name is required"),
      name: Yup.string()
        .max(255, "Must be shorter than 255 characters")
        .required("Client name is required"),
    });
    return (
      <div className={s.root}>
        <Formik
          initialValues={{
            domain_url: "",
            schema_name: "",
            client_name: "",
            config: [
              {
                date: "",
                Tenant_description: "",
              },
            ],
          }}
          // validationSchema={TenantSchema} this is commented off because it breaks
         submittions
          onSubmit={(values, { setSubmitting, resetForm }) => {
            setSubmitting(true);

            setTimeout(() => {
              alert(JSON.stringify(values, null, 2));
              resetForm();
              setSubmitting(false);
            }, 100);
          }}
        //onSubmit={onSubmit}

        >
          {({
            values,
            errors,
            status,
            touched,
            handleBlur,
            handleChange,
            isSubmitting,
            setFieldValue,
            handleSubmit,
            props,
          }) => (
            <FormGroup>
              <Form onSubmit={handleSubmit}>
                <legend>
                  <strong>Create</strong> Tenant
                </legend>
                <FormGroup row>
                  <Label for="normal-field" md={4} className="text-md-right">
                    Show URL
                  </Label>
                  <Col md={7}>
                    <InputGroup>
                      <Field
                        id="appended-input"
                        name="domain_url"
                        type="text"
                        value={values.domain_url}
                        onSubmit={(values) => {
                          values.domain_url = values.domain_url + ".localhost";
                        }} //this isn't working
                        className={
                          "form-control" +
                          (errors.domain_url && touched.domain_url
                            ? " is-invalid"
                            : "")
                        }
                      />
                      <ErrorMessage
                        name="domain_url"
                        component="div"
                        className="invalid-feedback"
                      />
                      <InputGroupAddon addonType="append">
                        .localhost
                      </InputGroupAddon>
                    </InputGroup>
                  </Col>
                </FormGroup>
                <FormGroup row>
                  <Label for="normal-field" md={4} className="text-md-right">
                    Database Name
                  </Label>
                  <Col md={7}>
                    <Field
                      name="schema_name"
                      type="text"
                      className={
                        "form-control" +
                        (errors.schema_name && touched.schema_name
                          ? " is-invalid"
                          : "")
                      }
                    />
                    <ErrorMessage
                      name="schema_name"
                      component="div"
                      className="invalid-feedback"
                    />
                  </Col>
                </FormGroup>
                <FormGroup row>
                  <Label for="normal-field" md={4} className="text-md-right">
                    Name
                  </Label>
                  <Col md={7}>
                    <Field
                      name="name"
                      type="text"
                      className={
                        "form-control" +
                        (errors.name && touched.name
                          ? " is-invalid"
                          : "")
                      }
                    />
                    <ErrorMessage
                      name="name"
                      component="div"
                      className="invalid-feedback"
                    />
                  </Col>
                </FormGroup>
                <FieldArray
                  name="config"
                  render={(arrayHelpers) => (
                    <div>
                      {values.config.map((config, index) => (
                        <div key={index}>
                           <FormGroup row>
                            <Label
                              md={4}
                              className="text-md-right"
                              for="mask-date"
                            >
                              Tenant Description
                            </Label>
                            <Col md={7}>
                              <TextareaAutosize
                                rows={3}
                                name={`config.${index}.tenant_description`}
                                id="elastic-textarea"
                                type="text"
                                onReset={values.event_description}
                                placeholder="Quick description of tenant"
                                onChange={handleChange}
                                value={values.tenant_description}
                                onBlur={handleBlur}
                                className={
                                  `form-control ${s.autogrow} transition-height` +
                                  (errors.tenant_description &&
                                  touched.tenant_description
                                    ? " is-invalid"
                                    : "")
                                }
                              />
                              <ErrorMessage
                                name="tenant_description"
                                component="div"
                                className="invalid-feedback"
                              />
                            </Col>
                          </FormGroup>
                          <FormGroup row>
                            <Label
                              for="normal-field"
                              md={4}
                              className="text-md-right"
                            >
                              Date
                            </Label>
                            <Col md={7}>
                              <DatePicker
                                tag={Field}
                                name={`config.${index}.date`}
                                type="date"
                                selected={values.date}
                                value={values.date}
                                className={
                                  "form-control" +
                                  (errors.date&& touched.date
                                    ? " is-invalid"
                                    : "")
                                }
                                onChange={(e) =>
                                  setFieldValue("date", e)
                                }
                              />
                              <ErrorMessage
                                name="date"
                                component="div"
                                className="invalid-feedback"
                              />
                            </Col>
                          </FormGroup>

                        </div>
                      ))}
                    </div>
                  )}
                />
                <div className="form-group">
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="btn btn-primary mr-2"
                  >
                    Save Tenant
                  </button>
                  <button type="reset" className="btn btn-secondary">
                    Reset
                  </button>
                </div>
              </Form>

              <Col md={7}>{JSON.stringify(values)}</Col>
            </FormGroup>
          )}
        </Formik>
      </div>
    );
  }
}

export default connect(null, { addTenant })(TenantForm);
</code>```

答:
You could use setFieldValue if you want to customize the value

https://jaredpalmer.com/formik/docs/api/formik#setfieldvalue-field-string-value-any-shouldvalidate-boolean--void

You can add onChange

```<code><Field
  id="appended-input"
  name="domain_url"
  type="text"
  value={values.domain_url}
  onChange={st => {
          let value = st.target.value;
          let suffix = ".localhost";
          let index = value.indexOf(".localhost");
          if (index > 0) {
            suffix = "";
          }
     //add suffix 'localhost' if it is  not already added
          props.setFieldValue("domain_url", value + suffix);
        }}

  className={
    "form-control" +
    (errors.domain_url && touched.domain_url ? " is-invalid" : "")
  }
/>;
</code>```

But adding suffix is more preferable on onSubmit:

```<code> onSubmit = {(values, actions) => {
       console.log('valuesbefore',values)
       values.domain_url= values.domain_url+ ".localhost"
       console.log('valuesafter',values)
       this.props.addTenant(values);
 };
</code>```

Body:
So this may be something simple but I'm hitting a roadblock. I want to take in a form input but can't seem to figure out how to append the value correctly so its appending string is captured.

I'm using Formik with yup in react.

<InputGroup>
    <Field
      id="appended-input"
      name="domain_url"
      type="text"
      value={values.domain_url}
      className={
        "form-control" +
        (errors.domain_url && touched.domain_url
          ? " is-invalid"
          : "")
      }
    />
    <ErrorMessage
      name="domain_url"
      component="div"
      className="invalid-feedback"
    />
    <InputGroupAddon addonType="append">
      .localhost
    </InputGroupAddon>
</InputGroup>

Any help would be appreciated. I just want to get the .localhost to be automatically added to the input items. for this field. I thought I could do something like value=({values.domain_url} + ".localhost") but that didn't seem to work and as you may already tell I am very new to javascript.

Thank you!

Full code below, I'm also having issues with datepicker displaying within the formik state, and then there's how to even get the values to push to my getTenant(function) to be passed to my api.

static propTypes = {
    addTenant: PropTypes.func.isRequired,
  };

  onSubmit = (values) => {
    values.preventDefault();

    this.props.addTenant(values);
  };

  render() {
    const {
      domain_url,
      schema_name,
      name,
      config,
    } = this.state;

    const TenantSchema = Yup.object().shape({
      domain_url: Yup.string()
        .max(255, "Must be shorter than 255 characters")
        .required("Client URL header is required"),
      schema_name: Yup.string()
        .max(255, "Must be shorter than 255 characters")
        .required("Client db name is required"),
      name: Yup.string()
        .max(255, "Must be shorter than 255 characters")
        .required("Client name is required"),
    });
    return (

        <Formik
          initialValues={{
            domain_url: "",
            schema_name: "",
            client_name: "",
            config: [
              {
                date: "",
                Tenant_description: "",
              },
            ],
          }}
          // validationSchema={TenantSchema} this is commented off because it breaks
         submittions
          onSubmit={(values, { setSubmitting, resetForm }) => {
            setSubmitting(true);

            setTimeout(() => {
              alert(JSON.stringify(values, null, 2));
              resetForm();
              setSubmitting(false);
            }, 100);
          }}
        //onSubmit={onSubmit}

        >
          {({
            values,
            errors,
            status,
            touched,
            handleBlur,
            handleChange,
            isSubmitting,
            setFieldValue,
            handleSubmit,
            props,
          }) => (
            <FormGroup>
              <Form onSubmit={handleSubmit}>
                <legend>
                  Create Tenant
                </legend>
                <FormGroup row>

                    Show URL

                  <Col md={7}>
                    <InputGroup>
                      <Field
                        id="appended-input"
                        name="domain_url"
                        type="text"
                        value={values.domain_url}
                        onSubmit={(values) => {
                          values.domain_url = values.domain_url + ".localhost";
                        }} //this isn't working
                        className={
                          "form-control" +
                          (errors.domain_url && touched.domain_url
                            ? " is-invalid"
                            : "")
                        }
                      />
                      <ErrorMessage
                        name="domain_url"
                        component="div"
                        className="invalid-feedback"
                      />
                      <InputGroupAddon addonType="append">
                        .localhost
                      </InputGroupAddon>
                    </InputGroup>
                  </Col>
                </FormGroup>
                <FormGroup row>

                    Database Name

                  <Col md={7}>
                    <Field
                      name="schema_name"
                      type="text"
                      className={
                        "form-control" +
                        (errors.schema_name && touched.schema_name
                          ? " is-invalid"
                          : "")
                      }
                    />
                    <ErrorMessage
                      name="schema_name"
                      component="div"
                      className="invalid-feedback"
                    />
                  </Col>
                </FormGroup>
                <FormGroup row>

                    Name

                  <Col md={7}>
                    <Field
                      name="name"
                      type="text"
                      className={
                        "form-control" +
                        (errors.name && touched.name
                          ? " is-invalid"
                          : "")
                      }
                    />
                    <ErrorMessage
                      name="name"
                      component="div"
                      className="invalid-feedback"
                    />
                  </Col>
                </FormGroup>
                <FieldArray
                  name="config"
                  render={(arrayHelpers) => (

                      {values.config.map((config, index) => (

                           <FormGroup row>

                              Tenant Description

                            <Col md={7}>
                              <TextareaAutosize
                                rows={3}
                                name={`config.${index}.tenant_description`}
                                id="elastic-textarea"
                                type="text"
                                onReset={values.event_description}
                                placeholder="Quick description of tenant"
                                onChange={handleChange}
                                value={values.tenant_description}
                                onBlur={handleBlur}
                                className={
                                  `form-control ${s.autogrow} transition-height` +
                                  (errors.tenant_description &&
                                  touched.tenant_description
                                    ? " is-invalid"
                                    : "")
                                }
                              />
                              <ErrorMessage
                                name="tenant_description"
                                component="div"
                                className="invalid-feedback"
                              />
                            </Col>
                          </FormGroup>
                          <FormGroup row>

                              Date

                            <Col md={7}>
                              <DatePicker
                                tag={Field}
                                name={`config.${index}.date`}
                                type="date"
                                selected={values.date}
                                value={values.date}
                                className={
                                  "form-control" +
                                  (errors.date&& touched.date
                                    ? " is-invalid"
                                    : "")
                                }
                                onChange={(e) =>
                                  setFieldValue("date", e)
                                }
                              />
                              <ErrorMessage
                                name="date"
                                component="div"
                                className="invalid-feedback"
                              />
                            </Col>
                          </FormGroup>

                      ))}

                  )}
                />

                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="btn btn-primary mr-2"
                  >
                    Save Tenant
                  </button>
                  <button type="reset" className="btn btn-secondary">
                    Reset
                  </button>

              </Form>

              <Col md={7}>{JSON.stringify(values)}</Col>
            </FormGroup>
          )}
        </Formik>

    );
  }
}

export default connect(null, { addTenant })(TenantForm);

Body:
You could use setFieldValue if you want to customize the value

https://jaredpalmer.com/formik/docs/api/formik#setfieldvalue-field-string-value-any-shouldvalidate-boolean--void

You can add onChange

<Field
  id="appended-input"
  name="domain_url"
  type="text"
  value={values.domain_url}
  onChange={st => {
          let value = st.target.value;
          let suffix = ".localhost";
          let index = value.indexOf(".localhost");
          if (index > 0) {
            suffix = "";
          }
     //add suffix 'localhost' if it is  not already added
          props.setFieldValue("domain_url", value + suffix);
        }}

  className={
    "form-control" +
    (errors.domain_url && touched.domain_url ? " is-invalid" : "")
  }
/>;

But adding suffix is more preferable on onSubmit:

 onSubmit = {(values, actions) => {
       console.log('valuesbefore',values)
       values.domain_url= values.domain_url+ ".localhost"
       console.log('valuesafter',values)
       this.props.addTenant(values);
 };


问:
How to properly import the libphonelib to the java project?
I'm trying to use the PhoneNumberMatcher from the libphonenumber library. After adding the jar file to my project and setting the BuildPath, I was able to import classes to my project:

import com.google.i18n.phonenumbers.*;

Inside the lib, there is a class named PhoneNumberMatcher.class. I've been trying to reach it but this class name isn't included in suggestions I normally get when I press Ctrl + Space.

If I insist and write the name class, eclipse will underline the name and the message "The type PhoneNumberMatcher is not visible".
Newly I realized that the class has a small blue flag icon is in the project explorer.

It's not the only one that has such a blue flag, then I try the other classes and I realized that all classes with this blue flag isn't accessible. That's why I think these classes probably are private, or for internal use of the lib.

I'm trying to create a tool to extract phone numbers out of a text and I read this lib is exactly for it.

How do I use the PhonNumberMatcher class in my java project, please?

答:
```<code> CharSequence text = "Call me at +1 425 882-8080 for details.";
 String country = "US";
 PhoneNumberUtil util = PhoneNumberUtil.getInstance();

 // Find the first phone number match:
 PhoneNumberMatch m = util.findNumbers(text, country).iterator().next();

 // rawString() contains the phone number as it appears in the text.
 "+1 425 882-8080".equals(m.rawString());

 // start() and end() define the range of the matched subsequence.
 CharSequence subsequence = text.subSequence(m.start(), m.end());
 "+1 425 882-8080".contentEquals(subsequence);

 // number() returns the the same result as PhoneNumberUtil.parse()
 // invoked on rawString().
 util.parse(m.rawString(), country).equals(m.number());
</code>```

https://javadoc.io/doc/com.googlecode.libphonenumber/libphonenumber

Body:
 CharSequence text = "Call me at +1 425 882-8080 for details.";
 String country = "US";
 PhoneNumberUtil util = PhoneNumberUtil.getInstance();

 // Find the first phone number match:
 PhoneNumberMatch m = util.findNumbers(text, country).iterator().next();

 // rawString() contains the phone number as it appears in the text.
 "+1 425 882-8080".equals(m.rawString());

 // start() and end() define the range of the matched subsequence.
 CharSequence subsequence = text.subSequence(m.start(), m.end());
 "+1 425 882-8080".contentEquals(subsequence);

 // number() returns the the same result as PhoneNumberUtil.parse()
 // invoked on rawString().
 util.parse(m.rawString(), country).equals(m.number());

https://javadoc.io/doc/com.googlecode.libphonenumber/libphonenumber


问:
How to print tuples of unicode strings in original language (not u'foo' form)
I have a list of tuples of unicode objects:

```<code>>>> t = [('亀',), ('犬',)]
</code>```

Printing this out, I get:

```<code>>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
</code>```

which I guess is a list of the utf-8 byte-code representation of those strings?

but what I want to see printed out is, surprise:

```<code>[('亀',), ('犬',)]
</code>```

but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form.

答:
So this appears to do what I want:

```<code>print '[%s]' % ', '.join([', '.join('(%s,)' % ', '.join(ti) for ti in t)])

>>> t = [('亀',), ('犬',)]
>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
>>> print '[%s]' % ', '.join([', '.join('(%s,)' % ', '.join(ti) for ti in t)])
[(亀,), (犬,)]
</code>```

Surely there's a better way to do it.

(but other two answers thus far don't result in the original string being printed out as desired).

OwnerDisplayName: Daniel H

ContentLicense: CC BY-SA 2.5

Body:
I have a list of tuples of unicode objects:

>>> t = [('亀',), ('犬',)]

Printing this out, I get:

>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]

which I guess is a list of the utf-8 byte-code representation of those strings?

but what I want to see printed out is, surprise:

[('亀',), ('犬',)]

but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form.

Body:
So this appears to do what I want:

print '[%s]' % ', '.join([', '.join('(%s,)' % ', '.join(ti) for ti in t)])

>>> t = [('亀',), ('犬',)]
>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
>>> print '[%s]' % ', '.join([', '.join('(%s,)' % ', '.join(ti) for ti in t)])
[(亀,), (犬,)]

Surely there's a better way to do it.

(but other two answers thus far don't result in the original string being printed out as desired).


问:
Django error :sdr_media' is not a valid tag library: Template library sdr_media not found . How to remove this error?
My sdr_media.py is in this path .

```<code>geodjango/geographic_admin/templates/templatetags/sdr_media.py
</code>```

My layer_upload.html is in this folder

```<code>   geodjango/geographic_admin/template/maps
</code>```

The code is this

```<code>{% load sdr_media %}
</code>```

But , still the sdr_media tag is  not found . The templatetags folder has init.py for it to work . Is my path wrong ?

Edit

This is the sdr_media.py code

```<code>from django import template
from django.conf import settings

register = template.Library()

@register.tag('sdr_media')
def geonode_media(parser, token):
    try:
        tagname, argument = token.split_contents()
        argument = argument[1:-1] # get rid of quotes
        if not argument in settings.MEDIA_LOCATIONS:
            raise template.TemplateSyntaxError, '%s is not a valid resource name' % argument
        return MediaNode(argument)
    except ValueError:
        raise template.TemplateSyntaxError, '%r requires a single argument' % token.contents.split()[0]

class MediaNode(template.Node):
    def __init__(self, resource):
        self.resource = resource

    def render(self, context):
        return settings.MEDIA_LOCATIONS[self.resource]
</code>```

答:
Yes, it is. templatetags directory should be in app directory, not in templates directory.

For example myproject/myapp/templatetags/sdr_media.py

Body:
My sdr_media.py is in this path .

geodjango/geographic_admin/templates/templatetags/sdr_media.py

My layer_upload.html is in this folder

   geodjango/geographic_admin/template/maps

The code is this

{% load sdr_media %}

But , still the sdr_media tag is  not found . The templatetags folder has init.py for it to work . Is my path wrong ?

Edit

This is the sdr_media.py code

from django import template
from django.conf import settings

register = template.Library()

@register.tag('sdr_media')
def geonode_media(parser, token):
    try:
        tagname, argument = token.split_contents()
        argument = argument[1:-1] # get rid of quotes
        if not argument in settings.MEDIA_LOCATIONS:
            raise template.TemplateSyntaxError, '%s is not a valid resource name' % argument
        return MediaNode(argument)
    except ValueError:
        raise template.TemplateSyntaxError, '%r requires a single argument' % token.contents.split()[0]

class MediaNode(template.Node):
    def __init__(self, resource):
        self.resource = resource

    def render(self, context):
        return settings.MEDIA_LOCATIONS[self.resource]


问:
python crashes while running jupyter notebook
i have installed Anaconda on my machine. In anaconda terminal python working properly but when I run jupyter notebook or spyder python crashes with following error message:

The exception unknown software exception(0x40000015) occurred in the application at location oxfcdbaa7d

```<code>Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: python.exe
  Application Version:  3.6.10150.1013
  Application Timestamp:    5eb4c8bb
  Fault Module Name:    KERNELBASE.dll
  Fault Module Version: 6.1.7600.16385
  Fault Module Timestamp:   4a5bdfe0
  Exception Code:   40000015
  Exception Offset: 000000000000aa7d
  OS Version:   6.1.7600.2.1.0.256.1
  Locale ID:    1033
  Additional Information 1: 389b
  Additional Information 2: 389bb461874f8b25850c900f8e8bed17
  Additional Information 3: ef28
  Additional Information 4: ef2897a45abdb10847ea1ff86dcfeb5c
</code>```

What i have tried:

windows and anaconda versions are same
reinstalling anaconda in the c drive
deleting previous python version
troubleshooting jupyter
links present in this article enter link description here

running on a different browser and almost everything present on google.

Please help I don't know what should i do next.

答: What browser did you use? Try Google chrome if you have not tried with it. </p>

Body:
i have installed Anaconda on my machine. In anaconda terminal python working properly but when I run jupyter notebook or spyder python crashes with following error message:

The exception unknown software exception(0x40000015) occurred in the application at location oxfcdbaa7d

Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: python.exe
  Application Version:  3.6.10150.1013
  Application Timestamp:    5eb4c8bb
  Fault Module Name:    KERNELBASE.dll
  Fault Module Version: 6.1.7600.16385
  Fault Module Timestamp:   4a5bdfe0
  Exception Code:   40000015
  Exception Offset: 000000000000aa7d
  OS Version:   6.1.7600.2.1.0.256.1
  Locale ID:    1033
  Additional Information 1: 389b
  Additional Information 2: 389bb461874f8b25850c900f8e8bed17
  Additional Information 3: ef28
  Additional Information 4: ef2897a45abdb10847ea1ff86dcfeb5c

What i have tried:

windows and anaconda versions are same
reinstalling anaconda in the c drive
deleting previous python version
troubleshooting jupyter
links present in this article enter link description here

running on a different browser and almost everything present on google.

Please help I don't know what should i do next.


答:
According to the documentation, it will cast the value to native js date

So you can pass

```<code>const data = [
{
    firstName: :"S",
    lastName: "Michel",
    today: "2020-06-01",
    afterfivedays: "2020-06-06"
}
]
</code>```

Title: How to assign date value for schema type Date in mongoose

Body:
According to the documentation, it will cast the value to native js date

So you can pass

const data = [
{
    firstName: :"S",
    lastName: "Michel",
    today: "2020-06-01",
    afterfivedays: "2020-06-06"
}
]


问:
How do I reference a system library used by an external dependency if copts doesn't allow system paths?
For Bazel, I'm pulling in an external library from within my WORKSPACE:

```<code>new_http_archive(
      name = "imgui",
      build_file = "deps/BUILD.imgui",
      sha256 = "c457fdc19b4e3aa74deccf6a2d9bc51f0d470b3acd9cc095bf04df16459d6474",
      strip_prefix = 'imgui-1.62',
      url = "https://github.com/ocornut/imgui/archive/v1.62.tar.gz",
)
</code>```

Inside BUILD.imgui, I'm attempting to build it:

```<code>cc_library(
 name = "imgui_sdl_opengl3",
 linkopts = ["-ldl", "-lGL", "-L/usr/lib/x86_64-linux-gnu", "-lSDL2", "-lSDL"],
 copts = ["-Iexamples/", "-D_REENTRANT",],
 includes = [".","examples/libs/gl3w"],
 hdrs = [
     "examples/imgui_impl_opengl3.h",
     "examples/libs/gl3w/GL/gl3w.h",
     "examples/imgui_impl_sdl.h",
     "examples/libs/gl3w/GL/glcorearb.h",
 ],
 srcs = [
     "examples/imgui_impl_opengl3.cpp",
     "examples/imgui_impl_sdl.cpp",
     "examples/libs/gl3w/GL/gl3w.c",
 ],
)
</code>```

The problem is that it can't find #include <SDL.h>.

I tried adding it to copts:

```<code> copts = ["-Iexamples/", "-D_REENTRANT", "-I/usr/include/SDL"],
</code>```

But the error is:

```<code>The include path '/usr/include/SDL' references a path outside of the execution root.
</code>```

Ok. Same if I try to add it to the includes argument of cc_library.

I tried this other trick I saw where you make the headers visible through another repo within Bazel editing the WORKSPACE as followed:

```<code>new_local_repository(
    name = "SDL",
    path = "/usr/include/SDL",
    build_file_content = """
package(
    default_visibility = [
        "//visibility:public",
    ],
)

cc_library(
    name = "headers",
    srcs = glob(["**/*.h"]),
)
""",
</code>```

The problem is, if I reference that repo as a deps to the external library I'm trying to build, I get the following error:

```<code>external/imgui/examples/imgui_impl_sdl.cpp:38:10: error: 'SDL.h' file not found with <angled> include; use "quotes" instead
#include <SDL.h>
         ^~~~~~~
         "SDL.h"
</code>```

Of course I can't change the header to that, because its not my header.  It comes from the external library I pulled down.

What do I do?

I don't understand why I can't add system paths to copts (probably hermetic reasons).  I don't know how to include paths and have them  accessible as system headers.  I tried different things with -isystem as as well, but saw the same errors.

答:
As László stated, you can set the includes to the current directory which will allow it to be detected as a system header when used as a dependency in other code:

```<code>cc_library(
    ...
    includes = [
        ".",
    ],
)
</code>```

Body:
For Bazel, I'm pulling in an external library from within my WORKSPACE:

new_http_archive(
      name = "imgui",
      build_file = "deps/BUILD.imgui",
      sha256 = "c457fdc19b4e3aa74deccf6a2d9bc51f0d470b3acd9cc095bf04df16459d6474",
      strip_prefix = 'imgui-1.62',
      url = "https://github.com/ocornut/imgui/archive/v1.62.tar.gz",
)

Inside BUILD.imgui, I'm attempting to build it:

cc_library(
 name = "imgui_sdl_opengl3",
 linkopts = ["-ldl", "-lGL", "-L/usr/lib/x86_64-linux-gnu", "-lSDL2", "-lSDL"],
 copts = ["-Iexamples/", "-D_REENTRANT",],
 includes = [".","examples/libs/gl3w"],
 hdrs = [
     "examples/imgui_impl_opengl3.h",
     "examples/libs/gl3w/GL/gl3w.h",
     "examples/imgui_impl_sdl.h",
     "examples/libs/gl3w/GL/glcorearb.h",
 ],
 srcs = [
     "examples/imgui_impl_opengl3.cpp",
     "examples/imgui_impl_sdl.cpp",
     "examples/libs/gl3w/GL/gl3w.c",
 ],
)

The problem is that it can't find #include <SDL.h>.

I tried adding it to copts:

 copts = ["-Iexamples/", "-D_REENTRANT", "-I/usr/include/SDL"],

But the error is:

The include path '/usr/include/SDL' references a path outside of the execution root.

Ok. Same if I try to add it to the includes argument of cc_library.

I tried this other trick I saw where you make the headers visible through another repo within Bazel editing the WORKSPACE as followed:

new_local_repository(
    name = "SDL",
    path = "/usr/include/SDL",
    build_file_content = """
package(
    default_visibility = [
        "//visibility:public",
    ],
)

cc_library(
    name = "headers",
    srcs = glob(["**/*.h"]),
)
""",

The problem is, if I reference that repo as a deps to the external library I'm trying to build, I get the following error:

external/imgui/examples/imgui_impl_sdl.cpp:38:10: error: 'SDL.h' file not found with <angled> include; use "quotes" instead
#include <SDL.h>
         ^~~~~~~
         "SDL.h"

Of course I can't change the header to that, because its not my header.  It comes from the external library I pulled down.

What do I do?

I don't understand why I can't add system paths to copts (probably hermetic reasons).  I don't know how to include paths and have them  accessible as system headers.  I tried different things with -isystem as as well, but saw the same errors.

Body:
As László stated, you can set the includes to the current directory which will allow it to be detected as a system header when used as a dependency in other code:

cc_library(
    ...
    includes = [
        ".",
    ],
)


问:
How to get post title by contact form 7
I'm using contact form 7 in a website for get REQUEST QUOTE of each product.

Link to example

When visitor submit the REQUEST QUOTE form then I get a mail with desalts and want to get each single post title in that mail. I used [_post_title] code for get single post title and I got title. But I got only one post title from top of the page.

How I can get every single post title in the mail ?

答:
Install Contact Form 7 Dynamic Text Extension and use this code inside form
In Form Tab of CF7

```<code>[dynamichidden unique-name "CF7_get_post_var key='title'"]
[dynamichidden page-url "CF7_URL"]
</code>```

In Mail Tab :

To Output this data ,
you can use the tag [unique-name] in
Subject or Message body in CF7 Mail tab

For Current Page title :
[dynamichidden unique-name "CF7_get_post_var key='title'"]

For Current Page Link :

[dynamichidden page-url "CF7_URL"]

Title: How to get post title by contact form 7

Body:
Install Contact Form 7 Dynamic Text Extension and use this code inside form
In Form Tab of CF7

[dynamichidden unique-name "CF7_get_post_var key='title'"]
[dynamichidden page-url "CF7_URL"]

In Mail Tab :

To Output this data ,
you can use the tag [unique-name] in
Subject or Message body in CF7 Mail tab

For Current Page title :
[dynamichidden unique-name "CF7_get_post_var key='title'"]

For Current Page Link :

[dynamichidden page-url "CF7_URL"]


问:
Saving Files c# - without overwriting?
I am saving data to a file every 60 secs, I have it saving every 60 secs ok but it deletes the previous data added. Is there a way in which it would add to the file rather than overwrite it. And without using save dialog as it is done in the background.

Any feedback is greatly appreciated

答:
You can use StreamWriter with append as true in the constructor.

See here.

Title: Saving Files c# - without overwriting?


问:
SwiftUI binding boolean if statement (Cannot convert value of type 'Binding<Bool>' to expected condition type 'Bool')
I'm trying to conditionally show a View (not using .sheet) and using a binding boolean returns the error above in the title. If I use self.menuactivated, no view will be presented upon the @State variable toggle. Is there a way around this?

```<code>struct ContentView: View {
    @State private var menuActivated  = false

    var body: some View {
        NavigationView {
            ... // code
        }
        if $menuActivated {
            menuView()
        }
    }
}
</code>```

答:
in case if you are looking for condition based view </p>

```<code>func getView() -> AnyView {
    return AnyView(
        //any business logic and view
    )
}
</code>```

<p>and use it like </p>

```<code>self.getView()
</code>```

Body:
I'm trying to conditionally show a View (not using .sheet) and using a binding boolean returns the error above in the title. If I use self.menuactivated, no view will be presented upon the @State variable toggle. Is there a way around this?

struct ContentView: View {
    @State private var menuActivated  = false

    var body: some View {
        NavigationView {
            ... // code
        }
        if $menuActivated {
            menuView()
        }
    }
}

Body:
in case if you are looking for condition based view

func getView() -> AnyView {
    return AnyView(
        //any business logic and view
    )
}

and use it like

self.getView()


问:
Angular async call inside an observable
I have a function to make expire date control for an Item.
In this function i create an observable that checks if the item is new or not.
If it´s new it works as expected but when a try to get some complementary data to define if its expiring date is when it does not work well.

If the call is made for a single Item it works fine but when i try to fill a table with several item it return undefined.

I think it is a matter of the async call. The subscriber is not waiting for the inner httprequest to finish before making a new call for the next item on the table.

1- Function that meke the call to get the expire date and set the proper status.

```<code> /* ValueGetter para mostrar en la tabla si la droga está vencida o vigente */
      ctlVigencia(params){
        let message: string;
        this.ds.ctlVencimientoDroga(params.data._id, params.data.informacion.fecha.vencimientoCertificado, null)
        .subscribe(res=> {
          console.log(res);

          if(res.fAsignada == null){
            message= 'No deterninado'
          } else {
            let now = moment(new Date());
            if (res.fAsignada > now ) {
              message= 'Vigente'
            } else {
              message= ('Vencida')
            }
          }
        })
        return message
      };
</code>```

2) Function that returns the value of the expiration date.

```<code>  /*Control vencimiento droga */
    ctlVencimientoDroga(idSelected: string, vencimientoCertificado: Date, modeForm?: string){
      let retesteos: Retesteo[];
      const resObs= Observable.create((observer:Observer<{[key: string]: any}>) =>{
        if (modeForm == 'nuevo'){
          observer.next({fAsignada: vencimientoCertificado})
          observer.complete();
        } else{
          this.rs.dataRetesteo.subscribe(res=>{
            retesteos= res;
            if (retesteos && retesteos.length == 0) {
              if(vencimientoCertificado != null) {
                observer.next({fAsignada: vencimientoCertificado});
              } else {
                observer.next(null);
              }
            }
            /* From here and down is where is the problem */
            if (retesteos && retesteos.length > 0){
              let fechaUltimoRetesteoAprobado: Date;
              retesteos.forEach(element => {
                if (element.estado.estado == estadoAprobacion.Aprobado && (fechaUltimoRetesteoAprobado == null || element.fVencimiento > fechaUltimoRetesteoAprobado )){
                  fechaUltimoRetesteoAprobado= element.fVencimiento
                }
              });
              observer.next({fAsignada: fechaUltimoRetesteoAprobado});
            }
            observer.complete();
          });
          this.rs.getById(idSelected);
        }
      })
      return resObs;
  }
}
</code>```

I appreciate your help.

答:
You are assigning the value to message inside an asynchronous operation, but returning message synchronously. Try modifying ctlVigencia to return an Observable and use map on the response of ctlVencimientoDroga.

```<code>ctlVigencia(params): Observable<string> {
  return this.ds.ctlVencimientoDroga(params.data._id, params.data.informacion.fecha.vencimientoCertificado, null)
  .pipe(map(res=> {
    console.log(res);

    if(res.fAsignada == null){
      message= 'No deterninado'
    } else {
      let now = moment(new Date());
      if (res.fAsignada > now ) {
        message= 'Vigente'
      } else {
        message= ('Vencida')
      }
    }

    return message;
  }))
};
</code>```

Please, not that I've changed subscribe for pipe and used map. Now, when invoking ctlVigencia you should subscribe

```<code>ctlVigencia(params).subscribe(message => console.log(message));
</code>```

Title: Angular async call inside an observable

Body:
I have a function to make expire date control for an Item.
In this function i create an observable that checks if the item is new or not.
If it´s new it works as expected but when a try to get some complementary data to define if its expiring date is when it does not work well.

If the call is made for a single Item it works fine but when i try to fill a table with several item it return undefined.

I think it is a matter of the async call. The subscriber is not waiting for the inner httprequest to finish before making a new call for the next item on the table.

1- Function that meke the call to get the expire date and set the proper status.

 /* ValueGetter para mostrar en la tabla si la droga está vencida o vigente */
      ctlVigencia(params){
        let message: string;
        this.ds.ctlVencimientoDroga(params.data._id, params.data.informacion.fecha.vencimientoCertificado, null)
        .subscribe(res=> {
          console.log(res);

          if(res.fAsignada == null){
            message= 'No deterninado'
          } else {
            let now = moment(new Date());
            if (res.fAsignada > now ) {
              message= 'Vigente'
            } else {
              message= ('Vencida')
            }
          }
        })
        return message
      };

2) Function that returns the value of the expiration date.

  /*Control vencimiento droga */
    ctlVencimientoDroga(idSelected: string, vencimientoCertificado: Date, modeForm?: string){
      let retesteos: Retesteo[];
      const resObs= Observable.create((observer:Observer<{[key: string]: any}>) =>{
        if (modeForm == 'nuevo'){
          observer.next({fAsignada: vencimientoCertificado})
          observer.complete();
        } else{
          this.rs.dataRetesteo.subscribe(res=>{
            retesteos= res;
            if (retesteos && retesteos.length == 0) {
              if(vencimientoCertificado != null) {
                observer.next({fAsignada: vencimientoCertificado});
              } else {
                observer.next(null);
              }
            }
            /* From here and down is where is the problem */
            if (retesteos && retesteos.length > 0){
              let fechaUltimoRetesteoAprobado: Date;
              retesteos.forEach(element => {
                if (element.estado.estado == estadoAprobacion.Aprobado && (fechaUltimoRetesteoAprobado == null || element.fVencimiento > fechaUltimoRetesteoAprobado )){
                  fechaUltimoRetesteoAprobado= element.fVencimiento
                }
              });
              observer.next({fAsignada: fechaUltimoRetesteoAprobado});
            }
            observer.complete();
          });
          this.rs.getById(idSelected);
        }
      })
      return resObs;
  }
}

I appreciate your help.

Body:
You are assigning the value to message inside an asynchronous operation, but returning message synchronously. Try modifying ctlVigencia to return an Observable and use map on the response of ctlVencimientoDroga.

ctlVigencia(params): Observable<string> {
  return this.ds.ctlVencimientoDroga(params.data._id, params.data.informacion.fecha.vencimientoCertificado, null)
  .pipe(map(res=> {
    console.log(res);

    if(res.fAsignada == null){
      message= 'No deterninado'
    } else {
      let now = moment(new Date());
      if (res.fAsignada > now ) {
        message= 'Vigente'
      } else {
        message= ('Vencida')
      }
    }

    return message;
  }))
};

Please, not that I've changed subscribe for pipe and used map. Now, when invoking ctlVigencia you should subscribe

ctlVigencia(params).subscribe(message => console.log(message));