问:
How to display an svg image in reactjs
I am working on a web application with Nodejs and Reactjs and currently i'm retrieving data from the mongo database and displaying it with react.

Here is some code :

```<code>import React, {Component} from 'react';
import axios from '../../node_modules/axios';
import {Col,Card} from 'react-bootstrap';

import {BrowserRouter as Router,Link, useRouteMatch} from 'react-router-dom';

const Brand = props => (
<Col lg="4" className="d-inline-block">
  <Link to="/admin/Marques/MarqueDetails/1">
  <Card className="marque-card" style={{ width: '100%' }}>
      <p>{props.brand.name}</p>
      <Card.Img className="marque-card" variant="top" src={`../../public/` +
       props.brand.imgUrl} />
  </Card>
  </Link>
</Col>
)

class cardBrand extends Component {

constructor(props) {
    super(props);

    this.state = {brands: []};
  }
  componentDidMount() {
    axios.get('http://localhost:5000/brand/')
      .then(response => {
        this.setState({ brands: response.data })
      })
      .catch((error) => {
        console.log(error);
      })
  }
  brandList() {
    return this.state.brands.map(currentBrand => {
      return <Brand brand={currentBrand} key={currentBrand._id}/>;
    })
  }
render() {
    return(
      <Col lg="12">
       { this.brandList() }
       </Col>
    )
  }
}
export default cardBrand;
</code>```

As you can see i have the img/brand folders inside the public folder and the props.brand.imgUrl contains the path and the image name, but unfortunately it's not working on the browser, here is an image :

P.S : i already tried react-svg but nothing happened, maybe because i didn't know how to use it.
Thank you in advance.

答:
From the screenshot, looks like your svg path is img/brand/svg-name.svg. to display the image don't include public in your source. for example, to display images in public/img/brand you use

```<code>// without specifying public directory
<img alt="test" src={'/img/brand/svg-name.svg'}/>
</code>```

Change your card src to

```<code><Card.Img className="marque-card" variant="top" src={`/${props.brand.imgUrl}`} />
</code>```

Title: How to display an svg image in reactjs

Body:
I am working on a web application with Nodejs and Reactjs and currently i'm retrieving data from the mongo database and displaying it with react.

Here is some code :

import React, {Component} from 'react';
import axios from '../../node_modules/axios';
import {Col,Card} from 'react-bootstrap';

import {BrowserRouter as Router,Link, useRouteMatch} from 'react-router-dom';

const Brand = props => (
<Col lg="4" className="d-inline-block">
  <Link to="/admin/Marques/MarqueDetails/1">
  <Card className="marque-card" style={{ width: '100%' }}>

{props.brand.name}

      <Card.Img className="marque-card" variant="top" src={`../../public/` +
       props.brand.imgUrl} />
  </Card>
  </Link>
</Col>
)

class cardBrand extends Component {

constructor(props) {
    super(props);

    this.state = {brands: []};
  }
  componentDidMount() {
    axios.get('http://localhost:5000/brand/')
      .then(response => {
        this.setState({ brands: response.data })
      })
      .catch((error) => {
        console.log(error);
      })
  }
  brandList() {
    return this.state.brands.map(currentBrand => {
      return <Brand brand={currentBrand} key={currentBrand._id}/>;
    })
  }
render() {
    return(
      <Col lg="12">
       { this.brandList() }
       </Col>
    )
  }
}
export default cardBrand;

As you can see i have the img/brand folders inside the public folder and the props.brand.imgUrl contains the path and the image name, but unfortunately it's not working on the browser, here is an image :

P.S : i already tried react-svg but nothing happened, maybe because i didn't know how to use it.
Thank you in advance.

Body:
From the screenshot, looks like your svg path is img/brand/svg-name.svg. to display the image don't include public in your source. for example, to display images in public/img/brand you use

// without specifying public directory
<img alt="test" src={'/img/brand/svg-name.svg'}/>

Change your card src to

<Card.Img className="marque-card" variant="top" src={`/${props.brand.imgUrl}`} />


来源: stackexchange

问:
Regex allowing spaces (for a Phone number regex)
I have this regex:

```<code>preg_match("#^([0-9]+)$#", $post['telephone'])
</code>```

who allow only numbers (for a phone number in the French type so 0123456789) but I would like to allow spaces. For example allow this type of string: "01 23 45 67 89".

Can you please help me?

答:
If it is OK to have spaces anywhere in your string then it is simple, just add it to your character class

```<code>preg_match("#^([0-9 ]+)$#", $post['telephone'])
</code>```

but this will allow 5 spaces in the beginning.

```<code>^\d{2}(?: ?\d+)*$
</code>```

would be a bit more sophisticated. Starts with two digits, then a optional group starting with an optional space followed by at least 1 digit. this group can be repeated 0 or more times.

This would match

01 23 45 67 89

0123456789

01234 5679

ContentLicense: CC BY-SA 3.0

Body:
I have this regex:

preg_match("#^([0-9]+)$#", $post['telephone'])

who allow only numbers (for a phone number in the French type so 0123456789) but I would like to allow spaces. For example allow this type of string: "01 23 45 67 89".

Can you please help me?

Body:
If it is OK to have spaces anywhere in your string then it is simple, just add it to your character class

preg_match("#^([0-9 ]+)$#", $post['telephone'])

but this will allow 5 spaces in the beginning.

^\d{2}(?: ?\d+)*$

would be a bit more sophisticated. Starts with two digits, then a optional group starting with an optional space followed by at least 1 digit. this group can be repeated 0 or more times.

This would match

01 23 45 67 89

0123456789

01234 5679


问:
Navigation Bar Heading Text Positioning
I have a navigation bar that will expand when the mouse is over it. I wish to display heading text once it is expanded (currently shows icons), I have used display: none on the heading tag, which then toggles to display: inline-block when the :hover event is active on the navbar. However, upon expansion of the navbar the text renders in on two lines before positioning itself into one which I want. I want to get rid of this and have the text render in as one line only while the navbar expands. My code:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Navigation Bar</title>
    <link href="css/styles.css" rel="stylesheet" type="text/css" />
    <script
      src="https://kit.fontawesome.com/6cc49d804e.js"
      crossorigin="anonymous"
    ></script>
  </head>

  <body>
    <div id="sidenav">
      <div id="sidenav-brand">
        <div id="sidenav-heading">
          <h2>Expanded Test</h2>
        </div>
        <div id="sidenav-expand">
          <i id="expand-icon" class="fas fa-angle-double-right fa-2x"></i>
        </div>
      </div>

      <div id="sidenav-links">
        <ul id="links">
          <li>
            <i class="fas fa-fw fa-id-card fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-graduation-cap fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-briefcase fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-smile-beam fa-2x"></i>
          </li>
        </ul>
      </div>
    </div>
  </body>
</html>

</code>```

```<code>body {
}

/* Make the width full-size then use javascript to minimise so content fits */
#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: width 0.5s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading {
  display: none;
}

#sidenav-heading h2 {
  margin: 0;
  color: white;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

#expand-icon {
  transition: transform 0.5s;
}

#sidenav:hover {
  width: 280px;
}

#sidenav:hover #expand-icon {
  transform: rotate(180deg);
}

#sidenav:hover #sidenav-heading {
  display: inline-block;
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

.fas {
  vertical-align: middle;
}

</code>```

Please check this fiddle for what I mean when the navbar expands:
https://jsfiddle.net/4pk25oLh/

P.S. The effect I want is the same as when you get rid of the space in the heading text (however, I will need the space). Any help would be greatly appreciated.

答:
I think white-space: nowrap; might help.

```<code> #sidenav-heading h2 {
      margin: 0;
      color: white;
      white-space: nowrap;
    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Navigation Bar Heading Text Positioning

Body:
I have a navigation bar that will expand when the mouse is over it. I wish to display heading text once it is expanded (currently shows icons), I have used display: none on the heading tag, which then toggles to display: inline-block when the :hover event is active on the navbar. However, upon expansion of the navbar the text renders in on two lines before positioning itself into one which I want. I want to get rid of this and have the text render in as one line only while the navbar expands. My code:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Navigation Bar</title>
    <link href="css/styles.css" rel="stylesheet" type="text/css" />

Expanded Test

body {
}

/* Make the width full-size then use javascript to minimise so content fits */
#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: width 0.5s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading {
  display: none;
}

#sidenav-heading h2 {
  margin: 0;
  color: white;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

#expand-icon {
  transition: transform 0.5s;
}

#sidenav:hover {
  width: 280px;
}

#sidenav:hover #expand-icon {
  transform: rotate(180deg);
}

#sidenav:hover #sidenav-heading {
  display: inline-block;
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

.fas {
  vertical-align: middle;
}

Please check this fiddle for what I mean when the navbar expands:
https://jsfiddle.net/4pk25oLh/

P.S. The effect I want is the same as when you get rid of the space in the heading text (however, I will need the space). Any help would be greatly appreciated.

Body:
I think white-space: nowrap; might help.

 #sidenav-heading h2 {
      margin: 0;
      color: white;
      white-space: nowrap;
    }


问:
How do I get AutoFixture AutoMoq to return results from injected services in an instantiated object?
I am trying to test a service class that consumers a repository service. I have customizations set up that I believe should work with my repository service, but instead return default Anonymous results. If you look at the code sample below, I'm trying to get the "Foo" objects that I registered in the Customization Class back when I call the svc.GetFoos method, instead I get nothing:

```<code>void Main()
{
    var fixture = new Fixture().Customize(
        new CompositeCustomization(
            new Customization(),
            new AutoMoqCustomization()));

    var svc = fixture.CreateAnonymous<Bar>();

    Console.Write(svc.GetFoos().Count());
}

// Define other methods and classes here
public class Bar
{

    public IQueryable<Foo> GetFoos()
    {
        return _rep.Query<Foo>();
    }

    public Bar(IRepository rep) { _rep = rep;  }

    private IRepository _rep;
}

public class Foo
{
    public string Name {get;set;}
}

public class Customization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        var f = fixture
                .Build<Foo>()
                .With(x => x.Name, "FromCustomize")
                .CreateMany(2)
                .AsQueryable();
        fixture.Register<IQueryable<Foo>>(() => f);
    }
}

public interface IRepository
{
    IQueryable<T> Query<T>();
}
</code>```

