问:
Take input from user using cmd after running Python script
I want to take input from the user after running my py script in Windows.

A new cmd should pop up displaying a particular message like "Do you wish to continue [y/n]" and store this value in a variable in the py script and cmd should close automatically after the user provides input.
(Using Python 3)
Can anyone please help.

答:
Here's a way:

Lets say you have three files, the first file (first_half.py) is for the first half of your program, the second file (ask.py) is where the user is asked whether or not to continue, and the third file (second_half.py) is for if the user chooses to continue, it gets executed.

In your first_half.py python file:

```<code># Your code
import os
os.system('cmd /k "python ask.py"')
</code>```

In a ask.py:

```<code>a = input("Do you wish to continue? ")
line = 5 # Choose which line of the second_half.py should define the variable
with open('second_half.py','r') as f:
    file = f.readlines()

if a == 'y':
    file.insert(line,'\na = "y"')
    with open('second_half.py','w') as f:
        f.write(''.join(file))
else:
    file.insert(line,'\na = "n"')
    with open('second_half.py','w') as f:
        f.write(''.join(file))

import os
os.system('second_half.py')
</code>```

This might not be what you're looking for, but does work for some specific situations.

Body:
Here's a way:

Lets say you have three files, the first file (first_half.py) is for the first half of your program, the second file (ask.py) is where the user is asked whether or not to continue, and the third file (second_half.py) is for if the user chooses to continue, it gets executed.

In your first_half.py python file:

# Your code
import os
os.system('cmd /k "python ask.py"')

In a ask.py:

a = input("Do you wish to continue? ")
line = 5 # Choose which line of the second_half.py should define the variable
with open('second_half.py','r') as f:
    file = f.readlines()

if a == 'y':
    file.insert(line,'\na = "y"')
    with open('second_half.py','w') as f:
        f.write(''.join(file))
else:
    file.insert(line,'\na = "n"')
    with open('second_half.py','w') as f:
        f.write(''.join(file))

import os
os.system('second_half.py')

This might not be what you're looking for, but does work for some specific situations.


来源: stackexchange

问:
Domain Specific Language resources
I was just listening to some older .Net Rocks! episodes, and I found #329 on DSLs to be interesting. My problem is that I can't find any good online resources for people trying to learn this technology. I get the basics of the creating new designers, but the MS docs on the T4 engine used by the DSL tools and then how to integrate the templates with the DSL models are lacking.

Does anyone know of some good introductory resources for the MS DSL tools?

答: A fantastic option for DSLs is Boo.  I've been using it for things like setting up my IoC container, defining routes, validation rules.  Ayende Rahien is writing an fantastic book on the subject for Manning called Building Domain Specific Languages in Boo</p>

ContentLicense: CC BY-SA 2.5

Title: Domain Specific Language resources

LastEditorDisplayName: Jeff Atwood

OwnerDisplayName: Chris Canal


问:
Is it possible to generate random numbers through physical process simulation?
Is it possible to generate random numbers through physical process simulation?

If I simulate the physical roll of a dice (i.e. you picking it up, shaking it in your hand, releasing it onto the table and recording which side ends up "up"...) will that produce a "random" number or would I just have a complex simulation which really accomplishes nothing.

答:
The later.

Unless you inject some random (or pseudo random) factors the simulation will produce the same results every time.

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: MarkusQ


问:
Looping through a data array and giving a from control name to an input field does not work correctly?
Problem:

I am rendering input sets through a loop in angular. So in there I am setting form control name to the input field like this.

```<code><input  formControlName="{{data.attributeName}}  min="1" id="{{data.id}}" type="{{data.type}}" />
</code>```

But when I see the source in the inspect window it is not showing the form control name with the input field. Can someone help me to find out a way to solve this issue? Thank you very much.

答:
You need to do:</p>

```<code><input [formControlName]="data.attributeName" min="1" [id]="data.id" [type]="data.type" />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Problem:

I am rendering input sets through a loop in angular. So in there I am setting form control name to the input field like this.

<input  formControlName="{{data.attributeName}}  min="1" id="{{data.id}}" type="{{data.type}}" />

But when I see the source in the inspect window it is not showing the form control name with the input field. Can someone help me to find out a way to solve this issue? Thank you very much.

Body:
You need to do:

<input [formControlName]="data.attributeName" min="1" [id]="data.id" [type]="data.type" />


问:
When I try to add a new category I got "The parameters dictionary contains a null entry for parameter 'X' of non-nullable type 'System.Int32'"
Error:

The parameters dictionary contains a null entry for parameter 'categoryId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult UpdateCategory(Int32)' in 'OnlineStore.Controllers.AdminController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
  Parameter name: parameters.

This is the code:

```<code>@model OnlineStore.Models.CategoryDetail
@{
    ViewBag.Title = "UpdateCategory";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

<div class="container-fluid">
    <!-- Breadcrumbs-->

    <ol class="breadcrumb">
        <li class="breadcrumb-item">
            <a href="#">Dashboard</a>
        </li>
        <li class="breadcrumb-item ">Categories</li>
        <li class="breadcrumb-item active">Add New Category</li>

    </ol>
    <!-- DataTables Example -->
    <div class="card mb-3">
        <div class="card-header">
            <i class="fas fa-table"></i>
            Add New Category

        </div>
        <div class="card-body">
            @using (Html.BeginForm("UpdateCategory", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                @Html.HiddenFor(m => m.CategoryId)

                <div class="form-group">
                    <label class="control-label">Category Name</label>

                    @Html.TextBoxFor(m => m.CategoryName, new { @class = "form-control", placeholder = "Enter category Name", required = "required", autofocus = "autofocus" })
                    @Html.ValidationMessageFor(m => m.CategoryName, "", new { @class = "text-danger" })
                </div>

                <a onclick="window.history.back();" class="btn btn-danger">Cancel</a>
                <input type="submit" class="btn btn-primary" value="Save" />
            }
        </div>
    </div>
</div>

public ActionResult UpdateCategory(int categoryId)
        {
            CategoryDetail cd;
            if (categoryId != null)
            {
                cd = JsonConvert.DeserializeObject<CategoryDetail>(JsonConvert.SerializeObject(_unitOfWork.GetRepositoryInstance<Tbl_Category>().GetFirstorDefault(categoryId)));
            }
            else
            {
                cd = new CategoryDetail();
            }
            return View("UpdateCategory", cd);

        }
</code>```

答:
Html.HiddenFor assumes that the submit action parameter is a viewmodel object - so the name it generates for the hidden input is crafted so that the MVC model binder recognises it as the property of a CategoryDetail. You don't have this however - you're passing a bare integer back to the action method instead. This is fine, but the two approaches don't match up.

You can fix this in either of two ways:

change the action method to take a CategoryDetail parameter. This will be a new instance of the class with only the values populated by the form post body.

use Html.Hidden instead, which does not try to guess the name of the generated input control, and pass a parameter object new { @name = "categoryId" } - according to this answer HiddenFor is meant to be helpful and doesn't allow this level of flexibility

Body:
Error:

The parameters dictionary contains a null entry for parameter 'categoryId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult UpdateCategory(Int32)' in 'OnlineStore.Controllers.AdminController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
  Parameter name: parameters.

This is the code:

@model OnlineStore.Models.CategoryDetail
@{
    ViewBag.Title = "UpdateCategory";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

            Dashboard

Categories

Add New Category

            Add New Category

            @using (Html.BeginForm("UpdateCategory", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                @Html.HiddenFor(m => m.CategoryId)

                    Category Name

                    @Html.TextBoxFor(m => m.CategoryName, new { @class = "form-control", placeholder = "Enter category Name", required = "required", autofocus = "autofocus" })
                    @Html.ValidationMessageFor(m => m.CategoryName, "", new { @class = "text-danger" })

                Cancel
                <input type="submit" class="btn btn-primary" value="Save" />
            }

public ActionResult UpdateCategory(int categoryId)
        {
            CategoryDetail cd;
            if (categoryId != null)
            {
                cd = JsonConvert.DeserializeObject<CategoryDetail>(JsonConvert.SerializeObject(_unitOfWork.GetRepositoryInstance<Tbl_Category>().GetFirstorDefault(categoryId)));
            }
            else
            {
                cd = new CategoryDetail();
            }
            return View("UpdateCategory", cd);

        }


问:
Populating Localizable.strings file with Terminal genstring command in SwiftUI
Trying to localize a SwiftUI app, I was under the impression that things had gotten a lot simpler.

I created the Localizable.strings files for both of my supported languages, but I can't populate them with the usual Terminal genstring command : genstrings -o en.lproj *.swift, even though I am launching this command from the correct directory.

Does anyone know if genstring is broken in swiftUI or if there is another way ?
Would HATE to have to go through the hundred strings in my app...

I did find many articles online about localization in SwiftUI, but nothing that clearly explains it.

My understanding is that in SwiftUI, we can simply write things like

Text("A text to be displayed")and this would be understood as a LocalizedStringKeyby default.

Am I wrong ?

Added Screenshot of issue after trying @Asperi's solution :

答:
Use -SwiftUI option (as in variant below, or any other used)

```<code>$ find ./ -name "*.swift" -print0 | xargs -0 genstrings -a -SwiftUI -o en.lproj
</code>```

for details

```<code>$ man genstrings
</code>```

Body:
Use -SwiftUI option (as in variant below, or any other used)

$ find ./ -name "*.swift" -print0 | xargs -0 genstrings -a -SwiftUI -o en.lproj

for details

$ man genstrings


问:
Angular 7 - How to retry an http request on certain response status codes?
I'm trying to catch http request's errors from an Angular interceptor and handle 401 as logout while retrying a 503 and 504 responses n times.

This is my http interceptor:

```<code>intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(req).pipe(
      catchError(error => {
        if (error.status === 401) {
          this.authenticationService.logout();
          this.router.navigate(['login']);
        }

        return throwError(error);
      }),
      retryWhen(errors => errors
        .pipe(
          concatMap((error, count) => {
            if (count < 2 && (error.status == 503 || error.status == 504)) {
              return of(error.status);
            }

            return throwError(error);
          }),
          delay(500)
        )
      )
    );
  }
</code>```

I'm 100% sure this code worked when I wrote it because I tested it multiple times but now it's giving me:

```<code>UnsubscriptionErrorImpl
{message: "1 errors occurred during unsubscription:↵1) TypeError: Cannot read property 'apply' of null", name: "UnsubscriptionError", errors: Array(1)}

errors: Array(1)
   0: TypeError: Cannot read property 'apply' of null at RetryWhenSubscriber._zoneUnsubscribe (http://localhost:4200/polyfills.js:8506:44) at RetryWhenSubscriber.push../node_modules/rxjs/_esm5/internal/Subscription.js.Subscription.unsubscribe (http://localhost:4200/polyfills.js:3739:30) at RetryWhenSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.unsubscribe (http://localhost:4200/polyfills.js:3524:38) at RetryWhenSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._unsubscribeAndRecycle (http://localhost:4200/polyfills.js:3541:14) at RetryWhenSubscriber.push../node_modules/rxjs/_esm5/internal/operators/retryWhen.js.RetryWhenSubscriber.notifyNext (http://localhost:4200/vendor.js:155632:14) at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._next (http://localhost:4200/polyfills.js:2717:21) at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (http://localhost:4200/polyfills.js:3504:18) at InnerSubscriber.rxjs.Subscriber.next (http://localhost:4200/polyfills.js:8537:29) at Notification.push../node_modules/rxjs/_esm5/internal/Notification.js.Notification.observe (http://localhost:4200/polyfills.js:2769:50) at AsyncAction.push../node_modules/rxjs/_esm5/internal/operators/delay.js.DelaySubscriber.dispatch (http://localhost:4200/vendor.js:153337:40)
length: 1
__proto__: Array(0)
message: "1 errors occurred during unsubscription:↵1) TypeError: Cannot read property 'apply' of null"
name: "UnsubscriptionError"
</code>```

Last time it was working, I was using angular 6. Now I'm using angular 7.
I already tried different rxjs versions to no avail.

How can I fix this and implement a simple retry logic?

EDIT:

I just noticed that if I remove the import 'zone.js/dist/zone-patch-rxjs'; from the poliyfills.ts file then it works but other things stop working.

答:
You need to close the stream in case of 401 to avoid further logic.

        if (error.status === 401) {
          this.authenticationService.logout();
          this.router.navigate(['login']);
          return EMPTY; // <- add this
        }
```

Body:
I'm trying to catch http request's errors from an Angular interceptor and handle 401 as logout while retrying a 503 and 504 responses n times.

This is my http interceptor:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(req).pipe(
      catchError(error => {
        if (error.status === 401) {
          this.authenticationService.logout();
          this.router.navigate(['login']);
        }

        return throwError(error);
      }),
      retryWhen(errors => errors
        .pipe(
          concatMap((error, count) => {
            if (count < 2 && (error.status == 503 || error.status == 504)) {
              return of(error.status);
            }

            return throwError(error);
          }),
          delay(500)
        )
      )
    );
  }

I'm 100% sure this code worked when I wrote it because I tested it multiple times but now it's giving me:

UnsubscriptionErrorImpl
{message: "1 errors occurred during unsubscription:↵1) TypeError: Cannot read property 'apply' of null", name: "UnsubscriptionError", errors: Array(1)}

errors: Array(1)
   0: TypeError: Cannot read property 'apply' of null at RetryWhenSubscriber._zoneUnsubscribe (http://localhost:4200/polyfills.js:8506:44) at RetryWhenSubscriber.push../node_modules/rxjs/_esm5/internal/Subscription.js.Subscription.unsubscribe (http://localhost:4200/polyfills.js:3739:30) at RetryWhenSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.unsubscribe (http://localhost:4200/polyfills.js:3524:38) at RetryWhenSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._unsubscribeAndRecycle (http://localhost:4200/polyfills.js:3541:14) at RetryWhenSubscriber.push../node_modules/rxjs/_esm5/internal/operators/retryWhen.js.RetryWhenSubscriber.notifyNext (http://localhost:4200/vendor.js:155632:14) at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._next (http://localhost:4200/polyfills.js:2717:21) at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (http://localhost:4200/polyfills.js:3504:18) at InnerSubscriber.rxjs.Subscriber.next (http://localhost:4200/polyfills.js:8537:29) at Notification.push../node_modules/rxjs/_esm5/internal/Notification.js.Notification.observe (http://localhost:4200/polyfills.js:2769:50) at AsyncAction.push../node_modules/rxjs/_esm5/internal/operators/delay.js.DelaySubscriber.dispatch (http://localhost:4200/vendor.js:153337:40)
length: 1
__proto__: Array(0)
message: "1 errors occurred during unsubscription:↵1) TypeError: Cannot read property 'apply' of null"
name: "UnsubscriptionError"

Last time it was working, I was using angular 6. Now I'm using angular 7.
I already tried different rxjs versions to no avail.

How can I fix this and implement a simple retry logic?

EDIT:

I just noticed that if I remove the import 'zone.js/dist/zone-patch-rxjs'; from the poliyfills.ts file then it works but other things stop working.


问:
Msix, packaging and task scheduler
I made a console app using .NET 5.0 in VS2019 pro preview , packaged it with "Windows application packaging project" msix. Everything going smoothly and installed correctly, updates perfectly. Problem arises when I want to add this program to a task scheduler as the .exe file is located in C:\Program Files\WindowsApps\PackageName\Version...<br>
 1. Can't run it from the WindowsApps folder due to restrictions (As there are going to be multiple other users it's not feasible to make them all gain access).
 2. The folder will change name if I push an update given the version nr.
Is there a way to do this correctly? Like a command to launch windows app files? Any help would be appreciated! </p>

答:
Have you tried defining an execution alias and specifying the alias name (not path) as target for the scheduled task?

This should solve both the permission and changing paths problem.

Title: Msix, packaging and task scheduler

Body:
I made a console app using .NET 5.0 in VS2019 pro preview , packaged it with "Windows application packaging project" msix. Everything going smoothly and installed correctly, updates perfectly. Problem arises when I want to add this program to a task scheduler as the .exe file is located in C:\Program Files\WindowsApps\PackageName\Version...

 1. Can't run it from the WindowsApps folder due to restrictions (As there are going to be multiple other users it's not feasible to make them all gain access).
 2. The folder will change name if I push an update given the version nr.
