问:
how do i change the .innerHTML of a html page after a link has been clicked on a different html page?
i have a problem i am trying to solve. i am trying to recreate the music video page (page 1) of Capital dreams pictures here is the page. the issue have now is that, when you click on the play button, it takes you to a different video page (page 2) corresponding to the link clicked here is the link for that. i don't want to single handedly code that page (page 2) for each of the link on the music video page (page 1). is there a way i can change the content of (page 2) when i click the play button link on (page 1).

here is the code for (Page 1). N.B i render the images using javascript

```<code><body class="body">
    <header>
        <p>your logo</p>
        <nav class="navbar">
            <ul class="nav-menu">
                <li class="nav-item"><a href="video.html" class="nav-link">Home</a></li>
                <li class="nav-item"><a href="musicvid.html" class="nav-link">Music Videos</a></li>
                <li class="nav-item"><a href="film.html" class="nav-link">Film</a></li>
                <li class="nav-item"><a href="showreels.html" class="nav-link">Show Reels</a></li>
                <li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li>
            </ul>
        </nav>
        <div class="burger">
            <div class="line1"></div>
            <div class="line2"></div>
            <div class="line3"></div>
        </div>
    </header>
    <h3>
        <p>music videos</p>
    </h3>
    <main>
        <section  class="dera">
            <!--------------------render images here hopefully -------------->
        </section>
    </main>

    <footer>
        <p>
            Copyright Simple <small>2021 - </small>
        <small id="demo"> </small>
        </p>
    </footer>
    <script>
        const d = new Date ();
        document.getElementById("demo").innerHTML = d.getFullYear();
    </script>
    <script src="array.js"></script>
    <script src="video.js"></script>
    </body>
</code>```

here is the html for (page 2)

```<code><body>
    <header>
        <p>your logo</p>
        <nav class="navbar">
            <ul class="nav-menu">
                <li class="nav-item"><a href="video.html" class="nav-link">Home</a></li>
                <li class="nav-item"><a href="musicvid.html" class="nav-link">Music Videos</a></li>
                <li class="nav-item"><a href="film.html" class="nav-link">Film</a></li>
                <li class="nav-item"><a href="showreels.html" class="nav-link">Show Reels</a></li>
                <li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li>
            </ul>
        </nav>
        <div class="burger">
            <div class="line1"></div>
            <div class="line2"></div>
            <div class="line3"></div>
        </div>
    </header>
    <h3>
        <p>video name here</p>
    </h3>

    <main>
    <div class="container">
        <div class="videocontainer">
            <iframe width="700" height="700"
            src="https://www.youtube.com/embed/OFKBep95lb4" title="YouTube video player"
            frameborder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowfullscreen>
            </iframe>
        </div>

        <div class="cat-container">
            <div class="cart-contain">
                <div class="category">
                    <p><b>category</b>: <span>Music Videos</span></p>
                </div>
                <div class="date">
                    <p><b>date</b>: <span>December 31, 2020</span></p>
                </div>
            </div>
        </div>
    </div>
    </main>
    <section>
        <div class="join">
            <p>previous</p>
            <i class="fab fa-instagram"></i>
            <p>next</p>
        </div>
    </section>
    <footer>
        <p>
            Copyright Simple <small>2021 - </small>
            <small id="demo"> </small>
        </p>
        <a href="music-page.html"><i class="fas fa-play"></i></a>
    </footer>
    <script>
        const d = new Date();
        document.getElementById("demo").innerHTML = d.getFullYear();
    </script>
    <script src="array.js"></script>
    <script src="video.js"></script>
</code>```

the array

```<code> const images = [
    {
        id: 0,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 1,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 2,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 3,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 4,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 5,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 6,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 7,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 8,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 9,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 10,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 11,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 12,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 13,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 14,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 15,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 16,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 17,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },
]

const images1 = [
    {
        id: 0,
        chidera: "https://www.youtube.com/embed/OFKBep95lb4",
    },

    {
        id: 1,
        chidera: "https://www.youtube.com/embed/JqFrYYIKl_4",
    },

    {
        id: 2,
        chidera: "https://www.youtube.com/embed/OFKBep95lb4"
    },

]
</code>```

the javascript

```<code>// select elements
    const burger =  document.querySelector(".burger");
    const navMenu = document.querySelector(".nav-menu");
    const navLink = document.querySelectorAll(".nav-link")

    burger.addEventListener("click",   function () {
   //toggles the burger
    burger.classList.toggle("is-active");

   //toggles the nav menu
    navMenu.classList.toggle("active");
});
    //removes well, you should know
    navLink.forEach(n =>  n.addEventListener("click", function () {
  burger.classList.remove("is-active");
  navMenu.classList.remove("active");
}))

//wahala dey to render images like this. somebody save me!!!!!!!!!
//this actually worked
    const dera = document.querySelector(".dera");
    const videoContainer = document.querySelector(".videocontainer");

    function renderImages() {
    images.forEach((image) => {
    dera.innerHTML += `<div>
                <!--------render images   here hopefully -->
                <img  src="${image.imgsrc}" alt="">
                <p>${image.videoName}</p>
                <samp> Music Videos </samp>
                <a href="${image.href}" ><i class="fas fa-play fa-3x"></i></a>
            </div>
            `
  })
}
    renderImages();

    //when users click on the play button,
    //i want to change the .innerHTML of the music video page :)
    //for music page thing
    //this is a massive fail tho
    console.log(videoContainer)
    const playButton = document.getElementsByTagName("i");
    const arr = [...playButton];
    console.log(arr)
    arr.forEach((button) => {
  button.addEventListener("click",  function () {
     images1.forEach((_thing) => {
      if (image.id === _thing.id) {
        videoContainer.innerHTML += `
            <iframe width="700"  height="700"
            src="${_thing.chidera}" title="YouTube video player"
            frameborder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowfullscreen>
            </iframe>
    `
      }
      else {
        alert('jdhcodshdioshdioES')
      }
    })
  })
  });
</code>```

please, how do i go about it? Thank you :)

答:
If I'm interpreting your question correctly, you want to have 1 page that displays a music video, but make it dynamic so that you dont need to make separate documents for each one. Traditionally this would be solved by server side rendering with a video id in the url query string, but you could also do it on the client using javascript.

For example you could have a page http://localhost/video.html, and pass in the exact video you want to display in the Query String (i.e. http://localhost/video.html?id=15). You can then use the javascript to get the id from the url like so:

const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');
```

Body:
i have a problem i am trying to solve. i am trying to recreate the music video page (page 1) of Capital dreams pictures here is the page. the issue have now is that, when you click on the play button, it takes you to a different video page (page 2) corresponding to the link clicked here is the link for that. i don't want to single handedly code that page (page 2) for each of the link on the music video page (page 1). is there a way i can change the content of (page 2) when i click the play button link on (page 1).

here is the code for (Page 1). N.B i render the images using javascript

your logo

Home

Music Videos

Film

Show Reels

Contact

music videos

            Copyright Simple 2021 -

here is the html for (page 2)

your logo

Home

Music Videos

Film

Show Reels

Contact

video name here

category: Music Videos

date: December 31, 2020

previous

next

            Copyright Simple 2021 -

the array

 const images = [
    {
        id: 0,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 1,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 2,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 3,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 4,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 5,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 6,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 7,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 8,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 9,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 10,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 11,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 12,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 13,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 14,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 15,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 16,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },

    {
        id: 17,
        videoName: "patoranking song",
        category: "first",
        href: "music-page.html",
        imgsrc: "img/background.jpg",
    },
]

const images1 = [
    {
        id: 0,
        chidera: "https://www.youtube.com/embed/OFKBep95lb4",
    },

    {
        id: 1,
        chidera: "https://www.youtube.com/embed/JqFrYYIKl_4",
    },

    {
        id: 2,
        chidera: "https://www.youtube.com/embed/OFKBep95lb4"
    },

]

the javascript

// select elements
    const burger =  document.querySelector(".burger");
    const navMenu = document.querySelector(".nav-menu");
    const navLink = document.querySelectorAll(".nav-link")

    burger.addEventListener("click",   function () {
   //toggles the burger
    burger.classList.toggle("is-active");

   //toggles the nav menu
    navMenu.classList.toggle("active");
});
    //removes well, you should know
    navLink.forEach(n =>  n.addEventListener("click", function () {
  burger.classList.remove("is-active");
  navMenu.classList.remove("active");
}))

//wahala dey to render images like this. somebody save me!!!!!!!!!
//this actually worked
    const dera = document.querySelector(".dera");
    const videoContainer = document.querySelector(".videocontainer");

    function renderImages() {
    images.forEach((image) => {
    dera.innerHTML += `

${image.videoName}

                <samp> Music Videos </samp>

            `
  })
}
    renderImages();

    //when users click on the play button,
    //i want to change the .innerHTML of the music video page :)
    //for music page thing
    //this is a massive fail tho
    console.log(videoContainer)
    const playButton = document.getElementsByTagName("i");
    const arr = [...playButton];
    console.log(arr)
    arr.forEach((button) => {
  button.addEventListener("click",  function () {
     images1.forEach((_thing) => {
      if (image.id === _thing.id) {
        videoContainer.innerHTML += `

    `
      }
      else {
        alert('jdhcodshdioshdioES')
      }
    })
  })
  });

please, how do i go about it? Thank you :)


来源: stackexchange

问:
Custom Gradle Plugin based ZipTask in Java
I want to create a custom Gradle Plugin in Java which will only create a Zip task.

The DSL version is as follow:

```<code>task _3_buildZip(type: Zip) {
   from compileJava
   from processResources
   into('lib') {
      from configurations.runtimeClasspath
      from('build.properties')
   }
}
</code>```

So far I've created the following code which is not working :-(

```<code>import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.tasks.bundling.Zip;

public class ZipTaskPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {

        Zip zipTask = project.getTasks().create("HelloZipWorld",Zip.class);
        zipTask.from(project.getComponents().getByName("java"));
        zipTask.from(project.getComponents().getByName("resources"));
        zipTask.into("lib").from(project.getConfigurations());

    }
}
</code>```

Please advise

答:
I finally got the solution myself. I'm sharing it here for the everyone.</p>
```<code>import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.CopySpec;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.tasks.bundling.Zip;

public class ZipTaskPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {

        Zip task= project.getTasks().create( "HelloZipWorld", Zip.class );