If I add the following code to the Main method after the fixture instantiation, it works how I want, but then I'm manually setting up my mocks, and I'm not sure what AutoFixture AutoMoq is getting me:

```<code>var mock = fixture.Freeze<Mock<IRepository>>();
mock
    .Setup(x => x.Query<Foo>())
    .Returns(fixture.CreateAnonymous<IQueryable<Foo>>);
</code>```

Thanks.

答:
I recently came across a similar topic. I was unable to execute queries for my automatically created IQueryable<T>.

Expression of type 'System.Object' cannot be used for parameter of type 'System.Linq.IQueryable`1[System.String]' of method 'Boolean Any...

I worked around this by creating a special specimen builder which always creates an array instead, and returns it AsQueryable.
In the end I did not use the code, but it works.

Very rough obviously, just trying things out...

void Main()
{
    Fixture fixture = new Fixture();

    fixture.Customize(new AutoMoqCustomization { ConfigureMembers = true, Relay = new QueryableBuilder() });

    // Possible ways to "override" the AutoMoqBehavior
//  fixture.Inject<string>("hallO");
//  fixture.Inject(new[] { "asd" });
//  fixture.Inject(new[] { "asds" }.AsQueryable());

    var queryable = fixture.Create<Foo>();
    queryable.Bar();

    fixture.Create<IQueryable<string>>().Any(x => x.Equals("asd"));
}

public class QueryableBuilder : ISpecimenBuilder
{
    MockRelay _Base = new MockRelay();

    public object Create(object request, ISpecimenContext context)
    {
        var t = request as Type;
        if (t == null ||
            !t.IsGenericType ||
            t.GetGenericTypeDefinition() != typeof(IQueryable<>))
            return _Base.Create(request, context);

        var queryableTypeName = typeof(IQueryable<>).Name;
        if (t.Name != queryableTypeName)
            return _Base.Create(request, context);

        var entityType = t.GetGenericArguments().Single();

        var tt = entityType.MakeArrayType();
        dynamic blbb = context.Resolve(tt);
        return ((IEnumerable)blbb).AsQueryable();
    }
}

public interface IHaveQueryable {
    IQueryable<string> Queryable {get;}
}

public class Foo {

    readonly IHaveQueryable _Queryable;

    public Foo(IHaveQueryable queryable){
        _Queryable = queryable;
    }

    public bool Bar(){
        return _Queryable.Queryable.Any(x => x.Equals("bar"));
    }
}
```

Body:
I am trying to test a service class that consumers a repository service. I have customizations set up that I believe should work with my repository service, but instead return default Anonymous results. If you look at the code sample below, I'm trying to get the "Foo" objects that I registered in the Customization Class back when I call the svc.GetFoos method, instead I get nothing:

void Main()
{
    var fixture = new Fixture().Customize(
        new CompositeCustomization(
            new Customization(),
            new AutoMoqCustomization()));

    var svc = fixture.CreateAnonymous<Bar>();

    Console.Write(svc.GetFoos().Count());
}

// Define other methods and classes here
public class Bar
{

    public IQueryable<Foo> GetFoos()
    {
        return _rep.Query<Foo>();
    }

    public Bar(IRepository rep) { _rep = rep;  }

    private IRepository _rep;
}

public class Foo
{
    public string Name {get;set;}
}

public class Customization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        var f = fixture
                .Build<Foo>()
                .With(x => x.Name, "FromCustomize")
                .CreateMany(2)
                .AsQueryable();
        fixture.Register<IQueryable<Foo>>(() => f);
    }
}

public interface IRepository
{
    IQueryable<T> Query<T>();
}

If I add the following code to the Main method after the fixture instantiation, it works how I want, but then I'm manually setting up my mocks, and I'm not sure what AutoFixture AutoMoq is getting me:

var mock = fixture.Freeze<Mock<IRepository>>();
mock
    .Setup(x => x.Query<Foo>())
    .Returns(fixture.CreateAnonymous<IQueryable<Foo>>);

Thanks.


问:
Lock USED cells every hour or 30 min
I have file that is used by a lot of people. They are entering data from time to time. I have locked and unlocked cells so the people can enter the data but not to mess around with the generated data (like time). I have a code that is locking the cell after every enter but then if someone enter the wrong data it can't be undone if I am not around.

So I decided to create VBA code to lock all USED cells every X minutes (so if someone make a mistake to fix it) but don't know how to do the minutes part.

I found this nice code for locking the used cells :

```<code>Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
On Error Resume Next
'Resume to next line if any error occurs
 Dim Cell As Range
 With ActiveSheet
 'first of all unprotect the entire
 'sheet and unlock all cells
 .Unprotect Password:=""
 .Cells.Locked = False
 'Now search for non blank cells
 'and lock them and unlock blank cells
 For Each Cell In ActiveSheet.UsedRange
 If Cell.Value = "" Then
 Cell.Locked = False
 Else
 Cell.Locked = True
 End If
 Next Cell
 .Protect Password:=""
 'Protect with blank password, you can change it
 End With
Exit Sub
End Sub
</code>```

The only thing that I need is to add a code to execute the above every 30 mins or 1 hour. Don't know if the Sub shoud be Sub Workbook_BeforeSave or AfterSave for this one as after every entry the file save itself automatically or should be like module.

Thank you in advance.

答:
Thank you Ricardo.

I manage to create this :

```<code>Private Sub save_cells()
On Error Resume Next
'Resume to next line if any error occurs
 Dim Cell As Range
 With ActiveSheet
 'first of all unprotect the entire
 'sheet and unlock all cells
 .Unprotect Password:="0"
 .Cells.Locked = False
 'Now search for non blank cells
 'and lock them and unlock blank cells
 For Each Cell In ActiveSheet.UsedRange
 If Cell.Value = "" Then
 Cell.Locked = False
 Else
 Cell.Locked = True
 End If
 If Cell.HasFormula Then
Cell.Locked = True
Cell.FormulaHidden = True
End If
 Next Cell
 .Protect Password:="0"
 'Protect with blank password, you can change it
 End With
 Application.SendKeys "{RIGHT}{LEFT}"
 Call savetimer
Exit Sub
End Sub

 Sub savetimer()
    Application.OnTime TimeValue("23:15:30"), "save_cells"
End Sub
</code>```

The only problem that I have now is that the code is scanning all of the rows and making my file slow when I put it to lock every 15 minutes or so. For that reason I decided to lock the cells one time per day.

If someone have idea how to amend the code to scan only A3:O600 whould be great.

Title: Lock USED cells every hour or 30 min

Body:
I have file that is used by a lot of people. They are entering data from time to time. I have locked and unlocked cells so the people can enter the data but not to mess around with the generated data (like time). I have a code that is locking the cell after every enter but then if someone enter the wrong data it can't be undone if I am not around.

So I decided to create VBA code to lock all USED cells every X minutes (so if someone make a mistake to fix it) but don't know how to do the minutes part.

I found this nice code for locking the used cells :

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
On Error Resume Next
'Resume to next line if any error occurs
 Dim Cell As Range
 With ActiveSheet
 'first of all unprotect the entire
 'sheet and unlock all cells
 .Unprotect Password:=""
 .Cells.Locked = False
 'Now search for non blank cells
 'and lock them and unlock blank cells
 For Each Cell In ActiveSheet.UsedRange
 If Cell.Value = "" Then
 Cell.Locked = False
 Else
 Cell.Locked = True
 End If
 Next Cell
 .Protect Password:=""
 'Protect with blank password, you can change it
 End With
Exit Sub
End Sub

The only thing that I need is to add a code to execute the above every 30 mins or 1 hour. Don't know if the Sub shoud be Sub Workbook_BeforeSave or AfterSave for this one as after every entry the file save itself automatically or should be like module.

Thank you in advance.

Body:
Thank you Ricardo.

I manage to create this :

Private Sub save_cells()
On Error Resume Next
'Resume to next line if any error occurs
 Dim Cell As Range
 With ActiveSheet
 'first of all unprotect the entire
 'sheet and unlock all cells
 .Unprotect Password:="0"
 .Cells.Locked = False
 'Now search for non blank cells
 'and lock them and unlock blank cells
 For Each Cell In ActiveSheet.UsedRange
 If Cell.Value = "" Then
 Cell.Locked = False
 Else
 Cell.Locked = True
 End If
 If Cell.HasFormula Then
Cell.Locked = True
Cell.FormulaHidden = True
End If
 Next Cell
 .Protect Password:="0"
 'Protect with blank password, you can change it
 End With
 Application.SendKeys "{RIGHT}{LEFT}"
 Call savetimer
Exit Sub
End Sub

 Sub savetimer()
    Application.OnTime TimeValue("23:15:30"), "save_cells"
End Sub

The only problem that I have now is that the code is scanning all of the rows and making my file slow when I put it to lock every 15 minutes or so. For that reason I decided to lock the cells one time per day.

If someone have idea how to amend the code to scan only A3:O600 whould be great.


问:
How to access and copy Cloudian S3 files using AWS CLI
I'm new to AWS S3. I need to access a Cloudian S3 bucket and copy files within a bucket to my local directory. What I was given was 4 piece of info in the following format:

```<code>•   Access key: 5x4x3x2x1xxx
•   Secret key: ssssssssssss
•   S3 endpoint: https://s3-aaa.xxx.bbb.net
•   Storage path: store/STORE1/
</code>```

When I'm trying to do a simple command like ls, I get this error:

aws s3 ls s3-aaa.xxx.bbb.net or aws s3 ls https://s3-aaa.xxx.bbb.net:

```<code>An error occurred (NoSuchBucket) when calling the ListObjectsV2 operation: The specified bucket does not exist
</code>```

What is the right commands to access the bucket and copy a file to my local directory?

答:
It looks like you are missing your bucket name - you should be able to see it on the AWS S3 console.
You should also be able to use either the cp or sync command like so:

```<code>aws s3 cp s3://SOURCE_BUCKET_NAME/s3/file/key SomeDrive:/path/to/my/local/directory
</code>```

Or:

```<code>aws s3 sync s3://SOURCE_BUCKET_NAME/s3/file/key SomeDrive:/path/to/my/local/directory
</code>```

You may also need to check the permissions on the s3 bucket.

More info:
aws s3 sync: https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html

aws s3 cp: https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html

aws s3 permissions: https://aws.amazon.com/premiumsupport/knowledge-center/s3-bucket-access-default-encryption/

Body:
I'm new to AWS S3. I need to access a Cloudian S3 bucket and copy files within a bucket to my local directory. What I was given was 4 piece of info in the following format:

•   Access key: 5x4x3x2x1xxx
•   Secret key: ssssssssssss
•   S3 endpoint: https://s3-aaa.xxx.bbb.net
•   Storage path: store/STORE1/

When I'm trying to do a simple command like ls, I get this error:

aws s3 ls s3-aaa.xxx.bbb.net or aws s3 ls https://s3-aaa.xxx.bbb.net:

An error occurred (NoSuchBucket) when calling the ListObjectsV2 operation: The specified bucket does not exist

What is the right commands to access the bucket and copy a file to my local directory?

Body:
It looks like you are missing your bucket name - you should be able to see it on the AWS S3 console.
You should also be able to use either the cp or sync command like so:

aws s3 cp s3://SOURCE_BUCKET_NAME/s3/file/key SomeDrive:/path/to/my/local/directory

Or:

aws s3 sync s3://SOURCE_BUCKET_NAME/s3/file/key SomeDrive:/path/to/my/local/directory

You may also need to check the permissions on the s3 bucket.

More info:
aws s3 sync: https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html

aws s3 cp: https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html

aws s3 permissions: https://aws.amazon.com/premiumsupport/knowledge-center/s3-bucket-access-default-encryption/


答:
How about this?</p>

```<code>preg_match("/^\d(\s*\d)*$/", $post['telephone'])
</code>```

Title: Regex allowing spaces (for a Phone number regex)

Body:
How about this?

preg_match("/^\d(\s*\d)*$/", $post['telephone'])


问:
This application failed to start because no Qt platform plugin could be initialized
I am stuck trying to run a very simple Python script, getting this error:

```<code>qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