Is there a way to do this correctly? Like a command to launch windows app files? Any help would be appreciated!


问:
Can I use await async inside an async function?
I'm an a newbie studying promises and async/await and would like to know if it's possible to change this code:

```<code>async function waiting() {
   let a = await new Promise(r => setTimeout(() => r('A'), 1e3))
   let b = await new Promise(r => setTimeout(() => r('B'), 2e3))
   let c = await new Promise(r => setTimeout(() => r('C'), 3e3))
   console.log(a, b, c)
}

waiting()
</code>```

And use something like this:

let a = await async () => setTimeout(() =>  'A', 1e3)

or similiar.

Update:

I also tried this:

let a = await (() => setTimeout(() => 'A', 1e3))()

I want to achieve the same with a shortened syntax.

答:
The short answer is yes. Awaiting anything turns it into a promise. You could say something like

```<code>// not asynchronous; not a promise
function foo() { return 3; }
. . .
async function do_it() {
  const x  = await foo();
}
</code>```

foo() essentially gets wrapped with something like

```<code>new Promise( (resolve, reject) => {
  try {
    resolve(foo());
  } catch (err) {
    reject(err);
  }
}
</code>```

So you could say something like:

```<code>const sleep = ms  => new Promise( resolve => setTimeout( () => resolve(), ms) );

async function waiting() {

   await sleep(1000);
   const a = await computeA();
   await sleep(2000);
   const b = await computeB();
   await sleep(3000);
   const c = await computeC();

   console.log(a, b, c)

}
</code>```

async/await allows one to express things in a more procedural looking manner. It also surrenders the event loop: other things can continue to process while you're waiting.

Body:
I'm an a newbie studying promises and async/await and would like to know if it's possible to change this code:

async function waiting() {
   let a = await new Promise(r => setTimeout(() => r('A'), 1e3))
   let b = await new Promise(r => setTimeout(() => r('B'), 2e3))
   let c = await new Promise(r => setTimeout(() => r('C'), 3e3))
   console.log(a, b, c)
}

waiting()

And use something like this:

let a = await async () => setTimeout(() =>  'A', 1e3)

or similiar.

Update:

I also tried this:

let a = await (() => setTimeout(() => 'A', 1e3))()

I want to achieve the same with a shortened syntax.

Body:
The short answer is yes. Awaiting anything turns it into a promise. You could say something like

// not asynchronous; not a promise
function foo() { return 3; }
. . .
async function do_it() {
  const x  = await foo();
}

foo() essentially gets wrapped with something like

new Promise( (resolve, reject) => {
  try {
    resolve(foo());
  } catch (err) {
    reject(err);
  }
}

So you could say something like:

const sleep = ms  => new Promise( resolve => setTimeout( () => resolve(), ms) );

async function waiting() {

   await sleep(1000);
   const a = await computeA();
   await sleep(2000);
   const b = await computeB();
   await sleep(3000);
   const c = await computeC();

   console.log(a, b, c)

}

async/await allows one to express things in a more procedural looking manner. It also surrenders the event loop: other things can continue to process while you're waiting.


问:
How do I open a minimized window using python?
is it possible to un-minimize a minimized window using python on windows 10? (I'm using python 3.8)

I would add more detail but that's really all I need to say.

答:
I combined information from multiple sources and got this to work (Miniconda Python 3.6, Windows 10)

```<code>import win32gui
import win32con

def windowEnumHandler(hwnd, top_windows):
    top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))

def bringToFront(window_name):
    top_windows = []
    win32gui.EnumWindows(windowEnumHandler, top_windows)
    for i in top_windows:
        # print(i[1])
        if window_name.lower() in i[1].lower():
            # print("found", window_name)
            win32gui.ShowWindow(i[0], win32con.SW_SHOWNORMAL)
            win32gui.SetForegroundWindow(i[0])
            break

# Test with notepad
if __name__ == "__main__":
    winname = "notepad"
    bringToFront(winname)
</code>```

The Handler is not optimal; it spits out various processes that are not the windows in the taskbar. However, as long as your window_name is specific I don't think you'll run into problems. If you remove the break, all matches will be "opened".

Sources: Mouse and Python Blog

Another StackOverflow question

Body:
I combined information from multiple sources and got this to work (Miniconda Python 3.6, Windows 10)

import win32gui
import win32con

def windowEnumHandler(hwnd, top_windows):
    top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))

def bringToFront(window_name):
    top_windows = []
    win32gui.EnumWindows(windowEnumHandler, top_windows)
    for i in top_windows:
        # print(i[1])
        if window_name.lower() in i[1].lower():
            # print("found", window_name)
            win32gui.ShowWindow(i[0], win32con.SW_SHOWNORMAL)
            win32gui.SetForegroundWindow(i[0])
            break

