问:
Log4J doesn't look like to work with sudo
I've got a Java application and I'm trying to run this application on Linux boot. Problem is that Log4J doesn't look like to work with commands "runuser", "sudo" and "su".
Every single time, I'm getting an error:

```<code>WARNING: sun.reflect.Reflection.getCallerClass is not supported. This will impact performance.
(30/05/2020-15:16:11.825) [FATAL] Unable to log file
Exception in thread "main" java.lang.NullPointerException
        at me.inao.discordbot.util.Logger.<init>(Logger.java:28)
        at me.inao.discordbot.Main.loadConfig(Main.java:65)
        at me.inao.discordbot.Main.starter(Main.java:46)
        at me.inao.discordbot.Main.main(Main.java:43)
</code>```

App is Open-Sourced, so here is my full source: https://github.com/onemoreplays/bufferBot
Does this happen to someone else? Is that because of my bad programming habits or it's a bug somewhere else?

Thank you for any help.

Jakub.

答:
Main#getApi() method is executed in the Logger constructor. But, according to the stacktrace, current logger is instantiated in the Main#loadConfig() method (Main.java, line 46), before api field is actually initialized (Main.java, line 47).

Update:
Described issue in Logger constructor hides an original exception, thrown in try..catch block of the loadConfig method. The most likely cause of the original issue is access to 'config.json' file under the root. But the best way is to fix NPE in the Logger class, so you will see stack trace of the original exception.

Also it could be a good idea to decouple Logger from your business logic.

Body:
I've got a Java application and I'm trying to run this application on Linux boot. Problem is that Log4J doesn't look like to work with commands "runuser", "sudo" and "su".
Every single time, I'm getting an error:

WARNING: sun.reflect.Reflection.getCallerClass is not supported. This will impact performance.
(30/05/2020-15:16:11.825) [FATAL] Unable to log file
Exception in thread "main" java.lang.NullPointerException
        at me.inao.discordbot.util.Logger.<init>(Logger.java:28)
        at me.inao.discordbot.Main.loadConfig(Main.java:65)
        at me.inao.discordbot.Main.starter(Main.java:46)
        at me.inao.discordbot.Main.main(Main.java:43)

App is Open-Sourced, so here is my full source: https://github.com/onemoreplays/bufferBot
Does this happen to someone else? Is that because of my bad programming habits or it's a bug somewhere else?

Thank you for any help.

Jakub.


来源: stackexchange

问:
Scala pattern matching Java enum value
I have my java enum such as: FOO("foo"), BAR("bar") ...
and I have a getValue() method to return the value "foo" and "bar" of the enum and this has to be in Java.

On the other hand, I have to match this in Scala:

```<code>result match {
  case "foo" =>
</code>```

I am trying to do:

```<code>result match {
  case Enum.FOO.getValue() =>
</code>```

I get this error:

```<code>method getValue is not a case class constructor, nor does it have an
unapply/unapplySeq method
</code>```

I'm not quite sure what is happening here since my getValue() method returns a String so why I can't use it for pattern matching? Thanks

答:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features. This library can nicely work with enums.</p>

```<code>   matches(myEnum).as(
      MyEnum.FOO,  () ->  System.out.println("FOO value");
      MyEnum.BAR,  () ->  System.out.println("BAR VALUE");
      Else.class,  () ->  System.out.println("Default value: " + data)
   );
</code>```

ContentLicense: CC BY-SA 3.0

Title: Scala pattern matching Java enum value

Body:
I have my java enum such as: FOO("foo"), BAR("bar") ...
and I have a getValue() method to return the value "foo" and "bar" of the enum and this has to be in Java.

On the other hand, I have to match this in Scala:

