问:
How do I create 3 columns with responsive text and images?
HTML/CSS beginner here... I have an image with text directly below it. I need to put 3 images with text below next to each other (see example below). I would like there to be equal amounts of space both around and between each column. Image 1 needs to be vertically aligned with Text1, Image2 with Text2 and Image3 with Text3.

```<code>Image1 Image2 Image3

Text1  Text2 Text3
</code>```

I also need the 3 columns to drop below one another when displayed on a smaller screen.

```<code>Image1

Text1

Image2

Text2

Image3

Text3
</code>```

I have been using Flexbox but have only managed to display it on a full sized screen. When I make the screen smaller for mobile use the images overlap and no longer line up with the text below. The 3 sections of text keep their position but the images don't seem to want to cooperate. Also, the images and text don't drop down onto the next line. I know...I am probably doing something very wrong here!

I think I can work out where I have been going wrong if someone can provide both the HTML and CSS code for this. If you can add an explanation for your code that would be beyond helpful... but any measure of help is appreciated.

答:
First create a div (here container) where 3 column will be displayed.
style the container display flex with flex direction row and flex-wrap = wrap.
Wrap is important because when screen will be small then it will display one by one like mobile view.Otherwise it overlap on with other and try to display 3 column together.

2nd you create three div here box each contain image heading and and p tag.
set the style of box flex and direction to column as it appears one under another.
justify and align all the items center

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

hello box1

Lorem ipsum dolor sit amet consectetur adipisicing elit. Similique molestias hic velit, ipsum facere nemo minus distinctio est quidem neque.

box2

Lorem ipsum dolor sit amet consectetur adipisicing elit. Similique molestias hic velit, ipsum facere nemo minus distinctio est quidem neque.

box3

Lorem ipsum dolor sit amet consectetur adipisicing elit. Similique molestias hic velit, ipsum facere nemo minus distinctio est quidem neque.

```

Body:
HTML/CSS beginner here... I have an image with text directly below it. I need to put 3 images with text below next to each other (see example below). I would like there to be equal amounts of space both around and between each column. Image 1 needs to be vertically aligned with Text1, Image2 with Text2 and Image3 with Text3.

Image1 Image2 Image3

Text1  Text2 Text3

I also need the 3 columns to drop below one another when displayed on a smaller screen.

Image1

Text1

Image2

Text2

Image3

Text3

I have been using Flexbox but have only managed to display it on a full sized screen. When I make the screen smaller for mobile use the images overlap and no longer line up with the text below. The 3 sections of text keep their position but the images don't seem to want to cooperate. Also, the images and text don't drop down onto the next line. I know...I am probably doing something very wrong here!

I think I can work out where I have been going wrong if someone can provide both the HTML and CSS code for this. If you can add an explanation for your code that would be beyond helpful... but any measure of help is appreciated.

Body:
First create a div (here container) where 3 column will be displayed.
style the container display flex with flex direction row and flex-wrap = wrap.
Wrap is important because when screen will be small then it will display one by one like mobile view.Otherwise it overlap on with other and try to display 3 column together.

2nd you create three div here box each contain image heading and and p tag.
set the style of box flex and direction to column as it appears one under another.
justify and align all the items center

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
.container{
    display:flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;

}
img{
    width:100%;
    height:auto;
}
.box{
    display:flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    max-width:25rem;
    min-width:18rem;
    margin: 10px;
    text-align: center;

}

    </style>
</head>
<body>
    <div class="container">
        <div class="box">
            <img src="https://images.pexels.com/photos/36753/flower-purple-lical-blosso.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940">
            <h1>hello box1</h1>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Similique molestias hic velit, ipsum facere nemo minus distinctio est quidem neque.</p>
        </div>
        <div class="box">
            <img src="https://images.pexels.com/photos/36753/flower-purple-lical-blosso.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940">
            <h1>box2</h1>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Similique molestias hic velit, ipsum facere nemo minus distinctio est quidem neque.</p>
        </div>
        <div class="box">
            <img src="https://images.pexels.com/photos/36753/flower-purple-lical-blosso.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940">
            <h1>box3</h1>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Similique molestias hic velit, ipsum facere nemo minus distinctio est quidem neque.</p>
        </div>
      </div>
</body>
</html>


来源: stackexchange

问:
How to query Wikidata items using its labels?
How can I query Wikidata to get all items that have labels contain a word?
I tried this but didn't work; it retrieved nothing.</p>

```<code>SELECT ?item ?itemLabel WHERE {
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en".
    ?item rdfs:label ?itemLabel.
  }
FILTER(CONTAINS(LCASE(?itemLabel), "keyword"))
}
LIMIT 1000
</code>```

答:
As of today (June 2020), the best way to do this seems to be using these CirrusSearch extensions. The following does a substring search in all English labels and comes back with 10,000 results in <20 seconds. I believe it also searches in aliases and descriptions.

```<code>SELECT DISTINCT ?item ?label
WHERE
{
  SERVICE wikibase:mwapi
  {
    bd:serviceParam wikibase:endpoint "www.wikidata.org";
                    wikibase:api "Generator";
                    mwapi:generator "search";
                    mwapi:gsrsearch "inlabel:city"@en;
                    mwapi:gsrlimit "max".
    ?item wikibase:apiOutputItem mwapi:title.
  }
  ?item rdfs:label ?label. FILTER( LANG(?label)="en" )

  # … at this point, you have matching ?item(s)
  # and can further restrict or use them
  # as in any other SPARQL query

  # Example: the following restricts the matches
  # to college towns (Q1187811) only

  ?item wdt:P31 wd:Q1187811 .
}
</code>```

Link to this query

ContentLicense: CC BY-SA 3.0

Body:
How can I query Wikidata to get all items that have labels contain a word?
I tried this but didn't work; it retrieved nothing.

SELECT ?item ?itemLabel WHERE {
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en".
    ?item rdfs:label ?itemLabel.
  }
FILTER(CONTAINS(LCASE(?itemLabel), "keyword"))
}
LIMIT 1000

Body:
As of today (June 2020), the best way to do this seems to be using these CirrusSearch extensions. The following does a substring search in all English labels and comes back with 10,000 results in <20 seconds. I believe it also searches in aliases and descriptions.

SELECT DISTINCT ?item ?label
WHERE
{
  SERVICE wikibase:mwapi
  {
    bd:serviceParam wikibase:endpoint "www.wikidata.org";
                    wikibase:api "Generator";
                    mwapi:generator "search";
                    mwapi:gsrsearch "inlabel:city"@en;
                    mwapi:gsrlimit "max".
    ?item wikibase:apiOutputItem mwapi:title.
  }
  ?item rdfs:label ?label. FILTER( LANG(?label)="en" )

  # … at this point, you have matching ?item(s)
  # and can further restrict or use them
  # as in any other SPARQL query

  # Example: the following restricts the matches
  # to college towns (Q1187811) only

  ?item wdt:P31 wd:Q1187811 .
}

<a href="https://query.wikidata.org/#SELECT%20DISTINCT%20%3Fitem%20%3Flabel%20%3Fisa%0AWHERE%0A%7B%0A%20%20SERVICE%20wikibase%3Amwapi%0A%20%20%7B%0A%20%20%20%20bd%3AserviceParam%20wikibase%3Aendpoint%20%22www.wikidata.org%22%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20wikibase%3Aapi%20%22Generator%22%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20mwapi%3Agenerator%20%22search%22%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20mwapi%3Agsrsearch%20%22inlabel%3Acity%22%40en%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20mwapi%3Agsrlimit%20%22max%22.%0A%20%20%20%20%3Fitem%20wikibase%3AapiOutputItem%20mwapi%3Atitle.%0A%20%20%7D%0A%20%20%3Fitem%20rdfs%3Alabel%20%3Flabel.%20FILTER%28%20LANG%28%3Flabel%29%3D%22en%22%20%29%0A%20%20%3Fitem%20wdt%3AP31%20wd%3AQ1187811%20.%0A%0A%7D%20limit%20100" rel="nofollow noreferrer">Link to this query

ContentLicense: CC BY-SA 4.0


问:
create view for each category - laravel
I currently print all categories in one view, with them I mark a difference between its subcategories

@foreach($tipos as $tipo)

{{$tipo->tipo }}

    @foreach($tipo->categories as $category)

      $category->slug]) }}">
        @if(!empty($category->image))
        image)}}" alt="">
        @else

        @endif

          $category->slug]) }}">{{$category->name}}

{{$category->descripcion}}

  @endforeach
  @endforeach```
</div>
</div>
</p>

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

<p>I get the names from:</p>

<p><img src="https://i.stack.imgur.com/N66mM.png" alt="enter image description here"></p>

<p>categories table:
<img src="https://i.stack.imgur.com/2QFY1.png" alt="enter image description here">
<strong>Now I need to create a view for each of them, enter it using url</strong>, </p>

<p>controller:</p>

```public function list($id){

   $tipos = App\Tipo::findOrFail($id);
   return view('list.tipos', compact('tipos'));
}
```

<p>route: </p>

```Route::get('/list{id}','HomeController@list')->name('list.categories');
```

pivot table:

How can I print the content of each category? help pls

答:
Modify your controller like this

Note: Change the Model Names (App\Pivote) and  (App\Category) to what you have set in your code.

```<code>public function list($id){

   $tipos = App\Tipo::findOrFail($id);
   $pivot_data = App\Pivote::select('category_id')->where('tipo_id',$id)->get()->toArray();
   $categories = App\Category::whereIn('id',$pivot_data)->get()->toArray();
   return view('list.tipos', compact('tipos','categories'));
}
</code>```

And modify your view something like this

```<code><div class="card">
    <h4 style="margin-top: 5px;">{{$tipos->tipo }}</h4>
</div>
@foreach($categories as $key => $category)
    <div style="margin-top: 20px;" class="col-lg-4 col-sm-6 mb-4">
        <div class="card h-100">
            <a href="{{ route('category-detail',['slug'=>$category['slug']]) }}">
            @if(!empty($category['image']))
                <img class="card-img-top" src="{{asset($category['image'])}}" alt="">
            @else
                <img class="card-img-top" src="http://placehold.it/700x400" alt="">
            @endif
            </a>
        <div class="card-body">
            <h4 class="card-title">
                <a href="{{ route('category-detail',['slug'=>$category['slug']]) }}">{{$category['name']}}</a>
            </h4>
            <p class="card-text">{{$category['descripcion']}}</p>
        </div>
    </div>
@endforeach
</code>```