        task.into(task.getArchiveFileName().get(), (CopySpec copySpec) ->{
                    copySpec.into("lib")
                            .from(project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME))
                            .from("build.properties");
                })
                .from(project.getTasks().getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME))
                .from(project.getTasks().getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME))
        ;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to create a custom Gradle Plugin in Java which will only create a Zip task.

The DSL version is as follow:

task _3_buildZip(type: Zip) {
   from compileJava
   from processResources
   into('lib') {
      from configurations.runtimeClasspath
      from('build.properties')
   }
}

So far I've created the following code which is not working :-(

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.tasks.bundling.Zip;

public class ZipTaskPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {

        Zip zipTask = project.getTasks().create("HelloZipWorld",Zip.class);
        zipTask.from(project.getComponents().getByName("java"));
        zipTask.from(project.getComponents().getByName("resources"));
        zipTask.into("lib").from(project.getConfigurations());

    }
}

Please advise

Body:
I finally got the solution myself. I'm sharing it here for the everyone.

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.CopySpec;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.tasks.bundling.Zip;

public class ZipTaskPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {

        Zip task= project.getTasks().create( "HelloZipWorld", Zip.class );

        task.into(task.getArchiveFileName().get(), (CopySpec copySpec) ->{
                    copySpec.into("lib")
                            .from(project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME))
                            .from("build.properties");
                })
                .from(project.getTasks().getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME))
                .from(project.getTasks().getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME))
        ;
    }
}


问:
How to git add all files excluding a certain folder, from anywhere in a repo?
I would like to create an alias that adds all modified files to the staging area, excluding any changes in extern/.

git add . will add all modified files and git add --all -- ':!extern/*' will add all modified files except anything in extern/. But that will only work if you are in the same directory as the extern (at the top level of the repo) folder. I don't know how to do this from anywhere in the repo, like from several directories deep.

I was wondering if there was an elegant way to reference the top level of the repo i.e. something like git add --all -- ':![top_level_of_repo]/extern/*'.

答:
You can use the -C argument to git to change directory, and use git rev-parse to get the top level of the repository:

```<code>git -C $(git rev-parse --show-toplevel) add --all -- ':!extern/*'
</code>```

...or, having just read the gitglossary(7) entry on pathspec, it looks like you could actually just write:

```<code>git add --all -- ':!/extern/*'
</code>```

Body:
You can use the -C argument to git to change directory, and use git rev-parse to get the top level of the repository:

git -C $(git rev-parse --show-toplevel) add --all -- ':!extern/*'

...or, having just read the gitglossary(7) entry on pathspec, it looks like you could actually just write:

git add --all -- ':!/extern/*'


问:
How can I dispay the data in django admin panel
I am creating an eCommerce website but I want to know how can I display a product_name or customer_name in the admin panel.

The concept is that if a customer places an order that it will go to the admin panel. So the other details are displaying properly except product_name or customet_name.

As shown in the below image:

models.py

```<code>class Order(models.Model):
        product = models.ForeignKey(Product, on_delete=models.CASCADE)
        customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
        quantity = models.IntegerField(default=1)
        address = models.CharField(max_length=50, default='', blank=True)
        phone = models.CharField(max_length=50, default='', blank=True)
        price = models.IntegerField()
        date = models.DateField(default=datetime.datetime.today)
        status = models.BooleanField(default=False)
</code>```

admin.py

```<code>class AdminOrders(admin.ModelAdmin):
    list_display = ['product', 'customer', 'quantity', 'address', 'phone', 'price', 'date', 'status']
</code>```

答:
If you call a function it have to return string if you want to display as word.
I know 2 ways to do this
First its repr Method

```<code>def __repr__(self):
     return self.(Model You wanna Display)
</code>```

or str Witch is akcually same

```<code>def __str__(self):
     return self.(Model You wanna Display)

</code>```

Body:
I am creating an eCommerce website but I want to know how can I display a product_name or customer_name in the admin panel.

The concept is that if a customer places an order that it will go to the admin panel. So the other details are displaying properly except product_name or customet_name.

As shown in the below image:

models.py

class Order(models.Model):
        product = models.ForeignKey(Product, on_delete=models.CASCADE)
        customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
        quantity = models.IntegerField(default=1)
        address = models.CharField(max_length=50, default='', blank=True)
        phone = models.CharField(max_length=50, default='', blank=True)
        price = models.IntegerField()
        date = models.DateField(default=datetime.datetime.today)
        status = models.BooleanField(default=False)

admin.py

class AdminOrders(admin.ModelAdmin):
    list_display = ['product', 'customer', 'quantity', 'address', 'phone', 'price', 'date', 'status']

Body:
If you call a function it have to return string if you want to display as word.
I know 2 ways to do this
First its repr Method

def __repr__(self):
     return self.(Model You wanna Display)

or str Witch is akcually same

def __str__(self):
     return self.(Model You wanna Display)


问:
Angular 5 Material Spinner is not working
Angular 5 Material Spinner is not working

app.module.ts

```<code>import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
@NgModule({
  imports: [
    MatProgressSpinnerModule
  ]})
</code>```

component.ts

```<code>import { MatSpinner } from '@angular/material';
</code>```

component.html

```<code><mat-spinner></mat-spinner>
</code>```

am I missing any configuration.?

In Reference, it's generating an SVG file for Spinner but I don't see anything inside mat-spinner tag.

答:
For me, the imports were correct, but I overlooked an error message in the console, regarding missing angular core theme.

Importing a theme in the main style.scss file solved that for me.
@import "@angular/material/prebuilt-themes/deeppurple-amber.css";

ContentLicense: CC BY-SA 3.0

Body:
Angular 5 Material Spinner is not working

app.module.ts

import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
@NgModule({
  imports: [
    MatProgressSpinnerModule
  ]})

component.ts

import { MatSpinner } from '@angular/material';

component.html

<mat-spinner></mat-spinner>

am I missing any configuration.?

In Reference, it's generating an SVG file for Spinner but I don't see anything inside mat-spinner tag.


问:
Typescript narrowing of keys in objects when passed to function
Why does TypeScript not apply type narrowing on members of objects to the object type itself, such that it can be passed to another function that expects a narrowed type? How can this be fixed/circumvented without loosing typesafety?

Minimal example:

type A = { key: string | null};
type B = {key: string};

function func(a: B) {};

const a: A = {key:'abcd'};
if(typeof(a.key)==='string') {
  a.key // has (narrowed) type 'string'
  func(a); // still does not work
}
```

The error message is: Types of property 'key' are incompatible. Type 'string | null' is not assignable to type 'string'.

Playground-Link

答:
What if you wanted to narrow from any property of an object based off a given type? @gwin-pin had the starter, but here it is:

```<code>const isValidPropType = <T extends Record<P, T[P]>, P extends keyof T, Z extends T[P]>(
  object: T,
  prop: P,
  typeofParam: Z
): object is T & Record<P, Z> => {
  return typeof object[prop] === typeof typeofParam;
};
</code>```

TS Playground using the original question.

Body:
Why does TypeScript not apply type narrowing on members of objects to the object type itself, such that it can be passed to another function that expects a narrowed type? How can this be fixed/circumvented without loosing typesafety?

Minimal example:

type A = { key: string | null};
type B = {key: string};

function func(a: B) {};

const a: A = {key:'abcd'};
if(typeof(a.key)==='string') {
  a.key // has (narrowed) type 'string'
  func(a); // still does not work
}

The error message is: Types of property 'key' are incompatible. Type 'string | null' is not assignable to type 'string'.

Playground-Link

Body:
What if you wanted to narrow from any property of an object based off a given type? @gwin-pin had the starter, but here it is:

const isValidPropType = <T extends Record<P, T[P]>, P extends keyof T, Z extends T[P]>(
  object: T,
  prop: P,
  typeofParam: Z
): object is T & Record<P, Z> => {
  return typeof object[prop] === typeof typeofParam;
};

TS Playground using the original question.


问:
Jenkins Pipeline from SCM. Can we select branch
We have our pipelines groovy scripts for Jenkins in SCM (git). I believe it currently gets the scripts from master as default.
Are we able to specify the branch we want to use for the groovy scripts?
There is a setting in the particular section but that seems to be for build branch if I understand correctly (as it allows for setting of multiple branches)</p>

答:
It appears that the branch option is the branch for the pipeline script.

I assume that multiple branches means you can run multiple branches of the different versions of that script. I suspect I am missing when that would be used but it does answer my original question.


问:
how to keep agora from showing sensitive user data in the browser console

Here you can see that in the console you can see the memberId as their email address. Any way to hide that or remove these updates from the console? I get them anytime someone enters or leaves a group chat.

答:
For agora 4.x sdk;
according to documentation at https://docs.agora.io/en/Interactive%20Broadcast/API%20Reference/web_ng/interfaces/iagorartc.html#setloglevel</p>
```<code>AgoraRTC.setLogLevel(1);

The output log level.

0: DEBUG. Output all API logs.
1: INFO. Output logs of the INFO, WARNING and ERROR level.
2: WARNING. Output logs of the WARNING and ERROR level.
3: ERROR. Output logs of the ERROR level.
4: NONE. Do not output any log.
</code>```

Body:
For agora 4.x sdk;
according to documentation at https://docs.agora.io/en/Interactive%20Broadcast/API%20Reference/web_ng/interfaces/iagorartc.html#setloglevel

AgoraRTC.setLogLevel(1);

The output log level.

0: DEBUG. Output all API logs.
1: INFO. Output logs of the INFO, WARNING and ERROR level.
2: WARNING. Output logs of the WARNING and ERROR level.
3: ERROR. Output logs of the ERROR level.
4: NONE. Do not output any log.


问:
Runtime Code Coverage Tools
I know that there are a number of tools for analysing .NET code and calculating the coverage, plus identifying classes/methods/properties etc that are never going to be hit.

However, I am trying to clean-up a legacy application that I am certain contains an amount of unused code - however a lot of code is accessed via some arbitrary and complex reflection tecniques that will disguise the intent to the compiler - thererfore any coverage tool that only analyses the compiled code is unlikely to generate any reliable reports on code useage within this application.

Are there any tools that work rather like profilers, whereby they listen to a running application and log what classes/methods/properties are actually hit and generate the coverage based on this data.

I hope Ive made everything clear - thanks in anticipation

答:
You can use the VS2010 Code Coverage tools - they do use Instrumentation (which means reflection won't trick it). Syed Aslam Basha has a post on it in his MSDN blog on how to enable it for manual testing (which it sounds like you will need to do).

Just remember you will need to click every feature etc. while its running; or just think twice before deleting code - but it should give you a good starting point.

Title: Runtime Code Coverage Tools


问:
How to insert records in related tables with the ContentValues method
I'm trying to insert data into related tables, but I've searched many forums and no option works for me, I'm just starting out with this.

The tables are the following:

Table 1:

```<code>form CREATE TABLE(
  form_id int(11) PRIMARY KEY,
  dateCreation date NOT NULL);