# Test with notepad
if __name__ == "__main__":
    winname = "notepad"
    bringToFront(winname)

The Handler is not optimal; it spits out various processes that are not the windows in the taskbar. However, as long as your window_name is specific I don't think you'll run into problems. If you remove the break, all matches will be "opened".

Sources: Mouse and Python Blog

Another StackOverflow question


问:
How to Fixed / Lock Position of Background Image & Divs Containing Images
I have a map image (1080x1080px) I want this to be the the background of the body or a container div. I need the image to stay fixed in its place always, even when resizing the browser window.

I have divs inside of the main div container and these divs have images which are map markers that have been places at specific locations and they are toggled on and off as required.

Both the background image (map) and the markers need to stay in their position permanently.

How can I achieve this? What I have is not working...

body, html {
  height: 100%;
}

#bg {
  background-image: url(treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

  input:checked + .hidable {
    display: none;
  }

  input:not(:checked) + .showable {
    display: none;
  }

  #mark01 {
    position: absolute;
    top: 240px;
    right: 490px;
  }

  #mark02 {
    position: absolute;
    top: 480px;
    left: 460px;
  }

  #mark03 {
    position: absolute;
    bottom: 260px;
    right: 490px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Treasure Map</title>
</head>
<body>

  <div id="bg">
    <div id="menu">
      <input type="checkbox" /> Marker 1
      <div class="showable"><img id="mark01" src="xmark_01.png" alt="X Mark Red"></div>
      <input type="checkbox" /> Marker 2
      <div class="showable"><img id="mark02" src="xmark_02.png" alt="X Mark Green"></div>
      <input type="checkbox" /> Marker 3
      <div class="showable"><img id="mark03" src="xmark_03.png" alt="X Mark Magenta"></div>
    </div>
  </div>

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

答:
Thanks but it won't send I'm trying to find a way out to send in a simple language programming. You can also write this code in the background shorthand then you'd simply add the background image to the div and adjust the height property as necessary.

Apostrophe in between the backgroundimage and and hyfin to end it to get the picture

Body:
I have a map image (1080x1080px) I want this to be the the background of the body or a container div. I need the image to stay fixed in its place always, even when resizing the browser window.

I have divs inside of the main div container and these divs have images which are map markers that have been places at specific locations and they are toggled on and off as required.

Both the background image (map) and the markers need to stay in their position permanently.

How can I achieve this? What I have is not working...

body, html {
  height: 100%;
}

#bg {
  background-image: url(treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

  input:checked + .hidable {
    display: none;
  }

  input:not(:checked) + .showable {
    display: none;
  }

  #mark01 {
    position: absolute;
    top: 240px;
    right: 490px;
  }

  #mark02 {
    position: absolute;
    top: 480px;
    left: 460px;
  }

  #mark03 {
    position: absolute;
    bottom: 260px;
    right: 490px;
  }

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Treasure Map</title>

      <input type="checkbox" /> Marker 1

      <input type="checkbox" /> Marker 2

      <input type="checkbox" /> Marker 3


问:
Repeating background service using Alarm Manager
Currently I'm working on a new android project which uses background service. Because android version >=Oreo kills service automatically. So i use AlarmManager. I need to display a notification on exact time. Time for notification is setted in shared preferences.
My Alarm handler is following

```<code>class AlarmHandler {
    private Context context;
    AlarmHandler(Context context){
        this.context=context;
    }
    void setAlarmManager(){
        Intent intent=new Intent(context,NotificationService.class);
        PendingIntent pendingIntent=PendingIntent.getBroadcast(context,2,intent,0);
        AlarmManager alarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if(alarmManager!=null){
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,5000,60000,pendingIntent);
        }
    }
    void cancelAlarmManager(){
        Intent intent=new Intent(context,NotificationService.class);
        PendingIntent pendingIntent=PendingIntent.getBroadcast(context,2,intent,0);
        AlarmManager alarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if(alarmManager!=null){
            alarmManager.cancel(pendingIntent);
        }
    }
}
</code>```

My Notification service is following

```<code>public class NotificationService extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String t1=timeFromsharedPreferences("t1");
        String t2=timeFromsharedPreferences("t2");
        String systemTime=getCurrentTime();
        if(systemTime.equals(t1)){
            notify();
        }else if(systemTime.equals(t2)){
            notify();
        }
    }
}
</code>```

I start AlarmHandler using following code

```<code>AlarmHandler alarmHandler=new AlarmHandler(this);
alarmHandler.cancelAlarmManager();
alarmHandler.setAlarmManager();
</code>```

I also register the broad cast receiver as following

```<code><receiver android:name=".NotificationService" android:enabled="true" />
</code>```

My problem is some times it's skipping my notification. Time is sheduled for 10:00 pm and 7:00 am. Notification on 10 pm is recieved (Note that i'm using phone at 10:00 pm or used minutes before 10:00 pm). But notification on 7:00 am is not receiving all time. Also note that i need notification on every day at same times. Please help me.

答:
You cannot have a repeating exact alarm. If you need it to repeat at exact intervals, you need to set an exact alarm at the 1st interval, then re-arm the alarm when it fires so it is armed for the next interval, and keep repeating that process.

Edit:

you need to do something like this

```<code>1.- compute delta in millis to next interval
2.- set exact alarm to fire in delta millis
3.- when the alarm fires, handle the event and then go to step 1
</code>```

Body:
Currently I'm working on a new android project which uses background service. Because android version >=Oreo kills service automatically. So i use AlarmManager. I need to display a notification on exact time. Time for notification is setted in shared preferences.
My Alarm handler is following

class AlarmHandler {
    private Context context;
    AlarmHandler(Context context){
        this.context=context;
    }
    void setAlarmManager(){
        Intent intent=new Intent(context,NotificationService.class);
        PendingIntent pendingIntent=PendingIntent.getBroadcast(context,2,intent,0);
        AlarmManager alarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if(alarmManager!=null){
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,5000,60000,pendingIntent);
        }
    }
    void cancelAlarmManager(){
        Intent intent=new Intent(context,NotificationService.class);
        PendingIntent pendingIntent=PendingIntent.getBroadcast(context,2,intent,0);
        AlarmManager alarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if(alarmManager!=null){
            alarmManager.cancel(pendingIntent);
        }
    }
}

My Notification service is following

public class NotificationService extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String t1=timeFromsharedPreferences("t1");
        String t2=timeFromsharedPreferences("t2");
        String systemTime=getCurrentTime();
        if(systemTime.equals(t1)){
            notify();
        }else if(systemTime.equals(t2)){
            notify();
        }
    }
}

I start AlarmHandler using following code

AlarmHandler alarmHandler=new AlarmHandler(this);
alarmHandler.cancelAlarmManager();
alarmHandler.setAlarmManager();

I also register the broad cast receiver as following

<receiver android:name=".NotificationService" android:enabled="true" />

My problem is some times it's skipping my notification. Time is sheduled for 10:00 pm and 7:00 am. Notification on 10 pm is recieved (Note that i'm using phone at 10:00 pm or used minutes before 10:00 pm). But notification on 7:00 am is not receiving all time. Also note that i need notification on every day at same times. Please help me.

Body:
You cannot have a repeating exact alarm. If you need it to repeat at exact intervals, you need to set an exact alarm at the 1st interval, then re-arm the alarm when it fires so it is armed for the next interval, and keep repeating that process.

Edit:

you need to do something like this

1.- compute delta in millis to next interval
2.- set exact alarm to fire in delta millis
3.- when the alarm fires, handle the event and then go to step 1


问:
No Main class found in NetBeans
I have been working on an assignment for my class in programming. I am working with NetBeans. I finished my project and it worked fine. I am getting a message that says "No main class found" when I try to run it. Here is some of the code with the main:

```<code>package luisrp3;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class LuisRp3 {

public static void main(String[] args) throws FileNotFoundException  {

    java.io.File newFile = new java.io.File("LuisRamosp4.txt");

    if (newFile.exists()) {
        newFile.delete();
    }

    System.setOut(new PrintStream(newFile));

    Guitar guitar = new Guitar();
</code>```

I posted this before but had a couple issues. i have fixed the others and now have just this one remaining. Any advice will be greatly appreciated.

答: The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class: box until you see the connections. (Note that the class containing the main method need not necessarily be named Main but the main method can have no other name.)

ContentLicense: CC BY-SA 3.0

Title: No Main class found in NetBeans

Body:
I have been working on an assignment for my class in programming. I am working with NetBeans. I finished my project and it worked fine. I am getting a message that says "No main class found" when I try to run it. Here is some of the code with the main:

package luisrp3;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class LuisRp3 {

public static void main(String[] args) throws FileNotFoundException  {

    java.io.File newFile = new java.io.File("LuisRamosp4.txt");

    if (newFile.exists()) {
        newFile.delete();
    }

    System.setOut(new PrintStream(newFile));

    Guitar guitar = new Guitar();

I posted this before but had a couple issues. i have fixed the others and now have just this one remaining. Any advice will be greatly appreciated.


问:
How can I define a 5x3 array of strings in python?
How can I define a 5x3 array of strings in python?

I want to save the following data in an array of strings:

```<code>Name    Surname Grade
Steve   Black   10
Jane    Red     10
Peter   Green   0
Kelly   Pink    7
</code>```

I am coming from C/C++ and in this programming language it would look like this:

```<code>matrix[5][3];

matrix[0][0] = "Name";
matrix[0][1] = "Surname";
matrix[0][2] = "Grade";

matrix[1][0] = "Steve";
matrix[1][1] = "Black";
matrix[1][2] = "10";

...
...
...

matrix[4][0] = "Kelly";
matrix[4][1] = "Pink";
matrix[4][2] = "7";
</code>```

Is there a way in python to create such table?

In case you know what kind of data type that is in python and how it work, please let me know.

答:
You could do something like this: </p>

```<code>data = \
'''
Name    Surname Grade
Steve   Black   10
Jane    Red     10
Peter   Green   0
Kelly   Pink    7
'''

matrix = [line.split() for line in data.strip().split('\n')]
print(matrix)
</code>```

Body:
How can I define a 5x3 array of strings in python?

I want to save the following data in an array of strings:

Name    Surname Grade
Steve   Black   10
Jane    Red     10
Peter   Green   0
Kelly   Pink    7

I am coming from C/C++ and in this programming language it would look like this:

matrix[5][3];

matrix[0][0] = "Name";
matrix[0][1] = "Surname";
matrix[0][2] = "Grade";

matrix[1][0] = "Steve";
matrix[1][1] = "Black";
matrix[1][2] = "10";

...
...
...

matrix[4][0] = "Kelly";
matrix[4][1] = "Pink";
matrix[4][2] = "7";

Is there a way in python to create such table?

In case you know what kind of data type that is in python and how it work, please let me know.

Body:
You could do something like this:

data = \
'''
Name    Surname Grade
Steve   Black   10
Jane    Red     10
Peter   Green   0
Kelly   Pink    7
'''

matrix = [line.split() for line in data.strip().split('\n')]
print(matrix)


答:
Put it in a nested list</p>

```<code>a = [["Steve", "Black", 10], ["Jane", "Red", 10], ["Peter", "Green", 0], ["Kelly", "Pink", 7]]
</code>```

Title: How can I define a 5x3 array of strings in python?

Body:
Put it in a nested list

a = [["Steve", "Black", 10], ["Jane", "Red", 10], ["Peter", "Green", 0], ["Kelly", "Pink", 7]]


问:
how to convert date format in php from an existing format
In a database, the date is stored like this: 14 May 2020 22:25

I was wondering, when reading this line from database, and change the output to this: 14-5-2020, is it possible to convert this easily? because sometimes i want to output 14 May 2020 22:25 and sometimes i want to output 14-5-2020. And if is possible, i only want to store 1 format in the database

答:
<?php

$date = DateTime::createFromFormat('d M Y H:i', '14 May 2020 22:25');
echo $date->format('d-n-Y'); //14-5-2020
```

As mentioned in the comment by @Sammitch, you can use PHP DateTime Class to achieve this.
You can format the Date and Time, once you create it. Be sure to check the format guide. Given below as link.

Useful Links:

Formatting DateTime in PHP

PHP DateTime

Body:
<?php

$date = DateTime::createFromFormat('d M Y H:i', '14 May 2020 22:25');
echo $date->format('d-n-Y'); //14-5-2020

As mentioned in the comment by @Sammitch, you can use PHP DateTime Class to achieve this.
You can format the Date and Time, once you create it. Be sure to check the format guide. Given below as link.

Useful Links:

Formatting DateTime in PHP

PHP DateTime


问:
How to convert JSON string column row into a queryable table
I have exported to BigQuery from Firestore a whole collection to perform certain queries on it.

After the data was populated in my BigQuery console, now I can query the whole set like this

```<code>SELECT *
FROM `myapp-1a602.firestore_orders.orders_raw_changelog`
LIMIT 1000
</code>```

Now, this statement throws my different columns, but the one I'm looking for is the data column, in my data column is each document JSON, but is in json format and I need to query all this values.

Now, this is the data from one row

```<code>{
    "cart": [{
        "qty": 1,
        "description": "Sprite 1 L",
        "productName": "Sprite 1 Liter",
        "price": 1.99,
        "productId": 9
    }],
    "storeName": "My awesome shop",
    "status": 5,
    "timestamp": {
        "_seconds": 1590713204,
        "_nanoseconds": 916000000
    }
}
</code>```

This data is inside the data column, so if I do this

```<code>SELECT data
FROM `myapp-1a602.firestore_orders.orders_raw_changelog`
LIMIT 1000
</code>```

I will get all the json values for each document, but I don't know how to query that values, lets say I want to know all orders with status 5 and shopName My awesome shop , now, I need to do something with this json to convert it into a table ? does I need to perform the query in the json itself ?

How can I query this json output ?

Thanks

答:
You can use UNNEST in the WHERE clause to access the cart's columns, and JSON_EXTRACT functions in the WHERE clause to filter the rows wanted. You need to take care on accessing either the json root or the array cart; json_data and cart_items in the example below (by the way, in your example shopName doesn't exist but storeName does).

```<code>WITH
  `myapp-1a602.firestore_orders.orders_raw_changelog` AS (
  SELECT
    '{"cart": [{"qty": 1,"description": "Sprite 1 L","productName": "Sprite 1 Liter","price": 1.99,"productId": 9}, {"qty": 11,"description": "Sprite 11 L","productName": "Sprite 11 Liter","price": 11.99,"productId": 19}],"storeName": "My awesome shop","status": 5,"timestamp": {"_seconds": 1590713204,"_nanoseconds": 916000000}}' json_data )
SELECT
  JSON_EXTRACT(json_data, '$.status') AS status,
  JSON_EXTRACT(json_data, '$.storeName') AS storeName,
  JSON_EXTRACT(cart_items, '$.productName') AS product,
  JSON_EXTRACT_SCALAR(cart_items, '$.qty') AS qty
FROM
  `myapp-1a602.firestore_orders.orders_raw_changelog`,
  UNNEST(JSON_EXTRACT_ARRAY(json_data, '$.cart')) AS cart_items
WHERE
  JSON_EXTRACT(json_data,'$.storeName') like "\"My awesome shop\"" AND
  CAST(JSON_EXTRACT_SCALAR(json_data,'$.status') AS NUMERIC) = 5
</code>```

Body:
I have exported to BigQuery from Firestore a whole collection to perform certain queries on it.

After the data was populated in my BigQuery console, now I can query the whole set like this

SELECT *
FROM `myapp-1a602.firestore_orders.orders_raw_changelog`
LIMIT 1000

Now, this statement throws my different columns, but the one I'm looking for is the data column, in my data column is each document JSON, but is in json format and I need to query all this values.

Now, this is the data from one row

{
    "cart": [{
        "qty": 1,
        "description": "Sprite 1 L",
        "productName": "Sprite 1 Liter",
        "price": 1.99,
        "productId": 9
    }],
    "storeName": "My awesome shop",
    "status": 5,
    "timestamp": {
        "_seconds": 1590713204,
        "_nanoseconds": 916000000
    }
}

This data is inside the data column, so if I do this

SELECT data
FROM `myapp-1a602.firestore_orders.orders_raw_changelog`
LIMIT 1000

I will get all the json values for each document, but I don't know how to query that values, lets say I want to know all orders with status 5 and shopName My awesome shop , now, I need to do something with this json to convert it into a table ? does I need to perform the query in the json itself ?

How can I query this json output ?

Thanks

Body:
You can use UNNEST in the WHERE clause to access the cart's columns, and JSON_EXTRACT functions in the WHERE clause to filter the rows wanted. You need to take care on accessing either the json root or the array cart; json_data and cart_items in the example below (by the way, in your example shopName doesn't exist but storeName does).

WITH
  `myapp-1a602.firestore_orders.orders_raw_changelog` AS (
  SELECT
    '{"cart": [{"qty": 1,"description": "Sprite 1 L","productName": "Sprite 1 Liter","price": 1.99,"productId": 9}, {"qty": 11,"description": "Sprite 11 L","productName": "Sprite 11 Liter","price": 11.99,"productId": 19}],"storeName": "My awesome shop","status": 5,"timestamp": {"_seconds": 1590713204,"_nanoseconds": 916000000}}' json_data )
SELECT
  JSON_EXTRACT(json_data, '$.status') AS status,
  JSON_EXTRACT(json_data, '$.storeName') AS storeName,
  JSON_EXTRACT(cart_items, '$.productName') AS product,
  JSON_EXTRACT_SCALAR(cart_items, '$.qty') AS qty
FROM
  `myapp-1a602.firestore_orders.orders_raw_changelog`,
  UNNEST(JSON_EXTRACT_ARRAY(json_data, '$.cart')) AS cart_items
WHERE
  JSON_EXTRACT(json_data,'$.storeName') like "\"My awesome shop\"" AND
  CAST(JSON_EXTRACT_SCALAR(json_data,'$.status') AS NUMERIC) = 5


问:
Is it safe to load HTML and js via ajax?
I'm using the Jquery load function $('#result').load('test.php'); to load a page into another page by clicking a tab. The page I'm loading contains javascript, php, and contains a form. Using the firebug console I saw that there is a GET for all my script sources in the page I'm loading as well. Not sure if that should be a concern..

Can data be hacked via the jquery load? Are there any issues to consider?

note: I'm aware that old browsers don't work with javascript but is there anything else to consider?

答:
Loading content using AJAX does not introduce any additional security issues.

An attacker can hijack the connection and inject his own Javascript (unless you're using HTTPS), but he can also do that to the page itself.

An attacker can exploit an XSS hole in your backend to run his own Javascript, but he can also do that to the page itself.


问:
Check that button is disabled in react-testing-library
I have a React component that generates a button whose content contains a  element like this one:

```<code>function Click(props) {
    return (
        <button disable={props.disable}>
            <span>Click me</span>
        </button>
    );
}
</code>```

I want to test the logic of this component with the use of react-testing-library and mocha + chai.

The problem at which I stuck at the moment is that the getByText("Click me") selector returns the  DOM node, but for the tests, I need to check the disable attribute of the <button> node. What is the best practice for handling such test cases? I see a couple of solutions, but all of them sound a little bit off:

Use data-test-id for <button> element

Select one of the ancestors of the <Click /> component and then select the button within(...) this scope

Click on the selected element with fireEvent and check that nothing has happened

Can you suggest a better approach?

答:
Another way to fix this would be to grab by the role and check the innerHTML like,

```<code>const { getByRole } = render(<Click />)
const button = getByRole('button')

// will make sure the 'Click me' text is in there somewhere
expect(button.innerHTML).toMatch(/Click me/))

</code>```

This isn't the best solution for your specific case, but it's one to keep in your back pocket if you have to deal with a button component that's not an actual button, e.g.,

Click Me

Body:
I have a React component that generates a button whose content contains a  element like this one:

function Click(props) {
    return (
        <button disable={props.disable}>
            Click me
        </button>
    );
}

I want to test the logic of this component with the use of react-testing-library and mocha + chai.

The problem at which I stuck at the moment is that the getByText("Click me") selector returns the  DOM node, but for the tests, I need to check the disable attribute of the <button> node. What is the best practice for handling such test cases? I see a couple of solutions, but all of them sound a little bit off:

Use data-test-id for <button> element

Select one of the ancestors of the <Click /> component and then select the button within(...) this scope

Click on the selected element with fireEvent and check that nothing has happened

Can you suggest a better approach?

Body:
Another way to fix this would be to grab by the role and check the innerHTML like,

const { getByRole } = render(<Click />)
const button = getByRole('button')

// will make sure the 'Click me' text is in there somewhere
expect(button.innerHTML).toMatch(/Click me/))

This isn't the best solution for your specific case, but it's one to keep in your back pocket if you have to deal with a button component that's not an actual button, e.g.,

<div role="button"><span>Click Me</span></div>


问:
visibility hidden on react native not working, to take space even not shown?
I have TouchableOpacity in a space between flex container that I want to take space even not shown,

My code:

```<code><TouchableOpacity
  style={showClear && { visibility: 'hidden' }}
  onPress={() => this.props.clearCompleted()}>
  <Text>Clear Completed</Text>
</TouchableOpacity>
</code>```

display: none works but it doesn't take space, the code above dont work but does in web?

答:
In my case, I needed to use the element, so I did something like this:

```<code><TextInput style={{opacity: 0, height: 0}} {...props} />
</code>```

I hope this works for someone else with my problem.

Body:
I have TouchableOpacity in a space between flex container that I want to take space even not shown,

My code:

<TouchableOpacity
  style={showClear && { visibility: 'hidden' }}
  onPress={() => this.props.clearCompleted()}>
  <Text>Clear Completed</Text>
</TouchableOpacity>

display: none works but it doesn't take space, the code above dont work but does in web?

Body:
In my case, I needed to use the element, so I did something like this:

<TextInput style={{opacity: 0, height: 0}} {...props} />

I hope this works for someone else with my problem.


问:
Concatenate multiple files based on similar ID in a loop
I have these files in the same folder:

```<code>results1_1_2_4
results2_1_2_4
results3_1_2_4
results4_1_2_4
results5_1_2_4

results1_0.001_2_25
results2_0.001_2_25
results3_0.001_2_25
results4_0.001_2_25
results5_0.001_2_25

results1_0.1_3_50
results2_0.1_3_50
results3_0.1_3_50
results4_0.1_3_50
results5_0.1_3_50
</code>```

I would like to combine the five files results1+results2+results3+results4+results5 for each combination, for example "1_2_4", "0.001_2_25" and "0.1_3_50". So the ouput should be:

```<code>results_1_2_4
results_0.001_2_25
results_0.1_3_50
</code>```

A similar question is here (cat multiple files based on ID in filename), but I tried with no success:

```<code>for f in results*; do cat "$f" >> "results${*_f%%}"; done
</code>```

答:
Just a slight adjustment to the parameter expansion:</p>

```<code>for f in results*; do
  cat "$f" >> "results_<b>${f#*_}</b>"
done</code>```

Body:
I have these files in the same folder:

results1_1_2_4
results2_1_2_4
results3_1_2_4
results4_1_2_4
results5_1_2_4

results1_0.001_2_25
results2_0.001_2_25
results3_0.001_2_25
results4_0.001_2_25
results5_0.001_2_25

results1_0.1_3_50
results2_0.1_3_50
results3_0.1_3_50
results4_0.1_3_50
results5_0.1_3_50

I would like to combine the five files results1+results2+results3+results4+results5 for each combination, for example "1_2_4", "0.001_2_25" and "0.1_3_50". So the ouput should be:

results_1_2_4
results_0.001_2_25
results_0.1_3_50

A similar question is here (cat multiple files based on ID in filename), but I tried with no success:

for f in results*; do cat "$f" >> "results${*_f%%}"; done

Body:
Just a slight adjustment to the parameter expansion:

for f in results*; do
  cat "$f" >> "results_${f#*_}"
done


问:
HTML Validation: Why is it not valid to put an interactive element inside an interactive element?
Disclaimer: I understand that it is not valid HTML. I am trying to understand why is it not allowed?

W3C suggests that an interactive element like button or a mustn't contain another interactive element.

I could find a lot of resources mentioning this rule and some workarounds, also some resources related to how this impacts accessibility and screenreaders, but almost all of those resources talk about the fact that this is a requirement but do not explain why.

https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html

https://codepen.io/vloux/pen/wXGyOv

Nesting  inside <button> doesn't work in Firefox

https://github.com/dequelabs/axe-core/issues/601

I wasn't really able to find an explanation for why is it not allowed? does it lead to any usability problems?

This is a related question:
Why should interactive element not be used within an anchor?

The accepted answer is satisfactory but is not enough to make this rule a requirement. The described situation can be avoided using proper event handling.

Also, if nested interactive content is invalid, how are we supposed to have something like this:

A card which is clickable as a whole, and also has a clickable secondary CTA inside it.
I know a workaround would be to have a primary and secondary CTA inside the card, but shouldn't the above be allowed as well?

Here is a fiddle:
https://jsfiddle.net/t9qbwas5/2/

```<code><button type="button" class="card">
  The card itself is the primary CTA.
  <br/>
  <br/>
  some important content to read through.
  some important content to read through.
  some important content to read through.
  <div class="cta">
   Secondary CTA
  </div>
</button>

.cta {
  padding: 4px;
  background: #00a9a9;
  color: white;
  width: 80px;
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
}

.card {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}
</code>```

In the above example, I am achieving this by using a clickable div inside the button, but that is not semantic (?) and also functionality wise, it is an interactive element inside another one. I am trying to understand that even if I use this workaround, is it fundamentally wrong to have nested interactive elements? is it a bad design/usability practice?

答:
It's hard to answer "why" questions, because there are many factors to be considered and ultimately the reason is that the specification specifies it, but I'll give it a try.

When this behavior was spec'ed, this design style was not very common. A link was normally either a single image or a small portion of text. Take a look at this link to an article from the year 2000:

]

Only the title and the image are interactive. The rest is simple text.

Even today, this is not so common. Take also look at the Microsoft 365 pricing page:

Note how the card itself is not interactive, only the things inside it. You can see the primary CTA "Buy now" in the form of a button and the secondary CTAs in the form of hyperlinks.

Now, about your example: Is that card really a button? It might be subjective, but for me that's not a button. A button normally appears with a color scheme contrasting with the surrounding page. I would make the card a
 and the secondary CTA a <button>.

However it might be confusing to users, as the card doesn't seem much interactive to me. Consider adding cursor: pointer to the
 (beyond all the things necessary for accessibility)`.

I noted you tagged accessibility. I think this is not a great idea for people using screen readers, and I think most screen readers would have problems interpreting a button inside a button (if the browser accepted that at all).

I would use the "Microsoft 365 pricing page approach" instead. It's simpler and works well with HTML.

Body:
Disclaimer: I understand that it is not valid HTML. I am trying to understand why is it not allowed?

W3C suggests that an interactive element like button or a mustn't contain another interactive element.

I could find a lot of resources mentioning this rule and some workarounds, also some resources related to how this impacts accessibility and screenreaders, but almost all of those resources talk about the fact that this is a requirement but do not explain why.

https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html

https://codepen.io/vloux/pen/wXGyOv

Nesting  inside <button> doesn't work in Firefox

https://github.com/dequelabs/axe-core/issues/601

I wasn't really able to find an explanation for why is it not allowed? does it lead to any usability problems?

This is a related question:
Why should interactive element not be used within an anchor?

The accepted answer is satisfactory but is not enough to make this rule a requirement. The described situation can be avoided using proper event handling.

Also, if nested interactive content is invalid, how are we supposed to have something like this:

A card which is clickable as a whole, and also has a clickable secondary CTA inside it.
I know a workaround would be to have a primary and secondary CTA inside the card, but shouldn't the above be allowed as well?

Here is a fiddle:
https://jsfiddle.net/t9qbwas5/2/

<button type="button" class="card">
  The card itself is the primary CTA.

  some important content to read through.
  some important content to read through.
  some important content to read through.

   Secondary CTA

</button>

.cta {
  padding: 4px;
  background: #00a9a9;
  color: white;
  width: 80px;
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
}

.card {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

In the above example, I am achieving this by using a clickable div inside the button, but that is not semantic (?) and also functionality wise, it is an interactive element inside another one. I am trying to understand that even if I use this workaround, is it fundamentally wrong to have nested interactive elements? is it a bad design/usability practice?

Body:
It's hard to answer "why" questions, because there are many factors to be considered and ultimately the reason is that the specification specifies it, but I'll give it a try.

When this behavior was spec'ed, this design style was not very common. A link was normally either a single image or a small portion of text. Take a look at this link to an article from the year 2000:

]

Only the title and the image are interactive. The rest is simple text.

Even today, this is not so common. Take also look at the Microsoft 365 pricing page:

Note how the card itself is not interactive, only the things inside it. You can see the primary CTA "Buy now" in the form of a button and the secondary CTAs in the form of hyperlinks.

Now, about your example: Is that card really a button? It might be subjective, but for me that's not a button. A button normally appears with a color scheme contrasting with the surrounding page. I would make the card a <div> and the secondary CTA a <button>.

However it might be confusing to users, as the card doesn't seem much interactive to me. Consider adding cursor: pointer to the <div> (beyond all the things necessary for accessibility)`.

I noted you tagged accessibility. I think this is not a great idea for people using screen readers, and I think most screen readers would have problems interpreting a button inside a button (if the browser accepted that at all).

I would use the "Microsoft 365 pricing page approach" instead. It's simpler and works well with HTML.


问:
Changing Tomcat server name in response header, is that possible?
When a http request from a browser is made, typically the server container will send along in the header what server it was.

For tomcat it sends

```<code>   Server:Apache-Coyote/1.1
</code>```

I know I can overwrite this header, for each request, but there  is also the case for websockets and potentially other connections.

So, is there a way to change this at the tomcat configuration level?

答:
GoTo your tomcat (server.xml) installation path
exa:- C:/[Apache-Tomcat-Installation-Directory]/conf/server.xml

find:-
Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000"

enableLookups="false" redirectPort="8443"

add:-
server="Any Server Name"
inside the above tag. for safety purpose take a backup of xml file.

Body:
When a http request from a browser is made, typically the server container will send along in the header what server it was.

For tomcat it sends

   Server:Apache-Coyote/1.1

I know I can overwrite this header, for each request, but there  is also the case for websockets and potentially other connections.

So, is there a way to change this at the tomcat configuration level?


答: So long as your site isn't compromised, a XHR to your own data is inherently no more dangerous than any other request.</p>

Title: Is it safe to load HTML and js via ajax?

Body:
I'm using the Jquery load function $('#result').load('test.php'); to load a page into another page by clicking a tab. The page I'm loading contains javascript, php, and contains a form. Using the firebug console I saw that there is a GET for all my script sources in the page I'm loading as well. Not sure if that should be a concern..

Can data be hacked via the jquery load? Are there any issues to consider?

note: I'm aware that old browsers don't work with javascript but is there anything else to consider?


答:
You can use numpy for this.
    import numpy as np

```<code>matrix_data = np.array([["Name", "Surname", "Grade"],
                    ["Steve", "Black", "10"],
                    ["Jane", "Red", "10"],
                    ["Peter", "Green", "0"],
                    ["Kelly", "Pink", "7"]])
</code>```

You can access elements of the array created using the line of code below,

Code:

```<code>print(matrix_data[0][2])
</code>```

Output:

```<code>Grade
</code>```

Using numpy is specifically useful when trying to obtain subsets of this matrix like shown below,

Code:

```<code>matrix_data[:,2]
</code>```

Output:

```<code>['Grade' '10' '10' '0' '7']
</code>```

Body:
You can use numpy for this.
    import numpy as np

matrix_data = np.array([["Name", "Surname", "Grade"],
                    ["Steve", "Black", "10"],
                    ["Jane", "Red", "10"],
                    ["Peter", "Green", "0"],
                    ["Kelly", "Pink", "7"]])

You can access elements of the array created using the line of code below,

Code:

print(matrix_data[0][2])

Output:

Grade

Using numpy is specifically useful when trying to obtain subsets of this matrix like shown below,

Code:

matrix_data[:,2]

Output:

['Grade' '10' '10' '0' '7']


问:
How can I wrap every request with RestClient to use :verify_ssl => false?
I'm trying

```<code>RestClient.add_before_execution_proc do |req, params|
  req(:verify_ssl => false)
end
</code>```

It isn't working.

How can I wrap every request with RestClient to use :verify_ssl => false?

答:
In response to @alb-i986's comment for @AlexandreAngelim's answer, I've written the follow monkey patch that wraps the constructor of RestClient::Request class instead so it would work with the latest RestClient:

```<code>module RestClient
    class Request
        orig_initialize = instance_method(:initialize)

        define_method(:initialize) do |args|
            args[:verify_ssl] = false
            orig_initialize.bind(self).(args)
        end
    end
end
</code>```

Body:
I'm trying

RestClient.add_before_execution_proc do |req, params|
  req(:verify_ssl => false)
end

It isn't working.

How can I wrap every request with RestClient to use :verify_ssl => false?

Body:
In response to @alb-i986's comment for @AlexandreAngelim's answer, I've written the follow monkey patch that wraps the constructor of RestClient::Request class instead so it would work with the latest RestClient:

module RestClient
    class Request
        orig_initialize = instance_method(:initialize)

        define_method(:initialize) do |args|
            args[:verify_ssl] = false
            orig_initialize.bind(self).(args)
        end
    end
end


问:
ggthemes::geom_tufteboxplot - prevent whiskers from extending to extremes
Does someone know how to prevent the "whiskers" in ggthemes::geom_tufteboxplot to be drawn up to the extreme values?
I tried changing the outlier and whisker arguments to no avail.

library(ggplot2)
library(ggthemes)

ggplot(iris, aes(Species, Sepal.Length)) +
  geom_boxplot()
```

<p>Whisker extend to 1.5xIQR as usual:
<img src="https://i.imgur.com/NKmeY5a.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>ggplot(iris, aes(Species, Sepal.Length)) +
  geom_tufteboxplot()
</code>```

"Whisker" extend to extreme value

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

答:
I was able to find a workable solution by changing the stat to "boxplot". Here's a reprex (the last example shows how to hide outliers, although the axis range will still consider them; the work-around for that is more involved):

library(ggplot2)
library(ggthemes)

ggplot(iris, aes(Species, Sepal.Length)) +
  geom_boxplot()
```

<p><img src="https://i.imgur.com/D19SQcZ.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>ggplot(iris, aes(Species, Sepal.Length)) +
  ggthemes::geom_tufteboxplot(stat = "boxplot")
</code>```

ggplot(iris, aes(Species, Sepal.Length)) +
  ggthemes::geom_tufteboxplot(stat = "boxplot", outlier.shape = NA)
```

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

Body:
Does someone know how to prevent the "whiskers" in ggthemes::geom_tufteboxplot to be drawn up to the extreme values?
I tried changing the outlier and whisker arguments to no avail.

library(ggplot2)
library(ggthemes)

ggplot(iris, aes(Species, Sepal.Length)) +
  geom_boxplot()

Whisker extend to 1.5xIQR as usual:

ggplot(iris, aes(Species, Sepal.Length)) +
  geom_tufteboxplot()

"Whisker" extend to extreme value

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

Body:
I was able to find a workable solution by changing the stat to "boxplot". Here's a reprex (the last example shows how to hide outliers, although the axis range will still consider them; the work-around for that is more involved):

library(ggplot2)
library(ggthemes)

ggplot(iris, aes(Species, Sepal.Length)) +
  geom_boxplot()

ggplot(iris, aes(Species, Sepal.Length)) +
  ggthemes::geom_tufteboxplot(stat = "boxplot")

ggplot(iris, aes(Species, Sepal.Length)) +
  ggthemes::geom_tufteboxplot(stat = "boxplot", outlier.shape = NA)

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


问:
Is there a way to Open an App just by its Name in Python
I'm making an "Advanced Virtual Assistant" by using Python and I want to be able to run any app on the PC with just entering its name. Something likes:

```<code>i = input("What App Do You Want To Open?:  ")
d = getDirectory(i)
os.startfile(d)
</code>```

Now I can set this up manually for some apps by getting their directory but it won't be for every app so its not what I need. Is there any easy way to do this?

答:
There are many good tools to do this already.

Here is an common solution you may try implement it:

Scan or record apps on your PC and store records in database or formated file. (e.g. registry / program files / other folders )

Map app name, description, caption or etc to the app executable path.(read executable information with wmi or other way as the other answers described.)

Try find the entered text in the fields.

(if you want nature language matching, that's another story.)

Use Python subprocess or other function/lib to run the executable of the record you just found.

Body:
I'm making an "Advanced Virtual Assistant" by using Python and I want to be able to run any app on the PC with just entering its name. Something likes:

i = input("What App Do You Want To Open?:  ")
d = getDirectory(i)
os.startfile(d)

Now I can set this up manually for some apps by getting their directory but it won't be for every app so its not what I need. Is there any easy way to do this?


问:
Python barcode library
I am looking for the python barcode library.
I am using ubuntu 12.04 and installed a pyBarcode libarary to generate barcode. but it is not supporting.it give me error like,

```<code>>>> import barcode
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named barcode
</code>```

Any guess?

答:
Check running python -c "import sys; print(sys.path)" and then running adding python -c "import sys; print(sys.path)" into the python file you're running.

Does the output of both differ? If so, then the PYTHONPATH (or maybe even python itself) in however you're running Python is different from the one pip used.

Title: Python barcode library

Body:
I am looking for the python barcode library.
I am using ubuntu 12.04 and installed a pyBarcode libarary to generate barcode. but it is not supporting.it give me error like,

>>> import barcode
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named barcode

Any guess?


问:
Extract Month from a Date and convert it to Month in words
I have obtained the date like obtaining this "2018-05-31".
Now, I want to create a new columnn which would be the month extracted, 05, and converting it to words "May". How could I do it?

```<code>df$Fecha<-as.Date(df$Fecha)
df$Fecha
[1] "2020-02-01" "2020-01-01" "2020-02-01" "2020-02-01"

df$Mes <- df$Fecha(Month = format(as.Date(df$Fecha), '%b'))
df$Mes
</code>```

I get an error

答:
We can use format after converting to Date class.

```<code>df1 <- data.frame(Month = format(as.Date(str1), '%b'))
df1
#  Month
#1   May
</code>```

If it is to create a new column in an already existing dataset

```<code>df$Mes <- format(as.Date(df$Fecha), '%b')
</code>```

If we need the full name, change the %b to %B

data

```<code>str1 <- "2018-05-31"
</code>```

Body:
I have obtained the date like obtaining this "2018-05-31".
Now, I want to create a new columnn which would be the month extracted, 05, and converting it to words "May". How could I do it?

df$Fecha<-as.Date(df$Fecha)
df$Fecha
[1] "2020-02-01" "2020-01-01" "2020-02-01" "2020-02-01"

df$Mes <- df$Fecha(Month = format(as.Date(df$Fecha), '%b'))
df$Mes

I get an error

Body:
We can use format after converting to Date class.

df1 <- data.frame(Month = format(as.Date(str1), '%b'))
df1
#  Month
#1   May

If it is to create a new column in an already existing dataset

df$Mes <- format(as.Date(df$Fecha), '%b')

If we need the full name, change the %b to %B

data

str1 <- "2018-05-31"


问:
How to unarchive data with unarchivedObjectOfClass:fromData:error:?
I am using unarchiveObjectWithData to unarchive data from NSUserDefaults and it is working good, but it was deprecated in iOS 12.0.
Xcode suggests to use unarchivedObjectOfClass:fromData:error:, but this method does not work.

I have an array of objects of my class to unarchive.

I have tried to use unarchivedObjectOfClass:fromData:error:, also unarchivedObjectOfClasses:fromData:error: with all classes (NSArray, NSString, MYCLASS..)

Works

```<code>NSArray *stored = [NSKeyedUnarchiver unarchiveObjectWithData:data];
</code>```

Does not:

```<code>NSArray *stored = [NSKeyedUnarchiver unarchivedObjectOfClass:[MYCLASS class] fromData:data error:&error];
</code>```

I am receiving ”The data couldn’t be read because it isn’t in the correct format.„

答:
I faced up with an issue and follow the @Darren answer, but unarchivedObjectOfClass returns nil ! :(

so i tried a lot of variation and found the only success way is my case:

supportsSecureCoding property must be YES

and

```<code>NSArray<MyClassConformedToNSObject_NSCoding_NSSecureCoding *> *arrayOfCustomObjects = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSObject class] fromData:data error:&error];
</code>```

Body:
I am using unarchiveObjectWithData to unarchive data from NSUserDefaults and it is working good, but it was deprecated in iOS 12.0.
Xcode suggests to use unarchivedObjectOfClass:fromData:error:, but this method does not work.

I have an array of objects of my class to unarchive.

I have tried to use unarchivedObjectOfClass:fromData:error:, also unarchivedObjectOfClasses:fromData:error: with all classes (NSArray, NSString, MYCLASS..)

Works

NSArray *stored = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Does not:

NSArray *stored = [NSKeyedUnarchiver unarchivedObjectOfClass:[MYCLASS class] fromData:data error:&error];

I am receiving ”The data couldn’t be read because it isn’t in the correct format.„

Body:
I faced up with an issue and follow the @Darren answer, but unarchivedObjectOfClass returns nil ! :(

so i tried a lot of variation and found the only success way is my case:

supportsSecureCoding property must be YES

and

NSArray<MyClassConformedToNSObject_NSCoding_NSSecureCoding *> *arrayOfCustomObjects = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSObject class] fromData:data error:&error];


问:
How to remove the default CRA react favicon?
I already remove the link in the head tag and still the favicon gets rendered, is there anyway this can be remove or change?</p>

答:
Go to directory of your project → public → open manifest.json:

```<code>  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    }
</code>```

Body:
Go to directory of your project → public → open manifest.json:

  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    }


问:
Linq FirstOrDefault(<condition>).Attribute vs Where(<condition>).Select(a => Attribute).FirstOrDefault()
I've been cleaning up some old code and came accross a few queries of the following structure:

var attribute = DbSet.Where(<condition>).Select(a => a.Attribute).SingleOrDefault();
```