Title: create view for each category - laravel

Body:
I currently print all categories in one view, with them I mark a difference between its subcategories

@foreach($tipos as $tipo)

{{$tipo->tipo }}

    @foreach($tipo->categories as $category)

      $category->slug]) }}">
        @if(!empty($category->image))
        image)}}" alt="">
        @else

        @endif

          $category->slug]) }}">{{$category->name}}

{{$category->descripcion}}

  @endforeach
  @endforeach

I get the names from:

categories table:

Now I need to create a view for each of them, enter it using url,

controller:

public function list($id){

   $tipos = App\Tipo::findOrFail($id);
   return view('list.tipos', compact('tipos'));
}

route:

Route::get('/list{id}','HomeController@list')->name('list.categories');

pivot table:

How can I print the content of each category? help pls

Body:
Modify your controller like this

Note: Change the Model Names (App\Pivote) and  (App\Category) to what you have set in your code.

public function list($id){

   $tipos = App\Tipo::findOrFail($id);
   $pivot_data = App\Pivote::select('category_id')->where('tipo_id',$id)->get()->toArray();
   $categories = App\Category::whereIn('id',$pivot_data)->get()->toArray();
   return view('list.tipos', compact('tipos','categories'));
}

And modify your view something like this

<div class="card">
    <h4 style="margin-top: 5px;">{{$tipos->tipo }}</h4>
</div>
@foreach($categories as $key => $category)
    <div style="margin-top: 20px;" class="col-lg-4 col-sm-6 mb-4">
        <div class="card h-100">
            <a href="{{ route('category-detail',['slug'=>$category['slug']]) }}">
            @if(!empty($category['image']))
                <img class="card-img-top" src="{{asset($category['image'])}}" alt="">
            @else
                <img class="card-img-top" src="http://placehold.it/700x400" alt="">
            @endif
            </a>
        <div class="card-body">
            <h4 class="card-title">
                <a href="{{ route('category-detail',['slug'=>$category['slug']]) }}">{{$category['name']}}</a>
            </h4>
            <p class="card-text">{{$category['descripcion']}}</p>
        </div>
    </div>
@endforeach


问:
How to match rows in excel and append columns for adding data
I have sheets of monthly data for all our products:

Sheet 1 - January:

```<code>Product Name  Total Items  Total Orders
Product1      3            5
Product2      5            5
Product3      2            1
</code>```

Sheet 2 - February:

```<code>Product Name  Total Items  Total Orders
Product1      1            1
Product2      2            1
Product4      4            4
Product5      3            2
</code>```

How do I combine these into one sheet so that I can have an output like:

```<code>Product Name  Jan Items  Jan Orders Feb Items Feb Orders
Product1      3          5           1          1
Product2      5          5           2          1
Product3      2          1
Product4                             4          4
Product5                             3          2
</code>```

I feel like this is standard excel work, so I'm sorry for the newbie ask here.  I have about 2000 records to go through on this, so I really don't want to do this manually.

Thank you

答:
You can combine the worksheets and create a Pivot table to you desired layout.</p>

```<code>Sub CombineWS()
    Dim sht As Worksheet
    Dim rng As Range

    Set ws = ActiveWorkbook.Worksheets.Add(before:=ActiveWorkbook.Worksheets(1))
    curRow = 2
    ws.Cells(1, 1) = "Month"
    ws.Cells(1, 2) = "Product Name"
    ws.Cells(1, 3) = "Total Items"
    ws.Cells(1, 4) = "Total Orders"
    With ws
        For Each sht In ActiveWorkbook.Worksheets
            If sht.Name <> ws.Name Then
                Set rng = sht.Cells(2, 1).Resize(sht.Cells(Rows.Count, 1).End(xlUp).Row - 1, 3)

                rng.Copy
                ws.Cells(curRow, 2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
                ws.Cells(curRow, 2).PasteSpecial Paste:=xlFormats

                ws.Cells(curRow, 1).Resize(rng.Rows.Count) = sht.Name

                curRow = curRow + rng.Rows.Count
            End If
        Next sht
    End With
End Sub
</code>```

Body:
I have sheets of monthly data for all our products:

Sheet 1 - January:

Product Name  Total Items  Total Orders
Product1      3            5
Product2      5            5
Product3      2            1

Sheet 2 - February:

Product Name  Total Items  Total Orders
Product1      1            1
Product2      2            1
Product4      4            4
Product5      3            2

How do I combine these into one sheet so that I can have an output like:

Product Name  Jan Items  Jan Orders Feb Items Feb Orders
Product1      3          5           1          1
Product2      5          5           2          1
Product3      2          1
Product4                             4          4
Product5                             3          2

I feel like this is standard excel work, so I'm sorry for the newbie ask here.  I have about 2000 records to go through on this, so I really don't want to do this manually.

Thank you

Body:
You can combine the worksheets and create a Pivot table to you desired layout.