zsh: abort      python3 mypuppy1.py
</code>```

The script code is:

```<code>import cv2
img = cv2.imread('00-puppy.jpg')
while True:
    cv2.imshow('Puppy',img)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()
</code>```

However this Notebook code works in JupyterLab:

```<code>import cv2
img = cv2.imread('00-puppy.jpg')
cv2.imshow('Puppy', img)
cv2.waitKey()
</code>```

I am on macOS, using Anaconda and JupyterLab. I would appreciate any help with this issue. Thanks!

答:
Try installing </p>

```<code>pip3 install opencv-python==4.1.2.30
</code>```

Body:
I am stuck trying to run a very simple Python script, getting this error:

qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

zsh: abort      python3 mypuppy1.py

The script code is:

import cv2
img = cv2.imread('00-puppy.jpg')
while True:
    cv2.imshow('Puppy',img)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()

However this Notebook code works in JupyterLab:

import cv2
img = cv2.imread('00-puppy.jpg')
cv2.imshow('Puppy', img)
cv2.waitKey()

I am on macOS, using Anaconda and JupyterLab. I would appreciate any help with this issue. Thanks!

Body:
Try installing

pip3 install opencv-python==4.1.2.30


问:
Linux writing GPU drivers to print arbitrary outputs from kernel side
I have questions about GPU drivers for linux kernel.

1-) Is it possible to write a custom kernel module to print words or colors on screen like VGA using a GPU over PCI express ?

2-) If it is, is it generic or device/chip dependent?

3-) If it is, is it possible with writing MMIO space?

What is on my mind is, I want to write a simple kernel module to print some arbitrary values over PCI express bus. My GPU is only have mDP and DVI-D outputs and it has a big kernel driver in linux kernel.

答:
First; let's split a video card into multiple different pieces:

video RAM (and probably some ROM for BIOS and/or UEFI that's used during boot, that we can ignore because it's useless after boot)

something that controls video RAM, converts physical accesses into VRAM accesses, may include "stealing of system RAM" (for integrated video), and probably includes some kind of DMA engine (to accelerate the transfer of data between system RAM and video RAM)

something that controls video signals being sent to a monitor (video mode timings), and pumps pixel data from frame buffer to a (VGA, DVI, HDMI, ...) socket, and is able to obtain information (EDID/Extended Display Identification Data) from the monitor. Note that if a video card supports multiple monitors all of this would have to be duplicated multiple times.

various fixed function accelerators - e.g. MPEG decoder.

a "processor unit" that executes some kind of machine code and does things. This is the GPU; and is typically used to execute programs that were compiled elsewhere (e.g. by video driver) from a more portable language (HLSL, GLSL, C) and used for shaders and GPGPU.

1-) Is it possible to write a custom kernel module to print words or colors on screen like VGA using a GPU over PCI express ?

In theory; yes. In practice it'd be far easier to do it without using the GPU (just writing pixel data directly to video RAM/frame buffer using the CPU instead), partly because using GPUs is unnecessary overkill, and partly because the compilers needed for "portability to different GPUs" are in user-space and not in the kernel. However this is mostly silly anyway - there's no guarantee that whatever is actually using the frame buffer (e.g. maybe a full screen game) won't overwrite whatever the kernel does before its sent to the monitor and no guarantee that the user will ever be able to see whatever the kernel did.

2-) If it is, is it generic or device/chip dependent?

It's very device/chip dependent; and also very "situation dependent" (e.g. depending on how other software in user-space, like Gnome or KDE or Wine or ..., is currently using the video card).

3-) If it is, is it possible with writing MMIO space?

Yes (but "MMIO" includes frame buffer, memory used for textures, and all of the internal control registers for all of the pieces of a video card). It's probably also possible to teach someone to play the piano by stabbing their brain with needles/electrodes - "possible" does NOT mean "easy" or "sensible".

To do what I think your goal is properly; you'd probably want to modify all "video card drivers" (where "video card driver" in Linux is many pieces strewn all over the place, with parts in kernel and parts in user-space libraries; where some parts are likely proprietary/closed source); so that the video card driver is responsible for setting up a "reserved for kernel only" overlay (that is super-imposed on top of whatever user-space wanted to display, for each different monitor). However, even in that case it probably can't work for some cases (old and/or low-end video cards often found in servers that can't support overlays, remote desktop where you're using something like RDP or X over a network and not a video card, video cards being used for "PCI passthrough" by hyper-visors/virtual machines).


问:
Kubernetes cert-manager cannot access letsencrypt API server
I'm trying to setup cert-manager v0.13.0 on my minikube cluster. I've followed their tutorial, but it seems the cert-manager pod keeps timing out, trying to get to the LetsEncrypt API servers:

```<code>$ kubectl apply --validate=false -f https://raw.githubusercontent.com/jetstack/cert-manager/v0.13.0/deploy/manifests/00-crds.yaml
$ kubectl create namespace cert-manager
$ helm repo add jetstack https://charts.jetstack.io
$ helm repo update
$ helm install cert-manager --namespace cert-manager --version v0.13.0 jetstack/cert-manager
</code>```

Here's my acme yaml:

```<code>apiVersion: cert-manager.io/v1alpha2
kind: ClusterIssuer
metadata:
  name: letsencrypt
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: xx@yyy.com
    privateKeySecretRef:
      name: my-issuer-account-key
    solvers:
      - dns01:
          cloudflare:
            email: xx@yyy.com
            apiKeySecretRef:
              name: cloudflare-api-token-secret
              key: api-token
</code>```

The cert-manager pod logs show the timeout:

```<code>I0209 20:43:34.382250       1 logger.go:90] Calling GetAccount
E0209 20:43:39.384093       1 setup.go:208] cert-manager/controller/clusterissuers "msg"="failed to verify ACME account" "error"="Get https://acme-staging-v02.api.letsencrypt.com/directory: dial tcp 192.64.119.254:443: i/o timeout" "related_resource_kind"="Secret" "related_resource_name"="my-issuer-account-key" "related_resource_namespace"="cert-manager" "resource_kind"="ClusterIssuer" "resource_name"="letsencrypt" "resource_namespace"=""
E0209 20:43:39.385555       1 sync.go:81] cert-manager/controller/clusterissuers "msg"="error setting up issuer" "error"="Get https://acme-staging-v02.api.letsencrypt.com/directory: dial tcp 192.64.119.254:443: i/o timeout" "resource_kind"="ClusterIssuer" "resource_name"="letsencrypt" "resource_namespace"=""
E0209 20:43:39.389659       1 controller.go:131] cert-manager/controller/clusterissuers "msg"="re-queuing item  due to error processing" "error"="Get https://acme-staging-v02.api.letsencrypt.com/directory: dial tcp 192.64.119.254:443: i/o timeout" "key"="letsencrypt"
</code>```

So I setup a bash pod to check the API's reachability, and there seems to be no problem:

```<code>$ kubectl run my-shell -n cert-manager --rm -i --tty --image ubuntu -- bash
$ apt-get update -y
$ apt-get install -y curl
$ https://acme-staging-v02.api.letsencrypt.org/directory

