问:
jest: window.print not implemented
every thing i do in jest, the error is not going to fix and keeps showing below :

```<code> console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Not implemented: window.alert
        at module.exports (D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\Window.js:594:7
        at util_ajvSchemaValidator (D:\Docs\Projects\EMM\emm_next\src\utils\commonUtility.ts:1557:5)
        at Object.<anonymous> (D:\Docs\Projects\EMM\emm_next\tests\unit\utils\commonUtility.test.ts:78:30)
        at Object.asyncJestTest (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\jasmine_async.js:108:37)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:56:12
        at new Promise (<anonymous>)
        at mapper (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:43:19)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:87:41
        at processTicksAndRejections (internal/process/task_queues.js:94:5) undefined

  console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Not implemented: window.print
        at module.exports (D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\Window.js:594:7
        at Object.<anonymous> (D:\Docs\Projects\EMM\emm_next\tests\unit\utils\commonUtility.test.ts:127:5)
        at Object.asyncJestTest (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\jasmine_async.js:108:37)
 FAIL  tests/unit/utils/commonUtility.test.ts (6.407s)jest-jasmine2\build\queue_runner.js:56:12
  util_sum
</code>```

i even used npm i jsdom, but it doesnt fix the problem. even add     "testEnvironment": "jsdom"
 to package.json, but the problem isnt fixed.
is there any proper way to fix this issue?

答:
Since window.alert, print and several other browser-specific side effects needs to be stubbed manually. This should preferably be done with Jest, so a spy could be tracked and cleaned up:

```<code>jest.spyOn(window, 'alert').mockReturnValue();
jest.spyOn(window, 'print').mockReturnValue();
function printTheWebPage(){
  window.print();
}
describe("print", () => {
  it('should print', function () {
    printTheWebPage();
    expect(window.print).toHaveBeenCalled();
  });
});
</code>```

for more info see below links:

https://stackoverflow.com/a/60155951/12666332

https://jestjs.io/docs/en/mock-function-api#mockfnmockreturnvaluevalue

https://jestjs.io/docs/en/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom

Title: jest: window.print not implemented

