答:
Use this if you are to specify dates

```<code>WITH foo( ID, Day, Total ) AS
(
 SELECT '01', date'2020-01-01' ,   10  FROM dual
 UNION ALL SELECT '01', date'2020-01-02' ,   50  FROM dual
 UNION ALL SELECT '01', date'2020-01-03' ,   50  FROM dual
 UNION ALL SELECT '01', date'2020-01-04' ,   50  FROM dual
 UNION ALL SELECT '01', date'2020-01-05' ,   20  FROM dual
 UNION ALL SELECT '02', date'2020-01-01' ,   10  FROM dual
 UNION ALL SELECT '02', date'2020-01-02' ,   10  FROM dual
 UNION ALL SELECT '02', date'2020-01-03' ,   10  FROM dual
 UNION ALL SELECT '02', date'2020-01-04' ,   10  FROM dual
 UNION ALL SELECT '02', date'2020-01-05' ,   10  FROM dual
)SELECT
    ID
FROM foo
WHERE day BETWEEN TO_DATE('2020-01-01', 'YYYY-MM-DD' ) AND TO_DATE('2020-01-04', 'YYYY-MM-DD' )
GROUP BY ID  HAVING SUM(Total) >= 150;
</code>```

RESULT:

```<code>ID|
--|
01|
</code>```

Title: With Oracle SQL how can I find 3 days where total sum >= 150

Body:
I have a report that needs to list activity where total is >= 150 over 3 consecutive days.

Let's say I've created a temp table foo, to summarize daily totals.

| ID | Day        | Total |
| -- | ---------- | ----- |
| 01 | 2020-01-01 |   10  |
| 01 | 2020-01-02 |   50  |
| 01 | 2020-01-03 |   50  |
| 01 | 2020-01-04 |   50  |
| 01 | 2020-01-05 |   20  |
| 02 | 2020-01-01 |   10  |
| 02 | 2020-01-02 |   10  |
| 02 | 2020-01-03 |   10  |
| 02 | 2020-01-04 |   10  |
| 02 | 2020-01-05 |   10  |

How Would I write SQL to return ID 01, but not 02?

Example Result:

| ID |
| -- |
| 01 |

Body:
Use this if you are to specify dates

WITH foo( ID, Day, Total ) AS
(
 SELECT '01', date'2020-01-01' ,   10  FROM dual
 UNION ALL SELECT '01', date'2020-01-02' ,   50  FROM dual
 UNION ALL SELECT '01', date'2020-01-03' ,   50  FROM dual
 UNION ALL SELECT '01', date'2020-01-04' ,   50  FROM dual
 UNION ALL SELECT '01', date'2020-01-05' ,   20  FROM dual
 UNION ALL SELECT '02', date'2020-01-01' ,   10  FROM dual
 UNION ALL SELECT '02', date'2020-01-02' ,   10  FROM dual
 UNION ALL SELECT '02', date'2020-01-03' ,   10  FROM dual
 UNION ALL SELECT '02', date'2020-01-04' ,   10  FROM dual
 UNION ALL SELECT '02', date'2020-01-05' ,   10  FROM dual
)SELECT
    ID
FROM foo
WHERE day BETWEEN TO_DATE('2020-01-01', 'YYYY-MM-DD' ) AND TO_DATE('2020-01-04', 'YYYY-MM-DD' )
GROUP BY ID  HAVING SUM(Total) >= 150;

RESULT:

ID|
--|
01|


来源: stackexchange

问:
Anchor tag isn't calling the onClick function in React
I'm trying to update my component state when you click on an anchor tag inside the render method. I've tried binding inside the constructor, but still the console.log isn't being called. Below is my code. Please help. This is holding me back from progressing lol.

This is modified code based on my previous question here on stackoverflow.

```<code>const React = require('react');

class Navbar extends React.Component {
  constructor(...props) {
    super(...props);
    this.setActiveTab = this.setActiveTab.bind(this)
    this.state = {
      currentPage: "/"
    }
  }

  setActiveTab(e) {
    console.log(e.target)
    this.setState({
      currentPage: e.target.href
    })
  }

  render() {
    const { path } = this.props
    let classString = path === this.state.currentPage ? 'nav-item is-tab is-active' : 'nav-item is-tab'

    return (
      <nav className="nav">

        <div className="nav-left">
          <a className="nav-item">
            <h1>CREATORS NEVER DIE</h1>
          </a>
        </div>

        <div className="nav-right nav-menu">
          <a href="/" className={classString} onClick={this.setActiveTab}>
            Home
          </a>
        </div>

      </nav>
    )
  }
}

module.exports = Navbar;
</code>```

答:
Researching the issue it appears you need to prevent the default of the anchor tag. Also if you create an arrow function you are able to handle the this.

Prevent default info can be found on React docs here

Hope this helps.

```<code> const React = require("react");

class Navbar extends React.Component {
    constructor(...props) {
        super(...props);
        this.setActiveTab = this.setActiveTab.bind(this);
        this.state = {
            currentPage: "/",
        };
    }

    setActiveTab = (e) => {
        e.preventDefault();
        console.log(e.target);
        this.setState({
            currentPage: e.target.href,
        });
    }

    render() {
        const { path } = this.props;
        let classString =
            path === this.state.currentPage ? "nav-item is-tab is-active" : "nav-item is-tab";

        return (
            <nav className="nav">
                <div className="nav-left">
                    <a className="nav-item">
                        <h1>CREATORS NEVER DIE</h1>
                    </a>
                </div>

                <div className="nav-right nav-menu">
                    <a href="/" className={classString} onClick={this.setActiveTab}>
                        Home
                    </a>
                </div>
            </nav>
        );
    }
}

module.exports = Navbar;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to update my component state when you click on an anchor tag inside the render method. I've tried binding inside the constructor, but still the console.log isn't being called. Below is my code. Please help. This is holding me back from progressing lol.

This is modified code based on my previous question here on stackoverflow.

const React = require('react');

class Navbar extends React.Component {
  constructor(...props) {
    super(...props);
    this.setActiveTab = this.setActiveTab.bind(this)
    this.state = {
      currentPage: "/"
    }
  }

  setActiveTab(e) {
    console.log(e.target)
    this.setState({
      currentPage: e.target.href
    })
  }

  render() {
    const { path } = this.props
    let classString = path === this.state.currentPage ? 'nav-item is-tab is-active' : 'nav-item is-tab'

    return (

CREATORS NEVER DIE

            Home

    )
  }
}

module.exports = Navbar;

Body:
Researching the issue it appears you need to prevent the default of the anchor tag. Also if you create an arrow function you are able to handle the this.

Prevent default info can be found on React docs here

Hope this helps.

 const React = require("react");

class Navbar extends React.Component {
    constructor(...props) {
        super(...props);
        this.setActiveTab = this.setActiveTab.bind(this);
        this.state = {
            currentPage: "/",
        };
    }

    setActiveTab = (e) => {
        e.preventDefault();
        console.log(e.target);
        this.setState({
            currentPage: e.target.href,
        });
    }

    render() {
        const { path } = this.props;
        let classString =
            path === this.state.currentPage ? "nav-item is-tab is-active" : "nav-item is-tab";

        return (
            <nav className="nav">
                <div className="nav-left">
                    <a className="nav-item">
                        <h1>CREATORS NEVER DIE</h1>
                    </a>
                </div>

                <div className="nav-right nav-menu">
                    <a href="/" className={classString} onClick={this.setActiveTab}>
                        Home
                    </a>
                </div>
            </nav>
        );
    }
}

module.exports = Navbar;

ContentLicense: CC BY-SA 4.0


问:
how to the svg water fill dynamic in angular
here's the code: https://stackblitz.com/edit/angular-cyqdzy?file=src/app/app.component.ts

html

typescript

```<code>data = [
  {
    name: 'server1',
    humidity: '50.9'
  },
  {
    name: 'server2',
    humidity: '52.9',
  },
  {
    name: 'server3',
    humidity: '53.9',
  }
]
  humidityPercentage: any;
  constructor() { }

  ngOnInit() {

    for (let x = 0; x <= this.data.length; x++) {
      this.humidityPercentage = this.data[x].humidity + '%';
    }
  }
</code>```

there's 3 item then what I want to do here is to make it dynamic for example the first item/water 50.9 then it will display on the first item if the second is 52.9 then it should 52.9.

the error is here is it will get the last data, it will not display based on the index.

答:
I recommend adding a pipe to make the code cleaner

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'humidityPipe'
})
export class HumidityPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return  value + '%' ;
  }

}
</code>```

and then you can use :

```<code><div *ngFor="let item of data;let i = index">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewbox="0 0 30 42" aria-hidden="true"
    attr.fill="url(#color-{{i}})">
    <defs>
        <linearGradient id="color-{{i}}" x1="0%" y1="100%" x2="0%" y2="0%">
            <stop offset="0%" stop-color="rgb(132, 219, 255)" />
            <stop [attr.offset]="item.humidity | humidityPipe" stop-color="rgb(132, 219, 255)" />
            <stop [attr.offset]="item.humidity | humidityPipe" stop-color="rgb(255, 255, 255)" />
            <stop offset="100%" stop-color="rgb(255, 255, 255)" />
        </linearGradient>
    </defs>

    <g transform="translate(35,65)">
        <path id="scale" stroke="#000" stroke-width="1.5" d="M15 3
                            Q20.5 12.8 40 35
                            A28.8 28.8 0 1 1 0 30
                            Q20.5 12.8 15 3z" />
    </g>
</svg>
</code>```

p.s. If you use <defs> tags, remember to use an id for each definition, otherwise you will always use the same filling!

I added a stackblitz for you:

https://stackblitz.com/edit/angular-ymupuk

Body:
here's the code: https://stackblitz.com/edit/angular-cyqdzy?file=src/app/app.component.ts

html

typescript

data = [
  {
    name: 'server1',
    humidity: '50.9'
  },
  {
    name: 'server2',
    humidity: '52.9',
  },
  {
    name: 'server3',
    humidity: '53.9',
  }
]
  humidityPercentage: any;
  constructor() { }

  ngOnInit() {

    for (let x = 0; x <= this.data.length; x++) {
      this.humidityPercentage = this.data[x].humidity + '%';
    }
  }

there's 3 item then what I want to do here is to make it dynamic for example the first item/water 50.9 then it will display on the first item if the second is 52.9 then it should 52.9.

