问:
How to get Primary Key and data from Django SessionWizardView
I have a SessionWizardView that generate 3 forms, depending of of a previous choice. After the selection of the form, the user fill the form and submit it to a specific ListView to each case, using POST. The problem are to get these values, mainly the Primary Key.

The SessionWizardView, I followed the documentation (https://django-formtools.readthedocs.io/en/stable/wizard.html#wizard-template-for-each-form) and it's working as I expected. The 3 forms has the last field pre filled, depending from the first field.

In the ListView, I've tried to use request.session.pop() to get the fields from the SessionWizardView. Here I had my first doubt: I used either the variable name in the forms.py  (e.g.:request.session.pop('formField1', {})), and the field id in the POST (request.session.pop('opcao1-formField1', {})). In both cases the browser return the 'int' object has no attribute 'pk' error.

I've tested the 3 forms that the Wizard can show me and all of them show the same error, so I will put the code for the first one, so text stay short.

urls.py:

```<code>logger = logging.getLogger(__name__)

urlpatterns = [
    # path('', views.IndexView.as_view(), name="index"),
    path('', views.IndexView.as_view(views.FORMS), name="index"),
    path('detail/', views.DetailView.as_view(), name="detail"),
</code>```

views.py:

```<code>class IndexView(SessionWizardView):
    condition_dict = {"opcao1" :  graficoEscolhido1,
    "opcao2" :  graficoEscolhido2,
    "opcao3" :  graficoEscolhido3,
    }
    template_name = 'solid/index.html'
    success_url = reverse_lazy('detail')

    def done(self, form_list, **kwargs):
        self.request.session['opcao1-dateDataInicial'] = str(form_list.cleaned_data['opcao1-dateDataInicial'])
        self.request.session['opcao1-dateDataFinal'] = str(form_list.cleaned_data['opcao1-dateDataFinal'])
        self.request.session['opcao1-codigoDuto'] = form_list.cleaned_data['opcao1-codigoDuto']
        self.request.session['opcao1-codigoExtremidade'] = float(form_list.cleaned_data['opcao1-codigoExtremidade'])
        # I've already commented the previous line, trade wizard for
        # request. Put form_list.get_all_cleaned_data(), too as test.
        return render(self.request, "solid/detail.html", {
            'form_data': [form.cleaned_data for form in form_list],
        })

class DetailView(generic.ListView):

    def get_context_data(self, **kwargs):
        cursor = connection.cursor()

        # Trying to get from previous session. I've replaced request for
        # wizard too, in previous attempt.
        inicio = self.request.session.pop('opcao1-dateDataInicial', {})
        final = self.request.session.pop('opcao1-dateDataFinal', {})
        cod_id = self.request.session.pop('opcao1-codigoID', {})
        extra = self.request.session.pop('opcao1-valorExtra', {})

        Temp1 = TEMP.objects.values_list('TE_CD_ID_S_Temp', flat = True).filter(
            TE_CD_ID_Cod = cod_id,
            TE_VL_Ponto = extra)

        Dens1 = DENS.objects.values_list('DE_CD_ID_S_Den', flat = True).filter(
            DE_CD_ID_Cod = cod_id,
            DE_VL_Ponto = extra)

        Vaz1 = VAZ.objects.values_list('VA_CD_ID_S_Vaz', flat = True).filter(
            VA_CD_ID_Cod = cod_id,
            VA_VL_Ponto = extra)

        Pres1 = PRES.objects.values_list('PR_CD_ID_S_Pres', flat = True).filter(
            PR_CD_ID_Cod = cod_id,
            PR_VL_Ponto = extra)

        cursor.execute('giant query',(str(sensorPres[0]), inicio, final,
                        str(sensorTemp[0]), inicio, final,
                        str(sensorDens[0]), inicio, final,
                        str(sensorVaz[0]), inicio, final))

        lista = cursor.fetchall()
        listaArray = np.asarray(lista)
        tempo = listaArray[:,0]

        valpres = listaArray[:,1]
        valpres = np.array(valpres)
        valpres = valpres.astype(float)

        valtemp = listaArray[:,2]
        valtemp = np.array(valtemp)
        valtemp = valtemp.astype(float)

        valden = listaArray[:,3]
        valden = np.array(valden)
        valden = valden.astype(float)

        valvaz = listaArray[:,4]
        valvaz = np.array(valvaz)
        valvaz = valvaz.astype(float)

        kwargs['tempo'] = tempo
        kwargs['valpres'] = valpres
        kwargs['valtemp'] = valtemp
        kwargs['valden'] = valden
        kwargs['valvaz'] = valvaz
        kwargs['dateInicial'] = inicio
        kwargs['dateFinal'] = final

        return super().get_context_data(**kwargs)
</code>```

forms.py:

```<code>class get_Codigo_DutoGrafico1(forms.Form):
# codigoID is a PK in the model.
    codigoID = forms.ModelMultipleChoiceField(label = "Código ID",
        queryset = PRINCIPAL.objects.values_list('CD_ID', flat = True),
        widget = forms.SelectMultiple(attrs = {'id' : 'id_codigo_id'}))
    dateDataInicial = forms.DateTimeField(label = 'Data Inicial',
        input_formats = ['%d/%m/%Y %H:%M:%S'],
        widget=XDSoftDateTimePickerInput())
    dateDataFinal = forms.DateTimeField(label = 'Data Final',
        input_formats = ['%d/%m/%Y %H:%M:%S'],
        widget=XDSoftDateTimePickerInput())
    valorExtra = forms.ModelMultipleChoiceField(label = 'Valor Extra',
        queryset = DENS.objects.values_list('DE_VL_Ponto', flat = True).none(),
        widget = forms.SelectMultiple(attrs = {'id' : 'id_codigoDropDown'}))
</code>```

index.html:

```<code><div class = "container-fluid" id = "wrapper">
    <div class = "row">
        {% load i18n %}
        {% block head %}
        {{ wizard.form.media }}
        {% endblock %}
      {% block content %}
      <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
      <form action = "" method = "post" id = "formGrafico"  data-data-url="{% url 'ajax_load_duto' %}" data-data2-url="{% url 'ajax_load_data2' %}" novalidate>
        {% csrf_token %}
      <table>
      {{ wizard.management_form }}
      {% if wizard.form.forms %}
          {{ wizard.form.management_form }}
          {% for form in wizard.form.forms %}
              {{ form }}
          {% endfor %}
      {% else %}
          {{ wizard.form }}
      {% endif %}
      </table>
      {% if wizard.steps.prev %}
        <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
        <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
      {% endif %}
      <input type="submit" value="{% trans "submit" %}"/>
      </form>
      {% endblock %}
</code>```

I expect to get the values in the detail.html and show the data in different ways. However, I get the following error: 'int' object has no attribute 'pk'. The POST is returning the following:

```<code>POST
Variable    Value
csrfmiddlewaretoken
'TArU7O0laFVnRiWp9rEpUOE4bUoPNYulB2zNkFbwnLFxbVBwr4Qmp7ZQ5FfhJ3r7'
index_view-current_step
'opcao1'
opcao1-codigoDuto
'177'
opcao1-dateDataInicial
'03/05/2018 10:19:00'
opcao1-dateDataFinal
'01/07/2018 10:20:00'
opcao1-codigoExtremidade
'2,127000000000000'
</code>```

The entire error traceback:

```<code>Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/

Django Version: 2.1.7
Python Version: 3.6.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'compressor',
 'django_extensions',
 'solid',
 'sekizai',
 'formtools']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/formtools/wizard/views.py" in dispatch
  248.         response = super(WizardView, self).dispatch(request, *args, **kwargs)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/formtools/wizard/views.py" in post
  301.         if form.is_valid():

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/forms.py" in is_valid
  185.         return self.is_bound and not self.errors

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/forms.py" in errors
  180.             self.full_clean()

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/forms.py" in full_clean
  381.         self._clean_fields()

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/forms.py" in _clean_fields
  399.                     value = field.clean(value)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/models.py" in clean
  1293.         qs = self._check_values(value)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/models.py" in _check_values
  1326.         pks = {str(getattr(o, key)) for o in qs}

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/models.py" in <setcomp>
  1326.         pks = {str(getattr(o, key)) for o in qs}

Exception Type: AttributeError at /
Exception Value: 'int' object has no attribute 'pk'
</code>```

So the data is passing from SessionWizardView, but something in the middle is wrong. To test the 'int' problem, I've set str() to the "cod_id" and still got 'int' error message. I've searched in the Stack something related to it, but I found nothing.

答:
The error is because your ModelMultipleChoiceField has a queryset attribute set to an integer list, that's wrong, your queryset should be a list of objects: PRINCIPAL.objects.all(). The ModelMultipleChoiceField receives an integer as input (the posted data), but wants an object (PRINCIPAL) as value.

If you want to customise how the values are displayed to the user, you should subclass ModelMultipleChoiceField and override the label_from_instance method:

```<code>class IDModelMultipleChoiceField(ModelMultipleChoiceField):
    def label_from_instance(self, instance):
        return instance.pk
</code>```

and in your form

```<code>cogidoID = IDModelMultipleChoiceField(queryset=..., label=...)
</code>```

Body:
I have a SessionWizardView that generate 3 forms, depending of of a previous choice. After the selection of the form, the user fill the form and submit it to a specific ListView to each case, using POST. The problem are to get these values, mainly the Primary Key.

The SessionWizardView, I followed the documentation (https://django-formtools.readthedocs.io/en/stable/wizard.html#wizard-template-for-each-form) and it's working as I expected. The 3 forms has the last field pre filled, depending from the first field.

In the ListView, I've tried to use request.session.pop() to get the fields from the SessionWizardView. Here I had my first doubt: I used either the variable name in the forms.py  (e.g.:request.session.pop('formField1', {})), and the field id in the POST (request.session.pop('opcao1-formField1', {})). In both cases the browser return the 'int' object has no attribute 'pk' error.

I've tested the 3 forms that the Wizard can show me and all of them show the same error, so I will put the code for the first one, so text stay short.

urls.py:

logger = logging.getLogger(__name__)

urlpatterns = [
    # path('', views.IndexView.as_view(), name="index"),
    path('', views.IndexView.as_view(views.FORMS), name="index"),
    path('detail/', views.DetailView.as_view(), name="detail"),

views.py:

class IndexView(SessionWizardView):
    condition_dict = {"opcao1" :  graficoEscolhido1,
    "opcao2" :  graficoEscolhido2,
    "opcao3" :  graficoEscolhido3,
    }
    template_name = 'solid/index.html'
    success_url = reverse_lazy('detail')

    def done(self, form_list, **kwargs):
        self.request.session['opcao1-dateDataInicial'] = str(form_list.cleaned_data['opcao1-dateDataInicial'])
        self.request.session['opcao1-dateDataFinal'] = str(form_list.cleaned_data['opcao1-dateDataFinal'])
        self.request.session['opcao1-codigoDuto'] = form_list.cleaned_data['opcao1-codigoDuto']
        self.request.session['opcao1-codigoExtremidade'] = float(form_list.cleaned_data['opcao1-codigoExtremidade'])
        # I've already commented the previous line, trade wizard for
        # request. Put form_list.get_all_cleaned_data(), too as test.
        return render(self.request, "solid/detail.html", {
            'form_data': [form.cleaned_data for form in form_list],
        })

class DetailView(generic.ListView):

    def get_context_data(self, **kwargs):
        cursor = connection.cursor()

        # Trying to get from previous session. I've replaced request for
        # wizard too, in previous attempt.
        inicio = self.request.session.pop('opcao1-dateDataInicial', {})
        final = self.request.session.pop('opcao1-dateDataFinal', {})
        cod_id = self.request.session.pop('opcao1-codigoID', {})
        extra = self.request.session.pop('opcao1-valorExtra', {})

        Temp1 = TEMP.objects.values_list('TE_CD_ID_S_Temp', flat = True).filter(
            TE_CD_ID_Cod = cod_id,
            TE_VL_Ponto = extra)

        Dens1 = DENS.objects.values_list('DE_CD_ID_S_Den', flat = True).filter(
            DE_CD_ID_Cod = cod_id,
            DE_VL_Ponto = extra)

        Vaz1 = VAZ.objects.values_list('VA_CD_ID_S_Vaz', flat = True).filter(
            VA_CD_ID_Cod = cod_id,
            VA_VL_Ponto = extra)

        Pres1 = PRES.objects.values_list('PR_CD_ID_S_Pres', flat = True).filter(
            PR_CD_ID_Cod = cod_id,
            PR_VL_Ponto = extra)

        cursor.execute('giant query',(str(sensorPres[0]), inicio, final,
                        str(sensorTemp[0]), inicio, final,
                        str(sensorDens[0]), inicio, final,
                        str(sensorVaz[0]), inicio, final))

        lista = cursor.fetchall()
        listaArray = np.asarray(lista)
        tempo = listaArray[:,0]

        valpres = listaArray[:,1]
        valpres = np.array(valpres)
        valpres = valpres.astype(float)

        valtemp = listaArray[:,2]
        valtemp = np.array(valtemp)
        valtemp = valtemp.astype(float)

        valden = listaArray[:,3]
        valden = np.array(valden)
        valden = valden.astype(float)

        valvaz = listaArray[:,4]
        valvaz = np.array(valvaz)
        valvaz = valvaz.astype(float)

        kwargs['tempo'] = tempo
        kwargs['valpres'] = valpres
        kwargs['valtemp'] = valtemp
        kwargs['valden'] = valden
        kwargs['valvaz'] = valvaz
        kwargs['dateInicial'] = inicio
        kwargs['dateFinal'] = final

        return super().get_context_data(**kwargs)

forms.py:

class get_Codigo_DutoGrafico1(forms.Form):
# codigoID is a PK in the model.
    codigoID = forms.ModelMultipleChoiceField(label = "Código ID",
        queryset = PRINCIPAL.objects.values_list('CD_ID', flat = True),
        widget = forms.SelectMultiple(attrs = {'id' : 'id_codigo_id'}))
    dateDataInicial = forms.DateTimeField(label = 'Data Inicial',
        input_formats = ['%d/%m/%Y %H:%M:%S'],
        widget=XDSoftDateTimePickerInput())
    dateDataFinal = forms.DateTimeField(label = 'Data Final',
        input_formats = ['%d/%m/%Y %H:%M:%S'],
        widget=XDSoftDateTimePickerInput())
    valorExtra = forms.ModelMultipleChoiceField(label = 'Valor Extra',
        queryset = DENS.objects.values_list('DE_VL_Ponto', flat = True).none(),
        widget = forms.SelectMultiple(attrs = {'id' : 'id_codigoDropDown'}))

index.html:

        {% load i18n %}
        {% block head %}
        {{ wizard.form.media }}
        {% endblock %}
      {% block content %}

Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}

      <form action = "" method = "post" id = "formGrafico"  data-data-url="{% url 'ajax_load_duto' %}" data-data2-url="{% url 'ajax_load_data2' %}" novalidate>
        {% csrf_token %}

      {{ wizard.management_form }}
      {% if wizard.form.forms %}
          {{ wizard.form.management_form }}
          {% for form in wizard.form.forms %}
              {{ form }}
          {% endfor %}
      {% else %}
          {{ wizard.form }}
      {% endif %}

      {% if wizard.steps.prev %}
        <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
        <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
      {% endif %}
      <input type="submit" value="{% trans "submit" %}"/>
      </form>
      {% endblock %}

I expect to get the values in the detail.html and show the data in different ways. However, I get the following error: 'int' object has no attribute 'pk'. The POST is returning the following:

POST
Variable    Value
csrfmiddlewaretoken
'TArU7O0laFVnRiWp9rEpUOE4bUoPNYulB2zNkFbwnLFxbVBwr4Qmp7ZQ5FfhJ3r7'
index_view-current_step
'opcao1'
opcao1-codigoDuto
'177'
opcao1-dateDataInicial
'03/05/2018 10:19:00'
opcao1-dateDataFinal
'01/07/2018 10:20:00'
opcao1-codigoExtremidade
'2,127000000000000'

The entire error traceback:

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/

Django Version: 2.1.7
Python Version: 3.6.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'compressor',
 'django_extensions',
 'solid',
 'sekizai',
 'formtools']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/formtools/wizard/views.py" in dispatch
  248.         response = super(WizardView, self).dispatch(request, *args, **kwargs)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/formtools/wizard/views.py" in post
  301.         if form.is_valid():

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/forms.py" in is_valid
  185.         return self.is_bound and not self.errors

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/forms.py" in errors
  180.             self.full_clean()

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/forms.py" in full_clean
  381.         self._clean_fields()

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/forms.py" in _clean_fields
  399.                     value = field.clean(value)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/models.py" in clean
  1293.         qs = self._check_values(value)

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/models.py" in _check_values
  1326.         pks = {str(getattr(o, key)) for o in qs}

File "/home/luiz/Projeto/Solid/venv/lib/python3.6/site-packages/django/forms/models.py" in <setcomp>
  1326.         pks = {str(getattr(o, key)) for o in qs}

Exception Type: AttributeError at /
Exception Value: 'int' object has no attribute 'pk'

So the data is passing from SessionWizardView, but something in the middle is wrong. To test the 'int' problem, I've set str() to the "cod_id" and still got 'int' error message. I've searched in the Stack something related to it, but I found nothing.

Body:
The error is because your ModelMultipleChoiceField has a queryset attribute set to an integer list, that's wrong, your queryset should be a list of objects: PRINCIPAL.objects.all(). The ModelMultipleChoiceField receives an integer as input (the posted data), but wants an object (PRINCIPAL) as value.

If you want to customise how the values are displayed to the user, you should subclass ModelMultipleChoiceField and override the label_from_instance method:

class IDModelMultipleChoiceField(ModelMultipleChoiceField):
    def label_from_instance(self, instance):
        return instance.pk

and in your form

cogidoID = IDModelMultipleChoiceField(queryset=..., label=...)


来源: stackexchange

问:
DynamoDB not triggering lambda
I'm experimenting with dynamo db and lambda and am having trouble with the following flow:

Lambda A is triggered by a put to S3 event. It takes the object, an audio file, calculates its duration and writes a record in dynamoDB for each 30 second segment.

Lambda B is triggered by dynamoDB, downloads the file from S3 and operates on the 30 second record defined in the dynamo row.

My trouble is that when I run this flow, function A writes all of the rows required to dynamo, by function B

Does not seem to be triggered for each row in dynamo

Times out after 5 minutes.

Configuration

Function B is set with the highest memory and 5 minute expiration

The trigger is set with a batch size of 1 and starting position latest

Things I've confirmed

When function B is triggered, the download from S3 happens fast. This does not seem to be the blocker

When I trigger function B with a test event it executes perfectly.

When I look at the cloudwatch metrics, function B has a nearly 100% error rate in invocation. I can't tell if this means he function was invoked and had an error or could not be invoked at all.

Has anyone had similar issues? Any idea what to check next?
Thanks

答:
I had the same problem, the solution was to create a VERSION from the Lambda and NOT to use the $LATEST Version, but a 'fixed' one.

It is not possible to use the latest ever-changing version to build a trigger upon.

Place to do that:
Lambda / Functions / YourLambdaName / Qualifiers Dropdown on the page / Switch versions/aliases / Version Tab -> check that you have a version

If not -> Actions / Publish new version

ContentLicense: CC BY-SA 3.0

Title: DynamoDB not triggering lambda

ContentLicense: CC BY-SA 4.0


问:
Location to save api token?
I'm not sure which is gonna be the best location to save API key which users generating by providing email address and password, right now I'm finding temporary direction on their machine and saving it there.

But I'm not sure if it is the best approach.

Notes:

API key has to be regenerated every 6 or 12 hours (depends).

I can't save it in the cache memory, because API endpoint which returning API key for another endpoint (which requires email and password) is rate-limited by 5 requests a day.

答:
You have to create an express-session: https://www.npmjs.com/package/express-sessions

Store Session:

```<code>let session = require("express-session");

app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: true,
    cookie: {secure: true,
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24
    }
}));
</code>```

Use:

```<code>router.route("/login")
    .post(function(req, res) {

        req.session.Auth = req.body.user // => user values?
    })
</code>```

Title: Location to save api token?

Body:
You have to create an express-session: https://www.npmjs.com/package/express-sessions

Store Session:

let session = require("express-session");

app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: true,
    cookie: {secure: true,
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24
    }
}));