Body:
every thing i do in jest, the error is not going to fix and keeps showing below :

 console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Not implemented: window.alert
        at module.exports (D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\Window.js:594:7
        at util_ajvSchemaValidator (D:\Docs\Projects\EMM\emm_next\src\utils\commonUtility.ts:1557:5)
        at Object.<anonymous> (D:\Docs\Projects\EMM\emm_next\tests\unit\utils\commonUtility.test.ts:78:30)
        at Object.asyncJestTest (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\jasmine_async.js:108:37)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:56:12
        at new Promise (<anonymous>)
        at mapper (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:43:19)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:87:41
        at processTicksAndRejections (internal/process/task_queues.js:94:5) undefined

  console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Not implemented: window.print
        at module.exports (D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\Window.js:594:7
        at Object.<anonymous> (D:\Docs\Projects\EMM\emm_next\tests\unit\utils\commonUtility.test.ts:127:5)
        at Object.asyncJestTest (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\jasmine_async.js:108:37)
 FAIL  tests/unit/utils/commonUtility.test.ts (6.407s)jest-jasmine2\build\queue_runner.js:56:12
  util_sum

i even used npm i jsdom, but it doesnt fix the problem. even add     "testEnvironment": "jsdom"
 to package.json, but the problem isnt fixed.
is there any proper way to fix this issue?

Body:
Since window.alert, print and several other browser-specific side effects needs to be stubbed manually. This should preferably be done with Jest, so a spy could be tracked and cleaned up:

jest.spyOn(window, 'alert').mockReturnValue();
jest.spyOn(window, 'print').mockReturnValue();
function printTheWebPage(){
  window.print();
}
describe("print", () => {
  it('should print', function () {
    printTheWebPage();
    expect(window.print).toHaveBeenCalled();
  });
});

for more info see below links:

https://stackoverflow.com/a/60155951/12666332

https://jestjs.io/docs/en/mock-function-api#mockfnmockreturnvaluevalue

https://jestjs.io/docs/en/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom


来源: stackexchange

问:
How is inline style added to HTML elements by Highcharts?
I am using the Highcharts library to create diagrams. I have two seemingly very similar charts that don't behave the same in terms of CSS for reasons I am trying to find out.

One thing I observed is that for example the menu items of an export button within these two charts have different code (extracted with Chrome Dev Tools).

The chart that 'behaves' in general as expected in terms of styling has this element code:

```<code><div class="highcharts-menu-item" style="cursor: pointer; padding: 0.5em 1em; color: rgb(51, 51, 51); background: none; font-size: 11px; transition: background 250ms ease 0s, color 250ms ease 0s;">Download PDF document</div>
</code>```

The chart that does not 'react' when I change styles has for the same menu item this element code:

```<code><div class="highcharts-menu-item">Download PDF document</div>
</code>```

So the inline style is missing. When I am trying to search inline style code of the first element given, e.g. 'background: none;' I get no results for my whole project. So I assume that the Highcharts library is responsible for adding these inline styles with some JavaScript.

What could be reasons that this is done in the first element given and not in the second one?

Some explanation on how this mechanism obviously used by the library works, would be very helpful for my understanding on what is going on.

PS: I am using the React wrapper in case this has any relevance:

```<code><HighchartsReact
  highcharts={ Highcharts }
  constructorType={"stockChart"}
  options={chartOptions}
  ref="chartComponent"
  allowChartUpdate={this.allowChartUpdate}
/>
</code>```

Edit: I am using styled mode. In this case it is necessary to write CSS rules using the classes defined by highcharts, e.g. .highcharts-title but still I need to write !important like here

```<code>font-size: 22px !important;
</code>```

so that this font-size supersedes the 'infused' styles as described above (although there is no style attribute given in the chartOptions (which I think would anyway be superseded by CSS rules).

答:
There is on props i.e. containerProps which needs class name (I think).

So what I suggest is create a css-class in your css file and pass that class name to that prop like this:

```<code>containerProps = {{ className: 'chartContainer' }}
</code>```

You can read more about this from here

ContentLicense: CC BY-SA 4.0

Body:
I am using the Highcharts library to create diagrams. I have two seemingly very similar charts that don't behave the same in terms of CSS for reasons I am trying to find out.

One thing I observed is that for example the menu items of an export button within these two charts have different code (extracted with Chrome Dev Tools).

The chart that 'behaves' in general as expected in terms of styling has this element code:

Download PDF document

The chart that does not 'react' when I change styles has for the same menu item this element code:

Download PDF document

So the inline style is missing. When I am trying to search inline style code of the first element given, e.g. 'background: none;' I get no results for my whole project. So I assume that the Highcharts library is responsible for adding these inline styles with some JavaScript.

What could be reasons that this is done in the first element given and not in the second one?

Some explanation on how this mechanism obviously used by the library works, would be very helpful for my understanding on what is going on.

PS: I am using the React wrapper in case this has any relevance:

<HighchartsReact
  highcharts={ Highcharts }
  constructorType={"stockChart"}
  options={chartOptions}
  ref="chartComponent"
  allowChartUpdate={this.allowChartUpdate}
/>

Edit: I am using styled mode. In this case it is necessary to write CSS rules using the classes defined by highcharts, e.g. .highcharts-title but still I need to write !important like here

font-size: 22px !important;

so that this font-size supersedes the 'infused' styles as described above (although there is no style attribute given in the chartOptions (which I think would anyway be superseded by CSS rules).

Body:
There is on props i.e. containerProps which needs class name (I think).

So what I suggest is create a css-class in your css file and pass that class name to that prop like this:

containerProps = {{ className: 'chartContainer' }}

You can read more about this from here


问:
How to access the api for git in visual studio code
I want to use the vscode git api in one my extension to do git clone and other tasks. Is it accessible from the vscode api ?
The code is present here.. api</p>

答:
Sample code for using git api in vscode extension :

const gitExtension = vscode.extensions.getExtension('vscode.git').exports;
const api = gitExtension.getAPI(1);

const repo = api.repositories[0];
const head = repo.state.HEAD;

// Get the branch and commit
const {commit,name: branch} = head;

// Get head of any other branch
const mainBranch = 'master'
const branchDetails = await repo.getBranch(mainBranch);

// Get last merge commit
const lastMergeCommit = await repo.getMergeBase(branch, mainBranch);

const status = await repo.status();

console.log({ branch, commit, lastMergeCommit, needsSync: lastMergeCommit !== commit });
```

<p>You also have to update extensionDependencies in you package.json: </p>

```"extensionDependencies": [
    "vscode.git"
  ]
```

ContentLicense: CC BY-SA 3.0

Body:
Sample code for using git api in vscode extension :

const gitExtension = vscode.extensions.getExtension('vscode.git').exports;
const api = gitExtension.getAPI(1);

const repo = api.repositories[0];
const head = repo.state.HEAD;

// Get the branch and commit
const {commit,name: branch} = head;

// Get head of any other branch
const mainBranch = 'master'
const branchDetails = await repo.getBranch(mainBranch);

// Get last merge commit
const lastMergeCommit = await repo.getMergeBase(branch, mainBranch);

const status = await repo.status();

console.log({ branch, commit, lastMergeCommit, needsSync: lastMergeCommit !== commit });

You also have to update extensionDependencies in you package.json:

"extensionDependencies": [
    "vscode.git"
  ]


问:
Changing the class name JS
I have this code on the page:

```<code><td class="CalendarDay CalendarDay--valid" style="width: 39px; height: 38px;"><button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button></td>
</code>```

I want to change the class name if there is a string "niedziela" in the "aria-label" attribute.
I wrote something, but unfortunately it doesn't work and I don't know what to do. My code:

```<code>var string = document.getElementsByClassName("CalendarDay CalendarDay--valid").aria-label,
    substring = "niedziela";

if (string.includes(substring)) {
    document.getElementsByClassName("CalendarDay CalendarDay--valid").className = "CalendarDay CalendarDay--blocked CalendarDay--blocked-out-of-range";
}
</code>```

答:
Perhaps this?

document.querySelector("button[aria-label*=niedziela]").classList.add("CalendarDay--blocked-out-of-range");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button { background-color:blue }
.CalendarDay--blocked-out-of-range { background-color:red }</code>```

<button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button>

```
</div>
</div>
</p>

<p>Perhaps just use CSS</p>

<p>Move the CSS under the datepicker one</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>button[aria-label*=niedziela] { background-color:red }</code>```

<button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button>

```

Title: Changing the class name JS

Body:
I have this code on the page:

<button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button>

I want to change the class name if there is a string "niedziela" in the "aria-label" attribute.
I wrote something, but unfortunately it doesn't work and I don't know what to do. My code:

var string = document.getElementsByClassName("CalendarDay CalendarDay--valid").aria-label,
    substring = "niedziela";

if (string.includes(substring)) {
    document.getElementsByClassName("CalendarDay CalendarDay--valid").className = "CalendarDay CalendarDay--blocked CalendarDay--blocked-out-of-range";
}

Body:
Perhaps this?

document.querySelector("button[aria-label*=niedziela]").classList.add("CalendarDay--blocked-out-of-range");

button { background-color:blue }
.CalendarDay--blocked-out-of-range { background-color:red }

<table><tr>
<td class="CalendarDay CalendarDay--valid" style="width: 39px; height: 38px;"><button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button></td></tr></table>

Perhaps just use CSS

Move the CSS under the datepicker one

button[aria-label*=niedziela] { background-color:red }

<table><tr>
<td class="CalendarDay CalendarDay--valid" style="width: 39px; height: 38px;"><button type="button" class="CalendarDay__button" aria-label="Choose niedziela, 16 lutego 2020 as your check-in date. It's available." tabindex="-1">16</button></td></tr></table>


问:
SQL padding 0 to the left of a number in string
I am a beginner in SQL language and I am using postgre sql and doing little exercices to learn. I have a column of strings named acronym from a destination table:

```<code> DO1
 ES1
 ES2
 FR1
 FR10
 FR2
 FR3
 FR4
 FR5
 FR6
 FR7
 FR8
 FR9
 GP1
 GP2
 IN1
 IN2
 MU1
 RU1
 TR1
 UA1
</code>```

I would like to add a padding zero for acronym numbers that have only one digit, output:

```<code> DO01
 ES01
 ES02
 FR01
 FR02
 FR03
 FR04
 FR05
 FR06
 FR07
 FR08
 FR09
 FR10
 GP01
 GP02
 IN01
 IN02
 MU01
 RU01
 TR01
 UA01
</code>```

How can I get to the left of the first number in the string? There is some regex I think but I did not figure it out

答:
You can use the rpad() function to add characters to the end of the value:

```<code>select rpad(col, '0', 4)
</code>```

In your case, though, you want a value in-between.  On simple method is -- assuming that the first two characters are strings -- is:

```<code>(case when length(col) = 3
      then left(col, 2) || '0' || right(col, 1)
      else col
 end)
</code>```

Another possibility is using regexp_replace():

```<code>regexp_replace(col, '^([^0-9]{2})([0-9])$', '\10\2')
</code>```

Both of these assume that the strings to be padded are three characters, which is consistent with your data.  It is unclear what you want for other lengths.

Body:
I am a beginner in SQL language and I am using postgre sql and doing little exercices to learn. I have a column of strings named acronym from a destination table:

 DO1
 ES1
 ES2
 FR1
 FR10
 FR2
 FR3
 FR4
 FR5
 FR6
 FR7
 FR8
 FR9
 GP1
 GP2
 IN1
 IN2
 MU1
 RU1
 TR1
 UA1

I would like to add a padding zero for acronym numbers that have only one digit, output:

 DO01
 ES01
 ES02
 FR01
 FR02
 FR03
 FR04
 FR05
 FR06
 FR07
 FR08
 FR09
 FR10
 GP01
 GP02
 IN01
 IN02
 MU01
 RU01
 TR01
 UA01

How can I get to the left of the first number in the string? There is some regex I think but I did not figure it out

Body:
You can use the rpad() function to add characters to the end of the value:

select rpad(col, '0', 4)

In your case, though, you want a value in-between.  On simple method is -- assuming that the first two characters are strings -- is:

(case when length(col) = 3
      then left(col, 2) || '0' || right(col, 1)
      else col
 end)

Another possibility is using regexp_replace():

regexp_replace(col, '^([^0-9]{2})([0-9])$', '\10\2')

Both of these assume that the strings to be padded are three characters, which is consistent with your data.  It is unclear what you want for other lengths.


问:
jQuery get anchor value
I am trying to get the value of a clicked anchor but I am not sure which anchor is being clicked or how to latch onto it with jquery.  I have a document.ready function

```<code>$(document).ready(function () {
var ActiveBlogStats = $('#BlogSelectList');
$('#BlogSelectList').click(function () {
    alert(ActiveBlogStats.text)
}); })
</code>```

Here is the id that it is working on

```<code><ul class="submenu" id="BlogSelectList">
  <xsl:for-each select="oohru/user/oohblog">
    <li>
      <a>
        <xsl:attribute name="href">#<xsl:value-of select="normalize-space(blogid)"/></xsl:attribute>
        <xsl:value-of select="oohblogurl"/>
      </a>
    </li>
  </xsl:for-each>
<li><a href="AddNewBlog.aspx">+ Create a new oohblog</a></li>
</ul>
</code>```

How can I get the href of the actual anchor being clicked?  I don't see how to make a document.ready even for items that don't exist until after the document is ready.
I suppose I could get the # value from the URL since when they click one it will update the URL but I would rather get it directly from the click.

答:
```<code>$("#BlogSelectList a").click(function(){

var href = $(this).attr("href");

});
</code>```

Title: jQuery get anchor value

Body:
I am trying to get the value of a clicked anchor but I am not sure which anchor is being clicked or how to latch onto it with jquery.  I have a document.ready function

$(document).ready(function () {
var ActiveBlogStats = $('#BlogSelectList');
$('#BlogSelectList').click(function () {
    alert(ActiveBlogStats.text)
}); })

Here is the id that it is working on

  <xsl:for-each select="oohru/user/oohblog">

        <xsl:attribute name="href">#<xsl:value-of select="normalize-space(blogid)"/></xsl:attribute>
        <xsl:value-of select="oohblogurl"/>

  </xsl:for-each>

+ Create a new oohblog

How can I get the href of the actual anchor being clicked?  I don't see how to make a document.ready even for items that don't exist until after the document is ready.
I suppose I could get the # value from the URL since when they click one it will update the URL but I would rather get it directly from the click.


问:
Django - Getting 405 error when submitting contact form
My Html contact form

```<code><form id="contact-form" method="post" action="{% url 'index' %}">
                        {% csrf_token %}
                        <div class="messages"></div>

                        <div class="controls">

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group wow fadeInDown" data-wow-delay="0.2s">
                                        <input id="form_name" type="text" name="name" class="form-control"
                                               placeholder="Enter your full name *" required="required"
                                               data-error="Fullname is required.">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group wow fadeInDown" data-wow-delay="0.4s">
                                        <input id="form_email" type="email" name="email" class="form-control"
                                               placeholder="Enter your email *" required="required"
                                               data-error="Valid email is required.">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group wow fadeInUp" data-wow-delay="0.6s">
                                        <textarea id="form_message" name="message" class="form-control"
                                                  placeholder="Your Message *" rows="4" required="required"
                                                  data-error="Leave a message for me"></textarea>
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <button class="btn btn-send" type="submit">Send message</button>
                                </div>
                            </div>
                        </div>

                    </form>
</code>```

urls.py

```<code>from django.urls import path
from .views import HomeTemplateView

urlpatterns = [
    path('', HomeTemplateView.as_view(), name="index")
]
</code>```

views.py, I defined my HomeTemplate view class with a method index that is handling my contact form

```<code>from django.shortcuts import render
from django.views.generic import TemplateView
from .models import *
from django.core.mail import send_mail
from django.conf import settings

class HomeTemplateView(TemplateView):
    template_name = 'home.html'

    # override get context date method
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['about'] = About.objects.first()
        context['services'] = Service.objects.all()
        context['works'] = RecentWork.objects.all()
        context['clients'] = Client.objects.all()
        return context

    def index(self, request):
        if request.method == 'POST':
            message = request.POST['message']
            sender = request.POST['email']

            send_mail('Contact Form',
                      message,
                      sender,
                      [settings.EMAIL_HOST_USER],
                      fail_silently=False)
        return render(request, 'home.html')
</code>```

Everytime I try to submit I get a 405 method not found, I just don't understand how to set up this correctly in order to work the way I want it to.
Does anyone have a solution ?

答:
Have you tried to add get and post method to your CBV?

from django.shortcuts import render
from django.views.generic import TemplateView
from .models import *
from django.core.mail import send_mail
from django.conf import settings

class HomeTemplateView(TemplateView):
    template_name = 'home.html'

    # override get context date method
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['about'] = About.objects.first()
        context['services'] = Service.objects.all()
        context['works'] = RecentWork.objects.all()
        context['clients'] = Client.objects.all()
        return context

    def get(self, request):
        return render(request, 'home.html')

    def post(self, request):
        if request.method == 'POST':
            message = request.POST['message']
            sender = request.POST['email']

            send_mail('Contact Form',
                      message,
                      sender,
                      [settings.EMAIL_HOST_USER],
                      fail_silently=False)
        return render(request, 'home.html')
```

Body:
My Html contact form

<form id="contact-form" method="post" action="{% url 'index' %}">
                        {% csrf_token %}

                                        <input id="form_name" type="text" name="name" class="form-control"
                                               placeholder="Enter your full name *" required="required"
                                               data-error="Fullname is required.">

                                        <input id="form_email" type="email" name="email" class="form-control"
                                               placeholder="Enter your email *" required="required"
                                               data-error="Valid email is required.">

                                        <textarea id="form_message" name="message" class="form-control"
                                                  placeholder="Your Message *" rows="4" required="required"
                                                  data-error="Leave a message for me"></textarea>

                                    <button class="btn btn-send" type="submit">Send message</button>

                    </form>

urls.py

from django.urls import path
from .views import HomeTemplateView

urlpatterns = [
    path('', HomeTemplateView.as_view(), name="index")
]

views.py, I defined my HomeTemplate view class with a method index that is handling my contact form

from django.shortcuts import render
from django.views.generic import TemplateView
from .models import *
from django.core.mail import send_mail
from django.conf import settings

class HomeTemplateView(TemplateView):
    template_name = 'home.html'

    # override get context date method
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['about'] = About.objects.first()
        context['services'] = Service.objects.all()
        context['works'] = RecentWork.objects.all()
        context['clients'] = Client.objects.all()
        return context

    def index(self, request):
        if request.method == 'POST':
            message = request.POST['message']
            sender = request.POST['email']

            send_mail('Contact Form',
                      message,
                      sender,
                      [settings.EMAIL_HOST_USER],
                      fail_silently=False)
        return render(request, 'home.html')

Everytime I try to submit I get a 405 method not found, I just don't understand how to set up this correctly in order to work the way I want it to.
Does anyone have a solution ?


问:
Value of input field chnaged in inspector but not in browser window
I dont know why but the value of my text field does not change when back button is pressed in chrome

below is the link to the video on youtube you can see that the program is working fine in edge but not in chrome and opera.

video - https://youtu.be/zRPRMa4f_hk project file - https://drive.google.com/file/d/13Q7gxc-fvzkvftk769Qy51u60_Pxd4IU/view?usp=sharing

the problem is that when i press the back button in chrome even though the query string changes and the value of input text element changes in inspector it does not change in browser window.

Please help me guy anyone. Im stuck.

答: write autocomplete = "off" in form</p>

Body: write autocomplete = "off" in form


问:
How to define conditional string types in Typescript like flow?
```<code>type UpsertMode = | 'add' | 'update' | 'delete';

interface IUpsertMembers {
  mode: UpsertMode;
}

const MagicButton = ({ mode: UpsertMode }) => {
  return (
    <button>{mode}</button>
  );
}

const UpsertMembers = ({ mode }: IUpsertMembers) => {
  return (
    <MagicButton mode={mode} />
  );
};

export default UpsertMembers;

</code>```

I am trying to use it inside a .tsx file and the type still turns out to be any

It gives an error saying

```<code>Binding element 'UpsertMode' implicitly has an 'any' type.  TS7031
</code>```

答:
Try removing the initial |</p>

```<code>type UpsertMode = add' | 'update' | 'delete';
</code>```

Body:
type UpsertMode = | 'add' | 'update' | 'delete';

interface IUpsertMembers {
  mode: UpsertMode;
}

const MagicButton = ({ mode: UpsertMode }) => {
  return (
    <button>{mode}</button>
  );
}

const UpsertMembers = ({ mode }: IUpsertMembers) => {
  return (
    <MagicButton mode={mode} />
  );
};

export default UpsertMembers;

I am trying to use it inside a .tsx file and the type still turns out to be any

It gives an error saying

Binding element 'UpsertMode' implicitly has an 'any' type.  TS7031

Body:
Try removing the initial |

type UpsertMode = add' | 'update' | 'delete';


问:
Can someone help me t understand this PHP code
I am working from an existing project and hit a road block

I am trying to understand the following

```<code>$list = "" . substr($data, $start,$length) . "";
$new_list = explode("|" , $list);
</code>```

Yes $start and $length are set, that is not the concern.

I need to try to understand the "double double quotes dot" and "dot double double quotes" and their implications on the php explode command that follows.

Is this simply saying that $list contents will be like this?

```<code>" . <Content here> . "
</code>```

I did not think concatenate "." was ever used with double quotes.

Thanks for any help

答:
dot is only for concatination of string.
double double quotes  is empty string.

explode makes an array from string.

```<code>$list = "aaaa|bbbb|cccc";
$new_list = explode("|" , $list);
</code>```

Result:

```<code>array("aaaa","bbbb","cccc");
</code>```

look at php.net. there are samples too.

Body:
I am working from an existing project and hit a road block

I am trying to understand the following

$list = "" . substr($data, $start,$length) . "";
$new_list = explode("|" , $list);

Yes $start and $length are set, that is not the concern.

I need to try to understand the "double double quotes dot" and "dot double double quotes" and their implications on the php explode command that follows.

Is this simply saying that $list contents will be like this?

" . <Content here> . "

I did not think concatenate "." was ever used with double quotes.

Thanks for any help

Body:
dot is only for concatination of string.
double double quotes  is empty string.

explode makes an array from string.

$list = "aaaa|bbbb|cccc";
$new_list = explode("|" , $list);

Result:

array("aaaa","bbbb","cccc");

look at php.net. there are samples too.


问:
How to get received Bytes data in Numpy array in Python
I am working on a python program to receive data from TCP socket. I am successfully able to receive the data in bytes format. The required result I need is to receive the output in Numpy array format. Please help me in the below code to receive the output in numpy array format.

Code:

```<code>from __future__ import print_function
import socket
import sys
import time
from time import sleep
import csv
start = time.time()
def comm_dists(ip, port):

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (ip, port)
    print(sys.stderr, 'connecting to %s port %s' % server_address)
    sock.connect(server_address)
    print("Connected")
    try:

        # Send data
        message = b'\x02\x02\x02\x02\x00\x00\x00\x10sMI 0 3 F4724744 '
        sock.sendall(message)
        print(sys.stderr, 'sending "%s"' % message)
        print('sent "%s"' % message)
        # Look for the response
        data = sock.recv(5000)
        print(sys.stderr, 'received "%s"' % data)
        sleep(0.05)
        # Error Verification
        #erros(data)
        message = b"\x02\x02\x02\x02\x00\x00\x00\x06sMI 5E'"
        sock.sendall(message)
        print(sys.stderr, 'sending "%s"' % message)
        print('sent "%s"' % message)
        data = sock.recv(5000)
        print(sys.stderr, 'received "%s"' % data)
        sleep(0.05)
        message = b'\x02\x02\x02\x02\x00\x00\x00\x05sMI 2e'
        sock.sendall(message)
        print(sys.stderr, 'sending "%s"' % message)
        print('sent "%s"' % message)
        data = sock.recv(5000)
        print(sys.stderr, 'received "%s"' % data)
        sleep(0.05)
        message = b'\x02\x02\x02\x02\x00\x00\x00\x07sEI A 1\x0f'
        sock.sendall(message)
        print(sys.stderr, 'sending "%s"' % message)
        print('sent "%s"' % message)
        data = sock.recv(5000)
        print(sys.stderr, 'received "%s"' % data)
        sleep(0.05)
        message = b'\x02\x02\x02\x02\x00\x00\x00\x06sRI C5>'
        sock.sendall(message)
        print(sys.stderr, 'sending "%s"' % message)
        print('sent "%s"' % message)
        data = sock.recv(5000)
        print(sys.stderr, 'received "%s"' % data)
        sleep(0.05)
        while True:
            data = sock.recv(500)
            print('received "%s"' % data)
    finally:
        print(sys.stderr, 'closing socket')
    return data

i=0

while i < int(1):
    data = comm_dists('192.168.0.1', 2111)
    data = data.decode()
    # data = re.sub(r'[^\x00-\x7f]', r'', data)
    print(data)
    end = time.time()
    print(end - start, 'segundos')
    i=i+1
</code>```

Below is the continuous output:

```<code>"b'\x02\x02\x02\x02\x00\x00\x00\x08sMA 0002]\x02\x02\x02\x02\x00\x00\x00\x0bsAI 0002 01x\x02\x02\x02\x02\x00\x00\x05\x97sSI 000A 425C0000 3E800000 0118 0AAB 0A98 0A87 0A6D 0A47 0950 0395 0397 038C 0389 0383 0384 037B 037E 0372 036C 0371 0370 0368 0365 0367 0362 0366 0364 035C 034D 0356 0353 0350 034B 034A 034F 0345 0346 0349 033B 033E 033C 033D 033C 033A 0334 0333 0336 0334 0330 0331 0331 0326 0325 0327 0323 0323 031E 031F 031F 0323 0320 031B 0319 0317 0319 0318 0317 0311 0314 030B 030E 030A 030D 0307 030C 030B 0309 030C 0307 0308 0302 0307 02FF 0301 0300 02FE 0300 02FC 02FA 02FE 02F9 02FC 02F8 02FB 02F7 02F7 02F8 02F3 02FB 02FB 02F5 02F4 02F3 02F2 02EC 02EE 02EF 02ED 02F0 02F0 02EB 02F1 02F0 02EA 02EB 02E7 02EB 02EA 02EB 02E9 02EC 02EA 02EC 02E5 02E3 02EC 02EA 02E4 02E8 02E7 02EC 02E7 02E4 02EC 02E8 02ED 02E1 02D9 029F 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000o'"
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'> sending "b'\x02\x02\x02\x02\x00\x00\x00\x06sRI C5>'"
sent "b'\x02\x02\x02\x02\x00\x00\x00\x06sRI C5>'"
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'> received "b'\x02\x02\x02\x02\x00\x00\x00\x0bsEA 000A 01\x07\x02\x02\x02\x02\x00\x00\x05\x97sSI 000A 425C0000 3E800000 0118 0AC1 0AB1 0A9B 0A8C 0A64 0A4E 0502 038B 0392 0386 0389 038D 0376 0374 0375 0376 0378 036F 036B 0367 0363 0363 035D 035E 0358 0357 0357 0351 0351 0352 0349 034C 0346 0344 0341 034B 033F 0341 0339 033C 033B 033B 0332 0331 0330 032B 0331 032F 032A 0327 0322 0324 0328 031E 031E 0320 0320 031C 0321 031D 0318 0317 0317 0316 0314 030F 0314 030D 0309 030C 030C 0309 0309 030A 0305 0303 0304 0303 0300 0303 02FE 0301 02F9 02FF 02FF 02FA 02F9 02FD 02FC 02F8 02F4 02FD 02F6 02F6 02F2 02FA 02FA 02F2 02F0 02F3 02F2 02F5 02EF 02F0 02EE 02EC 02F0 02E9 02F2 02EF 02ED 02EE 02E9 02EE 02EB 02E6 02E7 02E6 02E8 02E9 02EE 02E7 02E9 02E6 02E9 02E1 02E3 02E6 02E9 02E8 02EC 02E1 02EA 02D6 02DE 02CE 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000\x19'"
received "b'\x02\x02\x02\x02\x00\x00\x05\x97sRA 00C5 425C0000 3E800000 0118 0AC1 0AB1 0A9B 0A8C 0A64 0A4E 0502 038B 0392 0386 0389 038D 0376 0374 0375 0376 0378 036F 036B 0367 0363 0363 035D 035E 0358 0357 0357 0351 0351 0352 0349 034C 0346 0344 0341 034B 033F 0341 0339 033C 033B 033B 0332 0331 0330 032B 0331 032F 032A 0327 0322 0324 0328 031E 031E 0320 0320 031C 0321 031D 0318 0317 0317 0316 0314 030F 0314 030D 0309 030C 030C 0309 0309 030A 0305 0303 0304 0303 0300 0303 02FE 0301 02F9 02FF 02FF 02FA 02F9 02FD 02FC 02F8 02F4 02FD '"
received "b'02F6 02F6 02F2 02FA 02FA 02F2 02F0 02F3 02F2 02F5 02EF 02F0 02EE 02EC 02F0 02E9 02F2 02EF 02ED 02EE 02E9 02EE 02EB 02E6 02E7 02E6 02E8 02E9 02EE 02E7 02E9 02E6 02E9 02E1 02E3 02E6 02E9 02E8 02EC 02E1 02EA 02D6 02DE 02CE 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 '"
received "b'0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000\x17'"
received "b'\x02\x02\x02\x02\x00\x00\x05\x97sSI 000A 425C0000 3E800000 0118 0ABE 0AA9 0AA1 0A83 0A64 0A49 07C4 038E 0387 0385 0389 0384 037F 037F 0384 0376 0375 0372 0374 036D 0366 035C 0363 0360 035C 0359 035C 0352 0351 034B 0348 034C 0346 034A 0345 0347 0345 0342 0341 033A 033A 0335 0337 0336 0331 032F 032A 032D 032E 0325 0327 0322 0325 0329 0326 0322 031F 0321 0318 031B 031B 0317 031C 0311 0318 0312 030F 0311 030A 030A 030A 030A 030C 030C 0305 0309 0308 0304 0308 0305 0306 0307 02FE 02FA 02FE 0302 02FC 02FC 02F9 0300 02FA 02F7 '"

</code>```

Required Result: I want to view these above output as a numpy array. Please help in the above code to modify the result.

答:
Do this:

```<code>data = sock.recv(5000)
np.frombuffer(data, dtype='u1')
</code>```

Or you can choose another 1-byte dtype like 'S1' if you want to treat the values as characters, or 'i1' if you want to treat them as signed.

Body:
I am working on a python program to receive data from TCP socket. I am successfully able to receive the data in bytes format. The required result I need is to receive the output in Numpy array format. Please help me in the below code to receive the output in numpy array format.

Code:

from __future__ import print_function
import socket
import sys
import time
from time import sleep
import csv
start = time.time()
def comm_dists(ip, port):

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (ip, port)
    print(sys.stderr, 'connecting to %s port %s' % server_address)
    sock.connect(server_address)
    print("Connected")
    try:

        # Send data
        message = b'\x02\x02\x02\x02\x00\x00\x00\x10sMI 0 3 F4724744 '
        sock.sendall(message)
        print(sys.stderr, 'sending "%s"' % message)
        print('sent "%s"' % message)
        # Look for the response
        data = sock.recv(5000)
        print(sys.stderr, 'received "%s"' % data)
        sleep(0.05)
        # Error Verification
        #erros(data)
        message = b"\x02\x02\x02\x02\x00\x00\x00\x06sMI 5E'"
        sock.sendall(message)
        print(sys.stderr, 'sending "%s"' % message)
        print('sent "%s"' % message)
        data = sock.recv(5000)
        print(sys.stderr, 'received "%s"' % data)
        sleep(0.05)
        message = b'\x02\x02\x02\x02\x00\x00\x00\x05sMI 2e'
        sock.sendall(message)
        print(sys.stderr, 'sending "%s"' % message)
        print('sent "%s"' % message)
        data = sock.recv(5000)
        print(sys.stderr, 'received "%s"' % data)
        sleep(0.05)
        message = b'\x02\x02\x02\x02\x00\x00\x00\x07sEI A 1\x0f'
        sock.sendall(message)
        print(sys.stderr, 'sending "%s"' % message)
        print('sent "%s"' % message)
        data = sock.recv(5000)
        print(sys.stderr, 'received "%s"' % data)
        sleep(0.05)
        message = b'\x02\x02\x02\x02\x00\x00\x00\x06sRI C5>'
        sock.sendall(message)
        print(sys.stderr, 'sending "%s"' % message)
        print('sent "%s"' % message)
        data = sock.recv(5000)
        print(sys.stderr, 'received "%s"' % data)
        sleep(0.05)
        while True:
            data = sock.recv(500)
            print('received "%s"' % data)
    finally:
        print(sys.stderr, 'closing socket')
    return data

i=0

while i < int(1):
    data = comm_dists('192.168.0.1', 2111)
    data = data.decode()
    # data = re.sub(r'[^\x00-\x7f]', r'', data)
    print(data)
    end = time.time()
    print(end - start, 'segundos')
    i=i+1

Below is the continuous output:

"b'\x02\x02\x02\x02\x00\x00\x00\x08sMA 0002]\x02\x02\x02\x02\x00\x00\x00\x0bsAI 0002 01x\x02\x02\x02\x02\x00\x00\x05\x97sSI 000A 425C0000 3E800000 0118 0AAB 0A98 0A87 0A6D 0A47 0950 0395 0397 038C 0389 0383 0384 037B 037E 0372 036C 0371 0370 0368 0365 0367 0362 0366 0364 035C 034D 0356 0353 0350 034B 034A 034F 0345 0346 0349 033B 033E 033C 033D 033C 033A 0334 0333 0336 0334 0330 0331 0331 0326 0325 0327 0323 0323 031E 031F 031F 0323 0320 031B 0319 0317 0319 0318 0317 0311 0314 030B 030E 030A 030D 0307 030C 030B 0309 030C 0307 0308 0302 0307 02FF 0301 0300 02FE 0300 02FC 02FA 02FE 02F9 02FC 02F8 02FB 02F7 02F7 02F8 02F3 02FB 02FB 02F5 02F4 02F3 02F2 02EC 02EE 02EF 02ED 02F0 02F0 02EB 02F1 02F0 02EA 02EB 02E7 02EB 02EA 02EB 02E9 02EC 02EA 02EC 02E5 02E3 02EC 02EA 02E4 02E8 02E7 02EC 02E7 02E4 02EC 02E8 02ED 02E1 02D9 029F 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000o'"
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'> sending "b'\x02\x02\x02\x02\x00\x00\x00\x06sRI C5>'"
sent "b'\x02\x02\x02\x02\x00\x00\x00\x06sRI C5>'"
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'> received "b'\x02\x02\x02\x02\x00\x00\x00\x0bsEA 000A 01\x07\x02\x02\x02\x02\x00\x00\x05\x97sSI 000A 425C0000 3E800000 0118 0AC1 0AB1 0A9B 0A8C 0A64 0A4E 0502 038B 0392 0386 0389 038D 0376 0374 0375 0376 0378 036F 036B 0367 0363 0363 035D 035E 0358 0357 0357 0351 0351 0352 0349 034C 0346 0344 0341 034B 033F 0341 0339 033C 033B 033B 0332 0331 0330 032B 0331 032F 032A 0327 0322 0324 0328 031E 031E 0320 0320 031C 0321 031D 0318 0317 0317 0316 0314 030F 0314 030D 0309 030C 030C 0309 0309 030A 0305 0303 0304 0303 0300 0303 02FE 0301 02F9 02FF 02FF 02FA 02F9 02FD 02FC 02F8 02F4 02FD 02F6 02F6 02F2 02FA 02FA 02F2 02F0 02F3 02F2 02F5 02EF 02F0 02EE 02EC 02F0 02E9 02F2 02EF 02ED 02EE 02E9 02EE 02EB 02E6 02E7 02E6 02E8 02E9 02EE 02E7 02E9 02E6 02E9 02E1 02E3 02E6 02E9 02E8 02EC 02E1 02EA 02D6 02DE 02CE 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000\x19'"
received "b'\x02\x02\x02\x02\x00\x00\x05\x97sRA 00C5 425C0000 3E800000 0118 0AC1 0AB1 0A9B 0A8C 0A64 0A4E 0502 038B 0392 0386 0389 038D 0376 0374 0375 0376 0378 036F 036B 0367 0363 0363 035D 035E 0358 0357 0357 0351 0351 0352 0349 034C 0346 0344 0341 034B 033F 0341 0339 033C 033B 033B 0332 0331 0330 032B 0331 032F 032A 0327 0322 0324 0328 031E 031E 0320 0320 031C 0321 031D 0318 0317 0317 0316 0314 030F 0314 030D 0309 030C 030C 0309 0309 030A 0305 0303 0304 0303 0300 0303 02FE 0301 02F9 02FF 02FF 02FA 02F9 02FD 02FC 02F8 02F4 02FD '"
received "b'02F6 02F6 02F2 02FA 02FA 02F2 02F0 02F3 02F2 02F5 02EF 02F0 02EE 02EC 02F0 02E9 02F2 02EF 02ED 02EE 02E9 02EE 02EB 02E6 02E7 02E6 02E8 02E9 02EE 02E7 02E9 02E6 02E9 02E1 02E3 02E6 02E9 02E8 02EC 02E1 02EA 02D6 02DE 02CE 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 '"
received "b'0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000\x17'"
received "b'\x02\x02\x02\x02\x00\x00\x05\x97sSI 000A 425C0000 3E800000 0118 0ABE 0AA9 0AA1 0A83 0A64 0A49 07C4 038E 0387 0385 0389 0384 037F 037F 0384 0376 0375 0372 0374 036D 0366 035C 0363 0360 035C 0359 035C 0352 0351 034B 0348 034C 0346 034A 0345 0347 0345 0342 0341 033A 033A 0335 0337 0336 0331 032F 032A 032D 032E 0325 0327 0322 0325 0329 0326 0322 031F 0321 0318 031B 031B 0317 031C 0311 0318 0312 030F 0311 030A 030A 030A 030A 030C 030C 0305 0309 0308 0304 0308 0305 0306 0307 02FE 02FA 02FE 0302 02FC 02FC 02F9 0300 02FA 02F7 '"

Required Result: I want to view these above output as a numpy array. Please help in the above code to modify the result.

Body:
Do this:

data = sock.recv(5000)
np.frombuffer(data, dtype='u1')

Or you can choose another 1-byte dtype like 'S1' if you want to treat the values as characters, or 'i1' if you want to treat them as signed.


问:
How to run a python script as a subprocess inside Google Cloud Function
```<code>import subprocess
import os

def execute():
    code = "def Solution():\n\tprint('Hello')\n\nSolution()\n"
    f = open('/tmp/Solution.py','w')
    f.write(code+'\n')
    f.close()
    s = subprocess.check_output("python /tmp/Solution.py", shell = True)
    return s
</code>```

I am calling execute function from the cloud function handler. This works locally but on gcloud subprocess.check_output returns with non zero exit code.

Is it because gcloud runtime environment cannot find python interpreter? In either case, how can I do something like this? What am I missing here? I don't have much information in the logs so I am stuck.

Thanks

答: You have to expect your function as being deployed into a container that includes, in your case, a Python runtime. You can not assume that your cloud function includes a shell also. Therefore is not recommended to use subprocess in your python code.

Body:
import subprocess
import os

def execute():
    code = "def Solution():\n\tprint('Hello')\n\nSolution()\n"
    f = open('/tmp/Solution.py','w')
    f.write(code+'\n')
    f.close()
    s = subprocess.check_output("python /tmp/Solution.py", shell = True)
    return s

I am calling execute function from the cloud function handler. This works locally but on gcloud subprocess.check_output returns with non zero exit code.

Is it because gcloud runtime environment cannot find python interpreter? In either case, how can I do something like this? What am I missing here? I don't have much information in the logs so I am stuck.

Thanks


问:
mongodb how to get max value from collections
I have a mongodb collection like:

```<code>db.kids.find()
//results
[
    {name:'tom', age:10},
    {name:'alice', age:12},
    ....
]
</code>```

I need a query to get MAX 'age' from this collection
like in SQL: SELECT MAX(age) FROM kids WHERE 1

答:
You can also achieve this through aggregate pipeline.</p>

```<code>db.collection.aggregate([{$sort:{age:-1}}, {$limit:1}])
</code>```

Body:
I have a mongodb collection like:

db.kids.find()
//results
[
    {name:'tom', age:10},
    {name:'alice', age:12},
    ....
]

I need a query to get MAX 'age' from this collection
like in SQL: SELECT MAX(age) FROM kids WHERE 1

Body:
You can also achieve this through aggregate pipeline.

db.collection.aggregate([{$sort:{age:-1}}, {$limit:1}])


问:
Try catch not working in Laravel 5.6 when a number is divided by zero
Try catch block can not prevent run time exception in my Laravel code.
I wrote following code to test the exception handling:

```<code>try{
    $a=112/0;
}catch(Exception $e){
    $a=99;
}
</code>```

But it returns a Run time error. Please help me to solve the issue.

答:
Try this:

```<code>try{
    $a=112/0;
}catch(\Exception $e){
    $a=99;
}
</code>```

Notice the \ before Exception.

Update: As @Qirel suggests:

You can simply update your code to do it without try/catch:

```<code>if($d === 0){
    $a = 99;
} else{
    $a = 112/$d
}
</code>```

Body:
Try catch block can not prevent run time exception in my Laravel code.
I wrote following code to test the exception handling:

try{
    $a=112/0;
}catch(Exception $e){
    $a=99;
}

But it returns a Run time error. Please help me to solve the issue.

Body:
Try this:

try{
    $a=112/0;
}catch(\Exception $e){
    $a=99;
}

Notice the \ before Exception.

Update: As @Qirel suggests:

You can simply update your code to do it without try/catch:

if($d === 0){
    $a = 99;
} else{
    $a = 112/$d
}


问:
Iterate through dictionary with foreach loop and fetch all key/value pairs with value subset items
I have a concurrent dictionary that I am storing key/value pairs in. The complexity here is that the values are not single objects like string or integer, they are a collection of items that are added using a class model. It seems looking at the debug, I am able to add the items to the dictionary successfully, but the issue I have is not knowing how to read these items when iterating through the dictionary from another thread. I simply want to read all the key/value pairs, including all the items and add them to an array that I can pass back to the user through JsonResult/Ajax.

My AlarmEngine Class:

```<code>public static ConcurrentDictionary<string, object> concurrentDictionary = new ConcurrentDictionary<string, object>();

public class Alarm
{
    public int AlarmId { get; set; }
    public string AlarmName { get; set; }
    public string AlarmDescription { get; set; }
    public string ApplicationRoleId { get; set; }
    public DateTime DateTimeActivated { get; set; }
}
</code>```

An extract from the method where I add items to the dictionary:

```<code>concurrentDictionary.TryAdd(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), new Alarm
                {
                    DateTimeActivated = DateTime.Now,
                    ApplicationRoleId = applicationRoleId,
                    AlarmId = alarmId,
                    AlarmName = alarmName,
                    AlarmDescription = description,
                }); // I'm using datetime as the key as this is unique form each key/value pair added.
</code>```

My AlarmList MVC Controller:

```<code>[HttpGet]
public Task<IActionResult> FetchAlarmsListAsync()
{

    // Enumeration is thread-safe in ConcurrentDictionary.
    foreach (var item in AlarmEngine.concurrentDictionary)
    {
        // How do I access the key and value pairs here?
        // Note each value contains a subset of items
        // i want to access all items stored
    }

    return new JsonResult(Array containing all keys and value items);
}
</code>```

If it's better to read through the whole dictionary and store all keys/value(with sub items) to a list before returning to the user as an JSON array, this would be an acceptable solution for me as well, just keep in mind I want to do this as efficiently as possible to minimize converting from one form to another too many times. Items will be added and removed to the dictionary from other threads, but this particular bit of my application i.e. iteration through the dictionary is just for readonly purposes and it doesn't really matter to me if the contents have changed whilst reading through it, it's just to put together a list of alarms relevant/active at the time of the query.

答:
If these resources are shared amoung multiple clients/threads and mostly the clients are reading. I would suggest a ReaderWriterLockSlim. It allows multiple readers and one writer.

This way the jsons can be generated parallel. A ConcurrentX is usefull passing resources to others thread (like passing ownership) or just share simple typed data.

```<code>private static ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
</code>```

```<code>[HttpGet]
public Task<IActionResult> FetchAlarmsListAsync()
{
    cacheLock.EnterReadLock();
    try
    {
        // Enumeration is thread-safe in Dictionary.
        foreach (var item in AlarmEngine.normalDictionary)
        {
            // How do I access the key and value pairs here?
            // Note each value contains a subset of items
            // i want to access all items stored
        }

        return new JsonResult(Array containing all keys and value items);
    }
    finally
    {
        cacheLock.ExitReadLock();
    }
}
</code>```

```<code>cacheLock.EnterWriteLock();
try
{
    normalDictionary.TryAdd(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), new Alarm
    {
        DateTimeActivated = DateTime.Now,
        ApplicationRoleId = applicationRoleId,
        AlarmId = alarmId,
        AlarmName = alarmName,
        AlarmDescription = description,
    }); // I'm using datetime as the key as this is unique form each key/value pair added.
}
finally
{
    cacheLock.ExitWriteLock();
}
</code>```

It's even possible to cache the json result when the dictionary isn't changed, but you should only do such thing when it is a problem.

Body:
I have a concurrent dictionary that I am storing key/value pairs in. The complexity here is that the values are not single objects like string or integer, they are a collection of items that are added using a class model. It seems looking at the debug, I am able to add the items to the dictionary successfully, but the issue I have is not knowing how to read these items when iterating through the dictionary from another thread. I simply want to read all the key/value pairs, including all the items and add them to an array that I can pass back to the user through JsonResult/Ajax.

My AlarmEngine Class:

public static ConcurrentDictionary<string, object> concurrentDictionary = new ConcurrentDictionary<string, object>();

public class Alarm
{
    public int AlarmId { get; set; }
    public string AlarmName { get; set; }
    public string AlarmDescription { get; set; }
    public string ApplicationRoleId { get; set; }
    public DateTime DateTimeActivated { get; set; }
}

An extract from the method where I add items to the dictionary:

concurrentDictionary.TryAdd(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), new Alarm
                {
                    DateTimeActivated = DateTime.Now,
                    ApplicationRoleId = applicationRoleId,
                    AlarmId = alarmId,
                    AlarmName = alarmName,
                    AlarmDescription = description,
                }); // I'm using datetime as the key as this is unique form each key/value pair added.

My AlarmList MVC Controller:

[HttpGet]
public Task<IActionResult> FetchAlarmsListAsync()
{

    // Enumeration is thread-safe in ConcurrentDictionary.
    foreach (var item in AlarmEngine.concurrentDictionary)
    {
        // How do I access the key and value pairs here?
        // Note each value contains a subset of items
        // i want to access all items stored
    }

    return new JsonResult(Array containing all keys and value items);
}

If it's better to read through the whole dictionary and store all keys/value(with sub items) to a list before returning to the user as an JSON array, this would be an acceptable solution for me as well, just keep in mind I want to do this as efficiently as possible to minimize converting from one form to another too many times. Items will be added and removed to the dictionary from other threads, but this particular bit of my application i.e. iteration through the dictionary is just for readonly purposes and it doesn't really matter to me if the contents have changed whilst reading through it, it's just to put together a list of alarms relevant/active at the time of the query.

Body:
If these resources are shared amoung multiple clients/threads and mostly the clients are reading. I would suggest a ReaderWriterLockSlim. It allows multiple readers and one writer.

This way the jsons can be generated parallel. A ConcurrentX is usefull passing resources to others thread (like passing ownership) or just share simple typed data.

private static ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();

[HttpGet]
public Task<IActionResult> FetchAlarmsListAsync()
{
    cacheLock.EnterReadLock();
    try
    {
        // Enumeration is thread-safe in Dictionary.
        foreach (var item in AlarmEngine.normalDictionary)
        {
            // How do I access the key and value pairs here?
            // Note each value contains a subset of items
            // i want to access all items stored
        }

        return new JsonResult(Array containing all keys and value items);
    }
    finally
    {
        cacheLock.ExitReadLock();
    }
}

cacheLock.EnterWriteLock();
try
{
    normalDictionary.TryAdd(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), new Alarm
    {
        DateTimeActivated = DateTime.Now,
        ApplicationRoleId = applicationRoleId,
        AlarmId = alarmId,
        AlarmName = alarmName,
        AlarmDescription = description,
    }); // I'm using datetime as the key as this is unique form each key/value pair added.
}
finally
{
    cacheLock.ExitWriteLock();
}

It's even possible to cache the json result when the dictionary isn't changed, but you should only do such thing when it is a problem.


问:
Set a rule depending on a data prop on a vueJS form input
I took a look at this page: https://vuetifyjs.com/en/components/inputs

I saw it was possible to customize rules, for example:

```<code>  rules: [
    value => !!value || 'Required.',
    value => (value || '').length <= 20 || 'Max 20 characters',
    value => {
      const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      return pattern.test(value) || 'Invalid e-mail.'
    },
  ],
</code>```

However, I was wondering if it was possible to customize a rule depending on a component prop, for example:

```<code>value => (value || '').length <= this.maxLength || 'Max ' + this.maxLength + ' characters'
</code>```

My example above doesn't work, of course.
Thanks in advance :)

答:
Yes, it's possible. The mistakes that you were making

rules should be a computed property, since it can change

you should call it with parent component and pass prop maxLength

Here's a working example for you, where Validation is the component implementing rules and App is the parent component calling it with prop maxLength: https://codesandbox.io/s/nostalgic-thunder-mvl6o.

Body:
I took a look at this page: https://vuetifyjs.com/en/components/inputs

I saw it was possible to customize rules, for example:

  rules: [
    value => !!value || 'Required.',
    value => (value || '').length <= 20 || 'Max 20 characters',
    value => {
      const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      return pattern.test(value) || 'Invalid e-mail.'
    },
  ],

However, I was wondering if it was possible to customize a rule depending on a component prop, for example:

value => (value || '').length <= this.maxLength || 'Max ' + this.maxLength + ' characters'

My example above doesn't work, of course.
Thanks in advance :)


