问:
How to close all other open sub-menu when other parent menu item is clicked?
I am using this code LINK.

When i click on Parent Menu like Services then sub-menu of services menu will be open but when i click on other menu then other sub menu will also open.
I want when i click on other sub menu then previous sub-menu will be close.
Kindly provide me solution for this.
Thank you

```<code> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
 <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js">
  </script>
  <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
 <!------ Include the above in your HEAD tag ---------->
 <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

 <div class="nav-side-menu">
<div class="brand">Brand Logo</div>
<i class="fa fa-bars fa-2x toggle-btn" data-toggle="collapse" data-target="#menu-content"></i>

    <div class="menu-list">

        <ul id="menu-content" class="menu-content collapse out">
            <li>
              <a href="#">
              <i class="fa fa-dashboard fa-lg"></i> Dashboard
              </a>
            </li>

            <li  data-toggle="collapse" data-target="#products" class="collapsed active">
              <a href="#"><i class="fa fa-gift fa-lg"></i> UI Elements <span class="arrow"></span></a>
            </li>
            <ul class="sub-menu collapse" id="products">
                <li class="active"><a href="#">CSS3 Animation</a></li>
                <li><a href="#">General</a></li>
                <li><a href="#">Buttons</a></li>
                <li><a href="#">Tabs & Accordions</a></li>
                <li><a href="#">Typography</a></li>
                <li><a href="#">FontAwesome</a></li>
                <li><a href="#">Slider</a></li>
                <li><a href="#">Panels</a></li>
                <li><a href="#">Widgets</a></li>
                <li><a href="#">Bootstrap Model</a></li>
            </ul>
            <li data-toggle="collapse" data-target="#service" class="collapsed">
              <a href="#"><i class="fa fa-globe fa-lg"></i> Services <span class="arrow"></span></a>
            </li>
            <ul class="sub-menu collapse" id="service">
              <li>New Service 1</li>
              <li>New Service 2</li>
              <li>New Service 3</li>
            </ul>
            <li data-toggle="collapse" data-target="#new" class="collapsed">
              <a href="#"><i class="fa fa-car fa-lg"></i> New <span class="arrow"></span></a>
            </li>
            <ul class="sub-menu collapse" id="new">
              <li>New New 1</li>
              <li>New New 2</li>
              <li>New New 3</li>
            </ul>
             <li>
              <a href="#">
              <i class="fa fa-user fa-lg"></i> Profile
              </a>
              </li>

             <li>
              <a href="#">
              <i class="fa fa-users fa-lg"></i> Users
              </a>
            </li>
        </ul>
      </div>
      </div>
</code>```

答:
Another version of code which works for me.

```<code>$(".submenu").not('.submenu-child').click(function()
{
    $(".submenu").not(this).find(".collapse").collapse('hide');

});
</code>```

Where submenu class is applied to parent menu and submenu-child class applied to submenus.

Body:
I am using this code LINK.

When i click on Parent Menu like Services then sub-menu of services menu will be open but when i click on other menu then other sub menu will also open.
I want when i click on other sub menu then previous sub-menu will be close.
Kindly provide me solution for this.
Thank you

 <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

 <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

Brand Logo

               Dashboard

               UI Elements

CSS3 Animation

General

Buttons

Tabs & Accordions

Typography

FontAwesome

Slider

Panels

Widgets

Bootstrap Model

               Services

New Service 1

New Service 2

New Service 3

               New

New New 1

New New 2

New New 3

               Profile

               Users

Body:
Another version of code which works for me.

$(".submenu").not('.submenu-child').click(function()
{
    $(".submenu").not(this).find(".collapse").collapse('hide');

});

Where submenu class is applied to parent menu and submenu-child class applied to submenus.


来源: stackexchange

问:
Why is map traversal sequential?
Isn't that out of order output
QAQ

this is my code

```<code>var i=map[int]int{
   1:1,
   2:2,
   3:3,
}
for i2, i3 := range i {
       fmt.Println(i2, i3)
}
</code>```

and the output is

```<code>1 1
2 2
3 3
</code>```

why?

答:
Go maps do not guarantee iteration order. In fact, the order may change from one iteration to the other, and the order of insertion and type-specific value order is not relevant. More info here:

https://blog.golang.org/go-maps-in-action

ContentLicense: CC BY-SA 4.0

Title: Why is map traversal sequential?

Body:
Isn't that out of order output
QAQ

this is my code

var i=map[int]int{
   1:1,
   2:2,
   3:3,
}
for i2, i3 := range i {
       fmt.Println(i2, i3)
}

and the output is

1 1
2 2
3 3

why?


问:
Export a CREATE script for a database
Say I've created a database in pgAdmin, but I want to export a CREATE sql file.

How would I go about generating the dump?

答:
To generate a sql script that will create the tables as they exist in a given database do:

pg_dump --schema-only --no-owner the_database > create_the_tables.sql

This will give you a bunch of create table statements. Just to see how portable it was I tried the above as follows:

```<code>bvm$ pg_dump -s --no-owner devdb | sqlite3 so_ans.db
</code>```

And then:

```<code>bvm$ sqlite3 so_ans.db .schema
CREATE TABLE courses (
    id integer NOT NULL,
    name text,
    created_by integer,
    jc text
);
</code>```

Kind of cool.

Title: Export a CREATE script for a database

Body:
To generate a sql script that will create the tables as they exist in a given database do:

pg_dump --schema-only --no-owner the_database > create_the_tables.sql

This will give you a bunch of create table statements. Just to see how portable it was I tried the above as follows:

bvm$ pg_dump -s --no-owner devdb | sqlite3 so_ans.db

And then:

bvm$ sqlite3 so_ans.db .schema
CREATE TABLE courses (
    id integer NOT NULL,
    name text,
    created_by integer,
    jc text
);

Kind of cool.

ContentLicense: CC BY-SA 3.0


问:
How to get application in AndroidUnitTest
In AndroidUnitTest I need Application to pass to the one of classes (Actually my network manager). How I can get running application?

I tried for

```<code>instrumentationapplication = InstrumentationRegistry.getInstrumentation().targetContext as Application
</code>```

But, I get cast error and it does not works.

答:
you could use

```<code>val application = androidx.test.core.app.ApplicationProvider.getApplicationContext() as MyApplication
</code>```

make sure you have the androidx test library dependencies.

Body:
In AndroidUnitTest I need Application to pass to the one of classes (Actually my network manager). How I can get running application?

I tried for

instrumentationapplication = InstrumentationRegistry.getInstrumentation().targetContext as Application

But, I get cast error and it does not works.

Body:
you could use

