问:
Django - quiz app - issue with forms i guess
I'm trying to make an app by using django which allow me to study.

for now I have already done it

models.py

```<code>class Question(models.Model):
    question_text = models.CharField(max_length=200, null=True)
    answer_text = models.CharField(max_length=200, null=True)
    date_posted = models.DateTimeField(auto_now_add = True)
    def __str__(self):
        return self.question_text

class Test(models.Model):
    name = models.CharField(max_length=200)
    questions = models.ManyToManyField(Question)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True)
    date_posted = models.DateTimeField(auto_now_add = True)
</code>```

urls.py

```<code>urlpatterns = [
    path('', views.home, name='home'),
    path('test/<str:pk>/', views.test),
]
</code>```

views.py

```<code>def test(request, pk):
    test = Test.objects.get(id=pk)
    questions = test.questions.all()
    form = Answer()
    context = {'questions':questions, 'form':form}
    if request.method == 'POST':
        instance = Question.objects.get(id=pk)
        form = Answer(request.POST, instance=instance)

        if form.is_valid():
            if request.POST.get("answer").strip() == instance.answer:
                return redirect('home')

    return render(request, 'exam/test.html', context)
</code>```

forms.py

```<code>class Answer(ModelForm):
    class Meta:
        model = Question
        fields = ['answer_text']
    answer = forms.CharField(label='Your answer', max_length=100)
</code>```

and my html code:

```<code>{% for question in questions %}
        <div class="question-container">
            <p>{{question.question_text}}</p>
            <form method="POST">
                <td>{{ form.answer }}</td>
                {% csrf_token %}
                <input type="hidden" name="question_id" value="{{ question.id }}" />
                <td>
                    <input type="submit" value="submit">
                </td>
            </form>
        </div>
    {% endfor %}
</code>```
```<code>from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('', include('exam.urls'), name="home"),
    path('admin/', admin.site.urls),
]
</code>```

I haven't implemeted any point counter function. I wanted to be redirected to home page if answer is correct to see if the form works corectly but it is not. Where did i make mistake ?

答:
Original Answer

I believe the mistake is here:

if request.POST.get("answer").strip() == instance.answer:
```
<p>Which should be:</p>
```if request.POST.get("answer_text").strip() == instance.answer_text:
```
<p>Your <code>instance</code> is a Question object, with a field <code>answer_text</code>, not <code>answer</code>.</p>
<p>Your root urls.py also has a path with 'name', and I don't think you want it there.</p>
<pre class="lang-py prettyprint-override"><code># change
    path('', include('exam.urls'), name="home"),
# to this:
    path('', include('exam.urls')),
</code>```

The name is already in your exam.urls.py.

Edit

I think your forms.py has an issue, since it's a ModelForm, the field is already given in the class, so you don't need the line defining answer:

class Answer(ModelForm):
    class Meta:
        model = Question
        fields = ['answer_text']
    # Remove the line below:
    # answer = forms.CharField(label='Your answer', max_length=100)
```
<p>Then in your template:</p>
<pre class="lang-html prettyprint-override"><code>{% for question in questions %}
    <div class="question-container">
        <p>{{question.question_text}}</p>
        <form method="POST">
        {% csrf_token %}
            <td>{{ form.answer_text }}</td>
            <input type="hidden" name="question_id" value="{{ question.id }}" />
            <td>
                <input type="submit" value="submit">
            </td>
        </form>
    </div>
</code>```

And try to put the print statements as follows:

def test(request, pk):
    print("Am I getting here?")  #check if the view is even being called
    test = Test.objects.get(id=pk)
    questions = test.questions.all()
    form = Answer()
    context = {'questions':questions, 'form':form}
    if request.method == 'POST':
        print("request.POST", request.POST)  # to check what is being sent by the form
        instance = Question.objects.get(id=pk)
        form = Answer(request.POST, instance=instance)

        if form.is_valid():
            print("form is valid")  # To check if the form is valid
            if request.POST.get("answer_text").strip() == instance.answer_text:
                print("answer is correct")  # to check if this logic is working
                return redirect('home')

    return render(request, 'exam/test.html', context)
```
<p><strong>Edit 2</strong></p>
<p>Make sure to add the <code>print("request.POST", request.POST)</code>.  Since you're getting the "Am I getting here?", your path is fine.  Now do you get "Request.POST" in your terminal <em>when you click the submit button</em>?  If not, it probably means the html page is not going to the same path, in which case you need to tell it where to go by adding the action attribute to your form (this is <strong>not</strong> needed if <code>print(request.POST)</code> shows up):</p>
<pre class="lang-html prettyprint-override"><code>{% for question in questions %}
    <div class="question-container">
        <p>{{question.question_text}}</p>
        <form method="POST" action="{% url 'test' question.pk %}">
            <td>{{ form.answer }}</td>
                <input type="hidden" name="question_id" value="{{ question.id }}" />
            <td>
                <input type="submit" value="submit">
            </td>
        </form>
    </div>
{% endfor %}
</code>```

Also, since pk is an integer, you should change the path to

path('test/<int:pk>/', views.test),
```

Body:
I'm trying to make an app by using django which allow me to study.

for now I have already done it

models.py

class Question(models.Model):
    question_text = models.CharField(max_length=200, null=True)
    answer_text = models.CharField(max_length=200, null=True)
    date_posted = models.DateTimeField(auto_now_add = True)
    def __str__(self):
        return self.question_text

class Test(models.Model):
    name = models.CharField(max_length=200)
    questions = models.ManyToManyField(Question)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True)
    date_posted = models.DateTimeField(auto_now_add = True)

urls.py

urlpatterns = [
    path('', views.home, name='home'),
    path('test/<str:pk>/', views.test),
]

views.py

def test(request, pk):
    test = Test.objects.get(id=pk)
    questions = test.questions.all()
    form = Answer()
    context = {'questions':questions, 'form':form}
    if request.method == 'POST':
        instance = Question.objects.get(id=pk)
        form = Answer(request.POST, instance=instance)

        if form.is_valid():
            if request.POST.get("answer").strip() == instance.answer:
                return redirect('home')

    return render(request, 'exam/test.html', context)

forms.py

class Answer(ModelForm):
    class Meta:
        model = Question
        fields = ['answer_text']
    answer = forms.CharField(label='Your answer', max_length=100)

and my html code:

{% for question in questions %}

{{question.question_text}}

            <form method="POST">
                {{ form.answer }}
                {% csrf_token %}
                <input type="hidden" name="question_id" value="{{ question.id }}" />

                    <input type="submit" value="submit">

            </form>

    {% endfor %}

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('', include('exam.urls'), name="home"),
    path('admin/', admin.site.urls),
]

I haven't implemeted any point counter function. I wanted to be redirected to home page if answer is correct to see if the form works corectly but it is not. Where did i make mistake ?

Body:
Original Answer

I believe the mistake is here:

if request.POST.get("answer").strip() == instance.answer:

Which should be:

if request.POST.get("answer_text").strip() == instance.answer_text:

Your instance is a Question object, with a field answer_text, not answer.

Your root urls.py also has a path with 'name', and I don't think you want it there.

# change
    path('', include('exam.urls'), name="home"),
# to this:
    path('', include('exam.urls')),

The name is already in your exam.urls.py.

Edit

I think your forms.py has an issue, since it's a ModelForm, the field is already given in the class, so you don't need the line defining answer:

class Answer(ModelForm):
    class Meta:
        model = Question
        fields = ['answer_text']
    # Remove the line below:
    # answer = forms.CharField(label='Your answer', max_length=100)

Then in your template:

{% for question in questions %}
    <div class="question-container">
        <p>{{question.question_text}}</p>
        <form method="POST">
        {% csrf_token %}
            <td>{{ form.answer_text }}</td>
            <input type="hidden" name="question_id" value="{{ question.id }}" />
            <td>
                <input type="submit" value="submit">
            </td>
        </form>
    </div>

And try to put the print statements as follows:

def test(request, pk):
    print("Am I getting here?")  #check if the view is even being called
    test = Test.objects.get(id=pk)
    questions = test.questions.all()
    form = Answer()
    context = {'questions':questions, 'form':form}
    if request.method == 'POST':
        print("request.POST", request.POST)  # to check what is being sent by the form
        instance = Question.objects.get(id=pk)
        form = Answer(request.POST, instance=instance)

        if form.is_valid():
            print("form is valid")  # To check if the form is valid
            if request.POST.get("answer_text").strip() == instance.answer_text:
                print("answer is correct")  # to check if this logic is working
                return redirect('home')

    return render(request, 'exam/test.html', context)

Edit 2

Make sure to add the print("request.POST", request.POST).  Since you're getting the "Am I getting here?", your path is fine.  Now do you get "Request.POST" in your terminal when you click the submit button?  If not, it probably means the html page is not going to the same path, in which case you need to tell it where to go by adding the action attribute to your form (this is not needed if print(request.POST) shows up):

{% for question in questions %}
    <div class="question-container">
        <p>{{question.question_text}}</p>
        <form method="POST" action="{% url 'test' question.pk %}">
            <td>{{ form.answer }}</td>
                <input type="hidden" name="question_id" value="{{ question.id }}" />
            <td>
                <input type="submit" value="submit">
            </td>
        </form>
    </div>
{% endfor %}

Also, since pk is an integer, you should change the path to

path('test/<int:pk>/', views.test),


来源: stackexchange

问:
REACT JS - Working on eshop-like project, got stuck with product filters
So hello. I've been working on my own stuff as I believe it is the best way to learn things. So I got stuck, I am quite new to this react thing. I got this code, as you can see I have few checkboxes there, and what I want to achieve is to check the box to filter (hide) products from the array. I kinda got to the point where I don't know what should I do next, I know I need to put something into constructor, but I can't really figure out what. Can you please help me with that? Thanks!

class Shop extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        //I should put something here?
      }
    }

    render(){

        let checkbox = (a) => {
         this.setState({cpu: a.target.checked});

        }

        return (

            <input type="checkbox" onChange={checkbox} name="cpu" id="cpu"></input>

            //I will do these later, so far I'd be happy to get cpu filter to work.

            <input type="checkbox" name="gpu" id="gpu"></input>
            <input type="checkbox" name="psu" id="psu"></input>
            <input type="checkbox" name="mb" id="mb"></input>
            <input type="checkbox" name="ram" id="ram"></input>
            <input type="checkbox" name="case" id="case"></input>

            {products.filter(product =>{
            if (true) {
                return true;
            }
        }).map((shop) =>
          <>

{shop.name}

{shop.price}

          </>)}
);
}
}
ReactDOM.render(
  <Shop/>,
  document.getElementById('maincontent')
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.group:after {
    content: "";
    display: table;
    clear: both;
  }

  /* HEADER */

  header {
      background-color: rgb(57,184,231);
      height: 9em;
      border-bottom: 2px solid blue;
  }

  .mainheader {
      margin: 0 auto;
      width: 70em;
  }

.socialnetworks {

    display: flex;
    justify-content: flex-end;

    margin: -7px 0 0 0;

    width: 100%;

    background-color: rgb(0,170,203);
    height: 20px;
}

.socialnetworks i {
    padding-right: 20px;
    color: white;

    font-size: 20px;
}

.socialnetworks i:first-child:hover {
    color: rgb(66, 103, 178);
    cursor: pointer;
}

.socialnetworks i:last-child:hover {
    color: red;
    cursor: pointer;
}

.socicons {
    padding-right: 410px;
}

.socialnetworks i:last-child {
    padding: 0;
}

.logo {
    position: relative;
    top:0;
    left:0;

    max-width: 18%;

    font-size: 60px;

    color: white;

}

.logo span {
    font-weight: bolder;
}

.menu {
    text-align: center;
}

.menu span {
    margin-right: 15px;
    padding: 10px 10px 10px 10px;

    font-size: 25px;
    font-weight: bolder;
}

.menu span:hover {
    border-radius: 5px;
    background-color: rgb(33, 97, 194);
    cursor: pointer;
}

.menu a {
    text-decoration: none;
    color: whitesmoke;
}

.menu a:last-child {
    padding: 0;
}

.basket {
    position: absolute;
    top: 65px;
    right: 60px;
}

.basket span:hover {
    background-color: rgb(0, 140, 255);
    cursor: pointer;
}

.basket span {
    padding: 5px 5px 5px 5px;

    border: 1px solid grey;
    border-radius: 5px;

    background-color: rgb(0, 41, 128);
    color: whitesmoke;
}

/* MAIN_CONTENT */

#maincontent {

    padding-top: 10em;
    width: 1251px;
    margin: 0 auto;
}

#prodinfo {
    display: inline-block;

    width: 400px;
    height: 300px;

    border: 1px solid black;
    border-radius: 5px;

    margin: 0 15px 15px 0;
}

#pname {
    text-align: center;
    font-size: 30px;
    font-weight: bolder;
}

#pprice {
    position: relative;
    top: 165px;
    left: 60px;

    font-size: 20px;
}

#pimg {
    position: relative;
    bottom: 40px;
    left: 110px;

    height: 160px;
    width: 200px;
}

#pprice::after {
    content: "€";
}

#prodfilters {
    text-align: center;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="style.css">

    <title>PCzone</title>

             Facebook
             Youtube

            PCzone

            Domov
            Zľavené produkty
            O nás

            Nákupný košík

Filter produktov

```