答:
Because you are using php7 you need to use Throwable to catch the exception like this:

try{
    $a=112/0;
}catch(Exception $e){
    // For php 5
    $a=99;
} catch(\Throwable $e) {
// For php7
    $a=99;
}
```

Title: Try catch not working in Laravel 5.6 when a number is divided by zero


问:
Array of Strings to an Array of Objects
Maybe there is a method that does this that I don't know about - I doubt it though - but I'm trying to convert an array of strings to an array of Objects. Here is the problem: I'm reading a file in from the command line. The file represents several classes of the following types each with their own data fields. Vehicle is the parent class of all who follow: Vehicle,Car,American Car, Foreign car, Truck, Bicycle.

I have no problem reading the file into a string array. However I need to create objects of all these types and store them in an array of type Vehicle[]. For example a portion of the file looks like this:

Vehicle

Kim Stanley Robinson

2344 court drive

(221)885-7777

stackoverflow@overflow.com

American Car

John Bunyon

1010 binary lane

(221)885-55643

bgt.com

convertable

made in detroit

 union plant

Where Class type is the first line followed by, Owner's Name, address, phone number, email address...Each type has fields particular to it. So a foreign car is not made in Detroit. Each of these fields appear on a separate line in the file. So what I've done is read the  entire file into a string array. However, I need to find my types in the array of strings,create objects of those types, and store them in a Vehicle array. My main problem is that each data field is on a separate line. How should I approach this problem?
This is java code by the way.

答: You could read the file as you are doing just now but when you read a string that is a Class type create an instance of the correct Vehicle type. It would appear that you would then know that the next x lines of the file are properties of that particular type so you would read the properties and set them on your Vehicle instance. You then have your Vehicle instance to add to the Vehicle array.</p>

OwnerDisplayName: BloodParrot

ContentLicense: CC BY-SA 2.5

Title: Array of Strings to an Array of Objects

OwnerDisplayName: Mark


问:
How to ignore one or more output bus pins for a module instantiation
I want to ignore one or more bits in an array argument for a module in SystemVerilog.

```<code>module x(in a, out [0:3] z);
...
endmodule