the error is here is it will get the last data, it will not display based on the index.

Body:
I recommend adding a pipe to make the code cleaner

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'humidityPipe'
})
export class HumidityPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return  value + '%' ;
  }

}

and then you can use :

<div *ngFor="let item of data;let i = index">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewbox="0 0 30 42" aria-hidden="true"
    attr.fill="url(#color-{{i}})">
    <defs>
        <linearGradient id="color-{{i}}" x1="0%" y1="100%" x2="0%" y2="0%">
            <stop offset="0%" stop-color="rgb(132, 219, 255)" />
            <stop [attr.offset]="item.humidity | humidityPipe" stop-color="rgb(132, 219, 255)" />
            <stop [attr.offset]="item.humidity | humidityPipe" stop-color="rgb(255, 255, 255)" />
            <stop offset="100%" stop-color="rgb(255, 255, 255)" />
        </linearGradient>
    </defs>

    <g transform="translate(35,65)">
        <path id="scale" stroke="#000" stroke-width="1.5" d="M15 3
                            Q20.5 12.8 40 35
                            A28.8 28.8 0 1 1 0 30
                            Q20.5 12.8 15 3z" />
    </g>
</svg>

p.s. If you use <defs> tags, remember to use an id for each definition, otherwise you will always use the same filling!

I added a stackblitz for you:

https://stackblitz.com/edit/angular-ymupuk


问:
Change mac os x default php version
In my mac (version 10.13.6 High Sierra) php -v output is PHP 7.1.32 .
I need to update this 7.1 version to 7.3.

i tried to remove this version using brew unlink php7.1 but it's not worked.

How can i upgrade php version.

答:
$ brew upgrade php : ( get the latest homebrew php packages )

$ brew install php@7.4 : ( Install php 7.4 )

$ brew link php@7.4 : ( create an alias to this keg-only version; see comments output during installation )

$ echo 'export PATH="/usr/local/opt/php@7.4/bin:$PATH"' >> ~/.bash_profile : ( Add the alias to your path; see comments output during installation )

$ source ~/.bash_profile : ( Reload .bash_profile to use the new settings immediately )

Reference : How to use the php that brew installed?

Title: Change mac os x default php version


问:
vTiger blank page when trying to save any entity
I am currently in the process of creating new modules on vTiger 6.5. Currently I have been creating the modules using the vTlib, registering handlers ect.. All has been working well until I suddenly was unable to save any information on any modules even the standard modules.

I started a fresh install and went through the steps of installing my modules, I created one module fine but when registering the handler below I was then unable to save anything and just lead to index.php

```<code>    <?php
require_once('include/database/PearDatabase.php');
include_once('include/events/include.inc');

$adb = PearDatabase::getInstance();
$em = new VTEventsManager($adb);

$module = 'AddIsa';

$em->registerHandler('vtiger.entity.beforesave', 'modules/'.$module.'/'.$module.'Handler.php', $module.'Handler');
$em->registerHandler('vtiger.entity.beforesave.modifiable', 'modules/'.$module.'/'.$module.'Handler.php', $module.'Handler');
$em->registerHandler('vtiger.entity.beforesave.final', 'modules/'.$module.'/'.$module.'Handler.php', $module.'Handler');
$em->registerHandler('vtiger.entity.aftersave', 'modules/'.$module.'/'.$module.'Handler.php', $module.'Handler');

echo 'Events Added Successfully.';

?>
</code>```

UPDATE

I went to the table vtiger_eventhandlers and deleted the event handlers relating to my custom module and now it works fine. I cannot see why this would happen as I have previously registered event handlers using the same script which are also in this table.

Any ideas?

答:
event handlers registered will be executed for all modules. Your script might have some error, That's why you can not save to any module. In your handler script you can check current module and skip executing further code like this</p>

```<code>    $moduleName = $entityData->getModuleName();

    if ($moduleName != 'Invoice') {
        return;
    }
</code>```

Body:
I am currently in the process of creating new modules on vTiger 6.5. Currently I have been creating the modules using the vTlib, registering handlers ect.. All has been working well until I suddenly was unable to save any information on any modules even the standard modules.

I started a fresh install and went through the steps of installing my modules, I created one module fine but when registering the handler below I was then unable to save anything and just lead to index.php

    <?php
require_once('include/database/PearDatabase.php');
include_once('include/events/include.inc');

$adb = PearDatabase::getInstance();
$em = new VTEventsManager($adb);

$module = 'AddIsa';

$em->registerHandler('vtiger.entity.beforesave', 'modules/'.$module.'/'.$module.'Handler.php', $module.'Handler');
$em->registerHandler('vtiger.entity.beforesave.modifiable', 'modules/'.$module.'/'.$module.'Handler.php', $module.'Handler');
$em->registerHandler('vtiger.entity.beforesave.final', 'modules/'.$module.'/'.$module.'Handler.php', $module.'Handler');
$em->registerHandler('vtiger.entity.aftersave', 'modules/'.$module.'/'.$module.'Handler.php', $module.'Handler');

echo 'Events Added Successfully.';

?>

UPDATE

I went to the table vtiger_eventhandlers and deleted the event handlers relating to my custom module and now it works fine. I cannot see why this would happen as I have previously registered event handlers using the same script which are also in this table.

Any ideas?

Body:
event handlers registered will be executed for all modules. Your script might have some error, That's why you can not save to any module. In your handler script you can check current module and skip executing further code like this

    $moduleName = $entityData->getModuleName();

    if ($moduleName != 'Invoice') {
        return;
    }


问:
React useEffect hook does not fire when prop dependency changes
I am using a useEffect hook to make an API call depending on data from a photos prop being passed in.

```<code>const ImageCarousel = ({ src, photos }) => {
  const [photoList, setPhotos] = useState([]);
  const storageRef = firebase.storage().ref();
  console.log("photos prop:", photos);

  const getImage = photoId => {
    return new Promise((resolve, reject) => {
      storageRef
        .child("images/" + photoId)
        .getDownloadURL()
        .then(url => resolve(url))
        .catch(error => reject(error));
    });
  };

  useEffect(() => {
    console.log("trigger");
    Promise.all(
      photos.map(async photoId => {
        const url = await getImage(photoId);
        return url;
      })
    )
      .then(photoUrls => {
        setPhotos(photoUrls);
      })
      .catch(e => console.log(e));
  }, [photos]);

return (...)
}

</code>```

I have passed the photos prop into the dependency array of my useEffect hook, so it should fire when the photos prop changes. I can see that the prop is indeed changing in the console, but my useEffect hook does not fire when the prop change comes through. This is what appears in my console:

Why is the useEffect not firing twice? From my understanding it should fire when the component renders the first time, and fire again every time the photos prop changes.

答:
Try to make sure your photos prop is immutable,
meaning, you send a new array each time there is a change and not mutating the array

Body:
I am using a useEffect hook to make an API call depending on data from a photos prop being passed in.

const ImageCarousel = ({ src, photos }) => {
  const [photoList, setPhotos] = useState([]);
  const storageRef = firebase.storage().ref();
  console.log("photos prop:", photos);

  const getImage = photoId => {
    return new Promise((resolve, reject) => {
      storageRef
        .child("images/" + photoId)
        .getDownloadURL()
        .then(url => resolve(url))
        .catch(error => reject(error));
    });
  };

  useEffect(() => {
    console.log("trigger");
    Promise.all(
      photos.map(async photoId => {
        const url = await getImage(photoId);
        return url;
      })
    )
      .then(photoUrls => {
        setPhotos(photoUrls);
      })
      .catch(e => console.log(e));
  }, [photos]);

return (...)
}

I have passed the photos prop into the dependency array of my useEffect hook, so it should fire when the photos prop changes. I can see that the prop is indeed changing in the console, but my useEffect hook does not fire when the prop change comes through. This is what appears in my console:

Why is the useEffect not firing twice? From my understanding it should fire when the component renders the first time, and fire again every time the photos prop changes.


问:
Detect which field != null in POJO class?
Here I am trying to get values from Firebase database.

```<code>public class User {

    String id = null;
    String name = null;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}
</code>```

Some of those getter fields are null, and checking one by one is lengthy coding.

```<code>activityRef.child(uid).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot)
    {
        User usr =dataSnapshot.getValue(User.class);
        //here i want to check which value!=null
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
</code>```

答:
You can use a reflective solution but it will be far slower than if (object.getField() != null) {...}

As I've undestand it, there's only one value that is non-null?

You can achieve it like this:

User class:

```<code>class User {
    private String id;
    private String name;

    public String getId() {
      return id;
    }

    public void setId(String id) {
      this.id = id;
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    // this uses reflection to get the first non-null field
    // you can modify it to return a list of non-null fields
    // in the case I've misunderstood the point
    public Field getFirstNonNullField() {
      for (Field f : getClass().getDeclaredFields()) {
        f.setAccessible(true);
        try {
          if (f.get(this) != null)
            return f;
        } catch (IllegalArgumentException | IllegalAccessException e) {
          // TODO handle this exception as you want
          e.printStackTrace();
        }
      }
      return null;
    }
}
</code>```

Main method // example of use

```<code>public static void main(String[] str) {
    User u = new User();
    u.setName("hello");
    Field f = u.getFirstNonNullField();
    try {
      System.out.print(f.get(u));
    } catch (IllegalArgumentException | IllegalAccessException e) {
      // TODO handle this exception as you want
      e.printStackTrace();
    }
  }
</code>```

Body:
Here I am trying to get values from Firebase database.

public class User {