答:
In

```<code>this.state = {
        //I should put something here?
      }
</code>```

You should put the initial value of cpu, in this case i think you want to filter the products when the user checks the checkbox, so the initial value of the state variable is gonna be false, like this:

```<code> this.state = {
        cpu:false
      }
</code>```

So when the value of cpu is true you should filter all the products that are an cpu.

ContentLicense: CC BY-SA 4.0

Body:
So hello. I've been working on my own stuff as I believe it is the best way to learn things. So I got stuck, I am quite new to this react thing. I got this code, as you can see I have few checkboxes there, and what I want to achieve is to check the box to filter (hide) products from the array. I kinda got to the point where I don't know what should I do next, I know I need to put something into constructor, but I can't really figure out what. Can you please help me with that? Thanks!

class Shop extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        //I should put something here?
      }
    }

    render(){

        let checkbox = (a) => {
         this.setState({cpu: a.target.checked});

        }

        return (

            <input type="checkbox" onChange={checkbox} name="cpu" id="cpu"></input>

            //I will do these later, so far I'd be happy to get cpu filter to work.

            <input type="checkbox" name="gpu" id="gpu"></input>
            <input type="checkbox" name="psu" id="psu"></input>
            <input type="checkbox" name="mb" id="mb"></input>
            <input type="checkbox" name="ram" id="ram"></input>
            <input type="checkbox" name="case" id="case"></input>

            {products.filter(product =>{
            if (true) {
                return true;
            }
        }).map((shop) =>
          <>

{shop.name}

{shop.price}

          </>)}
);
}
}
ReactDOM.render(
  <Shop/>,
  document.getElementById('maincontent')
);

.group:after {
    content: "";
    display: table;
    clear: both;
  }

  /* HEADER */

  header {
      background-color: rgb(57,184,231);
      height: 9em;
      border-bottom: 2px solid blue;
  }

  .mainheader {
      margin: 0 auto;
      width: 70em;
  }

.socialnetworks {

    display: flex;
    justify-content: flex-end;

    margin: -7px 0 0 0;

    width: 100%;

    background-color: rgb(0,170,203);
    height: 20px;
}

.socialnetworks i {
    padding-right: 20px;
    color: white;

    font-size: 20px;
}

.socialnetworks i:first-child:hover {
    color: rgb(66, 103, 178);
    cursor: pointer;
}

.socialnetworks i:last-child:hover {
    color: red;
    cursor: pointer;
}

.socicons {
    padding-right: 410px;
}

.socialnetworks i:last-child {
    padding: 0;
}

.logo {
    position: relative;
    top:0;
    left:0;

    max-width: 18%;

    font-size: 60px;

    color: white;

}

.logo span {
    font-weight: bolder;
}

.menu {
    text-align: center;
}

.menu span {
    margin-right: 15px;
    padding: 10px 10px 10px 10px;

    font-size: 25px;
    font-weight: bolder;
}

.menu span:hover {
    border-radius: 5px;
    background-color: rgb(33, 97, 194);
    cursor: pointer;
}

.menu a {
    text-decoration: none;
    color: whitesmoke;
}

.menu a:last-child {
    padding: 0;
}

.basket {
    position: absolute;
    top: 65px;
    right: 60px;
}

.basket span:hover {
    background-color: rgb(0, 140, 255);
    cursor: pointer;
}

.basket span {
    padding: 5px 5px 5px 5px;

    border: 1px solid grey;
    border-radius: 5px;

    background-color: rgb(0, 41, 128);
    color: whitesmoke;
}

/* MAIN_CONTENT */

#maincontent {

    padding-top: 10em;
    width: 1251px;
    margin: 0 auto;
}

#prodinfo {
    display: inline-block;

    width: 400px;
    height: 300px;

    border: 1px solid black;
    border-radius: 5px;

    margin: 0 15px 15px 0;
}

#pname {
    text-align: center;
    font-size: 30px;
    font-weight: bolder;
}

#pprice {
    position: relative;
    top: 165px;
    left: 60px;

    font-size: 20px;
}

#pimg {
    position: relative;
    bottom: 40px;
    left: 110px;

    height: 160px;
    width: 200px;
}

#pprice::after {
    content: "€";
}

#prodfilters {
    text-align: center;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="style.css">

    <title>PCzone</title>

             Facebook
             Youtube

            PCzone

            Domov
            Zľavené produkty
            O nás

            Nákupný košík

Filter produktov

Body:
In

this.state = {
        //I should put something here?
      }

You should put the initial value of cpu, in this case i think you want to filter the products when the user checks the checkbox, so the initial value of the state variable is gonna be false, like this:

 this.state = {
        cpu:false
      }

So when the value of cpu is true you should filter all the products that are an cpu.


问:
Check if two hours are between a time range
I allow myself to ask my question here, because after several hours of trying to make my code work, it still does not work!
So I would simply like to check if two times (For example 8:00 and 10:00) are included between a time range (For example between 8:00 and 9:00). I have already tried several combinations, it seems to work from time to time, but when I check if 9:00 and 10:00 is between 8:00 and 9:00, it returns that the time is not included in the time slot when it is supposed to be!
Here is my code for the moment: (all data has been transformed into strtotime())

```<code>if ((($hdebut >= $ihdebutcours) && ($hdebut <= $ihfincours)) && (($hfin >= $ihdebutcours) && ($hfin >= $ihfincours))) {
    $f++;
}
</code>```

For example :

$hdebut = 9:00

$hfin = 11:15

$ihdebutcours = 9:00

$ihfincours = 10:00

Thank you very much to the people who will help me, it will help me enormously to continue my project, and sorry for my bad English! Good day to you !

答:
It sure is overkilled but when dealing with dates, I often go with Carbon.

With Carbon, you could easily check if a date is in the timerange of two dates

```<code>  $lessonStart = \Carbon\Carbon::parse('today at 9:00');
  $lessonEnd = \Carbon\Carbon::parse('today at 11:15');

  $arrivedAt = \Carbon\Carbon::parse('today at 9:00');
  $endedAt = \Carbon\Carbon::parse('today at 10:00');

  if ($arrivedAt->between($lessonStart, $lessonEnd) && $endedAt->between($lessonStart, $lessonEnd)) {
      //...
  }
</code>```

Body:
I allow myself to ask my question here, because after several hours of trying to make my code work, it still does not work!
So I would simply like to check if two times (For example 8:00 and 10:00) are included between a time range (For example between 8:00 and 9:00). I have already tried several combinations, it seems to work from time to time, but when I check if 9:00 and 10:00 is between 8:00 and 9:00, it returns that the time is not included in the time slot when it is supposed to be!
Here is my code for the moment: (all data has been transformed into strtotime())

if ((($hdebut >= $ihdebutcours) && ($hdebut <= $ihfincours)) && (($hfin >= $ihdebutcours) && ($hfin >= $ihfincours))) {
    $f++;
}

For example :

$hdebut = 9:00