module tb;
  logic my_a;
  logic [1:3] my_z;
  // I want to stop having to do this next line:
  logic ignore_this_bit;
  x myx(.a(my_a), .z({ignore_this_bit, my_z}));
endmodule
</code>```

What is the proper syntax to do this? I have been doing it just as shown above with a declaration of ignore_this_bit and simply never connecting to that net. But it seems there should be a simpler way. Something like just using a comma and no variable name in the arguments for the module instantiation or maybe using something like 1'bX instead of an output argument bit, or something like that.

Is this affected by the fact that I am using big-endian bit ordering for the vectors here? (I hate it, but I am building code for an old CPU that uses that ordering and it's way easier to match my code to the existing than to fix it.)

This is a hard concept to search for, and I have tried. Does anyone have expertise that can help me know how to do this "the right way"? Thanks.

答:
There is no special way in verilog for ignoring bits of the output. So, your way of using concat with an unneeded variable is a good way for doing it ({ignore_this_bit, my_z}). Naming of this variable is important for readability reasons.

It is not affected by the range description order. It looks like you are ignoring the left-most bit. And the bits are always ordered in the same way, no matter how you describe the range:

```<code>bits:   0011
[3:0]:  3  0
[0:3]:  0  3
concat: {ign, 0, 1, 1};
</code>```

The other way around is to use a variable big enough to connect to the output and then use its bits:

```<code>logic [1:3] my_z;
logic [0:3] their_z;
 x myx(.a(my_a), .z(their_z));
 assign my_z = their_z[1:3];