{
"xxxxxxxxx": "https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/33417",
"keyChange": "https://acme-staging-v02.api.letsencrypt.org/acme/key-change",
"meta": {
    "caaIdentities": [
    "letsencrypt.org"
    ],
    "termsOfService": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf",
    "website": "https://letsencrypt.org/docs/staging-environment/"
},
"newAccount": "https://acme-staging-v02.api.letsencrypt.org/acme/new-acct",
"newNonce": "https://acme-staging-v02.api.letsencrypt.org/acme/new-nonce",
"newOrder": "https://acme-staging-v02.api.letsencrypt.org/acme/new-order",
"revokeCert": "https://acme-staging-v02.api.letsencrypt.org/acme/revoke-cert"
}
</code>```

Update: as requested, here's the /etc/resolve.conf file from the bash pod:

```<code>nameserver 10.96.0.10
search cert-manager.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
</code>```

But I don't know how to get the same file from the cert-manager pod, as it doesn't let me open /bin/sh or /bin/bash.

I have no idea why the timeout occurs. Any thoughts?

答:
You mentioned acme server to acme-staging-v02.api.letsencrypt.org/directory, but it seems request is done to acme-staging-v02.api.letsencrypt.com/directory. There is a diff .com vs .org. Please check your clusterissuer yaml with the command:

```<code>kubectl get clusterissuer letsencrypt -o yaml
</code>```

If you added wrong url on the yaml, you can always delete that clusterissuer, and create again.

Body:
I'm trying to setup cert-manager v0.13.0 on my minikube cluster. I've followed their tutorial, but it seems the cert-manager pod keeps timing out, trying to get to the LetsEncrypt API servers:

$ kubectl apply --validate=false -f https://raw.githubusercontent.com/jetstack/cert-manager/v0.13.0/deploy/manifests/00-crds.yaml
$ kubectl create namespace cert-manager
$ helm repo add jetstack https://charts.jetstack.io
$ helm repo update
$ helm install cert-manager --namespace cert-manager --version v0.13.0 jetstack/cert-manager

Here's my acme yaml:

apiVersion: cert-manager.io/v1alpha2
kind: ClusterIssuer
metadata:
  name: letsencrypt
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: xx@yyy.com
    privateKeySecretRef:
      name: my-issuer-account-key
    solvers:
      - dns01:
          cloudflare:
            email: xx@yyy.com
            apiKeySecretRef:
              name: cloudflare-api-token-secret
              key: api-token

The cert-manager pod logs show the timeout:

I0209 20:43:34.382250       1 logger.go:90] Calling GetAccount
E0209 20:43:39.384093       1 setup.go:208] cert-manager/controller/clusterissuers "msg"="failed to verify ACME account" "error"="Get https://acme-staging-v02.api.letsencrypt.com/directory: dial tcp 192.64.119.254:443: i/o timeout" "related_resource_kind"="Secret" "related_resource_name"="my-issuer-account-key" "related_resource_namespace"="cert-manager" "resource_kind"="ClusterIssuer" "resource_name"="letsencrypt" "resource_namespace"=""
E0209 20:43:39.385555       1 sync.go:81] cert-manager/controller/clusterissuers "msg"="error setting up issuer" "error"="Get https://acme-staging-v02.api.letsencrypt.com/directory: dial tcp 192.64.119.254:443: i/o timeout" "resource_kind"="ClusterIssuer" "resource_name"="letsencrypt" "resource_namespace"=""
E0209 20:43:39.389659       1 controller.go:131] cert-manager/controller/clusterissuers "msg"="re-queuing item  due to error processing" "error"="Get https://acme-staging-v02.api.letsencrypt.com/directory: dial tcp 192.64.119.254:443: i/o timeout" "key"="letsencrypt"

So I setup a bash pod to check the API's reachability, and there seems to be no problem:

$ kubectl run my-shell -n cert-manager --rm -i --tty --image ubuntu -- bash
$ apt-get update -y
$ apt-get install -y curl
$ https://acme-staging-v02.api.letsencrypt.org/directory

{
"xxxxxxxxx": "https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/33417",
"keyChange": "https://acme-staging-v02.api.letsencrypt.org/acme/key-change",
"meta": {
    "caaIdentities": [
    "letsencrypt.org"
    ],
    "termsOfService": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf",
    "website": "https://letsencrypt.org/docs/staging-environment/"
},
"newAccount": "https://acme-staging-v02.api.letsencrypt.org/acme/new-acct",
"newNonce": "https://acme-staging-v02.api.letsencrypt.org/acme/new-nonce",
"newOrder": "https://acme-staging-v02.api.letsencrypt.org/acme/new-order",
"revokeCert": "https://acme-staging-v02.api.letsencrypt.org/acme/revoke-cert"
}

Update: as requested, here's the /etc/resolve.conf file from the bash pod:

nameserver 10.96.0.10
search cert-manager.svc.cluster.local svc.cluster.local cluster.local
options ndots:5

But I don't know how to get the same file from the cert-manager pod, as it doesn't let me open /bin/sh or /bin/bash.

I have no idea why the timeout occurs. Any thoughts?

Body:
You mentioned acme server to acme-staging-v02.api.letsencrypt.org/directory, but it seems request is done to acme-staging-v02.api.letsencrypt.com/directory. There is a diff .com vs .org. Please check your clusterissuer yaml with the command:

kubectl get clusterissuer letsencrypt -o yaml

If you added wrong url on the yaml, you can always delete that clusterissuer, and create again.


问:
Java Threads - Keep function in sync with multiple returning values from threads
This is just a concept :

I want to have a int be updated, by a function that is running inside multiple threads.

My function randomly chooses an int and checks if it's bigger than the existing int.

If so it updates the variable.

How do I ensure my values never clash or my function is looking at an older value not yet updated?

I'm new to threads so any information is valuable.

答:
This a job for AtomicInteger!

```<code>AtomicInteger atomic;
...
int newValue = atomic.accumulateAndGet(rand, Math::max);
</code>```

Body:
This a job for AtomicInteger!

AtomicInteger atomic;
...
int newValue = atomic.accumulateAndGet(rand, Math::max);


问:
problem using twitter in application android
I used this link http://abhinavasblog.blogspot.com/2010/09/using-twitter-with-oauth-on-andorid.html to use Twitter in my application Android.
But nothing appears in interface. Should I create the interface of authentification twitter or it generated directement by code. Can any one explain me why I didn't have any displayed</p>

答:
Try this link also :

https://gist.github.com/97ed32efcada70516cc9

You will need:

signpost-commonshttp4.....java

signpost-core.....java

Search for these jar files on net...........

Hope it helps


问:
Python Teradataml Connection
I'm attempting to use the Python teradataml library for Teradata to create a simple database connection using the logmech of LDAP.  However, i'm greeted with an attribute error of 'NoneType' ojbect has no attribute dialect in relation to sqlalchemy_engine.dialect.

My code to create the connection with the hostname changed

```<code>import teradataml as tdml
from teradataml import *

hostname = "address of host"
schema = "DL_RBA_DSS"

td_context = create_context(host = hostname, logmech='LDAP', temp_database_name = schema)
print(td_context)
</code>```

When running the code it gives me the following error:

```<code>File "c:/Python/teradatamlconnection.py", line 7, in <module>
    td_context = create_context(host = hostname, logmech='LDAP', temp_database_name = schema)
  File "C:\Users\UserID\AppData\Local\Programs\Python\Python36\lib\site-packages\teradataml\context\context.py", line 287, in create_context
    _load_function_aliases()
  File "C:\Users\UserID\AppData\Local\Programs\Python\Python36\lib\site-packages\teradataml\context\context.py", line 532, in _load_function_aliases
    __set_vantage_version()
  File "C:\Users\UserID\AppData\Local\Programs\Python\Python36\lib\site-packages\teradataml\context\context.py", line 562, in __set_vantage_version
    if td_sqlalchemy_engine.dialect.has_table(td_sqlalchemy_engine, "versionInfo", schema="pm"):
AttributeError: 'NoneType' object has no attribute 'dialect'
</code>```

I have tried to update the teradatasqlalchemy and sqlalchemy library, but i still am greeted with the error.  It shows all requirements are satisfied:

PS C:\Python\dsssecurity> pip install teradatasqlalchemy --upgrade

```<code>Requirement already up-to-date: teradatasqlalchemy in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (16.20.0.8)
Requirement already satisfied, skipping upgrade: teradatasql in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradatasqlalchemy) (16.20.0.52)
Requirement already satisfied, skipping upgrade: sqlalchemy>=1.2.11 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradatasqlalchemy) (1.3.13)
Requirement already satisfied, skipping upgrade: pycryptodome in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradatasql->teradatasqlalchemy) (3.9.0)
PS C:\Python\dsssecurity> pip install teradataml --upgrade
Requirement already up-to-date: teradataml in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (16.20.0.4)
Requirement already satisfied, skipping upgrade: teradatasql in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradataml) (16.20.0.52)
Requirement already satisfied, skipping upgrade: pandas>=0.22 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradataml) (1.0.1)
Requirement already satisfied, skipping upgrade: psutil in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradataml) (5.6.3)
Requirement already satisfied, skipping upgrade: teradatasqlalchemy>=16.20.0.8 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradataml) (16.20.0.8)
Requirement already satisfied, skipping upgrade: pycryptodome in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradatasql->teradataml) (3.9.0)
Requirement already satisfied, skipping upgrade: numpy>=1.13.3 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from pandas>=0.22->teradataml) (1.18.1)
Requirement already satisfied, skipping upgrade: pytz>=2017.2 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from pandas>=0.22->teradataml) (2017.2)
Requirement already satisfied, skipping upgrade: python-dateutil>=2.6.1 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from pandas>=0.22->teradataml) (2.6.1)
Requirement already satisfied, skipping upgrade: sqlalchemy>=1.2.11 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradatasqlalchemy>=16.20.0.8->teradataml) (1.3.13)
Requirement already satisfied, skipping upgrade: six>=1.5 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from python-dateutil>=2.6.1->pandas>=0.22->teradataml) (1.11.0)
</code>```

答:
For logmech='LDAP' you must supply a username and password, either via the separate attributes or as part of a logdata string.

For logdata the string can start with any of the formats authcid=diruser password=dirpass or just diruser password=dirpass or diruser@@dirpass. If there are multiple directory mappings then you can append qualifiers for database user= and/or profile= to be used; if there are multiple directory realms you can append a realm= qualifier`

Title: Python Teradataml Connection

Body:
I'm attempting to use the Python teradataml library for Teradata to create a simple database connection using the logmech of LDAP.  However, i'm greeted with an attribute error of 'NoneType' ojbect has no attribute dialect in relation to sqlalchemy_engine.dialect.

My code to create the connection with the hostname changed

import teradataml as tdml
from teradataml import *