<p>and as I'm trying to make the code more readable I would change that to:</p>

<pre class="lang-cs prettyprint-override"><code>var attribute = DbSet.SingleOrDefault(<condition>).Attribute;
</code>```

therefore shortening the statement.

But now I'm wondering which of the two is better for performance, and which is better for memory management.

答:
It depends. DbSet.SingleOrDefault(<condition>).Attribute will fetch whole row from database and pass it over the network to you application. So if your table has many columns and/or columns containing a lot of data (big stings, some binary data) then first one should be faster cause it will fetch only data which is actually needed.

Also note that SingleOrDefault can return null, so without null check you can get NullReferenceException.

Body:
I've been cleaning up some old code and came accross a few queries of the following structure:

var attribute = DbSet.Where(<condition>).Select(a => a.Attribute).SingleOrDefault();

and as I'm trying to make the code more readable I would change that to:

var attribute = DbSet.SingleOrDefault(<condition>).Attribute;

therefore shortening the statement.

But now I'm wondering which of the two is better for performance, and which is better for memory management.


问:
Convert XML data to Pandas
I want to extract data from an XML and convert it to Pandas Data Frame

First off i tried importing with Element Tree xml and just print out some of the columns with this code, no luck

So for now i've managed to extract some of the data with this code

import xml.etree.cElementTree as et
import pandas as pd
def getvalueofnode(node):
    """ return node text or None """
    return node.text if node is not None else None
def main():
    """ main """
    parsed_xml = et.parse("RTS_XTV100006361.xml")
    dfcols = ['start', 'stop', 'channel', 'type', 'title', 'category']
    df_xml = pd.DataFrame(columns=dfcols)
    for node in parsed_xml.getroot():
        start = node.attrib.get('start')
        stop = node.attrib.get('stop')
        channel = node.attrib.get('channel')
        type = node.attrib.get('type')
        title = node.find('title')
        category = node.find('category')
        df_xml = df_xml.append(
            pd.Series([start, stop, channel, type, getvalueofnode(category), getvalueofnode(title)], index=dfcols),
            ignore_index=True)
    print (df_xml)'
```