result match {
  case "foo" =>

I am trying to do:

result match {
  case Enum.FOO.getValue() =>

I get this error:

method getValue is not a case class constructor, nor does it have an
unapply/unapplySeq method

I'm not quite sure what is happening here since my getValue() method returns a String so why I can't use it for pattern matching? Thanks

Body:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features. This library can nicely work with enums.

   matches(myEnum).as(
      MyEnum.FOO,  () ->  System.out.println("FOO value");
      MyEnum.BAR,  () ->  System.out.println("BAR VALUE");
      Else.class,  () ->  System.out.println("Default value: " + data)
   );

ContentLicense: CC BY-SA 4.0


问:
Kotlin: Unchecked cast in my generic function
I'm trying to combine my two functions into one using generics.

```<code>fun <T> List<T>.toElementOrSize1(keySelector: (T) -> String): String {
    val key = keySelector(first())
    return if (all { keySelector(it) == key }) key else "size = $size"
}

fun <T> List<T>.toElementOrSize2(keySelector: (T) -> String?): String? {
    val key = keySelector(first())
    return if (all { keySelector(it) == key }) key else "size = $size"
}
</code>```

I could write this:

```<code>fun <T, K : String?> List<T>.toElementOrSize(keySelector: (T) -> K): K {
    val key = keySelector(first())
    return if (all { keySelector(it) == key }) {
        key
    } else {
        "size = $size" as K
    }
}
</code>```

This works, but  I've got an unchecked cast warning.

Why was this warning issued?
And how to avoid this warning?

Thanks.

答:
The compiler isn't sophisticated enough to see that the only possible types for K are String and String? (since String is final), so to the compiler, K could be some other subtype of String? and so casting your literal String could be unsafe. And since K is a generic type, the casting is unchecked due to type erasure.

There are a number of situations like this that turn up when working with generics. It doesn't mean you've necessarily done something wrong, only that the compiler doesn't know enough to be sure you didn't. You can use @Suppress("UNCHECKED_CAST") before the function or statement to remove the warning and acknowledge that you know that it's a safe cast. This doesn't mean you're doing something hacky or poorly designed. It's used several times in the standard library source code.

Body:
I'm trying to combine my two functions into one using generics.

fun <T> List<T>.toElementOrSize1(keySelector: (T) -> String): String {
    val key = keySelector(first())
    return if (all { keySelector(it) == key }) key else "size = $size"
}

fun <T> List<T>.toElementOrSize2(keySelector: (T) -> String?): String? {
    val key = keySelector(first())
    return if (all { keySelector(it) == key }) key else "size = $size"
}

I could write this:

fun <T, K : String?> List<T>.toElementOrSize(keySelector: (T) -> K): K {
    val key = keySelector(first())
    return if (all { keySelector(it) == key }) {
        key
    } else {
        "size = $size" as K
    }
}

This works, but  I've got an unchecked cast warning.

Why was this warning issued?
And how to avoid this warning?

Thanks.


问:
Vertically Assignment of Block in Page
I am learning DJANGO and while proceeding wanted to give nice look to some pages. I am currently new in programming (only 4 months coding) and mostly spent time with Python, could find time to properly learn front-end.

So my problem is I can`t center LOGIN block in the page. I am using Bootstrap4.5 and gave some Shadow to make object like floating. I now there were similar questions here with answers and tons of tutorial of centering elements either with custom CSS or Bootstrap Flex or Justify and I really tried almost everything I found with no result. Every time time position of Block is getting somewhere else but not center.

My Base HTML:

```<code><!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
          integrity="sha384-
          9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
          crossorigin="anonymous">

    <link rel="stylesheet" href="{% static 'css/base.css' %}">

    <title>Newspaper Project</title>
  </head>

  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
      <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse"
          data-target="#navbarCollapse" aria-controls="navbarCollapse"
          aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarCollapse">
        {% if user.is_authenticated %}
          <ul class="navbar-nav ml-auto">
            <li class="nav-item">
              <a class="nav-link dropdown-toggle" href="#" id="userMenu"
                data-toggle="dropdown" aria-haspopup="true"
                aria-expanded="false">
                {{ user.username }}
              </a>
              <div class="dropdown-menu dropdown-menu-right"
                aria-labelledby="userMenu">
                <a class="dropdown-item" href="{% url 'password_change'%}">Change
                                                                           password</a>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" href="{% url 'logout' %}">Log Out</a>
              </div>
            </li>
          </ul>
        {% else %}
          <form class="form-inline ml-auto">
            <a href="{% url 'login' %}" class="btn btn-outline-secondary">Log In</a>
            <a href="{% url 'users:signup' %}" class="btn btn-outline-info ml-2">Sign up</a>
          </form>
        {% endif %}
      </div>
    </nav>

<div class="container">
  {% block content %}

  {% endblock %}
</div>

<!-- JAVASCRIPT BOOTSTRAP -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
        integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

  </body>
</html>
</code>```

My Login HTML:

```<code>{% extends "base.html" %}

{% load crispy_forms_tags %}

{% block content %}

  {% if user.is_authenticated %}
    <h2>You are already logged in!</h2>
    <a href="{% url 'logout' %}">Log Out</a>
  {% else %}
      <form class="shadow-lg p-3 mb-5 bg-white rounded login" method="post">
        {% csrf_token %}
        {{ form|crispy }}
        <button class="btn btn-success" type="submit">Log In</button>
      </form>
  {% endif %}

{% endblock %}
</code>```

And attached image how the page is looking.
I really dont know what else I can try to center the login block. All I want is to center it below navbar in remaining space.

Thanks in advance!

答:
Try this, by setting the position to absolute you're positioning your form relative to the outer container, so you can tweak the percentage left and top as you wish.

.div {
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 1;
  width: 150px;
  height: 150px;
  margin: -75px 0 0 -75px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <div class="div">
    <h3> Hi, I'm just an example form </h3>
    <input><br>
    <input><br>
    <button>click me</button>

  </div>
</body></code>```

Title: Vertically Assignment of Block in Page

Body:
I am learning DJANGO and while proceeding wanted to give nice look to some pages. I am currently new in programming (only 4 months coding) and mostly spent time with Python, could find time to properly learn front-end.

So my problem is I can`t center LOGIN block in the page. I am using Bootstrap4.5 and gave some Shadow to make object like floating. I now there were similar questions here with answers and tons of tutorial of centering elements either with custom CSS or Bootstrap Flex or Justify and I really tried almost everything I found with no result. Every time time position of Block is getting somewhere else but not center.

My Base HTML:

<!DOCTYPE html>
{% load static %}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
          integrity="sha384-
          9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
          crossorigin="anonymous">

    <link rel="stylesheet" href="{% static 'css/base.css' %}">

    <title>Newspaper Project</title>

      Newspaper
      <button class="navbar-toggler" type="button" data-toggle="collapse"
          data-target="#navbarCollapse" aria-controls="navbarCollapse"
          aria-expanded="false" aria-label="Toggle navigation">

      </button>

        {% if user.is_authenticated %}

                {{ user.username }}

                Change
                                                                           password

                Log Out

        {% else %}
          <form class="form-inline ml-auto">
            Log In
            Sign up
          </form>
        {% endif %}

  {% block content %}

  {% endblock %}

My Login HTML:

{% extends "base.html" %}

{% load crispy_forms_tags %}

{% block content %}

  {% if user.is_authenticated %}

You are already logged in!

    Log Out
  {% else %}
      <form class="shadow-lg p-3 mb-5 bg-white rounded login" method="post">
        {% csrf_token %}
        {{ form|crispy }}
        <button class="btn btn-success" type="submit">Log In</button>
      </form>
  {% endif %}

{% endblock %}

And attached image how the page is looking.
I really dont know what else I can try to center the login block. All I want is to center it below navbar in remaining space.

Thanks in advance!

Body:
Try this, by setting the position to absolute you're positioning your form relative to the outer container, so you can tweak the percentage left and top as you wish.

.div {
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 1;
  width: 150px;
  height: 150px;
  margin: -75px 0 0 -75px;
}

<body>

  <div class="div">
    <h3> Hi, I'm just an example form </h3>
    <input><br>
    <input><br>
    <button>click me</button>

  </div>
</body>


问:
EditForm - How can I prevent submit on pressing enter key
I've found this article but I'm having a hard time to understand how can I prevent submit on "enter" key independently by any <input>

<EditForm Model="exampleModel" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText id="name" @bind-Value="exampleModel.Name" />
    <InputText id="name2" @bind-Value="exampleModel.Name2" />

    <button type="submit">Submit</button>
</EditForm>
```

<pre class="lang-cs prettyprint-override"><code>@code {
    private ExampleModel exampleModel = new ExampleModel();

    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }

    public class ExampleModel
    {
         [Required]
         [StringLength(10, ErrorMessage = "Name is too long.")]
         public string Name { get; set; }
         public string Name2 {get; set;}
    }
}
</code>```

Use Case

Enter key On HTML forms if you are filling out a text box and press the enter key it will submit the form, even if you haven't finished filling in the rest of the information. There are many websites which use this feature such as Google search box will submit when you press the enter key. This works because you only have one text box to fill out, but if there are more than one field to fill in you don't want the form to submit on the enter key.

答:
Leonardo Lurci, here's a complete solution implemented purely in C#, no JSInterop. As it turned out, Microsoft has already provided this feature, but they did not provide enough samples to demonstrate how to use it.

As it turned out, I cannot use the pair @onkeypress="@KeyHandler" and                             @onkeypress:preventDefault with the Forms components such as InputText, but applying these directives to Html tags is viable and works perfectly well. See for instance how I apply these directives to the "submit" button.

Consequently, I subclass the base class InputBase, this is the class from which the InputText components derive, overrides the default view rendering by adding an input element to which I can add the directives of the new feature.

TextBox.razor (this comes instead of InputText)

    @inherits InputBase<string>

    <input type="text" value="@CurrentValueAsString" id="Id" class="@CssClass"
       @onkeydown="KeyDownHandler" @onkeypress="KeyPressHandler"
                                                   @onkeypress:preventDefault/>

     @code{

    protected override bool TryParseValueFromString(string value, out string
                                      result, out string validationErrorMessage)
    {
        result = value;
        validationErrorMessage = null;
        return true;
    }

    void KeyDownHandler(KeyboardEventArgs args)
    {
        if (args.Key == "Backspace" && CurrentValueAsString.Length >=1)
        {
            CurrentValueAsString = CurrentValueAsString.Substring(0,
                                       CurrentValueAsString.Length - 1);
        }
    }

     void KeyPressHandler(KeyboardEventArgs args)
     {

        if (args.Key == "Enter")
        {
            return;
        }
        var key = (string)args.Key;
        CurrentValueAsString += key;
     }
    }
```
<p>Usage</p>
<pre class="lang-html prettyprint-override"><code>
    <p>Leave me a comment</p>

    <EditForm Model="Model" OnValidSubmit="HandleValidSubmit" >
    <DataAnnotationsValidator />

     <div class="form-group">
        <label for="name">Name: </label>
        <TextBox Id="name" Class="form-control" @bind-Value="@Model.Name" >
        </TextBox>
        <ValidationMessage For="@(() => Model.Name)" />

     </div>
     <div class="form-group">
        <label for="body">Text: </label>
        <InputTextArea Id="body" Class="form-control" @bind-Value="@Model.Text" >
        </InputTextArea>
        <ValidationMessage For="@(() => Model.Text)" />
     </div>
     <p>
        <button type="submit" @onkeypress="KeyHandler" @onkeypress:preventDefault>
            Submit
        </button>
     </p>
    </EditForm>

    @code
    {
        private Comment Model = new Comment();

        private void HandleValidSubmit()
        {
             Console.WriteLine("Submit...");
        }

        void KeyHandler(KeyboardEventArgs args)
        {
            if (args.Key == "Enter")
            {
               return;
             }
        }

        public class Comment
        {
            public string Name { get; set; } = "Jeff";
            public string Text { get; set; } = "I'm Jeff. I'm from Canada";
        }

    }
</code>```

Please, don't hesitate to ask any questions

Hope this helps...

Body:
I've found this article but I'm having a hard time to understand how can I prevent submit on "enter" key independently by any <input>

<EditForm Model="exampleModel" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText id="name" @bind-Value="exampleModel.Name" />
    <InputText id="name2" @bind-Value="exampleModel.Name2" />

    <button type="submit">Submit</button>
</EditForm>

@code {
    private ExampleModel exampleModel = new ExampleModel();

    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }

    public class ExampleModel
    {
         [Required]
         [StringLength(10, ErrorMessage = "Name is too long.")]
         public string Name { get; set; }
         public string Name2 {get; set;}
    }
}

Use Case

Enter key On HTML forms if you are filling out a text box and press the enter key it will submit the form, even if you haven't finished filling in the rest of the information. There are many websites which use this feature such as Google search box will submit when you press the enter key. This works because you only have one text box to fill out, but if there are more than one field to fill in you don't want the form to submit on the enter key.

Body:
Leonardo Lurci, here's a complete solution implemented purely in C#, no JSInterop. As it turned out, Microsoft has already provided this feature, but they did not provide enough samples to demonstrate how to use it.

As it turned out, I cannot use the pair @onkeypress="@KeyHandler" and                             @onkeypress:preventDefault with the Forms components such as InputText, but applying these directives to Html tags is viable and works perfectly well. See for instance how I apply these directives to the "submit" button.

Consequently, I subclass the base class InputBase, this is the class from which the InputText components derive, overrides the default view rendering by adding an input element to which I can add the directives of the new feature.

TextBox.razor (this comes instead of InputText)

    @inherits InputBase<string>

    <input type="text" value="@CurrentValueAsString" id="Id" class="@CssClass"
       @onkeydown="KeyDownHandler" @onkeypress="KeyPressHandler"
                                                   @onkeypress:preventDefault/>

     @code{

    protected override bool TryParseValueFromString(string value, out string
                                      result, out string validationErrorMessage)
    {
        result = value;
        validationErrorMessage = null;
        return true;
    }

    void KeyDownHandler(KeyboardEventArgs args)
    {
        if (args.Key == "Backspace" && CurrentValueAsString.Length >=1)
        {
            CurrentValueAsString = CurrentValueAsString.Substring(0,
                                       CurrentValueAsString.Length - 1);
        }
    }

     void KeyPressHandler(KeyboardEventArgs args)
     {

        if (args.Key == "Enter")
        {
            return;
        }
        var key = (string)args.Key;
        CurrentValueAsString += key;
     }
    }

Usage

    <p>Leave me a comment</p>

    <EditForm Model="Model" OnValidSubmit="HandleValidSubmit" >
    <DataAnnotationsValidator />

     <div class="form-group">
        <label for="name">Name: </label>
        <TextBox Id="name" Class="form-control" @bind-Value="@Model.Name" >
        </TextBox>
        <ValidationMessage For="@(() => Model.Name)" />

     </div>
     <div class="form-group">
        <label for="body">Text: </label>
        <InputTextArea Id="body" Class="form-control" @bind-Value="@Model.Text" >
        </InputTextArea>
        <ValidationMessage For="@(() => Model.Text)" />
     </div>
     <p>
        <button type="submit" @onkeypress="KeyHandler" @onkeypress:preventDefault>
            Submit
        </button>
     </p>
    </EditForm>

    @code
    {
        private Comment Model = new Comment();

        private void HandleValidSubmit()
        {
             Console.WriteLine("Submit...");
        }

        void KeyHandler(KeyboardEventArgs args)
        {
            if (args.Key == "Enter")
            {
               return;
             }
        }

        public class Comment
        {
            public string Name { get; set; } = "Jeff";
            public string Text { get; set; } = "I'm Jeff. I'm from Canada";
        }

    }

Please, don't hesitate to ask any questions

Hope this helps...


问:
Data too long for column when creating user
By going to

```<code>url(r'api/users/', views.MyUserCreate.as_view(), name='user-create'),
</code>```

one can see DRF Browsable API

which uses MyUserCreate (in views.py)

```<code>class MyUserCreate(APIView):
    """
    Creates the user.
    """

    def post(self, request, format='json'):
        serializer = MyUserSerializer(data=request.data)
        if serializer.is_valid():
            MyUser.objects.create_user(
                        serializer.username,
                        serializer.password
            )
            if user:
                return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
</code>```

Note that it references MyUserSerializer (in serializers.py)

```<code>class MyUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
            required=True,
            validators=[UniqueValidator(queryset=MyUser.objects.all())],
            min_length=5,
            max_length=20
            ),
    password = make_password(serializers.CharField(
            write_only=True,
            required=True,
            max_length=256
            ))

    class Meta:
        model = MyUser
        fields = ('username', 'password')

    def create_user(self, validated_data):
        password = make_password(validated_data['password'])
        user = MyUser.objects.create_user(validated_data['username'], password)
        return user