Use:

router.route("/login")
    .post(function(req, res) {

        req.session.Auth = req.body.user // => user values?
    })


问:
Saving timestamp in mysql table using php
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

```<code>INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')
</code>```

答: Datatype 'bigint unsigned' may suit this requirement.

Body:
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')


问:
Removing duplicates from List<double[]>
I am trying to remove the duplicates from a list of double arrays. I would like to keep the first instance of the duplicate but remove any found after.

Here is my code:

```<code>private static List<double[]> RemoveDupes(List<double[]> locData)
    {
        List<double[]> list = locData;
        while (ContainsDupes(list))
            for (int a = 0; a < list.Count; a++)
                for (int b = 0; b < list.Count; b++)
                    if (a != b && list[a][0] == list[b][0] && list[a][1] == list[b][1])
                        list.RemoveAt(b);

        return list;
    }
private static bool ContainsDupes(List<double[]> list)
    {
        for (int a = 0; a < list.Count; a++)
            for (int b = 0; b < list.Count; b++)
                if (a != b && list[a][0] == list[b][0] && list[a][1] == list[b][1])
                    return true;
        return false;
    }
</code>```

This method works almost all of the time but it's slow and in edge cases (1 out of a few thousand) it crashes my program with an index exception on line 6. I can't think of any other way to do this so any help would be appreciated.