Sub CombineWS()
    Dim sht As Worksheet
    Dim rng As Range

    Set ws = ActiveWorkbook.Worksheets.Add(before:=ActiveWorkbook.Worksheets(1))
    curRow = 2
    ws.Cells(1, 1) = "Month"
    ws.Cells(1, 2) = "Product Name"
    ws.Cells(1, 3) = "Total Items"
    ws.Cells(1, 4) = "Total Orders"
    With ws
        For Each sht In ActiveWorkbook.Worksheets
            If sht.Name <> ws.Name Then
                Set rng = sht.Cells(2, 1).Resize(sht.Cells(Rows.Count, 1).End(xlUp).Row - 1, 3)

                rng.Copy
                ws.Cells(curRow, 2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
                ws.Cells(curRow, 2).PasteSpecial Paste:=xlFormats

                ws.Cells(curRow, 1).Resize(rng.Rows.Count) = sht.Name

                curRow = curRow + rng.Rows.Count
            End If
        Next sht
    End With
End Sub


问:
Beginner Reading Python Programming Text: A Simple Game Keeps Returning AttributeError
Very sorry in advance for the long paste.

The code is straight from the text. It may be due to class Scene, that seems to have the instruction to: subclass it and implement enter(). But I don't know what that means.

from sys import exit
from random import randint
from textwrap import dedent

class Scene(object):

    def enter(self):
        print("This scene is not yet configured.")
        print("Subclass it and implement enter()")
        exit(1)
# Skeleton code: a base class for Scene that will have
# the common things that all scenes do.

class Engine(object):

    def __init__(self, scene_map):
        self.scene_map = scene_map

    def play(self):
        current_scene = self.scene_map.opening_scene()
        last_scene = self.scene_map.next_scene('finished')

        while current_scene != last_scene:
            next_scene_name = current_scene.enter()
            current_scene = self.scene_map.next_scene(next_scene_name)

        # be sure to print out the last scene
        current_scene.enter()

class Death(Scene):

    quips = [
        "You died.  You kinda suck at this.",
        "Your Mom would be proud...if she were smarter.",
        "Such a luser.",
        "I have a small puppy that's better at this.",
        "You're worse than your Dad's jokes."

    ]

    def enter(self):
        print(Death.quips[randint(0, len(self.quips)-1)])

class CentralCorridor(Scene):

    def enter(self):
        print(dedent("""
            The Gothons of Planet Percal #25 have invaded your ship and
            destroyed your entire crew.  You are the last surviving member
            member and your last mission is to get the neutron destruct
            bomb from the Weapons Armory, put it in the bridge, and
            blow the ship up after getting into an escape pod.

            You're running down the central corridor to the Weapons
            Armory when a Gothon jumps out, red scaly skin, dark grimy
            teeth, and evil clown costume flowing around his hate
            filled body.  He's blocking the door to the Armory and
            about to pull a weapon to blast you.
            """))

        action = input("> ")

        if action == "shoot!":
            print(dedent("""
                Quick on the draw you yank out your blaster and fire
                it at the Gothon.  His clown costume is flowing and
                moving around his body, which throws off your aim.
                Your laster hits his costume but misses him entirely.
                This completely ruins his brand new costume his mother
                bought him, which makes him fly into an insane rage
                and blast you repeatedly in the face until you are
                dead.  Then he eats you.
                """))
            return 'death'

        elif action == "dodge!":
            print(dedent("""
                Like a world class boxer you dodge, weave, slip and
                slide right as the Gothon's blaster cranks a laser
                past your head. In the middle of your artful dodge
                your foot slips and you bang your head on the metal
                wall and pass out.  You wake up shortly after only to
                die as the Gothon stomps on your head and eats you.
                """))
            return 'death'

        elif action == "tell a joke":
            print(dedent("""
                Lucky for you they made you learn Gothon insults in
                the academy.  You tell the one Gothon joke you know:
                Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr,
                fur fvgf nebhaq gur ubhfr.  The Gothon stops, tries
                not to laugh, then busts out laughing and can't move.
                While he's laughing you run up and shoot him square in
                the head putting him down, then jump through the
                Weapon Armory door.
                """))
            return 'laster_weapon_armory'

        else:
            print("DOES NOT COMPUTE!")
            return 'central_corridor'

class LaserWeaponArmory(Scene):

    def enter(self):
        print(dedent("""
            You do a dive roll into the Weapon Armory, crouch and scan
            the room for more GOthon that might be hiding. It's dead
            quiet, too quiet.  You stand up and run to the far side of
            the room and find the neutron bomb in its container.
            There's a keypad lock on the box and you need the code to
            get the bomb out. If you get the code wrong 10 times then
            the lock closes forever and you can't get the bomb.  The
            code is 3 digits.
            """))

        code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
        guess = input("[keypad]> ")
        guesses = 0

        while guess != code and guesses <10:
            print("BZZZZEDDD!")
            guesses += 1
            guess = input("[keypad]> ")

        if guess == code:
            print(dedent("""
                The container clicks open and the seal breaks, letting
                gas out.  You grab the neutron bomb and run as fast as
                you can to the bridge where you must place it in the
                right spot.
                """))
            return 'the_bridge'
        else:
            print(dedent("""
                The lock buzzes one last time and then you hear a
                sickening melting sound as the mechanism is fused
                together.  You decide to sit there, and finally the
                Gothons blow up the ship from their ship and you die.
                """))
            return 'death'

class Finished(Scene):

    def enter(self):
        print("You won! Good job.")
        return 'finished'

class Map(object):

    scenes = {
        'central_corridor': CentralCorridor(),
        'laster_weapon_armory': LaserWeaponArmory(),
        'the_bridge': TheBridge(),
        'escape_pod': EscapePod(),
        'death': Death(),
        'finished': Finished()
    }

    def __init__(self, start_scene):
        self.start_scene = start_scene

    def next_scene(self, scene_name):
        val = Map.scenes.get(scene_name)
        return val

    def opening_scene(self):
        return self.next_scene(self.start_scene)

# Finally the code that runs the game by making a Map, handing that map to
# an Engine before calling play to make game work.
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
```

<p>I'm trying to understand what's going on here, but I don't see it. I've also deleted two of the larger classes because they don't seem to be at issue here. </p>

<p>EDIT: The return I'm putting in is:</p>

```(base) ➜  Python python ex43.py
```

<p>Then,</p>

```dodge!
```

<p>This returns:</p>

```Like a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head. In the middle of your artful dodge your foot slips and you bang your head on the metal wall and pass out.  You wake up shortly after only to die as the Gothon stomps on your head and eats you.

You're worse than your Dad's jokes. Traceback (most recent call last): File "ex43.py", line 283, in <module>
    a_game.play()   File "ex43.py", line 45, in play
    next_scene_name = current_scene.enter() AttributeError: 'NoneType' object has no attribute 'enter'
```

答:
The enter method for the Death Scene doesn't return anything. In Python, all functions without an explicit return statement return None, which explains the error you're getting.

```<code>class Death(Scene):

    quips = [
        "You died.  You kinda suck at this.",
        "Your Mom would be proud...if she were smarter.",
        "Such a luser.",
        "I have a small puppy that's better at this.",
        "You're worse than your Dad's jokes."

    ]

    def enter(self):
        print(Death.quips[randint(0, len(self.quips)-1)])
        # NEED TO ADD RETURN LINE HERE <---
</code>```

Body:
Very sorry in advance for the long paste.

The code is straight from the text. It may be due to class Scene, that seems to have the instruction to: subclass it and implement enter(). But I don't know what that means.

from sys import exit
from random import randint
from textwrap import dedent

class Scene(object):

    def enter(self):
        print("This scene is not yet configured.")
        print("Subclass it and implement enter()")
        exit(1)
# Skeleton code: a base class for Scene that will have
# the common things that all scenes do.

class Engine(object):

    def __init__(self, scene_map):
        self.scene_map = scene_map

    def play(self):
        current_scene = self.scene_map.opening_scene()
        last_scene = self.scene_map.next_scene('finished')

        while current_scene != last_scene:
            next_scene_name = current_scene.enter()
            current_scene = self.scene_map.next_scene(next_scene_name)

        # be sure to print out the last scene
        current_scene.enter()

class Death(Scene):

    quips = [
        "You died.  You kinda suck at this.",
        "Your Mom would be proud...if she were smarter.",
        "Such a luser.",
        "I have a small puppy that's better at this.",
        "You're worse than your Dad's jokes."

    ]

    def enter(self):
        print(Death.quips[randint(0, len(self.quips)-1)])

class CentralCorridor(Scene):

    def enter(self):
        print(dedent("""
            The Gothons of Planet Percal #25 have invaded your ship and
            destroyed your entire crew.  You are the last surviving member
            member and your last mission is to get the neutron destruct
            bomb from the Weapons Armory, put it in the bridge, and
            blow the ship up after getting into an escape pod.

            You're running down the central corridor to the Weapons
            Armory when a Gothon jumps out, red scaly skin, dark grimy
            teeth, and evil clown costume flowing around his hate
            filled body.  He's blocking the door to the Armory and
            about to pull a weapon to blast you.
            """))

        action = input("> ")

        if action == "shoot!":
            print(dedent("""
                Quick on the draw you yank out your blaster and fire
                it at the Gothon.  His clown costume is flowing and
                moving around his body, which throws off your aim.
                Your laster hits his costume but misses him entirely.
                This completely ruins his brand new costume his mother
                bought him, which makes him fly into an insane rage
                and blast you repeatedly in the face until you are
                dead.  Then he eats you.
                """))
            return 'death'

        elif action == "dodge!":
            print(dedent("""
                Like a world class boxer you dodge, weave, slip and
                slide right as the Gothon's blaster cranks a laser
                past your head. In the middle of your artful dodge
                your foot slips and you bang your head on the metal
                wall and pass out.  You wake up shortly after only to
                die as the Gothon stomps on your head and eats you.
                """))
            return 'death'

        elif action == "tell a joke":
            print(dedent("""
                Lucky for you they made you learn Gothon insults in
                the academy.  You tell the one Gothon joke you know:
                Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr,
                fur fvgf nebhaq gur ubhfr.  The Gothon stops, tries
                not to laugh, then busts out laughing and can't move.
                While he's laughing you run up and shoot him square in
                the head putting him down, then jump through the
                Weapon Armory door.
                """))
            return 'laster_weapon_armory'

        else:
            print("DOES NOT COMPUTE!")
            return 'central_corridor'

class LaserWeaponArmory(Scene):

    def enter(self):
        print(dedent("""
            You do a dive roll into the Weapon Armory, crouch and scan
            the room for more GOthon that might be hiding. It's dead
            quiet, too quiet.  You stand up and run to the far side of
            the room and find the neutron bomb in its container.
            There's a keypad lock on the box and you need the code to
            get the bomb out. If you get the code wrong 10 times then
            the lock closes forever and you can't get the bomb.  The
            code is 3 digits.
            """))

        code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
        guess = input("[keypad]> ")
        guesses = 0

        while guess != code and guesses <10:
            print("BZZZZEDDD!")
            guesses += 1
            guess = input("[keypad]> ")

        if guess == code:
            print(dedent("""
                The container clicks open and the seal breaks, letting
                gas out.  You grab the neutron bomb and run as fast as
                you can to the bridge where you must place it in the
                right spot.
                """))
            return 'the_bridge'
        else:
            print(dedent("""
                The lock buzzes one last time and then you hear a
                sickening melting sound as the mechanism is fused
                together.  You decide to sit there, and finally the
                Gothons blow up the ship from their ship and you die.
                """))
            return 'death'

class Finished(Scene):

    def enter(self):
        print("You won! Good job.")
        return 'finished'

class Map(object):

    scenes = {
        'central_corridor': CentralCorridor(),
        'laster_weapon_armory': LaserWeaponArmory(),
        'the_bridge': TheBridge(),
        'escape_pod': EscapePod(),
        'death': Death(),
        'finished': Finished()
    }

    def __init__(self, start_scene):
        self.start_scene = start_scene

    def next_scene(self, scene_name):
        val = Map.scenes.get(scene_name)
        return val

    def opening_scene(self):
        return self.next_scene(self.start_scene)

# Finally the code that runs the game by making a Map, handing that map to
# an Engine before calling play to make game work.
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

I'm trying to understand what's going on here, but I don't see it. I've also deleted two of the larger classes because they don't seem to be at issue here.

EDIT: The return I'm putting in is:

(base) ➜  Python python ex43.py

Then,

dodge!

This returns:

Like a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head. In the middle of your artful dodge your foot slips and you bang your head on the metal wall and pass out.  You wake up shortly after only to die as the Gothon stomps on your head and eats you.

You're worse than your Dad's jokes. Traceback (most recent call last): File "ex43.py", line 283, in <module>
    a_game.play()   File "ex43.py", line 45, in play
    next_scene_name = current_scene.enter() AttributeError: 'NoneType' object has no attribute 'enter'

Body:
The enter method for the Death Scene doesn't return anything. In Python, all functions without an explicit return statement return None, which explains the error you're getting.

class Death(Scene):

    quips = [
        "You died.  You kinda suck at this.",
        "Your Mom would be proud...if she were smarter.",
        "Such a luser.",
        "I have a small puppy that's better at this.",
        "You're worse than your Dad's jokes."

    ]

    def enter(self):
        print(Death.quips[randint(0, len(self.quips)-1)])
        # NEED TO ADD RETURN LINE HERE <---


问:
We couldn't find uptime from /proc/uptime, using os.uptime() value, Pm2 3.5 error
We couldn't find uptime from /proc/uptime, using os.uptime() value, Pm2 3.5 error

```<code>2020-02-11T20:11:43: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:12:13: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:12:43: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:13:13: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:13:43: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:14:13: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:14:43: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:15:43: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:16:13: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
</code>```

答:
I don't have bulletproof evidences but same error started in our project when we updated PM2 from 4.2.3 to 4.4

To be honest, we installed module on host with internet and just copied it to production, this worked many times but it is anyway a bad practice.

So, after downgrade to 4.2.3 (installed correctly via Nexus) everything works fine

Body:
We couldn't find uptime from /proc/uptime, using os.uptime() value, Pm2 3.5 error

2020-02-11T20:11:43: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:12:13: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:12:43: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:13:13: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:13:43: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:14:13: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:14:43: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:15:43: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value
2020-02-11T20:16:13: PM2 warn: [pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value


问:
How to show proccess output in text box in other frame using Python tkinter
I'm trying to write the 'ping' output to a text box that will be
created in the 'output' tkinter frame
When I press the 'Submit' button while writing the output to file.

Questions:

1: Is there a way to place the text box inside the 'output' frame?

2: How can I print lines from files inside the 'output' frame?

3: How can I use threading or multiproccess to display the output in realtime?

Before clicking 'Submit':

```<code>import tkinter as tk
import subprocess as sub
from multiprocessing import Queue
import os

class GUI(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry("650x500")
        self.title("Gil Shwartz GUI Project")
        menu = tk.Frame(self, height=250, width=10, relief="solid")
        menu.pack(side=tk.LEFT, fill="both", anchor="w")
        container = tk.Frame(self, relief="flat")
        container.pack(side=tk.TOP, fill="y", expand=True)
        output = tk.LabelFrame(self, text="Output", height=350, width=70)
        output.pack(side=tk.BOTTOM, fill="both", expand=True)

        menu.grid_columnconfigure(0, weight=1)
        menu.grid_rowconfigure(0, weight=1)

        self.frames = ["Menu", "MainWelcome", "testPing", "PageOne", "PageTwo"]

        self.frames[0] = Menu(parent=menu, controller=self)
        self.frames[1] = MainWelcome(parent=container, controller=self)
        self.frames[2] = testPing(parent=container, controller=self)
        self.frames[3] = PageOne(parent=container, controller=self)
        self.frames[4] = PageTwo(parent=container, controller=self)

        self.frames[0].grid(row=0, column=0, sticky="nsew")
        self.frames[1].grid(row=0, column=0, sticky="nsew")
        self.frames[2].grid(row=0, column=0, sticky="nsew")
        self.frames[3].grid(row=0, column=0, sticky="nsew")
        self.frames[4].grid(row=0, column=0, sticky="nsew")

        self.show_frame(1)

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        print(frame)
        frame.tkraise()
        frame.grid(row=0, column=0, sticky="nsew")

class Menu(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        button1 = tk.Button(self, text="Ping Test",
                            command=lambda: controller.show_frame(2))
        button1.config(bg="royalblue2")
        button2 = tk.Button(self, text="Page Two",
                            command=lambda: controller.show_frame(4))
        button2.config(bg="dark violet")
        button3 = tk.Button(self, text="Quit",
                            command=lambda: Menu.terminate(self))
        button3.config(bg="gray40")

        button1.pack(fill="both", expand=True)
        button2.pack(fill="both", expand=True)
        button3.pack(fill="both", expand=True)
        button1.grid_columnconfigure(0, weight=1)
        button2.grid_columnconfigure(0, weight=0)
        button3.grid_rowconfigure(0, weight=0)

    def terminate(self):
        exit()

class MainWelcome(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        label = tk.Label(self, text="Text 1", bg="yellow")
        label.pack(fill="x", expand=True)
        label = tk.Label(self, text="Text 2", bg="yellow")
        label.pack(fill="x")

class testPing(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        urlLabel = tk.Label(self, text="Enter URL : ", padx=5, pady=5)
        urlLabel.pack(anchor="w")
        urlInputBox = tk.Entry(self)
        urlInputBox.pack(anchor="w")
        urlInputBox.grid_columnconfigure(0, weight=0)

        clearFileLabel = tk.Label(self, text="Clear File?", padx=5, pady=5)
        clearFileLabel.pack(anchor="w")

        clearFile = tk.BooleanVar()
        clearFile.set(False)
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: self.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: self.callback(clearFile.get()))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: self.pingURL(urlInputBox.get(),
                                                                 clearFile.get()))
        urlSubmitButton.pack(side=tk.RIGHT, anchor="e")

    def callback(self, clearFile):
        print(clearFile) # Debugging Mode - check Radio box Var.

    def pingURL(self, host, clearFile):

        global r

        file = fr'c:/users/{os.getlogin()}/Desktop/ping.txt'
        text = tk.Text(self, height=5, width=100, wrap=tk.WORD)
        text.pack(side=tk.TOP, expand=True)
        if clearFile == True:

            with open(file, 'a') as output:
                output.truncate(0)
                sub.call(['ping', f'{host}'], stdout=output)

        else:

            with open(file, 'a') as output:
                sub.call(['ping', f'{host}'], stdout=output)

        output.close()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", bg="red")
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to page 2",
                           command=lambda: controller.show_frame(2))
        button.pack()

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", bg="blue")
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame(1))
        button.pack()

if __name__ == "__main__":
    app = GUI()
    app.mainloop()
</code>```

After clicking 'Submit':

答:
First, you have to make the output frame available or else you can't access it later:

```<code>self.output = tk.LabelFrame(self, text="Output", height=350, width=70)
self.output.pack(side=tk.BOTTOM, fill="both", expand=True)
</code>```

Then, in the testPing() class pingURL() method you can pack the Text() widget in the output labelframe:

```<code>text = tk.Text(self.controller.output, height=5, width=100, wrap=tk.WORD)
</code>```

I don't know about using threading or multiproccess. In general I think you will get a better response if you post questions for each of your problems instead of listing them in the same question.

Body:
I'm trying to write the 'ping' output to a text box that will be
created in the 'output' tkinter frame
When I press the 'Submit' button while writing the output to file.

Questions:

1: Is there a way to place the text box inside the 'output' frame?

2: How can I print lines from files inside the 'output' frame?

3: How can I use threading or multiproccess to display the output in realtime?

Before clicking 'Submit':

import tkinter as tk
import subprocess as sub
from multiprocessing import Queue
import os

class GUI(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry("650x500")
        self.title("Gil Shwartz GUI Project")
        menu = tk.Frame(self, height=250, width=10, relief="solid")
        menu.pack(side=tk.LEFT, fill="both", anchor="w")
        container = tk.Frame(self, relief="flat")
        container.pack(side=tk.TOP, fill="y", expand=True)
        output = tk.LabelFrame(self, text="Output", height=350, width=70)
        output.pack(side=tk.BOTTOM, fill="both", expand=True)

        menu.grid_columnconfigure(0, weight=1)
        menu.grid_rowconfigure(0, weight=1)

        self.frames = ["Menu", "MainWelcome", "testPing", "PageOne", "PageTwo"]

        self.frames[0] = Menu(parent=menu, controller=self)
        self.frames[1] = MainWelcome(parent=container, controller=self)
        self.frames[2] = testPing(parent=container, controller=self)
        self.frames[3] = PageOne(parent=container, controller=self)
        self.frames[4] = PageTwo(parent=container, controller=self)

        self.frames[0].grid(row=0, column=0, sticky="nsew")
        self.frames[1].grid(row=0, column=0, sticky="nsew")
        self.frames[2].grid(row=0, column=0, sticky="nsew")
        self.frames[3].grid(row=0, column=0, sticky="nsew")
        self.frames[4].grid(row=0, column=0, sticky="nsew")

        self.show_frame(1)

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        print(frame)
        frame.tkraise()
        frame.grid(row=0, column=0, sticky="nsew")

class Menu(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        button1 = tk.Button(self, text="Ping Test",
                            command=lambda: controller.show_frame(2))
        button1.config(bg="royalblue2")
        button2 = tk.Button(self, text="Page Two",
                            command=lambda: controller.show_frame(4))
        button2.config(bg="dark violet")
        button3 = tk.Button(self, text="Quit",
                            command=lambda: Menu.terminate(self))
        button3.config(bg="gray40")

        button1.pack(fill="both", expand=True)
        button2.pack(fill="both", expand=True)
        button3.pack(fill="both", expand=True)
        button1.grid_columnconfigure(0, weight=1)
        button2.grid_columnconfigure(0, weight=0)
        button3.grid_rowconfigure(0, weight=0)

    def terminate(self):
        exit()

class MainWelcome(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        label = tk.Label(self, text="Text 1", bg="yellow")
        label.pack(fill="x", expand=True)
        label = tk.Label(self, text="Text 2", bg="yellow")
        label.pack(fill="x")

class testPing(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        urlLabel = tk.Label(self, text="Enter URL : ", padx=5, pady=5)
        urlLabel.pack(anchor="w")
        urlInputBox = tk.Entry(self)
        urlInputBox.pack(anchor="w")
        urlInputBox.grid_columnconfigure(0, weight=0)

        clearFileLabel = tk.Label(self, text="Clear File?", padx=5, pady=5)
        clearFileLabel.pack(anchor="w")

        clearFile = tk.BooleanVar()
        clearFile.set(False)
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: self.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: self.callback(clearFile.get()))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: self.pingURL(urlInputBox.get(),
                                                                 clearFile.get()))
        urlSubmitButton.pack(side=tk.RIGHT, anchor="e")

    def callback(self, clearFile):
        print(clearFile) # Debugging Mode - check Radio box Var.

    def pingURL(self, host, clearFile):

        global r

        file = fr'c:/users/{os.getlogin()}/Desktop/ping.txt'
        text = tk.Text(self, height=5, width=100, wrap=tk.WORD)
        text.pack(side=tk.TOP, expand=True)
        if clearFile == True:

            with open(file, 'a') as output:
                output.truncate(0)
                sub.call(['ping', f'{host}'], stdout=output)

        else:

            with open(file, 'a') as output:
                sub.call(['ping', f'{host}'], stdout=output)

        output.close()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", bg="red")
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to page 2",
                           command=lambda: controller.show_frame(2))
        button.pack()

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", bg="blue")
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame(1))
        button.pack()

if __name__ == "__main__":
    app = GUI()
    app.mainloop()

After clicking 'Submit':

Body:
First, you have to make the output frame available or else you can't access it later:

self.output = tk.LabelFrame(self, text="Output", height=350, width=70)
self.output.pack(side=tk.BOTTOM, fill="both", expand=True)

Then, in the testPing() class pingURL() method you can pack the Text() widget in the output labelframe:

text = tk.Text(self.controller.output, height=5, width=100, wrap=tk.WORD)

I don't know about using threading or multiproccess. In general I think you will get a better response if you post questions for each of your problems instead of listing them in the same question.


问:
How to use major tick marks in chart.js 2.9.3?
I use latest Chart.js 2.9.3. I've tried the following code with major ticks:

        var ctx = document.getElementById('chart').getContext('2d');
        var chart  = new Chart(ctx, {
            type: 'horizontalBar',

            data: {
                datasets: [{
                    barPercentage: 0.2,
                    borderColor: 'black',
                    borderWidth: 2,
                    borderSkipped: false,
                    backgroundColor: 'transparent',
                    data: [[0, 8000]]
                }]
            },

            options: {
                legend: false,
                tooltips: false,
                animation: false,
                title: {
                    display: true,
                    fontSize: '26',
                    text: 'AT1G24460'
                },
                scales: {
                    xAxes: [{
                        position: 'top',
                        offset: true,
                        ticks: {
                            major: {
                                enabled: true,
                                fontColor: 'red'
                            }
                        },
                        gridLines: {
                            drawOnChartArea: false
                        }
                    }],
                    yAxes: [{
                        display: false
                    }]
                }
            }
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
 <div class="text-center">
        <canvas id="chart"></canvas>
</div></code>```

The result is the following (major ticks are not displayed at all). So how to make major tick marks work in chart.js?

P.S. My final goal is to have top axis like this:

What axis styling is possible without direct canvas painting (ticks below axis baseline, first and last ticks are enlarged, two labels for first and last ticks, no labels except fof first and last tick, etc.)

Thank you in advance.

答:
Official answer:

Major ticks are only supported on the time scale in 2.9. In 3.0 they
  are also being added to the log scale. They're not in the linear scale
  yet. But major ticks are most useful for deciding which ticks not to
  skip in the autoSkipper. 3.0 will also add better support for tick
  styling via scriptable tick options (#7337), which will allow you to
  make ticks that you want bolder, bigger, different colors, etc. and
  you don't need major tick support for that. I'd recommend trying 3.0

Body:
I use latest Chart.js 2.9.3. I've tried the following code with major ticks:

        var ctx = document.getElementById('chart').getContext('2d');
        var chart  = new Chart(ctx, {
            type: 'horizontalBar',

            data: {
                datasets: [{
                    barPercentage: 0.2,
                    borderColor: 'black',
                    borderWidth: 2,
                    borderSkipped: false,
                    backgroundColor: 'transparent',
                    data: [[0, 8000]]
                }]
            },

            options: {
                legend: false,
                tooltips: false,
                animation: false,
                title: {
                    display: true,
                    fontSize: '26',
                    text: 'AT1G24460'
                },
                scales: {
                    xAxes: [{
                        position: 'top',
                        offset: true,
                        ticks: {
                            major: {
                                enabled: true,
                                fontColor: 'red'
                            }
                        },
                        gridLines: {
                            drawOnChartArea: false
                        }
                    }],
                    yAxes: [{
                        display: false
                    }]
                }
            }
        });

        <canvas id="chart"></canvas>

The result is the following (major ticks are not displayed at all). So how to make major tick marks work in chart.js?

P.S. My final goal is to have top axis like this:

What axis styling is possible without direct canvas painting (ticks below axis baseline, first and last ticks are enlarged, two labels for first and last ticks, no labels except fof first and last tick, etc.)

Thank you in advance.


问:
VMWare error: VMware Player and Device/Credential Guard are not compatible
I've been running ubuntu 19 (64 bit) on VMWare Workstation 15 Player for 2 months now. There was no problem in running the virtual machine till now, but today when I tried running the machine, it gave me the following error:
VMware Player and Device/Credential Guard are not compatible. VMware Player can be run after disabling Device/Credential Guard. Please visit http://www.vmware.com/go/turnoff_CG_DG for more details.
Following are the screenshots for the error:
Error regarding device credentials
Error code after returning to home screen

I followed the link provided by the dialog box, but it was of no use to me. After searching for a while, I found out that Hyper V could not be installed in my computer as I have Windows 10 Home version, and hence I could not find anything regarding device credentials on my computer.

Is there any solution that can be useful, other than uninstalling my VM or VMWare player?

答:
I faced the similar issue when hyper-v in windows was turned on for docker. I followed this link to fix the issue:

wmware workstation don't work with windows 10 pro 1903


问:
Check if User input correct ipv4 format
My first time here, i have a question please:

i want to check if user type on input an ipv4 if it's not ipv4 user should receive error 3 times and then exit. My example code below:

```<code>    # Hosts and Commands
    for attempt in range(3):
        host = input("Enter IPs separated by SPACE: ")
        cmd = input("Enter Command(s) seperated by ',' : ")
        if(len(host) != 0) and (len(cmd) != 0):
            break
        print("Fields Cannot be Blank, try again...")
    else:
        Screen().input("Sorry...Execution Terminated, Press [ENTER] to Exit")
        return
</code>```

答:
```<code>def validateIP(s):
    if not s: return False
    try:
        parts = [int(p) for p in s.split('.')]
    except:
        return False

    if len(parts) != 4: return False
    for part in parts:
        if not(0 <= part <= 255):
            return False
    return True

max_attempts = 3
for remaining in range(max_attempts-1, -1, -1):
    ip = input("Enter an IPv4 address: ")
    if validateIP(ip.strip()): break
    print("That is an invalid IPv4 address. You have", remaining, "attempts left")
</code>```

Title: Check if User input correct ipv4 format

Body:
My first time here, i have a question please:

i want to check if user type on input an ipv4 if it's not ipv4 user should receive error 3 times and then exit. My example code below:

    # Hosts and Commands
    for attempt in range(3):
        host = input("Enter IPs separated by SPACE: ")
        cmd = input("Enter Command(s) seperated by ',' : ")
        if(len(host) != 0) and (len(cmd) != 0):
            break
        print("Fields Cannot be Blank, try again...")
    else:
        Screen().input("Sorry...Execution Terminated, Press [ENTER] to Exit")
        return


问:
Sorting std::unordered_map by key
How can I sort an unordered_map by key? I need to print an unordered_map sorted by key.

答:
Are you sure you need this? Because that is not possible. An unordered_map is a hash container, that is, the keys are hashed. Inside of the container, they don't have the same representation as on the outside. Even the name implies that you can't sort it. It's one of the criteria to choose a hash container: You do not need a specific order.

If you do, get a normal map. The keys are automatically sorted in a strict-weak ordering. If you need another sort, write your own comparator.

If you only need to print it sorted, the following may be inefficient, but it's as close as you'll get if you still want to keep the unordered_map.

```<code>#include <map>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <functional>

struct map_streamer{
  std::ostream& _os;

  map_streamer(std::ostream& os) : _os(os) {}

  template<class K, class V>
  void operator()(std::pair<K,V> const& val){
    // .first is your key, .second is your value
    _os << val.first << " : " << val.second << "\n";
  }
};

template<class K, class V, class Comp>
void print_sorted(std::unordered_map<K,V> const& um, Comp pred){
  std::map<K,V> m(um.begin(), um.end(), pred);
  std::for_each(m.begin(),m.end(),map_streamer(std::cout));
}

template<class K, class V>
void print_sorted(std::unordered_map<K,V> const& um){
  print_sorted(um, std::less<int>());
}
</code>```

Example on Ideone.

Note that in C++0x, you can replace the two overloads with one function with a default template argument:

```<code>template<class K, class V, class Comp = std::less<int> >
void print_sorted(std::unordered_map<K,V> const& um, Comp pred = Comp()){
  std::map<K,V> m(um.begin(), um.end(), pred);
  std::for_each(m.begin(),m.end(),map_streamer(std::cout));
}
</code>```

Title: Sorting std::unordered_map by key

Body:
Are you sure you need this? Because that is not possible. An unordered_map is a hash container, that is, the keys are hashed. Inside of the container, they don't have the same representation as on the outside. Even the name implies that you can't sort it. It's one of the criteria to choose a hash container: You do not need a specific order.

If you do, get a normal map. The keys are automatically sorted in a strict-weak ordering. If you need another sort, write your own comparator.

If you only need to print it sorted, the following may be inefficient, but it's as close as you'll get if you still want to keep the unordered_map.

#include <map>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <functional>

struct map_streamer{
  std::ostream& _os;

  map_streamer(std::ostream& os) : _os(os) {}

  template<class K, class V>
  void operator()(std::pair<K,V> const& val){
    // .first is your key, .second is your value
    _os << val.first << " : " << val.second << "\n";
  }
};

template<class K, class V, class Comp>
void print_sorted(std::unordered_map<K,V> const& um, Comp pred){
  std::map<K,V> m(um.begin(), um.end(), pred);
  std::for_each(m.begin(),m.end(),map_streamer(std::cout));
}

template<class K, class V>
void print_sorted(std::unordered_map<K,V> const& um){
  print_sorted(um, std::less<int>());
}

Example on Ideone.

Note that in C++0x, you can replace the two overloads with one function with a default template argument:

template<class K, class V, class Comp = std::less<int> >
void print_sorted(std::unordered_map<K,V> const& um, Comp pred = Comp()){
  std::map<K,V> m(um.begin(), um.end(), pred);
  std::for_each(m.begin(),m.end(),map_streamer(std::cout));
}


问:
localStorage is not working on google chrome
I am using browsers localStorage to store a value, but while using google chrome, when we refresh the page using window.location.reload(), localStorage.value is flushed. e.g

```<code>localStorage.value1=true
</code>```

after reloading, i am not getting this value1 object in localStorage.

Same code works on mozila firefox, but not in chrome.
While using firefox, localstorage value is persistent.

答:
```<code>// main.go
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "io/ioutil"
    "net/http"
    "github.com/gorilla/mux"
)

// Article - Our struct for all articles
type Article struct {
    Id      string    `json:"Id"`
    Title   string `json:"Title"`
    Desc    string `json:"desc"`
    Content string `json:"content"`
}

var Articles []Article

func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to the HomePage!")
    fmt.Println("Endpoint Hit: homePage")
}

func returnAllArticles(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Endpoint Hit: returnAllArticles")
    json.NewEncoder(w).Encode(Articles)
}

func returnSingleArticle(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    key := vars["id"]

    for _, article := range Articles {
        if article.Id == key {
            json.NewEncoder(w).Encode(article)
        }
    }
}

func createNewArticle(w http.ResponseWriter, r *http.Request) {
    // get the body of our POST request
    // unmarshal this into a new Article struct
    // append this to our Articles array.
    reqBody, _ := ioutil.ReadAll(r)

    var article Article
    json.Unmarshal(reqBody, &article)
    // update our global Articles array to include
    // our new Article
    Articles = append(Articles, article)

    json.NewEncoder(w).Encode(article)
}

func deleteArticle(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]

    for index, article := range Articles {
        if article.Id == id {
            Articles = append(Articles[:index], Articles[index+1:]...)
        }
    }

}

func handleRequests() {
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/articles", returnAllArticles)
    myRouter.HandleFunc("/article", createNewArticle).Methods("POST")
    myRouter.HandleFunc("/article/{id}", deleteArticle).Methods("DELETE")
    myRouter.HandleFunc("/article/{id}", returnSingleArticle)
    log.Fatal(http.ListenAndServe(":10000", myRouter))
}

func main() {
    Articles = []Article{
        Article{Id: "1", Title: "Hello", Desc: "Article Description", Content: "Article Content"},
        Article{Id: "2", Title: "Hello 2", Desc: "Article Description", Content: "Article Content"},
    }
    handleRequests()
}
</code>```

Body:
I am using browsers localStorage to store a value, but while using google chrome, when we refresh the page using window.location.reload(), localStorage.value is flushed. e.g

localStorage.value1=true

after reloading, i am not getting this value1 object in localStorage.

Same code works on mozila firefox, but not in chrome.
While using firefox, localstorage value is persistent.


问:
Azure DevOps configure code coverage with JaCoCo
I want to view code coverage in Azure DevOps.

So I configured my azure-pipelines.yml like this:

```<code>trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

steps:
- task: NuGetToolInstaller@1

- task: NuGetCommand@2
  inputs:
    restoreSolution: '$(solution)'

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:DesktopBuildPackageLocation="$(build.artifactStagingDirectory)\WebApp.zip" /p:DeployIisAppPath="Default Web Site" /p:CollectCoverage=true /p:CoverletOutputFormat=jacoco /p:CoverletOutput=$(Build.DefaultWorkingDirectory)/TestResults/Coverage/'''
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'
    maximumCpuCount: true

- task: VSTest@2
  inputs:
    testSelector: 'testAssemblies'
    testAssemblyVer2: |
      **\*test.dll
      !**\*TestAdapter.dll
      !**\obj\**
    searchFolder: '$(System.DefaultWorkingDirectory)'
    codeCoverageEnabled: true
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

- task: PublishCodeCoverageResults@1
  inputs:
    codeCoverageTool: 'JaCoCo'
    summaryFileLocation: '$(System.DefaultWorkingDirectory)/TestResults/Coverage/*.xml'
</code>```

and the nuget-package coverlet.collector was added by Azure DevOps checkin.
I also added the part /p:CollectCoverage=true /p:CoverletOutputFormat=jacoco /p:CoverletOutput=$(Build.DefaultWorkingDirectory)/TestResults/Coverage/ in step VSBuild.

However, when I click on the last run pipeline it only shows a button Download code coverage results with a link to a .coverage-file.

I decided for JaCoCo over Cobertura for no specific reason, so taht can be changed if necessary.

How can I view code coverage?

答:
Azure DevOps configure code coverage with JaCoCo

This is a known issue on Azure devops. Now, we could only download the report, and open it with Visual Studio.

Azure devops only support the download link for .coverage files currently. The white page you see is a UI glitch. This scenario is only supposed to render a download link to the coverage file.

Besides, this issue has been submitted in this earlier suggestion ticket linked here:

support vstest .coverage "code coverage" build results tab

This feature request is On Roadmap, I believe it will be released soon, you can follow this thread to know its latest feedback.

Hope this helps.

Body:
I want to view code coverage in Azure DevOps.

So I configured my azure-pipelines.yml like this:

trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

steps:
- task: NuGetToolInstaller@1

- task: NuGetCommand@2
  inputs:
    restoreSolution: '$(solution)'

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:DesktopBuildPackageLocation="$(build.artifactStagingDirectory)\WebApp.zip" /p:DeployIisAppPath="Default Web Site" /p:CollectCoverage=true /p:CoverletOutputFormat=jacoco /p:CoverletOutput=$(Build.DefaultWorkingDirectory)/TestResults/Coverage/'''
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'
    maximumCpuCount: true

- task: VSTest@2
  inputs:
    testSelector: 'testAssemblies'
    testAssemblyVer2: |
      **\*test.dll
      !**\*TestAdapter.dll
      !**\obj\**
    searchFolder: '$(System.DefaultWorkingDirectory)'
    codeCoverageEnabled: true
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

- task: PublishCodeCoverageResults@1
  inputs:
    codeCoverageTool: 'JaCoCo'
    summaryFileLocation: '$(System.DefaultWorkingDirectory)/TestResults/Coverage/*.xml'

and the nuget-package coverlet.collector was added by Azure DevOps checkin.
I also added the part /p:CollectCoverage=true /p:CoverletOutputFormat=jacoco /p:CoverletOutput=$(Build.DefaultWorkingDirectory)/TestResults/Coverage/ in step VSBuild.

However, when I click on the last run pipeline it only shows a button Download code coverage results with a link to a .coverage-file.

I decided for JaCoCo over Cobertura for no specific reason, so taht can be changed if necessary.

How can I view code coverage?


问:
Sequelize: Date Comparison Inside of an AND Block
I hammered on this for hours -- trying to get a date comparison working inside of an and block. Both parts baffled me for a while -- the date comparison part, and the and syntax.

This is the syntax that did not work - then I'll post the answer with the code that does work.

Note: user_presence_time_of_last_update is a field of type time stamp with timezone.

DOES NOT WORK

```<code>const op = connectors.Sequelize.Op;
const timeTwoHoursAgo = new Date()
timeTwoHoursAgo.setMinutes(timeTwoHoursAgo.getMinutes() - 120)

var usersWhoWentOffline = connectors.epUserData.findAll({
    where: {
        $and:{
            user_presence_time_of_last_update: {$lt: new Date(new Date() - 5 * one_hour)},
            $or:[
                {user_presence: USER_PRESENCE_IDLE},
                {user_presence: USER_PRESENCE_ONLINE},
            ],
        }
    }
}).then((res) => res.map((item) => item.dataValues));
</code>```

答:
Here's the code that does work, with a big assist from this SO post:

DOES WORK

```<code>const op = connectors.Sequelize.Op;
const timeTwoHoursAgo = new Date()
timeTwoHoursAgo.setMinutes(timeTwoHoursAgo.getMinutes() - 120)

var usersWhoWentOffline = connectors.epUserData.findAll({
    where: {
        [op.and]: {
            user_presence_time_of_last_update: {
                [op.lt]: timeTwoHoursAgo
            },
            [op.or]: [
                {user_presence: USER_PRESENCE_IDLE},
                {user_presence: USER_PRESENCE_ONLINE},
            ]
        }
    }
})
</code>```

Body:
I hammered on this for hours -- trying to get a date comparison working inside of an and block. Both parts baffled me for a while -- the date comparison part, and the and syntax.

This is the syntax that did not work - then I'll post the answer with the code that does work.

Note: user_presence_time_of_last_update is a field of type time stamp with timezone.

DOES NOT WORK

const op = connectors.Sequelize.Op;
const timeTwoHoursAgo = new Date()
timeTwoHoursAgo.setMinutes(timeTwoHoursAgo.getMinutes() - 120)

var usersWhoWentOffline = connectors.epUserData.findAll({
    where: {
        $and:{
            user_presence_time_of_last_update: {$lt: new Date(new Date() - 5 * one_hour)},
            $or:[
                {user_presence: USER_PRESENCE_IDLE},
                {user_presence: USER_PRESENCE_ONLINE},
            ],
        }
    }
}).then((res) => res.map((item) => item.dataValues));

Body:
Here's the code that does work, with a big assist from this SO post:

DOES WORK

const op = connectors.Sequelize.Op;
const timeTwoHoursAgo = new Date()
timeTwoHoursAgo.setMinutes(timeTwoHoursAgo.getMinutes() - 120)

var usersWhoWentOffline = connectors.epUserData.findAll({
    where: {
        [op.and]: {
            user_presence_time_of_last_update: {
                [op.lt]: timeTwoHoursAgo
            },
            [op.or]: [
                {user_presence: USER_PRESENCE_IDLE},
                {user_presence: USER_PRESENCE_ONLINE},
            ]
        }
    }
})


问:
Type mismatch error in loop that adds numbers incrementally in column
I'm creating a sub that creates a time sheet for a specific month/year. The code is based on this Microsoft example code. The Microsoft code creates this calendar. I'm amending the code to insert the days of the week in a single column, like this.

My amended code correctly inserts the number 1 in the cell corresponding to the first day of the month, but the loop to add the subsequent day numbers does not work; Cell.Value = Cell.Offset(-1, 0).Value + 1 gives a Type Mismatch Error. Here is my amended code:

```<code>Sub Calendar_Genorator1()
Dim WS As Worksheet
Dim MyInput As Variant
Dim StartDay As Variant
Dim DayofWeek As Variant
Dim CurYear As Variant
Dim CurMonth As Variant
Dim FinalDay As Variant
Dim Cell As Range
Dim RowCell As Long
Dim ColCell As Long

Set WS = ActiveWorkbook.ActiveSheet

MyInput = InputBox("Type in Month and year for Calendar ")
    If MyInput = "" Then Exit Sub
       ' Get the date value of the beginning of inputted month.
       StartDay = DateValue(MyInput)
       ' Check if valid date but not the first of the month
       ' -- if so, reset StartDay to first day of month.
       If Day(StartDay) <> 1 Then
           StartDay = DateValue(Month(StartDay) & "/1/" & Year(StartDay))
       End If
       ' Prepare cell for Month and Year as fully spelled out.
       'Range("B3").NumberFormat = "d-mmmm"

       'Set headers
       Range("a1").Value = Application.Text(MyInput, "mmmm") & " Time Sheet"
       Range("a2") = "Day"
       Range("b2") = "Date"
       Range("c2") = "Time In"
       Range("d2") = "Time Out"
       Range("e2") = "Hours"
       Range("f2") = "Notes"
       Range("g2") = "Overtime"

       'Set weekdays
       Range("a3") = "Sunday"
       Range("a4") = "Monday"
       Range("a5") = "Tuesday"
       Range("a6") = "Wednesday"
       Range("a7") = "Thursday"
       Range("a8") = "Friday"
       Range("a9") = "Saturday"

       DayofWeek = Weekday(StartDay)
       ' Set variables to identify the year and month as separate variables.
       CurYear = Year(StartDay)
       CurMonth = Month(StartDay)
       ' Set variable and calculate the first day of the next month.
       FinalDay = DateSerial(CurYear, CurMonth + 1, 1)
       ' Place a "1" in cell position of the first day of the chosen month based on DayofWeek.
       Select Case DayofWeek
           Case 1
               Range("b3").Value = 1
           Case 2
               Range("b4").Value = 1
           Case 3
               Range("b5").Value = 1
           Case 4
               Range("b6").Value = 1
           Case 5
               Range("b7").Value = 1
           Case 6
               Range("b8").Value = 1
           Case 7
               Range("b9").Value = 1
       End Select

       'Loop through range b3:b44 incrementing each cell after the "1" cell.
       For Each Cell In Range("b3:b44")
           RowCell = Cell.Row
           ColCell = Cell.Column
           ' Do if "1" is in column B or 2.
           If Cell.Row = 1 And Cell.Column = 2 Then
           ' Do if current cell is not in 1st column.
           ElseIf Cell.Row <> 1 Then
               If Cell.Offset(-1, 0).Value >= 1 Then
                   Cell.Value = Cell.Offset(-1, 0).Value + 1 'Type Mismatch Error here
                   ' Stop when the last day of the month has been entered.
                   If Cell.Value > (FinalDay - StartDay) Then
                       Cell.Value = ""
                       ' Exit loop when calendar has correct number of days shown.
                       Exit For
                   End If
               End If
           End If
       Next
End Sub
</code>```

I changed the parameters in the loop to work inserting the days incrementally in column B, and I suspect the error is related to that. Any ideas as to why I'm getting an error for Cell.Value = Cell.Offset(-1, 0).Value + 1?

答:
Monthly Calendar

```<code>Option Explicit

Sub Calendar_Genorator1()

    Const TitleAddress As String = "A1"
    Const HeadersAddress As String = "A2"
    Const DaysAddress As String = "A3"
    Dim Headers As Variant
    Headers = Array("Day", "Date", "Time In", "Time Out", "Hours", _
                    "Notes", "Overtime")

    Dim MyInput As Variant, StartDay As Variant
    MyInput = InputBox("Type in setMonth and year for Calendar ")
    If MyInput = "" Then Exit Sub
    ' Get the date value of the beginning of inputted Month.
    StartDay = DateValue(MyInput)
    ' Check if valid date but not the first of the Month
    ' -- if so, reset StartDay to first day of Month.
    If Day(StartDay) <> 1 Then
        StartDay = DateValue(Month(StartDay) & "/1/" & Year(StartDay))
    End If

    Dim ws As Worksheet
    Set ws = ActiveWorkbook.ActiveSheet
    ' Write title.
    ws.Range(TitleAddress).Value = Application.Text(StartDay, "mmmm") _
                                   & " Time Sheet"
    ' Write headers.
    ws.Range(HeadersAddress).Resize(, UBound(Headers)) = Headers
    ' Write days.
    Dim Target As Variant
    Target = getDDDD_D_US(Month(StartDay), Year(StartDay))
    ws.Range(DaysAddress).Resize(UBound(Target), UBound(Target, 2)).Value = Target

End Sub

Function getDDDD_D_US(setMonth As Long, setYear As Long)
    Dim DaysData As Variant
    DaysData = Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", _
                     "Friday", "Saturday")
    Dim Result As Variant
    ReDim Result(1 To 42, 1 To 2)
    ' Write DDDD column.
    Dim i As Long, j As Long, k As Long
    For i = 1 To 6
        k = (i - 1) * 7 + 1
        For j = 0 To 6
            Result(k + j, 1) = DaysData(j)
        Next j
    Next i
    ' Write D column.
    Dim Current As Date
    Current = DateSerial(setYear, setMonth, 1)
    i = Weekday(Current)
    For i = i To i + 27
        Result(i, 2) = Day(Current)
        Current = Current + 1
    Next i
    For i = i To i + 2
        If Month(Current) = setMonth Then
            Result(i, 2) = Day(Current)
            Current = Current + 1
        End If
    Next i
    getDDDD_D_US = Result
End Function
</code>```

Body:
I'm creating a sub that creates a time sheet for a specific month/year. The code is based on this Microsoft example code. The Microsoft code creates this calendar. I'm amending the code to insert the days of the week in a single column, like this.

My amended code correctly inserts the number 1 in the cell corresponding to the first day of the month, but the loop to add the subsequent day numbers does not work; Cell.Value = Cell.Offset(-1, 0).Value + 1 gives a Type Mismatch Error. Here is my amended code:

Sub Calendar_Genorator1()
Dim WS As Worksheet
Dim MyInput As Variant
Dim StartDay As Variant
Dim DayofWeek As Variant
Dim CurYear As Variant
Dim CurMonth As Variant
Dim FinalDay As Variant
Dim Cell As Range
Dim RowCell As Long
Dim ColCell As Long

Set WS = ActiveWorkbook.ActiveSheet

MyInput = InputBox("Type in Month and year for Calendar ")
    If MyInput = "" Then Exit Sub
       ' Get the date value of the beginning of inputted month.
       StartDay = DateValue(MyInput)
       ' Check if valid date but not the first of the month
       ' -- if so, reset StartDay to first day of month.
       If Day(StartDay) <> 1 Then
           StartDay = DateValue(Month(StartDay) & "/1/" & Year(StartDay))
       End If
       ' Prepare cell for Month and Year as fully spelled out.
       'Range("B3").NumberFormat = "d-mmmm"

       'Set headers
       Range("a1").Value = Application.Text(MyInput, "mmmm") & " Time Sheet"
       Range("a2") = "Day"
       Range("b2") = "Date"
       Range("c2") = "Time In"
       Range("d2") = "Time Out"
       Range("e2") = "Hours"
       Range("f2") = "Notes"
       Range("g2") = "Overtime"

       'Set weekdays
       Range("a3") = "Sunday"
       Range("a4") = "Monday"
       Range("a5") = "Tuesday"
       Range("a6") = "Wednesday"
       Range("a7") = "Thursday"
       Range("a8") = "Friday"
       Range("a9") = "Saturday"

       DayofWeek = Weekday(StartDay)
       ' Set variables to identify the year and month as separate variables.
       CurYear = Year(StartDay)
       CurMonth = Month(StartDay)
       ' Set variable and calculate the first day of the next month.
       FinalDay = DateSerial(CurYear, CurMonth + 1, 1)
       ' Place a "1" in cell position of the first day of the chosen month based on DayofWeek.
       Select Case DayofWeek
           Case 1
               Range("b3").Value = 1
           Case 2
               Range("b4").Value = 1
           Case 3
               Range("b5").Value = 1
           Case 4
               Range("b6").Value = 1
           Case 5
               Range("b7").Value = 1
           Case 6
               Range("b8").Value = 1
           Case 7
               Range("b9").Value = 1
       End Select

       'Loop through range b3:b44 incrementing each cell after the "1" cell.
       For Each Cell In Range("b3:b44")
           RowCell = Cell.Row
           ColCell = Cell.Column
           ' Do if "1" is in column B or 2.
           If Cell.Row = 1 And Cell.Column = 2 Then
           ' Do if current cell is not in 1st column.
           ElseIf Cell.Row <> 1 Then
               If Cell.Offset(-1, 0).Value >= 1 Then
                   Cell.Value = Cell.Offset(-1, 0).Value + 1 'Type Mismatch Error here
                   ' Stop when the last day of the month has been entered.
                   If Cell.Value > (FinalDay - StartDay) Then
                       Cell.Value = ""
                       ' Exit loop when calendar has correct number of days shown.
                       Exit For
                   End If
               End If
           End If
       Next
End Sub

I changed the parameters in the loop to work inserting the days incrementally in column B, and I suspect the error is related to that. Any ideas as to why I'm getting an error for Cell.Value = Cell.Offset(-1, 0).Value + 1?

Body:
Monthly Calendar

Option Explicit

Sub Calendar_Genorator1()

    Const TitleAddress As String = "A1"
    Const HeadersAddress As String = "A2"
    Const DaysAddress As String = "A3"
    Dim Headers As Variant
    Headers = Array("Day", "Date", "Time In", "Time Out", "Hours", _
                    "Notes", "Overtime")

    Dim MyInput As Variant, StartDay As Variant
    MyInput = InputBox("Type in setMonth and year for Calendar ")
    If MyInput = "" Then Exit Sub
    ' Get the date value of the beginning of inputted Month.
    StartDay = DateValue(MyInput)
    ' Check if valid date but not the first of the Month
    ' -- if so, reset StartDay to first day of Month.
    If Day(StartDay) <> 1 Then
        StartDay = DateValue(Month(StartDay) & "/1/" & Year(StartDay))
    End If

    Dim ws As Worksheet
    Set ws = ActiveWorkbook.ActiveSheet
    ' Write title.
    ws.Range(TitleAddress).Value = Application.Text(StartDay, "mmmm") _
                                   & " Time Sheet"
    ' Write headers.
    ws.Range(HeadersAddress).Resize(, UBound(Headers)) = Headers
    ' Write days.
    Dim Target As Variant
    Target = getDDDD_D_US(Month(StartDay), Year(StartDay))
    ws.Range(DaysAddress).Resize(UBound(Target), UBound(Target, 2)).Value = Target

End Sub

Function getDDDD_D_US(setMonth As Long, setYear As Long)
    Dim DaysData As Variant
    DaysData = Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", _
                     "Friday", "Saturday")
    Dim Result As Variant
    ReDim Result(1 To 42, 1 To 2)
    ' Write DDDD column.
    Dim i As Long, j As Long, k As Long
    For i = 1 To 6
        k = (i - 1) * 7 + 1
        For j = 0 To 6
            Result(k + j, 1) = DaysData(j)
        Next j
    Next i
    ' Write D column.
    Dim Current As Date
    Current = DateSerial(setYear, setMonth, 1)
    i = Weekday(Current)
    For i = i To i + 27
        Result(i, 2) = Day(Current)
        Current = Current + 1
    Next i
    For i = i To i + 2
        If Month(Current) = setMonth Then
            Result(i, 2) = Day(Current)
            Current = Current + 1
        End If
    Next i
    getDDDD_D_US = Result
End Function


问:
Python, largest odd integer
I am new to coding and have been learning a few days now. I wrote this program in Python while following along in some MIT OpenCourseware lectures and a few books. Are there anyways to more easily express the program?

Finger exercise: Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.

```<code>a = int(raw_input('Enter your first integer: '))
b = int(raw_input('Enter your second integer: '))
c = int(raw_input('Enter your third integer: '))
d = int(raw_input('Enter your fourth integer: '))
e = int(raw_input('Enter your fifth integer: '))
f = int(raw_input('Enter your sixth integer: '))
g = int(raw_input('Enter your seventh integer: '))
h = int(raw_input('Enter your eighth integer: '))
i = int(raw_input('Enter your ninth integer: '))
j = int(raw_input('Enter your tenth integer: '))

if a%2 ==0:
    a = 0
else:
    a = a
if b%2 ==0:
    b = 0
else:
    b = b
if c%2 ==0:
    c = 0
else:
    c = c
if d%2 ==0:
    d = 0
else:
    d = d
if e%2 ==0:
    e = 0
else:
    e = e
if f%2 ==0:
    f = 0
else:
    f = f
if g%2 ==0:
    g = 0
else:
    g = g
if h%2 ==0:
    h = 0
else:
    h = h
if i%2 ==0:
    i = 0
else:
    i = i
if j%2 ==0:
    j = 0
else:
    j = j

value = a, b, c, d, e, f, g, h, i, j
max = max(value)
if max ==0:
    print 'There are no odd numbers.'
else:
    print max, 'is the largest odd integer.'
</code>```

答:
A simple answer is :

```<code>x = 0
result = None;
while(x < 10):
  inputx = raw_input('Enter integer #%d: ' % x)
  inputx = int(inputx)
  if (inputx % 2 == 1):
    if(inputx > result):
       result = inputx
  x += 1
if result is None:
  print 'no odd number was entered'
else:
  print result
</code>```

Note: if enter a String like '3f',it will throw a ValueError:

```<code>invalid literal for int() with base 10: '3f'
</code>```

So finally ，the best anwser is

```<code>result = None
x = 0
while(x < 10):
  inputx = raw_input('Enter integer #%d: ' % x)
  try:
    inputx = int(inputx)
  except ValueError:
    print'you enter value ',inputx,' is not a Integer. please try again!'
    continue
  if (inputx % 2 == 1):
    if(inputx > result):
       result = inputx
  x+=1
if result is None:
  print 'no odd number was entered'
else:
  print 'the largest odd number is: ',result
</code>```

Title: Python, largest odd integer

Body:
I am new to coding and have been learning a few days now. I wrote this program in Python while following along in some MIT OpenCourseware lectures and a few books. Are there anyways to more easily express the program?

Finger exercise: Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.

a = int(raw_input('Enter your first integer: '))
b = int(raw_input('Enter your second integer: '))
c = int(raw_input('Enter your third integer: '))
d = int(raw_input('Enter your fourth integer: '))
e = int(raw_input('Enter your fifth integer: '))
f = int(raw_input('Enter your sixth integer: '))
g = int(raw_input('Enter your seventh integer: '))
h = int(raw_input('Enter your eighth integer: '))
i = int(raw_input('Enter your ninth integer: '))
j = int(raw_input('Enter your tenth integer: '))

if a%2 ==0:
    a = 0
else:
    a = a
if b%2 ==0:
    b = 0
else:
    b = b
if c%2 ==0:
    c = 0
else:
    c = c
if d%2 ==0:
    d = 0
else:
    d = d
if e%2 ==0:
    e = 0
else:
    e = e
if f%2 ==0:
    f = 0
else:
    f = f
if g%2 ==0:
    g = 0
else:
    g = g
if h%2 ==0:
    h = 0
else:
    h = h
if i%2 ==0:
    i = 0
else:
    i = i
if j%2 ==0:
    j = 0
else:
    j = j

value = a, b, c, d, e, f, g, h, i, j
max = max(value)
if max ==0:
    print 'There are no odd numbers.'
else:
    print max, 'is the largest odd integer.'

Body:
A simple answer is :

x = 0
result = None;
while(x < 10):
  inputx = raw_input('Enter integer #%d: ' % x)
  inputx = int(inputx)
  if (inputx % 2 == 1):
    if(inputx > result):
       result = inputx
  x += 1
if result is None:
  print 'no odd number was entered'
else:
  print result

Note: if enter a String like '3f',it will throw a ValueError:

invalid literal for int() with base 10: '3f'

So finally ，the best anwser is

result = None
x = 0
while(x < 10):
  inputx = raw_input('Enter integer #%d: ' % x)
  try:
    inputx = int(inputx)
  except ValueError:
    print'you enter value ',inputx,' is not a Integer. please try again!'
    continue
  if (inputx % 2 == 1):
    if(inputx > result):
       result = inputx
  x+=1
if result is None:
  print 'no odd number was entered'
else:
  print 'the largest odd number is: ',result


问:
Else after return from first part of an if statement
The implementation of library's BigInteger.gcd(...) method begins with these statements:

```<code>public BigInteger gcd(BigInteger val) {
    if (val.signum == 0)
        return this.abs();
    else if (this.signum == 0)
        return val.abs();
    ...
}
</code>```

What is the purpose of the else keyword in this case? Is it just a remnant of an old code that the programmer has forgotten to delete or it impacts performance in some way?

I understand that, semantically, the versions with and without else are identical in this particular case. Quite often, however, I face the choice between

```<code><Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    } else {
        <Long branch>
        return ...;
    }
}
</code>```

and

```<code><Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    }
    <Long branch>
    return ...;
}
</code>```

Which option is better in terms of performance (note that this question is Java-specific)? If performance is almost identical in both cases, which one is better in terms of readability?

答:
My $0.02 worth: when faced with a choice of either

```<code><Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    } else {
        <Long branch>
        return ...;
    }
}
</code>```

or

```<code><Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    }
    <Long branch>
    return ...;
}
</code>```

I like to go with option #3 whenever possible:

```<code><Some method signature>(...) {
    T result;
    if (...) {
        <Short branch>
        result = ...;
    } else {
        <Long branch>
        result = ...;
    }
    return result;
</code>```

For a simple case like this, I like having the single logical end of the method (i.e., the return statement) which coincides with its physical end.

More efficient?
Doubtful.

Less efficient? Probably not.

More readable? I think so, but I can neither guarantee you'll think so, nor prove that you should.

Just throwing it out there.

Body:
The implementation of library's BigInteger.gcd(...) method begins with these statements:

public BigInteger gcd(BigInteger val) {
    if (val.signum == 0)
        return this.abs();
    else if (this.signum == 0)
        return val.abs();
    ...
}

What is the purpose of the else keyword in this case? Is it just a remnant of an old code that the programmer has forgotten to delete or it impacts performance in some way?

I understand that, semantically, the versions with and without else are identical in this particular case. Quite often, however, I face the choice between

<Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    } else {
        <Long branch>
        return ...;
    }
}

and

<Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    }
    <Long branch>
    return ...;
}

Which option is better in terms of performance (note that this question is Java-specific)? If performance is almost identical in both cases, which one is better in terms of readability?

Body:
My $0.02 worth: when faced with a choice of either

<Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    } else {
        <Long branch>
        return ...;
    }
}

or

<Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    }
    <Long branch>
    return ...;
}

I like to go with option #3 whenever possible:

<Some method signature>(...) {
    T result;
    if (...) {
        <Short branch>
        result = ...;
    } else {
        <Long branch>
        result = ...;
    }
    return result;

For a simple case like this, I like having the single logical end of the method (i.e., the return statement) which coincides with its physical end.

More efficient?
Doubtful.

Less efficient? Probably not.

More readable? I think so, but I can neither guarantee you'll think so, nor prove that you should.

Just throwing it out there.


问:
What's the status of std::vector::data()?
I just realized that I've been using std::vector::data() out of similarity with std::string, but a colleague pointed out that it's not standard.

Apparently Gcc implements it, but looking at its include files, I found this comment:

```<code>  // _GLIBCXX_RESOLVE_LIB_DEFECTS
  // DR 464. Suggestion for new member functions in standard containers.
  // data access
</code>```

My questions are:

is this method widely implemented by other compilers?

is it included in C++0x?

(I also wonder what DR 464 is, and also _GLIBCXX_RESOLVE_LIB_DEFECTS for that matter, but I might as well ask another question for those).

答: I can't comment on current compiler implementations but by looking at the c++0x standard n3290.pdf it is listed at 23.3.6.4.</p>

Body:
I just realized that I've been using std::vector::data() out of similarity with std::string, but a colleague pointed out that it's not standard.

Apparently Gcc implements it, but looking at its include files, I found this comment:

  // _GLIBCXX_RESOLVE_LIB_DEFECTS
  // DR 464. Suggestion for new member functions in standard containers.
  // data access

My questions are:

is this method widely implemented by other compilers?

is it included in C++0x?

(I also wonder what DR 464 is, and also _GLIBCXX_RESOLVE_LIB_DEFECTS for that matter, but I might as well ask another question for those).


问:
How to list latest timestamps files from partial duplicate name
I have more than 10k  files like as given in below example. I would like to filter out partial duplicate i.e 123456 is common in all listed files which are consider to be duplicate and out of these duplicate files I need file of latest time stamps

```<code>   123456_20200425-012034.xml
   123456_20200424-120102.xml
   123456_20200425-121102.xml
   234567_20200323-112232.xml
   123456_20200423-111102.xml --- consider that this file is having latest
                                  timestamps out of all above duplicate file
</code>```

How to do it using bash ?

Also output should have files which are not duplicate. It means out of 10K files few files are not duplicate those files should include in output.

Output is require like (latest timestamps files)

```<code>123456_20200423-111102.xml
234567_20200323-112232.xml
</code>```

答:
I have done like this:

list=$(ls | awk -F _ '{print $1}' | uniq)

for i in $list
do
  mv "$(find . -type f -name "$i*" -print | sort -n -t _ -k 2 | tail -1)" ../destination
done
```

1) Stored uniq files in list

2) Executed list file in to loop, find latest timestamp file and move it to destination folder

Body:
I have more than 10k  files like as given in below example. I would like to filter out partial duplicate i.e 123456 is common in all listed files which are consider to be duplicate and out of these duplicate files I need file of latest time stamps

   123456_20200425-012034.xml
   123456_20200424-120102.xml
   123456_20200425-121102.xml
   234567_20200323-112232.xml
   123456_20200423-111102.xml --- consider that this file is having latest
                                  timestamps out of all above duplicate file

How to do it using bash ?

Also output should have files which are not duplicate. It means out of 10K files few files are not duplicate those files should include in output.

Output is require like (latest timestamps files)

123456_20200423-111102.xml
234567_20200323-112232.xml

Body:
I have done like this:

list=$(ls | awk -F _ '{print $1}' | uniq)

for i in $list
do
  mv "$(find . -type f -name "$i*" -print | sort -n -t _ -k 2 | tail -1)" ../destination
done

1) Stored uniq files in list

2) Executed list file in to loop, find latest timestamp file and move it to destination folder


问:
Pandas dataframe with multiindex column - change levels
source data：

pd.pivot_table(ceshi, values=['num1', 'num2'], index=['date'],
            columns=['c'], aggfunc={'num1': np.sum,'num2': np.sum}, fill_value=0)
```

how to  transform to?：

答:
Use DataFrame.swaplevel with DataFrame.sort_index:

```<code>df = pd.pivot_table(ceshi, values=['num1', 'num2'], index=['date'],
                   columns=['c'], aggfunc={'num1': np.sum,'num2': np.sum}, fill_value=0)
</code>```

And then:

```<code>df = df.swaplevel(1,0, axis=1).sort_index(axis=1)
</code>```

Body:
source data：

pd.pivot_table(ceshi, values=['num1', 'num2'], index=['date'],
            columns=['c'], aggfunc={'num1': np.sum,'num2': np.sum}, fill_value=0)

how to  transform to?：

Body:
Use DataFrame.swaplevel with DataFrame.sort_index:

df = pd.pivot_table(ceshi, values=['num1', 'num2'], index=['date'],
                   columns=['c'], aggfunc={'num1': np.sum,'num2': np.sum}, fill_value=0)

And then:

df = df.swaplevel(1,0, axis=1).sort_index(axis=1)