</code>```

and MyUser (in models.py)

```<code>class MyUserManager(BaseUserManager):
    def create_user(self, username, password):
        user = self.model(
            username=username
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    objects = MyUserManager()
    class Meta:
        # managed = False
        db_table = 'user_entity'

    user_id = models.AutoField(primary_key=True, db_column='userId')
    username = models.CharField(db_column='username', unique=True, max_length=20)
    password = models.CharField(db_column='userPassword', max_length=256)

    USERNAME_FIELD = 'username'

    def __str__(self):
        return str(self.user_id) + " (%s)" % str(self.username)
</code>```

When I post to create a user

```<code>{
    "username": "tiagoperes",
    "password": "test"
}
</code>```

I get

django.db.utils.DataError: (1406, "Data too long for column 'username'
  at row 1")

Following information from other users, checked if the column is UTF8

and doesn't make sense to use TextField instead of CharField here.

答:
You are passing serializer.username to create function, which is not the data you are passed via POST request, hence the error.

Change your method create_user(...), to create(...) in MyUserSerializer so that, DRF will handle the function when you call the .save() method from view. (which is the DRF way)

Change your view as,

```<code>class MyUserCreate(APIView):

    def post(self, request, format='json'):
        serializer = MyUserSerializer(data=request.data)
        <b>if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)</b>
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</code>```

as well as your serializer

```<code>class MyUserSerializer(serializers.ModelSerializer):
    # rest of your code

    def <b>create</b>(self, validated_data):
        password = make_password(validated_data['password'])
        user = MyUser.objects.create_user(validated_data['username'], password)
        return user</code>```

Body:
By going to

url(r'api/users/', views.MyUserCreate.as_view(), name='user-create'),

one can see DRF Browsable API

which uses MyUserCreate (in views.py)

class MyUserCreate(APIView):
    """
    Creates the user.
    """

    def post(self, request, format='json'):
        serializer = MyUserSerializer(data=request.data)
        if serializer.is_valid():
            MyUser.objects.create_user(
                        serializer.username,
                        serializer.password
            )
            if user:
                return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

Note that it references MyUserSerializer (in serializers.py)

class MyUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
            required=True,
            validators=[UniqueValidator(queryset=MyUser.objects.all())],
            min_length=5,
            max_length=20
            ),
    password = make_password(serializers.CharField(
            write_only=True,
            required=True,
            max_length=256
            ))

    class Meta:
        model = MyUser
        fields = ('username', 'password')

    def create_user(self, validated_data):
        password = make_password(validated_data['password'])
        user = MyUser.objects.create_user(validated_data['username'], password)
        return user

and MyUser (in models.py)

class MyUserManager(BaseUserManager):
    def create_user(self, username, password):
        user = self.model(
            username=username
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    objects = MyUserManager()
    class Meta:
        # managed = False
        db_table = 'user_entity'

    user_id = models.AutoField(primary_key=True, db_column='userId')
    username = models.CharField(db_column='username', unique=True, max_length=20)
    password = models.CharField(db_column='userPassword', max_length=256)

    USERNAME_FIELD = 'username'

    def __str__(self):
        return str(self.user_id) + " (%s)" % str(self.username)

When I post to create a user

{
    "username": "tiagoperes",
    "password": "test"
}

I get

django.db.utils.DataError: (1406, "Data too long for column 'username'
  at row 1")

Following information from other users, checked if the column is UTF8

and doesn't make sense to use TextField instead of CharField here.

Body:
You are passing serializer.username to create function, which is not the data you are passed via POST request, hence the error.

Change your method create_user(...), to create(...) in MyUserSerializer so that, DRF will handle the function when you call the .save() method from view. (which is the DRF way)

Change your view as,

class MyUserCreate(APIView):

    def post(self, request, format='json'):
        serializer = MyUserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

as well as your serializer

class MyUserSerializer(serializers.ModelSerializer):
    # rest of your code

    def create(self, validated_data):
        password = make_password(validated_data['password'])
        user = MyUser.objects.create_user(validated_data['username'], password)
        return user


问:
Angular Project Structure with separate package.json files
I saw this Project Structure in Angular with Node.js as backend, where the Angular node modules and package.json were in the "app" folder, while the node.js' node modules and package.json were in the root of the project. (watch picture)

How do i get the requested outcome?

答:
Create the root directory.

From within the directory, run 'npm init'

To create the server file, run 'touch server.js'

Then, to create the angular app, from inside the root directory, run 'ng new app-name'


问:
How to deploy npm project to gh-pages
I'm trying to deploy a website to gh-pages using npm. I'm using blain HTML and CSS and asynchronous javascript. I haven't used any SPA framework (react or angular).
I'm currently using lite server for development purposes and gh-pages package.

I'm trying to deploy the src folder using the following command
npm run deploy

it fails because the build script is not specified.
my question is what should I write in the build script?

when I try to run npm run deploy it displays the following error

```<code>
'src' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! AmrAhmed@1.0.0 build: `src`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the AmrAhmed@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Amr\AppData\Roaming\npm-cache\_logs\2020-05-30T11_30_29_824Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! AmrAhmed@1.0.0 predeploy: `npm run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the AmrAhmed@1.0.0 predeploy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Amr\AppData\Roaming\npm-cache\_logs\2020-05-30T11_30_29_869Z-debug.log
</code>```

in similar projects using react, the build script has the following react-scripts build

this is my package.json file

{
    "name": "AmrAhmed",
    "version": "1.0.0",
    "description": "",
    "main": "truffle.js",
    "directories": {
        "test": "test"
    },
    "scripts": {
        "dev": "lite-server",
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "src",
        "predeploy": "npm run build",
        "deploy": "gh-pages -d src"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "gh-pages": "^3.0.0",
        "lite-server": "^2.5.4"
    }
}
```

election folder content

src folder content

答:
I found out that you don't need the build script or the pre-deploy script. they are unnecessary to be used, since my website is static, I can navigate directly to the build folder and it will work fine.

I have modified the config.json file to be as in the following

{
    "name": "AmrAhmed",
    "version": "1.0.0",
    "description": "",
    "main": "truffle.js",
    "directories": {
        "test": "test"
    },
    "scripts": {
        "dev": "lite-server",
        "test": "echo \"Error: no test specified\" && exit 1",
        "deploy": "gh-pages -d src"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "gh-pages": "^3.0.0",
        "lite-server": "^2.5.4"
    }
}
```

run the command
npm run build

and it will be deployed to Github pages.

Title: How to deploy npm project to gh-pages

Body:
I'm trying to deploy a website to gh-pages using npm. I'm using blain HTML and CSS and asynchronous javascript. I haven't used any SPA framework (react or angular).
I'm currently using lite server for development purposes and gh-pages package.

I'm trying to deploy the src folder using the following command
npm run deploy

it fails because the build script is not specified.
my question is what should I write in the build script?

when I try to run npm run deploy it displays the following error