    String id = null;
    String name = null;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

Some of those getter fields are null, and checking one by one is lengthy coding.

activityRef.child(uid).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot)
    {
        User usr =dataSnapshot.getValue(User.class);
        //here i want to check which value!=null
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

Body:
You can use a reflective solution but it will be far slower than if (object.getField() != null) {...}

As I've undestand it, there's only one value that is non-null?

You can achieve it like this:

User class:

class User {
    private String id;
    private String name;

    public String getId() {
      return id;
    }

    public void setId(String id) {
      this.id = id;
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    // this uses reflection to get the first non-null field
    // you can modify it to return a list of non-null fields
    // in the case I've misunderstood the point
    public Field getFirstNonNullField() {
      for (Field f : getClass().getDeclaredFields()) {
        f.setAccessible(true);
        try {
          if (f.get(this) != null)
            return f;
        } catch (IllegalArgumentException | IllegalAccessException e) {
          // TODO handle this exception as you want
          e.printStackTrace();
        }
      }
      return null;
    }
}

Main method // example of use

public static void main(String[] str) {
    User u = new User();
    u.setName("hello");
    Field f = u.getFirstNonNullField();
    try {
      System.out.print(f.get(u));
    } catch (IllegalArgumentException | IllegalAccessException e) {
      // TODO handle this exception as you want
      e.printStackTrace();
    }
  }


问:
Embed Paper.js in Python
I am building a Server application in Python language, but because I need to work with SVG graphics (specifically, I need the function of subtracting SVG Path Objects from one and another), I thought about embedding Paper.js, which delivers the functionality into Python, but my question is, is this possible? Or is there an alternative?</p>

答: I would advice using a Python SVG library (one of them) ; and if you need complex shape operations you can use Clipper, it's nice and very powerful (and usable with Python).</p>

Title: Embed Paper.js in Python


问:
Reducing one frequency in song
How would I take a song input and output the same song without certain frequencies?

Based on my research so far, the song should be broken down into chucks, FFT it, reduce the target frequencies, iFFT it, and stitch the chunks back together. However, I am unsure if this is the right approach to take, and if so, how I would convert from the audio to FFT input (what seems to be a vector matrix), how to reduce the target frequencies, and how to convert back from the FFT output to audio, and how to restitch.

For background, my grandpa loves music. However, recently he cannot listen to it, as he has become hypersensitive to certain frequencies within songs. I'm a high school student who has some background coding, and am just getting into algorithmic work and thus have very little experience using these algorithms. Please excuse me if these are basic questions; any pointers would be helpful.

EDIT: So far, I've understood the basic premise of fft (through basic 3blue1brown yt videos and the like) and that it is available through scipy/numpi, and figured out how to convert from youtube to 0.25 second chunks in a wav format.

答:
Your approach is right.

Concerning subquestions:

from the audio to FFT input - assign audio samples to real part of complex signal, imaginary part is zero

how to reduce the target frequencies - multiply FFT results near needed frequency by smooth (to diminish artifacts) function that becomes zero at that freqency and reaches 1.0 some samples apart

how to convert back - just make inverse FFT (don't forget about scale multiplier like 1/N) and copy real part into audio channel

Also consider using of simpler digital filtering - band-stop or notch filter.

Arbitrary found example1 example2

(calculation of parameters perhaps requires some understanding of DSP)

Title: Reducing one frequency in song


问:
Enable HTML-snippets for editing RHTML in Rstudio
Is it possible to use Rstudios build in HTML-snippets when editing RHTML-files in Rstudio?

When I open an RHTML-file the language is set to RHTML, as in the picture below:

But the HTML-snippets do not work for this language, and I can't see a way to enable RHTML as a language in the snippets menu.

The HTML-snippets work if I change the language to HTML, instead of RHTML, but then the R-functionality does not work anymore.

Any ideas to get HTML-snippets to work in a RHTML-file in Rstudio?

Using Rstudio Version 1.2.5033

答:
Answer:

Use <shift> <tab> to insert HTHL-code snippets in RHTML.

<tab> alone does not work, when the language is set to RTML.

This is hinted at here:
https://support.rstudio.com/hc/en-us/articles/204463668-Code-Snippets


问:
Failed to remove etcd after reset kubeadm
When I try to kubeadm reset -f, it report the etcd server can not be removed, you must remove it manually.

```<code>failed to remove etcd member: error syncing endpoints with etc: etcdclient: no available endpoints. Please manually remove this etcd member using etcdctl
</code>```

答:
Is this a control-plane (master) node?

If not: simply running kubectl delete node <node_id> should suffice (see reference below). This will update etcd and take care of the rest of cleanup. You'll still have to diagnose what caused the node to fail to reset in the first place if you're hoping to re-add it... but that's a separate problem. See discussion e.g., here on a related issue:

If the node is hard failed and you cannot call kubeadm reset on it, it requires manual steps. you'd have to:

Remove the control-plane IP from the kubeadm-config CM ClusterStatus

Remove the etcd member using etcdctl

Delete the Node object using kubectl (if you don't want the Node around anymore)

1 and 2 apply only to control-plane nodes.

Hope this helps — if you are dealing with a master node, I'd be happy to include examples of what commands to run.

Body:
When I try to kubeadm reset -f, it report the etcd server can not be removed, you must remove it manually.

failed to remove etcd member: error syncing endpoints with etc: etcdclient: no available endpoints. Please manually remove this etcd member using etcdctl


问:
How to mask an input string in Spring-Shell
I am using Spring-Shell and I would like to mask the input when typing the password field for a particular method.

Looking on the internet and here in the forum, I found many people suggesting to use the console.readPassword() command but, creating the console from inside the IDE gives me a null result.

```<code>Scanner in= new Scanner(System.in)
-------------------------------OR------------------------------------
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)
</code>```

these are the code lines I tried to get the input from the user, but I can't find a way to mask the input, so when someone types the password it shows on the screen.

Looking around I found out that to make the console command work I could use an external terminal instead of the IDE but, when starting SpringBoot (a Spring-Shell project) I get the Jline Warning:

"Unable to create a system terminal, creating a dumb terminal (enable debug logging for more information)".

So is there an easy way to mask the password using the scanner/BufferedReader classes, or do I need to enable the system terminal to use the console?

Thank you

答:
You can use org.jline.reader.LineReader from JLine library which you get by default in a Spring Shell application.

Here's some example code:

```<code>import org.jline.reader.LineReader;

public class InputReader {

private static final Character DEFAULT_MASK = '*';

private Character mask;
private LineReader lineReader;

public InputReader(LineReader lineReader) {
    this(lineReader, null);
}

public InputReader(LineReader lineReader, Character mask) {
    this.lineReader = lineReader;
    this.mask = mask != null ? mask : DEFAULT_MASK;
}

public String prompt(String  prompt) {
    return prompt(prompt, true);
}

public String prompt(String  prompt, boolean echo) {
    String answer;
    if (echo) {
        answer = lineReader.readLine(prompt + ": ");
    } else {
        answer = lineReader.readLine(prompt + ": ", mask);
    }
    return answer;
}
</code>```

}

Then, make it a bean:

```<code>@Bean
public InputReader inputReader(@Lazy LineReader lineReader) {
    return new InputReader(lineReader);
}
</code>```

and finally use it in your app:

```<code>@ShellComponent
public class YourShellComponent {

private final InputReader inputReader;

@Autowired
public YourShellComponent(InputReader inputReader) {
    this.inputReader = inputReader;
}

@ShellMethod(value = "connect")
public void connect() throws Exception {
    String username = this.inputReader.prompt("Username");
    String password = this.inputReader.prompt("Password", false);

    // other code
}
}
</code>```

Body:
I am using Spring-Shell and I would like to mask the input when typing the password field for a particular method.

Looking on the internet and here in the forum, I found many people suggesting to use the console.readPassword() command but, creating the console from inside the IDE gives me a null result.

Scanner in= new Scanner(System.in)
-------------------------------OR------------------------------------
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)

these are the code lines I tried to get the input from the user, but I can't find a way to mask the input, so when someone types the password it shows on the screen.

Looking around I found out that to make the console command work I could use an external terminal instead of the IDE but, when starting SpringBoot (a Spring-Shell project) I get the Jline Warning:

"Unable to create a system terminal, creating a dumb terminal (enable debug logging for more information)".

So is there an easy way to mask the password using the scanner/BufferedReader classes, or do I need to enable the system terminal to use the console?

Thank you

Body:
You can use org.jline.reader.LineReader from JLine library which you get by default in a Spring Shell application.

Here's some example code:

import org.jline.reader.LineReader;

public class InputReader {

private static final Character DEFAULT_MASK = '*';

private Character mask;
private LineReader lineReader;

public InputReader(LineReader lineReader) {
    this(lineReader, null);
}

public InputReader(LineReader lineReader, Character mask) {
    this.lineReader = lineReader;
    this.mask = mask != null ? mask : DEFAULT_MASK;
}

public String prompt(String  prompt) {
    return prompt(prompt, true);
}

public String prompt(String  prompt, boolean echo) {
    String answer;
    if (echo) {
        answer = lineReader.readLine(prompt + ": ");
    } else {
        answer = lineReader.readLine(prompt + ": ", mask);
    }
    return answer;
}

}

Then, make it a bean:

@Bean
public InputReader inputReader(@Lazy LineReader lineReader) {
    return new InputReader(lineReader);
}

and finally use it in your app:

@ShellComponent
public class YourShellComponent {

private final InputReader inputReader;

@Autowired
public YourShellComponent(InputReader inputReader) {
    this.inputReader = inputReader;
}

@ShellMethod(value = "connect")
public void connect() throws Exception {
    String username = this.inputReader.prompt("Username");
    String password = this.inputReader.prompt("Password", false);

    // other code
}
}


问:
pdfJet for .net - pdf.Flush(); - this gives me an error whn trying the example
1)    A call to PInvoke function 'PDFjet!PDFjet.NET.OptionalDeflateStream::compress' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

What is this? If I remove zlibwapi.dll from the same folder as the PdfJet assembly I get:
2)Unable to load DLL 'zlibwapi.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) (note that I don't add reference to this assembly, I only copy it to Debug folder, and get error1)

code:

```<code>   `static void Main(string[] args)
    {
        FileStream fos = new FileStream("Example_05.pdf", FileMode.Create);
        BufferedStream bos = new BufferedStream(fos);

        PDF pdf = new PDF(bos);
        pdf.setCompressor(Compressor.ORIGINAL_ZLIB);

        // Before you enable this flag please read README.ZLIB.TXT
        // in the 'optional' directory.

        // If PDF/A is not required use Helvetica, TimesRoman or Courier
        Font f1 = new Font(pdf, "Helvetica");
        /*
                Font f1 = new Font(pdf,
                        new FileStream(
                                "fonts/DroidFonts/DroidSans.otf", FileMode.Open),
                        CodePage.UNICODE,
                        Embed.YES);
        */
        Page page = new Page(pdf, Letter.PORTRAIT);

        TextLine text = new TextLine(f1);
        text.SetPosition(300.0, 300.0);
        for (int i = 0; i < 360; i += 15)
        {
            text.SetTextDirection(i);
            text.SetUnderline(true);
            // text.SetStrikeLine(true);
            text.SetText("             Hello, World -- " + i + " degrees.");
            text.DrawOn(page);
        }

        text = new TextLine(f1, "WAVE AWAY");
        text.SetPosition(70.0, 50.0);
        text.DrawOn(page);

        f1.SetKernPairs(true);
        text.SetPosition(70.0, 70.0);
        text.DrawOn(page);

        f1.SetKernPairs(false);
        text.SetPosition(70.0, 90.0);
        text.DrawOn(page);

        f1.SetSize(8);
        text = new TextLine(f1, "-- font.SetKernPairs(false);");
        text.SetPosition(150.0, 50.0);
        text.DrawOn(page);
        text.SetPosition(150.0, 90.0);
        text.DrawOn(page);
        text = new TextLine(f1, "-- font.SetKernPairs(true);");
        text.SetPosition(150.0, 70.0);
        text.DrawOn(page);

        Point point = new Point(300.0, 300.0);
        point.SetShape(Point.CIRCLE);
        point.SetFillShape(true);
        point.SetColor(RGB.BLUE);
        point.SetRadius(37.0);
        point.DrawOn(page);
        point.SetRadius(25.0);
        point.SetColor(RGB.WHITE);
        point.DrawOn(page);

        pdf.Flush();
        bos.Close();
    }`
</code>```

note: the code is the exact example provided on pdfJet website: pdfjet

答:
From your (sample) code:

```<code>// Before you enable this flag please read README.ZLIB.TXT
// in the 'optional' directory.
</code>```

From the README.ZLIB.TXT...:

The .NET version of PDFjet is using
  the DeflateStream privided by the
  framework. DeflateStream however does
  not compress data as well as the
  original zlib library.

If you are running PDFjet on 32 bit
  version of Windows and want it to
  create smaller PDF files - copy
  zlibwapi.dll to the same directory
  where PDFjet.dll is installed.

When zlibwapi.dll is not used PDFjet
  is 100% pure managed code. When
  zlibwapi.dll is used - you get better
  compression and smaller PDF files.

Emphasis mine. So you are on 32bit then, I guess? And you absolutely need the unmanaged compression and cannot just return to the managed one?

Body:
1)    A call to PInvoke function 'PDFjet!PDFjet.NET.OptionalDeflateStream::compress' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

What is this? If I remove zlibwapi.dll from the same folder as the PdfJet assembly I get:
2)Unable to load DLL 'zlibwapi.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) (note that I don't add reference to this assembly, I only copy it to Debug folder, and get error1)

code:

   `static void Main(string[] args)
    {
        FileStream fos = new FileStream("Example_05.pdf", FileMode.Create);
        BufferedStream bos = new BufferedStream(fos);

        PDF pdf = new PDF(bos);
        pdf.setCompressor(Compressor.ORIGINAL_ZLIB);

        // Before you enable this flag please read README.ZLIB.TXT
        // in the 'optional' directory.

        // If PDF/A is not required use Helvetica, TimesRoman or Courier
        Font f1 = new Font(pdf, "Helvetica");
        /*
                Font f1 = new Font(pdf,
                        new FileStream(
                                "fonts/DroidFonts/DroidSans.otf", FileMode.Open),
                        CodePage.UNICODE,
                        Embed.YES);
        */
        Page page = new Page(pdf, Letter.PORTRAIT);

        TextLine text = new TextLine(f1);
        text.SetPosition(300.0, 300.0);
        for (int i = 0; i < 360; i += 15)
        {
            text.SetTextDirection(i);
            text.SetUnderline(true);
            // text.SetStrikeLine(true);
            text.SetText("             Hello, World -- " + i + " degrees.");
            text.DrawOn(page);
        }

        text = new TextLine(f1, "WAVE AWAY");
        text.SetPosition(70.0, 50.0);
        text.DrawOn(page);

        f1.SetKernPairs(true);
        text.SetPosition(70.0, 70.0);
        text.DrawOn(page);

        f1.SetKernPairs(false);
        text.SetPosition(70.0, 90.0);
        text.DrawOn(page);

        f1.SetSize(8);
        text = new TextLine(f1, "-- font.SetKernPairs(false);");
        text.SetPosition(150.0, 50.0);
        text.DrawOn(page);
        text.SetPosition(150.0, 90.0);
        text.DrawOn(page);
        text = new TextLine(f1, "-- font.SetKernPairs(true);");
        text.SetPosition(150.0, 70.0);
        text.DrawOn(page);

        Point point = new Point(300.0, 300.0);
        point.SetShape(Point.CIRCLE);
        point.SetFillShape(true);
        point.SetColor(RGB.BLUE);
        point.SetRadius(37.0);
        point.DrawOn(page);
        point.SetRadius(25.0);
        point.SetColor(RGB.WHITE);
        point.DrawOn(page);

        pdf.Flush();
        bos.Close();
    }`

note: the code is the exact example provided on pdfJet website: pdfjet

Body:
From your (sample) code:

// Before you enable this flag please read README.ZLIB.TXT
// in the 'optional' directory.

From the README.ZLIB.TXT...:

The .NET version of PDFjet is using
  the DeflateStream privided by the
  framework. DeflateStream however does
  not compress data as well as the
  original zlib library.

If you are running PDFjet on 32 bit
  version of Windows and want it to
  create smaller PDF files - copy
  zlibwapi.dll to the same directory
  where PDFjet.dll is installed.

When zlibwapi.dll is not used PDFjet
  is 100% pure managed code. When
  zlibwapi.dll is used - you get better
  compression and smaller PDF files.

Emphasis mine. So you are on 32bit then, I guess? And you absolutely need the unmanaged compression and cannot just return to the managed one?


问:
Weird VueJS Routing behaviour
I have an issue with my routing. I have a simple on click handler to push to the router.

methods: {
   page(path) {
      this.$router.push(path);
   }
}
```

<p>which will display the correct content, but the URL <strong>briefly</strong> goes to the correct URL but then goes back to the previous. I only new it was happening because when I clicked the 'back' browser button the URL was then correct.</p>

<p>I opened up the console and decided to test the router</p>

<pre class="lang-js prettyprint-override"><code>$vm0.$router.push('/my-path');
</code>```

Which not only displayed the correct content but the URL was also correct.

I'm now stumped to how debug this further so if anyone has any ideas please let me know.

router.js

import VueRouter from 'vue-router';

const routes = [
    { path: '/', component: require('./views/Campaigns').default },
    { path: '/foo', component: require('./views/Foo').default },
    { path: '/campaign/edit', component: require('./views/EditCampaign').default },
];

export default new VueRouter({
    routes
});

```

<p>main.js</p>

<pre class="lang-js prettyprint-override"><code>import Vue from 'vue'
import VueRouter from 'vue-router';
import router from './routes';

Vue.config.productionTip = false;
Vue.use(VueRouter);

new Vue({
  el: '#app',
  router
});

</code>```

Regards

答:
You have the click event attached to an  element, so you need to prevent the default click behavior which is to follow the link.

You can achieve this in two ways:

1. Using Event Modifier

To address this problem, Vue provides event modifiers for v-on. Recall that modifiers are directive postfixes denoted by a dot.

Button
```
<p><strong>2. Using Event Handler</strong></p>
<p>If you need access to the event object:</p>
<pre class="lang-vue prettyprint-override"><code>Button
</code>```

page(path, e) {
  e.preventDefault()
  this.$router.push(path)
}
```

This might also apply for click events on other kinds of elements, like buttons inside a form. Source

Title: Weird VueJS Routing behaviour

Body:
I have an issue with my routing. I have a simple on click handler to push to the router.

methods: {
   page(path) {
      this.$router.push(path);
   }
}

which will display the correct content, but the URL briefly goes to the correct URL but then goes back to the previous. I only new it was happening because when I clicked the 'back' browser button the URL was then correct.

I opened up the console and decided to test the router

$vm0.$router.push('/my-path');

Which not only displayed the correct content but the URL was also correct.

I'm now stumped to how debug this further so if anyone has any ideas please let me know.

router.js

import VueRouter from 'vue-router';

const routes = [
    { path: '/', component: require('./views/Campaigns').default },
    { path: '/foo', component: require('./views/Foo').default },
    { path: '/campaign/edit', component: require('./views/EditCampaign').default },
];

export default new VueRouter({
    routes
});

main.js

import Vue from 'vue'
import VueRouter from 'vue-router';
import router from './routes';

Vue.config.productionTip = false;
Vue.use(VueRouter);

new Vue({
  el: '#app',
  router
});

Regards

Body:
You have the click event attached to an <a> element, so you need to prevent the default click behavior which is to follow the link.

You can achieve this in two ways:

1. Using Event Modifier

To address this problem, Vue provides event modifiers for v-on. Recall that modifiers are directive postfixes denoted by a dot.

<a @click.prevent="page('/foo')">Button</a>

2. Using Event Handler

If you need access to the event object:

<a @click="page('/foo', $event)">Button</a>

page(path, e) {
  e.preventDefault()
  this.$router.push(path)
}

This might also apply for click events on other kinds of elements, like buttons inside a form. Source


问:
Array loop always returning last value
I have the following loop:

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
  var html = "<div class='group' data-department='"+array[i]+"'>";
  html += "<div class='title'>" + textArray[i] + "</div>";
  html += "</div>";
}
</code>```

The output of this JS is:

```<code><div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>
</code>```

What I'm after is:

```<code><div class="group" data-department="Value 1">
   <div class="title">Text 1</div>
</div>

<div class="group" data-department="Value 2">
   <div class="title">Text 2</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>
</code>```

A console.log("Value: " + array[i]); returns:

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

And a console.log("Text: " + textArray[i]); returns:

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

So unsure why my markup is being rendered based on the last item in the array?

Following the removal of var from with the loop, I'm getting the following results (container divs get nested within each other):

var html = "";

for (let i = 0; i < array.length; i++) {
  html += "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="group" data-department="Value 1">
  <div class="title">Text 1</div>
  <div class="group" data-department="Value 2">
    <div class="title">Text 2</div>
    <div class="group" data-department="Value 3">
      <div class="title">Text 3</div>
    </div>
  </div>
</div></code>```

答:
```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
   html += "<div class='group' data-department='"+array[i]+"'>";
  html += "<div class='title'>" + textArray[i] + "</div>";
  html += "</div>";

}