hostname = "address of host"
schema = "DL_RBA_DSS"

td_context = create_context(host = hostname, logmech='LDAP', temp_database_name = schema)
print(td_context)

When running the code it gives me the following error:

File "c:/Python/teradatamlconnection.py", line 7, in <module>
    td_context = create_context(host = hostname, logmech='LDAP', temp_database_name = schema)
  File "C:\Users\UserID\AppData\Local\Programs\Python\Python36\lib\site-packages\teradataml\context\context.py", line 287, in create_context
    _load_function_aliases()
  File "C:\Users\UserID\AppData\Local\Programs\Python\Python36\lib\site-packages\teradataml\context\context.py", line 532, in _load_function_aliases
    __set_vantage_version()
  File "C:\Users\UserID\AppData\Local\Programs\Python\Python36\lib\site-packages\teradataml\context\context.py", line 562, in __set_vantage_version
    if td_sqlalchemy_engine.dialect.has_table(td_sqlalchemy_engine, "versionInfo", schema="pm"):
AttributeError: 'NoneType' object has no attribute 'dialect'

I have tried to update the teradatasqlalchemy and sqlalchemy library, but i still am greeted with the error.  It shows all requirements are satisfied:

PS C:\Python\dsssecurity> pip install teradatasqlalchemy --upgrade

Requirement already up-to-date: teradatasqlalchemy in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (16.20.0.8)
Requirement already satisfied, skipping upgrade: teradatasql in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradatasqlalchemy) (16.20.0.52)
Requirement already satisfied, skipping upgrade: sqlalchemy>=1.2.11 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradatasqlalchemy) (1.3.13)
Requirement already satisfied, skipping upgrade: pycryptodome in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradatasql->teradatasqlalchemy) (3.9.0)
PS C:\Python\dsssecurity> pip install teradataml --upgrade
Requirement already up-to-date: teradataml in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (16.20.0.4)
Requirement already satisfied, skipping upgrade: teradatasql in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradataml) (16.20.0.52)
Requirement already satisfied, skipping upgrade: pandas>=0.22 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradataml) (1.0.1)
Requirement already satisfied, skipping upgrade: psutil in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradataml) (5.6.3)
Requirement already satisfied, skipping upgrade: teradatasqlalchemy>=16.20.0.8 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradataml) (16.20.0.8)
Requirement already satisfied, skipping upgrade: pycryptodome in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradatasql->teradataml) (3.9.0)
Requirement already satisfied, skipping upgrade: numpy>=1.13.3 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from pandas>=0.22->teradataml) (1.18.1)
Requirement already satisfied, skipping upgrade: pytz>=2017.2 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from pandas>=0.22->teradataml) (2017.2)
Requirement already satisfied, skipping upgrade: python-dateutil>=2.6.1 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from pandas>=0.22->teradataml) (2.6.1)
Requirement already satisfied, skipping upgrade: sqlalchemy>=1.2.11 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from teradatasqlalchemy>=16.20.0.8->teradataml) (1.3.13)
Requirement already satisfied, skipping upgrade: six>=1.5 in c:\users\UserID\appdata\local\programs\python\python36\lib\site-packages (from python-dateutil>=2.6.1->pandas>=0.22->teradataml) (1.11.0)


问:
How do I create a multi-select header filter in tabulator?
This question has been asked several times in various forms over the years in the Tabulator GitHub repository. Here are a few instances:
https://github.com/olifolkerd/tabulator/issues/527, https://github.com/olifolkerd/tabulator/issues/1759

I'm looking for an example of how to achieve this using a dropdown menu of some form --- ideally as described in #1759 (dropdown with checkboxes) but another solution that would work for us is a "select" editor that adds/removes CSVs in the header filter when a value is selected/deselected (extending on the example provided in #527).

Hopefully someone with experience working with custom header filters / editors in tabulator can provide an example of a multi-select header filter dropdown, but if not, then I will post a JSFiddle link myself once I've got something that works.

答:
Here is an example of a custom header filter for tabulator of 'select multiple' type. It can be converted to a dropdown style if desired using external sources such as Chosen or multiselect.js

(I recommend running the below Code Snippet in Full Page view).

const speciesTypes = ['Human', 'Android', 'Betazoid', 'Klingon', 'Ferengi', 'Tamarian'];

function multiSelectHeaderFilter(cell) {

  var values = speciesTypes;

  const filterFunc = (rowData) => {
    return values.includes(rowData['species']);
  }

  const getSelectedValues = (multiSelect) => {
    var result = [];
    var options = multiSelect && multiSelect.options;
    var opt;

    for (var i = 0, iLen = options.length; i < iLen; i++) {
      opt = options[i];

      if (opt.selected) {
        result.push(opt.value || opt.text);
      }
    }
    return result;
  }

  const onChange = () => {
    var editor = document.getElementById('speciesSelector');
    values = getSelectedValues(editor);
    console.log("values: " + values);
    cell.getColumn().getTable().removeFilter(filterFunc);
    cell.getColumn().getTable().addFilter(filterFunc);
  }

  var select = document.createElement("select");
  select.multiple = "multiple";
  select.id = 'speciesSelector';
  select.class = "chosen-select";
  select.style = 'width: 100%';
  speciesTypes.forEach(species => {
    select.innerHTML += "<option id='" + species + "' value='" + species + "' selected='selected'>" + species + "</option>";
  });
  cell.getColumn().getTable().addFilter(filterFunc);
  select.addEventListener('change', onChange);

  return select;
}