$hfin = 11:15

$ihdebutcours = 9:00

$ihfincours = 10:00

Thank you very much to the people who will help me, it will help me enormously to continue my project, and sorry for my bad English! Good day to you !

Body:
It sure is overkilled but when dealing with dates, I often go with Carbon.

With Carbon, you could easily check if a date is in the timerange of two dates

  $lessonStart = \Carbon\Carbon::parse('today at 9:00');
  $lessonEnd = \Carbon\Carbon::parse('today at 11:15');

  $arrivedAt = \Carbon\Carbon::parse('today at 9:00');
  $endedAt = \Carbon\Carbon::parse('today at 10:00');

  if ($arrivedAt->between($lessonStart, $lessonEnd) && $endedAt->between($lessonStart, $lessonEnd)) {
      //...
  }


问:
Combine similar column values in pandas
I have the pandas dataframe as below

```<code>A        B     C
Apple   20     A1
Apple   30     A2
Apple   40     A3
Kiwi    20     K1
Kiwi    30     K2
Kiwi    10     K3
</code>```

I want the output as

```<code>A        B     C
Apple   20     A1
        30     A2
        40     A3
Kiwi    20     K1
        30     K2
        10     K3
</code>```

答:
Use Groupby.cumcount with df.loc and Series.ne:

```<code>In [938]: df.loc[df.groupby('A').cumcount().ne(0), 'A'] = ''

In [939]: df
Out[939]:
       A   B   C
0  Apple  20  A1
1         30  A2
2         40  A3
3   Kiwi  20  K1
4         30  K2
5         10  K3
</code>```

Title: Combine similar column values in pandas

Body:
I have the pandas dataframe as below

A        B     C
Apple   20     A1
Apple   30     A2
Apple   40     A3
Kiwi    20     K1
Kiwi    30     K2
Kiwi    10     K3

I want the output as

A        B     C
Apple   20     A1
        30     A2
        40     A3
Kiwi    20     K1
        30     K2
        10     K3

Body:
Use Groupby.cumcount with df.loc and Series.ne:

In [938]: df.loc[df.groupby('A').cumcount().ne(0), 'A'] = ''

In [939]: df
Out[939]:
       A   B   C
0  Apple  20  A1
1         30  A2
2         40  A3
3   Kiwi  20  K1
4         30  K2
5         10  K3


问:
Quartz CRON triggers job only once
i have a spring batch job which needs to be scheduled at specific hour of the day. I have setup a Quartz CRON scheduler to accomplish this. However i see that the job is getting triggered only once.

What could be wrong ?

following is the XML file snippet -

```<code><batch:job id="getFleetUpdatesJob" job-repository="jobRepository">
       <batch:step id="step0">
                <batch:tasklet ref="fleetUpdatesID" transaction-manager="jobRepository-transactionManager" />
       </batch:step>
       <!-- <batch:step id="step1" next="step2">
                <batch:tasklet ref="world" transaction-manager="jobRepository-transactionManager" />
       </batch:step> -->
    </batch:job>

    <!--  Quartz related beans START  -->

    <bean name="updateDataFeedJobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
      <property name="jobClass" value="<package>.schedule.UpdateDataFeedJob" />
    </bean>

    <bean id="cronTriggerId" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="updateDataFeedJobDetail" />
        <!-- run every morning at 3AM -->
        <!--  <property name="cronExpression" value="0 0 3 * * ?" /> -->

        <!-- run the job at 8pm everyday -->
        <property name="cronExpression" value="0 0 20 * * ?" />
    </bean>

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="cronTriggerId" />
            </list>
        </property>
    </bean>
    <!--  Quartz related beans END  -->
</code>```

答:
I suspect the cron expression is working correctly, however a Spring Batch job will only execute once unless it's parameters change.

You can verify this if you get a stack trace similar to:

```<code>2011-08-18 00:40:26,155 INFO [org.springframework.batch.core.launch.support.SimpleJobLauncher] - <Job: [FlowJob: [name=job1]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]>
2011-08-18 00:40:30,002 INFO [com.beny23.test.JobLauncherDetails] - <Quartz trigger firing with Spring Batch jobName=job1>
2011-08-18 00:40:30,015 ERROR [com.beny23.test.JobLauncherDetails] - <Could not execute job.>
org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException: A job instance already exists and is complete for parameters={run.id=1}.  If you want to run this job again, change the parameters.
    at org.springframework.batch.core.repository.support.SimpleJobRepository.createJobExecution(SimpleJobRepository.java:122)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
</code>```

In order to ensure that the parameters for each job invokation are different, you could modify the UpdateDataFeedJob class to call your job like this:

```<code>JobParametersBuilder builder = new JobParametersBuilder();
builder.addLong("run.ts", System.currentTimeMillis());
JobParameters jobParameters = builder.toJobParameters();

Job job = jobLocator.getJob(jobName);
jobLauncher.run(job, jobParameters);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Quartz CRON triggers job only once

Body:
i have a spring batch job which needs to be scheduled at specific hour of the day. I have setup a Quartz CRON scheduler to accomplish this. However i see that the job is getting triggered only once.

What could be wrong ?

following is the XML file snippet -

<batch:job id="getFleetUpdatesJob" job-repository="jobRepository">
       <batch:step id="step0">
                <batch:tasklet ref="fleetUpdatesID" transaction-manager="jobRepository-transactionManager" />
       </batch:step>

    </batch:job>

    <bean name="updateDataFeedJobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
      <property name="jobClass" value="<package>.schedule.UpdateDataFeedJob" />
    </bean>

    <bean id="cronTriggerId" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="updateDataFeedJobDetail" />

        <property name="cronExpression" value="0 0 20 * * ?" />
    </bean>

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="cronTriggerId" />
            </list>
        </property>
    </bean>

Body:
I suspect the cron expression is working correctly, however a Spring Batch job will only execute once unless it's parameters change.

You can verify this if you get a stack trace similar to:

2011-08-18 00:40:26,155 INFO [org.springframework.batch.core.launch.support.SimpleJobLauncher] - <Job: [FlowJob: [name=job1]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]>
2011-08-18 00:40:30,002 INFO [com.beny23.test.JobLauncherDetails] - <Quartz trigger firing with Spring Batch jobName=job1>
2011-08-18 00:40:30,015 ERROR [com.beny23.test.JobLauncherDetails] - <Could not execute job.>
org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException: A job instance already exists and is complete for parameters={run.id=1}.  If you want to run this job again, change the parameters.
    at org.springframework.batch.core.repository.support.SimpleJobRepository.createJobExecution(SimpleJobRepository.java:122)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)

In order to ensure that the parameters for each job invokation are different, you could modify the UpdateDataFeedJob class to call your job like this:

JobParametersBuilder builder = new JobParametersBuilder();
builder.addLong("run.ts", System.currentTimeMillis());
JobParameters jobParameters = builder.toJobParameters();

Job job = jobLocator.getJob(jobName);
jobLauncher.run(job, jobParameters);


问:
Whitespace as a value in .ini file
I want my .ini file to have an option to specify a certain character as a splitter for the parameters which is then handled with Python. That is:

```<code>[meta]
split_char = " "

[stuff]
field = value_1 value_2
</code>```

How can I specify a whitespace as a split char so it is recognizable? I have tried " " or [ ] and some other oprions, neither of them works.

As I've been asked, here is the Python scripts to read the .ini file:

```<code>from configparser import ConfigParser

config = ConfigParser()
config.read('config.ini')

# I need a nested dictionary, but this is not the point
split_char = config["meta"]["split_char"]
config = {section: dict(config.items(section)) for section in config.sections() if section != "meta"}
for section in config:
    for parameter in config[section]:
        config[section][parameter] = config[section][parameter].split(split_char)