console.log(html)
</code>```

You re assigned the variable html inside your loop.This is causing the html variable to reset everytime the loop starts. At the end you'll only have the last value.

You say the values are nested but for me thats not the case:

var html = "";
var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

for (let i = 0; i < array.length; i++) {
  html += "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}

console.log(html)```
</div>
</div>
</p>

<p>Returns :</p>

```

Text 1

Text 2

Text 3

```

Title: Array loop always returning last value

Body:
I have the following loop:

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
  var html = "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}

The output of this JS is:

Text 3

Text 3

Text 3

What I'm after is:

Text 1

Text 2

Text 3

A console.log("Value: " + array[i]); returns:

Value: Value 1
Value: Value 2
Value: Value 3

And a console.log("Text: " + textArray[i]); returns:

Text: Text 1
Text: Text 2
Text: Text 3

So unsure why my markup is being rendered based on the last item in the array?

Following the removal of var from with the loop, I'm getting the following results (container divs get nested within each other):

var html = "";

for (let i = 0; i < array.length; i++) {
  html += "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}

Text 1

Text 2

Text 3

Body:
var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
   html += "<div class='group' data-department='"+array[i]+"'>";
  html += "<div class='title'>" + textArray[i] + "</div>";
  html += "</div>";

}

console.log(html)

You re assigned the variable html inside your loop.This is causing the html variable to reset everytime the loop starts. At the end you'll only have the last value.

You say the values are nested but for me thats not the case:

var html = "";
var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

for (let i = 0; i < array.length; i++) {
  html += "<div class='group' data-department='"+array[i]+"'>";
  html += "<div class='title'>" + textArray[i] + "</div>";
  html += "</div>";
}

console.log(html)

Returns :

<div class='group' data-department='Value 1'>
    <div class='title'>Text 1</div>
</div>

<div class='group' data-department='Value 2'>
    <div class='title'>Text 2</div>
</div>

<div class='group' data-department='Value 3'>
    <div class='title'>Text 3</div><
/div>


问:
unexpected results when converting nvarchar to datetime using substrings
I have to deal with the following columns:

```<code>StartTime (nvarchar(10), null)
StartDate (nvarchar(10), null)
</code>```

StartTime contains the Time as following: hhmmss

StartDate contains the Date as following: yyyymmdd (m=month)

To concatenate and convert StartDate and StartTime to a datetime i use the following code inside a stored procedure:

```<code>TRY_CAST(SUBSTRING(xy.StartDate,7,2) + '.' + SUBSTRING(xy.StartDate,5,2) + '.' + SUBSTRING(xy.StartDate,1,4) + ' ' + SUBSTRING(xy.StartTime,1,2) + ':' + SUBSTRING(xy.StartTime,3,2) + ':' + SUBSTRING(xy.StartTime,5,2) as datetime) as FULLSTARTDATE
</code>```

Now imagine these values for two cases:

Case 1:

```<code>StartTime = 000000
StartDate = 20191201
FULLSTARTDATE = 2019-01-12 00:00:00.000
</code>```

Case 2:

```<code>StartTime = 000000
StartDate = 20191220
FULLSTARTDATE = NULL
</code>```

Why does Case 2 not output 2019-20-12? It may be a trivial issue but i can't seem to figure it out for almost an hour now.

答:
TSQL DATETIME ISO 8601</p>

```<code>select
TRY_CAST(SUBSTRING(xy.StartDate,1,4) + '-' + SUBSTRING(xy.StartDate,5,2) + '-' + SUBSTRING(xy.StartDate,7,2)+ 'T' + SUBSTRING(xy.StartTime,1,2) + ':' + SUBSTRING(xy.StartTime,3,2) + ':' + SUBSTRING(xy.StartTime,5,2)+'Z' as datetime) as FULLSTARTDATE,
try_cast(StartDate + ' ' + stuff(stuff(StartTime, 5, 0, ':'), 3, 0, ':') as datetime)
from
(values('20191201', '000000' ), ('20191220', '000000')) as xy(StartDate, StartTime);
</code>```

Body:
I have to deal with the following columns:

StartTime (nvarchar(10), null)
StartDate (nvarchar(10), null)

StartTime contains the Time as following: hhmmss

StartDate contains the Date as following: yyyymmdd (m=month)

To concatenate and convert StartDate and StartTime to a datetime i use the following code inside a stored procedure:

TRY_CAST(SUBSTRING(xy.StartDate,7,2) + '.' + SUBSTRING(xy.StartDate,5,2) + '.' + SUBSTRING(xy.StartDate,1,4) + ' ' + SUBSTRING(xy.StartTime,1,2) + ':' + SUBSTRING(xy.StartTime,3,2) + ':' + SUBSTRING(xy.StartTime,5,2) as datetime) as FULLSTARTDATE

Now imagine these values for two cases:

Case 1:

StartTime = 000000
StartDate = 20191201
FULLSTARTDATE = 2019-01-12 00:00:00.000

Case 2:

StartTime = 000000
StartDate = 20191220
FULLSTARTDATE = NULL

Why does Case 2 not output 2019-20-12? It may be a trivial issue but i can't seem to figure it out for almost an hour now.

Body:
TSQL DATETIME ISO 8601

select
TRY_CAST(SUBSTRING(xy.StartDate,1,4) + '-' + SUBSTRING(xy.StartDate,5,2) + '-' + SUBSTRING(xy.StartDate,7,2)+ 'T' + SUBSTRING(xy.StartTime,1,2) + ':' + SUBSTRING(xy.StartTime,3,2) + ':' + SUBSTRING(xy.StartTime,5,2)+'Z' as datetime) as FULLSTARTDATE,
try_cast(StartDate + ' ' + stuff(stuff(StartTime, 5, 0, ':'), 3, 0, ':') as datetime)
from
(values('20191201', '000000' ), ('20191220', '000000')) as xy(StartDate, StartTime);


问:
how to hide the title bar or window in python
i want to hide my window or tittle bar of my window. as i want to show the output of the opencv frameless.

tell me how can i do that with the help of tkinter or pyqt5.
and also i want the size of the output according to my specation.
and can i resize and change the place of the output like drag and drop anywhere on desktop while the code is running.

```<code>import cv2
import os
import numpy as np
import datetime

date=datetime.datetime.now()
framerate=24
screen_size=(640,480) #std res 640,480
filename='E:/project/videos/cam_%s%s%s%s%s%s.avi' %(date.year,date.month,date.day,date.hour,date.minute,date.second)
fourcc = cv2.VideoWriter_fourcc(*'XVID')

cap=cv2.VideoCapture(0)
out= cv2.VideoWriter(filename,fourcc,framerate,screen_size)
cv2.namedWindow('frame',cv2.WINDOW_NORMAL)
cv2.resizeWindow('frame',280,190)
cv2.moveWindow('frame',5,495)
#cv2.namedWindow('frame',cv2.WND_PROP_FULLSCREEN)   #use for full screen
#cv2.setWindowProperty('frame', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:

        frame=cv2.flip(frame,1)

        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()
screen.mainloop()
</code>```

答:
Below is an example using tkinter to show the capture images from webcam:

```<code>import cv2
import datetime
from tkinter import *
from PIL import Image, ImageTk

screen = Tk()
screen.overrideredirect(1)  # remove window decorations
screen.geometry('280x200+5+520')  # move the window

framerate = 24
screen_size = (640, 480) #std res 640,480

date = datetime.datetime.now()
filename = 'E:/project/videos/cam_%s%s%s%s%s%s.avi' % (date.year, date.month, date.day,
                                                       date.hour, date.minute, date.second)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(filename, fourcc, framerate, screen_size)

cap = cv2.VideoCapture(0)

imgbox = Label(screen)
imgbox.pack(fill=BOTH, expand=1)

def quit(event):
    cap.release()
    out.release()
    screen.destroy()

def read_frame():
    ret, frame = cap.read()
    if ret:
        frame = cv2.flip(frame, 1)
        out.write(frame)
        # since openCV capture image is in BGR color sequence
        # so need to convert it to RGB color sequence
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        # convert the openCV image to PIL (Pillow) format
        img = Image.fromarray(frame)
        #img = img.resize((280, 200))  # not keep aspect ratio
        img.thumbnail((280, 200))  # keep aspect ratio
        img = ImageTk.PhotoImage(img)
        imgbox.config(image=img)  # update the image
        img.image = img  # keep a reference of the image to avoid being garbage collected
    screen.after(20, read_frame)  # schedule next read after 20 ms

# bind the 'q' key to quit program
screen.bind('q', quit)

read_frame()
screen.mainloop()
</code>```

Body:
i want to hide my window or tittle bar of my window. as i want to show the output of the opencv frameless.

tell me how can i do that with the help of tkinter or pyqt5.
and also i want the size of the output according to my specation.
and can i resize and change the place of the output like drag and drop anywhere on desktop while the code is running.

import cv2
import os
import numpy as np
import datetime

date=datetime.datetime.now()
framerate=24
screen_size=(640,480) #std res 640,480
filename='E:/project/videos/cam_%s%s%s%s%s%s.avi' %(date.year,date.month,date.day,date.hour,date.minute,date.second)
fourcc = cv2.VideoWriter_fourcc(*'XVID')

cap=cv2.VideoCapture(0)
out= cv2.VideoWriter(filename,fourcc,framerate,screen_size)
cv2.namedWindow('frame',cv2.WINDOW_NORMAL)
cv2.resizeWindow('frame',280,190)
cv2.moveWindow('frame',5,495)
#cv2.namedWindow('frame',cv2.WND_PROP_FULLSCREEN)   #use for full screen
#cv2.setWindowProperty('frame', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:

        frame=cv2.flip(frame,1)

        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()
screen.mainloop()

Body:
Below is an example using tkinter to show the capture images from webcam:

import cv2
import datetime
from tkinter import *
from PIL import Image, ImageTk

screen = Tk()
screen.overrideredirect(1)  # remove window decorations
screen.geometry('280x200+5+520')  # move the window

framerate = 24
screen_size = (640, 480) #std res 640,480

date = datetime.datetime.now()
filename = 'E:/project/videos/cam_%s%s%s%s%s%s.avi' % (date.year, date.month, date.day,
                                                       date.hour, date.minute, date.second)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(filename, fourcc, framerate, screen_size)

cap = cv2.VideoCapture(0)