<p><strong>But title  and category are still empty</strong></p>

<p>This is example of XML:</p>

```    <?xml version="1.0" encoding="utf-8"?>
<tv xmlns="http://www.xmltv.org/xmltv" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <programme ID="58135" start="20200528000000 +0200" stop="20200528013000 +0200" channel="XTV100006361" recordable="Y" npvrenable="Y" cpvrenable="N" type="program" deleted="false">
    <blackoutInfo>
      <isBlackout>1</isBlackout>
      <groupIDs>2</groupIDs>
      <streams>00000001</streams>
    </blackoutInfo>
    <title lang="sr"><![CDATA[Yoga retreat]]></title>
    <category lang="sr"><![CDATA[Entertainment]]></category>
    <icon src="default_playbill.png" ptype="3" />
    <episode-num system="xmltv_ns">0.0.0</episode-num>
  </programme>
  <programme ID="58136" start="20200528013000 +0200" stop="20200528030000 +0200" channel="XTV100006361" recordable="Y" npvrenable="Y" cpvrenable="N" type="program" deleted="false">
    <blackoutInfo>
      <isBlackout>1</isBlackout>
      <groupIDs>2</groupIDs>
      <streams>00000001</streams>
    </blackoutInfo>
    <title lang="sr"><![CDATA[Doctor Who]]></title>
    <category lang="sr"><![CDATA[Entertainment]]></category>
    <icon src="default_playbill.png" ptype="3" />
    <episode-num system="xmltv_ns">0.0.0</episode-num>
  </programme>
</tv>
```