'src' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! AmrAhmed@1.0.0 build: `src`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the AmrAhmed@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Amr\AppData\Roaming\npm-cache\_logs\2020-05-30T11_30_29_824Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! AmrAhmed@1.0.0 predeploy: `npm run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the AmrAhmed@1.0.0 predeploy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Amr\AppData\Roaming\npm-cache\_logs\2020-05-30T11_30_29_869Z-debug.log

in similar projects using react, the build script has the following react-scripts build

this is my package.json file

{
    "name": "AmrAhmed",
    "version": "1.0.0",
    "description": "",
    "main": "truffle.js",
    "directories": {
        "test": "test"
    },
    "scripts": {
        "dev": "lite-server",
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "src",
        "predeploy": "npm run build",
        "deploy": "gh-pages -d src"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "gh-pages": "^3.0.0",
        "lite-server": "^2.5.4"
    }
}

election folder content

src folder content

Body:
I found out that you don't need the build script or the pre-deploy script. they are unnecessary to be used, since my website is static, I can navigate directly to the build folder and it will work fine.

I have modified the config.json file to be as in the following

{
    "name": "AmrAhmed",
    "version": "1.0.0",
    "description": "",
    "main": "truffle.js",
    "directories": {
        "test": "test"
    },
    "scripts": {
        "dev": "lite-server",
        "test": "echo \"Error: no test specified\" && exit 1",
        "deploy": "gh-pages -d src"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "gh-pages": "^3.0.0",
        "lite-server": "^2.5.4"
    }
}

run the command
npm run build

and it will be deployed to Github pages.


问:
Certificates from different sql servers version
I have a service broker configured in two different databases on two different servers. The problem is that I can't receive message because I have the problem:

 Connection handshake failed. The login 'public' does not have CONNECT permission on the endpoint. State 84.
I have endpoints with certyficates, I gave permission to connect to a specific user who has a certificate(I did it on two servers because it is always on availability group), while looking for a problem I noticed that the certificate from the initiating server is different from the certificate from the target server:

-initiator - signature algorithm: sha1RSA, key length: 1024 (sql ver. 11.0.7 ...)

-target - signature algorithm: sha256RSA, key length: 2048 (sql ver. 15.0.4 ...)

When I grant permission:

grant connect on endpoint :: BrokerEndPoint to PUBLIC

Servers communicate but this does not solve the problem.
Can different types of certificates be a problem?

答: Ty for your time, I checked the connection and data again and found no problem anywhere. As I was bothered by the fact that maybe it was a problem that I wrote about so for the test I created another connection but this time on the server with SHA256 certificate and as I thought it is a problem here. To confirm my theory, I replaced the certificate on the initial server about which I wrote earlier to SHA256 (I deleted and re-created the endpoint with this certificate) and on the target server I replaced this certificate and the problem was solved. So it's like I thought certificates must have the same type of encoding.</p>


问:
Terraform is not recognized as internal or external command in jenkins
I installed jenkins in local windows machine. Then i installed terraform plug in and did the config changed in global tool configuration in jenkins but when i run the jenkin pipeline i get 'terraform' is not recognized as an internal or external command,
operable program or batch file.

Code :

```<code>pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
            bat 'terraform --version'
            echo 'Hello World'
         }
      }
   }
}
</code>```

can you help me what i am doing wrong in this?

```<code>Started by user admin
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in C:\Program Files (x86)\Jenkins\workspace\actimize2
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Hello)
[Pipeline] script
[Pipeline] {
[Pipeline] tool
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: No tool named terraform found
Finished: FAILURE
</code>```

terraform config :

答:
You'll need to get the Terraform home using a tool command and then add it to the Path environment variable so that the shell interpreterinvoked by bat can find the terraform command:

```<code>def tfHome = tool name: 'Terraform', type: 'com.cloudbees.jenkins.plugins.customtools.CustomTool'
env.Path = "${tfHome};${env.Path}"
</code>```

In your pipeline, this would look like:

```<code>pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
            def tfHome = tool name: 'Terraform', type: 'com.cloudbees.jenkins.plugins.customtools.CustomTool'
            env.Path = "${tfHome};${env.Path}"
            bat 'terraform --version'
            echo 'Hello World'
         }
      }
   }
}
</code>```

You can also use tool directly in the bat command (this is what I used to do when I was using Jenkins regularly):

```<code>pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
            bat "${tool name: 'Terraform', type: 'com.cloudbees.jenkins.plugins.customtools.CustomTool'}\terraform --version"
            echo 'Hello World'
         }
      }
   }
}
</code>```

You can see a worked example in this Automating Terraform Projects with Jenkins article.

Body:
I installed jenkins in local windows machine. Then i installed terraform plug in and did the config changed in global tool configuration in jenkins but when i run the jenkin pipeline i get 'terraform' is not recognized as an internal or external command,
operable program or batch file.

Code :

pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
            bat 'terraform --version'
            echo 'Hello World'
         }
      }
   }
}

can you help me what i am doing wrong in this?

Started by user admin
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in C:\Program Files (x86)\Jenkins\workspace\actimize2
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Hello)
[Pipeline] script
[Pipeline] {
[Pipeline] tool
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: No tool named terraform found
Finished: FAILURE

terraform config :

Body:
You'll need to get the Terraform home using a tool command and then add it to the Path environment variable so that the shell interpreterinvoked by bat can find the terraform command:

def tfHome = tool name: 'Terraform', type: 'com.cloudbees.jenkins.plugins.customtools.CustomTool'
env.Path = "${tfHome};${env.Path}"

In your pipeline, this would look like:

pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
            def tfHome = tool name: 'Terraform', type: 'com.cloudbees.jenkins.plugins.customtools.CustomTool'
            env.Path = "${tfHome};${env.Path}"
            bat 'terraform --version'
            echo 'Hello World'
         }
      }
   }
}

You can also use tool directly in the bat command (this is what I used to do when I was using Jenkins regularly):

pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
            bat "${tool name: 'Terraform', type: 'com.cloudbees.jenkins.plugins.customtools.CustomTool'}\terraform --version"
            echo 'Hello World'
         }
      }
   }
}

You can see a worked example in this Automating Terraform Projects with Jenkins article.


问:
OnVScroll : invoked from CSpinButtonCtrl or Vertical ScrollBar?
I have a derived MFC CFormView class (CMyFormView) and I must implement my own OnVScroll function.

My CMyFormView is used for several dialog box resources, mainly, to re-implement the OnCtlColor() function. Some dialogs contain a CSpinButtonCtrl control.

My problem:

When the OnVScroll function is invoked, I am unable to know if the Windows message comes from a CSpinButtonCtrl or from the scrollbar.

```<code>void CMyFormView :: OnVScroll (UINT nSBCode, UINT nPos, CScrollBar * pScrollBar)
{
// message comes from CSpinButtonCtrl or VscrollBare ?
}
</code>```

I cannot use the CSpinButtonCtrl IDs (dlgitem) of the controls because they are very numerous.

Question:

How to know if the message comes from a CSpinButtonCtrl or the scrollbar?

Environment details:

Windows 7

Visual studio 2010

MFC

答:
If the OnVScroll handler is called via actions in a window's (framework-provided) scrollbar, then the pScrollBar parameter will be NULL; if it is from a control, then it will not be NULL. From the CWnd Documentation:

pScrollBar
 If the scroll message came from a scroll-bar control, contains a pointer to the control. If the user clicked a
  window's scroll bar, this parameter is NULL. The pointer may be
  temporary and should not be stored for later use.

So, you can simply check for a NULL value:

void CMyFormView :: OnVScroll (UINT nSBCode, UINT nPos, CScrollBar * pScrollBar)
{
    if (!pScrollBar) {
        // From window's scrollbar...
    }
    else {
        // From a control...
    }
}
```

Body:
I have a derived MFC CFormView class (CMyFormView) and I must implement my own OnVScroll function.

My CMyFormView is used for several dialog box resources, mainly, to re-implement the OnCtlColor() function. Some dialogs contain a CSpinButtonCtrl control.

My problem:

When the OnVScroll function is invoked, I am unable to know if the Windows message comes from a CSpinButtonCtrl or from the scrollbar.

void CMyFormView :: OnVScroll (UINT nSBCode, UINT nPos, CScrollBar * pScrollBar)
{
// message comes from CSpinButtonCtrl or VscrollBare ?
}

I cannot use the CSpinButtonCtrl IDs (dlgitem) of the controls because they are very numerous.

Question:

How to know if the message comes from a CSpinButtonCtrl or the scrollbar?

Environment details:

Windows 7

Visual studio 2010

MFC


问:
How can I deploy a telegram bot from intellij to heroku? I write the code using Java from a maven project
I started coding a telegram bot using intellij idea. I wanted to deploy the bot using IntelliJ to my Heroku app. I created a heroku app and I wanted to deploy it from intelliJ and I tried to follow the instructionFrom Here, but it doesn't work for me. can You help doing this considering I'm an amateur programmer. Thanks in advance  </p>

答:
There are several options to deploy an Heroku application, if you are looking for something simple I would use GitHub as code repository then link it from Heroku.

Once this is done the deployment it is just a push of a button or you can also enable the automated option (each push to GitHub will deploy to Heroku).

If you develop a Python app you can use the very powerful Python Telegram Bot, you can follow the steps in their documentation to deploy a Python application, in a nutshell:

add requirements.txt to the root of your repository

define Procfile in the root directory of your application

bind the port provided by Heroku with the env variable $PORT

If you develop a Java application the concepts are similar, follow Deploy Java Apps on Heroku, in a nutshell:

use maven-dependency-plugin to create an Uber jar

define Procfile in the root directory of your applicatio

bind the port provided by Heroku with the env variable $PORT


问:
flex preloader not working with # in the url (deep linking)
I can't get flash preloaders to work when there is a a # in the url of my page (even without any deep linking libraries or logic).  I am using flex 3.3.  Flash plugins 9 and 10, all browsers.

There is this bug regarding # in the url preventing preloaders from working:
http://bugs.adobe.com/jira/browse/SDK-14162

However, somehow, someone, somewhere has ways around this.  Here are somewhat working examples (remember to clear your cache to ensure you see the preloader awesomeness):

http://www.adobecards.com/index.html#wtf

http://www.escriba.es/base_en.html#wtf

http://www.sonypictures.com/movies/onceuponatimeinmexico/site/mexico.html#wtf

http://instinct.ru/flash.html#wtf

http://www.alternativedesign.tv/plant5.html#wtf

However, these do not work (no preloader at all or momentarily stuck on 100%):

http://www.flashmagazine.com/articlefiles/preloader_finished.html#wtf

http://www.mariaclaudiacortes.com/colors/Colors.html#wtf

http://whoswestudios.com/flashsite.html#wtf

http://www.iotashan.com/examples/NotSoCustomPreloader/index.html#wtf

So, what is going on here?  I suspect the flex framework.

Anyone know where to look in the flex code?  Or is this bug deeper than anyone but adobe can fix?