val application = androidx.test.core.app.ApplicationProvider.getApplicationContext() as MyApplication

make sure you have the androidx test library dependencies.


问:
Wake up Azure Function
I have an existing Azure Function that is on a consumption plan

I am writing another function which will call this

Once the existing function is running, it processes files in storage account.

In order the files in my storage account to be processed, we have to manually go into the portal and "wake up" the function by navigating

Is there a way to do this via C# code?

This function is hosted on a consumption based plan

答:
May be this is exact solution you are looking for. I came across this article "An Azure Function to keep other Functions/URLs warmed up" while looking for such solution, haven't tried it yet but I will. If you try it first do post the result.

https://www.sharepointnutsandbolts.com/2018/09/Azure-Function-Warmup-Cold-Start.html

The other approach that I came across is "pinging a health endpoint within your Azure Functions through Azure Monitor." Create a URL ping test. https://learn.microsoft.com/en-us/azure/azure-monitor/app/monitor-web-app-availability

I am in the process of trying these out. Hope this helps.

Title: Wake up Azure Function


问:
How to cache spacy model in gitlab runner when building docker image
I use docker and gitlab. My docker file is like this

```<code>FROM ubuntu:16.04
RUN apt-get update && apt-get install
RUN pip3 install wheel
RUN pip3 install spacy
RUN python3 -m spacy download en_core_web_md
</code>```

wheel and spacy packages are cached in the GitLab runner when I build the docker container, but not the spacy model.

Is there a way to cache the en_core_web_md model in the GitLab runner too, so that the model can be installed without downloading it again.

答:
Found the solution. Instead of installing the model using following command,

```<code>RUN python3 -m spacy download en_core_web_md
</code>```

First, you need to download the model

```<code>RUN pip3 download https://github.com/explosion/spacy-models/releases/download/en_core_web_md-2.2.0/en_core_web_md-2.2.0.tar.gz
</code>```

And then install it.

```<code>RUN pip3 install /en_core_web_md-2.1.0.tar.gz
</code>```

When you re-run the pipeline, model won't download again.

Body:
I use docker and gitlab. My docker file is like this

FROM ubuntu:16.04
RUN apt-get update && apt-get install
RUN pip3 install wheel
RUN pip3 install spacy
RUN python3 -m spacy download en_core_web_md

wheel and spacy packages are cached in the GitLab runner when I build the docker container, but not the spacy model.

Is there a way to cache the en_core_web_md model in the GitLab runner too, so that the model can be installed without downloading it again.

Body:
Found the solution. Instead of installing the model using following command,

RUN python3 -m spacy download en_core_web_md

First, you need to download the model

RUN pip3 download https://github.com/explosion/spacy-models/releases/download/en_core_web_md-2.2.0/en_core_web_md-2.2.0.tar.gz

And then install it.

RUN pip3 install /en_core_web_md-2.1.0.tar.gz

When you re-run the pipeline, model won't download again.


问:
Can't start docker on windows
I continue to get the following error when trying to start docker on Windows 10 pro.  my HyperV is turned on and running:
Version 18.04.0-ce-win62 (17151)
Channel: edge
e0a85f6

Any help would be appreciated!

Unable to create: The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Hyper-V encountered an error trying to access an object on computer 'C001715587' because the object was not found. The object might have been deleted. Verify that the Virtual Machine Management service on the computer is running.
at New-Switch, : line 117
at , : line 394
   at Docker.Core.Pipe.NamedPipeClient.Send(String action, Object[] parameters) in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Core\pipe\NamedPipeClient.cs:line 36
   at Docker.Actions.DoStart(SynchronizationContext syncCtx, Boolean showWelcomeWindow, Boolean executeAfterStartCleanup) in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Windows\Actions.cs:line 75
   at Docker.Actions.<>c__DisplayClass15_0.b__0() in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Windows\Actions.cs:line 59
   at Docker.WPF.TaskQueue.<>c__DisplayClass19_0.<.ctor>b__1() in C:\gopath\src\github.com\docker\pinata\win\src\Docker.WPF\TaskQueue.cs:line 59

答:
Try this. It's sorting the problem of many people.</p>

```<code>cd "C:\Program Files\Docker\Docker"
./DockerCli.exe -SwitchDaemon
</code>```

Title: Can't start docker on windows

Body:
Try this. It's sorting the problem of many people.

cd "C:\Program Files\Docker\Docker"
./DockerCli.exe -SwitchDaemon


问:
Twitter OAuth iPhone and Navigation Controllers
I'm new to Objective-C and iPhone programming so please bear with me. I am using the Twitter OAuth engine by bengottlieb and I can't figure out how to load the Login from a modal view or into a navigation controller.

This pushes the splash screen into the navigation controller but nothing else happens.

```<code>SA_OAuthTwitterController *twitterVC = [[SA_OAuthTwitterController alloc] init];
[self.navigationController pushViewController:twitterVC animated: YES];
</code>```

.. so I'm thinking I have to use something like this:

```<code>if(_engine)return;
    _engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];
    _engine.consumerKey    = kOAuthConsumerKey;
    _engine.consumerSecret = kOAuthConsumerSecret;

SA_OAuthTwitterController *twitterVC = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engine delegate:self];
[self.navigationController pushViewController:twitterVC animated: YES];
</code>```

(which does nothing)

Any help would be greatly appreciated.

答: After consulting with Ben himself, he said the twitter engine is not designed to be loaded from a modal or navigation view. My Twitter login page is not on the main view, but on a separate view so I used NSNotifications to pass data from a second view to the engine initialized on the first view.</p>

Body:
I'm new to Objective-C and iPhone programming so please bear with me. I am using the Twitter OAuth engine by bengottlieb and I can't figure out how to load the Login from a modal view or into a navigation controller.

This pushes the splash screen into the navigation controller but nothing else happens.

SA_OAuthTwitterController *twitterVC = [[SA_OAuthTwitterController alloc] init];
[self.navigationController pushViewController:twitterVC animated: YES];

.. so I'm thinking I have to use something like this:

if(_engine)return;
    _engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];
    _engine.consumerKey    = kOAuthConsumerKey;
    _engine.consumerSecret = kOAuthConsumerSecret;

SA_OAuthTwitterController *twitterVC = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engine delegate:self];
[self.navigationController pushViewController:twitterVC animated: YES];

(which does nothing)

Any help would be greatly appreciated.


问:
Click: "Got unexpected extra arguments" when passing string
```<code>import click

@cli.command()
@click.argument("namespace", nargs=1)
def process(namespace):
.....

@cli.command()
def run():
    for namespace in KEYS.iterkeys():
        process(namespace)
</code>```