var table = new Tabulator("#tabulator", {
  layout: "fitColumns",
  data: [{
    name: 'Geordi La Forge',
    species: 'Human'
  }, {
    name: 'Dathon',
    species: 'Tamarian'
  }, {
    name: 'Jean-Luc Picard',
    species: 'Human'
  }, {
    name: 'Worf, son of Mogh',
    species: 'Klingon'
  }, {
    name: 'Tasha Yarr',
    species: 'Human'
  }, {
    name: 'Data',
    species: 'Android'
  }, {
    name: 'Wesley Crusher',
    species: 'Human'
  }, {
    name: 'Jalad',
    species: 'Tamarian'
  }, {
    name: 'Lwaxana Troi',
    species: 'Betazoid'
  }, {
    name: 'Temba',
    species: 'Tamarian'
  }, {
    name: 'T\'Kuvma',
    species: 'Klingon'
  }, {
    name: 'Lore',
    species: 'Android'
  }, {
    name: 'Noonian Soongh',
    species: 'Human'
  }, {
    name: 'Darmok',
    species: 'Tamarian'
  }, {
    name: 'Reittan Grax',
    species: 'Betazoid'
  }, {
    name: 'Quark',
    species: 'Ferengi'
  }],
  headerSort: true,
  columns: [{
    title: 'Name',
    field: 'name',
    sorter: 'string'
  }, {
    title: 'Species',
    field: 'species',
    sorter: 'string',
    headerFilter: multiSelectHeaderFilter,
    headerFilterLiveFilter: false
  }, ],
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

  <head>
    <link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">
    <script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.5.3/dist/js/tabulator.min.js"></script>
  </head>

  <body>
    <div id="tabulator"></div>
  </body>

</html></code>```

JSFiddle: https://jsfiddle.net/jjech/3th28pv0/

Body:
Here is an example of a custom header filter for tabulator of 'select multiple' type. It can be converted to a dropdown style if desired using external sources such as Chosen or multiselect.js

(I recommend running the below Code Snippet in Full Page view).

const speciesTypes = ['Human', 'Android', 'Betazoid', 'Klingon', 'Ferengi', 'Tamarian'];

function multiSelectHeaderFilter(cell) {

  var values = speciesTypes;

  const filterFunc = (rowData) => {
    return values.includes(rowData['species']);
  }

  const getSelectedValues = (multiSelect) => {
    var result = [];
    var options = multiSelect && multiSelect.options;
    var opt;

    for (var i = 0, iLen = options.length; i < iLen; i++) {
      opt = options[i];

      if (opt.selected) {
        result.push(opt.value || opt.text);
      }
    }
    return result;
  }

  const onChange = () => {
    var editor = document.getElementById('speciesSelector');
    values = getSelectedValues(editor);
    console.log("values: " + values);
    cell.getColumn().getTable().removeFilter(filterFunc);
    cell.getColumn().getTable().addFilter(filterFunc);
  }

  var select = document.createElement("select");
  select.multiple = "multiple";
  select.id = 'speciesSelector';
  select.class = "chosen-select";
  select.style = 'width: 100%';
  speciesTypes.forEach(species => {
    select.innerHTML += "<option id='" + species + "' value='" + species + "' selected='selected'>" + species + "</option>";
  });
  cell.getColumn().getTable().addFilter(filterFunc);
  select.addEventListener('change', onChange);

  return select;
}

var table = new Tabulator("#tabulator", {
  layout: "fitColumns",
  data: [{
    name: 'Geordi La Forge',
    species: 'Human'
  }, {
    name: 'Dathon',
    species: 'Tamarian'
  }, {
    name: 'Jean-Luc Picard',
    species: 'Human'
  }, {
    name: 'Worf, son of Mogh',
    species: 'Klingon'
  }, {
    name: 'Tasha Yarr',
    species: 'Human'
  }, {
    name: 'Data',
    species: 'Android'
  }, {
    name: 'Wesley Crusher',
    species: 'Human'
  }, {
    name: 'Jalad',
    species: 'Tamarian'
  }, {
    name: 'Lwaxana Troi',
    species: 'Betazoid'
  }, {
    name: 'Temba',
    species: 'Tamarian'
  }, {
    name: 'T\'Kuvma',
    species: 'Klingon'
  }, {
    name: 'Lore',
    species: 'Android'
  }, {
    name: 'Noonian Soongh',
    species: 'Human'
  }, {
    name: 'Darmok',
    species: 'Tamarian'
  }, {
    name: 'Reittan Grax',
    species: 'Betazoid'
  }, {
    name: 'Quark',
    species: 'Ferengi'
  }],
  headerSort: true,
  columns: [{
    title: 'Name',
    field: 'name',
    sorter: 'string'
  }, {
    title: 'Species',
    field: 'species',
    sorter: 'string',
    headerFilter: multiSelectHeaderFilter,
    headerFilterLiveFilter: false
  }, ],
});

<html>

  <head>
    <link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">
    <script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.5.3/dist/js/tabulator.min.js"></script>
  </head>

  <body>
    <div id="tabulator"></div>
  </body>

</html>

JSFiddle: https://jsfiddle.net/jjech/3th28pv0/


问:
Why does my automated Blue Prism process fail in some stages in scheduler-mode, when these steps work totally fine in debug-mode?
For example I implemented a stage "Activate Application" that works in debug mode perfectly, but fails when I use schedule-mode or when I simply drag and drop the process on a runtime resource.

A second example that fails: I implemented an action called "Navigate to URL". These action sets the URL from the input variable In_URL firstly in the URL bar in browser Google Chrome. Then the URL bar is focused and the enter button is hit in the last stage.

In schedule mode the following error appeared:

ERROR: Internal : Failed to perform step 1 in Navigate Stage 'Click URL Field' on page 'Navigate to URL' - Could not identify process owning the current foreground window

Actually there is only one Google Chrome window, so I don't understand why it says these error message.

答: These issues are typically due to either Windows being locked, or using RDP to connect to the resources (RDP does not work well with Blue Prism). In both cases, the desktop will not be active, so any active accessibility or region elements will fail.</p>


问:
How to append some object arrays in C#?

Possible Duplicate:

  How do I concatenate two arrays in C#?

How do I append some object arrays into one big object array?

For example, I have 3 elements of type: object[] and want to make one of it. How to do this?

答:
You can call the method Concat on them

```<code> var newArray = a.Concat(b).Concat(c).ToArray();
</code>```

Title: How to append some object arrays in C#?

Body:
You can call the method Concat on them

 var newArray = a.Concat(b).Concat(c).ToArray();


问:
Elastic IP on application deployed using Elastic Beanstalk
I'm a bit confused about the use of the Elastic IP service offered by Amazazon Web Services. I guess the main idea is that I can switch to a new version of the web application with no downtime following this simple procedure:

Deploy the new version on a new EC2 instance

Configure the new version properly and test it using a staging DB

Once properly tested, make this new version use the live DB

Associate the Elastic IP to this instance

Terminate all the useless services (staging DB and old EC2 instance)

Is this the common way to deploy a new version of a web application?

Now, what if the application is scaled on more instances? I configured the auto scaling in the Elastic Beanstalk settings and this created a load balancer (I can it see in the EC2 section of the AWS Management Console). The problem is that I apparently cannot associate the Elastic IP with the load balancer, I have to associate it with an existing instance. To which instance should I associate it to? I'm confused...

Sorry if some questions may sound stupid but I'm only a programmer and this is the first time I set up a cloud system.

Thank you!

答:
I wrote a post describing how to accomplish this using a Cloudwatch rule when a new instance is launched, and a lambda function. Here's the lambda function code:

const AWS = require('aws-sdk');
const ec2 = new AWS.EC2();
const PROD_ENV_NAME = 'my-prod-env-name';

// Example Event
// {
//   "version": "0",
//   "id": "ee376907-2647-4179-9203-343cfb3017a4",
//   "detail-type": "EC2 Instance State-change Notification",
//   "source": "aws.ec2",
//   "account": "123456789012",
//   "time": "2015-11-11T21:30:34Z",
//   "region": "us-east-1",
//   "resources": [
//     "arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"
//   ],
//   "detail": {
//     "instance-id": "i-abcd1111",
//     "state": "running"
//   }
// }

exports.handler = async (event) => {
  console.log("EVENT:", event);

  // The newly launched instance ID.
  const instanceId = event.detail['instance-id'];

  // Fetch info about the newly launched instance
  const result = await ec2.describeInstances({
    Filters: [ { Name: "instance-id", Values: [instanceId] } ]
  }).promise()

  // The instance details are buried in this object
  const instance = result.Reservations[0].Instances[0];
  const isAttached = instance.NetworkInterfaces.find(int => int.Association.IpOwnerId !== 'amazon');

  // Bail if the instance is already attached to another EIP
  if (isAttached) {
    console.log("This instance is already assigned to an elastic IP")
    return { statusCode: 200, body: '' }
  }

  // In elastic beanstalk, the instance name gets assigned to the enviroment name.
  // There is also an environment name tag, which could be used here.
  const name = instance.Tags.find(t => t.Key === 'Name').Value;

  // Only assign EIPs to production instances
  if (name !== PROD_ENV_NAME) {
    console.log('Not a production instance. Not assigning. Instance name:', name)
    return { statusCode: 200, body: ''}
  }

  // Get a list of elastic IP addresses
  const addresses = await ec2.describeAddresses().promise();

  // Filter out addresses already assigned to instances
  const availableAddresses = addresses.Addresses.filter(a => !a.NetworkInterfaceId);

  // Raise an error if we have no more available IP addresses
  if (availableAddresses.length === 0) {
    console.log("ERROR: no available ip addresses");
    return { statusCode: 400, body: JSON.stringify("ERROR: no available ip addresses") }
  }

  const firstAvail = availableAddresses[0]
  try {
    // Associate the instance to the address
    const result = await ec2.associateAddress({
      AllocationId: firstAvail.AllocationId,
      InstanceId: instanceId
    }).promise();

    console.log('allocation result', result)

    return { statusCode: 200, body: JSON.stringify('Associated IP address.') };
  } catch (err) {
      console.log("ERROR: ", err);
  }
};

```


问:
Python: why urllib.request.urlopen.read() never finishes download?
I have the code:

```<code>from urllib.request import urlopen
url = 'http://gmsh.info/bin/MacOSX/gmsh-4.5.2-MacOSX-sdk.tgz'
sdk = urlopen(url).read()
</code>```

and the question: why this download never ends? Link is OK and it works in browsers. I tried to set some headers like this:

```<code>from urllib import request
req = request.Request(url)
req.add_header('user-agent', "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11")
sdk = request.urlopen(req).read()
</code>```

but this didn't help. Any ideas?

答:
this is because the file size is very big try downloading it into chunks..
as shown in example it will work..

import urllib.request
filedata = urllib.request.urlopen('http://gmsh.info/bin/MacOSX/gmsh-4.5.2-MacOSX-sdk.tgz')
CHUNK = 1 * 1024
with open('test.zip', 'wb') as f:
    while True:
        chunk = filedata.read(CHUNK)
        if not chunk:
            break
        f.write(chunk)

Body:
I have the code:

from urllib.request import urlopen
url = 'http://gmsh.info/bin/MacOSX/gmsh-4.5.2-MacOSX-sdk.tgz'
sdk = urlopen(url).read()

and the question: why this download never ends? Link is OK and it works in browsers. I tried to set some headers like this:

from urllib import request
req = request.Request(url)
req.add_header('user-agent', "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11")
sdk = request.urlopen(req).read()

but this didn't help. Any ideas?


问:
Why doesn't nmap ping scan need root permission
As I know, ping is a tool that requires root permission (set-uid) or CAP_NET_RAW Capability.

But I found that, when I start a Nmap ping scan(-sn), no privilege permission required:

```<code># getcap /usr/bin/nmap
# ls -al /usr/bin/nmap
-rwxr-xr-x 1 root root 2445920 May 28  2016 /usr/bin/nmap
# su -s /bin/bash www-data
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ nmap -sn example.com

Starting Nmap 6.47 ( http://nmap.org ) at 2020-02-17 16:35 CST
Nmap scan report for example.com (93.184.216.34)
Host is up (0.011s latency).
Nmap done: 1 IP address (1 host up) scanned in 11.05 seconds
</code>```

So how does ping scan of Nmap work? Why does ping need root permission and the nmap doesn't?

答:
When you run an Nmap ping scan as root, the default is to use the ICMP and ACK methods. Non-root users will use the connect() method, which attempts to connect to a machine, waiting for a response, and tearing down the connection as soon as it has been established (similar to the SYN/ACK method for root users, but this one establishes a full TCP connection!)

From the nmap website.

Body:
As I know, ping is a tool that requires root permission (set-uid) or CAP_NET_RAW Capability.

But I found that, when I start a Nmap ping scan(-sn), no privilege permission required:

# getcap /usr/bin/nmap
# ls -al /usr/bin/nmap
-rwxr-xr-x 1 root root 2445920 May 28  2016 /usr/bin/nmap
# su -s /bin/bash www-data
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ nmap -sn example.com

Starting Nmap 6.47 ( http://nmap.org ) at 2020-02-17 16:35 CST
Nmap scan report for example.com (93.184.216.34)
Host is up (0.011s latency).
Nmap done: 1 IP address (1 host up) scanned in 11.05 seconds

So how does ping scan of Nmap work? Why does ping need root permission and the nmap doesn't?


答:
How do I ensure my values never clash?

If you are new to threads, then I would say, use a synchronized block:

```<code>final Object lock = new Object();
int global_r = 0;
...
while (true) {
    int r = random.nextInt();
    synchronized(lock) {
        if (r > global_r) {
            global_r = r;
            break;
        }
    }
}
</code>```

Only one thread at a time can enter the synchronized(lock)... block. A thread that tries when another thread already is in it will be forced to wait.

One should always try to have threads spend as little time as possible inside a synchronized(...) block, which is why I generate the random number outside of the block, and only do the test and the assignment inside it.

Another answer here suggests that you use AtomicInteger.  That works too, but it is not what I would recommend for somebody who is taking their very first steps toward understanding how to use threads.

Title: Java Threads - Keep function in sync with multiple returning values from threads

Body:
This is just a concept :

I want to have a int be updated, by a function that is running inside multiple threads.

My function randomly chooses an int and checks if it's bigger than the existing int.

If so it updates the variable.

How do I ensure my values never clash or my function is looking at an older value not yet updated?

I'm new to threads so any information is valuable.

Body:
How do I ensure my values never clash?

If you are new to threads, then I would say, use a synchronized block:

final Object lock = new Object();
int global_r = 0;
...
while (true) {
    int r = random.nextInt();
    synchronized(lock) {
        if (r > global_r) {
            global_r = r;
            break;
        }
    }
}

Only one thread at a time can enter the synchronized(lock)... block. A thread that tries when another thread already is in it will be forced to wait.

One should always try to have threads spend as little time as possible inside a synchronized(...) block, which is why I generate the random number outside of the block, and only do the test and the assignment inside it.

Another answer here suggests that you use AtomicInteger.  That works too, but it is not what I would recommend for somebody who is taking their very first steps toward understanding how to use threads.


问:
Is it possible to build a generic function for the fetches?
I build an app in react.js with a lot of 'crud' operations. I am a beginner in React. For all these fetches there are always the same header (content-type, token...). And for each requests I have to resolve promises, test the code status, parse the answer, manage the errors , etc.... It is very long to write.

So I wonder if is possible to build a generic function. Something like that:

```<code>myBooks = callApi('endpoint', 'myparams');
</code>```

And that's all ! The function callApi would do all the necessary (add the headers, the token, etc....).

I tried on my side, but I have not enough skills to do that in React.

Do you make your fetches with a special package ? or do you write, like me, your fetches and too bad it's long to write.

Do you have some packages to suggest?

答:
I am using axios for fetching from REST apis. You can use axios.create to create an instance that you can pass headers and the base url of your API. You could even define middlewares with axios.

Using axios create:

```<code>const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
</code>```

Personally, I prefer to just wrap my axios calls myself like this:

```<code>function getHeaders() {
    return {
        accept: 'application/json',
        authorization: `Bearer ${ getStoredAuthToken() }`,
    };
}

function postHeaders() {
    return {
        'content-type': 'application/json',
        authorization: `Bearer ${ getStoredAuthToken() }`,
    };
}

export const postRequest = ( endpoint, data ) => axios
    .post( API + endpoint, data, { headers: postHeaders() } )
    .then( res => res.data )
    .catch( ( err ) => {
        LoggingUtility.error( `Error in post request to entpoint ${ endpoint }`, err );
        if ( isNetworkError( err ) ) {
            throwServerNotReachableError();
        }
        const { status } = err.response;
        if ( isUnauthorizedError( status ) ) {
            return refreshAuthToken(
                () => postRequest( endpoint, data ),
            );
        }
        throw err;
    } );
</code>```

You could do something like this for every http method, e.g. deleteRequest, putRequest, postRequest etc.

In React/Frontend land it is very common to do this in a folder called services which abstracts away all async fetches of data.

Body:
I build an app in react.js with a lot of 'crud' operations. I am a beginner in React. For all these fetches there are always the same header (content-type, token...). And for each requests I have to resolve promises, test the code status, parse the answer, manage the errors , etc.... It is very long to write.

So I wonder if is possible to build a generic function. Something like that:

myBooks = callApi('endpoint', 'myparams');

And that's all ! The function callApi would do all the necessary (add the headers, the token, etc....).

I tried on my side, but I have not enough skills to do that in React.

Do you make your fetches with a special package ? or do you write, like me, your fetches and too bad it's long to write.

Do you have some packages to suggest?

Body:
I am using axios for fetching from REST apis. You can use axios.create to create an instance that you can pass headers and the base url of your API. You could even define middlewares with axios.

Using axios create:

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

Personally, I prefer to just wrap my axios calls myself like this:

function getHeaders() {
    return {
        accept: 'application/json',
        authorization: `Bearer ${ getStoredAuthToken() }`,
    };
}

function postHeaders() {
    return {
        'content-type': 'application/json',
        authorization: `Bearer ${ getStoredAuthToken() }`,
    };
}

export const postRequest = ( endpoint, data ) => axios
    .post( API + endpoint, data, { headers: postHeaders() } )
    .then( res => res.data )
    .catch( ( err ) => {
        LoggingUtility.error( `Error in post request to entpoint ${ endpoint }`, err );
        if ( isNetworkError( err ) ) {
            throwServerNotReachableError();
        }
        const { status } = err.response;
        if ( isUnauthorizedError( status ) ) {
            return refreshAuthToken(
                () => postRequest( endpoint, data ),
            );
        }
        throw err;
    } );

You could do something like this for every http method, e.g. deleteRequest, putRequest, postRequest etc.

In React/Frontend land it is very common to do this in a folder called services which abstracts away all async fetches of data.


问:
Create new "execute" function/program in Windows (instead of command prompt)
I am using a small program called Youtube-DL to download videos but everytime I have to open the command prompt, get to the right folder and then execute, say, youtube-dl https://www.youtube.com/watch?v=uFk0mgljtns.

What do I need to set up so that I can do the same thing directly from the "execute" tool (the one you access with the shortcut Windows+R)? Ideally all I would need to do would be Windows+R, type yt-dl https://www.youtube.com/watch?v=uFk0mgljtns.

答: Add the youtube-dl executable to your %path%: Use setx /M PATH "%PATH%;C:\folder_with_youtubedl" with an admin cmd.


问:
Is it forbidden to use static methods in factory pattern?
I got told that using static methods when implementing the factory-method-pattern is wrong and should be avoided. Because I wasn't really familiar with the pattern I accepted that answer.

After reading articles and getting deeper into it, I couldn't find any source which supports this statement.

Can someone help me out with this situation. Should I avoid the static-keyword in factory-methods and if so, when are they useful?

答:
The first thing to be 100% clear about is that there is no single "Factory Pattern". The term Factory describes a category of patterns with wildly differing implementations. When someone says Factory Pattern they could be talking about any creational pattern; but most commonly the phrase Factory Pattern indicates ignorance of design patterns.

Two very specific Factory Patterns are published in the famous Gang of Four book: Abstract Factory and Factory Method.

Static Factory was popularized by Joshua Bloch in Effective Java. There is no relationship between Bloch's Static Factory Method and the GoF's Factory Method, other than having similar names.

I will adjust the original question then, to provide a clear answer.

Is it forbidden to use static methods in the GoF Factory Method pattern?

Yes. The GoF pattern requires inheritance, which is not supported by static methods. This does not make the Static Factory pattern less useful! Static Factory is a perfectly legitimate design pattern that happens to be implemented in a very different way from the GoF Factory Method pattern. You may use both patterns when appropriate; and now you can label them appropriately as well.


答:
I have actually done this on personal projects before, here is the basics that I use.

```<code>const baseUrl = 'http://localhost';
const port = '8080';

export async function get(route) {
  try {
    const response = await fetch(`${baseUrl}:${port}/${route}`, {
      method: 'GET',
      cache: 'no-cache',
      credentials: 'same-origin',
    });
    return response.json();
  } catch (err) {
    console.error(`GET error: ${err}`);
  }
}
</code>```

Of course, you'll have to modify this for authentication, https, etc, but you'll call it with something like (for a similar post method) (and one for get):

```<code>const response = await post('user-files/update', {
  uuid,
  newFilename: filename,
  originalFilename,
});

const rows = await get(`dataset/${uuid}`);
</code>```

Title: Is it possible to build a generic function for the fetches?

Body:
I have actually done this on personal projects before, here is the basics that I use.

const baseUrl = 'http://localhost';
const port = '8080';

export async function get(route) {
  try {
    const response = await fetch(`${baseUrl}:${port}/${route}`, {
      method: 'GET',
      cache: 'no-cache',
      credentials: 'same-origin',
    });
    return response.json();
  } catch (err) {
    console.error(`GET error: ${err}`);
  }
}

Of course, you'll have to modify this for authentication, https, etc, but you'll call it with something like (for a similar post method) (and one for get):

const response = await post('user-files/update', {
  uuid,
  newFilename: filename,
  originalFilename,
});

const rows = await get(`dataset/${uuid}`);


问:
Jenkins: How to disable DockerContainerWatchdog from running
I've installed Docker plugin and was able to setup a test job to run on a slave container.

The test job is a basic loop with echo that runs for 15 minutes.
My problem is that the job never finishes. It runs for a few minutes and then the connection to the slave docker is lost and job gets stuck and fails.

After reading about this issue, I tried several suggested solutions, but it didn't help.

One of the things that can affect my issue is disabling DockerContainerWatchdog from running.

My problem is that I can't figure out how to disable DockerContainerWatchdog from running.

Any help will be greatly appreciated.

Thanks,

Boris.

答:
Got it!

Run the following code in Jenkins' Script Console:

```<code>System.setProperty("com.nirima.jenkins.plugins.docker.DockerContainerWatchdog.enabled", "false")
</code>```

Please note: This will be active only until Jenkins' next restart.

Body:
Got it!

Run the following code in Jenkins' Script Console:

System.setProperty("com.nirima.jenkins.plugins.docker.DockerContainerWatchdog.enabled", "false")

Please note: This will be active only until Jenkins' next restart.


问:
npm install without ssl
I have an Ubuntu VM that is having trouble connecting to sites with ssl, i.e. https.  It can successfully download artifacts from the internet if the url begins with http.

npm install will download dependencies via https.  Is there anyway make it download via http?

答:
changing ssl-strict worked for me behind a corporate firewall

npm config set ssl-strict=false

Title: npm install without ssl


问:
Javascript timestamp to relative time
I'm looking for a nice JS snippet to convert a timestamp (e.g. from Twitter API) to a nice user friendly relative time (e.g. 2 seconds ago, one week ago etc).

Anyone care to share some of their favourite methods (preferably not using plugins)?

答:
const units = [
  ['year', 31536000000],
  ['month', 2628000000],
  ['day', 86400000],
  ['hour', 3600000],
  ['minute', 60000],
  ['second', 1000],
]

const rtf = new Intl.RelativeTimeFormat('en', { style:'narrow'})
const relatime = elapsed => {
  for (const [unit, amount] of units) {
    if (Math.abs(elapsed) > amount || unit === 'second') {
      return rtf.format(Math.round(elapsed/amount), unit)
    }
  }
}
```

<p>had some fun golfing it <code>192b</code> hehe</p>

<pre class="lang-js prettyprint-override"><code>const relatime = e=>{for(let[u,a]of Object.entries({year:31536e6,month:2628e6,day:864e5,hour:36e5,minute:6e4,second:1e3})){if(Math.abs(e)>a||a===1e3){return new Intl.RelativeTimeFormat('en',{style:'narrow'}).format(~~(e/a),u)}}}
</code>```

I also tested a functionnal version while golfing:

const rtf = new Intl.RelativeTimeFormat('en', { style:'narrow'})
const relatime = Object.entries({year:31536e6,month:2628e6,day:864e5,hour:36e5,minute:6e4,second:1e3})
  .reduce((f, [unit, amount]) => amount === 1e3
    ? f(elapsed => rtf.format(Math.round(elapsed/amount), unit))
    : next => f(e => Math.abs(e) < amount
      ? next(elapsed)
      : rtf.format(Math.round(elapsed/amount), unit)), _=>_)
```

All right i really have to get back to work now...

Title: Javascript timestamp to relative time

Body:
const units = [
  ['year', 31536000000],
  ['month', 2628000000],
  ['day', 86400000],
  ['hour', 3600000],
  ['minute', 60000],
  ['second', 1000],
]

const rtf = new Intl.RelativeTimeFormat('en', { style:'narrow'})
const relatime = elapsed => {
  for (const [unit, amount] of units) {
    if (Math.abs(elapsed) > amount || unit === 'second') {
      return rtf.format(Math.round(elapsed/amount), unit)
    }
  }
}

had some fun golfing it 192b hehe

const relatime = e=>{for(let[u,a]of Object.entries({year:31536e6,month:2628e6,day:864e5,hour:36e5,minute:6e4,second:1e3})){if(Math.abs(e)>a||a===1e3){return new Intl.RelativeTimeFormat('en',{style:'narrow'}).format(~~(e/a),u)}}}

I also tested a functionnal version while golfing:

const rtf = new Intl.RelativeTimeFormat('en', { style:'narrow'})
const relatime = Object.entries({year:31536e6,month:2628e6,day:864e5,hour:36e5,minute:6e4,second:1e3})
  .reduce((f, [unit, amount]) => amount === 1e3
    ? f(elapsed => rtf.format(Math.round(elapsed/amount), unit))
    : next => f(e => Math.abs(e) < amount
      ? next(elapsed)
      : rtf.format(Math.round(elapsed/amount), unit)), _=>_)

All right i really have to get back to work now...


问:
How can I access the current executing module or class name in Python?
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module.  Here is some code:

foo.py:

```<code>def f():
    print __name__
</code>```

bar.py:

```<code>from foo import f

def b(): f()
</code>```

This obviously does not work as __name__ is the name of the module that contains the function.  What I would like to be access inside the foo module is the name of the current executing module that is using foo.  So in the case above it would be bar but if any other module imported foo I would like foo to dynamically have access to the name of that module.

Edit: The inspect module looks quite promising but it is not exactly what I was looking for.  What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module.  Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.

Edit: Here is how I am trying to use this.  I have two different Django applications that both need to log errors to file.  Lets say that they are called "AppOne" and "AppTwo".  I also have a place to which I would like to log these files: "/home/hare/app_logs".  In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file.  However what I would like to do is create a directory under app_logs that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.

In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.

答: I don't believe that's possible since that's out of foo's scope.  foo will only be aware of its internal scope since it may be being called by countless other modules and applications.

OwnerDisplayName: Andrew Hare

ContentLicense: CC BY-SA 2.5

Body:
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module.  Here is some code:

foo.py:

def f():
    print __name__

bar.py:

from foo import f

def b(): f()

This obviously does not work as __name__ is the name of the module that contains the function.  What I would like to be access inside the foo module is the name of the current executing module that is using foo.  So in the case above it would be bar but if any other module imported foo I would like foo to dynamically have access to the name of that module.

Edit: The inspect module looks quite promising but it is not exactly what I was looking for.  What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module.  Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.

Edit: Here is how I am trying to use this.  I have two different Django applications that both need to log errors to file.  Lets say that they are called "AppOne" and "AppTwo".  I also have a place to which I would like to log these files: "/home/hare/app_logs".  In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file.  However what I would like to do is create a directory under app_logs that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.

In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.

LastEditorDisplayName: Andrew Hare

OwnerDisplayName: Soviut


问:
TextInputLayout "setError(null)" before "setErrorEnabled(false)" necessary?
Is it necessary to call setError(null) before setErrorEnable(false)? Why? I don't see the difference but I see many people do that.

答:
There is no need to call both of them. When you set an error for a TextInputLayout at the first time, it's height increase a little under it's EditText field for showing that error.

If you use setError(null) just the error text will delete, but if you use setErrorEnable(false) both error text and extra space will delete(note that if you have set a helper for TextInputLayout, the error simply replace with the helper text and doesn't add an extra space so you don't see any difference between this two methods).


问:
Applying multiple value thresholds to a dataframe in python
I am working with a data frame in python. I want to apply a threshold to the data. I want all S4 values >0.6 and <1. Please advice on how I could implement this and isolate all threshold entries. Please take into consideration that some of the data entries have a blank S4 value ie the data frame contains blank entries.

答:
I would suggest to replace the empty strings with 0 first. Then you can handle it the way you have started:

```<code>data[data['Total_S4_Sig1'] == ""] = 0
</code>```

Body:
I would suggest to replace the empty strings with 0 first. Then you can handle it the way you have started:

data[data['Total_S4_Sig1'] == ""] = 0


问:
Publish code coverage result failed in azuredevops pipeline
I have a .netcode test command and a publish code coverage results task in my pipeline.

config as below:

```<code>steps:
- task: DotNetCoreCLI@2
  displayName: 'Test Public API Project '
  inputs:
    command: test
    projects: '**/DWP.CDA.API.Test.csproj'
    arguments: '--output publish_output --configuration $(BuildConfiguration) /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:Threshold=99 /p:ThresholdStat=total /p:CoverletOutput=$(Build.SourcesDirectory)\TestResults\Coverage\ --collect "Code coverage"'

steps:
- task: PublishCodeCoverageResults@1
  displayName: 'Publish code coverage'
  inputs:
    codeCoverageTool: Cobertura
    summaryFileLocation: '$(Build.SourcesDirectory)/TestResults/Coverage/*cobertura.xml'
    reportDirectory: '($(Build.SourcesDirectory)/Src/TestResults/Coverage'
</code>```

But it seems that the publish results doed not take effect,such messages will show

```<code>[warning]No code coverage results were found to publish.
</code>```

答:
Did you install and run the ReportGenerator tool as well to get code coverage report in the proper format? Your warning looks like the build task isn't finding the xml file to publish in the folder that you're looking in.

I've used the following yaml in the past to run and publish code coverage results. You will need to change it to find your projects, but otherwise it should work.

```<code>- task: DotNetCoreCLI@2
  displayName: 'Install ReportGenerator'
  inputs:
    command: custom
    custom: tool
    arguments: 'install --global dotnet-reportgenerator-globaltool'

- task: DotNetCoreCLI@2
  displayName: 'Run unit tests - $(buildConfiguration)'
  inputs:
    command: 'test'
    arguments: '--no-build --configuration $(buildConfiguration) /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:CoverletOutput=$(Build.SourcesDirectory)/TestResults/Coverage/'
    publishTestResults: true
    projects: '**/*.Tests.csproj'

- script: |
    reportgenerator -reports:$(Build.SourcesDirectory)/**/coverage.cobertura.xml -targetdir:$(Build.SourcesDirectory)/CodeCoverage -reporttypes:HtmlInline_AzurePipelines
  displayName: 'Create code coverage report'

- task: PublishCodeCoverageResults@1
  displayName: 'Publish code coverage report'
  inputs:
    codeCoverageTool: 'cobertura'
    summaryFileLocation: '$(Build.SourcesDirectory)/**/coverage.cobertura.xml'
</code>```

Body:
I have a .netcode test command and a publish code coverage results task in my pipeline.

config as below:

steps:
- task: DotNetCoreCLI@2
  displayName: 'Test Public API Project '
  inputs:
    command: test
    projects: '**/DWP.CDA.API.Test.csproj'
    arguments: '--output publish_output --configuration $(BuildConfiguration) /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:Threshold=99 /p:ThresholdStat=total /p:CoverletOutput=$(Build.SourcesDirectory)\TestResults\Coverage\ --collect "Code coverage"'

steps:
- task: PublishCodeCoverageResults@1
  displayName: 'Publish code coverage'
  inputs:
    codeCoverageTool: Cobertura
    summaryFileLocation: '$(Build.SourcesDirectory)/TestResults/Coverage/*cobertura.xml'
    reportDirectory: '($(Build.SourcesDirectory)/Src/TestResults/Coverage'

But it seems that the publish results doed not take effect,such messages will show

[warning]No code coverage results were found to publish.

Body:
Did you install and run the ReportGenerator tool as well to get code coverage report in the proper format? Your warning looks like the build task isn't finding the xml file to publish in the folder that you're looking in.

I've used the following yaml in the past to run and publish code coverage results. You will need to change it to find your projects, but otherwise it should work.

- task: DotNetCoreCLI@2
  displayName: 'Install ReportGenerator'
  inputs:
    command: custom
    custom: tool
    arguments: 'install --global dotnet-reportgenerator-globaltool'

- task: DotNetCoreCLI@2
  displayName: 'Run unit tests - $(buildConfiguration)'
  inputs:
    command: 'test'
    arguments: '--no-build --configuration $(buildConfiguration) /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:CoverletOutput=$(Build.SourcesDirectory)/TestResults/Coverage/'
    publishTestResults: true
    projects: '**/*.Tests.csproj'

- script: |
    reportgenerator -reports:$(Build.SourcesDirectory)/**/coverage.cobertura.xml -targetdir:$(Build.SourcesDirectory)/CodeCoverage -reporttypes:HtmlInline_AzurePipelines
  displayName: 'Create code coverage report'

- task: PublishCodeCoverageResults@1
  displayName: 'Publish code coverage report'
  inputs:
    codeCoverageTool: 'cobertura'
    summaryFileLocation: '$(Build.SourcesDirectory)/**/coverage.cobertura.xml'