</code>```

tables 2:

```<code>create table form_mvdrecinto(
id_mvdrecinto INTEGER PRIMARY KEY AUTOINCREMENT,
fk_form_id int(11) not null,
long varchar(20) not null,
FOREIGN KEY(id_formulario_fk) REFERENCES form(id_form));
</code>```

In the save method is where I have the problem, specifically in the ContentValues, how the exact statement should be in my case to insert the data in both related tables.

Thank you.

答:
The method is the convenience insert method which simplifies the construction of INSERT SQL statements based upon a ContentValues.

SQL does not allow the insertion of rows into multiple tables. So you cannot insert into both tables in a single use of the insert method. Furthermore the insertion into the form_mvdrecinto requires you to know the value of the foreign key.

First you have various problems with the SQL.

I believe that you need/want something like ():-

```<code>CREATE TABLE IF NOT EXISTS form /* TABLE NAME AFTER, NOT BEFORE THE CREATE KEYWORD/CLAUSE */(form_id int(11) PRIMARY KEY, dateCreation date NOT NULL);
CREATE TABLE IF NOT EXISTS form_mvdrecinto(
    id_mvdrecinto INTEGER PRIMARY KEY AUTOINCREMENT,
    fk_form_id int(11) not null,
    long varchar(20) not null,
    FOREIGN KEY (fk_form_id /*<<<<< MUST BE A COLUMN IN THE TABLE */) REFERENCES form(form_id /*<<<<< pretty sureyou want to reference form_id column not the non-existent id_form column*/)
);
</code>```

Assuming What you would do as an example is to have a method based upon:-

```<code>void saveFormWithRelatedFormmvdrecinto(long formId, String date, String _long) {
    ContentValues cv = new ContentValues();
    cv.put("form_id,formId);
    cv.put("date",date);
    db.insert("form",null,cv);
    cv.clear();
    cv.put("fk_form_id",formId);
    cv.put("long",_long);
    db.insert("form_mvdrecinto",null,cv);
}
</code>```

obviously db is an SQLiteDatabase.

due to the ForeignKey constraint the form must be inserted prior to the formmvdrecinto (or formmvdrecintos are inserted).

As the SQLiteDatabase insert Method uses INSERT OR IGNORE ...., the above could be used for an existing form, it would simply ignore inserting the duplicate form and then continue to insert the formmdvrecinto.

It appears that you may have the misconception that FOREIGN KEY builds relationships automatically. It DOES NOT (it cannot) you have to indicate the actual relationship. FOREIGN KEY is a constraint, a rule, that says that the column(s) in the table with the foreign key MUST contain a value that exists in the REFRENECED column(s) in the REFRENCED TABLE otherwise a conflict (failure) will result. INSERT OR IGNORE does not ignore such a conflict.

Demonstration

The following is a working demonstration based upon the tables above. In addition to using a known form id for the insertion of form_mvdrecinto rows (it ads 2 such rows). It also demonstrates a more precarious insertion based upon the dateCreated (if not unique then the form_mvdrecinto inserted will be an arbritary row where the datecreated is matched).

First most of the code is in the DatabaseHelper class it being :-

```<code>class DatabaseHelper extends SQLiteOpenHelper {

   public static final String DATABASE_NAME = "the_database.db";
   public static final int DATABASE_VERSION = 1;
   public static final String FORM_TABLE = "form";
   public static final String COL_FORM_FORMID = "form_id";
   public static final String COL_FORM_DATECREATION = "date_creation";
   public static final String FORM_MVDRECINTO_TABLE = "form_mvdrecinto";
   public static final String COL_FORMMVDRECINTO_FORMMVDRECINTO_ID = "id_mvdrecinto";
   public static final String COL_FORMMVDRECINTO_FK_FORM_ID = "fk_form_id";
   public static final String COL_FORMMVDRECINTO_LONG = "long";

   private static volatile DatabaseHelper instance = null;
   private SQLiteDatabase db;

   private DatabaseHelper(Context context) {
      super(context, DATABASE_NAME,null, DATABASE_VERSION);
      db = this.getWritableDatabase();
      /* By defauly Foreign Keys are not turned no, so turn them on */
      db.setForeignKeyConstraintsEnabled(true);
   }

   public static DatabaseHelper getInstance(Context context) {
      if (instance == null) {
         instance = new DatabaseHelper(context);
      }
      return instance;
   }

   @Override
   public void onCreate(SQLiteDatabase db) {
      db.execSQL(
              "CREATE TABLE IF NOT EXISTS " + FORM_TABLE + " ("
                      + COL_FORM_FORMID + " INTEGER PRIMARY KEY "
                      +"," + COL_FORM_DATECREATION + " date NOT NULL"
                      + ");"
      );
      db.execSQL(
              "CREATE TABLE IF NOT EXISTS " + FORM_MVDRECINTO_TABLE +"("
                      + COL_FORMMVDRECINTO_FORMMVDRECINTO_ID + " INTEGER PRIMARY KEY"
                      + "," + COL_FORMMVDRECINTO_FK_FORM_ID + " INTEGER NOT NULL"
                      + "," + COL_FORMMVDRECINTO_LONG + " TEXT NOT NULL"
                      + ", FOREIGN KEY (" + COL_FORMMVDRECINTO_FK_FORM_ID + ") REFERENCES " + FORM_TABLE + "(" + COL_FORM_FORMID + ")"
                      + ");"
      );
   }

   public long insertForm(Long id, String dateCreated) {
      ContentValues cv = new ContentValues();
      if (id != null && id > 0) {
         cv.put(COL_FORM_FORMID,id);
      }
      cv.put(COL_FORM_DATECREATION,dateCreated);
      return db.insert(FORM_TABLE,null,cv);
   }

   public long insertForm(String dateCreated) {
      return insertForm(null,dateCreated);
   }

   public long insertFormMVDRecinto(Long id, long form_id, String _long) {
      ContentValues cv = new ContentValues();
      if (id != null && id > 0) {
         cv.put(COL_FORMMVDRECINTO_FORMMVDRECINTO_ID,id);;
      }
      cv.put(COL_FORMMVDRECINTO_FK_FORM_ID,form_id);
      cv.put(COL_FORMMVDRECINTO_LONG,_long);
      return db.insert(FORM_MVDRECINTO_TABLE,null,cv);
   }

   public long insertFormMVDRecinto(long form_id, String _long) {
      return insertFormMVDRecinto(null,form_id,_long);
   }

   @SuppressLint("Range")
   public long insertFormMVDRecinto(Long id, String dateCreated, String _long) {
      long rv = -1;
      Cursor csr = db.query(FORM_TABLE,new String[]{COL_FORM_FORMID},COL_FORM_DATECREATION + "=?",new String[]{dateCreated},null,null,null,"1");
      if (csr.moveToFirst()) {
         rv = insertFormMVDRecinto(id,csr.getLong(csr.getColumnIndex(COL_FORM_FORMID)),_long);
      }
      return rv;
   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int i, int i1) {

   }
}
</code>```

To actually demonstrate the following MainActivity is an activity which :-

Adds 3 Form rows

Adds 3 Form_mvdrecinto rows

The first two being added using the known form_id.

The last is added according to a known dateCreated value.

Tries to add a 4th Form_mdvrecinto row BUT with a dateCreated that IS NOT in any rows (due to the no row being extracted the attempt to insert a row which would result in a FK conflict is not attempted).

:-

```<code>public class MainActivity extends AppCompatActivity {

    DatabaseHelper dbhelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbhelper = DatabaseHelper.getInstance(this);

        long f1 = dbhelper.insertForm(10L,"2021-02-10 10:21:13"); /* id will be 10 */
        long f2 = dbhelper.insertForm("2021-02-10 11:13:55"); /* id will probably be 11 */
        long f3 = dbhelper.insertForm(1000l,"2021-02-10 09:00:00");

        long fm1 = dbhelper.insertFormMVDRecinto(f1,"Blah001");
        long fm2 = dbhelper.insertFormMVDRecinto(100l,f1,"Blah002");

        /* WARNING if more than 1 form with 2021-02-10 09:00:00 then could be related to any 1 */
        long fm3 = dbhelper.insertFormMVDRecinto(null,"2021-02-10 09:00:00","Blah003");
        /* WILL NOT INSERT as no such dateCreated value in the Form table*/
        /* does not attempt to insert into the Form_mdvrecinto because the row is not found/extracted */
        long fm4 = dbhelper.insertFormMVDRecinto(null,"NOT A DATE THAT WOULD EXIST","Blah004");
    }
}
</code>```

Body:
I'm trying to insert data into related tables, but I've searched many forums and no option works for me, I'm just starting out with this.

The tables are the following:

Table 1:

form CREATE TABLE(
  form_id int(11) PRIMARY KEY,
  dateCreation date NOT NULL);

tables 2:

create table form_mvdrecinto(
id_mvdrecinto INTEGER PRIMARY KEY AUTOINCREMENT,
fk_form_id int(11) not null,
long varchar(20) not null,
FOREIGN KEY(id_formulario_fk) REFERENCES form(id_form));

In the save method is where I have the problem, specifically in the ContentValues, how the exact statement should be in my case to insert the data in both related tables.

Thank you.

Body:
The method is the convenience insert method which simplifies the construction of INSERT SQL statements based upon a ContentValues.

SQL does not allow the insertion of rows into multiple tables. So you cannot insert into both tables in a single use of the insert method. Furthermore the insertion into the form_mvdrecinto requires you to know the value of the foreign key.

First you have various problems with the SQL.

I believe that you need/want something like ():-

CREATE TABLE IF NOT EXISTS form /* TABLE NAME AFTER, NOT BEFORE THE CREATE KEYWORD/CLAUSE */(form_id int(11) PRIMARY KEY, dateCreation date NOT NULL);
CREATE TABLE IF NOT EXISTS form_mvdrecinto(
    id_mvdrecinto INTEGER PRIMARY KEY AUTOINCREMENT,
    fk_form_id int(11) not null,
    long varchar(20) not null,
    FOREIGN KEY (fk_form_id /*<<<<< MUST BE A COLUMN IN THE TABLE */) REFERENCES form(form_id /*<<<<< pretty sureyou want to reference form_id column not the non-existent id_form column*/)
);

Assuming What you would do as an example is to have a method based upon:-

void saveFormWithRelatedFormmvdrecinto(long formId, String date, String _long) {
    ContentValues cv = new ContentValues();
    cv.put("form_id,formId);
    cv.put("date",date);
    db.insert("form",null,cv);
    cv.clear();
    cv.put("fk_form_id",formId);
    cv.put("long",_long);
    db.insert("form_mvdrecinto",null,cv);
}

obviously db is an SQLiteDatabase.

due to the ForeignKey constraint the form must be inserted prior to the formmvdrecinto (or formmvdrecintos are inserted).

As the SQLiteDatabase insert Method uses INSERT OR IGNORE ...., the above could be used for an existing form, it would simply ignore inserting the duplicate form and then continue to insert the formmdvrecinto.

It appears that you may have the misconception that FOREIGN KEY builds relationships automatically. It DOES NOT (it cannot) you have to indicate the actual relationship. FOREIGN KEY is a constraint, a rule, that says that the column(s) in the table with the foreign key MUST contain a value that exists in the REFRENECED column(s) in the REFRENCED TABLE otherwise a conflict (failure) will result. INSERT OR IGNORE does not ignore such a conflict.

Demonstration

The following is a working demonstration based upon the tables above. In addition to using a known form id for the insertion of form_mvdrecinto rows (it ads 2 such rows). It also demonstrates a more precarious insertion based upon the dateCreated (if not unique then the form_mvdrecinto inserted will be an arbritary row where the datecreated is matched).

First most of the code is in the DatabaseHelper class it being :-

class DatabaseHelper extends SQLiteOpenHelper {

   public static final String DATABASE_NAME = "the_database.db";
   public static final int DATABASE_VERSION = 1;
   public static final String FORM_TABLE = "form";
   public static final String COL_FORM_FORMID = "form_id";
   public static final String COL_FORM_DATECREATION = "date_creation";
   public static final String FORM_MVDRECINTO_TABLE = "form_mvdrecinto";
   public static final String COL_FORMMVDRECINTO_FORMMVDRECINTO_ID = "id_mvdrecinto";
   public static final String COL_FORMMVDRECINTO_FK_FORM_ID = "fk_form_id";
   public static final String COL_FORMMVDRECINTO_LONG = "long";

   private static volatile DatabaseHelper instance = null;
   private SQLiteDatabase db;

   private DatabaseHelper(Context context) {
      super(context, DATABASE_NAME,null, DATABASE_VERSION);
      db = this.getWritableDatabase();
      /* By defauly Foreign Keys are not turned no, so turn them on */
      db.setForeignKeyConstraintsEnabled(true);
   }

   public static DatabaseHelper getInstance(Context context) {
      if (instance == null) {
         instance = new DatabaseHelper(context);
      }
      return instance;
   }

   @Override
   public void onCreate(SQLiteDatabase db) {
      db.execSQL(
              "CREATE TABLE IF NOT EXISTS " + FORM_TABLE + " ("
                      + COL_FORM_FORMID + " INTEGER PRIMARY KEY "
                      +"," + COL_FORM_DATECREATION + " date NOT NULL"
                      + ");"
      );
      db.execSQL(
              "CREATE TABLE IF NOT EXISTS " + FORM_MVDRECINTO_TABLE +"("
                      + COL_FORMMVDRECINTO_FORMMVDRECINTO_ID + " INTEGER PRIMARY KEY"
                      + "," + COL_FORMMVDRECINTO_FK_FORM_ID + " INTEGER NOT NULL"
                      + "," + COL_FORMMVDRECINTO_LONG + " TEXT NOT NULL"
                      + ", FOREIGN KEY (" + COL_FORMMVDRECINTO_FK_FORM_ID + ") REFERENCES " + FORM_TABLE + "(" + COL_FORM_FORMID + ")"
                      + ");"
      );
   }

   public long insertForm(Long id, String dateCreated) {
      ContentValues cv = new ContentValues();
      if (id != null && id > 0) {
         cv.put(COL_FORM_FORMID,id);
      }
      cv.put(COL_FORM_DATECREATION,dateCreated);
      return db.insert(FORM_TABLE,null,cv);
   }

   public long insertForm(String dateCreated) {
      return insertForm(null,dateCreated);
   }

   public long insertFormMVDRecinto(Long id, long form_id, String _long) {
      ContentValues cv = new ContentValues();
      if (id != null && id > 0) {
         cv.put(COL_FORMMVDRECINTO_FORMMVDRECINTO_ID,id);;
      }
      cv.put(COL_FORMMVDRECINTO_FK_FORM_ID,form_id);
      cv.put(COL_FORMMVDRECINTO_LONG,_long);
      return db.insert(FORM_MVDRECINTO_TABLE,null,cv);
   }

   public long insertFormMVDRecinto(long form_id, String _long) {
      return insertFormMVDRecinto(null,form_id,_long);
   }

   @SuppressLint("Range")
   public long insertFormMVDRecinto(Long id, String dateCreated, String _long) {
      long rv = -1;
      Cursor csr = db.query(FORM_TABLE,new String[]{COL_FORM_FORMID},COL_FORM_DATECREATION + "=?",new String[]{dateCreated},null,null,null,"1");
      if (csr.moveToFirst()) {
         rv = insertFormMVDRecinto(id,csr.getLong(csr.getColumnIndex(COL_FORM_FORMID)),_long);
      }
      return rv;
   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int i, int i1) {

   }
}

To actually demonstrate the following MainActivity is an activity which :-

Adds 3 Form rows

Adds 3 Form_mvdrecinto rows

The first two being added using the known form_id.

The last is added according to a known dateCreated value.

Tries to add a 4th Form_mdvrecinto row BUT with a dateCreated that IS NOT in any rows (due to the no row being extracted the attempt to insert a row which would result in a FK conflict is not attempted).

:-

public class MainActivity extends AppCompatActivity {

    DatabaseHelper dbhelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbhelper = DatabaseHelper.getInstance(this);

        long f1 = dbhelper.insertForm(10L,"2021-02-10 10:21:13"); /* id will be 10 */
        long f2 = dbhelper.insertForm("2021-02-10 11:13:55"); /* id will probably be 11 */
        long f3 = dbhelper.insertForm(1000l,"2021-02-10 09:00:00");

        long fm1 = dbhelper.insertFormMVDRecinto(f1,"Blah001");
        long fm2 = dbhelper.insertFormMVDRecinto(100l,f1,"Blah002");

        /* WARNING if more than 1 form with 2021-02-10 09:00:00 then could be related to any 1 */
        long fm3 = dbhelper.insertFormMVDRecinto(null,"2021-02-10 09:00:00","Blah003");
        /* WILL NOT INSERT as no such dateCreated value in the Form table*/
        /* does not attempt to insert into the Form_mdvrecinto because the row is not found/extracted */
        long fm4 = dbhelper.insertFormMVDRecinto(null,"NOT A DATE THAT WOULD EXIST","Blah004");
    }
}


问:
How to parameterize precision of float on printf format
I have a C program that output values to stdout from measure. I use printf to display them and the format allows me to change the precision

```<code> printf("Scan=%d S_0=%.5f S_1=%.5f S_2=%.5f S_3=%.5f", scanId, S0, S1, S2, S3);
</code>```

My issue is that I have a lot of printing like this one and if I want to change the precision quickly I have to get on each one and change it. I was wondering if it was possible to use something like a #define to have it on a precise location and it will apply on each printf at compilation. I know it is not possible easily without recompile but I'm ok with that. I know something similar as I ask here in python is:

```<code>f"{s_0:.{prec}f}"
</code>```

答:
You can use a * symbol in place of the precision, in which case the precision is given as a parameter.  Then you can define a constant to pass to printf.

```<code>#define P_FLOAT 5