Running run('some string') produces:

Error: Got unexpected extra arguments (o m e  s t r i n g)

As if Click passes string argument by one character. Printing an argument shows correct result.

PS: KEYS dictionary defined and working as expected.

答: Using the click module only in the main script which you run might help. In my case, removing click from modules other than the main helped solve this problem. </p>

Body:
import click

@cli.command()
@click.argument("namespace", nargs=1)
def process(namespace):
.....

@cli.command()
def run():
    for namespace in KEYS.iterkeys():
        process(namespace)

Running run('some string') produces:

Error: Got unexpected extra arguments (o m e  s t r i n g)

As if Click passes string argument by one character. Printing an argument shows correct result.

PS: KEYS dictionary defined and working as expected.


问:
How to use val instead of var in scala
I simply want to remove var and use Val instead in below code

```<code>def getConfigId: Long = {
val object1: java.util.List[objectA] = objectRepo.findByUser(User(session.id))

var object2: objectA = null
if (object1.size() == 1) {
  object2 = object1.get(0)
} else if (object1.size() > 1) {
  object2 = object1.get(0)
  object1.forEach(a => if (a.endDate.compareTo(object2.endDate) >= 0) {
    object2 = a
  })
}
object2.configId
}
</code>```

I am trying to use case match, but it's not working

```<code>def getConfigId: Long = {
val object1: java.util.List[objectA] = objectRepo.findByUser(User(session.id))

val object2: objectA = {
  case x if object1.size() == 1 => object1.get(0)

  case x => if (object1.size() > 1) {
    object1.get(0)
    object1.forEach(a => if(a.endDate.compareTo(object2.endDate) >= 0) {
     object2 = a
   })
}
</code>```

答:
if is an expression in Scala - it returns a resulting value. This means, you can keep your logic and simply assign the returned value of an if statement to the variable:

```<code>var object2: objectA = if (object1.size() == 1) {
    object1.get(0)
  } else if (object1.size() > 1) {
    object1
      .filter(a => (a.endDate.compareTo(object1.get(0).endDate) >= 0))
      .lastOption
      .orElse(Some(object1.get(0)))
      .get
  }
</code>```

Or even easier:

```<code>val object2 = object1
      .filter(a => (a.endDate.compareTo(object1.get(0).endDate) >= 0))
      .last
</code>```

Title: How to use val instead of var in scala

Body:
I simply want to remove var and use Val instead in below code

def getConfigId: Long = {
val object1: java.util.List[objectA] = objectRepo.findByUser(User(session.id))

var object2: objectA = null
if (object1.size() == 1) {
  object2 = object1.get(0)
} else if (object1.size() > 1) {
  object2 = object1.get(0)
  object1.forEach(a => if (a.endDate.compareTo(object2.endDate) >= 0) {
    object2 = a
  })
}
object2.configId
}

I am trying to use case match, but it's not working