</code>```

Body:
I want to ignore one or more bits in an array argument for a module in SystemVerilog.

module x(in a, out [0:3] z);
...
endmodule

module tb;
  logic my_a;
  logic [1:3] my_z;
  // I want to stop having to do this next line:
  logic ignore_this_bit;
  x myx(.a(my_a), .z({ignore_this_bit, my_z}));
endmodule

What is the proper syntax to do this? I have been doing it just as shown above with a declaration of ignore_this_bit and simply never connecting to that net. But it seems there should be a simpler way. Something like just using a comma and no variable name in the arguments for the module instantiation or maybe using something like 1'bX instead of an output argument bit, or something like that.

Is this affected by the fact that I am using big-endian bit ordering for the vectors here? (I hate it, but I am building code for an old CPU that uses that ordering and it's way easier to match my code to the existing than to fix it.)

This is a hard concept to search for, and I have tried. Does anyone have expertise that can help me know how to do this "the right way"? Thanks.

Body:
There is no special way in verilog for ignoring bits of the output. So, your way of using concat with an unneeded variable is a good way for doing it ({ignore_this_bit, my_z}). Naming of this variable is important for readability reasons.

It is not affected by the range description order. It looks like you are ignoring the left-most bit. And the bits are always ordered in the same way, no matter how you describe the range:

bits:   0011
[3:0]:  3  0
[0:3]:  0  3
concat: {ign, 0, 1, 1};

The other way around is to use a variable big enough to connect to the output and then use its bits:

logic [1:3] my_z;
logic [0:3] their_z;
 x myx(.a(my_a), .z(their_z));
 assign my_z = their_z[1:3];


问:
Why does line comment tricks for bash not work with exclamation mark "!"
ref Inline comments for Bash?

We can use this tricks

```<code>echo abc `#put your comment here` \
     def `#another chance for a comment` \
     xyz etc