答:
I believe the problem you are having is that you have your assets loading into the same frame as your preloader assets and code.  Flash doesn't display a frame until it has been loaded to its entirety, cause your preloader not to be seen during load, and then covered up by the new asset after.

As a flex developer you do not have a timeline, so this is why it is important to use a small "container" as you call it or as loader movie.  This movie is to have a tiny foot print so that it is available asap.  Upon completion of load, the container can then call the main movie into itself, tracking the incoming data with the ProgressEvent.

It is hard to know exactly what the issue is from what you have said, but this is a common problem.  Fonts, and any other embedded items either need to be embedded on frame 2 or laterm which I believe you can only do with the flash IDE, or you require the extra loader swf, lightweight and quick to load!

I have successfully deeplinked the following with preloaders

http://www.madagascargame.com

http://www.kungfupandagame.com

OwnerDisplayName: jedierikb

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: jedierikb

OwnerDisplayName: Brian Hodge


问:
Is it okay to use functions to stay organized in C?
I'm a relatively new C programmer, and I've noticed that many conventions from other higher-level OOP languages don't exactly hold true on C.

Is it okay to use short functions to have your coding stay organized (even though it will likely be called only once)? An example of this would be 10-15 lines in something like void init_file(void), then calling it first in main().

答:
If I can take the liberty to do some quoting from Code Complete:

(These reason details have been abbreviated and in spots paraphrased, for the full explanation see the complete text.)

Valid Reasons to Create a Routine

Note the reasons overlap and are not intended to be independent of each other.

Reduce complexity - The single most important reason to create a routine is to reduce a program's complexity (hide away details so you don't need to think about them).

Introduce an intermediate, understandable abstraction - Putting a section of code int o a well-named routine is one of the best ways to document its purpose.

Avoid duplicate code - The most popular reason for creating a routine. Saves space and is easier to maintain (only have to check and/or modify one place).

Hide sequences - It's a good idea to hide the order in which events happen to be processed.

Hide pointer operations - Pointer operations tend to be hard to read and error prone. Isolating them into routines shifts focus to the intent of the operation instead of the mechanics of pointer manipulation.

Improve portability - Use routines to isolate nonportable capabilities.

Simplify complicated boolean tests - Putting complicated boolean tests into a function makes the code more readable because the details of the test are out of the way and a descriptive function name summarizes the purpose of the tests.

Improve performance - You can optimize the code in one place instead of several.

To ensure all routines are small? - No. With so many good reasons for putting code into a routine, this one is unnecessary.  (This is the one thrown into the list to make sure you are paying attention!)

And one final quote from the text (Chapter 7: High-Quality Routines)

One of the strongest mental blocks to
  creating effective routines is a
  reluctance to create a simple routine
  for a simple purpose. Constructing a
  whole routine to contain two or three
  lines of code might seem like
  overkill, but experience shows how
  helpful a good small routine can be.


问:
100 equals to1 minute in SQL
My Database:

Database

When I need End Time to be +10secs from now I execute:

```<code>INSERT INTO `record` (`End_Time`) VALUES (now() + 10);
</code>```

Result:

Result 1

When I need End Time to be +10 min from now I execute:

```<code>INSERT INTO `record` (`End_Time`) VALUES (now() + 600);
</code>```

Result:

Result 2

It added only 6 mins from now and not 10!

Does this mean as per SQL 100 seconds equals to 1 minute? (If yes, this will make lots of confusion)

Result:

答:
You are using the wrong syntax.  You want to use interval:

```<code>VALUES (now() + interval 10 second)
</code>```

MySQL gets a bit confused about +.  Without interval it treats the values as big integers, in the format YYYYMMDDHHMMSS -- so you get the results you are seeing.  With interval it knows that you want + to add date/time values.

You could also use date_add().

Title: 100 equals to1 minute in SQL

Body:
My Database:

Database

When I need End Time to be +10secs from now I execute:

INSERT INTO `record` (`End_Time`) VALUES (now() + 10);

Result:

Result 1

When I need End Time to be +10 min from now I execute:

INSERT INTO `record` (`End_Time`) VALUES (now() + 600);

Result:

Result 2

It added only 6 mins from now and not 10!

Does this mean as per SQL 100 seconds equals to 1 minute? (If yes, this will make lots of confusion)

Result:

Body:
You are using the wrong syntax.  You want to use interval:

VALUES (now() + interval 10 second)

MySQL gets a bit confused about +.  Without interval it treats the values as big integers, in the format YYYYMMDDHHMMSS -- so you get the results you are seeing.  With interval it knows that you want + to add date/time values.

You could also use date_add().


问:
Virtual Environment for Python on mac error with Google API Client?
I created a virtual environment on my Desktop called project_env. I then installed the Google API Python Client from github (https://github.com/googleapis/google-api-python-client). Then created a Python file called youtube.py with the following code. When I run the file I get "ImportError no module googleapiclient"

```<code>  from googleapiclient.discovery import build

  api_key = "My Key"

  youtube = build('youtube', 'v3', developerKeys=api_key)

  request = youtube.channels().list(
   part='statistics',
  forUsername='livelifetothefull'
  )

 response = request.execute()
  print(response)
</code>```

I'm very new to this, so any help would be much appreciated.

答:
It would have been great if you had provided details on how you are running it and what version of Python you are using. Without that, I have provided solutions that applies in a general context.

You may need to add your venv to your path so that it can recognize the site-packages. See here on how you can do that.

It may also mean that the interpreter may not be resolving to the correct venv. For example, if you running through cmd line try running it with python3 if you doing with python or vice-versa.

Change of library issue, see here on that.

Body:
I created a virtual environment on my Desktop called project_env. I then installed the Google API Python Client from github (https://github.com/googleapis/google-api-python-client). Then created a Python file called youtube.py with the following code. When I run the file I get "ImportError no module googleapiclient"

  from googleapiclient.discovery import build

  api_key = "My Key"

  youtube = build('youtube', 'v3', developerKeys=api_key)

  request = youtube.channels().list(
   part='statistics',
  forUsername='livelifetothefull'
  )

 response = request.execute()
  print(response)

I'm very new to this, so any help would be much appreciated.


问:
Remove consecutive uppercase words from string
I'm having a long string where I would like to remove consecutive words with uppercase (2+ in a row) and if a punctation follows the last uppercase word, that as well.
But at the same time I would like to keep single uppercase words and uppercase words that are part of a "mixed" word (see reprex).

I struggle to implement the consecutive word group in reprex.

string <- "Lorem ipsum DOLOR SIT AMET? consectetuer adipiscing elit. Morbi gravida libero NEC velit. Morbi scelerisque luctus velit. ETIAM-123 dui sem, fermentum vitae, SAGITTIS ID? malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam IN LOREM SIT amet leo accumsan"

#remove all consecutive UPPERCASE words including punctation (--> DOLOR SIT AMET?), but not single uppercase words (--> NEC) or "mixed" words with uppercase and digits (--> ETIAM-123)
#this doesn't work:
string %>%
  stringr::str_remove_all("\\b[:upper:]+\\b")
#> [1] "Lorem ipsum   ? consectetuer adipiscing elit. Morbi gravida libero  velit. Morbi scelerisque luctus velit. -123 dui sem, fermentum vitae,  ? malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam    amet leo accumsan"
```

Created on 2020-05-30 by the reprex package (v0.3.0)

Any hints are appreciated :)

答:
Perhaps this?

stringr::str_remove_all(string, "([[:upper:]]+ )+[[:upper:]]+( |[:punct:])*")
#> [1] "Lorem ipsum consectetuer adipiscing elit. Morbi gravida libero NEC velit. Morbi scelerisque luctus velit. ETIAM-123 dui sem, fermentum vitae, malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam amet leo accumsan"
```

Created on 2020-05-30 by the reprex package (v0.3.0)

Body:
I'm having a long string where I would like to remove consecutive words with uppercase (2+ in a row) and if a punctation follows the last uppercase word, that as well.
But at the same time I would like to keep single uppercase words and uppercase words that are part of a "mixed" word (see reprex).

I struggle to implement the consecutive word group in reprex.

string <- "Lorem ipsum DOLOR SIT AMET? consectetuer adipiscing elit. Morbi gravida libero NEC velit. Morbi scelerisque luctus velit. ETIAM-123 dui sem, fermentum vitae, SAGITTIS ID? malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam IN LOREM SIT amet leo accumsan"

#remove all consecutive UPPERCASE words including punctation (--> DOLOR SIT AMET?), but not single uppercase words (--> NEC) or "mixed" words with uppercase and digits (--> ETIAM-123)
#this doesn't work:
string %>%
  stringr::str_remove_all("\\b[:upper:]+\\b")
#> [1] "Lorem ipsum   ? consectetuer adipiscing elit. Morbi gravida libero  velit. Morbi scelerisque luctus velit. -123 dui sem, fermentum vitae,  ? malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam    amet leo accumsan"

Created on 2020-05-30 by the reprex package (v0.3.0)

Any hints are appreciated :)

Body:
Perhaps this?

stringr::str_remove_all(string, "([[:upper:]]+ )+[[:upper:]]+( |[:punct:])*")
#> [1] "Lorem ipsum consectetuer adipiscing elit. Morbi gravida libero NEC velit. Morbi scelerisque luctus velit. ETIAM-123 dui sem, fermentum vitae, malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam amet leo accumsan"

Created on 2020-05-30 by the reprex package (v0.3.0)


问:
Populate DefaultTableModel from test file
I have this text file:

```<code>A
B
3.00

A
B
3.00
</code>```

and my view is:

I want to match each row with each column(first_row-first_column,second_row-second_column, etc..) Where have I made a mistake?
My code is as follows:

```<code>    BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String title = "";
        String author = "";
        String price = "";
        try {
            while ((line  = infile.readLine()) != null) {
                ++counter;

                if (counter == 1) {
                    title = line;
                } else if (counter == 2) {
                    author = line;
                } else if (counter == 3) {
                    price = line;
                    SimpleBook sb = new SimpleBook(title, author, price);
                    bookList.add(sb);
                    counter = 0;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
</code>```

答:
you can do this as there is an blank line in your input file  .</p>

```<code>BufferedReader infile = new BufferedReader(reader);
    String line = "";
    int counter = 0;
    String title = "";
    String author = "";
    String price = "";
    try {
        while ((line  = infile.readLine()) != null) {
            if(line.isEmpty())
                  continue;

            ++counter;

            if (counter == 1) {
                title = line;
            } else if (counter == 2) {
                author = line;
            } else if (counter == 3) {
                price = line;
                SimpleBook sb = new SimpleBook(title, author, price);
                bookList.add(sb);
                counter = 0;
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

Body:
I have this text file:

A
B
3.00

A
B
3.00

and my view is:

I want to match each row with each column(first_row-first_column,second_row-second_column, etc..) Where have I made a mistake?
My code is as follows:

    BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String title = "";
        String author = "";
        String price = "";
        try {
            while ((line  = infile.readLine()) != null) {
                ++counter;

                if (counter == 1) {
                    title = line;
                } else if (counter == 2) {
                    author = line;
                } else if (counter == 3) {
                    price = line;
                    SimpleBook sb = new SimpleBook(title, author, price);
                    bookList.add(sb);
                    counter = 0;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Body:
you can do this as there is an blank line in your input file  .

BufferedReader infile = new BufferedReader(reader);
    String line = "";
    int counter = 0;
    String title = "";
    String author = "";
    String price = "";
    try {
        while ((line  = infile.readLine()) != null) {
            if(line.isEmpty())
                  continue;

            ++counter;

            if (counter == 1) {
                title = line;
            } else if (counter == 2) {
                author = line;
            } else if (counter == 3) {
                price = line;
                SimpleBook sb = new SimpleBook(title, author, price);
                bookList.add(sb);
                counter = 0;
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
    }


问:
Send email notification from Jenkins throwing error
I am trying to send email to users from Jenkins.

Below is how my configuration looks alike.

Without SSL

With SSL

When enabling the SSL option, I am getting the below error

```<code>javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted
</code>```

While I am sure that credentials are valid.

While with the same credentials & without SSL if I try throws the error.

```<code>javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
</code>```

How do I add my Gmail account to send email?

Thanks!

答:
You need to allow less secure apps, you can do it by click below link

```<code>https://www.google.com/settings/security/lesssecureapps
</code>```

also, try this one

```<code>https://accounts.google.com/DisplayUnlockCaptcha
</code>```

if it still not works try changing the password for Gmail.

ABove is tried and tested and it worked for me.

Body:
I am trying to send email to users from Jenkins.

Below is how my configuration looks alike.

Without SSL

With SSL

When enabling the SSL option, I am getting the below error

javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted

While I am sure that credentials are valid.

While with the same credentials & without SSL if I try throws the error.

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

How do I add my Gmail account to send email?

Thanks!

Body:
You need to allow less secure apps, you can do it by click below link

https://www.google.com/settings/security/lesssecureapps

also, try this one

https://accounts.google.com/DisplayUnlockCaptcha

if it still not works try changing the password for Gmail.

ABove is tried and tested and it worked for me.


问:
Binary serialization protocol
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

```<code>class Person
{
   int age;
   string name;
};
</code>```

Java class

```<code>class Person
{
   int age;
   String name;
}
</code>```

C++ encoding

```<code>Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);
</code>```

Java decoding

```<code>byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);
</code>```

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.

答: Sounds like you want Protobufs: http://code.google.com/apis/protocolbuffers/docs/tutorials.html</p>

Title: Binary serialization protocol

Body:
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

class Person
{
   int age;
   string name;
};

Java class

class Person
{
   int age;
   String name;
}

C++ encoding

Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);

Java decoding

byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.


问:
Sublime Text Does Not Let Me Save My Files
How do I fix this on Mac?

Unable to save /test.py Error: Read-only file system

答:
Once you make your document, go to File and click Save (or just press cmd+n).

Write the title of your document.

Right under the name there should be a little box that says Macintosh. You can click on it and change it to whatever file you prefer.


问:
Extending FrozenSet from typing
I'm probably doing something dumb here. For those of you who want to copy and paste, make sure that you:

```<code>from typing import *
</code>```

I'm using Python 3.7.4.

This:

```<code>class S(FrozenSet[str]):
    def __init__(self, strs: Iterable[str], name: str):
            super().__init__(strs)
            self.name = name