Input:

```<code>{{45.5, 23.6}, {34.54, 98.34}, {45.5, 23.6}}
</code>```

Desired output:

```<code>{{45.5, 23.6}, {34.54, 98.34}}
</code>```

(length of the double[] is always 2)

答:
You could use https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal?redirectedfrom=MSDN&view=netframework-4.8#System_Linq_Enumerable_SequenceEqual__1_System_Collections_Generic_IEnumerable___0__System_Collections_Generic_IEnumerable___0__

```<code>var l = new List<int[]>(){
            new int[]{5,4,3},
            new int[]{5,4,3},
            new int[]{5,4,2},
            };

            var indexStore = new List<int>();

            for (int i = 0; i < l.Count - 1; i++)
            {
                for (int x = i + 1; x < l.Count-1; x++)
                {
                    if (l[i].SequenceEqual(l[x]))
                    {
                        indexStore.Add(x);
                    }
                }
            }

            foreach (var index in indexStore)
            {
                l.RemoveAt(index);
            }
</code>```

Do not remove while looping better store the duplicate indexes

Title: Removing duplicates from List<double[]>

Body:
I am trying to remove the duplicates from a list of double arrays. I would like to keep the first instance of the duplicate but remove any found after.

Here is my code:

private static List<double[]> RemoveDupes(List<double[]> locData)
    {
        List<double[]> list = locData;
        while (ContainsDupes(list))
            for (int a = 0; a < list.Count; a++)
                for (int b = 0; b < list.Count; b++)
                    if (a != b && list[a][0] == list[b][0] && list[a][1] == list[b][1])
                        list.RemoveAt(b);

        return list;
    }
private static bool ContainsDupes(List<double[]> list)
    {
        for (int a = 0; a < list.Count; a++)
            for (int b = 0; b < list.Count; b++)
                if (a != b && list[a][0] == list[b][0] && list[a][1] == list[b][1])
                    return true;
        return false;
    }

This method works almost all of the time but it's slow and in edge cases (1 out of a few thousand) it crashes my program with an index exception on line 6. I can't think of any other way to do this so any help would be appreciated.

Input:

{{45.5, 23.6}, {34.54, 98.34}, {45.5, 23.6}}

Desired output:

{{45.5, 23.6}, {34.54, 98.34}}

(length of the double[] is always 2)

Body:
You could use https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal?redirectedfrom=MSDN&view=netframework-4.8#System_Linq_Enumerable_SequenceEqual__1_System_Collections_Generic_IEnumerable___0__System_Collections_Generic_IEnumerable___0__

var l = new List<int[]>(){
            new int[]{5,4,3},
            new int[]{5,4,3},
            new int[]{5,4,2},
            };

            var indexStore = new List<int>();

            for (int i = 0; i < l.Count - 1; i++)
            {
                for (int x = i + 1; x < l.Count-1; x++)
                {
                    if (l[i].SequenceEqual(l[x]))
                    {
                        indexStore.Add(x);
                    }
                }
            }

            foreach (var index in indexStore)
            {
                l.RemoveAt(index);
            }

Do not remove while looping better store the duplicate indexes


问:
how to map inside another map in React.js
Using the map function in React.js to get what's inside Mp3 from this json:

```<code>{
  "175": {
    "label": "Pub Radio",
    "icone": "",
    "Mp3": {
      "33278": {
        "id": 33278,
        "titre": "Ricardo Villalobos - Caminando",
        "intention1": "Doux",
        "intention2": "Doux",
        "intention3": "Doux",
        "langue": "Allemand",
        "visibilite": 1
      }
    }
  },
  "176": {
    "label": "Pub Cd/Dvd",
    "icone": "",
    "Mp3": {
      "33277": {
        "id": 33277,
        "titre": "Mano lo taugh - Primative People",
        "intention1": "Chaleureux, rassurant",
        "intention2": "Joyeux",
        "intention3": "Souriant",
        "langue": "Allemand",
        "visibilite": 1
      },
      "33279": {
        "id": 33279,
        "titre": "Foals - Late Night (Solomun Remix).mp3",
        "intention1": "Amical, complice",
        "intention2": "Amical, complice",
        "intention3": "Amical, complice",
        "langue": "Allemand",
        "visibilite": 1
      }
    }
  },
  "245": {
    "label": "Billboard",
    "icone": "",
    "Mp3": {
      "33280": {
        "id": 33280,
        "titre": "Techno",
        "intention1": "Posé, calme",
        "intention2": "Amical, complice",
        "intention3": "Souriant",
        "langue": "Americain",
        "visibilite": 1
      }
    }
  }
}
</code>```

this is my map function :

```<code>  {Object.keys(extraitMP3).map((label, i) => (
    <li key={i}>
        <span >key: {i} Name: {extraitMP3[label]}</span>
            {Object.keys(extraitMP3[label]).map((Mp3, i) => (
        <li key={i}>
            <span >key: {i} Name: {extraitMP3[label][Mp3]}</span>

            {Object.keys(extraitMP3[label][Mp3]).map((idSon, i) => (
        <li key={i}>
            <span >key: {i} Name: {extraitMP3[label][Mp3][idSon]}</span>
            {console.log('Titre',extraitMP3[label][Mp3][idSon].titre)}
            {console.log('Intention 1',extraitMP3[label][Mp3][idSon].intention1)}
            {console.log('Intention 2',extraitMP3[label][Mp3][idSon].intention2)}
            {console.log('Intention 3',extraitMP3[label][Mp3][idSon].intention3)}
            {console.log('Langue',extraitMP3[label][Mp3][idSon].langue)}
            {console.log('Visibilite',extraitMP3[label][Mp3][idSon].visibilite)}
        </li>
    ))}
        </li>
    ))}
        </li>
    ))}
</code>```

Results are shown in the console as expected but also I receive a lot of other results as undefined. I think it's a problem of looping with map but I don't where is my problem exactly :

This is what I found in the console :

答:
this can be simplified as

```<code>{
   Object.keys(extraitMP3).map(ids => {
     return (
        <li key={ids}>
           <span >key: {ids} Name: {extraitMP3[ids].label}</span>
              {
                Object.keys(extraitMP3[ids].Mp3).map(idJson => {
                  return(
                    <li key={idJson}>
                      <span>key: {idJson} Name: {idJson}</span>
                      {console.log('Titre',extraitMP3[ids].Mp3[idJson].titre)}
                      {console.log('Intention1',extraitMP3[ids].Mp3[idJson].intention1)}
                      {console.log('Intention 2',extraitMP3[ids].Mp3[idJson].intention2)}
                      {console.log('Intention 3',extraitMP3[ids].Mp3[idJson].intention3)}
                      {console.log('Langue',extraitMP3[ids].Mp3[idJson].langue)}
                      {console.log('Visibilite',extraitMP3[ids].Mp3[idJson].visibilite)}
                   </li>
                  );
                 })
                }
              </li>
            );
          })
        }
</code>```

and using index as key is not a good way

hope this helps !!!

Body:
Using the map function in React.js to get what's inside Mp3 from this json:

{
  "175": {
    "label": "Pub Radio",
    "icone": "",
    "Mp3": {
      "33278": {
        "id": 33278,
        "titre": "Ricardo Villalobos - Caminando",
        "intention1": "Doux",
        "intention2": "Doux",
        "intention3": "Doux",
        "langue": "Allemand",
        "visibilite": 1
      }
    }
  },
  "176": {
    "label": "Pub Cd/Dvd",
    "icone": "",
    "Mp3": {
      "33277": {
        "id": 33277,
        "titre": "Mano lo taugh - Primative People",
        "intention1": "Chaleureux, rassurant",
        "intention2": "Joyeux",
        "intention3": "Souriant",
        "langue": "Allemand",
        "visibilite": 1
      },
      "33279": {
        "id": 33279,
        "titre": "Foals - Late Night (Solomun Remix).mp3",
        "intention1": "Amical, complice",
        "intention2": "Amical, complice",
        "intention3": "Amical, complice",
        "langue": "Allemand",
        "visibilite": 1
      }
    }
  },
  "245": {
    "label": "Billboard",
    "icone": "",
    "Mp3": {
      "33280": {
        "id": 33280,
        "titre": "Techno",
        "intention1": "Posé, calme",
        "intention2": "Amical, complice",
        "intention3": "Souriant",
        "langue": "Americain",
        "visibilite": 1
      }
    }
  }
}

this is my map function :

  {Object.keys(extraitMP3).map((label, i) => (

        key: {i} Name: {extraitMP3[label]}
            {Object.keys(extraitMP3[label]).map((Mp3, i) => (

            key: {i} Name: {extraitMP3[label][Mp3]}

            {Object.keys(extraitMP3[label][Mp3]).map((idSon, i) => (

            key: {i} Name: {extraitMP3[label][Mp3][idSon]}
            {console.log('Titre',extraitMP3[label][Mp3][idSon].titre)}
            {console.log('Intention 1',extraitMP3[label][Mp3][idSon].intention1)}
            {console.log('Intention 2',extraitMP3[label][Mp3][idSon].intention2)}
            {console.log('Intention 3',extraitMP3[label][Mp3][idSon].intention3)}
            {console.log('Langue',extraitMP3[label][Mp3][idSon].langue)}
            {console.log('Visibilite',extraitMP3[label][Mp3][idSon].visibilite)}

    ))}

    ))}

    ))}