desired output that i would like is that i get this columns:

channel, start, stop, title, category

答:
As indicated by @mzjn, there is a default namespace for the XML; you'll have to use it in your computation</p>
```<code>import xml.etree.ElementTree as ET

def main():
    root = ET.parse("RTS_XTV100006361.xml")
    #declare namespace
    ns = '{http://www.xmltv.org/xmltv}'

    #required keys
    keys = ['channel','start','stop','type']
    box = []
    for ent in root.findall(f".//{ns}programme"):
        d = {key:value for key,value in ent.attrib.items() if key in keys}
        #attach title and category to dictionary
        d.update({"title" : ent.find(f".//{ns}title").text,
                  "category" : ent.find(f".//{ns}category").text
                 })
        box.append(d)

    return pd.DataFrame(box)

main()

           start                  stop               channel         type   title            category
0   20200528000000 +0200    20200528013000 +0200    XTV100006361    program Yoga retreat    Entertainment
1   20200528013000 +0200    20200528030000 +0200    XTV100006361    program Doctor Who      Entertainment
</code>```

Title: Convert XML data to Pandas

Body:
I want to extract data from an XML and convert it to Pandas Data Frame

First off i tried importing with Element Tree xml and just print out some of the columns with this code, no luck

So for now i've managed to extract some of the data with this code

import xml.etree.cElementTree as et
import pandas as pd
def getvalueofnode(node):
    """ return node text or None """
    return node.text if node is not None else None
def main():
    """ main """
    parsed_xml = et.parse("RTS_XTV100006361.xml")
    dfcols = ['start', 'stop', 'channel', 'type', 'title', 'category']
    df_xml = pd.DataFrame(columns=dfcols)
    for node in parsed_xml.getroot():
        start = node.attrib.get('start')
        stop = node.attrib.get('stop')
        channel = node.attrib.get('channel')
        type = node.attrib.get('type')
        title = node.find('title')
        category = node.find('category')
        df_xml = df_xml.append(
            pd.Series([start, stop, channel, type, getvalueofnode(category), getvalueofnode(title)], index=dfcols),
            ignore_index=True)
    print (df_xml)'

But title  and category are still empty

This is example of XML:

    <?xml version="1.0" encoding="utf-8"?>
<tv xmlns="http://www.xmltv.org/xmltv" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <programme ID="58135" start="20200528000000 +0200" stop="20200528013000 +0200" channel="XTV100006361" recordable="Y" npvrenable="Y" cpvrenable="N" type="program" deleted="false">
    <blackoutInfo>
      <isBlackout>1</isBlackout>
      <groupIDs>2</groupIDs>
      <streams>00000001</streams>
    </blackoutInfo>
    <title lang="sr"><![CDATA[Yoga retreat]]></title>
    <category lang="sr"><![CDATA[Entertainment]]></category>
    <icon src="default_playbill.png" ptype="3" />
    <episode-num system="xmltv_ns">0.0.0</episode-num>
  </programme>
  <programme ID="58136" start="20200528013000 +0200" stop="20200528030000 +0200" channel="XTV100006361" recordable="Y" npvrenable="Y" cpvrenable="N" type="program" deleted="false">
    <blackoutInfo>
      <isBlackout>1</isBlackout>
      <groupIDs>2</groupIDs>
      <streams>00000001</streams>
    </blackoutInfo>
    <title lang="sr"><![CDATA[Doctor Who]]></title>
    <category lang="sr"><![CDATA[Entertainment]]></category>
    <icon src="default_playbill.png" ptype="3" />
    <episode-num system="xmltv_ns">0.0.0</episode-num>
  </programme>
</tv>

desired output that i would like is that i get this columns:

channel, start, stop, title, category

Body:
As indicated by @mzjn, there is a default namespace for the XML; you'll have to use it in your computation

import xml.etree.ElementTree as ET

def main():
    root = ET.parse("RTS_XTV100006361.xml")
    #declare namespace
    ns = '{http://www.xmltv.org/xmltv}'

    #required keys
    keys = ['channel','start','stop','type']
    box = []
    for ent in root.findall(f".//{ns}programme"):
        d = {key:value for key,value in ent.attrib.items() if key in keys}
        #attach title and category to dictionary
        d.update({"title" : ent.find(f".//{ns}title").text,
                  "category" : ent.find(f".//{ns}category").text
                 })
        box.append(d)

    return pd.DataFrame(box)

main()

           start                  stop               channel         type   title            category
0   20200528000000 +0200    20200528013000 +0200    XTV100006361    program Yoga retreat    Entertainment
1   20200528013000 +0200    20200528030000 +0200    XTV100006361    program Doctor Who      Entertainment


问:
When I try to run this code it's gives me no output
I built it when I click to run it's showing no errors no warnings nothing

```<code>#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char name[20], address[30];
    char c;
    printf("put your pass key: ");
    c = getchar();

    printf("Enter your name: ");
    scanf("%s",name);

    printf("Enter your address: ");
    scanf("%s",address);

    printf("--------------------------\n");
    printf("Entered Name: %s\n",name);
    printf("Entered Address: %s\n",address);

    printf("Your pass key: ");
    putchar(c);
}
</code>```

I tried to run it from pass key point and it works but when I continue it's given me nothing

答: I have compiled you code and it works fine for me. Everything is fine. Maybe the input values provided by you is not in correct format.</p>

Body:
I built it when I click to run it's showing no errors no warnings nothing

#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char name[20], address[30];
    char c;
    printf("put your pass key: ");
    c = getchar();

    printf("Enter your name: ");
    scanf("%s",name);

    printf("Enter your address: ");
    scanf("%s",address);

    printf("--------------------------\n");
    printf("Entered Name: %s\n",name);
    printf("Entered Address: %s\n",address);

    printf("Your pass key: ");
    putchar(c);
}

I tried to run it from pass key point and it works but when I continue it's given me nothing


问:
How to set date range selection in react JS DateRangePicker?
I am using 'DateRangePicker' component in my react JS application.
I am trying to restrict start date to last 6 month only and difference between
start and end date should not be more than 1 month.
I wrote following code

```<code>isOutsideRange = (day) => {
  if (day > moment()) return true;
  else if (this.state.startDate) {
    if (day > moment(this.state.endDate)) return true;
    if (day < moment().subtract(6, 'months')) return true;
    else return false;
  } else if (this.state.endDate) {
    if (day > moment(this.state.endDate)) return true;
    if ((moment(this.state.endDate) > (moment(this.state.startDate).subtract(1, 'month')))) return true;
    else return false;
  }
}
</code>```