</code>```

but these do not work if we have an exclamation mark in comment

```<code>echo 1 `# 2 !3`
<error>
-bash: !3: event not found
</code>```

if we type it directly it will not be translated to an event

```<code># 2 !3
<that is OK>
</code>```

It seams that we need an other # symbol to workaround it.

```<code>echo 1 `# 2 #!3`
<that is OK>
1
</code>```

or do we have to double the leading # symbol?

```<code>echo 1 `# # 2 !3`
<that is OK>
1
</code>```

答:
(The following explanation turned out to be WRONG though it explained everything. See the UPDATE as follows.)

# !xxx

This works as expected because ! is in the comment.

echo # !xxx

This also works as expected because ! is also in the comment.

echo `true # !xxx`

This also works because ! is still in the comment, though it's in the `...` context.

echo `# !xxx`

Why doesn't this work?

I guess there's a little bug when Bash interprets the `...` part. In `...`, Bash always assumes (wrongly) the first WORD is  a COMMAND name so it does not think ! is in a comment and so history expansion is triggered. That's to say, echo `# !xxx` is just like echo `COMMAND !xxx`.

echo `# # !xxx`

Why does this work?

As explained in #4, the first # is parsed as a COMMAND so it's just like echo `COMMAND # !xxx` so now ! is in the comment.

echo `## !xxx`

This double hash does not work either.

As explained in #4 and #5, here ## is the first WORD and it's parsed as the COMMAND name so it's also like echo `COMMAND !xxx`.

Note that, in the `...` context, the bug is only in the first round syntax parser. That's to say, even though Bash initially parses the # as a COMMAND name, it does not really run it as a command which is named #.

UPDATE 2020-03-04

The above explanation turned out to be WRONG though it explained everything. Please see the discussion in bug-bash mailing list.

I'd quote Chet's explanation here for easy reference:

```<code>> $ set -H
> $ true `# !xxx`
> bash: !xxx`: event not found
</code>```