Results are shown in the console as expected but also I receive a lot of other results as undefined. I think it's a problem of looping with map but I don't where is my problem exactly :

This is what I found in the console :

Body:
this can be simplified as

{
   Object.keys(extraitMP3).map(ids => {
     return (
        <li key={ids}>
           <span >key: {ids} Name: {extraitMP3[ids].label}</span>
              {
                Object.keys(extraitMP3[ids].Mp3).map(idJson => {
                  return(
                    <li key={idJson}>
                      <span>key: {idJson} Name: {idJson}</span>
                      {console.log('Titre',extraitMP3[ids].Mp3[idJson].titre)}
                      {console.log('Intention1',extraitMP3[ids].Mp3[idJson].intention1)}
                      {console.log('Intention 2',extraitMP3[ids].Mp3[idJson].intention2)}
                      {console.log('Intention 3',extraitMP3[ids].Mp3[idJson].intention3)}
                      {console.log('Langue',extraitMP3[ids].Mp3[idJson].langue)}
                      {console.log('Visibilite',extraitMP3[ids].Mp3[idJson].visibilite)}
                   </li>
                  );
                 })
                }
              </li>
            );
          })
        }

and using index as key is not a good way

hope this helps !!!


问:
How to install OpenJDK 11 on Windows?
In the past, Oracle used to publish an executable installers for Windows that would:

Unpack files

Add registry keys indicating the installed version and path

Add the JRE to the system PATH

Register an uninstaller with Windows.

As of Java 11, the Oracle's free version of Java (Oracle OpenJDK) doesn't seem to include an installer. It is just a zip file containing the binaries.

How are we supposed to install OpenJDK 11 on Windows seeing as the aforementioned integrations are no longer there? Aren't they necessary?

答:
Java 17 (LTS) and up

For Java 17 and up, you can use the Eclipse Adoptium website. According to their about section, the Eclipse Adoptium project is the continuation of the original AdoptOpenJDK mission.

Java 11 (LTS), Java 8 - 16

For Java 11 (8 through 16), you can use AdoptOpenJDK, a website hosted by the java community. You can find .msi installers for OpenJDK 8 through 16 there, which will perform all the things listed in the question (Unpacking, registry keys, PATH variable updating (and JAVA_HOME), uninstaller...).

Title: How to install OpenJDK 11 on Windows?


问:
Access main activity FloatingActionButton from Fragments
I have a an activity with 3 fragments. Each fragment has to have a FAB with different icon an action.
The FAB is defined on the main activity layout. Now I saw that I cannot access it from fragments. How can I do it?

Here's my code:
main_activity layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        tools:layout_editor_absoluteX="16dp">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />
    </android.support.v4.view.ViewPager>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="24dp"
        android:src="@android:drawable/ic_dialog_email"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

my fragment layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackgroundFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/contact_recycleview">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>
</code>```

inflating the fragment:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v= inflater.inflate(R.layout.filters_fragment,container,false);

    myrecyclerview = (RecyclerView) v.findViewById(R.id.contact_recycleview);
    recyclerAdapter = new RecyclerViewAdapterCall(getContext(), lstCall);
    myrecyclerview.setLayoutManager(new LinearLayoutManager((getActivity())));
    myrecyclerview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    myrecyclerview.setAdapter(recyclerAdapter);

    return v;
}
</code>```

so here I'll like to change icon an action, how?

答:
Android developer guide recommend the following way to do Activity, Fragment communication.

Fragment access Activity by listener. Activity access Fragment by getSupportFragmentManager().getFragments()

So you have two ways to use the fab.

First, directly access the fab in Fragment

```<code>class MyFragment extends Fragment {
    MyFragmentListener listener;

    void myFunction() {
        FloatingActionButton fab = listener.getFab();
        ...
    }
}

interface MyFragmentListener {
    FloatingActionButton getFab();
}

class MyActivity extends AppCompatActivity implements MyFragmentListener {
    FloationActionButton fab;

    @Override
    FloationActionButton getFab() {
        return fab;
    }

    @Override
    void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        if(fragment instanceof MyFragment) {
            ((MyFragment) fragment).listener = this;
        }
    }
}
</code>```

Second, Call Fragment's function when fab is clicked

```<code>//In Activity
fab.setOnClickListener(new OnClickListener() {
    for(fragment : getSupportFragmentManager().getFragments()) {
        if(fragment instanceof MyFragment) {
            ((MyFragment) fragment).someFunction();
        }
    }
});
</code>```

Body:
I have a an activity with 3 fragments. Each fragment has to have a FAB with different icon an action.
The FAB is defined on the main activity layout. Now I saw that I cannot access it from fragments. How can I do it?

Here's my code:
main_activity layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        tools:layout_editor_absoluteX="16dp">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />
    </android.support.v4.view.ViewPager>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="24dp"
        android:src="@android:drawable/ic_dialog_email"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

my fragment layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackgroundFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/contact_recycleview">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

inflating the fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v= inflater.inflate(R.layout.filters_fragment,container,false);

    myrecyclerview = (RecyclerView) v.findViewById(R.id.contact_recycleview);
    recyclerAdapter = new RecyclerViewAdapterCall(getContext(), lstCall);
    myrecyclerview.setLayoutManager(new LinearLayoutManager((getActivity())));
    myrecyclerview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    myrecyclerview.setAdapter(recyclerAdapter);

    return v;
}

so here I'll like to change icon an action, how?

Body:
Android developer guide recommend the following way to do Activity, Fragment communication.

Fragment access Activity by listener. Activity access Fragment by getSupportFragmentManager().getFragments()

So you have two ways to use the fab.

First, directly access the fab in Fragment

class MyFragment extends Fragment {
    MyFragmentListener listener;

    void myFunction() {
        FloatingActionButton fab = listener.getFab();
        ...
    }
}

interface MyFragmentListener {
    FloatingActionButton getFab();
}

class MyActivity extends AppCompatActivity implements MyFragmentListener {
    FloationActionButton fab;

    @Override
    FloationActionButton getFab() {
        return fab;
    }

    @Override
    void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        if(fragment instanceof MyFragment) {
            ((MyFragment) fragment).listener = this;
        }
    }
}

Second, Call Fragment's function when fab is clicked

//In Activity
fab.setOnClickListener(new OnClickListener() {
    for(fragment : getSupportFragmentManager().getFragments()) {
        if(fragment instanceof MyFragment) {
            ((MyFragment) fragment).someFunction();
        }
    }
});


问:
How to find folders that containt a certain string using CMD?
I need to find the path of every folder that contains the words "test" or "Test" or "TEST" in a specific location. The file tree is huge.

This is to remove every folder that contains "test". I've tried using
the findstr function.

```<code>findstr /i "test"
</code>```

I expect to get every folder path that contains "test"

答:
The list of directories can be generated and iterated over using a FOR loop. When you are satisfied that the correct directories will be deleted, remove the echo from the line containing rmdir.

```<code>@echo off
pushd \
for /f "delims=" %%a in ('dir /s /b /a:d "*test*"') do (
    echo if exist "%%~a" (rmdir /s /q "%%~a")
)
popd
</code>```

If you wanted to push ahead into Powershell, which Microsoft says is the future, something like this might work. When you are satisfied that the correct directories will be removed, remove the -WhatIf from the Remove-Item cmdlet.

=== Remove-TestDirectories.ps1

```<code>$previousdir = ":" # set to impossible filesystem name

Get-ChildItem -Directory -Recurse -Path "C:\" -Filter "*test*" -Force -ErrorAction SilentlyContinue |
    Sort-Object -Property FullName |
    ForEach-Object {
        #"{0} and {1} and {2}" -f @($previousdir, $_.FullName, $_.FullName.StartsWith($previousdir))
        if (-not $_.FullName.StartsWith($previousdir)) {
            $previousdir = $_.FullName
            if (Test-Path -Path $_.FullName) { Remove-Item -Path $_.FullName -Recurse -WhatIf}
        }
    }
</code>```

This can be run from a cmd.exe shell.

```<code>powershell -NoLogo -NoProfile -File Remove-TestDirectories.ps1
</code>```

Body:
I need to find the path of every folder that contains the words "test" or "Test" or "TEST" in a specific location. The file tree is huge.

This is to remove every folder that contains "test". I've tried using
the findstr function.

findstr /i "test"

I expect to get every folder path that contains "test"

Body:
The list of directories can be generated and iterated over using a FOR loop. When you are satisfied that the correct directories will be deleted, remove the echo from the line containing rmdir.

@echo off
pushd \
for /f "delims=" %%a in ('dir /s /b /a:d "*test*"') do (
    echo if exist "%%~a" (rmdir /s /q "%%~a")
)
popd

If you wanted to push ahead into Powershell, which Microsoft says is the future, something like this might work. When you are satisfied that the correct directories will be removed, remove the -WhatIf from the Remove-Item cmdlet.

=== Remove-TestDirectories.ps1

$previousdir = ":" # set to impossible filesystem name

Get-ChildItem -Directory -Recurse -Path "C:\" -Filter "*test*" -Force -ErrorAction SilentlyContinue |
    Sort-Object -Property FullName |
    ForEach-Object {
        #"{0} and {1} and {2}" -f @($previousdir, $_.FullName, $_.FullName.StartsWith($previousdir))
        if (-not $_.FullName.StartsWith($previousdir)) {
            $previousdir = $_.FullName
            if (Test-Path -Path $_.FullName) { Remove-Item -Path $_.FullName -Recurse -WhatIf}
        }
    }

This can be run from a cmd.exe shell.

powershell -NoLogo -NoProfile -File Remove-TestDirectories.ps1


问:
hbase completebulkload long running
A hadoop cluster was upgraded from CDH 4.4 to CDH 5.7.6, HBASE: 0.94 -> 1.2.0
After that time of hbase completebulkload process has increased from 2 hours to 3-4 for small tables and 10+ hours for big tables. Why it happens? What should I check for?</p>

答:
The problem was in disabled blockcache. If you load hfiles through the code using LoadIncrementalHFiles it works properly.
https://issues.apache.org/jira/browse/HBASE-10500</p>

Title: hbase completebulkload long running


问:
Exclude "a" tags with specific parent from jquery scroll function
i implemented smooth scrolling on my page with a script i'll provide below.
but i also implemented a tabs section. and i don't want the smooth scrolling implemented there.

this is my jquery code:

```<code>$('a[href*="#"]')
    // Remove links that don't actually link to anything
    .not('[href="#"]')
    .not('[href="#0"]')
    .click(function(event) {
      // On-page links
      if (
        location.pathname.replace(/^\//, "") ==
          this.pathname.replace(/^\//, "") &&
        location.hostname == this.hostname
      ) {
        // Figure out element to scroll to
        var target = $(this.hash);
        target = target.length
          ? target
          : $("[name=" + this.hash.slice(1) + "]");
        // Does a scroll target exist?
        if (target.length) {
          // Only prevent default if animation is actually gonna happen
          event.preventDefault();
          $("html, body").animate(
            {
              scrollTop: target.offset().top - 91
            },
            1000,
            function() {
              // Callback after animation
              // Must change focus!
              var $target = $(target);
              $target.focus();
              if ($target.is(":focus")) {
                // Checking if the target was focused
                return false;
              } else {
                $target.attr("tabindex", "-1"); // Adding tabindex for elements not focusable
                $target.focus(); // Set focus again
              }
            }
          );
        }
      }
    });
</code>```

i want to exclude all a elements that are children of service-menu-area class.

i'll provide the html:

```<code><div class="service-menu-area">
  <ul class="nav">
      <li>
        <a class="active" data-toggle="tab" href="#spa">
              <span class="service-icon">
                  <img src="img/icon/service-icon1.png" alt="">
              </span>
         <span class="service-title">Room Service</span>
         <span class="text">
         <span>Room Service</span>
         luptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia
         </span>
         </a>
     </li>
</ul>
</div>
</code>```

so i expect that when i click on one of the html tabs i won't see any scroll animation.

答: You can add a .not('.service-menu-area a') before you add the .click handler.

Body:
i implemented smooth scrolling on my page with a script i'll provide below.
but i also implemented a tabs section. and i don't want the smooth scrolling implemented there.

this is my jquery code:

$('a[href*="#"]')
    // Remove links that don't actually link to anything
    .not('[href="#"]')
    .not('[href="#0"]')
    .click(function(event) {
      // On-page links
      if (
        location.pathname.replace(/^\//, "") ==
          this.pathname.replace(/^\//, "") &&
        location.hostname == this.hostname
      ) {
        // Figure out element to scroll to
        var target = $(this.hash);
        target = target.length
          ? target
          : $("[name=" + this.hash.slice(1) + "]");
        // Does a scroll target exist?
        if (target.length) {
          // Only prevent default if animation is actually gonna happen
          event.preventDefault();
          $("html, body").animate(
            {
              scrollTop: target.offset().top - 91
            },
            1000,
            function() {
              // Callback after animation
              // Must change focus!
              var $target = $(target);
              $target.focus();
              if ($target.is(":focus")) {
                // Checking if the target was focused
                return false;
              } else {
                $target.attr("tabindex", "-1"); // Adding tabindex for elements not focusable
                $target.focus(); // Set focus again
              }
            }
          );
        }
      }
    });

i want to exclude all a elements that are children of service-menu-area class.

i'll provide the html:

         Room Service

         Room Service
         luptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia

so i expect that when i click on one of the html tabs i won't see any scroll animation.


问:
Symfony there are no commands defined in the "make" namespace
Following the documentation found here I enter php bin/console make:entity Product in Terminal and get the following error:

[Symfony\Component\Console\Exception\CommandNotFoundException]

There are no commands defined in the "make" namespace.

答: Try composer require symfony/maker-bundle --dev it work for me.


问:
Compiler policies on destruction of temporaries
I've been playing with the following piece of code. file_string returns a temporary string that should only "live" until the end of the statement. In Visual Studio 2008, when you use pTempFolder, it contains rubbish as expected. In Linux though, with Intel compiler 11.0, pTempFolder still points to a valid string. Do compilers have different policies regarding the destruction of temporaries, kind of eager (Visual) versus lazy (Intel)? Or maybe this is just a coincidence?

```<code>boost::filesystem wpathTempFolder("/tmp");
const wchar_t* const pTempFolder = wpathTempFolder.file_string().c_str();
// use pTempFolder
</code>```

BTW, that is boost filesystem version 2. I've also seen that file_string is being deprecated in boost filesystem version 3. And that there is a new c_str method that operates over a string&, instead of over a temporary string.

```<code>/*filesystem 2*/
const string_type file_string() const;
/*filesystem 3*/
const string_type&  native() const;  // native format, encoding
const value_type*   c_str() const;   // native().c_str()
</code>```

答: Likely, the string is still invalid, it just so happens that that section of memory hasn't yet been de-allocated at the operating system level and it "happens" to work. This program exhibits undefined behaviour- which always includes "may continue to work as if nothing went wrong". Visual Studio is completely correct here to crash your program or pretty much anything. </p>

Body:
I've been playing with the following piece of code. file_string returns a temporary string that should only "live" until the end of the statement. In Visual Studio 2008, when you use pTempFolder, it contains rubbish as expected. In Linux though, with Intel compiler 11.0, pTempFolder still points to a valid string. Do compilers have different policies regarding the destruction of temporaries, kind of eager (Visual) versus lazy (Intel)? Or maybe this is just a coincidence?

boost::filesystem wpathTempFolder("/tmp");
const wchar_t* const pTempFolder = wpathTempFolder.file_string().c_str();
// use pTempFolder

BTW, that is boost filesystem version 2. I've also seen that file_string is being deprecated in boost filesystem version 3. And that there is a new c_str method that operates over a string&, instead of over a temporary string.

/*filesystem 2*/
const string_type file_string() const;
/*filesystem 3*/
const string_type&  native() const;  // native format, encoding
const value_type*   c_str() const;   // native().c_str()


问:
Wordpress author page link redirets to top page
I'm trying to figure out whats wrong with this website's author page link. The author.php is placed on the theme folder correctly.

This is the only code I have to link it:

```<code><p class="autor">por <?php get_the_author_posts_link(); ?></p>
</code>```

Here is an example of author page link:
https://aoriente.com/news/author/goncaloasm/

And here is a post. The author link is just bellow the tittle:
https://aoriente.com/news/688/

What might be wrong?

答:
The author page can be enabled/disabled via Yoast SEO plugin.

You should look at Yoast SEO settings to enable it.

https://kb.yoast.com/kb/disable-enable-author-archives/

Body:
I'm trying to figure out whats wrong with this website's author page link. The author.php is placed on the theme folder correctly.

This is the only code I have to link it:

por <?php get_the_author_posts_link(); ?>

Here is an example of author page link:
https://aoriente.com/news/author/goncaloasm/

And here is a post. The author link is just bellow the tittle:
https://aoriente.com/news/688/

What might be wrong?


问:
How to check for vertical velocity in 2d unity?
I am trying to animate my sprite when my vertical velocity is less than 0 (moving downwards). How do you do it?

```<code>if (VERTICALVELOCITY < 0) {
animator.SetFloat("IsFalling", true);
}
</code>```

Try to change VERTICALVELOCITY and maybe help with the code.
Also, should I do it in Void Update or FixedUpdate?

答:
Do you have a rigidbody on that gameobject? Then it's easy.

```<code>private Rigidbody rb;

Start()
{
    rb = getComponent<Rigidbody>();
}

Update ()
{
    if(rb.velocity.y < 0)
    {
        // do your stuff
    }
}
</code>```

Otherwise, you need to log the y-position every frame.

```<code>float ypos_lastframe = 0;

Start()
{
    ypos_lastframe = transform.position.y;
}

Update()
{
    if(transform.position.y < ypos_lastframe)
    {
       // do your stuff
    }
    // important to do this assignment AFTER the check above.
    ypos_lastframe = transform.position.y;
}
</code>```

Body:
I am trying to animate my sprite when my vertical velocity is less than 0 (moving downwards). How do you do it?

if (VERTICALVELOCITY < 0) {
animator.SetFloat("IsFalling", true);
}

Try to change VERTICALVELOCITY and maybe help with the code.
Also, should I do it in Void Update or FixedUpdate?

Body:
Do you have a rigidbody on that gameobject? Then it's easy.

private Rigidbody rb;

Start()
{
    rb = getComponent<Rigidbody>();
}

Update ()
{
    if(rb.velocity.y < 0)
    {
        // do your stuff
    }
}

Otherwise, you need to log the y-position every frame.

float ypos_lastframe = 0;

Start()
{
    ypos_lastframe = transform.position.y;
}

Update()
{
    if(transform.position.y < ypos_lastframe)
    {
       // do your stuff
    }
    // important to do this assignment AFTER the check above.
    ypos_lastframe = transform.position.y;
}


问:
How to dynamically enable the textbox?
I have 10 textbox and corresponding to that I have 10 dropdown boxes .
So my requirement is when I fill the text in first textbox and select its corresponding dropdown list , then only second textbox and its corresponding dropdown should be activate else they all should be deactivate.

How do I achieve it using angular 2+ ??

Any help would be appreciated.

Thanks

答:
In the *.ts-file do something like:

```<code>value: string;

isValueEmpty(): boolean {
  if ('' !== this.value && this.value.length > 0) {
    return true;
  }

  return false;
}
</code>```

In the *.html-file do something like this:

```<code><input [(ngModel)]="value" />
<mat-select *ngIf="isValueEmpty()">
  ...
</mat-select>
</code>```

You probably want to iterate those fields:

```<code><div *ngFor="let value of values">
  ...
</div>
</code>```

Then you need to change your function accordingly.

*.html-file:

```<code><input [(ngModel)]="value" />
<mat-select *ngIf="isValueEmpty(value)">
  ...
</mat-select>
</code>```

*.ts-file:

```<code>isValueEmpty(value: string): boolean {
  if ('' !== value && value.length > 0) {
    return true;
  }

  return false;
}
</code>```

Title: How to dynamically enable the textbox?

Body:
In the *.ts-file do something like:

value: string;

isValueEmpty(): boolean {
  if ('' !== this.value && this.value.length > 0) {
    return true;
  }

  return false;
}

In the *.html-file do something like this:

<input [(ngModel)]="value" />
<mat-select *ngIf="isValueEmpty()">
  ...
</mat-select>

You probably want to iterate those fields:

<div *ngFor="let value of values">
  ...
</div>

Then you need to change your function accordingly.

*.html-file:

<input [(ngModel)]="value" />
<mat-select *ngIf="isValueEmpty(value)">
  ...
</mat-select>

*.ts-file:

isValueEmpty(value: string): boolean {
  if ('' !== value && value.length > 0) {
    return true;
  }

  return false;
}


问:
How can I refactor this if elif statements?
There is list of grades - [a,b,c,d,e,f]

```<code>grade = int(input())
if grade >= 90 and grade <= 100:
    print('a')
elif grade >=70 and grade <= 80:
    print('b')
elif grade >=60 and grade <= 70:
    print('c')
elif grade >= 50 and grade <= 60:
    print('d')
elif grade < 50:
    print('e')
</code>```

How can I rewrite this elegantly in 2-3 lines of code?

Like, there is dictionary with key grades 'a', 'b', 'c', 'd' and it prints depending on the grade?

答:
Well you could easily get rid of one half of the range checks, by rephrasing as follows:

```<code>grade = int(input())
if grade < 50:
    print('e')
elif grade <= 60:
    print('d')
elif grade <= 70:
    print('c')
elif grade <= 80:
    print('b')
elif grade >= 90 and grade <= 100:
    print('a')
else
    print('unknown')
</code>```

I am not sure if your 90 <= grade <= 100 range is accurate, or if you intended for it to be adjacent to the previous lower range.  In any case, it does not change my suggested refactor much.

Body:
There is list of grades - [a,b,c,d,e,f]

grade = int(input())
if grade >= 90 and grade <= 100:
    print('a')
elif grade >=70 and grade <= 80:
    print('b')
elif grade >=60 and grade <= 70:
    print('c')
elif grade >= 50 and grade <= 60:
    print('d')
elif grade < 50:
    print('e')

How can I rewrite this elegantly in 2-3 lines of code?

Like, there is dictionary with key grades 'a', 'b', 'c', 'd' and it prints depending on the grade?

Body:
Well you could easily get rid of one half of the range checks, by rephrasing as follows:

grade = int(input())
if grade < 50:
    print('e')
elif grade <= 60:
    print('d')
elif grade <= 70:
    print('c')
elif grade <= 80:
    print('b')
elif grade >= 90 and grade <= 100:
    print('a')
else
    print('unknown')

I am not sure if your 90 <= grade <= 100 range is accurate, or if you intended for it to be adjacent to the previous lower range.  In any case, it does not change my suggested refactor much.


问:
install Xcode 8.3.3 beside Xcode 10.2.1 in macOS mojave
I have installed Xcode 8.3.3 that I need for an old project with swift 3.3
and when I try to lunch Xcode 8.3.3 I have this error message </p>

```<code>Application Specific Information:
dyld: launch, loading dependent libraries

Dyld Error Message:
  Symbol not found: _OBJC_IVAR_$_NSTextViewIvars.sharedData
  Referenced from: /Applications/Xcode 8.app/Contents/MacOS/../SharedFrameworks/DVTKit.framework/Versions/A/DVTKit
  Expected in: /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit
 in /Applications/Xcode 8.app/Contents/MacOS/../SharedFrameworks/DVTKit.framework/Versions/A/DVTKit

</code>```

答: Xcode 8.3.3 is no more support in MacOS Mojave 10.14+</p>

Body:
I have installed Xcode 8.3.3 that I need for an old project with swift 3.3
and when I try to lunch Xcode 8.3.3 I have this error message

Application Specific Information:
dyld: launch, loading dependent libraries

Dyld Error Message:
  Symbol not found: _OBJC_IVAR_$_NSTextViewIvars.sharedData
  Referenced from: /Applications/Xcode 8.app/Contents/MacOS/../SharedFrameworks/DVTKit.framework/Versions/A/DVTKit
  Expected in: /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit
 in /Applications/Xcode 8.app/Contents/MacOS/../SharedFrameworks/DVTKit.framework/Versions/A/DVTKit


问:
how to change color of TextinputLayout's label and edittext underline android
I am using android design library's TextinputLayout. But couldn't customize the hint color, label color and the underline color of EditText inside TextinputLayout. Please help.

答:
A TextinputLayout is not a view, but a Layout, as very nicely described by Dimitrios Tsigouris in his blog post here. Therefore, you don't need a Style, which is for Views only, but use a Theme. Following the blog post, I ended up with the following solution:

Start in your styles.xml with

```<code><style name="TextInputLayoutAppearance" parent="Widget.Design.TextInputLayout">
        <!-- reference our hint & error styles -->
        <item name="android:textColor">@color/your_colour_here</item>
        <item name="android:textColorHint">@color/your_colour_here</item>
        <item name="colorControlNormal">@color/your_colour_here</item>
        <item name="colorControlActivated">@color/your_colour_here</item>
        <item name="colorControlHighlight">@color/your_colour_here</item>
</style>
</code>```

And in your layout add

```<code><com.google.android.material.textfield.TextInputLayout
                android:theme="@style/TextInputLayoutAppearance"
...
</code>```

Body:
A TextinputLayout is not a view, but a Layout, as very nicely described by Dimitrios Tsigouris in his blog post here. Therefore, you don't need a Style, which is for Views only, but use a Theme. Following the blog post, I ended up with the following solution:

Start in your styles.xml with

<style name="TextInputLayoutAppearance" parent="Widget.Design.TextInputLayout">
        <!-- reference our hint & error styles -->
        <item name="android:textColor">@color/your_colour_here</item>
        <item name="android:textColorHint">@color/your_colour_here</item>
        <item name="colorControlNormal">@color/your_colour_here</item>
        <item name="colorControlActivated">@color/your_colour_here</item>
        <item name="colorControlHighlight">@color/your_colour_here</item>
</style>

And in your layout add

<com.google.android.material.textfield.TextInputLayout
                android:theme="@style/TextInputLayoutAppearance"
...


问:
How to use PHP7 with Mysql?
As we all know PHP 7 removed the Mysql and kept only mysqli and PDO.

But I have some condition on my project to use the PHP7 with Mysql, how can i handle that, without changing too much of code or existing extensions?

答: You can define almost all mysql_* functions using MySQLi or PDO in separated file, which you can include on top of your project. This is my solution: https://github.com/sunhater/php7-mysql

Title: How to use PHP7 with Mysql?


问:
check if value of one column lies between the range of another column(array) in a dataframe
I have a dataframe where I need to compare a few values and deduce a few things out of it.

For instance,

my DF

```<code>CITY DAY MONTH TAG RANGE     VALUE  RANK
A    1    01    A   [50, 90]   55     1
A    2    02    B   [30, 40]   34     3
A    1    03    A   [05, 10]   15    20
A    1    04    B   [50, 60]   11    10
A    1    05    B   [50, 60]   54    4
</code>```

I have to check , for every row if the value of "VALUE" lies between the "RANGE". Here, arr[0] is the lower limit and arr[1] is the upper limit.

I need to create a new DF such that,

NEW-DF

```<code>TAG  Positive  Negative
A     1          1
B     2          1
</code>```

If the "value" lies between the given range and the rank < 5 then I would add it to "positive"

If the value doesnt lie in the given range , then it is a negative

If the value lies in the given range, but the rank > 5, then I would count it as negative

"Positive" and "Negative" is nothing but the count of the values fulfilling either conditions.

答:
We can use element_at to get the elements at each position and compare them to the corresponding value in each row, along with the rank condition, and then perform a groupby with sum on the tag:

```<code>from pyspark.sql import functions as F
from pyspark.sql.types import IntegerType

range_df = df.withColumn('in_range', (F.element_at('range', 1).cast(IntegerType()) < F.col('value')) &
                                     (F.col('value') < F.element_at('range', 2).cast(IntegerType())) &
                                     (F.col('rank') < 5))

range_df.show()

grouped_df = range_df.groupby('tag').agg(F.sum(F.col('in_range').cast(IntegerType())).alias('total_positive'),
                                         F.sum((~F.col('in_range')).cast(IntegerType())).alias('total_negative'))

grouped_df.show()
</code>```

Output:

```<code>+---+--------+-----+----+--------+
|tag|   range|value|rank|in_range|
+---+--------+-----+----+--------+
|  A|[50, 90]|   55|   1|    true|
|  B|[30, 40]|   34|   3|    true|
|  A|[05, 10]|   15|  20|   false|
|  B|[50, 60]|   11|  10|   false|
|  B|[50, 60]|   54|   4|    true|
+---+--------+-----+----+--------+

+---+--------------+--------------+
|tag|total_positive|total_negative|
+---+--------------+--------------+
|  B|             2|             1|
|  A|             1|             1|
+---+--------------+--------------+
</code>```

Body:
I have a dataframe where I need to compare a few values and deduce a few things out of it.

For instance,

my DF

CITY DAY MONTH TAG RANGE     VALUE  RANK
A    1    01    A   [50, 90]   55     1
A    2    02    B   [30, 40]   34     3
A    1    03    A   [05, 10]   15    20
A    1    04    B   [50, 60]   11    10
A    1    05    B   [50, 60]   54    4

I have to check , for every row if the value of "VALUE" lies between the "RANGE". Here, arr[0] is the lower limit and arr[1] is the upper limit.

I need to create a new DF such that,

NEW-DF

TAG  Positive  Negative
A     1          1
B     2          1

If the "value" lies between the given range and the rank < 5 then I would add it to "positive"

If the value doesnt lie in the given range , then it is a negative

If the value lies in the given range, but the rank > 5, then I would count it as negative

"Positive" and "Negative" is nothing but the count of the values fulfilling either conditions.

Body:
We can use element_at to get the elements at each position and compare them to the corresponding value in each row, along with the rank condition, and then perform a groupby with sum on the tag:

from pyspark.sql import functions as F
from pyspark.sql.types import IntegerType

range_df = df.withColumn('in_range', (F.element_at('range', 1).cast(IntegerType()) < F.col('value')) &
                                     (F.col('value') < F.element_at('range', 2).cast(IntegerType())) &
                                     (F.col('rank') < 5))

range_df.show()

grouped_df = range_df.groupby('tag').agg(F.sum(F.col('in_range').cast(IntegerType())).alias('total_positive'),
                                         F.sum((~F.col('in_range')).cast(IntegerType())).alias('total_negative'))

grouped_df.show()

Output:

+---+--------+-----+----+--------+
|tag|   range|value|rank|in_range|
+---+--------+-----+----+--------+
|  A|[50, 90]|   55|   1|    true|
|  B|[30, 40]|   34|   3|    true|
|  A|[05, 10]|   15|  20|   false|
|  B|[50, 60]|   11|  10|   false|
|  B|[50, 60]|   54|   4|    true|
+---+--------+-----+----+--------+

+---+--------------+--------------+
|tag|total_positive|total_negative|
+---+--------------+--------------+
|  B|             2|             1|
|  A|             1|             1|
+---+--------------+--------------+


问:
Location to save api token?
I'm not sure which is gonna be the best location to save API key which users generating by providing email address and password, right now I'm finding temporary direction on their machine and saving it there.

But I'm not sure if it is the best approach.

Notes:

API key has to be regenerated every 6 or 12 hours (depends).

I can't save it in the cache memory, because API endpoint which returning API key for another endpoint (which requires email and password) is rate-limited by 5 requests a day.

答:
You could use local storage.

See https://www.w3schools.com/html/html5_webstorage.asp

Title: Location to save api token?


问:
How to apply :PluginInstall on Vim
I have trouble applying the vim command :PluginInstall, When I do it it seems to work, but it opens a Vundler Installer (or so I think) window which I can't seem to quit while applying the plugins. I tried with :q, :x and :wq (:w don't work on this window apparently), and I also tried restarting my terminal. Also I tried vim +PluginInstall +qall from my terminal.

Here's the window that opens with :PluginInstall (on the left)

And here's when I :q the window (as you can see, the status bar on the bottom isn't here anymore)