imgbox = Label(screen)
imgbox.pack(fill=BOTH, expand=1)

def quit(event):
    cap.release()
    out.release()
    screen.destroy()

def read_frame():
    ret, frame = cap.read()
    if ret:
        frame = cv2.flip(frame, 1)
        out.write(frame)
        # since openCV capture image is in BGR color sequence
        # so need to convert it to RGB color sequence
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        # convert the openCV image to PIL (Pillow) format
        img = Image.fromarray(frame)
        #img = img.resize((280, 200))  # not keep aspect ratio
        img.thumbnail((280, 200))  # keep aspect ratio
        img = ImageTk.PhotoImage(img)
        imgbox.config(image=img)  # update the image
        img.image = img  # keep a reference of the image to avoid being garbage collected
    screen.after(20, read_frame)  # schedule next read after 20 ms

# bind the 'q' key to quit program
screen.bind('q', quit)

read_frame()
screen.mainloop()


问:
Getting 'str.indexOf is not a function' error when trying to S3.getSignedUrl()
While trying to get a signed URL for a getObject I am getting the following error from the aws-sdk library:

```<code><proj-dir>\node_modules\aws-sdk\lib\util.js:983
      return str && str.indexOf('arn:') === 0 && str.split(':').length >= 6;
                        ^

TypeError: str.indexOf is not a function
    at Object.validateARN [as validate] (<proj-dir>\node_modules\aws-sdk\lib\util.js:983:25)
    at features.constructor.hasBucketInParams [as isAccessPointApplicable] (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:180:2
3)
    at features.constructor.setupRequestListeners (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:126:14)
    at features.constructor.addAllRequestListeners (<proj-dir>\node_modules\aws-sdk\lib\service.js:276:10)
    at features.constructor.makeRequest (<proj-dir>\node_modules\aws-sdk\lib\service.js:203:10)
    at features.constructor.getSignedUrl (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:1026:24)
    at Object.<anonymous> (<proj-dir>\s3-test.js:101:8)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
</code>```

Other S3 calls (like listBuckets) are working fine. Here's my test file:

```<code>const S3 = require('./utils/s3Util');
const C = require('./utils/constants');
const _ = require('lodash');

// other code...

S3.svc.getSignedUrl('getObject', { Bucket: C.S3_BUCKET, Key: 'TestFrequencyCount.java', Expires: 60 }).promise()
    .then(retVal => {
        console.log("Return value:", retVal);
    }).catch(err => {
        console.log("Error::", err);
    });
</code>```

The s3Util.js file:

```<code>const C = require('./constants');
const AWS = require('aws-sdk');
const keys = require("../config/aws-config.json");

// AWS.config.update(keys);

const s3 = new AWS.S3({...keys, apiVersion: C.S3_API_VER, signatureVersion: 'v4' });

module.exports = Object.freeze({
    svc: s3,
});
</code>```

I was using aws-sdk version 2.610.0, then updated that to 2.621.0, but the problem remains.

Even tried by changing the way I was loading the AWS account credentials (will use an IAM user once I have things figured out) based on a combination of this note from AWS SDK documentation:

Note: You must ensure that you have static or previously resolved
credentials if you call this method synchronously (with no callback),
otherwise it may not properly sign the request. If you cannot
guarantee this (you are using an asynchronous credential provider,
i.e., EC2 IAM roles), you should always call this method with an
asynchronous callback.

and the solution given at Node.js and aws credentials error - json (which suggested not using AWS.config.loadFromPath(path) but instead loading the parameters directly through AWS.config.update(...)), but to no avail.

In deseparation I tried the callback version as well, but as expected it gave the same result:

```<code>S3.svc.getSignedUrl('getObject', { Bucket: C.S3_BUCKET, Key: 'TestFrequencyCount.java', Expires: 60 }, (err, retVal) => {
    if (err) {
        console.log("Error::", err);
    } else {
        console.log("Return value:", retVal);
    }
});
</code>```

答: The error was with the definition of C.S3_BUCKET: it should have been used instead as: C.S3_BUCKET[process.env.NODE_ENV].

Body:
While trying to get a signed URL for a getObject I am getting the following error from the aws-sdk library:

<proj-dir>\node_modules\aws-sdk\lib\util.js:983
      return str && str.indexOf('arn:') === 0 && str.split(':').length >= 6;
                        ^

TypeError: str.indexOf is not a function
    at Object.validateARN [as validate] (<proj-dir>\node_modules\aws-sdk\lib\util.js:983:25)
    at features.constructor.hasBucketInParams [as isAccessPointApplicable] (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:180:2
3)
    at features.constructor.setupRequestListeners (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:126:14)
    at features.constructor.addAllRequestListeners (<proj-dir>\node_modules\aws-sdk\lib\service.js:276:10)
    at features.constructor.makeRequest (<proj-dir>\node_modules\aws-sdk\lib\service.js:203:10)
    at features.constructor.getSignedUrl (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:1026:24)
    at Object.<anonymous> (<proj-dir>\s3-test.js:101:8)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)

Other S3 calls (like listBuckets) are working fine. Here's my test file:

const S3 = require('./utils/s3Util');
const C = require('./utils/constants');
const _ = require('lodash');

// other code...

S3.svc.getSignedUrl('getObject', { Bucket: C.S3_BUCKET, Key: 'TestFrequencyCount.java', Expires: 60 }).promise()
    .then(retVal => {
        console.log("Return value:", retVal);
    }).catch(err => {
        console.log("Error::", err);
    });

The s3Util.js file:

const C = require('./constants');
const AWS = require('aws-sdk');
const keys = require("../config/aws-config.json");

// AWS.config.update(keys);

const s3 = new AWS.S3({...keys, apiVersion: C.S3_API_VER, signatureVersion: 'v4' });

module.exports = Object.freeze({
    svc: s3,
});

I was using aws-sdk version 2.610.0, then updated that to 2.621.0, but the problem remains.

Even tried by changing the way I was loading the AWS account credentials (will use an IAM user once I have things figured out) based on a combination of this note from AWS SDK documentation:

Note: You must ensure that you have static or previously resolved
credentials if you call this method synchronously (with no callback),
otherwise it may not properly sign the request. If you cannot
guarantee this (you are using an asynchronous credential provider,
i.e., EC2 IAM roles), you should always call this method with an
asynchronous callback.

and the solution given at Node.js and aws credentials error - json (which suggested not using AWS.config.loadFromPath(path) but instead loading the parameters directly through AWS.config.update(...)), but to no avail.

In deseparation I tried the callback version as well, but as expected it gave the same result:

S3.svc.getSignedUrl('getObject', { Bucket: C.S3_BUCKET, Key: 'TestFrequencyCount.java', Expires: 60 }, (err, retVal) => {
    if (err) {
        console.log("Error::", err);
    } else {
        console.log("Return value:", retVal);
    }
});


问:
Python write both commands and their output to a file
Is there any way to write both commands and their output to an external file?

Let's say I have a script outtest.py :

```<code>import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
d_median = round(median(d), 2)
print(f'median: {d_median}')
</code>```

Now if I want to capture its output only I know I can just do:

```<code>python3 outtest.py > outtest.txt
</code>```

However, this will only give me an outtest.txt file with e.g.:

```<code>mean: 0.34
median: 0.27
</code>```

What I'm looking for is a way to get an output file like:

```<code>import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
>> mean: 0.34
d_median = round(median(d), 2)
print(f'median: {d_median}')
>> median: 0.27
</code>```

Or some other format (markdown, whatever). Essentially, something like jupyter notebook or Rmarkdown but with using standard .py files.

Is there any easy way to achieve this?

答:
You can assign result to variable before print out and later on write those values to file

Here is example

```<code>import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
foo = f'mean: {d_mean}'
print(foo)
d_median = round(median(d), 2)
bar = f'median: {d_median}'
print(bar)

# save to file
with open("outtest.txt", "a+") as file:
    file.write(foo + "\n")
    file.write(bar + "\n")
    file.close()
</code>```

argument "a+" mean open file and append content to file instead of overwrite if file was exist.

Body:
Is there any way to write both commands and their output to an external file?

Let's say I have a script outtest.py :

import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
d_median = round(median(d), 2)
print(f'median: {d_median}')

Now if I want to capture its output only I know I can just do:

python3 outtest.py > outtest.txt

However, this will only give me an outtest.txt file with e.g.:

mean: 0.34
median: 0.27

What I'm looking for is a way to get an output file like:

import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
>> mean: 0.34
d_median = round(median(d), 2)
print(f'median: {d_median}')
>> median: 0.27

Or some other format (markdown, whatever). Essentially, something like jupyter notebook or Rmarkdown but with using standard .py files.

Is there any easy way to achieve this?

Body:
You can assign result to variable before print out and later on write those values to file

Here is example

import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
foo = f'mean: {d_mean}'
print(foo)
d_median = round(median(d), 2)
bar = f'median: {d_median}'
print(bar)

# save to file
with open("outtest.txt", "a+") as file:
    file.write(foo + "\n")
    file.write(bar + "\n")
    file.close()

argument "a+" mean open file and append content to file instead of overwrite if file was exist.


问:
Get column sum and use it for distribute a value
I have 2 tables, sales_order and sales_order_line.

sales_order table contains a detail of a transaction in transaction level and sales_order_line table contains a detail in SKU (item) level. I joined those 2 tables and realized that discount value is on transaction level. When customer bought more than 1 item, I need to distribute the value of discount based on item price and when customer bought just 1 item, discount value just applied as it is. The tables look like this.

sales_order

```<code>ID   | PLATFORM_ORDER_CODE | OMS_ORDER_CODE | DISCOUNT_TOTAL
0001          19000001         nebula0001         300000
0002          19000001         nebula0002         300000
0003          19000001         nebula0003         300000
0004          19000002         nebula0004         100000
0005          19000002         nebula0005         100000
0006          19000003         nebula0006          50000
</code>```

sales_order_line

```<code>SALES_ORDER_ID | PLATFORM_ORDER_CODE | SKU_CODE | UNIT_PRICE
0001                   19000001        SKUA0001     200000
0002                   19000001        SKUA0002     100000
0003                   19000001        SKUA0003     300000
0004                   19000002        SKUA0001     200000
0005                   19000002        SKUA0002     100000
0006                   19000003        SKUA0001     200000
</code>```