printf("Scan=%d S_0=%.*f S_1=%.*f S_2=%.*f S_3=%.*f",
       scanId, P_FLOAT, S0, P_FLOAT, S1, P_FLOAT, S2, P_FLOAT, S3);
</code>```

Body:
I have a C program that output values to stdout from measure. I use printf to display them and the format allows me to change the precision

 printf("Scan=%d S_0=%.5f S_1=%.5f S_2=%.5f S_3=%.5f", scanId, S0, S1, S2, S3);

My issue is that I have a lot of printing like this one and if I want to change the precision quickly I have to get on each one and change it. I was wondering if it was possible to use something like a #define to have it on a precise location and it will apply on each printf at compilation. I know it is not possible easily without recompile but I'm ok with that. I know something similar as I ask here in python is:

f"{s_0:.{prec}f}"

Body:
You can use a * symbol in place of the precision, in which case the precision is given as a parameter.  Then you can define a constant to pass to printf.

#define P_FLOAT 5

printf("Scan=%d S_0=%.*f S_1=%.*f S_2=%.*f S_3=%.*f",
       scanId, P_FLOAT, S0, P_FLOAT, S1, P_FLOAT, S2, P_FLOAT, S3);


问:
Why does float() not "unstring" a string formatted list element?
I need to parse a comma delimited string that is part of a dict into values. I receive the data originally as a (huge) JSON formatted string and am loading it into a dict with json.loads().

Some of the values split from the string will always be floats and I just want to float() those, while others can be either strings, null, or empty and will need to be treated separately (not the topic of this question).

Bizarrely, after splitting the string, the resulting list appears to contain some non-float()-able version of a string.

Consider this small python3 example code

```<code># construct the sample dict
var = {}
var['abc'] = '"123.456","zzz"'

# JSONify it
var_json = json.dumps(var)

print("var_json: %s" % json.loads(var_json))

# var_json now exemplifies the input data
# deJSONify it:
data_in = json.loads(var_json)

a = data_in['abc'].split(",")
print(a[0])
print("this works:", float("123.456"))
print("this borks:", float(a[0]))
</code>```

This results in the following output:

```<code>var_json: {'abc': '"123.456","456"'}
"123.456"
this works: 123.456
Traceback (most recent call last):
  File "./test.py", line 26, in <module>
    print("this borks:", float(a[0]))