I'm very new to Vim and I guess I did something wrong with the installation or even in my .vimrc file (there's still a lot I don't understand in there).

My .vimrc:

```<code> 1 set nocompatible
  2 filetype off
  3
  4 set rtp+=~/.vim/bundle/Vundle.vim
  5 call vundle#begin()
  6
  7 Plugin 'gmarik/Vundle.vim'
  8
  9
 10 Plugin 'tpope/vim-rails'
 11 Plugin 'tpope/vim-surround'
 12 Plugin 'scrooloose/nerdtree'
 13 Plugin 'ctrlpvim/ctrlp.vim'
 14 Plugin 'godlygeek/tabular'
 15 Plugin 'itchyny/lightline.vim'
 16 Plugin 'vim-ruby/vim-ruby'
 17 set rtp+=~/.fzf
 18 Plugin 'junegunn/fzf.vim'
 19 call vundle#end()
 20
 21
 22 filetype plugin indent on
 23
 24 set number
 25 set mouse=a
 26 syntax on
 27 set backspace=indent,eol,start
 28 set tabstop=2 shiftwidth=2 expandtab
 29 if has("multi_byte")
 30   set encoding=utf-8
 31   setglobal fileencoding=utf-8
 32 else
 33   echoerr "Sorry, this version of (g)vim was not compiled with +multi_byte"
 34 endif

</code>```

答: :close should close the PluginInstall window and return vim to the initial window that was active before running :PluginInstall

Title: How to apply :PluginInstall on Vim

Body:
I have trouble applying the vim command :PluginInstall, When I do it it seems to work, but it opens a Vundler Installer (or so I think) window which I can't seem to quit while applying the plugins. I tried with :q, :x and :wq (:w don't work on this window apparently), and I also tried restarting my terminal. Also I tried vim +PluginInstall +qall from my terminal.

Here's the window that opens with :PluginInstall (on the left)

And here's when I :q the window (as you can see, the status bar on the bottom isn't here anymore)

I'm very new to Vim and I guess I did something wrong with the installation or even in my .vimrc file (there's still a lot I don't understand in there).

My .vimrc:

 1 set nocompatible
  2 filetype off
  3
  4 set rtp+=~/.vim/bundle/Vundle.vim
  5 call vundle#begin()
  6
  7 Plugin 'gmarik/Vundle.vim'
  8
  9
 10 Plugin 'tpope/vim-rails'
 11 Plugin 'tpope/vim-surround'
 12 Plugin 'scrooloose/nerdtree'
 13 Plugin 'ctrlpvim/ctrlp.vim'
 14 Plugin 'godlygeek/tabular'
 15 Plugin 'itchyny/lightline.vim'
 16 Plugin 'vim-ruby/vim-ruby'
 17 set rtp+=~/.fzf
 18 Plugin 'junegunn/fzf.vim'
 19 call vundle#end()
 20
 21
 22 filetype plugin indent on
 23
 24 set number
 25 set mouse=a
 26 syntax on
 27 set backspace=indent,eol,start
 28 set tabstop=2 shiftwidth=2 expandtab
 29 if has("multi_byte")
 30   set encoding=utf-8
 31   setglobal fileencoding=utf-8
 32 else
 33   echoerr "Sorry, this version of (g)vim was not compiled with +multi_byte"
 34 endif


问:
How I Can Use For Loop With Array And Get value One By One By Clicking
Please, I want some help.
I want to use for-loop with array and i want to get values one by one using button.

I want on click and get --> "A",

when i click again and get --> "B",

when i click again and get --> "C"

...

When i use for loop i get only the last value
you can see and edit the code here.

How can I use for-loop with an array and get value one by one by clicking:

```<code>var myArray = ["A", "B", "C", "D", "E", "F"];

var display = document.getElementById("display");
var x = 0;

function oneByOne() {
    for (i = 0; i < myArray.length; i++) {
    display.innerHTML = myArray[i]; // Result => "F"
 }
}
</code>```

Like the following code:

```<code>display.innerHTML = myArray[0];

function oneByOne() {
 x++;
 if (x < myArray.length) {
   display.innerHTML = myArray[x];

} else {
   display.innerHTML = "End";
 }
}
</code>```

HTML code:

```<code><h1 id="display"></h1>
<button onclick="oneByOne()"> One By One </button>
</code>```

答:
Ok, after your clarification here is working code:

var myArray = ["A", "B", "C", "D", "E", "F"];

var display = document.getElementById("display");

var x = 0;

function oneByOne() {
  if (x < myArray.length) {
    display.innerHTML = myArray[x];
  } else {
    display.innerHTML = "End";
  }
  x++;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 id="display"></h1>
<button onclick="oneByOne()"> One By One </button></code>```

Body:
Please, I want some help.
I want to use for-loop with array and i want to get values one by one using button.

I want on click and get --> "A",

when i click again and get --> "B",

when i click again and get --> "C"

...

When i use for loop i get only the last value
you can see and edit the code here.

How can I use for-loop with an array and get value one by one by clicking:

var myArray = ["A", "B", "C", "D", "E", "F"];

var display = document.getElementById("display");
var x = 0;

function oneByOne() {
    for (i = 0; i < myArray.length; i++) {
    display.innerHTML = myArray[i]; // Result => "F"
 }
}

Like the following code:

display.innerHTML = myArray[0];

function oneByOne() {
 x++;
 if (x < myArray.length) {
   display.innerHTML = myArray[x];

} else {
   display.innerHTML = "End";
 }
}

HTML code:

<button onclick="oneByOne()"> One By One </button>

Body:
Ok, after your clarification here is working code:

var myArray = ["A", "B", "C", "D", "E", "F"];

var display = document.getElementById("display");

var x = 0;

function oneByOne() {
  if (x < myArray.length) {
    display.innerHTML = myArray[x];
  } else {
    display.innerHTML = "End";
  }
  x++;
}

<h1 id="display"></h1>
<button onclick="oneByOne()"> One By One </button>


问:
Case classes - Copy multiple fields with transforms
I have a case class with 25 fields and need to convert it into another with 22, of which 19 of these are shared and 3 are simply renamed.

I have found a few examples of how to do this using shapeless (e.g. an answer here and some code examples from Miles Sabin here and here) but the last of those looks a bit out of date, and I can't figure out from the Github example how I can use shapeless to rename multiple fields, or do more manipulation on a field before adding it to the new object. Can anyone help me out?

Simplified code example;

```<code>import shapeless.LabelledGeneric
case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)

val aGen = LabelledGeneric[A]
val bGen = LabelledGeneric[B]

val freddie = new A(1,"Freddie","somestring")

val record = aGen.to(freddie)
val atmp = freddie.fieldA
record.Remove("fielda")

val freddieB = bGen.from(record +
  (Symbol("fieldARenamed") ->> atmp) +
  (Symbol("fieldCTransformed") ->> freddie.fieldC.toUpperCase)
) //Errors everywhere, even if I replace + with :: etc.
</code>```

I have a feeling Align is going to come into the picture somewhere here, but understanding how to do this in the leanest possible fashion - e.g. without creating additional traits like Field, as in that third link above - would be interesting.

In The Shapeless Guide, there is also some usage of a single quote, (e.g. 'fieldC) notation, which I haven't been able to find much information on, so if that plays a role some explanation would also be really helpful. Fairly new to this depth of Scala sorcery, so apologies if the question seems obtuse or covers too many disparate topics.

EDIT: For the avoidance of doubt, I am not looking for answers which suggest that I just manually create a new case class by referencing fields from the first, as in;

```<code>val freddieB = B(fieldARenamed = freddie.fieldA, fieldB = freddie.fieldB, fieldC = freddie.fieldC, fieldCTransformed =freddie.fieldC.toUpperCase)
</code>```

See below comment for various reasons why this is inappropriate.

答:
One other option is to use automapper; in particular, Dynamic Mappings feature.

For your particular example it would look like the following:

```<code>import io.bfil.automapper._

case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)

val freddie = new A(1,"Freddie","somestring")