This is my attempt on DB Fiddle and I need the result to be like this

```<code>PLATFORM_ORDER_CODE | OMS_ORDER_CODE | SKU_CODE | UNIT_PRICE | DISCOUNT
19000001                 nebula0001    SKUA0001     200000      100000
19000001                 nebula0002    SKUA0002     100000      50000
19000001                 nebula0003    SKUA0003     300000      150000
19000002                 nebula0004    SKUA0001     200000      66666.6666
19000002                 nebula0005    SKUA0002     100000      33333.3333
19000003                 nebula0006    SKUA0001     200000      50000
</code>```

答:
```<code>SELECT B.PLATFORM_ORDER_CODE,
       A.OMS_ORDER_CODE,
       B.SKU_CODE,
       B.UNIT_PRICE,
       A.DISCOUNT_TOTAL/C.TOTAL_PRICE*B.UNIT_PRICE DISCOUNT
FROM t_td_sales_order A
JOIN t_td_sales_order_line B ON B.SALES_ORDER_ID = A.ID
JOIN ( SELECT PLATFORM_ORDER_CODE, SUM(UNIT_PRICE) TOTAL_PRICE
       FROM t_td_sales_order_line
       GROUP BY PLATFORM_ORDER_CODE ) C ON B.PLATFORM_ORDER_CODE = C.PLATFORM_ORDER_CODE
</code>```

fiddle

Body:
I have 2 tables, sales_order and sales_order_line.

sales_order table contains a detail of a transaction in transaction level and sales_order_line table contains a detail in SKU (item) level. I joined those 2 tables and realized that discount value is on transaction level. When customer bought more than 1 item, I need to distribute the value of discount based on item price and when customer bought just 1 item, discount value just applied as it is. The tables look like this.

sales_order

ID   | PLATFORM_ORDER_CODE | OMS_ORDER_CODE | DISCOUNT_TOTAL
0001          19000001         nebula0001         300000
0002          19000001         nebula0002         300000
0003          19000001         nebula0003         300000
0004          19000002         nebula0004         100000
0005          19000002         nebula0005         100000
0006          19000003         nebula0006          50000

sales_order_line

SALES_ORDER_ID | PLATFORM_ORDER_CODE | SKU_CODE | UNIT_PRICE
0001                   19000001        SKUA0001     200000
0002                   19000001        SKUA0002     100000
0003                   19000001        SKUA0003     300000
0004                   19000002        SKUA0001     200000
0005                   19000002        SKUA0002     100000
0006                   19000003        SKUA0001     200000

This is my attempt on DB Fiddle and I need the result to be like this

PLATFORM_ORDER_CODE | OMS_ORDER_CODE | SKU_CODE | UNIT_PRICE | DISCOUNT
19000001                 nebula0001    SKUA0001     200000      100000
19000001                 nebula0002    SKUA0002     100000      50000
19000001                 nebula0003    SKUA0003     300000      150000
19000002                 nebula0004    SKUA0001     200000      66666.6666
19000002                 nebula0005    SKUA0002     100000      33333.3333
19000003                 nebula0006    SKUA0001     200000      50000

Body:
SELECT B.PLATFORM_ORDER_CODE,
       A.OMS_ORDER_CODE,
       B.SKU_CODE,
       B.UNIT_PRICE,
       A.DISCOUNT_TOTAL/C.TOTAL_PRICE*B.UNIT_PRICE DISCOUNT
FROM t_td_sales_order A
JOIN t_td_sales_order_line B ON B.SALES_ORDER_ID = A.ID
JOIN ( SELECT PLATFORM_ORDER_CODE, SUM(UNIT_PRICE) TOTAL_PRICE
       FROM t_td_sales_order_line
       GROUP BY PLATFORM_ORDER_CODE ) C ON B.PLATFORM_ORDER_CODE = C.PLATFORM_ORDER_CODE

fiddle


问:
delete button issue 'str' object is not a mapping
I have an Imageloader app that each time upload an image it will show on the html page so i added download button to the images and i want to add delete button also ,I am trying to add delete button to image each time I press the button I got error 'str' object is not a mapping, even I don't understand what this error mean I tried a lot of things but it didn't work below is my code, any help appreciated.

urls.py -main

```<code>urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home, name='home'),
    path('image/', include('imageloader.urls'), 'imageloader'),
]
</code>```

urls.py -app

```<code>app_name = 'imageloader'
urlpatterns = [
    path('<int:pk>/', views.delete_pic, name='delete_pic'),
]
</code>```

models.py -updated

```<code>class Imageloader(models.Model):
def validate_file_size(value):
    filesize = value.size

    if filesize > 3000000:
        raise ValidationError(
            "The maximum file size that can be uploaded is 3MB")
    else:
        return value

image = models.ImageField(
    help_text='max size only 3mb ',
    upload_to="imageloader_file/",
    validators=[validate_file_size],
    max_length=120,
    blank=False,
    unique=True,
)

class Meta:
    ordering = ['-id']

def __str__(self):
    return str(self.image)
</code>```

view.py

```<code>def home(request):
    """this function to view the home page """
    template_home = 'index.html'
    img = Imageloader.objects.all()
    if request.method == "POST":
        form = Imageloaderform(request.POST, request.FILES)
        if form.is_valid():
            image = form.cleaned_data.get("image")
            form.save()
            messages.success(request, f'Image uploaded successfully')
            return redirect('home')
        else:
            messages.error(request, f'Pls upload an Image!')
    else:
        form = Imageloaderform()
    return render(request, template_home, {
        'form': form,
        'img': img,
    })

def delete_pic(request, pk):
    if request.method == "POST":
        img = Imageloader.object.get(pk=pk)
        img.delete()
    return redirect('home')
</code>```

the template:

```<code>{% for image2 in img %}
        <div class="container">
            <div class="d-flex justify-content-center">
                <img style="height: 300px;" class="mb-3 w-50" src="{{ image2.image.url }}" alt="images!">

            </div>
            <div class="d-flex justify-content-center">
                <a href="{{ image2.image.url }}" download>
                    <button type="button" class="btn btn-outline-primary mb-3">Download</button>
                </a>
                <form method="POST" action="{% url 'imageloader:delete_pic' image2.id %}">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-outline-danger ml-2">Delete</button>
                </form>

            </div>

        </div>
        {% endfor %}
</code>```

below is the exception: -updated

```<code>    TypeError at /image/10/
'str' object is not a mapping
Request Method: POST
Request URL:    http://127.0.0.1:8000/image/10/
Django Version: 3.0.3
Exception Type: TypeError
Exception Value:
'str' object is not a mapping
Exception Location: D:\Work\Dummy-Website\dummy website practice\second try\practice_2 project\env\lib\site-packages\django\urls\resolvers.py in resolve, line 556
Python Executable:  D:\Work\Dummy-Website\dummy website practice\second try\practice_2 project\env\Scripts\python.exe
Python Version: 3.7.4
Python Path:
['D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env\\Scripts\\python37.zip',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env\\DLLs',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env\\lib',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env\\Scripts',
 'c:\\users\\yazan bader\\appdata\\local\\programs\\python\\python37\\Lib',
 'c:\\users\\yazan bader\\appdata\\local\\programs\\python\\python37\\DLLs',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env\\lib\\site-packages']
Server time:    Thu, 20 Feb 2020 18:27:55 +0300
</code>```

答:
You can not call delete() method on the self.image as it is not an object, hence the error. In my opinion, you should use signals to do so. Once the object is deleted from the database you can remove the actual file from the file system.

```<code>@receiver(models.signals.post_delete, sender=Imageloader)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    """
    Deletes file from filesystem
    when corresponding `MediaFile` object is deleted.
    """
    if os.path.isfile(instance.image.path):
        os.remove(instance.image.path)
</code>```

EDIT:

If you just want to delete the database entry then remove the code for method delete in you models.py and the delete() method provided by Django will work absolutely fine. Because there is no need to override the delete method if you are just deleting the object from the database and not performing any other action.

Body:
I have an Imageloader app that each time upload an image it will show on the html page so i added download button to the images and i want to add delete button also ,I am trying to add delete button to image each time I press the button I got error 'str' object is not a mapping, even I don't understand what this error mean I tried a lot of things but it didn't work below is my code, any help appreciated.

urls.py -main

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home, name='home'),
    path('image/', include('imageloader.urls'), 'imageloader'),
]

urls.py -app

app_name = 'imageloader'
urlpatterns = [
    path('<int:pk>/', views.delete_pic, name='delete_pic'),
]

models.py -updated

class Imageloader(models.Model):
def validate_file_size(value):
    filesize = value.size

    if filesize > 3000000:
        raise ValidationError(
            "The maximum file size that can be uploaded is 3MB")
    else:
        return value

image = models.ImageField(
    help_text='max size only 3mb ',
    upload_to="imageloader_file/",
    validators=[validate_file_size],
    max_length=120,
    blank=False,
    unique=True,
)

class Meta:
    ordering = ['-id']

def __str__(self):
    return str(self.image)

view.py

def home(request):
    """this function to view the home page """
    template_home = 'index.html'
    img = Imageloader.objects.all()
    if request.method == "POST":
        form = Imageloaderform(request.POST, request.FILES)
        if form.is_valid():
            image = form.cleaned_data.get("image")
            form.save()
            messages.success(request, f'Image uploaded successfully')
            return redirect('home')
        else:
            messages.error(request, f'Pls upload an Image!')
    else:
        form = Imageloaderform()
    return render(request, template_home, {
        'form': form,
        'img': img,
    })

def delete_pic(request, pk):
    if request.method == "POST":
        img = Imageloader.object.get(pk=pk)
        img.delete()
    return redirect('home')

the template:

{% for image2 in img %}

                    <button type="button" class="btn btn-outline-primary mb-3">Download</button>

                <form method="POST" action="{% url 'imageloader:delete_pic' image2.id %}">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-outline-danger ml-2">Delete</button>
                </form>

        {% endfor %}

below is the exception: -updated

    TypeError at /image/10/