ValueError: could not convert string to float: '"123.456"'
</code>```

So: Clearly, to python the value in the list resulting from the split is a string (has double quotes around it in the output). But using float() on that string doesn't work.

Changing that last line to manually replace the quotes works:

```<code>print(float(a[0].replace("\"", "")))
</code>```

So it looks like a[0] is in fact a string containing double quotes.

The same error occurs even without the json.dumps/loads roundtrip, e.g. just accessing the split list from the dict directly:

```<code>print("This also borks: ", float(var['abc'].split(",")[0]))
</code>```

Why does float() not "unstring" what very clearly is a string and a valid float conversion input? How can I avoid that .replace() call?

答:
It's not enough to just split on commas; you also need to remove the literal quotation marks from the content of the string.

Quotation marks are not numbers. Thus, a string that contains quotation marks as part of the data within it is not a string that contains only a number. Just as the Python string 'a123a' cannot be parsed as a number, neither can '"123"': The "s are just as out-of-place in the second example as the as are in the first.

For example, you could use:

```<code>float(a[0].replace('"', ''))
</code>```

Insofar as your JSON document is encapsulating CSV data, you can use the Python csv module to parse it in a way that will remove those quotes:

```<code>data_in = {'abc': '"123.456","zzz"'}
a = csv.reader([data_in['abc']]).__next__()
print("this now works:", float(a[0]))
</code>```

Body:
I need to parse a comma delimited string that is part of a dict into values. I receive the data originally as a (huge) JSON formatted string and am loading it into a dict with json.loads().

Some of the values split from the string will always be floats and I just want to float() those, while others can be either strings, null, or empty and will need to be treated separately (not the topic of this question).

Bizarrely, after splitting the string, the resulting list appears to contain some non-float()-able version of a string.

Consider this small python3 example code

# construct the sample dict
var = {}
var['abc'] = '"123.456","zzz"'

# JSONify it
var_json = json.dumps(var)

print("var_json: %s" % json.loads(var_json))

# var_json now exemplifies the input data
# deJSONify it:
data_in = json.loads(var_json)

a = data_in['abc'].split(",")
print(a[0])
print("this works:", float("123.456"))
print("this borks:", float(a[0]))

This results in the following output:

var_json: {'abc': '"123.456","456"'}
"123.456"
this works: 123.456
Traceback (most recent call last):
  File "./test.py", line 26, in <module>
    print("this borks:", float(a[0]))
ValueError: could not convert string to float: '"123.456"'

So: Clearly, to python the value in the list resulting from the split is a string (has double quotes around it in the output). But using float() on that string doesn't work.

Changing that last line to manually replace the quotes works:

print(float(a[0].replace("\"", "")))

So it looks like a[0] is in fact a string containing double quotes.

The same error occurs even without the json.dumps/loads roundtrip, e.g. just accessing the split list from the dict directly:

print("This also borks: ", float(var['abc'].split(",")[0]))

Why does float() not "unstring" what very clearly is a string and a valid float conversion input? How can I avoid that .replace() call?

Body:
It's not enough to just split on commas; you also need to remove the literal quotation marks from the content of the string.

Quotation marks are not numbers. Thus, a string that contains quotation marks as part of the data within it is not a string that contains only a number. Just as the Python string 'a123a' cannot be parsed as a number, neither can '"123"': The "s are just as out-of-place in the second example as the as are in the first.

For example, you could use:

float(a[0].replace('"', ''))

Insofar as your JSON document is encapsulating CSV data, you can use the Python csv module to parse it in a way that will remove those quotes:

data_in = {'abc': '"123.456","zzz"'}
a = csv.reader([data_in['abc']]).__next__()
print("this now works:", float(a[0]))


问:
Why is the data that I'm getting from axios not working but when I use the same data in a const it works normally
I'm getting data from axios by using axios.get and saving the data in a state, and then trying to use that data in a component's prop named disabledDates so i insert the state in the prop and nothing happens but when i put the same data in a const it works

```<code>const [selected, setSelected] = useState("");

const url = "http://000.000.0.00:0000/calendar";

const [data, setData] = useState("");

useEffect(() => {
    // Update the document title using the browser API
    axios
        .get(url)
        .then((res) => setData(JSON.stringify(res.data[0].date)))
        .catch((err) => {
            console.error(err);
        });
}, [data]);

console.log(data);

return (
    <SafeAreaView style={styles.container}>
        <CalendarPicker
            onDateChange={(date) => setSelected(date)}
            disabledDates={data}
            disabledDatesTextStyle={{ color: "red" }}
        />
    </SafeAreaView>
);

</code>```

this is the code that contains the issue

答:
I see two things wrong with your react code.

your use of useEffect is incorrect.

You have dataa as a dependency. Every time your axios request finishes and it sets the data on the state, dataa will change and you will remake the request going into an infinite loop.

You use JSON.stringify() to convert a Json response to a string.

I am not aware which specific library you are using for the date picker but it is unlikely that it expects a string.

Axios responses are already a JavaScript object so just set that to the state of your component, no need to stringify. This will depend on the documentation of the library you are using and in which format they expect the data.

Body:
I'm getting data from axios by using axios.get and saving the data in a state, and then trying to use that data in a component's prop named disabledDates so i insert the state in the prop and nothing happens but when i put the same data in a const it works

const [selected, setSelected] = useState("");

const url = "http://000.000.0.00:0000/calendar";

const [data, setData] = useState("");

useEffect(() => {
    // Update the document title using the browser API
    axios
        .get(url)
        .then((res) => setData(JSON.stringify(res.data[0].date)))
        .catch((err) => {
            console.error(err);
        });
}, [data]);

console.log(data);

return (
    <SafeAreaView style={styles.container}>
        <CalendarPicker
            onDateChange={(date) => setSelected(date)}
            disabledDates={data}
            disabledDatesTextStyle={{ color: "red" }}
        />
    </SafeAreaView>
);

this is the code that contains the issue


问:
Google Sheet + Script + Textfinder + Check
Hi I'm using this code to get a list of rows that matches the searchtext from column "A" and that works great .
But what I'm trying to do is insert a checkmark in column C for each row that match
So basically how would I use the array from .map((r) => r.offset(0,3).getA1Notation()) to insert a checkmark on those rows in column "C"

Thanks

```<code>function check(){
  var rangeList = SpreadsheetApp.getActive().getSheetByName('sheet1').getRange('A2:A');
  var searchText = "dog";
  .createTextFinder(searchText)
  .matchEntireCell(true)
  .findAll()
  .map((r) => r.offset(0,3).getA1Notation())

   console.log(rangeList);
}
</code>```

答:
Insert Checkboxes

```<code>function check(){
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1')
  const searchText = "dog";
  const rangeList = sh.getRange(2,1,sh.getLastRow() - 1).createTextFinder(searchText).matchEntireCell(true).findAll().map((r) => r.offset(0,3).insertCheckboxes());
}
</code>```

Sheet:

Body:
Hi I'm using this code to get a list of rows that matches the searchtext from column "A" and that works great .
But what I'm trying to do is insert a checkmark in column C for each row that match
So basically how would I use the array from .map((r) => r.offset(0,3).getA1Notation()) to insert a checkmark on those rows in column "C"

Thanks

function check(){
  var rangeList = SpreadsheetApp.getActive().getSheetByName('sheet1').getRange('A2:A');
  var searchText = "dog";
  .createTextFinder(searchText)
  .matchEntireCell(true)
  .findAll()
  .map((r) => r.offset(0,3).getA1Notation())

   console.log(rangeList);
}

Body:
Insert Checkboxes

function check(){
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1')
  const searchText = "dog";
  const rangeList = sh.getRange(2,1,sh.getLastRow() - 1).createTextFinder(searchText).matchEntireCell(true).findAll().map((r) => r.offset(0,3).insertCheckboxes());
}

Sheet:


问:
How to run through list of keyword vectors and fuzzy match them to a different file (R)
I have two files, one is full of keywords (roughly 2,000 rows) and the other is full of text (roughly 770,000 rows). The keyword file looks like:

```<code>Event Name            Keyword
All-day tabby fest    tabby, all-day
All-day tabby fest    tabby, fest
Maine Coon Grooming   maine coon, groom
Maine Coon Grooming   coon, groom