S(['a'], 'a')
</code>```

raises an error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: S expected at most 1 arguments, got 2
</code>```

, but this:

```<code>class S(Set[str]):
    def __init__(self, strs: Iterable[str], name: str):
            super().__init__(strs)
            self.name = name

S(['a'], 'a')
</code>```

outputs just fine:

```<code>S({'a'})
</code>```

I want the extra functionality of a set, but I don't want my users to change it.

EDIT: I know I could just use composition over inheritance, but it would be nice if I could make this work as well.

答:
As it's a frozenset, once created, you can't modify its content.

Therefore, I think you should override __new__:

class S(FrozenSet[str]):
    def __new__(cls, strs: Iterable[str], name: str):
        return super(S, cls).__new__(cls, strs)

    def __init__(self, strs: Iterable[str], name: str):
        self.name = name
```

Title: Extending FrozenSet from typing

Body:
I'm probably doing something dumb here. For those of you who want to copy and paste, make sure that you:

from typing import *

I'm using Python 3.7.4.

This:

class S(FrozenSet[str]):
    def __init__(self, strs: Iterable[str], name: str):
            super().__init__(strs)
            self.name = name

S(['a'], 'a')

raises an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: S expected at most 1 arguments, got 2

, but this:

class S(Set[str]):
    def __init__(self, strs: Iterable[str], name: str):
            super().__init__(strs)
            self.name = name

S(['a'], 'a')

outputs just fine:

S({'a'})

I want the extra functionality of a set, but I don't want my users to change it.

EDIT: I know I could just use composition over inheritance, but it would be nice if I could make this work as well.


问:
How do I parse url after searching?
I'm trying to parse a specifc part of url after search using
any language.(Ideally Javascript but open to Python)

How do I get a specific part of url and save/store?

For example,
In songking.com,
The way to get artist_id is checking a specific part of the url after searching artist name
in the search bar of the website.

in the case below,
the artist id is 301329.

https://www.songkick.com/artists/301329-rac

I strongly believe there is a way to parse this part using either python or js
given that I have a csv file that has artist name in its column. Instead of searching all the artists one by one. I wonder about the algorithm that literate my csv column and search it and parse the url and save/store.

It would be very grateful even if I could only get a hint that I could start with.

Thank you so much always.

答:
First, you can use RegEx simply.
In python

```<code>import re
url = 'https://www.songkick.com/artists/301329-rac'
pattern = '/artists/(\d+)-\w'
match = re.search(pattern, url)
if match:
    artist_id = match.group(1)
</code>```

I hope this will help you.

Title: How do I parse url after searching?

Body:
First, you can use RegEx simply.
In python

import re
url = 'https://www.songkick.com/artists/301329-rac'
pattern = '/artists/(\d+)-\w'
match = re.search(pattern, url)
if match:
    artist_id = match.group(1)

I hope this will help you.


问:
Laravel Spatie Permissions - user and role relation get only id and name
I'm using Laravel Spatie Permissions to manage roles and permissions in my app. I'm traing to retrieve only Role id and name in the relation between users and roles. My UserResource looks like this:

```<code>class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'        => $this->id,
            'name'      => $this->name,
            'surname'   => $this->surname,
            'email'     => $this->email,
            'inactive'  => $this->inactive,
            'roles'     => $this->roles
        ];
    }
}
</code>```

And the json looks like this:

```<code>"data": [
        {
            "id": 1,
            "name": "Admin",
            "surname": "Sudo",
            "email": "admin@sudo.com",
            "inactive": 0,
            "roles": [
                {
                    "id": 1,
                    "name": "Admin",
                    "guard_name": "web",
                    "created_at": "2020-05-28 23:18:58",
                    "updated_at": "2020-05-28 23:18:58",
                    "pivot": {
                        "model_id": 1,
                        "role_id": 1,
                        "model_type": "App\\User"
                    }
                }
            ]
        },
]
</code>```

What I really need it's a json like this:

```<code>"data": [
        {
            "id": 1,
            "name": "Admin",
            "surname": "Sudo",
            "email": "admin@sudo.com",
            "inactive": 0,
            "roles": [
                {
                    "id": 1,
                    "name": "Admin",
                },
                {
                    "id": 2,
                    "name": "Default",
                },
                {
                    "id": 3,
                    "name": "Guest",
                }
            ]
        },
]
</code>```

I really don't know how to modified my models relations or the parameter $this->roles (in UserResources) to could get this json.

答:
The easiest solution was using a map function:</p>

```<code>'roles'     => $this->roles->map(function($role){
            return [
                'id' => $role['id'],
                'name' => $role['name']
            ];
        })