'str' object is not a mapping
Request Method: POST
Request URL:    http://127.0.0.1:8000/image/10/
Django Version: 3.0.3
Exception Type: TypeError
Exception Value:
'str' object is not a mapping
Exception Location: D:\Work\Dummy-Website\dummy website practice\second try\practice_2 project\env\lib\site-packages\django\urls\resolvers.py in resolve, line 556
Python Executable:  D:\Work\Dummy-Website\dummy website practice\second try\practice_2 project\env\Scripts\python.exe
Python Version: 3.7.4
Python Path:
['D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env\\Scripts\\python37.zip',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env\\DLLs',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env\\lib',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env\\Scripts',
 'c:\\users\\yazan bader\\appdata\\local\\programs\\python\\python37\\Lib',
 'c:\\users\\yazan bader\\appdata\\local\\programs\\python\\python37\\DLLs',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env',
 'D:\\Work\\Dummy-Website\\dummy website practice\\second try\\practice_2 '
 'project\\env\\lib\\site-packages']
Server time:    Thu, 20 Feb 2020 18:27:55 +0300

Body:
You can not call delete() method on the self.image as it is not an object, hence the error. In my opinion, you should use signals to do so. Once the object is deleted from the database you can remove the actual file from the file system.

@receiver(models.signals.post_delete, sender=Imageloader)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    """
    Deletes file from filesystem
    when corresponding `MediaFile` object is deleted.
    """
    if os.path.isfile(instance.image.path):
        os.remove(instance.image.path)

EDIT:

If you just want to delete the database entry then remove the code for method delete in you models.py and the delete() method provided by Django will work absolutely fine. Because there is no need to override the delete method if you are just deleting the object from the database and not performing any other action.


问:
C# Design pattern for periodic execution of multiple Threads
I have a below requirement in my C# Windows Service.

At the starting of Service, it fetches a collection of data from db
and keeps it in memory.

Have a business logic to be executed periodically from 3 different threads.

Each thread will execute same bussiness logic with different subset of data from the data collection mentioned in step 1. Each thread will produce different result sets.

All 3 threads will run periodically if any change happened to the data collection.

When any client makes call to the service, service should be able to return the status of the thread execution.

I know C# has different mechanisms to implement periodic thread execution.
 Timers, Threads with Sleep, Event eventwaithandle ect.,
 I am trying to understand Which threading mechanism or design pattern will be best fit for this requirement?

答:
A more modern approach would be using tasks but have a look at the principles </p>

```<code>namespace Test {

public class Program {

    public static void Main() {

        System.Threading.Thread main = new System.Threading.Thread(() => new Processor().Startup());
        main.IsBackground = false;
        main.Start();
        System.Console.ReadKey();
    }
}

public class ProcessResult { /* add your result state */ }

public class ProcessState {

    public ProcessResult ProcessResult1 { get; set; }
    public ProcessResult ProcessResult2 { get; set; }
    public ProcessResult ProcessResult3 { get; set; }
    public string State { get; set; }
}

public class Processor {

    private readonly object _Lock = new object();
    private readonly DataFetcher _DataFetcher;
    private ProcessState _ProcessState;

    public Processor() {
        _DataFetcher = new DataFetcher();
        _ProcessState = null;
    }

    public void Startup() {
        _DataFetcher.DataChanged += DataFetcher_DataChanged;
    }

    private void DataFetcher_DataChanged(object sender, DataEventArgs args) => StartProcessingThreads(args.Data);

    private void StartProcessingThreads(string data) {

        lock (_Lock) {
            _ProcessState = new ProcessState() { State = "Starting", ProcessResult1 = null, ProcessResult2 = null, ProcessResult3 = null };

            System.Threading.Thread one = new System.Threading.Thread(() => DoProcess1(data)); // manipulate the data toa subset
            one.IsBackground = true;
            one.Start();

            System.Threading.Thread two = new System.Threading.Thread(() => DoProcess2(data)); // manipulate the data toa subset
            two.IsBackground = true;
            two.Start();

            System.Threading.Thread three = new System.Threading.Thread(() => DoProcess3(data)); // manipulate the data toa subset
            three.IsBackground = true;
            three.Start();
        }
    }

    public ProcessState GetState() => _ProcessState;

    private void DoProcess1(string dataSubset) {
        // do work
        ProcessResult result = new ProcessResult(); // this object contains the result
        // on completion
        lock (_Lock) {
            _ProcessState = new ProcessState() { State = (_ProcessState.State ?? string.Empty) + ", 1 done", ProcessResult1 = result, ProcessResult2 = _ProcessState?.ProcessResult2, ProcessResult3 = _ProcessState?.ProcessResult3 };
        }
    }

    private void DoProcess2(string dataSubset) {
        // do work
        ProcessResult result = new ProcessResult(); // this object contains the result
        // on completion
        lock (_Lock) {
            _ProcessState = new ProcessState() { State = (_ProcessState.State ?? string.Empty) + ", 2 done", ProcessResult1 = _ProcessState?.ProcessResult1 , ProcessResult2 = result, ProcessResult3 = _ProcessState?.ProcessResult3 };
        }
    }

    private void DoProcess3(string dataSubset) {
        // do work
        ProcessResult result = new ProcessResult(); // this object contains the result
        // on completion
        lock (_Lock) {
            _ProcessState = new ProcessState() { State = (_ProcessState.State ?? string.Empty) + ", 3 done", ProcessResult1 = _ProcessState?.ProcessResult1, ProcessResult2 = _ProcessState?.ProcessResult2, ProcessResult3 = result };
        }
    }
}

public class DataEventArgs : System.EventArgs {

    // data here is string, but could be anything -- just think of thread safety when accessing from the 3 processors
    private readonly string _Data;

    public DataEventArgs(string data) {
        _Data = data;
    }

    public string Data => _Data;
}

public class DataFetcher {
    //  watch for data changes and fire when data has changed
    public event System.EventHandler<DataEventArgs> DataChanged;
}
</code>```

<p>}</p>

Body:
A more modern approach would be using tasks but have a look at the principles

namespace Test {

public class Program {

    public static void Main() {

        System.Threading.Thread main = new System.Threading.Thread(() => new Processor().Startup());
        main.IsBackground = false;
        main.Start();
        System.Console.ReadKey();
    }
}

public class ProcessResult { /* add your result state */ }

public class ProcessState {

    public ProcessResult ProcessResult1 { get; set; }
    public ProcessResult ProcessResult2 { get; set; }
    public ProcessResult ProcessResult3 { get; set; }
    public string State { get; set; }
}

public class Processor {

    private readonly object _Lock = new object();
    private readonly DataFetcher _DataFetcher;
    private ProcessState _ProcessState;

    public Processor() {
        _DataFetcher = new DataFetcher();
        _ProcessState = null;
    }

    public void Startup() {
        _DataFetcher.DataChanged += DataFetcher_DataChanged;
    }

    private void DataFetcher_DataChanged(object sender, DataEventArgs args) => StartProcessingThreads(args.Data);

    private void StartProcessingThreads(string data) {

        lock (_Lock) {
            _ProcessState = new ProcessState() { State = "Starting", ProcessResult1 = null, ProcessResult2 = null, ProcessResult3 = null };

            System.Threading.Thread one = new System.Threading.Thread(() => DoProcess1(data)); // manipulate the data toa subset
            one.IsBackground = true;
            one.Start();

            System.Threading.Thread two = new System.Threading.Thread(() => DoProcess2(data)); // manipulate the data toa subset
            two.IsBackground = true;
            two.Start();

            System.Threading.Thread three = new System.Threading.Thread(() => DoProcess3(data)); // manipulate the data toa subset
            three.IsBackground = true;
            three.Start();
        }
    }

    public ProcessState GetState() => _ProcessState;

    private void DoProcess1(string dataSubset) {
        // do work
        ProcessResult result = new ProcessResult(); // this object contains the result
        // on completion
        lock (_Lock) {
            _ProcessState = new ProcessState() { State = (_ProcessState.State ?? string.Empty) + ", 1 done", ProcessResult1 = result, ProcessResult2 = _ProcessState?.ProcessResult2, ProcessResult3 = _ProcessState?.ProcessResult3 };
        }
    }

    private void DoProcess2(string dataSubset) {
        // do work
        ProcessResult result = new ProcessResult(); // this object contains the result
        // on completion
        lock (_Lock) {
            _ProcessState = new ProcessState() { State = (_ProcessState.State ?? string.Empty) + ", 2 done", ProcessResult1 = _ProcessState?.ProcessResult1 , ProcessResult2 = result, ProcessResult3 = _ProcessState?.ProcessResult3 };
        }
    }

    private void DoProcess3(string dataSubset) {
        // do work
        ProcessResult result = new ProcessResult(); // this object contains the result
        // on completion
        lock (_Lock) {
            _ProcessState = new ProcessState() { State = (_ProcessState.State ?? string.Empty) + ", 3 done", ProcessResult1 = _ProcessState?.ProcessResult1, ProcessResult2 = _ProcessState?.ProcessResult2, ProcessResult3 = result };
        }
    }
}

public class DataEventArgs : System.EventArgs {

    // data here is string, but could be anything -- just think of thread safety when accessing from the 3 processors
    private readonly string _Data;

    public DataEventArgs(string data) {
        _Data = data;
    }

    public string Data => _Data;
}

public class DataFetcher {
    //  watch for data changes and fire when data has changed
    public event System.EventHandler<DataEventArgs> DataChanged;
}

}


问:
How do you echo a 4-digit Unicode character in Bash?
I'd like to add the Unicode skull and crossbones to my shell prompt (specifically the 'SKULL AND CROSSBONES' (U+2620)), but I can't figure out the magic incantation to make echo spit it, or any other, 4-digit Unicode character. Two-digit one's are easy. For example, echo -e "\x55", .

In addition to the answers below it should be noted that, obviously, your terminal needs to support Unicode for the output to be what you expect. gnome-terminal does a good job of this, but it isn't necessarily turned on by default.

On macOS's Terminal app Go to Preferences-> Encodings and choose Unicode (UTF-8).

答:
```<code>% echo -e '\u2620'     # \u takes four hexadecimal digits
☠
% echo -e '\U0001f602' # \U takes eight hexadecimal digits

</code>```

This works in Zsh (I've checked version 4.3) and in Bash 4.2 or newer.

OwnerDisplayName: masukomi

LastEditorDisplayName: masukomi

Body:
% echo -e '\u2620'     # \u takes four hexadecimal digits
☠
% echo -e '\U0001f602' # \U takes eight hexadecimal digits

This works in Zsh (I've checked version 4.3) and in Bash 4.2 or newer.

OwnerDisplayName: Juliano

LastEditorDisplayName: Juliano