val freddieB = automap(freddie).dynamicallyTo[B](
  fieldARenamed = freddie.fieldA,
  fieldCTransformed = freddie.fieldC.toUpperCase
)
</code>```

and I guess you can make it a function

```<code>def atob(a: A): B = {
  automap(a).dynamicallyTo[B](
    fieldARenamed = a.fieldA,
    fieldCTransformed = a.fieldC.toUpperCase
  )
}
</code>```

From efficiency point of view, this lib uses macros, so the generated code is practically as good as one could've written by hand

Body:
I have a case class with 25 fields and need to convert it into another with 22, of which 19 of these are shared and 3 are simply renamed.

I have found a few examples of how to do this using shapeless (e.g. an answer here and some code examples from Miles Sabin here and here) but the last of those looks a bit out of date, and I can't figure out from the Github example how I can use shapeless to rename multiple fields, or do more manipulation on a field before adding it to the new object. Can anyone help me out?

Simplified code example;

import shapeless.LabelledGeneric
case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)

val aGen = LabelledGeneric[A]
val bGen = LabelledGeneric[B]

val freddie = new A(1,"Freddie","somestring")

val record = aGen.to(freddie)
val atmp = freddie.fieldA
record.Remove("fielda")

val freddieB = bGen.from(record +
  (Symbol("fieldARenamed") ->> atmp) +
  (Symbol("fieldCTransformed") ->> freddie.fieldC.toUpperCase)
) //Errors everywhere, even if I replace + with :: etc.

I have a feeling Align is going to come into the picture somewhere here, but understanding how to do this in the leanest possible fashion - e.g. without creating additional traits like Field, as in that third link above - would be interesting.

In The Shapeless Guide, there is also some usage of a single quote, (e.g. 'fieldC) notation, which I haven't been able to find much information on, so if that plays a role some explanation would also be really helpful. Fairly new to this depth of Scala sorcery, so apologies if the question seems obtuse or covers too many disparate topics.

EDIT: For the avoidance of doubt, I am not looking for answers which suggest that I just manually create a new case class by referencing fields from the first, as in;

val freddieB = B(fieldARenamed = freddie.fieldA, fieldB = freddie.fieldB, fieldC = freddie.fieldC, fieldCTransformed =freddie.fieldC.toUpperCase)

See below comment for various reasons why this is inappropriate.

Body:
One other option is to use automapper; in particular, Dynamic Mappings feature.

For your particular example it would look like the following:

import io.bfil.automapper._

case class A(fieldA:Int, fieldB:String, fieldC:String)
case class B(fieldARenamed:Int, fieldB:String, fieldC:String, fieldCTransformed:String)

val freddie = new A(1,"Freddie","somestring")

val freddieB = automap(freddie).dynamicallyTo[B](
  fieldARenamed = freddie.fieldA,
  fieldCTransformed = freddie.fieldC.toUpperCase
)

and I guess you can make it a function

def atob(a: A): B = {
  automap(a).dynamicallyTo[B](
    fieldARenamed = a.fieldA,
    fieldCTransformed = a.fieldC.toUpperCase
  )
}

From efficiency point of view, this lib uses macros, so the generated code is practically as good as one could've written by hand


问:
PHP sort by arbitrary order
I need a function in php to sort a list of words according to an arbitrary ordering.

Any words in the list not in my predefined order should be sorted alphabetically at the end of the list.

Below is my first attempt, it is neither elegant or efficient. Can you suggest a better way to acheive this?

Thanks

```<code>public static function sortWords(&$inputArray){
    $order=array("Banana","Orange", "Apple", "Kiwi");
    sort($inputArray);
    for($i=0;$i<count($inputArray));$i++){
        $ac = $inputArray[$i];
        $position = array_search($ac,$order);
        if($position !== false && $i != $position){
            $temp=$inputArray[$position];
            $inputArray[$position]=$inputArray[$i];
            $inputArray[$i]=$temp;
        }
    }
}
</code>```

答:
Probably slower than Headshota's solution, but just to provide you another (not tested) possibility:</p>

```<code>function sortWordsCmp($a, $b) {
  $order=array("Banana","Orange", "Apple", "Kiwi");
  $a = array_search($a, $order);
  $b = array_search($b, $order);

  if ($a === $b)
    return 0;

  return (($b===false) || ($a < $b)) ? -1 : +1;
}

public static function sortWords($inputArray){
  usort($inputArray, 'sortWordsCmp');
  return $inputArray;
}
</code>```

Title: PHP sort by arbitrary order

Body:
I need a function in php to sort a list of words according to an arbitrary ordering.

Any words in the list not in my predefined order should be sorted alphabetically at the end of the list.

Below is my first attempt, it is neither elegant or efficient. Can you suggest a better way to acheive this?

Thanks

public static function sortWords(&$inputArray){
    $order=array("Banana","Orange", "Apple", "Kiwi");
    sort($inputArray);
    for($i=0;$i<count($inputArray));$i++){
        $ac = $inputArray[$i];
        $position = array_search($ac,$order);
        if($position !== false && $i != $position){
            $temp=$inputArray[$position];
            $inputArray[$position]=$inputArray[$i];
            $inputArray[$i]=$temp;
        }
    }
}

Body:
Probably slower than Headshota's solution, but just to provide you another (not tested) possibility:

function sortWordsCmp($a, $b) {
  $order=array("Banana","Orange", "Apple", "Kiwi");
  $a = array_search($a, $order);
  $b = array_search($b, $order);

  if ($a === $b)
    return 0;

  return (($b===false) || ($a < $b)) ? -1 : +1;
}

public static function sortWords($inputArray){
  usort($inputArray, 'sortWordsCmp');
  return $inputArray;
}


问:
Strange type of union
Sorry for the strange title, I don't have much experience with SQL. I'm working with 2 tables : table COMPONENTS, that lists some components, and table OPERATIONS that is a list of operations applied to components.

Table COMPONENTS looks like that :

```<code>+-------+--------------+-------------------+-------+
| Level | Main Article | Secondary Article | Brand |
+-------+--------------+-------------------+-------+
|     1 | Article A    | Article 1         | Foo   |
|     1 | Article B    | Article 1         | Bar   |
+-------+--------------+-------------------+-------+
</code>```

It has a lot more columns, but this is the idea. Basically it lists all articles in stock and what articles they are made of.

The OPERATIONStable contains all the operations a secondary article has to undergo to be incorporated into a main one :

```<code>+--------------------+-----------+------+
| Secondary Article  | Operation | Cost |
+--------------------+-----------+------+
| Article 1          | Cutting   | X    |
| Article 1          | Knitting  | Y    |
| Article 1          | Bleaching | Z    |
+--------------------+-----------+------+
</code>```

What would be the best way to combine those two tables into one that would have this structure ?

```<code>+-------+--------------+-------------------+-----------+------+-------+
| Level | Main Article | Secondary Article | Operation | Cost | Brand |
+-------+--------------+-------------------+-----------+------+-------+
|     1 | Article A    | Article 1         |           |      | Foo   |
|     1 | Article A    | Article 1         | Cutting   | X    | Foo   |
|     1 | Article A    | Article 1         | Knitting  | Y    | Foo   |
|     1 | Article A    | Article 1         | Bleaching | Z    | Foo   |
|     1 | Article B    | Article 1         |           |      | Bar   |
|     1 | Article B    | Article 1         | Cutting   | X    | Bar   |
|     1 | Article B    | Article 1         | Knitting  | Y    | Bar   |
|     1 | Article B    | Article 1         | Bleaching | Z    | Bar   |
+-------+--------------+-------------------+-----------+------+-------+
</code>```

I tried to simplify the problem as much as possible. How should I proceed to manage this ? I tried with joins and unions, but it doesn't work.

It seems to me that this would be super easy to do with a programming language that allows loops, but I'm completely lost here.

答:
This seems like a union all with join:

```<code>select c.Level, c.MainArticle, c.SecondaryArticle,
       NULL as operation, NULL as cost, c.brand
from components c
union all
select c.level, c.MainArticle, c.SecondaryArticle,
       o.operation, o.cost, c.brand
from components c join
     operations o
     on c.SecondaryArticle = o.SecondaryArticle;
</code>```

If you care about the ordering in the result set, use:

```<code>order by MainArticle, SecondaryArticle
</code>```

and whatever other keys you might want.

You could also do the union all before the join, although this might affect performance:

```<code>select c.level, c.MainArticle, c.SecondaryArticle,
       o.operation, o.cost, c.brand
from components c join
     ((select o.SecondaryArticle, o.operation, o.cost
       from operations o
      ) union all
      (select c.SecondaryArticle, NULL, NULL
       from components c
      )
     ) o
     on c.SecondaryArticle = o.SecondaryArticle;
</code>```

Title: Strange type of union

Body:
Sorry for the strange title, I don't have much experience with SQL. I'm working with 2 tables : table COMPONENTS, that lists some components, and table OPERATIONS that is a list of operations applied to components.

Table COMPONENTS looks like that :

+-------+--------------+-------------------+-------+
| Level | Main Article | Secondary Article | Brand |
+-------+--------------+-------------------+-------+
|     1 | Article A    | Article 1         | Foo   |
|     1 | Article B    | Article 1         | Bar   |
+-------+--------------+-------------------+-------+

It has a lot more columns, but this is the idea. Basically it lists all articles in stock and what articles they are made of.

The OPERATIONStable contains all the operations a secondary article has to undergo to be incorporated into a main one :

+--------------------+-----------+------+
| Secondary Article  | Operation | Cost |
+--------------------+-----------+------+
| Article 1          | Cutting   | X    |
| Article 1          | Knitting  | Y    |
| Article 1          | Bleaching | Z    |
+--------------------+-----------+------+

What would be the best way to combine those two tables into one that would have this structure ?

+-------+--------------+-------------------+-----------+------+-------+
| Level | Main Article | Secondary Article | Operation | Cost | Brand |
+-------+--------------+-------------------+-----------+------+-------+
|     1 | Article A    | Article 1         |           |      | Foo   |
|     1 | Article A    | Article 1         | Cutting   | X    | Foo   |
|     1 | Article A    | Article 1         | Knitting  | Y    | Foo   |
|     1 | Article A    | Article 1         | Bleaching | Z    | Foo   |
|     1 | Article B    | Article 1         |           |      | Bar   |
|     1 | Article B    | Article 1         | Cutting   | X    | Bar   |
|     1 | Article B    | Article 1         | Knitting  | Y    | Bar   |
|     1 | Article B    | Article 1         | Bleaching | Z    | Bar   |
+-------+--------------+-------------------+-----------+------+-------+

I tried to simplify the problem as much as possible. How should I proceed to manage this ? I tried with joins and unions, but it doesn't work.

It seems to me that this would be super easy to do with a programming language that allows loops, but I'm completely lost here.

Body:
This seems like a union all with join:

select c.Level, c.MainArticle, c.SecondaryArticle,
       NULL as operation, NULL as cost, c.brand
from components c
union all
select c.level, c.MainArticle, c.SecondaryArticle,
       o.operation, o.cost, c.brand
from components c join
     operations o
     on c.SecondaryArticle = o.SecondaryArticle;

If you care about the ordering in the result set, use:

order by MainArticle, SecondaryArticle

and whatever other keys you might want.

You could also do the union all before the join, although this might affect performance:

select c.level, c.MainArticle, c.SecondaryArticle,
       o.operation, o.cost, c.brand
from components c join
     ((select o.SecondaryArticle, o.operation, o.cost
       from operations o
      ) union all
      (select c.SecondaryArticle, NULL, NULL
       from components c
      )
     ) o
     on c.SecondaryArticle = o.SecondaryArticle;