</code>```

Body:
I'm using Laravel Spatie Permissions to manage roles and permissions in my app. I'm traing to retrieve only Role id and name in the relation between users and roles. My UserResource looks like this:

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'        => $this->id,
            'name'      => $this->name,
            'surname'   => $this->surname,
            'email'     => $this->email,
            'inactive'  => $this->inactive,
            'roles'     => $this->roles
        ];
    }
}

And the json looks like this:

"data": [
        {
            "id": 1,
            "name": "Admin",
            "surname": "Sudo",
            "email": "admin@sudo.com",
            "inactive": 0,
            "roles": [
                {
                    "id": 1,
                    "name": "Admin",
                    "guard_name": "web",
                    "created_at": "2020-05-28 23:18:58",
                    "updated_at": "2020-05-28 23:18:58",
                    "pivot": {
                        "model_id": 1,
                        "role_id": 1,
                        "model_type": "App\\User"
                    }
                }
            ]
        },
]

What I really need it's a json like this:

"data": [
        {
            "id": 1,
            "name": "Admin",
            "surname": "Sudo",
            "email": "admin@sudo.com",
            "inactive": 0,
            "roles": [
                {
                    "id": 1,
                    "name": "Admin",
                },
                {
                    "id": 2,
                    "name": "Default",
                },
                {
                    "id": 3,
                    "name": "Guest",
                }
            ]
        },
]

I really don't know how to modified my models relations or the parameter $this->roles (in UserResources) to could get this json.

Body:
The easiest solution was using a map function:

'roles'     => $this->roles->map(function($role){
            return [
                'id' => $role['id'],
                'name' => $role['name']
            ];
        })


问:
How to take last four characters from a varchar?
I'm trying to take the last four characters only from a varchar field. All the rows are different lengths. What function should I be using to accomplish this?</p>

答:
tested solution on hackerrank....</p>

```<code>select distinct(city) from station
where substr(lower(city), length(city), 1) in ('a', 'e', 'i', 'o', 'u') and substr(lower(city), 1, 1) in ('a', 'e', 'i', 'o', 'u');
</code>```

Body:
tested solution on hackerrank....

select distinct(city) from station
where substr(lower(city), length(city), 1) in ('a', 'e', 'i', 'o', 'u') and substr(lower(city), 1, 1) in ('a', 'e', 'i', 'o', 'u');


问:
Selenium java code runs test successfully but fails when run as headless
My java selenium java test case with Chrome version 77 runs fine when options.setHeadless(false); but fails when I change this line options.setHeadless(true);

The java code was exported by the katalon selenium recorder chrome extension.

Output when it runs fine with options.setHeadless(false);:

```<code>Title of the page is 9 -> Scan History
Title of the page is 10 -> Scan History
Title of the page is 10.1 -> Scan History
Title of the page is 10.2 -> Scan History
Title of the page is 10.3 -> Scan History
Title of the page is 10.4 -> Scan History
Title of the page is 10.5 -> Scan History
</code>```

When I run the same code with options.setHeadless(true); I get a below warning as well as an error message and the execution terminates before completion.

```<code>Title of the page is 10 -> Scan History
[0530/125542.102:INFO:CONSOLE(0)] "Error parsing header X-XSS-Protection: 1; mod
e=block, 1;mode=block: expected semicolon at character position 13. The default
protections will be applied.", source: https://qualysguard.myshop.com/fo/scan/sca
nList.php (0)
Title of the page is 10.1 -> Scan History
Title of the page is 10.2 -> Scan History
Title of the page is 10.3 -> Scan History
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such e
lement: Unable to locate element: {"method":"css selector","selector":"#ext\-gen
117"}
  (Session info: headless chrome=77.0.3865.75)
For documentation on this error, please visit: https://www.seleniumhq.org/except
ions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17
:03'
System info: host: 'myhostserver', ip: '10.9.111.32', os.name: 'Windows Serve
r 2012 R2', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_45'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 7
7.0.3865.75, chrome: {chromedriverVersion: 77.0.3865.40 (f484704e052e0..., userD
ataDir: C:\Users\1886\AppData\Loc...}, goog:chromeOptions: {debuggerAddress: l
ocalhost:56128}, javascriptEnabled: true, networkConnectionEnabled: false, pageL
oadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRe
ct: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 30
0000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 09a309a747f7bcb42735bb8b6c39ad1f
*** Element info: {Using=id, value=ext-gen117}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Sou
rce)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(
W3CHttpResponseCodec.java:187)
        at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpRe
sponseCodec.java:122)
        at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpRe
sponseCodec.java:49)
        at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExe
cutor.java:158)
        at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(Driv
erCommandExecutor.java:83)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.ja
va:552)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDrive
r.java:323)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebD
river.java:372)
        at org.openqa.selenium.By$ById.findElement(By.java:188)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDrive
r.java:315)
        at pack.QualysScan.testQualysScan(QualysScan.java:182)
        at pack.QualysScan.main(QualysScan.java:284)