</code>```

If I place a whitespace as it is, Python considers the splitter empty, adding quotes or any other auxiliary signs does not get the things done.

Update

The thing is that I would also like to be able to require splitters like ', ', which is a string with a whitespace.

答:
This can be done with a trickery like:

```<code>split_char = config["meta"]["split_char"][1:-1]
</code>```

Then the splitter can be placed inside quotes or brackets or whatever:

```<code>[meta]
split_char = " "
</code>```

The amount of characters to split does not matter as well, it's easy to go with things like , .

Title: Whitespace as a value in .ini file

Body:
I want my .ini file to have an option to specify a certain character as a splitter for the parameters which is then handled with Python. That is:

[meta]
split_char = " "

[stuff]
field = value_1 value_2

How can I specify a whitespace as a split char so it is recognizable? I have tried " " or [ ] and some other oprions, neither of them works.

As I've been asked, here is the Python scripts to read the .ini file:

from configparser import ConfigParser

config = ConfigParser()
config.read('config.ini')

# I need a nested dictionary, but this is not the point
split_char = config["meta"]["split_char"]
config = {section: dict(config.items(section)) for section in config.sections() if section != "meta"}
for section in config:
    for parameter in config[section]:
        config[section][parameter] = config[section][parameter].split(split_char)

If I place a whitespace as it is, Python considers the splitter empty, adding quotes or any other auxiliary signs does not get the things done.

Update

The thing is that I would also like to be able to require splitters like ', ', which is a string with a whitespace.

Body:
This can be done with a trickery like:

split_char = config["meta"]["split_char"][1:-1]

Then the splitter can be placed inside quotes or brackets or whatever:

[meta]
split_char = " "

The amount of characters to split does not matter as well, it's easy to go with things like , .


问:
How can I get a specific element value of object in localstorage
I'm trying to get "city" value (in case: Porto, Lisboa, Leiria, Londres) of localstorage and put It in a variable. I wish to do this in a loop for and use each city name in a function.

Now, I'm here:

```<code>Object.entries(localStorage).map(([id, valueJSON]) => {
  cityName = JSON.parse(JSON.stringify(localStorage.getItem('persist:root', 'allWeather', 'city')));
  console.log(cityName)
</code>```

My return is this:

{"allWeather":"[{"id":0.47266066302275545,"city":"Porto"},{"id":0.8669553925029849,"city":"Lisboa"},{"id":0.5502373167192611,"city":"Leiria"},{"id":0.19655712000371484,"city":"Londres"}]","_persist":"{"version":-1,"rehydrated":true}"}

How can I do this? I appreciate any help.

答:
Try this:

const cities =
    // Parse the localstorage item to object
    JSON.parse(localStorage.getItem('persist:root', 'allWeather', 'city'))
    // Get the allWeather property
    .allWeather
    // Get the city properties only
    .map(weather => weather.city);
```

Body:
I'm trying to get "city" value (in case: Porto, Lisboa, Leiria, Londres) of localstorage and put It in a variable. I wish to do this in a loop for and use each city name in a function.

Now, I'm here:

Object.entries(localStorage).map(([id, valueJSON]) => {
  cityName = JSON.parse(JSON.stringify(localStorage.getItem('persist:root', 'allWeather', 'city')));
  console.log(cityName)

My return is this:

{"allWeather":"[{"id":0.47266066302275545,"city":"Porto"},{"id":0.8669553925029849,"city":"Lisboa"},{"id":0.5502373167192611,"city":"Leiria"},{"id":0.19655712000371484,"city":"Londres"}]","_persist":"{"version":-1,"rehydrated":true}"}

How can I do this? I appreciate any help.


问:
Hibernate: "Field 'id' doesn't have a default value"
I'm facing what I think is a simple problem with Hibernate, but can't solve it (Hibernate forums being unreachable certainly doesn't help).

I have a simple class I'd like to persist, but keep getting:

```<code>SEVERE: Field 'id' doesn't have a default value
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not insert: [hibtest.model.Mensagem]
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
    [ a bunch more ]
Caused by: java.sql.SQLException: Field 'id' doesn't have a default value
    [ a bunch more ]
</code>```

The relevant code for the persisted class is:

```<code>package hibtest.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Mensagem  {
    protected Long id;

    protected Mensagem() { }

    @Id
    @GeneratedValue
    public Long getId() {
        return id;
}

    public Mensagem setId(Long id) {
        this.id = id;
        return this;
    }
}
</code>```

And the actual running code is just plain:

```<code>SessionFactory factory = new AnnotationConfiguration()
    .configure()
    .buildSessionFactory();

{
    Session session = factory.openSession();
    Transaction tx = session.beginTransaction();

    Mensagem msg = new Mensagem("YARR!");

    session.save(msg);

    tx.commit();
    session.close();
}
</code>```

I tried some "strategies" within the GeneratedValue annotation but it just doesn't seem to work. Initializing id doesn't help either! (eg Long id = 20L).

Could anyone shed some light?

EDIT 2: confirmed: messing with@GeneratedValue(strategy = GenerationType.XXX) doesn't solve it

SOLVED: recreating the database solved the problem

答: I solved similar problem, when I altered the database column type , and did not add auto_increment. After adding back auto_increment in the alter table command  (as in my original table creation) it worked</p>

Body:
I'm facing what I think is a simple problem with Hibernate, but can't solve it (Hibernate forums being unreachable certainly doesn't help).

I have a simple class I'd like to persist, but keep getting:

SEVERE: Field 'id' doesn't have a default value
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not insert: [hibtest.model.Mensagem]
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
    [ a bunch more ]
Caused by: java.sql.SQLException: Field 'id' doesn't have a default value
    [ a bunch more ]

The relevant code for the persisted class is:

package hibtest.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Mensagem  {
    protected Long id;

    protected Mensagem() { }

    @Id
    @GeneratedValue
    public Long getId() {
        return id;
}

    public Mensagem setId(Long id) {
        this.id = id;
        return this;
    }
}

And the actual running code is just plain:

SessionFactory factory = new AnnotationConfiguration()
    .configure()
    .buildSessionFactory();

{
    Session session = factory.openSession();
    Transaction tx = session.beginTransaction();

    Mensagem msg = new Mensagem("YARR!");

    session.save(msg);

    tx.commit();
    session.close();
}

I tried some "strategies" within the GeneratedValue annotation but it just doesn't seem to work. Initializing id doesn't help either! (eg Long id = 20L).

Could anyone shed some light?

EDIT 2: confirmed: messing with@GeneratedValue(strategy = GenerationType.XXX) doesn't solve it

SOLVED: recreating the database solved the problem


问:
Java and spring boot: Can you automatically generate dependencies in eclipse or another program?
I have a problem with an application built in java and spring boot.

1/ How can to generate eclipse project from only src folder? Is it possible to somehow automatically generate dependencies (pom.xml etc.)? I don't have a pom.xml file, just a src folder? Is there any way to automatically generate project from src folder in e.g. eclipse and generate dependencies automatically?

2/ Second question: I would like to move a java application from one server to new another server. I don't have project files. I have the structure as below in Tomcat webapps:

Is it possible to generate a project from this strukture in eclipse or intelliJ?
I am asking for help and some step-by-step instructions. I'm just learning java

答:
It doesn't work like this, actually it works in an opposite direction:

You start with a project with java files.

You use maven or gradle as a build system. Technically it means that you place the sources in some folder which is by convention recognized by these build tools and add some build tools specific files. For example for maven you add pom.xml file.

In the pom.xml (I'll stick to maven) add all the relevant dependencies. Its important to understand that you don't generate these dependencies because you want to be sure that the correct dependencies are added with the verified versions, etc. So you define dependencies by yourself, rather than generate them from your source code.

Build tool prepares the artifact (JAR, WAR, etc.) - whatever is required by your project.

To directly address your second question - if you write everything correctly, the generated artifact should not depend on the environment its intended to be run in. For example, if you hard-code an address of your locally installed database so that this data finds its way into the resulting artifact - this means that the artifact will depend on your environment and this is wrong.

Eclipse / IntelliJ as an IDE can read pom.xml file and parse all the dependencies out of it as like as setting up all the required stuff. So you can open pom.xml right in Eclipse and it will "prepare" an eclipse project for you.


问:
How to use Pacemaker to restart httpd
We have two servers with a Pacemaker (crm) setup that enables a primary/standby cluster.  There are currently two services controlled/monitored by Pacemaker that, if either goes down, will cause a fail-over to the standby, our own custom service (hereafter called customservice1) and mysql.

customservice1 and mysql are stopped on the standby and running on the primary (obviously).  When a failover occurs, it appears that pacemaker will stop both (or ensure they are stopped if only one failed for whatever reason, I'm not quite clear on this point), change the ip address of the primary and standby (so that an alias in DNS will always go to the primary), then start customservice1 and mysql on what was previously the standby.

I would like to add a step to this, controlled by pacemaker, that will simply restart httpd whenever a failover has occurred.  httpd currently is running on both the primary and standby at all times.  A failure in httpd currently does not cause a failover and I'm not really interested in adding that monitoring, I simply want pacemaker to run the equivalent of 'service httpd restart' when making the standby become the primary.

What is the correct syntax for adding a new primitive that will only restart a service?

Current pacemaker configuration is below:

```<code>node $id="XX" some.machine.name \
        attributes standby="off"
node $id="YY" another.machine.name
primitive customservice1 lsb:customservice1 \
        op monitor interval="30s" timeout="30s" \
        op start interval="0" timeout="120" \
        op stop interval="0" timeout="120" \
        meta target-role="Started"
primitive mysql-server ocf:heartbeat:mysql \
        params binary="/usr/bin/mysqld_safe" config="/etc/my.cnf" datadir="/some/data/dir" user="mysql" pid="/var/lib/mysql/mysql.pid" socket="/var/lib/mysql/mysql.sock" \
        op monitor interval="30s" timeout="30s" \
        op start interval="0" timeout="120" \
        op stop interval="0" timeout="120"
primitive node1-stonith stonith:external/riloe \
        params hostlist="some.machine.name" ilo_user="Administrator" ilo_hostname="some-ilo.machine.name" ilo_password="<ilopassword>" ilo_can_reset="1" ilo_protocol="2.0" ilo_powerdown_method="button" \
        op monitor interval="120s" timeout="40s" \
        meta target-role="Started"
primitive node2-stonith stonith:external/riloe \
        params hostlist="another.machine.name" ilo_user="Administrator" ilo_hostname="another-ilo.machine.name" ilo_password="<ilopassword>" ilo_can_reset="1" ilo_protocol="2.0" ilo_powerdown_method="button" \
        op monitor interval="120s" timeout="40s" \
        meta target-role="Started"
primitive node_one_ip ocf:heartbeat:IPaddr2 \
        params ip="1.1.1.1" cidr_netmask="255.255.255.0" nic="eth0" \
        op monitor interval="40s" timeout="20s"
primitive node_two_ip ocf:heartbeat:IPaddr2 \
        params ip="1.1.1.2" cidr_netmask="255.255.255.0" nic="eth0" \
        op monitor interval="40s" timeout="20s" \
        meta target-role="Started"
group only-group node_one_ip mysql-server customservice1
property $id="cib-bootstrap-options" \
        dc-version="1.0.9-89bd754939df5150de7cd76835f98fe90851b677" \
        cluster-infrastructure="Heartbeat" \
        no-quorum-policy="ignore" \
        last-lrm-refresh="1287686604" \
        default-resource-stickiness="1"
</code>```

答:
In order for Pacemaker to do this, you'd need to put the http server under Pacemaker's control and then create an ordering constraint between the group and the http daemon.
From memory you need to make sure score > 0 on the constraint.

Otherwise, you'd need to modify the script of an existing resource to restart httpd as necessary.

Title: How to use Pacemaker to restart httpd

Body:
We have two servers with a Pacemaker (crm) setup that enables a primary/standby cluster.  There are currently two services controlled/monitored by Pacemaker that, if either goes down, will cause a fail-over to the standby, our own custom service (hereafter called customservice1) and mysql.

customservice1 and mysql are stopped on the standby and running on the primary (obviously).  When a failover occurs, it appears that pacemaker will stop both (or ensure they are stopped if only one failed for whatever reason, I'm not quite clear on this point), change the ip address of the primary and standby (so that an alias in DNS will always go to the primary), then start customservice1 and mysql on what was previously the standby.

I would like to add a step to this, controlled by pacemaker, that will simply restart httpd whenever a failover has occurred.  httpd currently is running on both the primary and standby at all times.  A failure in httpd currently does not cause a failover and I'm not really interested in adding that monitoring, I simply want pacemaker to run the equivalent of 'service httpd restart' when making the standby become the primary.

What is the correct syntax for adding a new primitive that will only restart a service?

Current pacemaker configuration is below:

node $id="XX" some.machine.name \
        attributes standby="off"
node $id="YY" another.machine.name
primitive customservice1 lsb:customservice1 \
        op monitor interval="30s" timeout="30s" \
        op start interval="0" timeout="120" \
        op stop interval="0" timeout="120" \
        meta target-role="Started"
primitive mysql-server ocf:heartbeat:mysql \
        params binary="/usr/bin/mysqld_safe" config="/etc/my.cnf" datadir="/some/data/dir" user="mysql" pid="/var/lib/mysql/mysql.pid" socket="/var/lib/mysql/mysql.sock" \
        op monitor interval="30s" timeout="30s" \
        op start interval="0" timeout="120" \
        op stop interval="0" timeout="120"
primitive node1-stonith stonith:external/riloe \
        params hostlist="some.machine.name" ilo_user="Administrator" ilo_hostname="some-ilo.machine.name" ilo_password="<ilopassword>" ilo_can_reset="1" ilo_protocol="2.0" ilo_powerdown_method="button" \
        op monitor interval="120s" timeout="40s" \
        meta target-role="Started"
primitive node2-stonith stonith:external/riloe \
        params hostlist="another.machine.name" ilo_user="Administrator" ilo_hostname="another-ilo.machine.name" ilo_password="<ilopassword>" ilo_can_reset="1" ilo_protocol="2.0" ilo_powerdown_method="button" \
        op monitor interval="120s" timeout="40s" \
        meta target-role="Started"
primitive node_one_ip ocf:heartbeat:IPaddr2 \
        params ip="1.1.1.1" cidr_netmask="255.255.255.0" nic="eth0" \
        op monitor interval="40s" timeout="20s"
primitive node_two_ip ocf:heartbeat:IPaddr2 \
        params ip="1.1.1.2" cidr_netmask="255.255.255.0" nic="eth0" \
        op monitor interval="40s" timeout="20s" \
        meta target-role="Started"
group only-group node_one_ip mysql-server customservice1
property $id="cib-bootstrap-options" \
        dc-version="1.0.9-89bd754939df5150de7cd76835f98fe90851b677" \
        cluster-infrastructure="Heartbeat" \
        no-quorum-policy="ignore" \
        last-lrm-refresh="1287686604" \
        default-resource-stickiness="1"


问:
How to fix incompatible jars
I'm using a gradle wrapper on Gradle 4.10.1 and JVM 1.8.0_282 (AdoptOpenJDK 25.282-b08) (quite old I know).

My build.gradle originally looked like this:

```<code>    compile "com.google.cloud:google-cloud-bigquery:1.100.0"
    compile "com.google.cloud:google-cloud-pubsub:1.104.1"
    compile "com.google.cloud:google-cloud-storage:1.100.0"
</code>```

This occurred after I added com.google.cloud:google-cloud-bigquerystorage:2.8.4:

```<code>    compile "com.google.cloud:google-cloud-bigquery:1.100.0"
    compile "com.google.cloud:google-cloud-pubsub:1.104.1"
    compile "com.google.cloud:google-cloud-storage:1.100.0"
    compile "com.google.cloud:google-cloud-bigquerystorage:2.8.4"
</code>```

All of my unit tests now fails with:

```<code>com.google.api.gax.rpc.InternalException: io.grpc.StatusRuntimeException: INTERNAL: Panic! This is a bug!
    at com.google.api.gax.rpc.ApiExceptionFactory.createException(ApiExceptionFactory.java:65)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:72)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:60)
    at com.google.api.gax.grpc.GrpcExceptionCallable$ExceptionTransformingFuture.onFailure(GrpcExceptionCallable.java:97)
    at com.google.api.core.ApiFutures$1.onFailure(ApiFutures.java:68)
    at com.google.common.util.concurrent.Futures$4.run(Futures.java:1123)
    at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:435)
    at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:900)
    at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:811)
    at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:675)
    at io.grpc.stub.ClientCalls$GrpcFuture.setException(ClientCalls.java:564)
    at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:534)
    at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
    at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23)
    at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40)
    at com.google.api.gax.grpc.ChannelPool$ReleasingClientCall$1.onClose(ChannelPool.java:455)
    at io.grpc.internal.DelayedClientCall$DelayedListener$3.run(DelayedClientCall.java:463)
    at io.grpc.internal.DelayedClientCall$DelayedListener.delayOrExecute(DelayedClientCall.java:427)
    at io.grpc.internal.DelayedClientCall$DelayedListener.onClose(DelayedClientCall.java:460)
    at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:562)
    at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:70)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:743)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:722)
    at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: io.grpc.StatusRuntimeException: INTERNAL: Panic! This is a bug!
    at io.grpc.Status.asRuntimeException(Status.java:535)
    ... 17 more
Caused by: java.lang.AbstractMethodError: io.grpc.netty.shaded.io.grpc.netty.NettyClientTransport.newStream(Lio/grpc/MethodDescriptor;Lio/grpc/Metadata;Lio/grpc/CallOptions;[Lio/grpc/ClientStreamTracer;)Lio/grpc/internal/ClientStream;
    at io.grpc.internal.CallCredentialsApplyingTransportFactory$CallCredentialsApplyingTransport.newStream(CallCredentialsApplyingTransportFactory.java:159)
    at io.grpc.internal.ForwardingConnectionClientTransport.newStream(ForwardingConnectionClientTransport.java:51)
    at io.grpc.internal.InternalSubchannel$CallTracingTransport.newStream(InternalSubchannel.java:673)
    at io.grpc.internal.DelayedClientTransport$PendingStream.createRealStream(DelayedClientTransport.java:366)
    at io.grpc.internal.DelayedClientTransport$PendingStream.access$400(DelayedClientTransport.java:351)
    at io.grpc.internal.DelayedClientTransport.reprocess(DelayedClientTransport.java:309)
    at io.grpc.internal.ManagedChannelImpl.updateSubchannelPicker(ManagedChannelImpl.java:899)
    at io.grpc.internal.ManagedChannelImpl.access$5300(ManagedChannelImpl.java:118)
    at io.grpc.internal.ManagedChannelImpl$LbHelperImpl$1UpdateBalancingState.run(ManagedChannelImpl.java:1479)
    at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:95)
    at io.grpc.SynchronizationContext.execute(SynchronizationContext.java:127)
    at io.grpc.internal.InternalSubchannel$TransportListener.transportReady(InternalSubchannel.java:547)
    at io.grpc.netty.shaded.io.grpc.netty.ClientTransportLifecycleManager.notifyReady(ClientTransportLifecycleManager.java:44)
    at io.grpc.netty.shaded.io.grpc.netty.NettyClientHandler$FrameListener.onSettingsRead(NettyClientHandler.java:909)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener.onSettingsRead(DefaultHttp2ConnectionDecoder.java:479)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$PrefaceFrameListener.onSettingsRead(DefaultHttp2ConnectionDecoder.java:702)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2InboundFrameLogger$1.onSettingsRead(Http2InboundFrameLogger.java:93)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2FrameReader.readSettingsFrame(DefaultHttp2FrameReader.java:542)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2FrameReader.processPayloadState(DefaultHttp2FrameReader.java:263)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:160)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:174)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:378)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.decode(Http2ConnectionHandler.java:242)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:438)
    at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:501)
    at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:440)
    at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
    at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
    at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
    at io.grpc.netty.shaded.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:714)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:650)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:576)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
    at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
    at io.grpc.netty.shaded.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    ... 1 more
</code>```

This occurs without any code changes (just added that one dep to build.gradle), so I'm guessing this is an incompatible jar issue caused by the new dependency (as suggested by this comment). Since I'm on gradle 4.10.1, I can't resolve this with a pom. How does one go about resolving this?

答: This is because of an incompatibility in the grpc JARs. You may have to modify the versions of the other com.google.cloud JARs to make sure that they are compatible. Here is an issue from the upstream project where they recommend a Google Cloud Libraries BOM to simplify managing versions of these libraries and hopefully avoid conflicts like this. Since you are on Gradle 4.10.1 you can either use the feature preview for BOM support or use the Spring Dependency Management plugin.

Title: How to fix incompatible jars

Body:
I'm using a gradle wrapper on Gradle 4.10.1 and JVM 1.8.0_282 (AdoptOpenJDK 25.282-b08) (quite old I know).

My build.gradle originally looked like this:

    compile "com.google.cloud:google-cloud-bigquery:1.100.0"
    compile "com.google.cloud:google-cloud-pubsub:1.104.1"
    compile "com.google.cloud:google-cloud-storage:1.100.0"

This occurred after I added com.google.cloud:google-cloud-bigquerystorage:2.8.4:

    compile "com.google.cloud:google-cloud-bigquery:1.100.0"
    compile "com.google.cloud:google-cloud-pubsub:1.104.1"
    compile "com.google.cloud:google-cloud-storage:1.100.0"
    compile "com.google.cloud:google-cloud-bigquerystorage:2.8.4"

All of my unit tests now fails with:

com.google.api.gax.rpc.InternalException: io.grpc.StatusRuntimeException: INTERNAL: Panic! This is a bug!
    at com.google.api.gax.rpc.ApiExceptionFactory.createException(ApiExceptionFactory.java:65)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:72)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:60)
    at com.google.api.gax.grpc.GrpcExceptionCallable$ExceptionTransformingFuture.onFailure(GrpcExceptionCallable.java:97)
    at com.google.api.core.ApiFutures$1.onFailure(ApiFutures.java:68)
    at com.google.common.util.concurrent.Futures$4.run(Futures.java:1123)
    at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:435)
    at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:900)
    at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:811)
    at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:675)
    at io.grpc.stub.ClientCalls$GrpcFuture.setException(ClientCalls.java:564)
    at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:534)
    at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
    at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23)
    at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40)
    at com.google.api.gax.grpc.ChannelPool$ReleasingClientCall$1.onClose(ChannelPool.java:455)
    at io.grpc.internal.DelayedClientCall$DelayedListener$3.run(DelayedClientCall.java:463)
    at io.grpc.internal.DelayedClientCall$DelayedListener.delayOrExecute(DelayedClientCall.java:427)
    at io.grpc.internal.DelayedClientCall$DelayedListener.onClose(DelayedClientCall.java:460)
    at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:562)
    at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:70)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:743)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:722)
    at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: io.grpc.StatusRuntimeException: INTERNAL: Panic! This is a bug!
    at io.grpc.Status.asRuntimeException(Status.java:535)
    ... 17 more