and here is the UI code

```<code><DateRangePicker
  startDate={this.state.startDate}
  startDateId="validFromDate"
  endDate={this.state.endDate}
  endDateId="validToDate"
  onDatesChange={({ startDate, endDate }) =>
    this.handleValidDatesChange(startDate, endDate)
  }
  focusedInput={this.state.ofrFocusedInput}
  onFocusChange={(ofrFocusedInput) => this.setState({ ofrFocusedInput })}
  isOutsideRange={(e) => this.isOutsideRange(e)}
  showDefaultInputIcon={true}
  small={true}
  minimumNights={0}
  hideKeyboardShortcutsPanel={true}
  showClearDates={true}
  min={this.maxDate}
  shouldDisableDate={({ startDate }) => this.disablePrevDates(startDate)}
  // minDate={subDays(new Date(), 10)}
  displayFormat={() => "DD/MM/YYYY"}
/>;

</code>```

I tried to debug but it is not working.
Can someone suggest the solution ?

答:
To check if a moment is between two other moments, optionally looking at unit scale (minutes, hours, days, etc), you should use:

```<code>moment().isBetween(moment-like, moment-like, String, String);
// where moment-like is Moment|String|Number|Date|Array
</code>```

For instance, if you need to check today - 6months <= someDate <= today, you would use something like:

```<code>// returns TRUE if date is outside the range
const isOutsideRange = date => {
    const now = moment();
    return !moment(date)
             .isBetween(now.subtract(6, 'months'), now, undefined, '[]');
    // [] - match is inclusive
}
</code>```

For more details, please check Is Between docs. This method is very flexible, for instance, you can have exclusive or inclusive match.

Now, the second condition. If you would like to check if endDate - startDate <= 1 month, you can play with moments as well to achieve this.

```<code>// so if you add 1 month to your startDate and then your end date
// is still before the result or the same - you can say the duration
// between them is 1 month
const lessThanMonth = (startDate, endDate) => {
    return endDate.isSameOrBefore(moment(startDate).add(1, 'months'));
}
</code>```

Body:
I am using 'DateRangePicker' component in my react JS application.
I am trying to restrict start date to last 6 month only and difference between
start and end date should not be more than 1 month.
I wrote following code

isOutsideRange = (day) => {
  if (day > moment()) return true;
  else if (this.state.startDate) {
    if (day > moment(this.state.endDate)) return true;
    if (day < moment().subtract(6, 'months')) return true;
    else return false;
  } else if (this.state.endDate) {
    if (day > moment(this.state.endDate)) return true;
    if ((moment(this.state.endDate) > (moment(this.state.startDate).subtract(1, 'month')))) return true;
    else return false;
  }
}

and here is the UI code

<DateRangePicker
  startDate={this.state.startDate}
  startDateId="validFromDate"
  endDate={this.state.endDate}
  endDateId="validToDate"
  onDatesChange={({ startDate, endDate }) =>
    this.handleValidDatesChange(startDate, endDate)
  }
  focusedInput={this.state.ofrFocusedInput}
  onFocusChange={(ofrFocusedInput) => this.setState({ ofrFocusedInput })}
  isOutsideRange={(e) => this.isOutsideRange(e)}
  showDefaultInputIcon={true}
  small={true}
  minimumNights={0}
  hideKeyboardShortcutsPanel={true}
  showClearDates={true}
  min={this.maxDate}
  shouldDisableDate={({ startDate }) => this.disablePrevDates(startDate)}
  // minDate={subDays(new Date(), 10)}
  displayFormat={() => "DD/MM/YYYY"}
/>;

I tried to debug but it is not working.
Can someone suggest the solution ?

Body:
To check if a moment is between two other moments, optionally looking at unit scale (minutes, hours, days, etc), you should use:

moment().isBetween(moment-like, moment-like, String, String);
// where moment-like is Moment|String|Number|Date|Array

For instance, if you need to check today - 6months <= someDate <= today, you would use something like:

// returns TRUE if date is outside the range
const isOutsideRange = date => {
    const now = moment();
    return !moment(date)
             .isBetween(now.subtract(6, 'months'), now, undefined, '[]');
    // [] - match is inclusive
}

For more details, please check Is Between docs. This method is very flexible, for instance, you can have exclusive or inclusive match.

Now, the second condition. If you would like to check if endDate - startDate <= 1 month, you can play with moments as well to achieve this.

// so if you add 1 month to your startDate and then your end date
// is still before the result or the same - you can say the duration
// between them is 1 month
const lessThanMonth = (startDate, endDate) => {
    return endDate.isSameOrBefore(moment(startDate).add(1, 'months'));
}


问:
(FLASK) I can't figure out why my html file doesn't update/render
I already tried clearing my browser cache and history, but that did not seem to help. The old html file I used (Jinja) doesn't seem to update.

Basically, I rendered a file before this and jinja seems to be rendering that old file (not sample or index) instead of either sample or index .html.

I'm a beginner at Flask, so if this is a simple fix I apologize I don't know much...

Here is my code:

sample.py

```<code>from flask import Flask, render_template, redirect, url_for

app = Flask(" APP ")

@app.route("/home")
def home():
    return render_template("sample.html")

if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug = True)
</code>```

index.html (inherits from sample.html)

```<code>{% extends "sample.html" %}
{% block title %}Home Page {% endblock %}
{% block content %}
<h1> Welcome to the Index Page!</h1>
{% endblock %}
</code>```

sample.html

```<code><!doctype html>
<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
       <span class="navbar-toggler-icon"></span>
   </button>
         <div class="collapse navbar-collapse" id="navbarNav">
             <ul class="navbar-nav">
           <li class="nav-item active">
                     <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
    </li>
    <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
    </li>
      </ul>
        </div>
    </nav>
    {% block content %}
    {% endblock %}
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
</code>```

答:
You have to render index.html file like this</p>

```<code>def home():
    return render_template("index.html") ```
</code>```

Body:
I already tried clearing my browser cache and history, but that did not seem to help. The old html file I used (Jinja) doesn't seem to update.

Basically, I rendered a file before this and jinja seems to be rendering that old file (not sample or index) instead of either sample or index .html.

I'm a beginner at Flask, so if this is a simple fix I apologize I don't know much...

Here is my code:

sample.py

from flask import Flask, render_template, redirect, url_for

app = Flask(" APP ")

@app.route("/home")
def home():
    return render_template("sample.html")

if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug = True)

index.html (inherits from sample.html)

{% extends "sample.html" %}
{% block title %}Home Page {% endblock %}
{% block content %}

 Welcome to the Index Page!

{% endblock %}

sample.html

<!doctype html>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>

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

   </button>

                     Home (current)

        Features

        Pricing

        Disabled

    {% block content %}
    {% endblock %}

Body:
You have to render index.html file like this

def home():
    return render_template("index.html") ```


问:
ytdl() error: The "url" argument must be of type string. Received type undefined
I'm experiencing an issue with both ytdl( ) and downloadFromInfo( ) functions.

Error:

```<code>TypeError_ [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined

at validateString (internal/validators.js:107:11)
at Url.parse (url.js:155:3)
at Object.urlParse [as parse] (url.js:150:13)
at doDownload (E:\Discord Bots\Astralis Time 2\node_modules\miniget\dist\index.js:90:28)
at processTicksAndRejections (internal/process/task_queues.js:75:11)
</code>```

In the case of ytdl( ) I checked if my input was incorrect, but it wasn't. I believe there may be a problem when ytdl-core tries to read the object from the getInfo( ) function.

With some videos it does work, but those cases are rare.

This is the code I use, I have checked all my variables, including songInfo and they all seem to be correct, the error only appears when I run ytdl( ) or downloadFromInfo( ).

```<code>async function playSong(channela, message){
var songInfo;
var songTitle;
let connection;
let dispatcher;

if(typeof servers[message.guild.id].queue[0] === 'undefined' || !servers[message.guild.id].queue[0] || typeof servers[message.guild.id].queue[0] !== 'string'){
    servers[message.guild.id].queue.shift();
    if(!servers[message.guild.id].queue[0]){
        connection.disconnect();
        message.member.voice.channel.leave();
    }
}
try{
    songInfo = await ytdl.getInfo(servers[message.guild.id].queue[0]);
    songTitle = songInfo.title;
    connection = await channela.join();
    let stream = await ytdl.downloadFromInfo(songInfo, {filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1<<25});
    dispatcher = await connection.play(stream, {highWaterMark: 1});
}catch(error){
    console.error('Could not play the video:' + error);
    message.channel.send('**Please, try again.**');
}
</code>```

Thank you for your time.

答: I had to manually update ytdl-core, for some reason, npm install ytdl-core@latest didn't update the module.

Body:
I'm experiencing an issue with both ytdl( ) and downloadFromInfo( ) functions.

Error:

TypeError_ [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined

at validateString (internal/validators.js:107:11)
at Url.parse (url.js:155:3)
at Object.urlParse [as parse] (url.js:150:13)
at doDownload (E:\Discord Bots\Astralis Time 2\node_modules\miniget\dist\index.js:90:28)
at processTicksAndRejections (internal/process/task_queues.js:75:11)

In the case of ytdl( ) I checked if my input was incorrect, but it wasn't. I believe there may be a problem when ytdl-core tries to read the object from the getInfo( ) function.

With some videos it does work, but those cases are rare.

This is the code I use, I have checked all my variables, including songInfo and they all seem to be correct, the error only appears when I run ytdl( ) or downloadFromInfo( ).

async function playSong(channela, message){
var songInfo;
var songTitle;
let connection;
let dispatcher;

if(typeof servers[message.guild.id].queue[0] === 'undefined' || !servers[message.guild.id].queue[0] || typeof servers[message.guild.id].queue[0] !== 'string'){
    servers[message.guild.id].queue.shift();
    if(!servers[message.guild.id].queue[0]){
        connection.disconnect();
        message.member.voice.channel.leave();
    }
}
try{
    songInfo = await ytdl.getInfo(servers[message.guild.id].queue[0]);
    songTitle = songInfo.title;
    connection = await channela.join();
    let stream = await ytdl.downloadFromInfo(songInfo, {filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1<<25});
    dispatcher = await connection.play(stream, {highWaterMark: 1});
}catch(error){
    console.error('Could not play the video:' + error);
    message.channel.send('**Please, try again.**');
}

Thank you for your time.