Well, the history comment character (#) is not found at the start of a
word (here # is part of the word `#), so the rest of the line is processed for history expansion.

```<code>$ true `# # !xxx`
</code>```

The history comment character is found at the start of a word (here the 2nd # itself is a word) and history
expansion skips the rest of the line.

Readline history expansion knows very little about shell syntax; in
particular, it doesn't know backquotes. It never has.

Body:
ref Inline comments for Bash?

We can use this tricks

echo abc `#put your comment here` \
     def `#another chance for a comment` \
     xyz etc

but these do not work if we have an exclamation mark in comment

echo 1 `# 2 !3`
<error>
-bash: !3: event not found

if we type it directly it will not be translated to an event

# 2 !3
<that is OK>

It seams that we need an other # symbol to workaround it.

echo 1 `# 2 #!3`
<that is OK>
1

or do we have to double the leading # symbol?

echo 1 `# # 2 !3`
<that is OK>
1

Body:
(The following explanation turned out to be WRONG though it explained everything. See the UPDATE as follows.)

# !xxx

This works as expected because ! is in the comment.

echo # !xxx

This also works as expected because ! is also in the comment.

echo `true # !xxx`

This also works because ! is still in the comment, though it's in the `...` context.

echo `# !xxx`

Why doesn't this work?

I guess there's a little bug when Bash interprets the `...` part. In `...`, Bash always assumes (wrongly) the first WORD is  a COMMAND name so it does not think ! is in a comment and so history expansion is triggered. That's to say, echo `# !xxx` is just like echo `COMMAND !xxx`.

echo `# # !xxx`

Why does this work?

As explained in #4, the first # is parsed as a COMMAND so it's just like echo `COMMAND # !xxx` so now ! is in the comment.

echo `## !xxx`

This double hash does not work either.

As explained in #4 and #5, here ## is the first WORD and it's parsed as the COMMAND name so it's also like echo `COMMAND !xxx`.

Note that, in the `...` context, the bug is only in the first round syntax parser. That's to say, even though Bash initially parses the # as a COMMAND name, it does not really run it as a command which is named #.

UPDATE 2020-03-04

The above explanation turned out to be WRONG though it explained everything. Please see the discussion in bug-bash mailing list.

I'd quote Chet's explanation here for easy reference:

> $ set -H
> $ true `# !xxx`
> bash: !xxx`: event not found

Well, the history comment character (#) is not found at the start of a
word (here # is part of the word `#), so the rest of the line is processed for history expansion.

$ true `# # !xxx`

The history comment character is found at the start of a word (here the 2nd # itself is a word) and history
expansion skips the rest of the line.

Readline history expansion knows very little about shell syntax; in
particular, it doesn't know backquotes. It never has.


问:
Angular Material (8) S2591: Cannot find name 'require'
I am trying to log date/time into the javascript console. The error message I am getting is as follows and was generated by the code below.

ETA: the code does work. The dates are going to the console. It is just the Error Message remains

Message:

ERROR in src/app/kdc/services/customers.api.service.ts(60,9): error
TS2591: Cannot find name 'require'. Do you need to install type
definitions for node? Try npm i @types/node and then add node to
the types field in your tsconfig.

NOTE: I have already made changes to the tsconfig.json file and have also done npm i @types/node and npm i @types/node --save When running npm result was 3 high-security vulnerabilities (see below)

What can I do at this point?`

customer.api.service.ts

```<code>   getCustomers(): Observable<Customers[]> {
        return this.httpclient.get<Customers[]>(this._url)
        .pipe( catchError(this.handleError));

    }

    handleError(error:HttpErrorResponse){
        let rval = Math.random().toString(36).substring(7).toUpperCase();
        require('log-timestamp');
        console.error('MSG NO :' + rval );
        console.error(error);
        return throwError(rval + " <-> " + error.name + " <-> " + error.statusText );
     }
</code>```

ETA
I found the message here Cannot find name 'require' after upgrading to Angular4  and made the change to my
tsconfig.app.json file - it may be overkill, but it worked ...

```<code>  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [ "node" ],
    "typeRoots": [ "../node_modules/@types" ]
  },
</code>```

答:
Make sure you put the type in your tsconfig.app.json not your tsconfig.json

```<code>  "compilerOptions": {
    "module": "esNext",
    "types": ["node"]
  },
</code>```

Also make sure your systax in your component look like this

```<code>const someLib = require("someLib"); // make sure the name is match with your package name
</code>```

Then stop angular cli then run again

Body:
I am trying to log date/time into the javascript console. The error message I am getting is as follows and was generated by the code below.

ETA: the code does work. The dates are going to the console. It is just the Error Message remains

Message:

ERROR in src/app/kdc/services/customers.api.service.ts(60,9): error
TS2591: Cannot find name 'require'. Do you need to install type
definitions for node? Try npm i @types/node and then add node to
the types field in your tsconfig.

NOTE: I have already made changes to the tsconfig.json file and have also done npm i @types/node and npm i @types/node --save When running npm result was 3 high-security vulnerabilities (see below)

What can I do at this point?`

customer.api.service.ts

   getCustomers(): Observable<Customers[]> {
        return this.httpclient.get<Customers[]>(this._url)
        .pipe( catchError(this.handleError));

    }

    handleError(error:HttpErrorResponse){
        let rval = Math.random().toString(36).substring(7).toUpperCase();
        require('log-timestamp');
        console.error('MSG NO :' + rval );
        console.error(error);
        return throwError(rval + " <-> " + error.name + " <-> " + error.statusText );
     }

ETA
I found the message here Cannot find name 'require' after upgrading to Angular4  and made the change to my
tsconfig.app.json file - it may be overkill, but it worked ...

  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [ "node" ],
    "typeRoots": [ "../node_modules/@types" ]
  },

Body:
Make sure you put the type in your tsconfig.app.json not your tsconfig.json

  "compilerOptions": {
    "module": "esNext",
    "types": ["node"]
  },

Also make sure your systax in your component look like this

const someLib = require("someLib"); // make sure the name is match with your package name

Then stop angular cli then run again


问:
How to deactivate inline mode in your Bot?
How to deactivate inline mode in your Bot? When you talk to BotFather by /help he doesn't give any instructions. Thanks</p>

答: Type /setinline, choose bot to disable inline mode, that type /empty. This will disable inline mode in your bot.


问:
Passing shellcode from Python as command line argument
I am currently preparing a small presentation about computer security among my fellow students. To get them at least a bit excited I wanted to demonstrate how the wrong use of the strcpy-function inc C can be exploited.
This is the code of the vulnerable program:

```<code>#include<string.h>
#include<stdio.h>
void function(char *buffer1)
{
 char buffer2[5];
 strcpy(buffer2,buffer1);
}

int main (int argc, char **argv)
{
 function(argv[1]);
 return 0;
}
</code>```

Just using the command line I was able to crash the application by calling it with

```<code>test.exe ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

Which gave me the correct 0x4D4C4B4A (MLKJ) for the EIP. It also works if I call it from Python:

```<code>os.system("test.exe ABCDEFGHIJKLMNOPQRSTUVWXYZ")
</code>```

However, if I want to put an address instead of JKLM, like this:

```<code> os.system("test.exe ABCDEFGHI\x75\x9a\x21\x1bNOPQRSTUVWXYZ")
</code>```

It gives me following output near the ESP on the Stack:

```<code>0028cca0  e4 21 d7 41 42 43 44 45-46 47 48 49 75 c2 9a 21  .!.ABCDEFGHIu..!
0028ccb0  1b 4e 4f 50 51 52 53 54-55 56 57 58 59 5a 00 00  .NOPQRSTUVWXYZ..
</code>```

Here the 75 c2 9a 21 matters because it is almost what I expected, except the 0x1B, which is the ASCII Character for ESCAPE, is replaced by 0xC2.
When I change the order of the address, so it looks like this: \x21\x1b\x75\x9a, the 9a gets replaced by the same mysterious C2.
Does anyone know whats the matter with the code? Am I missing some basic point or is it some kind of protection against stack based buffer overflows?

Thanks,

答:
It looks like your text is undergoing UTF-8 conversion. Note that your original bytes:

```<code>75 9a 21 1b
   ^^
</code>```

are replaced by

```<code>75 c2 9a 21 1b
   ^^^^^
</code>```

I've highlighted the UTF-8 encoded byte. If you're using Python 3, try:

```<code>os.system(b"test.exe ABCDEFGHI\x75\x9a\x21\x1bNOPQRSTUVWXYZ")
</code>```

The b"" indicates that the data is a byte sequence, and shouldn't be converted from Unicode to the default encoding (which in your case seems to be UTF-8).

Body:
I am currently preparing a small presentation about computer security among my fellow students. To get them at least a bit excited I wanted to demonstrate how the wrong use of the strcpy-function inc C can be exploited.
This is the code of the vulnerable program:

#include<string.h>
#include<stdio.h>
void function(char *buffer1)
{
 char buffer2[5];
 strcpy(buffer2,buffer1);
}

int main (int argc, char **argv)
{
 function(argv[1]);
 return 0;
}

Just using the command line I was able to crash the application by calling it with

test.exe ABCDEFGHIJKLMNOPQRSTUVWXYZ

Which gave me the correct 0x4D4C4B4A (MLKJ) for the EIP. It also works if I call it from Python:

os.system("test.exe ABCDEFGHIJKLMNOPQRSTUVWXYZ")

However, if I want to put an address instead of JKLM, like this:

 os.system("test.exe ABCDEFGHI\x75\x9a\x21\x1bNOPQRSTUVWXYZ")

It gives me following output near the ESP on the Stack:

0028cca0  e4 21 d7 41 42 43 44 45-46 47 48 49 75 c2 9a 21  .!.ABCDEFGHIu..!
0028ccb0  1b 4e 4f 50 51 52 53 54-55 56 57 58 59 5a 00 00  .NOPQRSTUVWXYZ..

Here the 75 c2 9a 21 matters because it is almost what I expected, except the 0x1B, which is the ASCII Character for ESCAPE, is replaced by 0xC2.
When I change the order of the address, so it looks like this: \x21\x1b\x75\x9a, the 9a gets replaced by the same mysterious C2.
Does anyone know whats the matter with the code? Am I missing some basic point or is it some kind of protection against stack based buffer overflows?

Thanks,

Body:
It looks like your text is undergoing UTF-8 conversion. Note that your original bytes:

75 9a 21 1b
   ^^

are replaced by

75 c2 9a 21 1b
   ^^^^^

I've highlighted the UTF-8 encoded byte. If you're using Python 3, try:

os.system(b"test.exe ABCDEFGHI\x75\x9a\x21\x1bNOPQRSTUVWXYZ")

The b"" indicates that the data is a byte sequence, and shouldn't be converted from Unicode to the default encoding (which in your case seems to be UTF-8).


问:
Type hints for a function that accepts a (homogeneous) sequence of one of several types
I'm trying to provide type hints for a function that accepts a sequence
with one of two types of elements, and I'm at a loss how to make mypy happy.  Please note, the sequence is homogeneous, meaning the types can't be mixed, either-or.  Usually I do this when they are "compatible" types, e.g. a path str or a pathlib.Path object, and annotating that with Union works just fine.  But in the case of a sequence, Sequence[Union[..]] (or Union[Sequence[..]]) doesn't seem to work.  Here's a minimal working example:

```<code>from pathlib import Path
from typing import Sequence, Dict, Union

def fn_accepts_dict(adict):
    """Function from an external module that accepts `dict`s."""
    for key, val in adict.items():
        print(f"{key}, {val}")

def vararg_test(resources: Sequence[Union[str, Dict]]):
    """My function where I want to provide type hints"""
    if isinstance(resources[0], str):
        resources2 = [{"path": Path(f)} for f in resources]
    else:
        resources2 = resources
    for d in resources2:
        fn_accepts_dict(d)
</code>```

Now, with the above definitions, calling vararg_test with either of
these two work as expected:

```<code>l1 = ["foo/bar", "bar/baz"]
l2 = [{"path": Path("foo/bar")}, {"path": Path("bar/baz")}]
</code>```

But running mypy gives me the following errors:

```<code>type_hints.py:14: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:16: error: Incompatible types in assignment (expression has type "Sequence[Union[str, Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")
Found 2 errors in 1 file (checked 1 source file)
</code>```

How can I resolve this?

Edit:
To give some background, the str is a path, and the dict has metadata corresponding to that path, and the function fn_accepts_dict collates metadata into one metadata object.  So they logical flow is either: str -> dict -> fn_accepts_dict or, dict -> fn_accepts_dict.

While @ShadowRanger's suggestion looked promising, no luck.  I get the same error with the following hints:

```<code>def vararg_test2(resources: Union[Sequence[str], Sequence[Dict]]):
    ... # same implementation as above
</code>```

mypy error:

```<code>type_hints.py:24: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:26: error: Incompatible types in assignment (expression has type "Union[Sequence[str], Sequence[Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")
</code>```

Edit 2:  unfortunately, with all the annotations, it looks more like C/C++ than Python; see my own answer below for a much more Pythonic solution.

答:
TLDR: mypy only understands isinstance(v, tp) with respect to v. It does not understand isinstance(v<expr>, tp) with respect to v, e.g. v[0]: str implying the type of v: List[str].

mypy doesn't understand isinstance(resources[0], str) to branch between resources: Sequence[str] and resources: Sequence[Dict]. This means that resources = resources2 infers both to be the exact same type, which either breaks on assigning or using resources2.

You must annotate resources2 to prevent inferred type equality, and cast in the branches to mark them as such.

```<code>def vararg_test(resources: Union[Sequence[str], Sequence[Dict]]):
    """My function where I want to provide type hints"""
    resources2: Sequence[Dict]  # fixed type to prevent inferred equality
    if isinstance(resources[0], str):  # Mypy does not recognise this branch by itself!
        # exclude second Union branch
        resources = cast(Sequence[str], resources)
        resources2 = [{"path": Path(f)} for f in resources]
    else:
        # exclude first Union branch
        resources2 = cast(Sequence[Dict], resources)
    for d in resources2:
        fn_accepts_dict(d)
</code>```

Body:
I'm trying to provide type hints for a function that accepts a sequence
with one of two types of elements, and I'm at a loss how to make mypy happy.  Please note, the sequence is homogeneous, meaning the types can't be mixed, either-or.  Usually I do this when they are "compatible" types, e.g. a path str or a pathlib.Path object, and annotating that with Union works just fine.  But in the case of a sequence, Sequence[Union[..]] (or Union[Sequence[..]]) doesn't seem to work.  Here's a minimal working example:

from pathlib import Path
from typing import Sequence, Dict, Union

def fn_accepts_dict(adict):
    """Function from an external module that accepts `dict`s."""
    for key, val in adict.items():
        print(f"{key}, {val}")

def vararg_test(resources: Sequence[Union[str, Dict]]):
    """My function where I want to provide type hints"""
    if isinstance(resources[0], str):
        resources2 = [{"path": Path(f)} for f in resources]
    else:
        resources2 = resources
    for d in resources2:
        fn_accepts_dict(d)

Now, with the above definitions, calling vararg_test with either of
these two work as expected:

l1 = ["foo/bar", "bar/baz"]
l2 = [{"path": Path("foo/bar")}, {"path": Path("bar/baz")}]

But running mypy gives me the following errors:

type_hints.py:14: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:16: error: Incompatible types in assignment (expression has type "Sequence[Union[str, Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")
Found 2 errors in 1 file (checked 1 source file)

How can I resolve this?

Edit:
To give some background, the str is a path, and the dict has metadata corresponding to that path, and the function fn_accepts_dict collates metadata into one metadata object.  So they logical flow is either: str -> dict -> fn_accepts_dict or, dict -> fn_accepts_dict.

While @ShadowRanger's suggestion looked promising, no luck.  I get the same error with the following hints:

def vararg_test2(resources: Union[Sequence[str], Sequence[Dict]]):
    ... # same implementation as above

mypy error:

type_hints.py:24: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:26: error: Incompatible types in assignment (expression has type "Union[Sequence[str], Sequence[Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")

Edit 2:  unfortunately, with all the annotations, it looks more like C/C++ than Python; see my own answer below for a much more Pythonic solution.

Body:
TLDR: mypy only understands isinstance(v, tp) with respect to v. It does not understand isinstance(v<expr>, tp) with respect to v, e.g. v[0]: str implying the type of v: List[str].

mypy doesn't understand isinstance(resources[0], str) to branch between resources: Sequence[str] and resources: Sequence[Dict]. This means that resources = resources2 infers both to be the exact same type, which either breaks on assigning or using resources2.

You must annotate resources2 to prevent inferred type equality, and cast in the branches to mark them as such.

def vararg_test(resources: Union[Sequence[str], Sequence[Dict]]):
    """My function where I want to provide type hints"""
    resources2: Sequence[Dict]  # fixed type to prevent inferred equality
    if isinstance(resources[0], str):  # Mypy does not recognise this branch by itself!
        # exclude second Union branch
        resources = cast(Sequence[str], resources)
        resources2 = [{"path": Path(f)} for f in resources]
    else:
        # exclude first Union branch
        resources2 = cast(Sequence[Dict], resources)
    for d in resources2:
        fn_accepts_dict(d)


问:
check how many dominant numbers there are in a 2D array
in this program i'm supposed to find how many dominant numbers the matrix has. a dominant number is a number that is bigger than whatever is below to the right onwards(bear with my english please).

i entered this :

```<code>5 (9) 2  4  1 (7)  2  4///
3  5  6  2  5 (6)  1  2///
1  3  4  7  8 (8) (3) 0///
1  3  5  6  7  8   2  1///
</code>```

the ones i circled are supposed to be the dominant ones but it gave me back 6, what went wrong?

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

#define NR 4
#define NC 8

int dominants(int a[NR][NC]);
int main(int argc, char * argv[]){
int array[NR][NC];
int ndom;
int i,j;

for(i=0;i<NR;i++){
        for(j=0;j<NC;j++){

        scanf("%d", &array[i][j]);
        }
}
printf("array entered:\n\n");
for(i=0;i<NR;i++){
        printf("\n");
        for(j=0;j<NC;j++){

        printf("%d  ", array[i][j]);
        }
}

ndom=dominants(array);

printf("amount of dominant numbers:%d", ndom);
return 0;
}
int dominants(int a[NR][NC]){
int domflag;
int i,j, l, m;
int numdom=0;
for(i=0;i<NR-1;i++){
    for(j=0;j<NC-1;j++){
        for(l=i+1;l<NR;l++){
                domflag=1;
                for(m=j+1;m<NC;m++){
                if(a[i][j]<=a[l][m]){
                    domflag=0;
                                    }
                                   }
                           }
            if(domflag==1){
                numdom++;
                          }
        }

    }
    return numdom;
}
</code>```

答:
Do not put all the logic into the main function. Try to use functions. It makes things much easier

```<code>int isdominant(int *arr, size_t cols, size_t rows, size_t col, size_t row)
{
    int *rowend = arr + (row + 1) * cols - 1;
    int *pos = arr + row * cols + col;
    while(rowend > pos)
        if(*pos <= *rowend--) return 0;
    return 1;
}

#define COLS 10
#define ROWS 7

int main()
{
    int arr[ROWS][COLS];
    int *ptr = &arr[0][0];
    unsigned dominants = 0;

    for(size_t index = 0; index < ROWS * COLS; index++) *ptr++ = rand() % 50;

    for(size_t row = 0; row < ROWS; row++)
    {
        for(size_t col = 0; col < COLS; col++)
        {
            int dom = 0;
            if(col != COLS - 1) dom = isdominant(arr[0], COLS, ROWS, col, row);
            printf("%s%d%s\t", dom ? "(" : "", arr[row][col], dom ? ")" : "");
            dominants += dom;
        }
        printf("\n");
    }
    printf("Dominant numbers: %u\n", dominants);
}
</code>```

https://godbolt.org/z/tpwnm2

Body:
in this program i'm supposed to find how many dominant numbers the matrix has. a dominant number is a number that is bigger than whatever is below to the right onwards(bear with my english please).

i entered this :

5 (9) 2  4  1 (7)  2  4///
3  5  6  2  5 (6)  1  2///
1  3  4  7  8 (8) (3) 0///
1  3  5  6  7  8   2  1///

the ones i circled are supposed to be the dominant ones but it gave me back 6, what went wrong?

#include <stdio.h>
#include <stdlib.h>

#define NR 4
#define NC 8

int dominants(int a[NR][NC]);
int main(int argc, char * argv[]){
int array[NR][NC];
int ndom;
int i,j;

for(i=0;i<NR;i++){
        for(j=0;j<NC;j++){

        scanf("%d", &array[i][j]);
        }
}
printf("array entered:\n\n");
for(i=0;i<NR;i++){
        printf("\n");
        for(j=0;j<NC;j++){

        printf("%d  ", array[i][j]);
        }
}

ndom=dominants(array);

printf("amount of dominant numbers:%d", ndom);
return 0;
}
int dominants(int a[NR][NC]){
int domflag;
int i,j, l, m;
int numdom=0;
for(i=0;i<NR-1;i++){
    for(j=0;j<NC-1;j++){
        for(l=i+1;l<NR;l++){
                domflag=1;
                for(m=j+1;m<NC;m++){
                if(a[i][j]<=a[l][m]){
                    domflag=0;
                                    }
                                   }
                           }
            if(domflag==1){
                numdom++;
                          }
        }

    }
    return numdom;
}

Body:
Do not put all the logic into the main function. Try to use functions. It makes things much easier

int isdominant(int *arr, size_t cols, size_t rows, size_t col, size_t row)
{
    int *rowend = arr + (row + 1) * cols - 1;
    int *pos = arr + row * cols + col;
    while(rowend > pos)
        if(*pos <= *rowend--) return 0;
    return 1;
}

#define COLS 10
#define ROWS 7

int main()
{
    int arr[ROWS][COLS];
    int *ptr = &arr[0][0];
    unsigned dominants = 0;

    for(size_t index = 0; index < ROWS * COLS; index++) *ptr++ = rand() % 50;

    for(size_t row = 0; row < ROWS; row++)
    {
        for(size_t col = 0; col < COLS; col++)
        {
            int dom = 0;
            if(col != COLS - 1) dom = isdominant(arr[0], COLS, ROWS, col, row);
            printf("%s%d%s\t", dom ? "(" : "", arr[row][col], dom ? ")" : "");
            dominants += dom;
        }
        printf("\n");
    }
    printf("Dominant numbers: %u\n", dominants);
}

https://godbolt.org/z/tpwnm2


问:
How to print JSON data to the console only after fetch in React Native?
I have tried the following code:

```<code>const response =await fetch('https://facebook.github.io/react-native/movies.json');
const json= await response.json();
console.log(json.result);
</code>```

to print fetched JSON data to the console but it's not working. How can I write fetched data directly to console?

答:
In my opinion, this is the right way to write :</p>

```<code>async function fetchblogEntry(){
    const response=await fetch('https://facebook.github.io/react-native/movies.json');
    console.log(response.json())
}

fetchblogEntry()
</code>```

Body:
I have tried the following code:

const response =await fetch('https://facebook.github.io/react-native/movies.json');
const json= await response.json();
console.log(json.result);

to print fetched JSON data to the console but it's not working. How can I write fetched data directly to console?

Body:
In my opinion, this is the right way to write :

async function fetchblogEntry(){
    const response=await fetch('https://facebook.github.io/react-native/movies.json');
    console.log(response.json())
}

fetchblogEntry()


问:
How to add org.apache.commons.lang3 to AndroidStudio with gradle
Due to this question
I want to use class StringEscapeUntils in package org.apache.commons.lang3.

But when I try to import Apache lib by add line compile 'org.apache.commons:commons-collections4:4.0' to build.grade file then can not import the class above.

Is there any one can help me how to import above one to my project via gradle (not by download .jar and put them into project folder).

答:
for StringUtils you need to add in app.gradle

```<code>implementation 'org.apache.commons:commons-text:1.7'
</code>```

Body:
for StringUtils you need to add in app.gradle

implementation 'org.apache.commons:commons-text:1.7'


问:
Compiler infering the template argument
```<code>template<typename T>
class A
{
    public:

    A(T &t)
    : t_(t){}

    T t_;
};

int main()
{
    int value;
    A<decltype(value)> a(value);
    // what I wish for : A a(value);
    // which does not compile "missing template argument before 'a'"
}
</code>```

Is there a way in the declaration of A (or somewhere else) to hint the compiler that T should be automatically resolved to the type passed to the constructor ?

(ideally c++11, but happy to hear about less old versions)

答: C++17 does it out of the box (or with the help of deduction guides), previous versions cannot.</p>

Title: Compiler infering the template argument

Body:
template<typename T>
class A
{
    public:

    A(T &t)
    : t_(t){}

    T t_;
};

int main()
{
    int value;
    A<decltype(value)> a(value);
    // what I wish for : A a(value);
    // which does not compile "missing template argument before 'a'"
}

Is there a way in the declaration of A (or somewhere else) to hint the compiler that T should be automatically resolved to the type passed to the constructor ?

(ideally c++11, but happy to hear about less old versions)