Caused by: java.lang.AbstractMethodError: io.grpc.netty.shaded.io.grpc.netty.NettyClientTransport.newStream(Lio/grpc/MethodDescriptor;Lio/grpc/Metadata;Lio/grpc/CallOptions;[Lio/grpc/ClientStreamTracer;)Lio/grpc/internal/ClientStream;
    at io.grpc.internal.CallCredentialsApplyingTransportFactory$CallCredentialsApplyingTransport.newStream(CallCredentialsApplyingTransportFactory.java:159)
    at io.grpc.internal.ForwardingConnectionClientTransport.newStream(ForwardingConnectionClientTransport.java:51)
    at io.grpc.internal.InternalSubchannel$CallTracingTransport.newStream(InternalSubchannel.java:673)
    at io.grpc.internal.DelayedClientTransport$PendingStream.createRealStream(DelayedClientTransport.java:366)
    at io.grpc.internal.DelayedClientTransport$PendingStream.access$400(DelayedClientTransport.java:351)
    at io.grpc.internal.DelayedClientTransport.reprocess(DelayedClientTransport.java:309)
    at io.grpc.internal.ManagedChannelImpl.updateSubchannelPicker(ManagedChannelImpl.java:899)
    at io.grpc.internal.ManagedChannelImpl.access$5300(ManagedChannelImpl.java:118)
    at io.grpc.internal.ManagedChannelImpl$LbHelperImpl$1UpdateBalancingState.run(ManagedChannelImpl.java:1479)
    at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:95)
    at io.grpc.SynchronizationContext.execute(SynchronizationContext.java:127)
    at io.grpc.internal.InternalSubchannel$TransportListener.transportReady(InternalSubchannel.java:547)
    at io.grpc.netty.shaded.io.grpc.netty.ClientTransportLifecycleManager.notifyReady(ClientTransportLifecycleManager.java:44)
    at io.grpc.netty.shaded.io.grpc.netty.NettyClientHandler$FrameListener.onSettingsRead(NettyClientHandler.java:909)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener.onSettingsRead(DefaultHttp2ConnectionDecoder.java:479)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$PrefaceFrameListener.onSettingsRead(DefaultHttp2ConnectionDecoder.java:702)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2InboundFrameLogger$1.onSettingsRead(Http2InboundFrameLogger.java:93)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2FrameReader.readSettingsFrame(DefaultHttp2FrameReader.java:542)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2FrameReader.processPayloadState(DefaultHttp2FrameReader.java:263)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:160)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:174)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:378)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.decode(Http2ConnectionHandler.java:242)
    at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:438)
    at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:501)
    at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:440)
    at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
    at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
    at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
    at io.grpc.netty.shaded.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:714)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:650)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:576)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
    at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
    at io.grpc.netty.shaded.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    ... 1 more