def getConfigId: Long = {
val object1: java.util.List[objectA] = objectRepo.findByUser(User(session.id))

val object2: objectA = {
  case x if object1.size() == 1 => object1.get(0)

  case x => if (object1.size() > 1) {
    object1.get(0)
    object1.forEach(a => if(a.endDate.compareTo(object2.endDate) >= 0) {
     object2 = a
   })
}

Body:
if is an expression in Scala - it returns a resulting value. This means, you can keep your logic and simply assign the returned value of an if statement to the variable:

var object2: objectA = if (object1.size() == 1) {
    object1.get(0)
  } else if (object1.size() > 1) {
    object1
      .filter(a => (a.endDate.compareTo(object1.get(0).endDate) >= 0))
      .lastOption
      .orElse(Some(object1.get(0)))
      .get
  }

Or even easier:

val object2 = object1
      .filter(a => (a.endDate.compareTo(object1.get(0).endDate) >= 0))
      .last


问:
how to sort list in alphabetical order in python?
I have a program where I take in a txt file and break up the text into individual words and puts them into a list. the next part is to sort the list alphabetically and print it.

so far I have a text file that just says:
 "the quick brown fox jumps over the lazy dog"

and my program so far looks like:

```<code>file = input("Enter File Name: ")
myList =[]

readFile = open(file, 'r')

for line in readFile:
    myList.append(line.split(" "))

myList.sort()

print(myList)
</code>```

the problem is that when I run the program the list is being created and filled with each word but when it is printed out it is not being sorted in alphabetical order. I also tried print(myList.sort()) and the only thing that prints is "none"

答:
From what I observed the problem is your list of words is in a list,

myList = [["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]].

So instead of

```<code>for line in readFile:
    myList.append(line.split(" "))
</code>```

You should be writing

```<code>for line in readFile:
    myList = line.split(" "))
</code>```

Body:
I have a program where I take in a txt file and break up the text into individual words and puts them into a list. the next part is to sort the list alphabetically and print it.

so far I have a text file that just says:
 "the quick brown fox jumps over the lazy dog"

and my program so far looks like:

file = input("Enter File Name: ")
myList =[]

readFile = open(file, 'r')

for line in readFile:
    myList.append(line.split(" "))

myList.sort()

print(myList)

the problem is that when I run the program the list is being created and filled with each word but when it is printed out it is not being sorted in alphabetical order. I also tried print(myList.sort()) and the only thing that prints is "none"

Body:
From what I observed the problem is your list of words is in a list,

myList = [["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]].

So instead of

for line in readFile:
    myList.append(line.split(" "))

You should be writing

for line in readFile:
    myList = line.split(" "))


问:
Same class on parent and child element for navigation ".nav-links" - Looking for best CSS solution
I have to create left section for a website ".leftpart" in which I have parent navigation class ".nav-links" with CSS properties. I have also have same class ".nav-links" as a sub section under parent ".nav-links". I want to give a different background color "red" to child ".nav-links" [Edit and Save]. Can you anyone suggest best way to do this ?

My code is below, thanks in advance :

.leftpart {
          width: 100%;
          display: block;
          margin: 20px;
        }

        .leftpart .nav-links ul {
          list-style: none;
          margin: 0;
          padding: 0;
          display: block;
        }

        .leftpart .nav-links ul li {
          margin-bottom:20px;
        }

        .leftpart .nav-links ul li a {
           background:green;
           color:#fff;
           padding: 20px;
           display: inline-block;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="leftpart">
        <div class="nav-links">
          <h1> Primary Links </h1>
          <ul>
            <li>
              Profile
            </li>

            <li>
              Friends
            </li>

            <li>
              Milestones
            </li>

            <li>
              Groups
            </li>
          </ul>

          <div class="sub-seciton">
              <div class="nav-links">
                <ul>
                  <li>
                    Edit
                  </li>

                  <li>
                    Save
                  </li>
                </ul>
              </div>
          </div>

        </div>

        <div class="nav-links">
          <h1> Secondary Links </h1>
          <ul>
            <li>
              Privacy
            </li>

            <li>
              Settings
            </li>
          </ul>
        </div>
    </div></code>```

答:
.leftpart {
          width: 100%;
          display: block;
          margin: 20px;
        }

      .leftpart .sub-seciton>.nav-links ul li:nth-child(1) a,
      .leftpart .sub-seciton>.nav-links ul li:nth-child(2) a{
          background:red;
        }

        .leftpart .nav-links ul {
          list-style: none;
          margin: 0;
          padding: 0;
          display: block;
        }

        .leftpart .nav-links ul li {
          margin-bottom:20px;
        }

        .leftpart .nav-links ul li a {
           background:green;
           color:#fff;
           padding: 20px;
           display: inline-block;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="leftpart">
        <div class="nav-links">
          <h1> Primary Links </h1>
          <ul>
            <li>
              Profile
            </li>

            <li>
              Friends
            </li>

            <li>
              Milestones
            </li>

            <li>
              Groups
            </li>
          </ul>

          <div class="sub-seciton">
              <div class="nav-links">
                <ul>
                  <li>
                    Edit
                  </li>

                  <li>
                    Save
                  </li>
                </ul>
              </div>
          </div>

        </div>

        <div class="nav-links">
          <h1> Secondary Links </h1>
          <ul>
            <li>
              Privacy
            </li>

            <li>
              Settings
            </li>
          </ul>
        </div>
    </div></code>```

Body:
I have to create left section for a website ".leftpart" in which I have parent navigation class ".nav-links" with CSS properties. I have also have same class ".nav-links" as a sub section under parent ".nav-links". I want to give a different background color "red" to child ".nav-links" [Edit and Save]. Can you anyone suggest best way to do this ?

My code is below, thanks in advance :

.leftpart {
          width: 100%;
          display: block;
          margin: 20px;
        }

        .leftpart .nav-links ul {
          list-style: none;
          margin: 0;
          padding: 0;
          display: block;
        }

        .leftpart .nav-links ul li {
          margin-bottom:20px;
        }

        .leftpart .nav-links ul li a {
           background:green;
           color:#fff;
           padding: 20px;
           display: inline-block;
        }

 Primary Links

              Profile

              Friends

              Milestones

              Groups

                    Edit

                    Save

 Secondary Links

              Privacy

              Settings

Body:
.leftpart {
          width: 100%;
          display: block;
          margin: 20px;
        }

      .leftpart .sub-seciton>.nav-links ul li:nth-child(1) a,
      .leftpart .sub-seciton>.nav-links ul li:nth-child(2) a{
          background:red;
        }

        .leftpart .nav-links ul {
          list-style: none;
          margin: 0;
          padding: 0;
          display: block;
        }

        .leftpart .nav-links ul li {
          margin-bottom:20px;
        }

        .leftpart .nav-links ul li a {
           background:green;
           color:#fff;
           padding: 20px;
           display: inline-block;
        }

<div class="leftpart">
        <div class="nav-links">
          <h1> Primary Links </h1>
          <ul>
            <li>
              <a href="/profile.html">Profile</a>
            </li>

            <li>
              <a href="/friends.html">Friends</a>
            </li>

            <li>
              <a href="/milestone.html">Milestones</a>
            </li>

            <li>
              <a href="/groups.html">Groups</a>
            </li>
          </ul>

          <div class="sub-seciton">
              <div class="nav-links">
                <ul>
                  <li>
                    <a href="#">Edit</a>
                  </li>

                  <li>
                    <a href="#">Save</a>
                  </li>
                </ul>
              </div>
          </div>

        </div>

        <div class="nav-links">
          <h1> Secondary Links </h1>
          <ul>
            <li>
              <a href="/privacy.html">Privacy</a>
            </li>

            <li>
              <a href="/settings.html">Settings</a>
            </li>
          </ul>
        </div>
    </div>


问:
use multiple api docs for swagger in node js?
I have given versioned my API for a project. so it has two folders v1 and v2  which has diffrent apis. Now in ordrer to implement swagger for v1 and v2 i have written below code in app.js.

```<code>// Swagger definition
// You can set every attribute except paths and swagger
const swaggerDefinition = {
    swagger: '2.0',
    info: {
        // API informations (required)
        title: 'API', // Title (required)
        version: '1.0.0', // Version (required)
        description: 'Used for  api documentation', // Description (optional)
    },
    host: `localhost:3000`, // Host (optional)
    basePath: '/v1', // Base path (optional)
};

// Options for the swagger docs
const optionsV1 = {
    // Import swaggerDefinitions
    swaggerDefinition,
    // Path to the API docs
    // Note that this path is relative to the current directory from which the Node.js is ran, not the application itself.
    apis: ['./app/v1/docs/*.yaml']
};

const optionsV2 = {
    // Import swaggerDefinitions
    swaggerDefinition,
    // Path to the API docs
    // Note that this path is relative to the current directory from which the Node.js is ran, not the application itself.
    apis: ['./app/v2/docs/*.yaml']
};
optionsV2.swaggerDefinition.basePath = "/v2"
// Initialize swagger-jsdoc -> returns validated swagger spec in json format
const swaggerSpecV1 = swaggerJSDoc(optionsV1);
const swaggerSpecV2 = swaggerJSDoc(optionsV2);
// const swaggerDocument = require('./app/v1/docs/swagger.json');
// app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use('/v1/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpecV1));
app.use('/v2/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpecV2));
</code>```

but the if i hit url as /v1/docs or /v2/docs it always show me the api doc for v2. so the last line written here for v2 so it always showing doc for v2 only. Please suggests how to support multiple api?

答:
Try the following configuration:</p>

```<code>app.use('/v1/docs', swaggerUi.serve, (...args) => swaggerUI.setup(swaggerSpecV1)(...args));
app.use('/v2/docs', swaggerUi.serve, (...args) => swaggerUI.setup(swaggerSpecV2)(...args));
</code>```

Body:
I have given versioned my API for a project. so it has two folders v1 and v2  which has diffrent apis. Now in ordrer to implement swagger for v1 and v2 i have written below code in app.js.

// Swagger definition
// You can set every attribute except paths and swagger
const swaggerDefinition = {
    swagger: '2.0',
    info: {
        // API informations (required)
        title: 'API', // Title (required)
        version: '1.0.0', // Version (required)
        description: 'Used for  api documentation', // Description (optional)
    },
    host: `localhost:3000`, // Host (optional)
    basePath: '/v1', // Base path (optional)
};

// Options for the swagger docs
const optionsV1 = {
    // Import swaggerDefinitions
    swaggerDefinition,
    // Path to the API docs
    // Note that this path is relative to the current directory from which the Node.js is ran, not the application itself.
    apis: ['./app/v1/docs/*.yaml']
};

const optionsV2 = {
    // Import swaggerDefinitions
    swaggerDefinition,
    // Path to the API docs
    // Note that this path is relative to the current directory from which the Node.js is ran, not the application itself.
    apis: ['./app/v2/docs/*.yaml']
};
optionsV2.swaggerDefinition.basePath = "/v2"
// Initialize swagger-jsdoc -> returns validated swagger spec in json format
const swaggerSpecV1 = swaggerJSDoc(optionsV1);
const swaggerSpecV2 = swaggerJSDoc(optionsV2);
// const swaggerDocument = require('./app/v1/docs/swagger.json');
// app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use('/v1/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpecV1));
app.use('/v2/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpecV2));

but the if i hit url as /v1/docs or /v2/docs it always show me the api doc for v2. so the last line written here for v2 so it always showing doc for v2 only. Please suggests how to support multiple api?

Body:
Try the following configuration:

app.use('/v1/docs', swaggerUi.serve, (...args) => swaggerUI.setup(swaggerSpecV1)(...args));
app.use('/v2/docs', swaggerUi.serve, (...args) => swaggerUI.setup(swaggerSpecV2)(...args));


问:
How can I return custom error message for error status code 401 in .Net Core?
Please help me to display a custom error message for an error status code 401 in .Net Core WebApi. </p>

答:
The ASP Core documentation explains how to handle custom error responses:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1#usestatuscodepages

In your case, you could try app.UseStatusCodePages in your startup Configure method(add a reference to Microsoft.AspNetCore.Http)

```<code>if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseHsts();
}
app.UseStatusCodePages(async context =>
{
    if (context.HttpContext.Response.StatusCode == 401)
    {
        await context.HttpContext.Response.WriteAsync("Custom Unauthorized request");
    }
});
//other middlewars
</code>```

Action:

```<code>[HttpGet]
public ActionResult Get()
{
   return Unauthorized();
}
</code>```

Body:
The ASP Core documentation explains how to handle custom error responses:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1#usestatuscodepages

In your case, you could try app.UseStatusCodePages in your startup Configure method(add a reference to Microsoft.AspNetCore.Http)

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseHsts();
}
app.UseStatusCodePages(async context =>
{
    if (context.HttpContext.Response.StatusCode == 401)
    {
        await context.HttpContext.Response.WriteAsync("Custom Unauthorized request");
    }
});
//other middlewars

Action:

[HttpGet]
public ActionResult Get()
{
   return Unauthorized();
}


问:
Use two RecyclerView with different adapter inside NestedScrollView load very slowly
I need to use two RecyclerView with different Adapter in the same view.

My First RecyclerView will load just once in onCreate.

My Second RecyclerView will load more and more data when user scroll to bottom and call the api to get new data.

When I let my Second RecyclerView call the api to load more and more data, it will load very slowly and scroll heavy.

How can I fix that, thank you!

Here is my fragment:

```<code>public class NewFragment extends Fragment {

    private void setRecyclerAndAdapter(){
        if(swipeRefreshLayout != null && postRecycler != null){

            layoutManager = new LinearLayoutManager(context);
            postRecycler.setLayoutManager(layoutManager);

            LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_up_to_down);
            postRecycler.setLayoutAnimation(animationController);

            if(postAdAdapter == null){
                postAdAdapter = new PostCardAdapter(context, postDataList);
                postRecycler.setAdapter(postAdAdapter);

                setListener();
            }else{
                postAdAdapter.notifyDataSetChanged();
            }
        }else
            return;
    }
.
    private void setListener(){
        if(swipeRefreshLayout != null && postRecycler != null){

            ......

            nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
                @Override
                public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if(v.getChildAt(v.getChildCount() - 1) != null) {
                        if ((scrollY >= (v.getChildAt(v.getChildCount() - 1).getMeasuredHeight() - v.getMeasuredHeight())) &&
                                scrollY > oldScrollY) {

                            visibleItemCount = layoutManager.getChildCount();
                            totalItemCount = layoutManager.getItemCount();
                            pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();

                            if(controlCanGetMorePostData == true){
                                controlCanGetMorePostData = false;

                                if(postAdAdapter != null){
                                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                                        postAdAdapter.setLoadState(postAdAdapter.LOADING);
                                        callApiManagerGetMoreData();
                                    }
                                }else
                                    return;
                            }
                            else{
                                hasMorePostData = false;
                                setMoreDataState();
                            }
                        }
                    }
                }
            });
        }else
            return;
    }

}
</code>```

Here is my Layout:

```<code><androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/fragment_new_swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/fragment_new_nestedScroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            android:scrollbars="none">

                <GridLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:columnCount="1"
                    android:rowCount="2">

                        <RelativeLayout
                            android:id="@+id/fragment_new_banner_content"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_row="0">

                                <androidx.recyclerview.widget.RecyclerView
                                    android:id="@+id/fragment_new_first_recycler"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:scrollbars="vertical" />

                                <com.gmpsykr.each.Game.BannerIndicator
                                    android:id="@+id/fragment_new_banner_indicator"
                                    android:layout_width="match_parent"
                                    android:layout_height="32dp"
                                    android:layout_alignBottom="@+id/fragment_new_banner_recycler"
                                    app:selectColor="@color/colorAccent"
                                    app:unselectedColor="#ffffff"
                                    app:radius="3dp"
                                    app:space="10dp" />

                        </RelativeLayout>

                        <androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/fragment_new_second_recycler"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layoutAnimation="@anim/layout_animation_up_to_down"
                            android:layout_row="1" />

                </GridLayout>

        </androidx.core.widget.NestedScrollView>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</code>```

答:
```<code><androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fragment_new_swipe_refresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:orientation="vertical">

                                <RelativeLayout
                                    android:layout_width="match_parent"
                                    android:layout_height="50dp"
                                    android:background="@color/colorAppPrimaryRed" />

                                <androidx.recyclerview.widget.RecyclerView
                                    android:id="@+id/fragment_new_recycler"
                                    android:layout_width="match_parent"
                                    android:layout_height="match_parent"
                                    android:nestedScrollingEnabled="false"
                                    android:layoutAnimation="@anim/layout_animation_up_to_down" />

                        </LinearLayout>

        </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</code>```

Body:
I need to use two RecyclerView with different Adapter in the same view.

My First RecyclerView will load just once in onCreate.

My Second RecyclerView will load more and more data when user scroll to bottom and call the api to get new data.

When I let my Second RecyclerView call the api to load more and more data, it will load very slowly and scroll heavy.

How can I fix that, thank you!

Here is my fragment:

public class NewFragment extends Fragment {

    private void setRecyclerAndAdapter(){
        if(swipeRefreshLayout != null && postRecycler != null){

            layoutManager = new LinearLayoutManager(context);
            postRecycler.setLayoutManager(layoutManager);

            LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_up_to_down);
            postRecycler.setLayoutAnimation(animationController);

            if(postAdAdapter == null){
                postAdAdapter = new PostCardAdapter(context, postDataList);
                postRecycler.setAdapter(postAdAdapter);

                setListener();
            }else{
                postAdAdapter.notifyDataSetChanged();
            }
        }else
            return;
    }
.
    private void setListener(){
        if(swipeRefreshLayout != null && postRecycler != null){

            ......

            nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
                @Override
                public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if(v.getChildAt(v.getChildCount() - 1) != null) {
                        if ((scrollY >= (v.getChildAt(v.getChildCount() - 1).getMeasuredHeight() - v.getMeasuredHeight())) &&
                                scrollY > oldScrollY) {

                            visibleItemCount = layoutManager.getChildCount();
                            totalItemCount = layoutManager.getItemCount();
                            pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();

                            if(controlCanGetMorePostData == true){
                                controlCanGetMorePostData = false;

                                if(postAdAdapter != null){
                                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                                        postAdAdapter.setLoadState(postAdAdapter.LOADING);
                                        callApiManagerGetMoreData();
                                    }
                                }else
                                    return;
                            }
                            else{
                                hasMorePostData = false;
                                setMoreDataState();
                            }
                        }
                    }
                }
            });
        }else
            return;
    }

}

Here is my Layout:

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/fragment_new_swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/fragment_new_nestedScroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            android:scrollbars="none">

                <GridLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:columnCount="1"
                    android:rowCount="2">

                        <RelativeLayout
                            android:id="@+id/fragment_new_banner_content"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_row="0">

                                <androidx.recyclerview.widget.RecyclerView
                                    android:id="@+id/fragment_new_first_recycler"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:scrollbars="vertical" />

                                <com.gmpsykr.each.Game.BannerIndicator
                                    android:id="@+id/fragment_new_banner_indicator"
                                    android:layout_width="match_parent"
                                    android:layout_height="32dp"
                                    android:layout_alignBottom="@+id/fragment_new_banner_recycler"
                                    app:selectColor="@color/colorAccent"
                                    app:unselectedColor="#ffffff"
                                    app:radius="3dp"
                                    app:space="10dp" />

                        </RelativeLayout>

                        <androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/fragment_new_second_recycler"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layoutAnimation="@anim/layout_animation_up_to_down"
                            android:layout_row="1" />

                </GridLayout>

        </androidx.core.widget.NestedScrollView>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>


问:
Why can't I save data in plist file with Swift
** the readData.plist is:**

```<code>
  <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>currentChapter</key>
    <string>2</string>
    <key>currentLine</key>
    <string>2</string>
    <key>bookname</key>
    <string>ExcelBible</string>
</dict>
</plist>

</code>```

** The following is code:**

```<code>
        let Chapter = currentChapter
        let Line = currentLine
        let name = bookname

        let dict:NSMutableDictionary = NSMutableDictionary()

        dict.setObject("1", forKey: "currentChapter" as NSCopying)
        dict.setObject("1", forKey: "currentLine" as NSCopying)
        dict.setObject("WordBible", forKey: "bookname" as NSCopying)

        //I also use dict[0] = "1", and setValue() method both of them are not work

        let plistPath = Bundle.main.path(forResource: "readData", ofType: "plist")

        dict.write(toFile: plistPath!, atomically: true)

</code>```

Blockquote
     I also use FileManager and several examples here to save data, some display "Successfully write", but the file does't change.

Blockquote

I am an iOS developer since Feb 12, 2020

答:
Blockquote

I used the following code, but it does't work too.

Blockquote

```<code>
let currentChapter = "10"
let currentLine = "10"
let nameOfBook = "WordBible"

let readData = [currentChapter, currentLine, nameOfBook]
//

let dataFilePaths = FileManager.default.urls(for: .documentDirectory,
                                             in: .userDomainMask)[0].appendingPathComponent("gameSave.plist")

let data = try PropertyListEncoder().encode(readData)

try? data.write(to: dataFilePaths, options: Data.WritingOptions.atomic)
</code>```

Body:
** the readData.plist is:**

  <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>currentChapter</key>
    <string>2</string>
    <key>currentLine</key>
    <string>2</string>
    <key>bookname</key>
    <string>ExcelBible</string>
</dict>
</plist>

** The following is code:**

        let Chapter = currentChapter
        let Line = currentLine
        let name = bookname

        let dict:NSMutableDictionary = NSMutableDictionary()

        dict.setObject("1", forKey: "currentChapter" as NSCopying)
        dict.setObject("1", forKey: "currentLine" as NSCopying)
        dict.setObject("WordBible", forKey: "bookname" as NSCopying)

        //I also use dict[0] = "1", and setValue() method both of them are not work

        let plistPath = Bundle.main.path(forResource: "readData", ofType: "plist")

        dict.write(toFile: plistPath!, atomically: true)

Blockquote
     I also use FileManager and several examples here to save data, some display "Successfully write", but the file does't change.

Blockquote

I am an iOS developer since Feb 12, 2020

Body:
Blockquote

I used the following code, but it does't work too.

Blockquote

let currentChapter = "10"
let currentLine = "10"
let nameOfBook = "WordBible"

let readData = [currentChapter, currentLine, nameOfBook]
//

let dataFilePaths = FileManager.default.urls(for: .documentDirectory,
                                             in: .userDomainMask)[0].appendingPathComponent("gameSave.plist")

let data = try PropertyListEncoder().encode(readData)

try? data.write(to: dataFilePaths, options: Data.WritingOptions.atomic)


问:
Runtime analysis of dependent nested for
0

Here is the algorithm:

```<code>int sum = 0
for (int i = 2N; i > 0; i = i / 4)
  for (int j = 0; j < i; j+=2)
    sum++
  end for
end for
</code>```

I figured this would be linearithmic, but it's just linear. I would appreciate seeing a formalized summation and not a qualitative explanation. I have tried doing this but I fail to get linear runtime.

答:
Since you requested a formalized summation only; please note that the number of operations of your algorithm can be modeled by the series:

Which converges to:

(This can be validated by using the geometric series test).

So your algorithm's time complexity is O(N).

Body:
0

Here is the algorithm:

int sum = 0
for (int i = 2N; i > 0; i = i / 4)
  for (int j = 0; j < i; j+=2)
    sum++
  end for
end for

I figured this would be linearithmic, but it's just linear. I would appreciate seeing a formalized summation and not a qualitative explanation. I have tried doing this but I fail to get linear runtime.


问:
jquery select after all elements with certain class
I have a few divs with the same class.  The divs are generated dynamically, so I don't always know the exact number of these divs.

I want to place another div after the last div.

```<code><div class="someclassname">content here</div>
<div class="someclassname">content here</div>
<div class="someclassname">content here</div>
</code>```

When I do this:

```<code>$('.someclassname').after('place another div here');
</code>```

It places it after each one.
Is there a way to select the last div with .someclassname?

答:
```<code>$('.someclassname:last').after('place another div here');
</code>```

Body:
I have a few divs with the same class.  The divs are generated dynamically, so I don't always know the exact number of these divs.

I want to place another div after the last div.

content here

content here

content here

When I do this:

$('.someclassname').after('place another div here');

It places it after each one.
Is there a way to select the last div with .someclassname?


问:
How to show my path in my branching QUIZ on JavaScript?
I saw this question and made my QUIZ based on it. Could you please tell me how to print the path the user has followed? I want to write further conditions, for example, if a user walked on path 23, then show him such a picture.

My QUIZ

var questions = {
  "text": "Why, besides the obvious are you buying wine today?",
  "choices": [{
      "label": "For a party",
      "path": 1,
      "question": {
        "text": "For party...", //1 a
        "choices": [{
            "label": "It's a game day baby!",
            "path": 11
          },
          {
            "label": "It's Kelly's Bach party!",
            "path": 12
          },
        ]
      }
    },
    {
      "label": "As a gift",
      "path": 2,
      "question": {
        "text": "How much do you wanna spend?", //1 b
        "choices": [{
            "label": "$",
            "path": 21,
          },
          {
            "label": "$$",
            "path": 22,
            "question": {
              "text": "You sure? It this for...", //1 a
              "choices": [{
                  "label": "Your yoga instructor Namaste",
                  "path": 221
                },
                {
                  "label": "A spouse/significant other",
                  "path": 222
                },
                {
                  "label": "Your boss / a client",
                  "path": 223
                },
              ]
            }
          },
          {
            "label": "$$$",
            "path": 23
          },
        ]
      }
    },
  ]
};

   ```

答:
As you have a path value for each answers, you can just refer to the the last selected answer. so after the quiz complete:</p>

```<code>alert("you have chosen the path:" + currentObj.choices[value].path );
</code>```

Body:
As you have a path value for each answers, you can just refer to the the last selected answer. so after the quiz complete:

alert("you have chosen the path:" + currentObj.choices[value].path );


问:
Does spark write dataframes asynchronously
I have two spark dataframes df1 and df2.  I'm trying to write them out to two different file paths.  Can someone tell me, do the writes occur synchronously or asynchronously?  That is since they're two different dataframes writting to two different paths, will the writes occur at the same time, or do I have to wait until it finishes writing df1 out before it starts writing df2 out?

example code:

update added importing libraries:

```<code>import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

glueContext = GlueContext(SparkContext.getOrCreate())

# updated 11/19/19 for error caused in error logging function
spark = glueContext.spark_session

from pyspark.sql import Window
from pyspark.sql.functions import col
from pyspark.sql.functions import first
from pyspark.sql.functions  import date_format
from pyspark.sql.functions import lit,StringType
from pyspark.sql.types import *
from pyspark.sql.functions import substring, length, min,when,format_number,dayofmonth,hour,dayofyear,month,year,weekofyear,date_format,unix_timestamp
import time
import math

df1.write.mode("overwrite").parquet(filepath1)

df2.write.mode("overwrite").parquet(filepath2)
</code>```

答: If its on single thread it will write one at a time. You can use threding and share the spark Context.</p>

Body:
I have two spark dataframes df1 and df2.  I'm trying to write them out to two different file paths.  Can someone tell me, do the writes occur synchronously or asynchronously?  That is since they're two different dataframes writting to two different paths, will the writes occur at the same time, or do I have to wait until it finishes writing df1 out before it starts writing df2 out?

example code:

update added importing libraries:

import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

glueContext = GlueContext(SparkContext.getOrCreate())

# updated 11/19/19 for error caused in error logging function
spark = glueContext.spark_session

from pyspark.sql import Window
from pyspark.sql.functions import col
from pyspark.sql.functions import first
from pyspark.sql.functions  import date_format
from pyspark.sql.functions import lit,StringType
from pyspark.sql.types import *
from pyspark.sql.functions import substring, length, min,when,format_number,dayofmonth,hour,dayofyear,month,year,weekofyear,date_format,unix_timestamp
import time
import math

df1.write.mode("overwrite").parquet(filepath1)

df2.write.mode("overwrite").parquet(filepath2)


问:
Compare two files(file1 & file2) and add one column from from file2 to file1 if first column of two files matches
I have two files (file1 and file2)

file1

```<code>ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/abc/patch142007
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/def/patch143005
DEF=14.3.0.5.SAMPLE2=git.calypso/plugins/gitiles/+/refs/heads/clientpatch/def/patch14300-calib
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/hij/patch120000sp3
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/mno/patch161028
</code>```

.......(150 lines)

file2

```<code>IJK = open
ABC = closed
PQR = closed
DEF = open
HIJ = open
LMN = closed
MNO = closed
PQR = open
</code>```

......(> 150 lines)

output file

```<code>ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/abc/patch142007=closed
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/def/patch143005=open
DEF=14.3.0.5.SAMPLE2=git.xyz/plugins/gitiles/+/refs/heads/client/def/patch14300-calib=open
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/client/hij/patch120000sp3=open
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/mno/patch161028=closed
</code>```

I have tried the following script. But it is not giving me any output. Not even printing anything. No errors

```<code>while IFS= read -r line
do
key1=`echo $line | awk -F "=" '{print $1}'` < file1
key2=`echo $line | awk -F "=" '{print $2}'` < file1
key3=`echo $line | awk -F "=" '{print $3}'` < file1
key4=`echo $line | awk -F "=" '{print $1}'` < file2
value3=`echo $line | awk -F "=" '{print $2}'` < file2
if [ "$key1" == "$key4" ]; then
echo "$key1=$key2=$key3=$value3"
fi
done
</code>```

Giving a brief description for how the code should work.

The code should compare first columns of two files(file1 and file2). If each name matches it should give me output file as listed above. Else go to the next line. I should get output if my two files are either in sorted or unsorted format.
Helps will be appreciated. Thank you

答:
Could you please try following.

```<code>awk '
BEGIN{
  OFS="="
}
FNR==NR{
  a[$1]=$NF
  next
}
($1 in a){
  print $0,a[$1]
}
'   Input_file2  FS="="  Input_file1
</code>```

Explanation: Adding detailed explanation for above code.

```<code>awk '                   ##Starting awk program from here.
BEGIN{                  ##Starting BEGIN section from here.
  OFS="="               ##Setting OFS as = here for all lines.
}
FNR==NR{                ##Checking condition if FNR==NR which will be TRUE when file2 is being read.
  a[$1]=$NF             ##Creating an array a with index $1 and value is last field.
  next                  ##next will skip all further statements from here.
}
($1 in a){              ##Checking condition if $1 of current line is present in array a then do following.
  print $0,a[$1]        ##Printing current line and value of array a with index $1.
}
'  file2 FS="=" file1   ##Mentioning Input_file file2 and file1 and setting FS="=" for file1 here.
</code>```

Body:
I have two files (file1 and file2)

file1

ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/abc/patch142007
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/def/patch143005
DEF=14.3.0.5.SAMPLE2=git.calypso/plugins/gitiles/+/refs/heads/clientpatch/def/patch14300-calib
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/hij/patch120000sp3
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/mno/patch161028

.......(150 lines)

file2

IJK = open
ABC = closed
PQR = closed
DEF = open
HIJ = open
LMN = closed
MNO = closed
PQR = open

......(> 150 lines)

output file

ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/abc/patch142007=closed
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/def/patch143005=open
DEF=14.3.0.5.SAMPLE2=git.xyz/plugins/gitiles/+/refs/heads/client/def/patch14300-calib=open
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/client/hij/patch120000sp3=open
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/mno/patch161028=closed

I have tried the following script. But it is not giving me any output. Not even printing anything. No errors

while IFS= read -r line
do
key1=`echo $line | awk -F "=" '{print $1}'` < file1
key2=`echo $line | awk -F "=" '{print $2}'` < file1
key3=`echo $line | awk -F "=" '{print $3}'` < file1
key4=`echo $line | awk -F "=" '{print $1}'` < file2
value3=`echo $line | awk -F "=" '{print $2}'` < file2
if [ "$key1" == "$key4" ]; then
echo "$key1=$key2=$key3=$value3"
fi
done

Giving a brief description for how the code should work.

The code should compare first columns of two files(file1 and file2). If each name matches it should give me output file as listed above. Else go to the next line. I should get output if my two files are either in sorted or unsorted format.
Helps will be appreciated. Thank you

Body:
Could you please try following.

awk '
BEGIN{
  OFS="="
}
FNR==NR{
  a[$1]=$NF
  next
}
($1 in a){
  print $0,a[$1]
}
'   Input_file2  FS="="  Input_file1

Explanation: Adding detailed explanation for above code.

awk '                   ##Starting awk program from here.
BEGIN{                  ##Starting BEGIN section from here.
  OFS="="               ##Setting OFS as = here for all lines.
}
FNR==NR{                ##Checking condition if FNR==NR which will be TRUE when file2 is being read.
  a[$1]=$NF             ##Creating an array a with index $1 and value is last field.
  next                  ##next will skip all further statements from here.
}
($1 in a){              ##Checking condition if $1 of current line is present in array a then do following.
  print $0,a[$1]        ##Printing current line and value of array a with index $1.
}
'  file2 FS="=" file1   ##Mentioning Input_file file2 and file1 and setting FS="=" for file1 here.


问:
Timing this programs duration while it runs
Here's the entire program, but I'm trying to figure out how to time it (days:hours:minutes:seconds) if at all possible. It is written in Python.</p>

```<code>import random

x = 1
attempt = 0
while x ==1:
  rand1 = random.randint(1,1000)
  rand2 = random.randint(1,1000)
  attempt = attempt + 1
  if rand1 ==rand2:
    x=2
    print(rand1)
    print(rand2)
    print("Match Found.")
  else:
    print(rand1)
    print(rand2)
    print("Trying again.")
print("")
print("It took ", attempt," attempts to find a matching number.")
#for x in range(10):
# rand1 = random.randint(1,101)
# print(rand1)
# ignore the googol that's what I'm using when I figure out how to time it -> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
</code>```

答:
The better code:</p>

```<code>import random
import time
from datetime import datetime
from datetime import timedelta
print('Current time: %s' % datetime. now())

attempt = 0
start_time = time.time()
while 1:
  rand1 = random.randint(1,1000)
  rand2 = random.randint(1,1000)
  attempt += 1
  if rand1 == rand2:
    print(rand1)
    print(rand2)
    print("Match Found.", end = '\n\n')
    break
  else:
    print(rand1)
    print(rand2)
    print("Trying again.", end = '\n\n')
print("It took %s attempts to find a matching number." % attempt)
print("It took %s to finish" % str(timedelta(seconds=(time.time() - start_time))))
</code>```

Body:
Here's the entire program, but I'm trying to figure out how to time it (days:hours:minutes:seconds) if at all possible. It is written in Python.

import random

x = 1
attempt = 0
while x ==1:
  rand1 = random.randint(1,1000)
  rand2 = random.randint(1,1000)
  attempt = attempt + 1
  if rand1 ==rand2:
    x=2
    print(rand1)
    print(rand2)
    print("Match Found.")
  else:
    print(rand1)
    print(rand2)
    print("Trying again.")
print("")
print("It took ", attempt," attempts to find a matching number.")
#for x in range(10):
# rand1 = random.randint(1,101)
# print(rand1)
# ignore the googol that's what I'm using when I figure out how to time it -> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Body:
The better code:

import random
import time
from datetime import datetime
from datetime import timedelta
print('Current time: %s' % datetime. now())

attempt = 0
start_time = time.time()
while 1:
  rand1 = random.randint(1,1000)
  rand2 = random.randint(1,1000)
  attempt += 1
  if rand1 == rand2:
    print(rand1)
    print(rand2)
    print("Match Found.", end = '\n\n')
    break
  else:
    print(rand1)
    print(rand2)
    print("Trying again.", end = '\n\n')
print("It took %s attempts to find a matching number." % attempt)
print("It took %s to finish" % str(timedelta(seconds=(time.time() - start_time))))