</code>```

Here is the part of the code concerning the issue:

```<code>System.out.println("Title of the page is 10 -> " + driver.getTitle());
driver.findElement(By.id("body-header")).click();
driver.get("https://qualysguard.myshop.com/fo/scan/scanList.php");
System.out.println("Title of the page is 10.1 -> " + driver.getTitle());
driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='Add to my Calendar'])[1]/following::em[2]")).click();
System.out.println("Title of the page is 10.2 -> " + driver.getTitle());
System.out.println("Title of the page is 10.3 -> " + driver.getTitle());
driver.findElement(By.id("ext-gen117")).click();
System.out.println("Title of the page is 10.4 -> " + driver.getTitle());
System.out.println("Title of the page is 10.5 -> " + driver.getTitle());
String your_title = "Launch Compliance Scan";
</code>```

And here is how the driver is setup:

```<code>public static void setUp() throws Exception {
          System.setProperty("webdriver.chrome.driver", "H:\\Downloads\\Qualys\\vdi\\chromedriver.exe");
          ChromeOptions options =  new ChromeOptions();
          options.setHeadless(true);
          DesiredCapabilities capabilities = DesiredCapabilities.chrome();
 capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
    capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
    options.merge(capabilities);
    driver = new ChromeDriver(options);
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  }
</code>```

I'm sharing snapshot of element ext\-gen117 as visible on the portal.

Video of the issue:

https://www.youtube.com/watch?v=abSwsPtOOG4

Can you please suggest how can I overcome the issue?

答:
This is likely caused by a race condition between the browser and selenium, where selenium attempts to click on something before it exists in the DOM. Using an explicit wait should resolve the issue:</p>

```<code>WebDriverWait wait = new WebDriverWait (driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("ext-gen117");
element.click();
</code>```

Body:
My java selenium java test case with Chrome version 77 runs fine when options.setHeadless(false); but fails when I change this line options.setHeadless(true);

The java code was exported by the katalon selenium recorder chrome extension.

Output when it runs fine with options.setHeadless(false);:

Title of the page is 9 -> Scan History
Title of the page is 10 -> Scan History
Title of the page is 10.1 -> Scan History
Title of the page is 10.2 -> Scan History
Title of the page is 10.3 -> Scan History
Title of the page is 10.4 -> Scan History
Title of the page is 10.5 -> Scan History

When I run the same code with options.setHeadless(true); I get a below warning as well as an error message and the execution terminates before completion.

Title of the page is 10 -> Scan History
[0530/125542.102:INFO:CONSOLE(0)] "Error parsing header X-XSS-Protection: 1; mod
e=block, 1;mode=block: expected semicolon at character position 13. The default
protections will be applied.", source: https://qualysguard.myshop.com/fo/scan/sca
nList.php (0)
Title of the page is 10.1 -> Scan History
Title of the page is 10.2 -> Scan History
Title of the page is 10.3 -> Scan History
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such e
lement: Unable to locate element: {"method":"css selector","selector":"#ext\-gen
117"}
  (Session info: headless chrome=77.0.3865.75)
For documentation on this error, please visit: https://www.seleniumhq.org/except
ions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17
:03'
System info: host: 'myhostserver', ip: '10.9.111.32', os.name: 'Windows Serve
r 2012 R2', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_45'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 7
7.0.3865.75, chrome: {chromedriverVersion: 77.0.3865.40 (f484704e052e0..., userD
ataDir: C:\Users\1886\AppData\Loc...}, goog:chromeOptions: {debuggerAddress: l
ocalhost:56128}, javascriptEnabled: true, networkConnectionEnabled: false, pageL
oadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRe
ct: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 30
0000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 09a309a747f7bcb42735bb8b6c39ad1f
*** Element info: {Using=id, value=ext-gen117}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Sou
rce)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(
W3CHttpResponseCodec.java:187)
        at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpRe
sponseCodec.java:122)
        at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpRe
sponseCodec.java:49)
        at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExe
cutor.java:158)
        at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(Driv
erCommandExecutor.java:83)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.ja
va:552)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDrive
r.java:323)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebD
river.java:372)
        at org.openqa.selenium.By$ById.findElement(By.java:188)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDrive
r.java:315)
        at pack.QualysScan.testQualysScan(QualysScan.java:182)
        at pack.QualysScan.main(QualysScan.java:284)

Here is the part of the code concerning the issue:

System.out.println("Title of the page is 10 -> " + driver.getTitle());
driver.findElement(By.id("body-header")).click();
driver.get("https://qualysguard.myshop.com/fo/scan/scanList.php");
System.out.println("Title of the page is 10.1 -> " + driver.getTitle());
driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='Add to my Calendar'])[1]/following::em[2]")).click();
System.out.println("Title of the page is 10.2 -> " + driver.getTitle());
System.out.println("Title of the page is 10.3 -> " + driver.getTitle());
driver.findElement(By.id("ext-gen117")).click();
System.out.println("Title of the page is 10.4 -> " + driver.getTitle());
System.out.println("Title of the page is 10.5 -> " + driver.getTitle());
String your_title = "Launch Compliance Scan";

And here is how the driver is setup:

public static void setUp() throws Exception {
          System.setProperty("webdriver.chrome.driver", "H:\\Downloads\\Qualys\\vdi\\chromedriver.exe");
          ChromeOptions options =  new ChromeOptions();
          options.setHeadless(true);
          DesiredCapabilities capabilities = DesiredCapabilities.chrome();
 capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
    capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
    options.merge(capabilities);
    driver = new ChromeDriver(options);
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  }

I'm sharing snapshot of element ext\-gen117 as visible on the portal.

Video of the issue:

https://www.youtube.com/watch?v=abSwsPtOOG4

Can you please suggest how can I overcome the issue?

Body:
This is likely caused by a race condition between the browser and selenium, where selenium attempts to click on something before it exists in the DOM. Using an explicit wait should resolve the issue:

WebDriverWait wait = new WebDriverWait (driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("ext-gen117");
element.click();


问:
Passing info from a Form into a function React js
I am new to react and js and I want to create an edit form that contains some modifiable info, which can be later posted to an API using Axios. the thing is, that I do not enter my function when I click on my submit button, and I dont know if my form info is passed correctly to my edit function.

```<code>function EditJob (jobid, event) {
  console.log('editjob fired 1')
  console.log(jobid)

  const updateJob = {
    title: event.target.jobtitle.value,
    company_name: event.target.companyname.value,
    internal_code: event.target.internalcode.value,
    department: event.target.department.value,
    location: event.target.jlocation.value,
    tags: event.target.tags.value,
    benefits: event.target.benefits.value,
    description: event.target.description.value,
    requirements: event.target.requirements.value
  }
  return axios({
    method: 'put',
    url: '/api/jobs/update-job/' + jobid,
    headers: headers,
    data: updateJob
  })
}
</code>```

```<code>export default function Jobs () {
  const classes = useStyles()
  const [jobs, locations, departments, tags, deleteJob, editJob] = useJobs()
  const [show, setShow] = React.useState(false)

  const handleClose = () => setShow(false)
  const handleShow = () => setShow(true)

  return (
    <>
   {jobs.map(job => (
          <>
            <Modal show={show} onHide={handleClose}>
              <Modal.Header closeButton>
                <Modal.Title>Edit Job Position</Modal.Title>
              </Modal.Header>
              <Modal.Body>

                <div className='container'>

                <Form onSubmit = {async () => { await EditJob(job.id); editJob() }}>

                <Row>
                  <Col lg={6}>
                    <Form.Group controlId='jobtitle'>
                      <Form.Label style={{ color: 'green' }}>Job Title :</Form.Label>
                      <Form.Control type='textbox' defaultValue={job.title} name='jobtitle' required placeholder='Enter Job Title' />
                    </Form.Group>

                    <Form.Group controlId='internalCode'>
                      <Form.Label style={{ color: 'green' }}>Internal Code :</Form.Label>
                      <Form.Control type='textbox' defaultValue={job.internal_code} name='internalcode' required placeholder='Enter Internal Code' />
                    </Form.Group>

                    <Form.Group controlId='department'>
                    <Form.Label style={{ color: 'green' }}>Department :</Form.Label>
                    <Form.Control type='textbox' defaultValue={job.department} name='department' disabled required placeholder='Enter Department' />
                  </Form.Group>

                  </Col>
                <Col lg={6}>

                  <Form.Group controlId='jlocation'>
                    <Form.Label style={{ color: 'green' }}>Location :</Form.Label>
                    <Form.Control type='textbox' defaultValue={job.location} name='jlocation' disabled required placeholder='Enter Location' />
                  </Form.Group>

                </Col>
              <Col lg={12}>
              <Form.Group>
                <Button style={{ position: 'relative', left: '295px' }} variant='success' type='submit'>Edit Job Position</Button>
              </Form.Group>
              </Col>
            </Row>
              </Form>
                </div>
              </Modal.Body>
        </Modal>
</code>```

the updateJob const is supposed to hold the info sent from the Form using event.target but I think I'm doing something wrong because I don't even enter the function and my page just refreshes when I click on the submit button. what is the correct solution to do this?

答:
The default behavior of the form is to trigger a reload on click of submit button. You can prevent this behavior by using event.preventDefault() in the onSubmit method

```<code><Form onSubmit = {async (event) => {
       event.preventDefault();
       await EditJob(job.id);
       editJob()
}}>
</code>```

Body:
I am new to react and js and I want to create an edit form that contains some modifiable info, which can be later posted to an API using Axios. the thing is, that I do not enter my function when I click on my submit button, and I dont know if my form info is passed correctly to my edit function.

function EditJob (jobid, event) {
  console.log('editjob fired 1')
  console.log(jobid)

  const updateJob = {
    title: event.target.jobtitle.value,
    company_name: event.target.companyname.value,
    internal_code: event.target.internalcode.value,
    department: event.target.department.value,
    location: event.target.jlocation.value,
    tags: event.target.tags.value,
    benefits: event.target.benefits.value,
    description: event.target.description.value,
    requirements: event.target.requirements.value
  }
  return axios({
    method: 'put',
    url: '/api/jobs/update-job/' + jobid,
    headers: headers,
    data: updateJob
  })
}

export default function Jobs () {
  const classes = useStyles()
  const [jobs, locations, departments, tags, deleteJob, editJob] = useJobs()
  const [show, setShow] = React.useState(false)

  const handleClose = () => setShow(false)
  const handleShow = () => setShow(true)

  return (
    <>
   {jobs.map(job => (
          <>
            <Modal show={show} onHide={handleClose}>
              <Modal.Header closeButton>
                <Modal.Title>Edit Job Position</Modal.Title>
              </Modal.Header>
              <Modal.Body>

                <Form onSubmit = {async () => { await EditJob(job.id); editJob() }}>

                <Row>
                  <Col lg={6}>
                    <Form.Group controlId='jobtitle'>
                      <Form.Label style={{ color: 'green' }}>Job Title :</Form.Label>
                      <Form.Control type='textbox' defaultValue={job.title} name='jobtitle' required placeholder='Enter Job Title' />
                    </Form.Group>

                    <Form.Group controlId='internalCode'>
                      <Form.Label style={{ color: 'green' }}>Internal Code :</Form.Label>
                      <Form.Control type='textbox' defaultValue={job.internal_code} name='internalcode' required placeholder='Enter Internal Code' />
                    </Form.Group>

                    <Form.Group controlId='department'>
                    <Form.Label style={{ color: 'green' }}>Department :</Form.Label>
                    <Form.Control type='textbox' defaultValue={job.department} name='department' disabled required placeholder='Enter Department' />
                  </Form.Group>

                  </Col>
                <Col lg={6}>

                  <Form.Group controlId='jlocation'>
                    <Form.Label style={{ color: 'green' }}>Location :</Form.Label>
                    <Form.Control type='textbox' defaultValue={job.location} name='jlocation' disabled required placeholder='Enter Location' />
                  </Form.Group>

                </Col>
              <Col lg={12}>
              <Form.Group>
                <Button style={{ position: 'relative', left: '295px' }} variant='success' type='submit'>Edit Job Position</Button>
              </Form.Group>
              </Col>
            </Row>
              </Form>

              </Modal.Body>
        </Modal>

the updateJob const is supposed to hold the info sent from the Form using event.target but I think I'm doing something wrong because I don't even enter the function and my page just refreshes when I click on the submit button. what is the correct solution to do this?

Body:
The default behavior of the form is to trigger a reload on click of submit button. You can prevent this behavior by using event.preventDefault() in the onSubmit method

<Form onSubmit = {async (event) => {
       event.preventDefault();
       await EditJob(job.id);
       editJob()
}}>


问:
How to keep child's stdout open after parent's termination in linux?
I am trying to run a child process from the parent app in Ubuntu. Both are C programs. The parent uses fork() with subsequent execl(), then waits for ~1 sec and terminates. The idea is to let parent terminate in a regular way, and keep child alive and running in the same console. So, the child begins to print some output with intervals of 300 ms, and I can see it for about the time while parent is alive. Then parent terminates, and further child output can not be seen in the console.

From what I have read to this moment, it seems that since the child shares all the handles, upon parent's exit stdout gets closed for both parent and child. So, I guess the child has to somehow preserve binding to the same console it was bound to upon its start. Please, advice how to achieve this.

答:
Sorry for bothering you guys and thank you all for your comments! As a windows-backgrounded person I just was not sure what should be normal behaviour in such a scenario.

While building and trying out the example, I think I understood the reason of this behaviour. The problem was that I ran it in mc with panels shown. Now, I have tried to run it under different conditions, and have the following picture: if I run it from bare console, it works fine; if I run it from mc with panels hidden, it runs OK either. The only case when it stops to show output after parent had closed is when I run it with panels shown. Now it's obvious to me that in this case the mc prints "Press any key to continue..." message right upon the parent's termination and stops showing any further output from the child.


问:
Angular Project Structure with separate package.json files
I saw this Project Structure in Angular with Node.js as backend, where the Angular node modules and package.json were in the "app" folder, while the node.js' node modules and package.json were in the root of the project. (watch picture)

How do i get the requested outcome?

答:
Step 1 :- Run npm i @angular/cli@latest in command prompt

Step 2 :- create a empty folder.

Step 3 :- go to your newly created folder inside command prompt.

Step 4 :- run npm init

Step 5 :- then run ng new my-app

Step 6 :- then run touch server.js