This occurs without any code changes (just added that one dep to build.gradle), so I'm guessing this is an incompatible jar issue caused by the new dependency (as suggested by this comment). Since I'm on gradle 4.10.1, I can't resolve this with a pom. How does one go about resolving this?


问:
How to deserialize a protobuf bytearray to java object
New to protobuf, need your kind advice please.

I have a JMS subscriber which is receiving a message (Type -> com.tibco.tibjmsTibjmsBytesMessage) from a TIBCO queue. The messages have been published as Protobuf bytes message on the queue. As as subscriber I have converted these bytesMessage to byte array. Since I have the protobuf message's JAVA class protoFile.class, hence in order to deserialize the byte array, I am calling the protoFile.parseFrom(byte[] data) function. However in response I see that the values of all the fields are empty.

Can someone please suggest what is being missed ?
All I need is to read the data from my Protobuf bytes message and assign them to java objects.
I do not have the schema of the proto file, only have the compiled JAVA class of the proto file say protoFile.class

TIA!

答:
A protobuf message does not have the class name in the data stream. This I think is done because the language of origin can be different than the receiver's language. The receive's end point would expect a given type and have proto generated code to convert it. If you restrict your world to Java on both ends, you could send the class name along with the data. You could even use another proto message to do that. Then assume that all messages are of that type. The real message and type are wrapped up in that message. Then you have the classname and the data. Here's a MessageConverter for Jms that you could grab parts of it that fits your situation.

The proto file

```<code>syntax = "proto3";
package jms;

option java_package = "some.package.here.jms";
option java_multiple_files = true;

message AnyMessage{
  string classname = 1;
  bytes bytesData = 2;
}
</code>```

The code

```<code>@Slf4j
public class ProtobufJmsMessageConverter implements MessageConverter {

@Override
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
    GeneratedMessageV3 protoMsg = (GeneratedMessageV3) object;

    AnyMessage wrap = AnyMessage.newBuilder().setClassname(object.getClass().getName()).setBytesData(protoMsg.toByteString()).build();

    BytesMessage bytesMessage = session.createBytesMessage();
    bytesMessage.writeBytes(wrap.toByteArray());
    return bytesMessage;
}

@Override
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
    BytesMessage bytesMessage = (BytesMessage) message;
    int messageLength = (int) bytesMessage.getBodyLength();
    byte[] rawProtoMsg = new byte[messageLength];
    bytesMessage.readBytes(rawProtoMsg);
    try {
        AnyMessage anyMessage = AnyMessage.parseFrom(rawProtoMsg);
        Class protoClass = Class.forName(anyMessage.getClassname());

        Method m = protoClass.getMethod("parseFrom", byte[].class);
        Object result = m.invoke(null, anyMessage.getBytesData().toByteArray());
        return result;
    } catch (InvalidProtocolBufferException | ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        log.error("",e);
        throw new MessageConversionException("Only AnyMessage should be sent.", e);
    }
}

}
</code>```

Body:
A protobuf message does not have the class name in the data stream. This I think is done because the language of origin can be different than the receiver's language. The receive's end point would expect a given type and have proto generated code to convert it. If you restrict your world to Java on both ends, you could send the class name along with the data. You could even use another proto message to do that. Then assume that all messages are of that type. The real message and type are wrapped up in that message. Then you have the classname and the data. Here's a MessageConverter for Jms that you could grab parts of it that fits your situation.

The proto file

syntax = "proto3";
package jms;

option java_package = "some.package.here.jms";
option java_multiple_files = true;

message AnyMessage{
  string classname = 1;
  bytes bytesData = 2;
}

The code

@Slf4j
public class ProtobufJmsMessageConverter implements MessageConverter {

@Override
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
    GeneratedMessageV3 protoMsg = (GeneratedMessageV3) object;

    AnyMessage wrap = AnyMessage.newBuilder().setClassname(object.getClass().getName()).setBytesData(protoMsg.toByteString()).build();

    BytesMessage bytesMessage = session.createBytesMessage();
    bytesMessage.writeBytes(wrap.toByteArray());
    return bytesMessage;
}

@Override
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
    BytesMessage bytesMessage = (BytesMessage) message;
    int messageLength = (int) bytesMessage.getBodyLength();
    byte[] rawProtoMsg = new byte[messageLength];
    bytesMessage.readBytes(rawProtoMsg);
    try {
        AnyMessage anyMessage = AnyMessage.parseFrom(rawProtoMsg);
        Class protoClass = Class.forName(anyMessage.getClassname());

        Method m = protoClass.getMethod("parseFrom", byte[].class);
        Object result = m.invoke(null, anyMessage.getBytesData().toByteArray());
        return result;
    } catch (InvalidProtocolBufferException | ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        log.error("",e);
        throw new MessageConversionException("Only AnyMessage should be sent.", e);
    }
}

}


问:
Can not find a (Map) Key deserializer for type [simple type, class com.example.app.ReferralApiModel]
I'm trying to fetch JSON data from my website throw REST API with retrofit2.
But when I run the app this error message show:

Can not find a (Map) Key deserializer for type [simple type, class com.example.app.ReferralApiModel]

I'm using retrofit library.

This is my code for the retrofit call:

```<code>Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.URL)
                .addConverterFactory(JacksonConverterFactory.create())
                .client(defaultHttpClient)
                .build();

        ReferralsPlaceHolderApi placeHolderApi = retrofit.create(ReferralsPlaceHolderApi.class);

        Call<List<Map<ReferralApiModel, String>>> call = placeHolderApi.getReferrals();
</code>```

And this is my ReferralsPlaceHolderApi class:

```<code>public interface ReferralsPlaceHolderApi {

    @JsonDeserialize(keyAs = ReferralsCustomDeserializer.class)
    @GET(AppConfig.ENDPOINT_REFERRALS)
    Call<List<Map<ReferralApiModel, String>>> getReferrals();
}
</code>```

Also this is my ReferralApiModel class:

```<code>public class ReferralApiModel {
    private String date;
    private String amount;
    private String currency;
    private String status;

    public ReferralApiModel() {}

    public ReferralApiModel(String date, String amount, String currency, String status) {
        this.date = date;
        this.amount = amount;
        this.currency = currency;
        this.status = status;
    }

    public String getDate() {
        return date;
    }

    public String getAmount() {
        return amount;
    }

    public String getCurrency() {
        return currency;
    }

    public String getStatus() {
        return status;
    }
}
</code>```

This is the json data that I'm trying to get:

```<code>"[{\"id\":\"1\",\"refferal_wp_uid\":\"0\",\"campaign\":\"\",\"affiliate_id\":\"5\",\"visit_id\":\"1\",\"description\":\"\",\"source\":\"woo\",\"reference\":\"302\",\"reference_details\":\"68\",\"parent_referral_id\":\"0\",\"child_referral_id\":\"0\",\"amount\":\"1500.00\",\"currency\":\"\د\ج\",\"date\":\"2022-01-31 12:53:29\",\"status\":\"0\",\"payment\":\"0\",\"username\":\"aaa\"},{\"id\":\"2\",\"refferal_wp_uid\":\"0\",\"campaign\":\"\",\"affiliate_id\":\"5\",\"visit_id\":\"2\",\"description\":\"\",\"source\":\"woo\",\"reference\":\"303\",\"reference_details\":\"68\",\"parent_referral_id\":\"0\",\"child_referral_id\":\"0\",\"amount\":\"1500.00\",\"currency\":\"\د\ج\",\"date\":\"2022-01-31 13:03:43\",\"status\":\"1\",\"payment\":\"0\",\"username\":\"aaa\"},{\"id\":\"3\",\"refferal_wp_uid\":\"0\",\"campaign\":\"\",\"affiliate_id\":\"5\",\"visit_id\":\"2\",\"description\":\"\",\"source\":\"woo\",\"reference\":\"304\",\"reference_details\":\"68\",\"parent_referral_id\":\"0\",\"child_referral_id\":\"0\",\"amount\":\"1500.00\",\"currency\":\"\د\ج\",\"date\":\"2022-01-31 13:04:33\",\"status\":\"2\",\"payment\":\"0\",\"username\":\"aaa\"}]"
</code>```

Can anyone help me with this?.

Also I've found that this problem may be a class mapping problem, from this answer :
https://stackoverflow.com/a/16383752/8055951
If it's ?!, Can someone tell me how to map the ReferralsPlaceHolderApi class.

Thanks.

答:
Jackson cannot deserialize custom classes as map keys. The key of your deserialized map is ReferralApiModel. I order to achieve it, you need to write your own KeyDeserializer and register it for your class with Jackson. You can see here or here how to do that.

Also the json string in the question makes it look as if you don't need to deserialize into List<Map<ReferralApiModel, String>>, but into List<ReferralApiModel> instead. Which would make writing custom key deseriaslizers redundant.

Edit: Ok, receiving json array, which has been json sting-ified is just strange. It would be best, if someone on your team is responsible for this API and can fix it. If not, you have workarounds:

Parse twice with object mapper - first parse it to normal string, which would be json array, then parse this string into List<YourObject>

```<code>ObjectMapper mapper = new ObjectMapper();
String string = mapper.readValue(initialJson, String.class);
List<ReferralApiModel> list = mapper.readValue(string, TypeFactory.defaultInstance().constructCollectionType(List.class, ReferralApiModel.class));
list.forEach(System.out::println);
</code>```

Turn it manually into proper json array. That means remove first and last char - double quote, and remove all those escapes - \. Something like this:

```<code>String jsonString = "the string";
jsonString = jsonString.substring(1, jsonString.length() - 1).replace("\\", "");

ObjectMapper mapper = new ObjectMapper();
List<ReferralApiModel> list = mapper.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(List.class, ReferralApiModel.class));
list.forEach(System.out::println);
</code>```

Body:
I'm trying to fetch JSON data from my website throw REST API with retrofit2.
But when I run the app this error message show:

Can not find a (Map) Key deserializer for type [simple type, class com.example.app.ReferralApiModel]

I'm using retrofit library.

This is my code for the retrofit call:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.URL)
                .addConverterFactory(JacksonConverterFactory.create())
                .client(defaultHttpClient)
                .build();

        ReferralsPlaceHolderApi placeHolderApi = retrofit.create(ReferralsPlaceHolderApi.class);

        Call<List<Map<ReferralApiModel, String>>> call = placeHolderApi.getReferrals();

And this is my ReferralsPlaceHolderApi class:

public interface ReferralsPlaceHolderApi {

    @JsonDeserialize(keyAs = ReferralsCustomDeserializer.class)
    @GET(AppConfig.ENDPOINT_REFERRALS)
    Call<List<Map<ReferralApiModel, String>>> getReferrals();
}

Also this is my ReferralApiModel class:

public class ReferralApiModel {
    private String date;
    private String amount;
    private String currency;
    private String status;

    public ReferralApiModel() {}

    public ReferralApiModel(String date, String amount, String currency, String status) {
        this.date = date;
        this.amount = amount;
        this.currency = currency;
        this.status = status;
    }

    public String getDate() {
        return date;
    }

    public String getAmount() {
        return amount;
    }

    public String getCurrency() {
        return currency;
    }

    public String getStatus() {
        return status;
    }
}

This is the json data that I'm trying to get:

"[{\"id\":\"1\",\"refferal_wp_uid\":\"0\",\"campaign\":\"\",\"affiliate_id\":\"5\",\"visit_id\":\"1\",\"description\":\"\",\"source\":\"woo\",\"reference\":\"302\",\"reference_details\":\"68\",\"parent_referral_id\":\"0\",\"child_referral_id\":\"0\",\"amount\":\"1500.00\",\"currency\":\"\د\ج\",\"date\":\"2022-01-31 12:53:29\",\"status\":\"0\",\"payment\":\"0\",\"username\":\"aaa\"},{\"id\":\"2\",\"refferal_wp_uid\":\"0\",\"campaign\":\"\",\"affiliate_id\":\"5\",\"visit_id\":\"2\",\"description\":\"\",\"source\":\"woo\",\"reference\":\"303\",\"reference_details\":\"68\",\"parent_referral_id\":\"0\",\"child_referral_id\":\"0\",\"amount\":\"1500.00\",\"currency\":\"\د\ج\",\"date\":\"2022-01-31 13:03:43\",\"status\":\"1\",\"payment\":\"0\",\"username\":\"aaa\"},{\"id\":\"3\",\"refferal_wp_uid\":\"0\",\"campaign\":\"\",\"affiliate_id\":\"5\",\"visit_id\":\"2\",\"description\":\"\",\"source\":\"woo\",\"reference\":\"304\",\"reference_details\":\"68\",\"parent_referral_id\":\"0\",\"child_referral_id\":\"0\",\"amount\":\"1500.00\",\"currency\":\"\د\ج\",\"date\":\"2022-01-31 13:04:33\",\"status\":\"2\",\"payment\":\"0\",\"username\":\"aaa\"}]"

Can anyone help me with this?.

Also I've found that this problem may be a class mapping problem, from this answer :
https://stackoverflow.com/a/16383752/8055951
If it's ?!, Can someone tell me how to map the ReferralsPlaceHolderApi class.

Thanks.

Body:
Jackson cannot deserialize custom classes as map keys. The key of your deserialized map is ReferralApiModel. I order to achieve it, you need to write your own KeyDeserializer and register it for your class with Jackson. You can see here or here how to do that.

Also the json string in the question makes it look as if you don't need to deserialize into List<Map<ReferralApiModel, String>>, but into List<ReferralApiModel> instead. Which would make writing custom key deseriaslizers redundant.

Edit: Ok, receiving json array, which has been json sting-ified is just strange. It would be best, if someone on your team is responsible for this API and can fix it. If not, you have workarounds:

Parse twice with object mapper - first parse it to normal string, which would be json array, then parse this string into List<YourObject>

ObjectMapper mapper = new ObjectMapper();
String string = mapper.readValue(initialJson, String.class);
List<ReferralApiModel> list = mapper.readValue(string, TypeFactory.defaultInstance().constructCollectionType(List.class, ReferralApiModel.class));
list.forEach(System.out::println);

Turn it manually into proper json array. That means remove first and last char - double quote, and remove all those escapes - \. Something like this:

String jsonString = "the string";
jsonString = jsonString.substring(1, jsonString.length() - 1).replace("\\", "");

ObjectMapper mapper = new ObjectMapper();
List<ReferralApiModel> list = mapper.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(List.class, ReferralApiModel.class));
list.forEach(System.out::println);


问:
Using mod_rewrite to convert folders to querystring
What's the easiest way to convert these requests:

```<code>http://www.example.com/en/
http://www.example.com/en/index.php
</code>```

To:

```<code>http://www.example.com/index.php?language_id=en
</code>```

There's various PHP files, so the rule would also need to map

```<code>http://www.example.com/en/anyfile.php
</code>```

To:

```<code>http://www.example.com/anyfile.php?language_id=en
</code>```

The language ID can be any two letter code (it's checked within the PHP script, to ensure it's valid).

Presumably, I'll need to use .htaccess, and any advice on how to implement the above would be greatly appreciated.  Thanks.

Update

The following worked for me.

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ([a-z]+)/(css|js|images)/(.+) /$2/$3 [L]
  RewriteRule ([a-z]+)/(.+).php /$2.php?language_id=$1 [QSA,L]
  RewriteRule ([a-z]+)/$ /index.php?language_id=$1 [QSA,L]
</IfModule>
</code>```

This also re-routes requests to the css, js, and images folders back to the root folder.  It also works if no filename is entered, automatically redirecting to index.php.

OwnerDisplayName: Mun

ContentLicense: CC BY-SA 2.5

Body:
What's the easiest way to convert these requests:

http://www.example.com/en/
http://www.example.com/en/index.php

To:

http://www.example.com/index.php?language_id=en

There's various PHP files, so the rule would also need to map

http://www.example.com/en/anyfile.php

To:

http://www.example.com/anyfile.php?language_id=en

The language ID can be any two letter code (it's checked within the PHP script, to ensure it's valid).

Presumably, I'll need to use .htaccess, and any advice on how to implement the above would be greatly appreciated.  Thanks.

Update

The following worked for me.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ([a-z]+)/(css|js|images)/(.+) /$2/$3 [L]
  RewriteRule ([a-z]+)/(.+).php /$2.php?language_id=$1 [QSA,L]
  RewriteRule ([a-z]+)/$ /index.php?language_id=$1 [QSA,L]
</IfModule>

This also re-routes requests to the css, js, and images folders back to the root folder.  It also works if no filename is entered, automatically redirecting to index.php.

LastEditorDisplayName: Mun

Body: RewriteRule /([^/]+)/(.*) /$2?language_id=$1

OwnerDisplayName: vartec


问:
Hardhat - How to get the block in timestamp in deployment file
I try to deploy my masterchef contract. I have 2 arguments to specify in the constructor (the token address and the actual block number in secondes). I use hardhat for doing this and I actually trying to get the value of the actuel block number in secondes ? How can I do this ?</p>
```<code>const StakingRewards = await hre.ethers.getContractFactory("Masterchef");
const stakingRewards = await StakingRewards.deploy(token.address, block.timestamp);
</code>```

答:
You can get the timestamp of the previous block like this:

// getting timestamp
const blockNumBefore = await ethers.provider.getBlockNumber();
const blockBefore = await ethers.provider.getBlock(blockNumBefore);
const timestampBefore = blockBefore.timestamp;
```