keywordFile <- tibble(EventName = c("All-day tabby fest", "All-day tabby fest", "Maine Coon Grooming","Maine Coon Grooming"), Keyword = c("tabby, all-day", "tabby, fest", "maine coon, groom", "coon, groom")
</code>```

The text file looks like:

```<code>Description
Bring your tabby to the fest on Tuesday
All cats are welcome to the fest on Tuesday
Mainecoon grooming will happen at noon Wednesday
Maine coons will be pampered at noon on Wednesday

text <- tibble(Description = c("Bring your tabby to the fest on Tuesday","All cats are welcome to the fest on Tuesday","Mainecoon grooming will happen at noon Wednesday","Maine coons will be pampered at noon on Wednesday")
</code>```

What I want is to iterate through the text file and look for fuzzy matches (must include each word in the "Keyword" column) and return a new column that displays TRUE or False. If that is TRUE, then I want a third column to display the event name. So something that looks like:

```<code>Description                                          Match?   Event Name
Bring your tabby to the fest on Tuesday              TRUE     All-day tabby fest
All cats are welcome to the fest on Tuesday          FALSE
Mainecoon grooming will happen at noon Wednesday     TRUE     Maine Coon Grooming
Maine coons will be pampered at noon on Wednesday    FALSE
</code>```

I am able to successfully do my fuzzy matches (after converting everything to lowercase) with stuff like this, thanks to Molx (How can I check if multiple strings exist in another string?):

```<code>str <- c("tabby", "all-day")
myStr <- "Bring your tabby to the fest on Tuesday"
all(sapply(str, grepl, myStr))
</code>```

However, I am getting stuck when I try to fuzzy match the whole files. I tried something like this:

```<code>for (i in seq_along(text$Description)){
  for (j in seq_along(keywordFile$EventName)) {
    # below I am creating the TRUE/FALSE column
    text$TF[i] <- all(sapply(keywordFile$Keyword[j], grepl,
                                                     text$Description[i]))
    if (isTRUE(text$TF))
      # below I am creating the EventName column
      text$EventName <- keywordFile$EventName
    }
}
</code>```

I don't think I'm having trouble converting the right things to vectors and strings. My keywordFile$Keyword column is a bunch of string vectors and my text$Description column is a character string. But I'm struggling with how to iterate properly through both files. The error I'm getting is

```<code>Error in ... replacement has 13 rows, data has 1
</code>```

Has anyone done anything like this before?

答: Approximate matching can be done in R using agrep() or grepl() functions. It works with option fixed=False. You do not need any additional libraries for these functions.

Body:
I have two files, one is full of keywords (roughly 2,000 rows) and the other is full of text (roughly 770,000 rows). The keyword file looks like:

Event Name            Keyword
All-day tabby fest    tabby, all-day
All-day tabby fest    tabby, fest
Maine Coon Grooming   maine coon, groom
Maine Coon Grooming   coon, groom

keywordFile <- tibble(EventName = c("All-day tabby fest", "All-day tabby fest", "Maine Coon Grooming","Maine Coon Grooming"), Keyword = c("tabby, all-day", "tabby, fest", "maine coon, groom", "coon, groom")

The text file looks like:

Description
Bring your tabby to the fest on Tuesday
All cats are welcome to the fest on Tuesday
Mainecoon grooming will happen at noon Wednesday
Maine coons will be pampered at noon on Wednesday

text <- tibble(Description = c("Bring your tabby to the fest on Tuesday","All cats are welcome to the fest on Tuesday","Mainecoon grooming will happen at noon Wednesday","Maine coons will be pampered at noon on Wednesday")

What I want is to iterate through the text file and look for fuzzy matches (must include each word in the "Keyword" column) and return a new column that displays TRUE or False. If that is TRUE, then I want a third column to display the event name. So something that looks like:

Description                                          Match?   Event Name
Bring your tabby to the fest on Tuesday              TRUE     All-day tabby fest
All cats are welcome to the fest on Tuesday          FALSE
Mainecoon grooming will happen at noon Wednesday     TRUE     Maine Coon Grooming
Maine coons will be pampered at noon on Wednesday    FALSE

I am able to successfully do my fuzzy matches (after converting everything to lowercase) with stuff like this, thanks to Molx (How can I check if multiple strings exist in another string?):

str <- c("tabby", "all-day")
myStr <- "Bring your tabby to the fest on Tuesday"
all(sapply(str, grepl, myStr))

However, I am getting stuck when I try to fuzzy match the whole files. I tried something like this:

for (i in seq_along(text$Description)){
  for (j in seq_along(keywordFile$EventName)) {
    # below I am creating the TRUE/FALSE column
    text$TF[i] <- all(sapply(keywordFile$Keyword[j], grepl,
                                                     text$Description[i]))
    if (isTRUE(text$TF))
      # below I am creating the EventName column
      text$EventName <- keywordFile$EventName
    }
}

I don't think I'm having trouble converting the right things to vectors and strings. My keywordFile$Keyword column is a bunch of string vectors and my text$Description column is a character string. But I'm struggling with how to iterate properly through both files. The error I'm getting is

Error in ... replacement has 13 rows, data has 1

Has anyone done anything like this before?


问:
How do I attach a configmap to a deployment in Kubernetes?
Based on the instructions found here (https://kubernetes.io/docs/tasks/access-application-cluster/connecting-frontend-backend/) I am trying to create an nginx deployment and configure it using a config-map. I can successfully access nginx using curl (yea!) but the configmap does not appear to be "sticking."  The only thing it is supposed to do right now is forward the traffic along. I have seen the thread here (How do I load a configMap in to an environment variable?). although I am using the same format, their answer was not relevant.

Can anyone tell me how to properly configure the configmaps?  the yaml is

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: sandbox
spec:
  selector:
    matchLabels:
      run: nginx
      app: dsp
      tier: frontend
  replicas: 2
  template:
    metadata:
      labels:
        run: nginx
        app: dsp
        tier: frontend
    spec:
      containers:
      - name: nginx
        image: nginx
        env:
        # Define the environment variable
        - name: nginx-conf
          valueFrom:
            configMapKeyRef:
              # The ConfigMap containing the value you want to assign to SPECIAL_LEVEL_KEY
              name: nginx-conf
              # Specify the key associated with the value
              key: nginx.conf
        resources:
          limits:
            memory: "128Mi"
            cpu: "500m"
        ports:
containerPort: 80
</code>```

the nginx-conf is

```<code> # The identifier Backend is internal to nginx, and used to name this specific upstream
upstream Backend {
    # hello is the internal DNS name used by the backend Service inside Kubernetes
    server dsp;
}

server {
    listen 80;

    location / {
        # The following statement will proxy traffic to the upstream named Backend
        proxy_pass http://Backend;
    }
}
</code>```

I turn it into a configmap using the following line

```<code>kubectl create configmap -n sandbox nginx-conf --from-file=apps/nginx.conf
</code>```

答:
You need to mount the configMap rather than use it as an environment variable, as the setting is not a key-value format.

Your Deployment yaml should be like below:

containers:
- name: nginx
  image: nginx
  volumeMounts:
  - mountPath: /etc/nginx
    name: nginx-conf
volumes:
- name: nginx-conf
  configMap:
    name: nginx-conf
    items:
      - key: nginx.conf
        path: nginx.conf
```
<p>You need to create (apply) the configMap beforehand. You can create it from file:</p>
```kubectl create configmap nginx-conf --from-file=nginx.conf
```
<p>or you can directly describe configMap manifest:</p>
```apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-conf
data:
  nginx.conf: |
    # The identifier Backend is internal to nginx, and used to name this specific upstream
    upstream Backend {
        # hello is the internal DNS name used by the backend Service inside Kubernetes
        server dsp;
    }
    ...
}
```

Body:
Based on the instructions found here (https://kubernetes.io/docs/tasks/access-application-cluster/connecting-frontend-backend/) I am trying to create an nginx deployment and configure it using a config-map. I can successfully access nginx using curl (yea!) but the configmap does not appear to be "sticking."  The only thing it is supposed to do right now is forward the traffic along. I have seen the thread here (How do I load a configMap in to an environment variable?). although I am using the same format, their answer was not relevant.

Can anyone tell me how to properly configure the configmaps?  the yaml is

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: sandbox
spec:
  selector:
    matchLabels:
      run: nginx
      app: dsp
      tier: frontend
  replicas: 2
  template:
    metadata:
      labels:
        run: nginx
        app: dsp
        tier: frontend
    spec:
      containers:
      - name: nginx
        image: nginx
        env:
        # Define the environment variable
        - name: nginx-conf
          valueFrom:
            configMapKeyRef:
              # The ConfigMap containing the value you want to assign to SPECIAL_LEVEL_KEY
              name: nginx-conf
              # Specify the key associated with the value
              key: nginx.conf
        resources:
          limits:
            memory: "128Mi"
            cpu: "500m"
        ports:
containerPort: 80

the nginx-conf is

 # The identifier Backend is internal to nginx, and used to name this specific upstream
upstream Backend {
    # hello is the internal DNS name used by the backend Service inside Kubernetes
    server dsp;
}

server {
    listen 80;

    location / {
        # The following statement will proxy traffic to the upstream named Backend
        proxy_pass http://Backend;
    }
}

I turn it into a configmap using the following line

kubectl create configmap -n sandbox nginx-conf --from-file=apps/nginx.conf

Body:
You need to mount the configMap rather than use it as an environment variable, as the setting is not a key-value format.

Your Deployment yaml should be like below:

containers:
- name: nginx
  image: nginx
  volumeMounts:
  - mountPath: /etc/nginx
    name: nginx-conf
volumes:
- name: nginx-conf
  configMap:
    name: nginx-conf
    items:
      - key: nginx.conf
        path: nginx.conf

You need to create (apply) the configMap beforehand. You can create it from file:

kubectl create configmap nginx-conf --from-file=nginx.conf

or you can directly describe configMap manifest:

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-conf
data:
  nginx.conf: |
    # The identifier Backend is internal to nginx, and used to name this specific upstream
    upstream Backend {
        # hello is the internal DNS name used by the backend Service inside Kubernetes
        server dsp;
    }
    ...
}


问:
How to share tensorboard running in my localhost:6006 with my collegues?
I'd like to share the Tensorboard (Embedding Projector) with my colleagues and I'm trying to find possible ways to share it over the intranet. I can't use an embedding projector since it has sensitive information. Any responses would help. Thanks a lot</p>

答: Use the flag --bind_all to serve on your public network. Then just lookup your computer’s local IP and share it with your colleagues!


问:
How to document kwargs according to Numpy style docstring?
So, I've found posts related to other styles and I am aware of this NumPy page about the documentation but I am confused. I didn't understand how to add each kwargs to the parameters section of a method. This is from the given web page:

```<code>def foo(var1, var2, *args, long_var_name='hi', **kwargs):
    r"""Summarize the function in one line.

    Several sentences providing an extended description. Refer to
    variables using back-ticks, e.g. `var`.

    Parameters
    ----------
    var1 : array_like
        Array_like means all those objects -- lists, nested lists, etc. --
        that can be converted to an array.  We can also refer to
        variables like `var1`.
    var2 : int
        The type above can either refer to an actual Python type
        (e.g. ``int``), or describe the type of the variable in more
        detail, e.g. ``(N,) ndarray`` or ``array_like``.
    *args : iterable
        Other arguments.
    long_var_name : {'hi', 'ho'}, optional
        Choices in brackets, default first when optional.
    **kwargs : dict
        Keyword arguments.
</code>```

It is not clear how to add each kwargs here. I also saw this sphinx page "Example NumPy Style Python Docstring", here is the section about the kwargs:

```<code>def module_level_function(param1, param2=None, *args, **kwargs):
    """This is an example of a module level function.

    Function parameters should be documented in the ``Parameters`` section.
    The name of each parameter is required. The type and description of each
    parameter is optional, but should be included if not obvious.

    If \*args or \*\*kwargs are accepted,
    they should be listed as ``*args`` and ``**kwargs``.

    The format for a parameter is::

        name : type
            description

            The description may span multiple lines. Following lines
            should be indented to match the first line of the description.
            The ": type" is optional.

            Multiple paragraphs are supported in parameter
            descriptions.

    Parameters
    ----------
    param1 : int
        The first parameter.
    param2 : :obj:`str`, optional
        The second parameter.
    *args
        Variable length argument list.
    **kwargs
        Arbitrary keyword arguments.
</code>```

Nope, I am still confused. Is it something like this?

```<code>"""
Dummy docstring.

Parameters
----------
**kwargs: dict
    first_kwarg: int
        This is an integer
    second_kwarg: str
        This is a string
"""
</code>```

答:
Summary

The **kwargs are not typically listed in the function, but instead the final destination of the **kwargs is mentioned. For example:

```<code>**kwargs
    Instructions on how to decorate your plots.
    The keyword arguments are passed to `matplotlib.axes.Axes.plot()`
</code>```

If there are multiple possible targets, they are all listed (see below)

If you happen to use some automation tool to interpolate and link your documentation, then you might list the possible keyword arguments in **kwargs for the convenience of the end users. This kind of approach is used in matplotlib, for example. (see below)

How and when document **kwargs (Numpydoc)

1) When to use **kwargs?

First thing to note here is that **kwargs should be used to pass arguments to underlying functions and methods. If the argument inside **kwargs would be used in the function (and not passed down), it should be written out as normal keyword argument, instead.

2) Where to put **kwargs decription?

The location of **kwargs description is in the Parameters section. Sometimes it is appropriate to list them in the Other Parameters section, but remember: Other Parameters should only be used if a function has a large number of keyword parameters, to prevent cluttering the Parameters section.

matplotlib.axes.Axes.grid has **kwargs in Parameters section.

matplotlib.axes.Axes.plot has **kwargs in Other Parameters section (reasoning probably to large number of keyword arguments).

3) Syntax for **kwargs decription

The syntax for the description for the **kwargs is, following Numpydoc styleguide

```<code>Parameters
----------
... (other lines)
**kwargs : sometype
     Some description on what the kwargs are
     used for.
</code>```

or

```<code>Parameters
----------
... (other lines)
**kwargs
     Some description on what the kwargs are
     used for.
</code>```

The one describing the type is more appropriate, as [source].

For the parameter types, be as precise as possible

One exception for this is for example when the **kwargs could be passed to one of many functions based on other parameter values, as in seaborn.kdeplot. Then, the line for the type would become too long for describing all the types and it would be cleaner to use a bullet point list, which also describes the conditions on when the **kwargs are forwarded to where. Eg.:

```<code>Parameters
----------
fill: bool or None
    If True, fill in the area under univariate density curves or between
     bivariate contours. If None, the default depends on multiple.
**kwargs
    Other keyword arguments are passed to one of the following matplotlib
    functions:

    * matplotlib.axes.Axes.plot() (univariate, fill=False),

    * matplotlib.axes.Axes.fill_between() (univariate, fill=True),

    * matplotlib.axes.Axes.contour() (bivariate, fill=False),

    * matplotlib.axes.contourf() (bivariate, fill=True).
</code>```

You may also add listing of the valid keyword arguments in **kwargs like in  matplotlib.axes.Axes.grid. Here is the interpolated python doc/text version:

```<code>Parameters
----------
... (other lines)
**kwargs : `.Line2D` properties
    Define the line properties of the grid, e.g.::

        grid(color='r', linestyle='-', linewidth=2)

    Valid keyword arguments are:

    Properties:
    agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
    alpha: float or None
    animated: bool
    antialiased or aa: bool
    clip_box: `.Bbox`
    clip_on: bool
    clip_path: Patch or (Path, Transform) or None
    color or c: color
    contains: unknown
    dash_capstyle: {'butt', 'round', 'projecting'}
    dash_joinstyle: {'miter', '
    ... (more lines)
</code>```

This is convenient for the user, but challenging for the developer. In matplotlib this kind of luxury is made possible with the automatization using some special documentation decorators and linking1. Manual writing of allowed kwargs will surely become a code maintenance nightmare.

4) Notes related to **kwargs / Extended help

Some additional info about the **kwargs could be included in the Notes section.
For example matplotlib.axes.Axes.plot discusses marker styles, line styles and colors in the Notes section. [2]

[1] They use a @docstring.dedent_interpd decorator which pulls the meaning of the kwargs to the final docs. So that is happening in place of %(Line2D:kwdoc)s, for example.

[2] See: help(ax.plot) where ax is instance of matplotlib.axes.Axes.

Body:
So, I've found posts related to other styles and I am aware of this NumPy page about the documentation but I am confused. I didn't understand how to add each kwargs to the parameters section of a method. This is from the given web page:

def foo(var1, var2, *args, long_var_name='hi', **kwargs):
    r"""Summarize the function in one line.

    Several sentences providing an extended description. Refer to
    variables using back-ticks, e.g. `var`.

    Parameters
    ----------
    var1 : array_like
        Array_like means all those objects -- lists, nested lists, etc. --
        that can be converted to an array.  We can also refer to
        variables like `var1`.
    var2 : int
        The type above can either refer to an actual Python type
        (e.g. ``int``), or describe the type of the variable in more
        detail, e.g. ``(N,) ndarray`` or ``array_like``.
    *args : iterable
        Other arguments.
    long_var_name : {'hi', 'ho'}, optional
        Choices in brackets, default first when optional.
    **kwargs : dict
        Keyword arguments.

It is not clear how to add each kwargs here. I also saw this sphinx page "Example NumPy Style Python Docstring", here is the section about the kwargs:

def module_level_function(param1, param2=None, *args, **kwargs):
    """This is an example of a module level function.

    Function parameters should be documented in the ``Parameters`` section.
    The name of each parameter is required. The type and description of each
    parameter is optional, but should be included if not obvious.

    If \*args or \*\*kwargs are accepted,
    they should be listed as ``*args`` and ``**kwargs``.

    The format for a parameter is::

        name : type
            description

            The description may span multiple lines. Following lines
            should be indented to match the first line of the description.
            The ": type" is optional.

            Multiple paragraphs are supported in parameter
            descriptions.

    Parameters
    ----------
    param1 : int
        The first parameter.
    param2 : :obj:`str`, optional
        The second parameter.
    *args
        Variable length argument list.
    **kwargs
        Arbitrary keyword arguments.

Nope, I am still confused. Is it something like this?

"""
Dummy docstring.

Parameters
----------
**kwargs: dict
    first_kwarg: int
        This is an integer
    second_kwarg: str
        This is a string
"""

Body:
Summary

The **kwargs are not typically listed in the function, but instead the final destination of the **kwargs is mentioned. For example:

**kwargs
    Instructions on how to decorate your plots.
    The keyword arguments are passed to `matplotlib.axes.Axes.plot()`

If there are multiple possible targets, they are all listed (see below)

If you happen to use some automation tool to interpolate and link your documentation, then you might list the possible keyword arguments in **kwargs for the convenience of the end users. This kind of approach is used in matplotlib, for example. (see below)

How and when document **kwargs (Numpydoc)

1) When to use **kwargs?

First thing to note here is that **kwargs should be used to pass arguments to underlying functions and methods. If the argument inside **kwargs would be used in the function (and not passed down), it should be written out as normal keyword argument, instead.

2) Where to put **kwargs decription?

The location of **kwargs description is in the Parameters section. Sometimes it is appropriate to list them in the Other Parameters section, but remember: Other Parameters should only be used if a function has a large number of keyword parameters, to prevent cluttering the Parameters section.

matplotlib.axes.Axes.grid has **kwargs in Parameters section.

matplotlib.axes.Axes.plot has **kwargs in Other Parameters section (reasoning probably to large number of keyword arguments).

3) Syntax for **kwargs decription

The syntax for the description for the **kwargs is, following Numpydoc styleguide

Parameters
----------
... (other lines)
**kwargs : sometype
     Some description on what the kwargs are
     used for.

or

Parameters
----------
... (other lines)
**kwargs
     Some description on what the kwargs are
     used for.

The one describing the type is more appropriate, as [source].

For the parameter types, be as precise as possible

One exception for this is for example when the **kwargs could be passed to one of many functions based on other parameter values, as in seaborn.kdeplot. Then, the line for the type would become too long for describing all the types and it would be cleaner to use a bullet point list, which also describes the conditions on when the **kwargs are forwarded to where. Eg.:

Parameters
----------
fill: bool or None
    If True, fill in the area under univariate density curves or between
     bivariate contours. If None, the default depends on multiple.
**kwargs
    Other keyword arguments are passed to one of the following matplotlib
    functions:

    * matplotlib.axes.Axes.plot() (univariate, fill=False),

    * matplotlib.axes.Axes.fill_between() (univariate, fill=True),

    * matplotlib.axes.Axes.contour() (bivariate, fill=False),

    * matplotlib.axes.contourf() (bivariate, fill=True).

You may also add listing of the valid keyword arguments in **kwargs like in  matplotlib.axes.Axes.grid. Here is the interpolated python doc/text version:

Parameters
----------
... (other lines)
**kwargs : `.Line2D` properties
    Define the line properties of the grid, e.g.::

        grid(color='r', linestyle='-', linewidth=2)

    Valid keyword arguments are:

    Properties:
    agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
    alpha: float or None
    animated: bool
    antialiased or aa: bool
    clip_box: `.Bbox`
    clip_on: bool
    clip_path: Patch or (Path, Transform) or None
    color or c: color
    contains: unknown
    dash_capstyle: {'butt', 'round', 'projecting'}
    dash_joinstyle: {'miter', '
    ... (more lines)

This is convenient for the user, but challenging for the developer. In matplotlib this kind of luxury is made possible with the automatization using some special documentation decorators and linking1. Manual writing of allowed kwargs will surely become a code maintenance nightmare.

4) Notes related to **kwargs / Extended help

Some additional info about the **kwargs could be included in the Notes section.
For example matplotlib.axes.Axes.plot discusses marker styles, line styles and colors in the Notes section. [2]

[1] They use a @docstring.dedent_interpd decorator which pulls the meaning of the kwargs to the final docs. So that is happening in place of %(Line2D:kwdoc)s, for example.

[2] See: help(ax.plot) where ax is instance of matplotlib.axes.Axes.


问:
Make Sticky header of web page in Safari on iPad
I want to make a sticky header like this url: http://www.cssplay.co.uk/layouts/fixit.html has done!
But put this url on Safari of iPad, it also fails to fix the header.

Does anyone knows how to do sticky header on iPad Safari?

Thanks in advance!

答:
In fact all you need to address this issue for iOS devices (iPad, iPhone, etc) is to add the following to your CSS:

```<code>#container {
  position:fixed;
  top:120px;
  bottom:0px;
  overflow:auto;
}
</code>```

This example is assuming that:

the part you want to scroll starts 120px below your header (ie the
header will be 120px high)

the div you want to have scrolling has an id='container'

you will use 2 fingers to scroll it. If you use one finger then the
header will move as well.

This actually is pretty cool on iPad as it gives the user a choice (move the whole thing or keep the header visible by using one or two fingers). It also works for footers (change bottom value).

Finally note that this is for "Apple" browsers (I successfully tested it on iPad and Mac Safari and Chrome) so if you want to support something else you WILL have to create different codes using something like :

```<code>if (navigator.userAgent.match("Apple") == null) {
    /* use a different container id */
}
</code>```

Edit on Oct 7, 2011: Thx to chris-barr.com I found this solution. Simply add this code:

```<code><script>
function touchScroll(id){
    var el=document.getElementById(id);
    var scrollStartPos=0;

    document.getElementById(id).addEventListener("touchstart", function(event) {
        scrollStartPos=this.scrollTop+event.touches[0].pageY;
        event.preventDefault();
    },false);

    document.getElementById(id).addEventListener("touchmove", function(event) {
        this.scrollTop=scrollStartPos-event.touches[0].pageY;
        event.preventDefault();
    },false);
}
</script>

<body onload="touchScroll('container')">
</code>```

and it will work in iOS (iPhone, iPad) AND Android WITH ONLY ONE FINGER !!!

ContentLicense: CC BY-SA 2.5

Body:
In fact all you need to address this issue for iOS devices (iPad, iPhone, etc) is to add the following to your CSS:

#container {
  position:fixed;
  top:120px;
  bottom:0px;
  overflow:auto;
}

This example is assuming that:

the part you want to scroll starts 120px below your header (ie the
header will be 120px high)

the div you want to have scrolling has an id='container'

you will use 2 fingers to scroll it. If you use one finger then the
header will move as well.

This actually is pretty cool on iPad as it gives the user a choice (move the whole thing or keep the header visible by using one or two fingers). It also works for footers (change bottom value).

Finally note that this is for "Apple" browsers (I successfully tested it on iPad and Mac Safari and Chrome) so if you want to support something else you WILL have to create different codes using something like :

if (navigator.userAgent.match("Apple") == null) {
    /* use a different container id */
}

Edit on Oct 7, 2011: Thx to chris-barr.com I found this solution. Simply add this code:

<script>
function touchScroll(id){
    var el=document.getElementById(id);
    var scrollStartPos=0;

    document.getElementById(id).addEventListener("touchstart", function(event) {
        scrollStartPos=this.scrollTop+event.touches[0].pageY;
        event.preventDefault();
    },false);

    document.getElementById(id).addEventListener("touchmove", function(event) {
        this.scrollTop=scrollStartPos-event.touches[0].pageY;
        event.preventDefault();
    },false);
}
</script>

<body onload="touchScroll('container')">

and it will work in iOS (iPhone, iPad) AND Android WITH ONLY ONE FINGER !!!


问:
Pandas, how to add a column iterating the dataframe?
I've a dataset like this:

```<code>d = {'state': ['United States', 'IT', 'Spain', 'JP', 'FR'], 'continent': ['North America', 'Europe', 'Europe', 'Asia', 'Europe']}
df = pd.DataFrame(data=d)
</code>```

with two columns, df['state'] and df['continent']:

```<code>United States       North America
IT                  Europe
Spain               Europe
JP                  Asia
FR                  Europe
</code>```

I want to create a new column that is composed in this way:

```<code>for state in df['state']:
    if(len(state) <= 2):
        # df['newCol'] = df['continent'] + ' - ' + df['state']
</code>```

So that the result would be:

```<code>United States
Europe - IT
Spain
Asia - JP
Europe - FR
</code>```

But I have some problems with the iteration of the dataset...

答:
Use np.where:

```<code>df['new'] = np.where(df['state'].str.len() <= 2, df['continent'] + ' - ' + df['state'], df['state'])
</code>```

Output:

```<code>>>> df
           state      continent            new
0  United States  North America  United States
1             IT         Europe    Europe - IT
2          Spain         Europe          Spain
3             JP           Asia      Asia - JP
4             FR         Europe    Europe - FR
</code>```

Body:
I've a dataset like this:

d = {'state': ['United States', 'IT', 'Spain', 'JP', 'FR'], 'continent': ['North America', 'Europe', 'Europe', 'Asia', 'Europe']}
df = pd.DataFrame(data=d)

with two columns, df['state'] and df['continent']:

United States       North America
IT                  Europe
Spain               Europe
JP                  Asia
FR                  Europe

I want to create a new column that is composed in this way:

for state in df['state']:
    if(len(state) <= 2):
        # df['newCol'] = df['continent'] + ' - ' + df['state']

So that the result would be:

United States
Europe - IT
Spain
Asia - JP
Europe - FR

But I have some problems with the iteration of the dataset...

Body:
Use np.where:

df['new'] = np.where(df['state'].str.len() <= 2, df['continent'] + ' - ' + df['state'], df['state'])

Output:

>>> df
           state      continent            new
0  United States  North America  United States
1             IT         Europe    Europe - IT
2          Spain         Europe          Spain
3             JP           Asia      Asia - JP
4             FR         Europe    Europe - FR


问:
Problem with Tweet! for jQuery
Tweet! for jQuery works fine most of the time, but sporadically I get this:

```<code>"NetworkError: 400 Bad Request - http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jlowgren&count=5&include_rts=1&page=1&callback=jQuery16202827138555332698_1313661810432&_=1313661810465
</code>```

This is the jQuery call:

```<code>$(".tweet").tweet({
    username: "jlowgren",
    count: 5,
    loading_text: "Loading tweets…",
    refresh_interval: 120
});
</code>```

The site in question is www.jorum.se.

Anyone with a handsome solution for this will be richly rewarded in karma!

答:
I think that you should always assume that the Twitter network will occasionally fail (it always has done to date).  So wrap your jquery tweet call in a javascript try catch.</p>

```<code>try {
    $(".tweet").tweet({
    username: "jlowgren",
    count: 5,
    loading_text: "Loading tweets…",
    refresh_interval: 120
});
} catch (error) {
    // error message or other response goes here
}
</code>```

Title: Problem with Tweet! for jQuery

Body:
Tweet! for jQuery works fine most of the time, but sporadically I get this:

"NetworkError: 400 Bad Request - http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jlowgren&count=5&include_rts=1&page=1&callback=jQuery16202827138555332698_1313661810432&_=1313661810465

This is the jQuery call:

$(".tweet").tweet({
    username: "jlowgren",
    count: 5,
    loading_text: "Loading tweets…",
    refresh_interval: 120
});

The site in question is www.jorum.se.

Anyone with a handsome solution for this will be richly rewarded in karma!

Body:
I think that you should always assume that the Twitter network will occasionally fail (it always has done to date).  So wrap your jquery tweet call in a javascript try catch.

try {
    $(".tweet").tweet({
    username: "jlowgren",
    count: 5,
    loading_text: "Loading tweets…",
    refresh_interval: 120
});
} catch (error) {
    // error message or other response goes here
}


问:
Espresso test is not finishing and it keeps on finding element when there is an issue in the application
I have the espresso test. When there is any issue in the app the test is not finishing and it keeps on staying on the same screen. Is there anyway we can give timeout for the espresso test. I cant find solution for the global timeout. Junit Android Espresso Test</p>
```<code>@Before
public static void beforeClass() {
    IdlingPolicies.setMasterPolicyTimeout(10, TimeUnit.SECONDS);
    IdlingPolicies.setIdlingResourceTimeout(10, TimeUnit.SECONDS);
}
</code>```

答:
You could add a timeout rule.
E.g. Rule to timeout after 2 minutes</p>
```<code>@get:Rule val globalTimeout: Timeout = Timeout.seconds(120)
</code>```

Body:
I have the espresso test. When there is any issue in the app the test is not finishing and it keeps on staying on the same screen. Is there anyway we can give timeout for the espresso test. I cant find solution for the global timeout. Junit Android Espresso Test

@Before
public static void beforeClass() {
    IdlingPolicies.setMasterPolicyTimeout(10, TimeUnit.SECONDS);
    IdlingPolicies.setIdlingResourceTimeout(10, TimeUnit.SECONDS);
}

Body:
You could add a timeout rule.
E.g. Rule to timeout after 2 minutes

@get:Rule val globalTimeout: Timeout = Timeout.seconds(120)


问:
Compiling Filesystem in USErspace in Eclipse
My english is not the best so i'am sorry of that. I want to build my own filesystem using fuse. Is it possible to do this project in Eclipse? I have some problems when try to do it. I've added pkg-config fuse --cflags --libs to "Compiler invocation arguments" but it didn't help.
Please help,
Cris

答: Open the project's Properties and go to C/C++ Build → Settings → Tool settings.  Make sure that the Configuration is set to [ All configurations ].  Now go to GCC C Compiler → Miscellaneous and add `pkg-config fuse --cflags` to the Other flags field then hit Apply.  Next go to GCC C Linker and add `pkg-config fuse --libs` to the end of Command line pattern (under Expert settings) then click on Apply and close.  Your FUSE project should now compile without errors.


问:
Why is there a no column name for car names in mtcars dataset in R?
I had a question regarding mtcars dataset in R. All the columns have names except first column,that contains Car names such as Toyota Corolla, Mazda. Is there any specific reason for it. If yes, I would like to know the reason. Also, I was wondering if we can do same for one specific column in our own dataset ? If so how ?

Thanks in advance!

答:
I also stumbled on this missing invisible  column, it's killing my mind, absolutely hard to get why, especially if you're beginner.
It's clearly says that it's 11 column, but what column has value 'Mazda' ??</p>
```<code>    mtcars
> mtcars
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
str(mtcars)
> str(mtcars)
'data.frame':   32 obs. of  11 variables:
  $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...

colnames(mtcars)
[1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
#!!!!! where is name for MODEL ???????

# tried to name columns so there is 11 of them ???
colnames(mtcars) <- c('model', 'mpg', 'cyl', 'disp', 'hp', 'drat', 'wt', 'qsec', 'vs', 'am', 'gear', 'carb')
> colnames(mtcars)
</code>```

Body:
I also stumbled on this missing invisible  column, it's killing my mind, absolutely hard to get why, especially if you're beginner.
It's clearly says that it's 11 column, but what column has value 'Mazda' ??

    mtcars
> mtcars
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
str(mtcars)
> str(mtcars)
'data.frame':   32 obs. of  11 variables:
  $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...

colnames(mtcars)
[1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
#!!!!! where is name for MODEL ???????

# tried to name columns so there is 11 of them ???
colnames(mtcars) <- c('model', 'mpg', 'cyl', 'disp', 'hp', 'drat', 'wt', 'qsec', 'vs', 'am', 'gear', 'carb')
> colnames(mtcars)