Body:
I try to deploy my masterchef contract. I have 2 arguments to specify in the constructor (the token address and the actual block number in secondes). I use hardhat for doing this and I actually trying to get the value of the actuel block number in secondes ? How can I do this ?

const StakingRewards = await hre.ethers.getContractFactory("Masterchef");
const stakingRewards = await StakingRewards.deploy(token.address, block.timestamp);


问:
Initialising a C vector pointer throws a bus error but initialising a vector doesn't
This C code:

```<code>#include <stdlib.h>

typedef struct
{
    int *a;
    int sz, cap;
} Vector;

void vector_init(Vector *v)
{
    v->a = (int *)malloc(sizeof(int));
    v->sz = 0;
    v->cap = 1;
}

int main()
{
    Vector *v;
    vector_init(v);
}
</code>```

throws a bus error.
but replacing Vector *v with Vector v and vector_init(v) with vector_init(&v) solves it. why?

答:
When you write Vector *v, you're creating an uninitialized pointer to Vector. There's no object of type Vector that exists in this program. v is uninitialized, dereferencing it is undefined behaviour, and in practice will often lead to a crash because of an illegal memory access.

Defining a pointer does not automatically create memory for an object of the pointed-to type, you need to do that.

Doing Vector v with vector_init(&v) works because you're creating an actual object of type Vector, then passing in a pointer to that.

To have an object of type Vector *, you have to give it an object to point to. That could be by explicitly creating an object:

```<code>Vector v_storage;
Vector *v = &v_storage;
vector_init(v);
</code>```

Though it'd be silly to do the above in actual code, you should just stick with the Vector v and vector_init(&v).

You could also create storage for a Vector using a dynamic memory allocation using malloc, if that was appropriate for what you want to write, and then clean it up with free later.

Body:
This C code:

#include <stdlib.h>

typedef struct
{
    int *a;
    int sz, cap;
} Vector;

void vector_init(Vector *v)
{
    v->a = (int *)malloc(sizeof(int));
    v->sz = 0;
    v->cap = 1;
}

int main()
{
    Vector *v;
    vector_init(v);
}

throws a bus error.
but replacing Vector *v with Vector v and vector_init(v) with vector_init(&v) solves it. why?

Body:
When you write Vector *v, you're creating an uninitialized pointer to Vector. There's no object of type Vector that exists in this program. v is uninitialized, dereferencing it is undefined behaviour, and in practice will often lead to a crash because of an illegal memory access.

Defining a pointer does not automatically create memory for an object of the pointed-to type, you need to do that.

Doing Vector v with vector_init(&v) works because you're creating an actual object of type Vector, then passing in a pointer to that.

To have an object of type Vector *, you have to give it an object to point to. That could be by explicitly creating an object:

Vector v_storage;
Vector *v = &v_storage;
vector_init(v);

Though it'd be silly to do the above in actual code, you should just stick with the Vector v and vector_init(&v).

You could also create storage for a Vector using a dynamic memory allocation using malloc, if that was appropriate for what you want to write, and then clean it up with free later.


问:
Flutter: How can delete from firebase an array of objects?
I have this list with user products and I want to delete a product on button clic. Products ara store in firebase inside user doc as a Map products:[nameProduct:'',owned:'']
Can u help me to figure how to delete a prodruct?</p>
```<code>List.generate(
          userData['products'].length,
          (index) => ListTile(
              contentPadding: const EdgeInsets.only(
                 right: 15,
                 left: 15,
                 top: 0,
              ),
              title: Text(
                       userData['products'][index]['nameProducts'],
                       style: const TextStyle(letterSpacing: 2.0)),
                       subtitle: Text(productOwnedFunction(userData, index)),
                       trailing: IconButton(
                                  icon: const Icon(CupertinoIcons.trash),
                                  onPressed: () async {
                                    try {
                                      await FirebaseFirestore.instance
                                          .collection('users')
                                          .doc(userData['uid'])
                                          .update(
                                        {
                                          'products':
                                              FieldValue.arrayRemove(
                                                  [index])
                                        },
                                      );
                                    } catch (e) {
                                      print(e);
                                    }
                                  },
                                ),
                              )),
</code>```

答:
You can't remove an item from an array by its index in Firestore API.

If you know the entire object to remove (so know all fields), you can pass that entire object to FieldValue.arrayRemove().

If all you have is the index of the item to remove, you'll have to:

Read the document from the database and get the array from it.

Modify the array contents in your application code.

Write the entire array back to the databae.

Body:
I have this list with user products and I want to delete a product on button clic. Products ara store in firebase inside user doc as a Map products:[nameProduct:'',owned:'']
Can u help me to figure how to delete a prodruct?

List.generate(
          userData['products'].length,
          (index) => ListTile(
              contentPadding: const EdgeInsets.only(
                 right: 15,
                 left: 15,
                 top: 0,
              ),
              title: Text(
                       userData['products'][index]['nameProducts'],
                       style: const TextStyle(letterSpacing: 2.0)),
                       subtitle: Text(productOwnedFunction(userData, index)),
                       trailing: IconButton(
                                  icon: const Icon(CupertinoIcons.trash),
                                  onPressed: () async {
                                    try {
                                      await FirebaseFirestore.instance
                                          .collection('users')
                                          .doc(userData['uid'])
                                          .update(
                                        {
                                          'products':
                                              FieldValue.arrayRemove(
                                                  [index])
                                        },
                                      );
                                    } catch (e) {
                                      print(e);
                                    }
                                  },
                                ),
                              )),


问:
WebRTC Recording Size
After few hours of research I can't find a solution to my problem and it seems impossible.

I built a simple WebRTC chat (2 clients) where you can create / join a room.

When two clients join the same room they can talk to each other. I have one localStream which is the local user camera and one remoteStream which is the other client camera from the PeerConnection.

I created a button that allows me to start a recording (local) of the remoteStream video. So my client 1 press this button and start record the video of the client 2.

My problem is when I check video data from the remoteStream the frame rate and the video resolution change over time. When I start recording the MediaRecorder grab the current remoteStream size and create a blob which contain my video. Later I can download this video by stopping the recording and download the blob. The problem is the size (definition) of the final video will depend on the current remoteStream size when the user click the button.

So if we are unlucky we will get an entire 360p video for example, if we start the recording later we can have a 1000p video or 868p or other random value between 1p and 2160p. So the video size will depend on the timing and will never be the same.

Is that possible to create a recording which take a fix video size and ignore this WebRTC fluctuation ?

Regards

答:
WebRTC implements congestion control: the size, framerate and quality of the video is varied depending on the network conditions (packet loss and packet delay).

There are some knobs to control the behaviour.  The one that I've found to be most useful is the contentHint field of MediaStreamTrack; if you set this field to the string detail, then the stack will prefer to reduce framerate rather than reducing the resolution.

At the end of the day, however, there doesn't seem to be anything you can do to forcibly prevent the stack from reducing the resolution when the network conditions are bad, so your code will need to handle that case.

Title: WebRTC Recording Size


问:
How to mock an async function returning a tuple?
I need to test the following function

```<code>class C:
    async def f():
        a, b = await self.g()  # need to mock g
</code>```

However, the following test got the error of TypeError: object tuple can't be used in 'await' expression

```<code>@pytest.mark.asyncio
async def test_f():
    sut = C()
    sut.g = MagicMock(return_value=(1,2)) # TypeError: object tuple can't be used in 'await' expression
    await sut.f()
    sut.g.assert_called_once()
</code>```

答:
Use AsyncMock instead of the MagicMock:

```<code>from unittest.mock import AsyncMock

@pytest.mark.asyncio
async def test_f():
    sut = C()
    sut.g = AsyncMock(return_value=(1,2))
    await sut.f()
    sut.g.assert_called_once()
</code>```

AsyncMock is part of the standard library since Python 3.8; if you need a backport for older versions, install and use the asyncmock package.

Body:
I need to test the following function

class C:
    async def f():
        a, b = await self.g()  # need to mock g

However, the following test got the error of TypeError: object tuple can't be used in 'await' expression

@pytest.mark.asyncio
async def test_f():
    sut = C()
    sut.g = MagicMock(return_value=(1,2)) # TypeError: object tuple can't be used in 'await' expression
    await sut.f()
    sut.g.assert_called_once()

Body:
Use AsyncMock instead of the MagicMock:

from unittest.mock import AsyncMock

@pytest.mark.asyncio
async def test_f():
    sut = C()
    sut.g = AsyncMock(return_value=(1,2))
    await sut.f()
    sut.g.assert_called_once()

AsyncMock is part of the standard library since Python 3.8; if you need a backport for older versions, install and use the asyncmock package.


问:
Analyzing Android APK
After Analyzing Android APK I noticed there is lib folder one of the APK file components
And it taking too much from the Whole APK file size, After searching I realised that :

lib/: Contains the compiled code that is specific to the software
layer of a processor. This directory contains a subdirectory for each
platform type, like armeabi, armeabi-v7a, arm64-v8a, x86, x86_64, and
mips.

So My question is how to optimize this file? and Is it important to have it inside APKs
or its ok to exclude it in build file , or use include native lib = false

答:
You can create APKs for specific CPU types. This way only the code for that specific ABI (Application Binary Interface) will be included.

Check out this guide how to configure it in gradle: Build multiple APKs

Alternatively if you only want to upload your app to the Google Play Store anyway, you can create an Android App Bundle (AAB) and upload this. The Play Store will automatically generate APKs for different device configurations and offer smaller APKs to the end users.

Title: Analyzing Android APK