问:
Design pattern for object containing sets of other objects
I have a complex structure of classes Hero, Castle, Artefact and Position. They are in the following relationships:

A Position can contain several or none Heroes, while a Hero can be only on
one Position.

A Castle belongs to one Hero and can be built on one Position. A Hero
can have 0-1 Castles. A Position can have 0-1 Castes as well.

An Artefact can either be buried in a Position or can be equipped by a
Hero. Thus, Artefact has reference to 0-1 Heroes and 0-1 Positions. A
Hero can have 0-1 Artefacts and a Position can contain 0-1 Artefacts
as well.

Now, to implement those both-way relationships, it is difficult to always change the references in all affected objects (e.g. when a Hero equips an Artefact, I have to change Hero.Artefact, Artefact.Hero, Artefact.Position and Position.Artefact). Therefore, I am using a Game class, that serves as a container for all of them (in other words, the Game class has 4 lists, one for each class).

Then, I add the reference just to the containing Game and with the help of IDs I am able to change the individual references much more elegantly (equipping the Artefact again):

```<code>Artefact.HeroID = newHeroID;
Artefact.PositionID = null;
</code>```

All the accessors in the respective classes then allow me to get the right object(s):

```<code>Hero.Artefact
{
    get
    {
        return this.Game.Artefacts.FirstOrDefault(a => a.HeroID == this.ID);
    }
}

Artefact.Hero
{
    get
    {
        return this.Game.Heroes.FirstOrDefault(h => h.ID == this.HeroID);
    }
}
</code>```

etc.

Is there a name for this design pattern (is it a design pattern)? It is really hard to find the right answer, when you know the implementation, but don't know the name :D (the other way around is quite simple).

答: There is NO ONE design pattern to solve your business problem. Those patterns are just documented implementation approaches that encourage reuse. I'd suggest you give this a read https://dofactory.com/net/design-patterns Probably the most readable and concise tutorials around. It may give you some insights and direction to your problem.</p>

Body:
I have a complex structure of classes Hero, Castle, Artefact and Position. They are in the following relationships:

A Position can contain several or none Heroes, while a Hero can be only on
one Position.

A Castle belongs to one Hero and can be built on one Position. A Hero
can have 0-1 Castles. A Position can have 0-1 Castes as well.

An Artefact can either be buried in a Position or can be equipped by a
Hero. Thus, Artefact has reference to 0-1 Heroes and 0-1 Positions. A
Hero can have 0-1 Artefacts and a Position can contain 0-1 Artefacts
as well.

Now, to implement those both-way relationships, it is difficult to always change the references in all affected objects (e.g. when a Hero equips an Artefact, I have to change Hero.Artefact, Artefact.Hero, Artefact.Position and Position.Artefact). Therefore, I am using a Game class, that serves as a container for all of them (in other words, the Game class has 4 lists, one for each class).

Then, I add the reference just to the containing Game and with the help of IDs I am able to change the individual references much more elegantly (equipping the Artefact again):

Artefact.HeroID = newHeroID;
Artefact.PositionID = null;

All the accessors in the respective classes then allow me to get the right object(s):

Hero.Artefact
{
    get
    {
        return this.Game.Artefacts.FirstOrDefault(a => a.HeroID == this.ID);
    }
}

Artefact.Hero
{
    get
    {
        return this.Game.Heroes.FirstOrDefault(h => h.ID == this.HeroID);
    }
}

etc.

Is there a name for this design pattern (is it a design pattern)? It is really hard to find the right answer, when you know the implementation, but don't know the name :D (the other way around is quite simple).


来源: stackexchange

问:
PowerDNS not sync zones from master to slave
I have installed PowerDNS on 2 VPS servers:

```<code>ns1 - 10.0.0.1

ns2 - 10.0.0.2
</code>```

The Problem is the records/zones are not getting synced from Master to Slave. Here are the configurations:

Master Server:

```<code>allow-axfr-ips=10.0.0.2/32
daemon=yes
disable-axfr=no
include-dir=/etc/powerdns/pdns.d
master=yes
setgid=pdns
setuid=pdns
</code>```

Slave Server:

```<code>daemon=yes
disable-axfr=yes
include-dir=/etc/powerdns/pdns.d
setgid=pdns
setuid=pdns
slave=yes
slave-cycle-interval=60
</code>```

Database on Slave Server

```<code>MariaDB [powerdns]> select * from supermasters;
+-------------+------------------+---------+
| ip          | nameserver       | account |
+-------------+------------------+---------+
| 10.0.0.1    | ns2.example.com  | admin   |
+-------------+------------------+---------+
1 row in set (0.000 sec)
</code>```

Both servers are running on MySQL database backend. Master is serving all records as expected but Slave server is giving this:

```<code>root@vps10:~# dig example.com @localhost

; <<>> DiG 9.16.1-Ubuntu <<>> example.com @localhost
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: REFUSED, id: 22750
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
;; QUESTION SECTION:
;example.com.              IN      A

;; Query time: 4 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Fri Feb 04 22:11:39 UTC 2022
;; MSG SIZE  rcvd: 45
</code>```

I have also checked the Slave server and it does not have any zones from Master. Also tried this on the master server:

```<code>root@vps06:~# pdns_control notify example.com
Added to queue
</code>```

Surfed the internet for any solutions but nothing was available. Can anyone guide me or point out what is wrong with my configuration?

答: You'll need to enable superslave and make sure your primary sends the correct notifications (NS records, ALSO-NOTIFY metadata (https://doc.powerdns.com/authoritative/domainmetadata.html?#also-notify) etc)

ContentLicense: CC BY-SA 4.0

Body:
I have installed PowerDNS on 2 VPS servers:

ns1 - 10.0.0.1

ns2 - 10.0.0.2

The Problem is the records/zones are not getting synced from Master to Slave. Here are the configurations:

Master Server:

allow-axfr-ips=10.0.0.2/32
daemon=yes
disable-axfr=no
include-dir=/etc/powerdns/pdns.d
master=yes
setgid=pdns
setuid=pdns

Slave Server:

daemon=yes
disable-axfr=yes
include-dir=/etc/powerdns/pdns.d
setgid=pdns
setuid=pdns
slave=yes
slave-cycle-interval=60

Database on Slave Server

MariaDB [powerdns]> select * from supermasters;
+-------------+------------------+---------+
| ip          | nameserver       | account |
+-------------+------------------+---------+
| 10.0.0.1    | ns2.example.com  | admin   |
+-------------+------------------+---------+
1 row in set (0.000 sec)

Both servers are running on MySQL database backend. Master is serving all records as expected but Slave server is giving this:

root@vps10:~# dig example.com @localhost

; <<>> DiG 9.16.1-Ubuntu <<>> example.com @localhost
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: REFUSED, id: 22750
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
;; QUESTION SECTION:
;example.com.              IN      A

;; Query time: 4 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Fri Feb 04 22:11:39 UTC 2022
;; MSG SIZE  rcvd: 45

I have also checked the Slave server and it does not have any zones from Master. Also tried this on the master server:

root@vps06:~# pdns_control notify example.com
Added to queue

Surfed the internet for any solutions but nothing was available. Can anyone guide me or point out what is wrong with my configuration?


问:
where does "this" refer to? (javascript30 --Day10 by Wes Bos)
First of all, I'm a Japanese beginner web devlopment learner.
So, My English might be weird and I don't have enough knowledge about programming.
I'm taking a course called javascript30 that focuses on various usage of vanilla JS and

I'm currently  making  a scheme to check the multiple checkboxes by pushing shift button and clicking it(if my explanation doesn't make scence, please copy and paste the source code below)

Accornig to source code, I gotta change the boolean of "inBetween" by setting if sentence.
I can understand what  he does but I can't understand that where does "this"  of "checkbox === this" refer to?
Why writing the code like "checkbox === this" means that it checks if check box is checked?
And I also struggle to catch the meaning of"let lastChecked".
I understand "let lastChecked" is the key to check if it is the last checkbox that was checked by user, but why he set the value of "lastChecked" like "let lastChecked = this"?
Sorry for long sentence and poor English.
I'll be happy if someone explain it.
I'll paste the source code below.

source code

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Hold Shift to Check Multiple Checkboxes</title>

      <input type="checkbox">

This is an inbox layout.

      <input type="checkbox">

Check one item

      <input type="checkbox">

Hold down your Shift key

      <input type="checkbox">

Check a lower item

      <input type="checkbox">

Everything in between should also be set to checked

      <input type="checkbox">

Try do it without any libraries

      <input type="checkbox">

Just regular JavaScript

      <input type="checkbox">

Good Luck!

      <input type="checkbox">

Don't forget to tweet your result!

```

答:
Inside a non arrow event listener, this refers to the event target, i.e. the checkbox that was checked/unchecked.

Since you mention that you are a beginner, I'd prefer that you avoid this as much as possible, & instead use event.target to refer the target element inside an event listener.

this has around major meanings depending on the context, & much more in case you use jQuery/jQueryUI.


问:
Using prefix option for flex in automake/flex/bison stack
I'm converting a build process to use automake/libtool and I've hit a road block for supporting a .l/.y set.

The original build process did these two steps:

```<code>flex -t  -Pq_parser_yy ../../code/q_parser.l > q_parser.h
bison ../../code/q_parser.y -o q_parser.c
</code>```

Flex:  I don't know how to recreate the -P option from the Makefile.am. In my Makefile.am I just list q_parser.l and let automake figure out what to do -- but it outputs q_parser.c not q_parser.h.

The q_parser.h is then included by q_parser.y which outputs q_parser.c. Very confusing for someone who has never used flex/bison!

So on to how it works from automake:

```<code>.l.c:
  $(am__skiplex) $(SHELL) $(YLWRAP) $< $(LEX_OUTPUT_ROOT).c $@ -- $(LEXCOMPILE)

q_parser.c: $(db_dir)/q_parser.l
  $(am__skiplex) \
  $(SHELL) $(YLWRAP) `test -f '$(db_dir)/q_parser.l' || echo '$(srcdir)/'`$(db_dir)/q_parser.l $(LEX_OUTPUT_ROOT).c q_parser.c -- $(LEX) $(LFLAGS) $(AM_LFLAGS)

.y.c:
  $(am__skipyacc) $(SHELL) $(YLWRAP) $< y.tab.c $@ y.tab.h $*.h y.output $*.output -- $(YACCCOMPILE)
</code>```

So automake is mapping .l -> .c and .y -> .c so I run in to the error where gcc is trying to read the .l -> .c output and falling over itself.

I need to override automake to perform .l -> .h and then I should be ok to let it take the wheel. Any tips?

答:
You could just bypass all that neat stuff since it's getting in your way:

```<code>q_parser.h : ../../code/q_parser.l
        $(LEX) $(LFLAGS) $(AM_LFLAGS) -Pq_parser_yy -o$@ $<
q_parser.c : ../../code/q_parser.y q_parser.h
        $(YACC) $(YFLAGS) $< -o $@
</code>```

It doesn't seem that POSIX compatibility is what you're after now anyway.

ContentLicense: CC BY-SA 3.0

Body:
I'm converting a build process to use automake/libtool and I've hit a road block for supporting a .l/.y set.

The original build process did these two steps:

flex -t  -Pq_parser_yy ../../code/q_parser.l > q_parser.h
bison ../../code/q_parser.y -o q_parser.c

Flex:  I don't know how to recreate the -P option from the Makefile.am. In my Makefile.am I just list q_parser.l and let automake figure out what to do -- but it outputs q_parser.c not q_parser.h.

The q_parser.h is then included by q_parser.y which outputs q_parser.c. Very confusing for someone who has never used flex/bison!

So on to how it works from automake:

.l.c:
  $(am__skiplex) $(SHELL) $(YLWRAP) $< $(LEX_OUTPUT_ROOT).c $@ -- $(LEXCOMPILE)

q_parser.c: $(db_dir)/q_parser.l
  $(am__skiplex) \
  $(SHELL) $(YLWRAP) `test -f '$(db_dir)/q_parser.l' || echo '$(srcdir)/'`$(db_dir)/q_parser.l $(LEX_OUTPUT_ROOT).c q_parser.c -- $(LEX) $(LFLAGS) $(AM_LFLAGS)

.y.c:
  $(am__skipyacc) $(SHELL) $(YLWRAP) $< y.tab.c $@ y.tab.h $*.h y.output $*.output -- $(YACCCOMPILE)

So automake is mapping .l -> .c and .y -> .c so I run in to the error where gcc is trying to read the .l -> .c output and falling over itself.

I need to override automake to perform .l -> .h and then I should be ok to let it take the wheel. Any tips?

Body:
You could just bypass all that neat stuff since it's getting in your way:

q_parser.h : ../../code/q_parser.l
        $(LEX) $(LFLAGS) $(AM_LFLAGS) -Pq_parser_yy -o$@ $<
q_parser.c : ../../code/q_parser.y q_parser.h
        $(YACC) $(YFLAGS) $< -o $@

It doesn't seem that POSIX compatibility is what you're after now anyway.


问:
react-router-dom useHistory() not working
The useHistory() hook is not working in my project. I have it in different components but none of them work.
I am using "react-router-dom": "^5.2.0",

```<code>import {useHistory} from 'react-router-dom'

const history = useHistory()

const logout = () => {
   toggleMenu()
   setUser(null)
   dispatch({type: 'LOGOUT'})
   history.push('/')
}
</code>```

And also in action its not working

```<code>export const signin = (formdata, history, setError) => async (dispatch) => {
try {
    const {data} = await API.signIn(formdata)
    if(data.error){
        setError(data.message)
    }else{
        dispatch({type: SIGNIN, data})
        history.push('/dashboard')
    }

   } catch (error) {
    setError(error)
    console.log(error)
  }
}
</code>```

Here is my router.js file

```<code>const Router = () => {
    const user = JSON.parse(localStorage.getItem('profile'))
    return (
       <BrowserRouter>
                <>
                    {user && <Navigation/>}
                    <Switch>
                        <Route path='/page-not-found' component={Auth}/>
                        <Route path='/' exact component={()=>((user && user.result) ? <Redirect to="/dasboard"/> : <Auth/>)} />

                        <Route path='/dashboard' component={() => (user ? <Dashboard/> : <Redirect to='/'/>)} />
                        <Route path='/books-purchase' component={() => (user ? <BooksPage/> : <Redirect to='/' />)} />

                    </Switch>
                </>

        </BrowserRouter>
      )
  }
</code>```

答:
In my point of view, It doesn't need to downgrade react-router-dom, just use "useNavigate" hook instead of "useHistory" hook. For example if you also want to send some data to your dashboard page, you can use it like so:

import { useNavigate } from 'react-router-dom'

const FunctionalComponent = () => {
    const navigate = useNavigate();

    const TestHandler = (someData) => {
        navigate("/dashboard", {state: {someData: someData}});
        //and if you don't want to send any data use like so:
        //navigate("/dashboard");
    }
}```
</div>
</div>
</p>
<p>Finally, if you want to use that sent data for example in your dashboard page, you can do it like so:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import { useLocation } from 'react-router-dom'

export const Dashboard = () => {
    const location = useLocation();

    useEffect(() => {
        if (location.state.someData) {
            // "someData" is available here.
        }
    });</code>```

You can refer to this migration guide: https://reactrouter.com/docs/en/v6/upgrading/v5

Body:
The useHistory() hook is not working in my project. I have it in different components but none of them work.
I am using "react-router-dom": "^5.2.0",

import {useHistory} from 'react-router-dom'

const history = useHistory()

const logout = () => {
   toggleMenu()
   setUser(null)
   dispatch({type: 'LOGOUT'})
   history.push('/')
}

And also in action its not working

export const signin = (formdata, history, setError) => async (dispatch) => {
try {
    const {data} = await API.signIn(formdata)
    if(data.error){
        setError(data.message)
    }else{
        dispatch({type: SIGNIN, data})
        history.push('/dashboard')
    }

   } catch (error) {
    setError(error)
    console.log(error)
  }
}

Here is my router.js file

const Router = () => {
    const user = JSON.parse(localStorage.getItem('profile'))
    return (
       <BrowserRouter>
                <>
                    {user && <Navigation/>}
                    <Switch>
                        <Route path='/page-not-found' component={Auth}/>
                        <Route path='/' exact component={()=>((user && user.result) ? <Redirect to="/dasboard"/> : <Auth/>)} />

                        <Route path='/dashboard' component={() => (user ? <Dashboard/> : <Redirect to='/'/>)} />
                        <Route path='/books-purchase' component={() => (user ? <BooksPage/> : <Redirect to='/' />)} />

                    </Switch>
                </>

        </BrowserRouter>
      )
  }

Body:
In my point of view, It doesn't need to downgrade react-router-dom, just use "useNavigate" hook instead of "useHistory" hook. For example if you also want to send some data to your dashboard page, you can use it like so:

import { useNavigate } from 'react-router-dom'

const FunctionalComponent = () => {
    const navigate = useNavigate();

    const TestHandler = (someData) => {
        navigate("/dashboard", {state: {someData: someData}});
        //and if you don't want to send any data use like so:
        //navigate("/dashboard");
    }
}

Finally, if you want to use that sent data for example in your dashboard page, you can do it like so:

import { useLocation } from 'react-router-dom'

export const Dashboard = () => {
    const location = useLocation();

    useEffect(() => {
        if (location.state.someData) {
            // "someData" is available here.
        }
    });

You can refer to this migration guide: https://reactrouter.com/docs/en/v6/upgrading/v5


问:
Why is the image still not appearing?
The Page

So it appears that some images are being shown but others nada. Why?

Code`
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

```<code>#Image Handleing
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/Detect')
def upload_form():
    return render_template('upload_image.html',title='Update', year=datetime.now().year)

@app.route('/Detect', methods=['POST'])
def upload_image():
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No image selected for uploading')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #print('upload_image filename: ' + filename)
        flash('Image successfully uploaded and displayed below')
        return render_template('upload_image.html', filename=filename,title='Detection', year=datetime.now().year)
    else:
        flash('Allowed image types are -> png, jpg, jpeg, gif')
        return redirect(request.url)

@app.route('/display/<filename>')
def display_image(filename):
    #print('display_image filename: ' + filename)
    return redirect(url_for('upload_image', filename='/uploads/' + filename), code=301)

<!--
<h1 class="jumbotron">Image Classification</h1>
    <br><br>
    <div class="row">
      <div class="col-auto col-md-4 mx-auto">
        <form class="form-horizontal" action="/Detect" method="post" enctype="multipart/form-data">

          <div class="mb-3">
              <label for="" class="form-label"></label>
              <input type="file" name="file" id="" class="form-control" placeholder=".png, .jpeg etc..." aria-describedby="helpId">
              <small id="helpId" class="text-muted">Upload Your Image</small>
          </div>
          <br>
          <input type="submit" value="Upload" class="btn btn-success">

        </form>
      </div>
      <div class = "col-md-4 col-auto mx-auto">
        {% if filename %}
          <img src="{{ url_for('display_image', filename=filename) }}" />
        {% endif %}
      </div>
-->
</code>```

`

In Addition it doesn't even give me a 404 on the terminal it just gives me 200 and maybe 304 as an insult.
here are image of that
Mock Me,
Mocks Me again...

Please tell me I am doin something wrong or is it a bug?

答:
So, Every thing is the same except the following...

```<code>from flask import Flask, send_from_directory

@app.route('/Detect')
def upload_form():
    return render_template('upload_image.html',title='Update', year=datetime.now().year)

@app.route('/Detect', methods=['POST'])
def upload_image():
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No image selected for uploading')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #print('upload_image filename: ' + filename)
        flash('Image successfully uploaded and displayed below')
        return render_template('upload_image.html', filename=filename)
    else:
        flash('Allowed image types are -> png, jpg, jpeg, gif')
        return redirect(request.url)

@app.route('/display/<filename>')
def display_image(filename):
    #print('display_image filename: ' + filename)
    return send_from_directory(app.config["UPLOAD_FOLDER"], filename)
</code>```

The HTML Tag Stuff

```<code>{% if filename %}
    <div>
        <img src="{{ url_for('display_image', filename=filename) }}" />
    </div>
{% endif %}
</code>```

to be completely honest I sill have no idea why this is working and the previous one wasn't even though I followed the guide to an extent Guide...

Title: Why is the image still not appearing?

Body:
The Page

So it appears that some images are being shown but others nada. Why?

Code`
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

#Image Handleing
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/Detect')
def upload_form():
    return render_template('upload_image.html',title='Update', year=datetime.now().year)

@app.route('/Detect', methods=['POST'])
def upload_image():
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No image selected for uploading')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #print('upload_image filename: ' + filename)
        flash('Image successfully uploaded and displayed below')
        return render_template('upload_image.html', filename=filename,title='Detection', year=datetime.now().year)
    else:
        flash('Allowed image types are -> png, jpg, jpeg, gif')
        return redirect(request.url)

@app.route('/display/<filename>')
def display_image(filename):
    #print('display_image filename: ' + filename)
    return redirect(url_for('upload_image', filename='/uploads/' + filename), code=301)

`

In Addition it doesn't even give me a 404 on the terminal it just gives me 200 and maybe 304 as an insult.
here are image of that
Mock Me,
Mocks Me again...

Please tell me I am doin something wrong or is it a bug?

Body:
So, Every thing is the same except the following...

from flask import Flask, send_from_directory

@app.route('/Detect')
def upload_form():
    return render_template('upload_image.html',title='Update', year=datetime.now().year)

@app.route('/Detect', methods=['POST'])
def upload_image():
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No image selected for uploading')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #print('upload_image filename: ' + filename)
        flash('Image successfully uploaded and displayed below')
        return render_template('upload_image.html', filename=filename)
    else:
        flash('Allowed image types are -> png, jpg, jpeg, gif')
        return redirect(request.url)

@app.route('/display/<filename>')
def display_image(filename):
    #print('display_image filename: ' + filename)
    return send_from_directory(app.config["UPLOAD_FOLDER"], filename)

The HTML Tag Stuff

{% if filename %}
    <div>
        <img src="{{ url_for('display_image', filename=filename) }}" />
    </div>
{% endif %}

to be completely honest I sill have no idea why this is working and the previous one wasn't even though I followed the guide to an extent Guide...


问:
Subsetting a dataframe in R by retaining first occurrences of unique elements from all columns
df is a test dataframe which has 5 rows and 6 columns and it is a subset of a much larger dataframe (dimensions: 1000000 X 30).

```<code>df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5"),
 category1 = c("a", "", "b", "a", ""),
 category2 = c("c", "", "", "d", "c"),
 category3 = c("", "", "e", "f", "f"),
 category4 = c("", "", "", "", ""),
 category5 = c("i", "", "i", "j", ""))
</code>```

df looks like this

For each column from category1 to category5 I need to retain only the first occurrences of all the unique elements. e.g. For category1, the unique elements are a and b and their first occurrences are in rows 1 and 3 respectively. So rows 1 and 3 should be retained, and so on. The output should look something like this

答:
I was challenged to find a tidyverse solution and ended up with this, not to recommend as solution but as a learning effect:

The basic idea was to bring the data in long format remove the duplicates and bring back to wide format, but this "simple" idea turned out to be quite complicated as you can see here:

```<code>library(tidyverse)
df %>%
  pivot_longer(
    everything()
  ) %>%
  mutate(value = na_if(value, "")) %>%
  unique() %>%
  group_by(id = cumsum(name=="Hits")) %>%
  mutate(row = row_number()) %>%
  pivot_wider() %>%
  fill(everything(), .direction = "updown") %>%
  filter(if_any(category1:category5, ~ !is.na(.))) %>%
  slice(1) %>%
  ungroup() %>%
  select(-c(id, row)) %>%
  mutate(across(everything(), ~replace_na(.,"")))
</code>```
```<code>  Hits  category1 category2 category3 category4 category5
  <chr> <chr>     <chr>     <chr>     <chr>     <chr>
1 Hit1  "a"       "c"       ""        ""        "i"
2 Hit3  "b"       ""        "e"       ""        ""
3 Hit4  ""        "d"       "f"       ""        "j"
</code>```

Body:
df is a test dataframe which has 5 rows and 6 columns and it is a subset of a much larger dataframe (dimensions: 1000000 X 30).

df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5"),
 category1 = c("a", "", "b", "a", ""),
 category2 = c("c", "", "", "d", "c"),
 category3 = c("", "", "e", "f", "f"),
 category4 = c("", "", "", "", ""),
 category5 = c("i", "", "i", "j", ""))

df looks like this

For each column from category1 to category5 I need to retain only the first occurrences of all the unique elements. e.g. For category1, the unique elements are a and b and their first occurrences are in rows 1 and 3 respectively. So rows 1 and 3 should be retained, and so on. The output should look something like this

Body:
I was challenged to find a tidyverse solution and ended up with this, not to recommend as solution but as a learning effect:

The basic idea was to bring the data in long format remove the duplicates and bring back to wide format, but this "simple" idea turned out to be quite complicated as you can see here:

library(tidyverse)
df %>%
  pivot_longer(
    everything()
  ) %>%
  mutate(value = na_if(value, "")) %>%
  unique() %>%
  group_by(id = cumsum(name=="Hits")) %>%
  mutate(row = row_number()) %>%
  pivot_wider() %>%
  fill(everything(), .direction = "updown") %>%
  filter(if_any(category1:category5, ~ !is.na(.))) %>%
  slice(1) %>%
  ungroup() %>%
  select(-c(id, row)) %>%
  mutate(across(everything(), ~replace_na(.,"")))

  Hits  category1 category2 category3 category4 category5
  <chr> <chr>     <chr>     <chr>     <chr>     <chr>
1 Hit1  "a"       "c"       ""        ""        "i"
2 Hit3  "b"       ""        "e"       ""        ""
3 Hit4  ""        "d"       "f"       ""        "j"


问:
How can I embed Youtube homepage to my website iframe or embed or object element?
In HTML ,
if I do this ->

or,
 <embed src="https://www.youtube.com/"></embed>
or,
 <object data="https://www.youtube.com/"></embed>

it shows me an error { Refused to display 'https://www.youtube.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'. }
and says youtube.com refused to connect.
can I get rid off?
Is there any way to show youtube homepage to my website  iframe  or  embed  or  object  element?

答:
Good try, normally you can indeed add a site with iframe in your own site like:

```<code><iframe src="https://yoursite.com/" " width="100% " height="600 "></iframe>
</code>```

Websites like youtube can use x-frame options or a content security policy to check if other website may embed them on their own page.

This is an important security feature to prevent clickjacking, which is an attack that allows malicious sites to trick users into clicking links on a site. source

Body:
Good try, normally you can indeed add a site with iframe in your own site like:

<iframe src="https://yoursite.com/" " width="100% " height="600 "></iframe>

Websites like youtube can use x-frame options or a content security policy to check if other website may embed them on their own page.

This is an important security feature to prevent clickjacking, which is an attack that allows malicious sites to trick users into clicking links on a site. source


问:
Do I need to create stream for generating a list in range?
I am new in Java Stream API and trying to solve some exercises. In a problem, I need to return the odd numbers as a List<Integer> with the given range. First, I used a loop as shown below:

```<code>public static List<Integer> oddNumbers(int l, int r) {
    List<Integer> list = new ArrayList<>();
    for (int i = l; i <= r; i++) {
        if (i % 2 != 0) {
            list.add(i);
        }
    }
    return list;
}
</code>```

Then I thought that maybe it is better using stream in order to provide a cleaner solution. But it is not working when I tried with filter and anyMatch.

```<code>public static List<Integer> oddNumbers(int l, int r) {

    return IntStream.range(l,r)
        .filter(x -> x % 2 != 0)
        // .anyMatch(x -> x % 2 == 0)
        .collect(Collectors.toList());
}
</code>```

So:
1. How can I make it work using stream?

2. Should I prefer the second approach as it seems to be cleaner?

答:
Like this:

```<code>public static List<Integer> oddNumbers(final int l, final int r) {
  return IntStream.range(l, r + 1).filter(i -> i % 2 != 0).boxed().toList();
}
</code>```

It is a matter of taste, but one could argue that the intent is more clear using the stream API.

(toList() is new from Java 16, otherwise one have to use collect(Collectors.toList())

Body:
I am new in Java Stream API and trying to solve some exercises. In a problem, I need to return the odd numbers as a List<Integer> with the given range. First, I used a loop as shown below:

public static List<Integer> oddNumbers(int l, int r) {
    List<Integer> list = new ArrayList<>();
    for (int i = l; i <= r; i++) {
        if (i % 2 != 0) {
            list.add(i);
        }
    }
    return list;
}

Then I thought that maybe it is better using stream in order to provide a cleaner solution. But it is not working when I tried with filter and anyMatch.

public static List<Integer> oddNumbers(int l, int r) {

    return IntStream.range(l,r)
        .filter(x -> x % 2 != 0)
        // .anyMatch(x -> x % 2 == 0)
        .collect(Collectors.toList());
}

So:
1. How can I make it work using stream?

2. Should I prefer the second approach as it seems to be cleaner?

Body:
Like this:

public static List<Integer> oddNumbers(final int l, final int r) {
  return IntStream.range(l, r + 1).filter(i -> i % 2 != 0).boxed().toList();
}

It is a matter of taste, but one could argue that the intent is more clear using the stream API.

(toList() is new from Java 16, otherwise one have to use collect(Collectors.toList())


问:
Add my own class file in ASP.NET MVC, and it couldn't be referenced?
I am currently stuck trying to add my own class file into ASP.NET MVC project, so it could
be referenced by my controller. But Visual studio 2010 always complain about "The type or name 'Products' could not be found (are your missing a using directive or assembly reference?)

I am not sure where to put my class file and tried add the class to Models or Controllers directory, and it wouldn't work either. My the class is under the right namespace, and I did reference the Models namespace in my Controller. It could be something obvious, but I couldn't get it working:(

答: Make sure that the "Build Action" property of the file is set to "Compile" in Visual Studio.  Perhaps when you initially added the file, you added it to a location or added it as a file type that did not automatically set the build action properly.</p>


问:
How to get particular part of string from an array of strings using javascript?
Hi below is array of strings

```<code>const arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
    "some-domain/4/item/5/subitem/1/",
]
</code>```

i have to filter those strings that start with  string "item/3/" or ends with string "item/3/"

so from above array expected filtered array is like below,

```<code>const filtered_arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
]
</code>```

from the filtered array i want to get the number after "/item/". so from above filtered array the expected output is

```<code>const arr_ids = ["1", "2", "3"]
</code>```

what i have tried,

i have used below to match those strings that start or end with /item/3/

```<code>const filtered_arr = arr.map(str) => {
    return str.match(/item\/[0-9](\/)?$/g);
}
</code>```

this gives the filtered_arr

```<code>const filtered_arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
]
</code>```

but how do i map through each array item and get the number after string "/item/".

could someone help me with this. thanks.

答:
Use filter to filter paths either starting or ending in item/\d+/.  Then use map to extract the item number from each matching path.

const arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
    "some-domain/4/item/5/subitem/1",
];
var output = arr.filter(x => x.match(/^item\/\d+|\bitem\/\d+\/$/))
                .map(x => x.match(/(?<=^item\/)\d+|(?<=\bitem\/)\d+(?=\/$)/)[0]);
console.log(output);```

Body:
Hi below is array of strings

const arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
    "some-domain/4/item/5/subitem/1/",
]

i have to filter those strings that start with  string "item/3/" or ends with string "item/3/"

so from above array expected filtered array is like below,

const filtered_arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
]

from the filtered array i want to get the number after "/item/". so from above filtered array the expected output is

const arr_ids = ["1", "2", "3"]

what i have tried,

i have used below to match those strings that start or end with /item/3/

const filtered_arr = arr.map(str) => {
    return str.match(/item\/[0-9](\/)?$/g);
}

this gives the filtered_arr

const filtered_arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
]

but how do i map through each array item and get the number after string "/item/".

could someone help me with this. thanks.


问:
Azure Blob Storage Java SDK 12 extract file name from blob name
let's say I have blob structure like this:

dir0

├── dir1

│   ├── file11

│   └── file12

├── dir2

└── dir3

After listing the dir1 that contains two files file11, file12 with listBlobsByHierarchy("dir0/dir1/") method I'm getting two blobs with blobName property set to dir0/dir1/file11 and dir0/dir1/file12, so <virtual_path>/<file_name>. That's OK, but in some point I need to get the <file_name> part.

My question is: Does Azure Storage SDK 12 for Java provides a mechanism for obtaining <file_name> part from blob name? I could do it myself but it's hard to believe that SDK doesn't provide this functionality... Maybe you guys know different elegant way to do so? How do you usually handle such things?

It's a bit weird to me that SDK seems not to support building prefixes or getting file names from blob names :P I expected sth like fileName field in BlobItem class or buildPrefix(List<String> segments) method for joining path segments with '/'.

答:
You just do:

```<code>blobName.replaceFirst("^/dir0/dir1/", "")
</code>```

Directories in blob storage are not real, the structure is flat and there are only some helper methods that take prefixes into account. See this explanation for more details.

You can always enable hierarchical namespace (aka. Datalake Storage) in your blob account. This makes blob containers more like traditional filesystem with real directories. You are using a different SDK then (->docs). And its DirectoryEntry object differentiates between name (without path) and fullName (with path).

Body:
You just do:

blobName.replaceFirst("^/dir0/dir1/", "")

Directories in blob storage are not real, the structure is flat and there are only some helper methods that take prefixes into account. See this explanation for more details.

You can always enable hierarchical namespace (aka. Datalake Storage) in your blob account. This makes blob containers more like traditional filesystem with real directories. You are using a different SDK then (->docs). And its DirectoryEntry object differentiates between name (without path) and fullName (with path).


问:
JS: No contents in array from parent class
I am using two classes in javascript.

class Challenge and class Modules, that extends Challenge.

in Challenge i have this constructor:

```<code>constructor() {
    this.handles = [];
}
</code>```

and this method:

```<code>bla() {

    let elmnts = document.querySelectorAll("p"); // 5x

        for(let i=0; i < elmnts.length; i++) {

            let elmnt = elmnts[i];
            this.handles[elmnt['id']] = elmnt; // saves the handles to each element in separate array for later use

        }

}
</code>```

in the child Class i am trying to use this "this.handles" array, but it is always empty.

It is not "undefined" but it is an empty array as i defined it in the constructor. its like the entries have never been set... but they are (as console.log() shows, when i insert it directly after the for()-loop)

```<code>console.log(this.handles); // --> []
</code>```

Why does this happen?

答:
this.handles is an array. So when you are doing this.handles[elmnt['id']], elmnt['id'] returns a string, whereas an array expects (positive) integer for index. So the elements are not set in the array.

Maybe you meant this.handles to be an object?

class Ex1 {
  constructor() {
    this.handles = {};
  }

  bla() {

    let elmnts = document.querySelectorAll("p"); // 5x

    for (let i = 0; i < elmnts.length; i++) {

      let elmnt = elmnts[i];
      this.handles[elmnt['id']] = elmnt; // saves the handles to each element in separate array for later use
    }

  }
}

class Ex2 extends Ex1 {
  constructor(){
    super();
  }

  m1(){
    console.log(this.handles);
  }
}

let p1 = new Ex2();
p1.m1();
p1.bla();
p1.m1();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="one">1</p>
<p id="two">2</p>
<p id="three">3</p>
<p id="four">4</p>
<p id="five">5</p></code>```

Body:
I am using two classes in javascript.

class Challenge and class Modules, that extends Challenge.

in Challenge i have this constructor:

constructor() {
    this.handles = [];
}

and this method:

bla() {

    let elmnts = document.querySelectorAll("p"); // 5x

        for(let i=0; i < elmnts.length; i++) {

            let elmnt = elmnts[i];
            this.handles[elmnt['id']] = elmnt; // saves the handles to each element in separate array for later use

        }

}

in the child Class i am trying to use this "this.handles" array, but it is always empty.

It is not "undefined" but it is an empty array as i defined it in the constructor. its like the entries have never been set... but they are (as console.log() shows, when i insert it directly after the for()-loop)

console.log(this.handles); // --> []

Why does this happen?

Body:
this.handles is an array. So when you are doing this.handles[elmnt['id']], elmnt['id'] returns a string, whereas an array expects (positive) integer for index. So the elements are not set in the array.

Maybe you meant this.handles to be an object?

class Ex1 {
  constructor() {
    this.handles = {};
  }

  bla() {

    let elmnts = document.querySelectorAll("p"); // 5x

    for (let i = 0; i < elmnts.length; i++) {

      let elmnt = elmnts[i];
      this.handles[elmnt['id']] = elmnt; // saves the handles to each element in separate array for later use
    }

  }
}

class Ex2 extends Ex1 {
  constructor(){
    super();
  }

  m1(){
    console.log(this.handles);
  }
}

let p1 = new Ex2();
p1.m1();
p1.bla();
p1.m1();

<p id="one">1</p>
<p id="two">2</p>
<p id="three">3</p>
<p id="four">4</p>
<p id="five">5</p>


问:
When is it the right time to use C# class library (.dll)?
I'm a programmer who has never really used .dll files.
Of cause, when I need 3rd party software, such as a graphics library, a library to help me create graphs etc. I do add the references/ddl files to my program and use them in my code.

Also, it seems like you can use .dll for a lot of different things, so I'd like the topic to concentrate on C#.

Right now I am working on a sanitizing library(?) (I think that is the correct term), which will be full of relevant methods that can sanitize variables in all sorts of different ways.

What I want to know is:

would there be any advantage to:

1) Write the methods to class library -> compile/build it -> add the library as a reference to the program - which would need to sanitize some variables ?

Or would it be exactly the same if I where to:

2) Create a new SanitizeClass in the program -> add all the sanitize methods -> call the methods from the SanitizeClass in the different classes in the program that needs to sanitize variables

In general, I also want to know when it is an advantage to use compiled class libraries.
I'm thinking of speed, security, all of it.

Could anyone enlightenment me? :)

答:
if you would be reusing this code in different apps - ie: this would be some sort of shared library - then compile it as a dll

reg performance, please note any code which is executed against an external assemble would  always be a bit slower than executing code within the same assembly

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Raj


问:
Why is memset() incorrectly initializing int?
Why is the output of the following program 84215045?

```<code>int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}
</code>```

答:
memset is about setting bytes, not values. One of the many ways to set array values in C++ is std::fill_n:

```<code>std::fill_n(grid, 100, 5);
</code>```

Body:
Why is the output of the following program 84215045?

int grid[110];
int main()
{
    memset(grid, 5, 100 * sizeof(int));
    printf("%d", grid[0]);
    return 0;
}

Body:
memset is about setting bytes, not values. One of the many ways to set array values in C++ is std::fill_n:

std::fill_n(grid, 100, 5);


问:
How can we remove the "Copy Link Requires Adobe Flash Player" link from the OBIEE12c analytical report?
We configure "instanceconfig.xml" file to remove the Adobe flash player dependency to show the charts and graphs in the obiee12c analytical reports and dashboards. Now, OBIEE12c can display charts without the Adobe Flash Player, However, reports still shows a link named "Copy Link Requires Adobe Flash Player"</p>

答:
a) "12c" doesn't mean anything as there were 5 major releases with over 50 bundle patches

b) This is fixed since 2016 and clearly explained in support document 2111430.1:
https://support.oracle.com/epmos/faces/DocContentDisplay?id=2111430.1


问:
How to detect the closest value below and above a given reference variable in a data frame in R?
Consider the following random MWE.

For every row, I am trying to determine which variable has the closest value below the constant reference_day and which variable has the closest value above the constant reference_day.

```<code>df1 <-
  structure(
    list(id = 1:5,
      gender = c("female", "male", "male", "male", "male"),
      reference_day = structure(c(18052, NA, 18052, 18052, 18052), class = "Date"),
      var1 = structure(c(16505, 17144, 18139, NA, 16639), class = "Date"),
      var2 = structure(c(NA, 18042, 16544, 16697, NA), class = "Date"),
      var3 = structure(c(17845, 18070, 17152, 16571, NA), class = "Date")),
  row.names = c(NA, -5L), class = "data.frame")

df1

  id gender reference_day       var1       var2       var3
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>
</code>```

The result I'm after is this:

```<code>  id gender reference_day       var1       var2       var3 closest_to_left closest_to_right
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10            var3             <NA>
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23            <NA>             <NA>
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17            var3             var1
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16            var2             <NA>
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>            var1             <NA>
</code>```

After much trial and error, I was actually able to find a solution to this with the case_when function of dplyr, but it took an insane amount of boilerplate code, which lead me to think that there just has to be a more clever solution.

I personally prefer to work with dplyr, but any help is greatly appreciated.

答:
A custom function to do this -</p>
```<code>library(dplyr)

cols <- df1 %>% select(starts_with('var')) %>% names

closest_to_right <- function(x, y) {
  tmp <- y - x
  if(any(tmp > 0, na.rm = TRUE))
     cols[tmp %in% min(tmp[tmp > 0], na.rm = TRUE)] else NA
}

closest_to_left <- function(x, y) {
  tmp <- y - x
  if(any(tmp < 0, na.rm = TRUE))
     cols[tmp %in% max(tmp[tmp < 0], na.rm = TRUE)] else NA
}

df1 %>%
  rowwise() %>%
  mutate(closest_to_left = closest_to_left(reference_day, c_across(starts_with('var'))),
         closest_to_right = closest_to_right(reference_day, c_across(starts_with('var')))) %>%
  ungroup

#     id gender reference_day var1       var2       var3       closest_to_left closest_to_right
#  <int> <chr>  <date>        <date>     <date>     <date>     <chr>           <chr>
#1     1 female 2019-06-05    2015-03-11 NA         2018-11-10 var3            NA
#2     2 male   NA            2016-12-09 2019-05-26 2019-06-23 NA              NA
#3     3 male   2019-06-05    2019-08-31 2015-04-19 2016-12-17 var3            var1
#4     4 male   2019-06-05    NA         2015-09-19 2015-05-16 var2            NA
#5     5 male   2019-06-05    2015-07-23 NA         NA         var1            NA
</code>```

Body:
Consider the following random MWE.

For every row, I am trying to determine which variable has the closest value below the constant reference_day and which variable has the closest value above the constant reference_day.

df1 <-
  structure(
    list(id = 1:5,
      gender = c("female", "male", "male", "male", "male"),
      reference_day = structure(c(18052, NA, 18052, 18052, 18052), class = "Date"),
      var1 = structure(c(16505, 17144, 18139, NA, 16639), class = "Date"),
      var2 = structure(c(NA, 18042, 16544, 16697, NA), class = "Date"),
      var3 = structure(c(17845, 18070, 17152, 16571, NA), class = "Date")),
  row.names = c(NA, -5L), class = "data.frame")

df1

  id gender reference_day       var1       var2       var3
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>

The result I'm after is this:

  id gender reference_day       var1       var2       var3 closest_to_left closest_to_right
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10            var3             <NA>
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23            <NA>             <NA>
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17            var3             var1
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16            var2             <NA>
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>            var1             <NA>

After much trial and error, I was actually able to find a solution to this with the case_when function of dplyr, but it took an insane amount of boilerplate code, which lead me to think that there just has to be a more clever solution.

I personally prefer to work with dplyr, but any help is greatly appreciated.

Body:
A custom function to do this -

library(dplyr)

cols <- df1 %>% select(starts_with('var')) %>% names

closest_to_right <- function(x, y) {
  tmp <- y - x
  if(any(tmp > 0, na.rm = TRUE))
     cols[tmp %in% min(tmp[tmp > 0], na.rm = TRUE)] else NA
}

closest_to_left <- function(x, y) {
  tmp <- y - x
  if(any(tmp < 0, na.rm = TRUE))
     cols[tmp %in% max(tmp[tmp < 0], na.rm = TRUE)] else NA
}

df1 %>%
  rowwise() %>%
  mutate(closest_to_left = closest_to_left(reference_day, c_across(starts_with('var'))),
         closest_to_right = closest_to_right(reference_day, c_across(starts_with('var')))) %>%
  ungroup

#     id gender reference_day var1       var2       var3       closest_to_left closest_to_right
#  <int> <chr>  <date>        <date>     <date>     <date>     <chr>           <chr>
#1     1 female 2019-06-05    2015-03-11 NA         2018-11-10 var3            NA
#2     2 male   NA            2016-12-09 2019-05-26 2019-06-23 NA              NA
#3     3 male   2019-06-05    2019-08-31 2015-04-19 2016-12-17 var3            var1
#4     4 male   2019-06-05    NA         2015-09-19 2015-05-16 var2            NA
#5     5 male   2019-06-05    2015-07-23 NA         NA         var1            NA


问:
trublle with component in React
I had a problem exporting NavBottom and I don't understand why the problem is that when I insert it into a component it knocks out an error, but the import and export are correct. Maybe there are nuances when using TypeScript, I recently started using it. I will be glad for any answer to my problem. Maybe I must "open" do object ?</p>
```<code>
TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & boolean'.
  Type '{}' is not assignable to type 'true'.
    46 |         <div />
    47 |       </StyledBurger>
  > 48 |       <NavBottom  />
       |        ^^^^^^^^^
    49 |     </>
    50 |   )
    51 | }
</code>```
```<code>import React, { useState } from 'react';
const styled = require('styled-components');
import {NavBottom} from './NavBottom';

const BurgerMenu = () => {

  const [open, setOpen] = useState(false)

  const StyledBurger = styled.div`
  width: 2rem;
  height: 16px;
  margin-top:16px;
  margin-left: 19px;
  position: fixed;
  z-index: 20;
  display: none;
    display: flex;
    justify-content: space-around;
    flex-flow: column nowrap;
  div {
    width: 18px;
    height: 2px;
    background-color: #fff;
    border-radius: 10px;
    transform-origin: 1px;
    transition: all 0.3s linear;
    &:nth-child(1) {
      transform: ${open ? 'rotate(45deg)' : 'rotate(0)'};
    }
    &:nth-child(2) {
      transform: ${open ? 'translateX(100%)' : 'translateX(0)'};
      opacity: ${open ? 0 : 1};
    }
    &:nth-child(3) {
      transform: ${open ? 'rotate(-45deg)' : 'rotate(0)'};
    }
  }
`;

interface Props {
  open: boolean;
}

  return (
    <>
      <StyledBurger open={open} onClick={() => setOpen(!open)}>
        <div />
        <div />
        <div />
      </StyledBurger>
      <NavBottom open={open} />
    </>
  )
}

export {BurgerMenu};
</code>```

答: just try to define your function like export const NavBottom = () =>, then import it without using {} - import NavBottom from.</p>

Title: trublle with component in React

Body:
I had a problem exporting NavBottom and I don't understand why the problem is that when I insert it into a component it knocks out an error, but the import and export are correct. Maybe there are nuances when using TypeScript, I recently started using it. I will be glad for any answer to my problem. Maybe I must "open" do object ?

TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & boolean'.
  Type '{}' is not assignable to type 'true'.
    46 |

    47 |       </StyledBurger>
  > 48 |       <NavBottom  />
       |        ^^^^^^^^^
    49 |     </>
    50 |   )
    51 | }

import React, { useState } from 'react';
const styled = require('styled-components');
import {NavBottom} from './NavBottom';

const BurgerMenu = () => {

  const [open, setOpen] = useState(false)

  const StyledBurger = styled.div`
  width: 2rem;
  height: 16px;
  margin-top:16px;
  margin-left: 19px;
  position: fixed;
  z-index: 20;
  display: none;
    display: flex;
    justify-content: space-around;
    flex-flow: column nowrap;
  div {
    width: 18px;
    height: 2px;
    background-color: #fff;
    border-radius: 10px;
    transform-origin: 1px;
    transition: all 0.3s linear;
    &:nth-child(1) {
      transform: ${open ? 'rotate(45deg)' : 'rotate(0)'};
    }
    &:nth-child(2) {
      transform: ${open ? 'translateX(100%)' : 'translateX(0)'};
      opacity: ${open ? 0 : 1};
    }
    &:nth-child(3) {
      transform: ${open ? 'rotate(-45deg)' : 'rotate(0)'};
    }
  }
`;

interface Props {
  open: boolean;
}

  return (
    <>

      <NavBottom open={open} />
    </>
  )
}

export {BurgerMenu};


问:
Laravel hasFile() return true even if file is not uploaded
If I uploaded the file works all perfectly, but when I avoid to upload it ( is optional ) I get this error:

```<code>fread(): read of 8192 bytes failed with errno=21 Is a directory
</code>```

In my controller I tried to check if file exists with the function hasFile but it seems doesn't work:

```<code> if($request->hasFile('my_file')) {
          $fileName = time().'.'.$request->my_file->extension();
          $request->my_file->move(public_path('uploads'), $fileName);
          $content->my_file= $fileName;
        }
</code>```

Also I tried to print the content of $request->my_file to debug with dd($request->my_file). It's null.

The stranger thing is that also if $request->my_file is null this check getting the error:

```<code>if($request->file('my_file') != null)
</code>```

答:
I found and solved the problem.
HasFile works correctly but the error was in a next step of saving.</p>

Body:
If I uploaded the file works all perfectly, but when I avoid to upload it ( is optional ) I get this error:

fread(): read of 8192 bytes failed with errno=21 Is a directory

In my controller I tried to check if file exists with the function hasFile but it seems doesn't work:

 if($request->hasFile('my_file')) {
          $fileName = time().'.'.$request->my_file->extension();
          $request->my_file->move(public_path('uploads'), $fileName);
          $content->my_file= $fileName;
        }

Also I tried to print the content of $request->my_file to debug with dd($request->my_file). It's null.

The stranger thing is that also if $request->my_file is null this check getting the error:

if($request->file('my_file') != null)


问:
webpack-cli : Error: spawn Unknown system error -86 / Symfony
I have just acquired a new mac with M1 chip and I wonder if the error is related to this, because on my old one I have no problem.

```<code>[webpack-cli] Error: spawn Unknown system error -86
    at ChildProcess.spawn (node:internal/child_process:412:11)
    at spawn (node:child_process:698:9)
    at Object.execFile (node:child_process:325:17)
    at Object.module.exports.fileCommandJson (/Users/mlc/Sites/ImapImport/node_modules/node-notifier/lib/utils.js:88:13)
    at NotificationCenter.notifyRaw (/Users/mlc/Sites/ImapImport/node_modules/node-notifier/notifiers/notificationcenter.js:81:11)
    at WebpackNotifierPlugin.compilationDone (/Users/mlc/Sites/ImapImport/node_modules/webpack-notifier/index.js:129:14)
    at Hook.eval [as callAsync] (eval at create (/Users/mlc/Sites/ImapImport/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:18:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/mlc/Sites/ImapImport/node_modules/tapable/lib/Hook.js:18:14)
    at /Users/mlc/Sites/ImapImport/node_modules/webpack/lib/Compiler.js:498:23
    at Compiler.emitRecords (/Users/mlc/Sites/ImapImport/node_modules/webpack/lib/Compiler.js:906:5) {
  errno: -86,
  code: 'Unknown system error -86',
  syscall: 'spawn'
}
</code>```

It occurs when the command is launched:

```<code>npm run dev
</code>```

or

```<code>yarn encore dev
</code>```

I have already tried deleting the node_modules file as well as the package-lock.json, and clearing the npm cache then re-running npm install but nothing worked.

Suggestions ?

答:
Problem solved, thanks to @andreasm for pointing me in the right direction.
I explain myself after checking on xcode was installed with the command :

```<code>xcode-select -p
</code>```

it was, so I did not carry more attention than that, today just out of curiosity by executing :

```<code>xcode-select --install
</code>```

the error has disappeared, morality: Do not trust the first command.

Body:
I have just acquired a new mac with M1 chip and I wonder if the error is related to this, because on my old one I have no problem.

[webpack-cli] Error: spawn Unknown system error -86
    at ChildProcess.spawn (node:internal/child_process:412:11)
    at spawn (node:child_process:698:9)
    at Object.execFile (node:child_process:325:17)
    at Object.module.exports.fileCommandJson (/Users/mlc/Sites/ImapImport/node_modules/node-notifier/lib/utils.js:88:13)
    at NotificationCenter.notifyRaw (/Users/mlc/Sites/ImapImport/node_modules/node-notifier/notifiers/notificationcenter.js:81:11)
    at WebpackNotifierPlugin.compilationDone (/Users/mlc/Sites/ImapImport/node_modules/webpack-notifier/index.js:129:14)
    at Hook.eval [as callAsync] (eval at create (/Users/mlc/Sites/ImapImport/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:18:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/mlc/Sites/ImapImport/node_modules/tapable/lib/Hook.js:18:14)
    at /Users/mlc/Sites/ImapImport/node_modules/webpack/lib/Compiler.js:498:23
    at Compiler.emitRecords (/Users/mlc/Sites/ImapImport/node_modules/webpack/lib/Compiler.js:906:5) {
  errno: -86,
  code: 'Unknown system error -86',
  syscall: 'spawn'
}

It occurs when the command is launched:

npm run dev

or

yarn encore dev

I have already tried deleting the node_modules file as well as the package-lock.json, and clearing the npm cache then re-running npm install but nothing worked.

Suggestions ?

Body:
Problem solved, thanks to @andreasm for pointing me in the right direction.
I explain myself after checking on xcode was installed with the command :

xcode-select -p

it was, so I did not carry more attention than that, today just out of curiosity by executing :

xcode-select --install

the error has disappeared, morality: Do not trust the first command.


问:
Low pass shape curve with low cycle count

Hi, I want to achieve the above curve in software without using a dsp function. I was hoping to use a fast and low cycle arm function like multiply-accumulate.

Is there any fast way of doing this in C on an embedded arm processor?

答:
The curve shown is that of the simplest possible first-order filter charactarised by a 3dB cut-off frequency fc> and a 6dB/Octave or 20dB/Decade roll-off. As an analogue filter it could be implemented as a simple passive RC filter thus:

In the digital domain such a filter would be implemented by:

yn = a0 xn + b1 yn-1

Where y are input samples and x output samples.  Or in code:

```<code>void lowPassFilter( const tSample* x, tSample* y, size_t sample_count )
{
    static tSample y_1 = 0 ;

    for( int i = 0; i < n; ++i)
    {
        y[i] = a0 * x[i] + b1 * y_1 ;
        y_1 = y[i];
    }
}
</code>```

The filter is characterised by the coefficients:

a0 = 1 - x

b1 = x

where x is a value between 0 and 1 (I'll address the eradication of the implied floating point operations in due course):

x = e-2πfc

Where fc is the desired -3dB cut-off frequency expressed as a fraction of the sample rate.  So for a sample rate 32Ksps and a cut-off frequency of 1KHz, fc = 1000/32000 = 0.03125, so:

b1 = x = e-2πfc = 0.821725

a0 = 1 - x = 0.178275

Now naïvely plugging those constants into the lowPassFilter() will result in generation of floating point code and on an MCU without an FPU that might be prohibitive and even with an FPU might be be sub-optimal.  So in this case we might use a fixed-point representation.  Since all the real values are less than one, and the machine is 32bit, a UQ0.16 representation would be appropriate, as intermediate multiplication results will not then overflow a 32 bit machine word.  This does require the sample width to be 16bit or less (or scaled accordingly).  So using fixed-point the code might look like:

```<code>typedef uint16_t tSample ;

#define b1 53852    // 0.821725 * 65535
#define a0 (1 - b1)

#define FIXED_MUL( x, y ) (((x)*(y))>>16))

void lowPassFilter( const tSample* x, tSample* y, size_t sample_count )
{
    static tSample y_1 = 0 ;

    for( int i = 0; i < n; ++i)
    {
        y[i] = FIXED_MUL(a0, x[i]) + FIXED_MUL(b1, y_1) ;
        y_1 = y[i];
    }
}
</code>```

Now that is not a significant amount of processing for most ARM processors at 32ksps suggested in this example.  Obviously it depends what other demands are on the processor, but on its own this would not be a significant load, even without applying compiler optimisation.  As with any optimisation, you should implement it, measure it and improve it if necessary.

As a first stab I'd trust the compiler optimiser to generate code that in most cases will meet requirements or at least be as good as you might achieve with handwritten assembler.  Whether or not it would choose to use a multiply-accumulate instruction is out of your hands, but if it didn't the chances are that it is because there s no advantage.

Bare in mind that ARM Cortex-M4 and M7 for example include DSP instructions not supported in M0 or M3 ports.  The compiler may or may not utilise these, but the simplest way to guarantee that without resorting to assembler would be to use the CMSIS DSP Library whether or not that provided greater performance or better fidelity than the above, you would have to test.

Worth noting that the function lowPassFilter() retains state staically so can be called iteratively for "blocks" of samples (from ADC DMA transfer for example), so you might have:

```<code>int dma_buffer_n = 0
for(;;)
{
    waitEvent( DMA_BUFFER_READY ) ;
    lowPassFilter( dma_buffer[dma_buffer_n], output_buffer, DMA_BLOCK_SIZE ) ;
    dma_buffer_n = dma_buffer_n == 0 ? 1 : 0 ; // Flip buffers
}
</code>```

The use of DMA double-buffering is likely to be far more important to performance than the filter function implementation.  I have worked on a DSP application sampling two channels at 48ksps on a 72MHz Cortex-M3 with far more complex DSP requirements than this with each channel having a high pass IIR, an 18 coefficient FIR and a Viterbi decoder, so I really do think that your assumption that this simple filter will not be fast enough is somewhat premature.

Body:
The curve shown is that of the simplest possible first-order filter charactarised by a 3dB cut-off frequency fc> and a 6dB/Octave or 20dB/Decade roll-off. As an analogue filter it could be implemented as a simple passive RC filter thus:

In the digital domain such a filter would be implemented by:

yn = a0 xn + b1 yn-1

Where y are input samples and x output samples.  Or in code:

void lowPassFilter( const tSample* x, tSample* y, size_t sample_count )
{
    static tSample y_1 = 0 ;

    for( int i = 0; i < n; ++i)
    {
        y[i] = a0 * x[i] + b1 * y_1 ;
        y_1 = y[i];
    }
}

The filter is characterised by the coefficients:

a0 = 1 - x

b1 = x

where x is a value between 0 and 1 (I'll address the eradication of the implied floating point operations in due course):

x = e-2πfc

Where fc is the desired -3dB cut-off frequency expressed as a fraction of the sample rate.  So for a sample rate 32Ksps and a cut-off frequency of 1KHz, fc = 1000/32000 = 0.03125, so:

b1 = x = e-2πfc = 0.821725

a0 = 1 - x = 0.178275

Now naïvely plugging those constants into the lowPassFilter() will result in generation of floating point code and on an MCU without an FPU that might be prohibitive and even with an FPU might be be sub-optimal.  So in this case we might use a fixed-point representation.  Since all the real values are less than one, and the machine is 32bit, a UQ0.16 representation would be appropriate, as intermediate multiplication results will not then overflow a 32 bit machine word.  This does require the sample width to be 16bit or less (or scaled accordingly).  So using fixed-point the code might look like:

typedef uint16_t tSample ;

#define b1 53852    // 0.821725 * 65535
#define a0 (1 - b1)

#define FIXED_MUL( x, y ) (((x)*(y))>>16))

void lowPassFilter( const tSample* x, tSample* y, size_t sample_count )
{
    static tSample y_1 = 0 ;

    for( int i = 0; i < n; ++i)
    {
        y[i] = FIXED_MUL(a0, x[i]) + FIXED_MUL(b1, y_1) ;
        y_1 = y[i];
    }
}

Now that is not a significant amount of processing for most ARM processors at 32ksps suggested in this example.  Obviously it depends what other demands are on the processor, but on its own this would not be a significant load, even without applying compiler optimisation.  As with any optimisation, you should implement it, measure it and improve it if necessary.

As a first stab I'd trust the compiler optimiser to generate code that in most cases will meet requirements or at least be as good as you might achieve with handwritten assembler.  Whether or not it would choose to use a multiply-accumulate instruction is out of your hands, but if it didn't the chances are that it is because there s no advantage.

Bare in mind that ARM Cortex-M4 and M7 for example include DSP instructions not supported in M0 or M3 ports.  The compiler may or may not utilise these, but the simplest way to guarantee that without resorting to assembler would be to use the CMSIS DSP Library whether or not that provided greater performance or better fidelity than the above, you would have to test.

Worth noting that the function lowPassFilter() retains state staically so can be called iteratively for "blocks" of samples (from ADC DMA transfer for example), so you might have:

int dma_buffer_n = 0
for(;;)
{
    waitEvent( DMA_BUFFER_READY ) ;
    lowPassFilter( dma_buffer[dma_buffer_n], output_buffer, DMA_BLOCK_SIZE ) ;
    dma_buffer_n = dma_buffer_n == 0 ? 1 : 0 ; // Flip buffers
}

The use of DMA double-buffering is likely to be far more important to performance than the filter function implementation.  I have worked on a DSP application sampling two channels at 48ksps on a 72MHz Cortex-M3 with far more complex DSP requirements than this with each channel having a high pass IIR, an 18 coefficient FIR and a Viterbi decoder, so I really do think that your assumption that this simple filter will not be fast enough is somewhat premature.


问:
Error building AAB - Flutter (Android) - Integrity check failed: java.security.NoSuchAlgorithmException: Algorithm HmacPBESHA256 not available
I am trying to build an AAB for my flutter app. I generated the keystore using the following below command:

```<code>keytool -genkey -v -keystore ~/pc-keystore.jks -keyalg RSA -keysize 2048 -validity 10000 -alias pckey
</code>```

I have a key.properties file, and I have referenced it using the provided code in the flutter docs. How can I solve this Java related issue?  My program throws the following exception

```<code>* What went wrong:
Execution failed for task ':app:signReleaseBundle'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Failed to read key pckey from store "/Users/jrperfetto/pc-keystore.jks": Integrity check failed: java.security.NoSuchAlgorithmException: Algorithm HmacPBESHA256 not available

</code>```

答:
AS I lost my Keystore, and was unable to return it back, read google documentation about getting a new key.

Google: If you’ve lost your private upload key or it’s been compromised, you can create a new one, and then ask your account owner to contact support to reset the key. When contacting support, make sure your account owner attaches the upload_certificate.pem file.

I emailed google at the following link:
https://support.google.com/googleplay/android-developer/contact/key

They sent me the following commands to re-generate keystore and certificate.pem:

Here’s how to generate and register a new upload key:

Follow the instructions in the Android Studio Help Center to generate a new key. It must be different from any previous keys. Alternatively, you can use the following command line to generate a new key:

keytool -genkeypair -alias upload -keyalg RSA -keysize 2048 -validity 9125 -keystore keystore.jks

This key must be a 2048 bit RSA key and have 25-year validity.
Export the certificate for that key to PEM format:

keytool -export -rfc -alias upload -file upload_certificate.pem -keystore keystore.jks

Reply to this email and attach the upload_certificate.pem file, after replying, they will send an email mentioning your key store will be updated after 2 days,

now you have a new key store, in order to generate a signed bundle keys, you must do the following:

1- Go to the android side in your flutter (2.8.1) project.
2- go to settings> Build, Execution ..> Gradle>
3- change gradle JDK to something between 16 and 11, **JDK 15 worked for me.

note: if you don't have jdk, you can download it in same place Gradle JDK with jdk
download option.
note: you must build your signed app bundle within android only not inside flutter framework.

Body:
I am trying to build an AAB for my flutter app. I generated the keystore using the following below command:

keytool -genkey -v -keystore ~/pc-keystore.jks -keyalg RSA -keysize 2048 -validity 10000 -alias pckey

I have a key.properties file, and I have referenced it using the provided code in the flutter docs. How can I solve this Java related issue?  My program throws the following exception

* What went wrong:
Execution failed for task ':app:signReleaseBundle'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Failed to read key pckey from store "/Users/jrperfetto/pc-keystore.jks": Integrity check failed: java.security.NoSuchAlgorithmException: Algorithm HmacPBESHA256 not available


问:
Read array from file separated with commas and newlines
I have a file that has two different words per line, delimited by a comma and a line break. How can you read this file and store every word in an array? My code doesn't work because I think only works for "one line" array.

File Sample:

Each word is separated by a comma and a line break.

```<code>Dog,cat
shark,rabbit
mouse,bird
whale,dolphin
</code>```

Desired input

```<code>"${array[0]}" = Dog
"${array[1]}" = cat
"${array[2]}" = shark
"${array[3]}" = rabbit
"${array[4]}" = mouse
"${array[5]}" = bird
"${array[6]}" = whale
"${array[7]}" = dolphin
</code>```

My Code:

```<code>input=$(cat "/path/source_file")
IFS=',' read -r -a array <<< "$input"
</code>```

答:
Input Format:

Read the inarr1 from line 1 with array elements separated by (,) comma.

Read the inarr2 from line 2 with array elements separated by (,) comma.

Read the input from the standard input stream

Output format:

Body:
I have a file that has two different words per line, delimited by a comma and a line break. How can you read this file and store every word in an array? My code doesn't work because I think only works for "one line" array.

File Sample:

Each word is separated by a comma and a line break.

Dog,cat
shark,rabbit
mouse,bird
whale,dolphin

Desired input

"${array[0]}" = Dog
"${array[1]}" = cat
"${array[2]}" = shark
"${array[3]}" = rabbit
"${array[4]}" = mouse
"${array[5]}" = bird
"${array[6]}" = whale
"${array[7]}" = dolphin

My Code:

input=$(cat "/path/source_file")
IFS=',' read -r -a array <<< "$input"


问:
"Send With DocuSign" URL Button Works In Sandbox But Not Production
An APEX email error is received when trying to utilize the "Send With DocuSign" URL button on the contract object in Salesforce. This button was just created to meet the requirements to move from a JavaScript button. The button does not trigger an error in Sandbox, works as expected. But I can not replicate in production without getting the error shown below. Any idea on how to get this resolved?</p>
```<code>Developer script exception from Franklin Madison Group : DocuSignAPICredentials : Please verify that you have been granted access to DocuSign, your account settings are correct and that you have responded to all activation emails.

Apex script unhandled exception by user/organization: 0053n000007GFbq/00D70000000Je65

Visualforce Page: /apex/dsfs__docusign_editenvelope

caused by: dsfs.UnauthorizedException: Please verify that you have been granted access to DocuSign, your account settings are correct and that you have responded to all activation emails.

Class.dsfs.DocuSignAPICredentials.getInstance: line 71, column 1
Class.dsfs.DocuSignAPICredentials.getInstance: line 56, column 1
Class.dsfs.AccountFeatures.getInstance: line 139, column 1
Class.dsfs.EnvelopeController.loadEnvelope: line 164, column 1
</code>```

答:
Cause
Common causes for the issue are listed below,

The DocuSign user associated with the Salesforce user sending the envelope is not active

The Salesforce user has not been added to the DocuSign users list in DocuSign Setup settings (in Salesforce)
You are attempting to use Salesforce Login Access on behalf of a user "not yet Authorized DocuSign eSignature for Salesforce (DAL)"
Note: If the user hasn't authorized already, please refer to Step 4 in this article

Solution
Before continuing, ensure that you are on the most recent version of DocuSign eSignature for Salesforce (DAL). If you are on an outdated version, some of these steps will be unavailable.

To resolve this error, you’ll need to verify both issues that cause this error has been addressed.

First, you’ll need to verify that this Salesforce user has been added to DocuSign.

To verify if a Salesforce user has been added properly:
Navigate to DocuSign Setup.
Select User Management, then select Add User.
Enter the name of the user in the Value box. When they appear in the search results, select the checkbox next to their name and select Continue.
Assign the appropriate permissions to the user and select Apply. If your package is up to date and a DocuSign user already exists for this user, the Salesforce user will be mapped to their existing DocuSign user.
Click Done to finish.

Second, verify that the DocuSign user associated with this Salesforce account is active.

To check if a user is active in DocuSign:

Navigate to the DocuSign web app and select Settings.
Navigate to Users and search for the user in question.
If the user is not active, select Actions > Resend Invitation to send the invite to the user again.

To activate a user:
The User will need to navigate to their email client and open the invitation email.
Click the link in the email to activate.
Create a password and security question.

Once the user is active, have the user attempt to send an envelope from Salesforce to confirm the issue is resolved.

Additional Troubleshooting
If the DAL Admin and all users are noticing the same error, try to disconnect and reconnect.

Steps to Disconnect [Note: Disconnecting accounts will remove the DocuSign Gen and DocuSign Negotiate permissions for the Salesforce users that were given access under the old connection. You have to re-add DocuSign users and permissions in your organization.]
Steps to Reconnect

If the Salesforce Administrator attempting to make this change is unable to access the DocuSign Setup object, ensure that they have the correct permission set assignment to access the object.

To view permission set assignments in Salesforce:

Navigate to Setup, select Users.
Navigate to the user in question and open their profile.
Navigate to Permission Set Assignments, if the DocuSign permissions are missing, edit the section and add DocuSign Administrator.

Note: If you are running both DocuSign Apps Launcher and legacy DocuSign eSignature for Salesforce, you will see duplicate permission sets with similar names. Add both to ensure correct permissions are applied to the user.

Retest to see if the user can access DocuSign Setup. If it’s still failing, follow the steps in this article to navigate to the DocuSign Troubleshooting page and select Delete DocuSign Credentials. You should then be able to navigate to DocuSign Setup and reestablish the connection between DocuSign and Salesforce.

Body:
An APEX email error is received when trying to utilize the "Send With DocuSign" URL button on the contract object in Salesforce. This button was just created to meet the requirements to move from a JavaScript button. The button does not trigger an error in Sandbox, works as expected. But I can not replicate in production without getting the error shown below. Any idea on how to get this resolved?

Developer script exception from Franklin Madison Group : DocuSignAPICredentials : Please verify that you have been granted access to DocuSign, your account settings are correct and that you have responded to all activation emails.

Apex script unhandled exception by user/organization: 0053n000007GFbq/00D70000000Je65

Visualforce Page: /apex/dsfs__docusign_editenvelope

caused by: dsfs.UnauthorizedException: Please verify that you have been granted access to DocuSign, your account settings are correct and that you have responded to all activation emails.

Class.dsfs.DocuSignAPICredentials.getInstance: line 71, column 1
Class.dsfs.DocuSignAPICredentials.getInstance: line 56, column 1
Class.dsfs.AccountFeatures.getInstance: line 139, column 1
Class.dsfs.EnvelopeController.loadEnvelope: line 164, column 1


问:
Getting "ViCommand: no such keymap" errors while using Term::Readline:Zoid
I have a simple bit of code that works well until I export

```<code>PERL_RL='Zoid default_mode=ViCommand'
</code>```

in order to use vi mode while editing.  When I test the code I'm getting the error: ViCommand: no such keymap.  I installed libterm-readline-zoid-perl and from what I can tell ViCommand is built in so I should be good to go but apparently not.

```<code>#!/usr/bin/env perl
use warnings;
use strict;
use Term::ReadLine;

my $term = new Term::ReadLine 'LineEdit';

while ( defined ($_ = $term->readline($ARGV[0],$ARGV[1])) ) {
    print $_;
    exit;
}
</code>```

答:
Another solution:

$term->parse_and_bind("set editing-mode vi");
```

Body:
I have a simple bit of code that works well until I export

PERL_RL='Zoid default_mode=ViCommand'

in order to use vi mode while editing.  When I test the code I'm getting the error: ViCommand: no such keymap.  I installed libterm-readline-zoid-perl and from what I can tell ViCommand is built in so I should be good to go but apparently not.

#!/usr/bin/env perl
use warnings;
use strict;
use Term::ReadLine;

my $term = new Term::ReadLine 'LineEdit';

while ( defined ($_ = $term->readline($ARGV[0],$ARGV[1])) ) {
    print $_;
    exit;
}


问:
Perl advice - Taking in a file and changing contents
I have a request for some advice on how to approach this script I want to write in Perl. Basically I have a file that looks like :

```<code>  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4
</code>```

There are certain keywords such as pet and color that have numbers after then. I want to be able to take in a file and look for these keywords (there are 5 or 6 of them) and then change the number to the word that number corresponds to. That is to say for the keyword "Pet"---> 0 =dog, 1 = cat, 2=fish. And for the keyword "color" 0 = red, 1=blue,2=purple,3=brown,4=white. The script should find and change these numbers. The goal should be an output file that looks like:

```<code>      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white
</code>```

I've been struggling with how to do this for a while. I looked up online maybe I could do an array of hashes or something but I'm relatively new to Perl and don't know exactly how to even approach this problem.... Any advice would be much appreciated!

Thanks

答:
If we're talking about a small set of values, you could have a hash of arrays:

```<code>%lookups = ( pet => [ "dog", "cat", "fish" ],
             color => [ "red", "blue", "purple", "brown", "white" ] );
</code>```

Then, when you're reading the file, check each keyword against the hash. If it has a key with that keyword in it, replace the value in the line you read with the value from the hash.

Body:
I have a request for some advice on how to approach this script I want to write in Perl. Basically I have a file that looks like :

  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4

There are certain keywords such as pet and color that have numbers after then. I want to be able to take in a file and look for these keywords (there are 5 or 6 of them) and then change the number to the word that number corresponds to. That is to say for the keyword "Pet"---> 0 =dog, 1 = cat, 2=fish. And for the keyword "color" 0 = red, 1=blue,2=purple,3=brown,4=white. The script should find and change these numbers. The goal should be an output file that looks like:

      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white

I've been struggling with how to do this for a while. I looked up online maybe I could do an array of hashes or something but I'm relatively new to Perl and don't know exactly how to even approach this problem.... Any advice would be much appreciated!

Thanks

Body:
If we're talking about a small set of values, you could have a hash of arrays:

%lookups = ( pet => [ "dog", "cat", "fish" ],
             color => [ "red", "blue", "purple", "brown", "white" ] );

Then, when you're reading the file, check each keyword against the hash. If it has a key with that keyword in it, replace the value in the line you read with the value from the hash.


问:
Tabling in Prolog, when are values stored?
So let's say I have this code that uses a table to take 'note' of previous solutions or answers.

```<code>first_rule:-
   doSomething,
   recursive_call(A,B,C). %where A and B are lists of character codes

:- table recursive_call(_,_,min).

recursive_call([],B,C):- doSomething.
recursive_call(A,[],C):- doSomething.
</code>```

My question is, are the values being 'stored' or 'cached' into the table each time recursive_call is called?

Note (just to add more context to this code in case it might help): This is actually a snippet code of edit distance algorithm implementation in Prolog. So the purpose of :- table recursive_call(_,_,min) is to add the solutions or answers into the table while keeping the minimum value.

答:
Maybe this example will help (it uses a "lattice" rather than "min", but they're similar; and if you're doing edit distance, you might want to keep a list of the edits anyway):
https://www.swi-prolog.org/pldoc/man?section=tabling-mode-directed

"In this execution model one or more arguments are not added to the table. Instead, we remember a single aggregated value for these arguments."

Body:
So let's say I have this code that uses a table to take 'note' of previous solutions or answers.

first_rule:-
   doSomething,
   recursive_call(A,B,C). %where A and B are lists of character codes

:- table recursive_call(_,_,min).

recursive_call([],B,C):- doSomething.
recursive_call(A,[],C):- doSomething.

My question is, are the values being 'stored' or 'cached' into the table each time recursive_call is called?

Note (just to add more context to this code in case it might help): This is actually a snippet code of edit distance algorithm implementation in Prolog. So the purpose of :- table recursive_call(_,_,min) is to add the solutions or answers into the table while keeping the minimum value.


问:
How to get particular part of string from an array of strings using javascript?
Hi below is array of strings

```<code>const arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
    "some-domain/4/item/5/subitem/1/",
]
</code>```

i have to filter those strings that start with  string "item/3/" or ends with string "item/3/"

so from above array expected filtered array is like below,

```<code>const filtered_arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
]
</code>```

from the filtered array i want to get the number after "/item/". so from above filtered array the expected output is

```<code>const arr_ids = ["1", "2", "3"]
</code>```

what i have tried,

i have used below to match those strings that start or end with /item/3/

```<code>const filtered_arr = arr.map(str) => {
    return str.match(/item\/[0-9](\/)?$/g);
}
</code>```

this gives the filtered_arr

```<code>const filtered_arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
]
</code>```

but how do i map through each array item and get the number after string "/item/".

could someone help me with this. thanks.

答:
This may help:</p>
```<code>const filtered_arr = arr.map(str) => {
    const match = str.match(/\/item\/(\d)/);
    return(match[1]);
}
</code>```

Body:
Hi below is array of strings

const arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
    "some-domain/4/item/5/subitem/1/",
]

i have to filter those strings that start with  string "item/3/" or ends with string "item/3/"

so from above array expected filtered array is like below,

const filtered_arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
]

from the filtered array i want to get the number after "/item/". so from above filtered array the expected output is

const arr_ids = ["1", "2", "3"]

what i have tried,

i have used below to match those strings that start or end with /item/3/

const filtered_arr = arr.map(str) => {
    return str.match(/item\/[0-9](\/)?$/g);
}

this gives the filtered_arr

const filtered_arr = [
    "list/1/item/1/",
    "some-domain/2/item/2/",
    "item/3/",
]

but how do i map through each array item and get the number after string "/item/".

could someone help me with this. thanks.

Body:
This may help:

const filtered_arr = arr.map(str) => {
    const match = str.match(/\/item\/(\d)/);
    return(match[1]);
}


问:
How to Validate InputQuery user input before the user clicks OK?
In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I show an INPUT DIALOG to the user:

```<code>  var aNewFolderName: string := 'New Project Folder';
  if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
  begin
    // Todo: Create the folder if everything went OK, ELSE REPEAT the input action :-(
  end;
</code>```

Is there a way to VALIDATE the user's input BEFORE he clicks the OK button? (E.g., checking for not allowed characters, existing folder, etc.). Just repeating the whole input action in the case of invalid input AFTER the user clicked OK is not very smart and efficient:

```<code>  var aNewFolderName: string := 'New Project Folder';
  var InputIsValid: Boolean;
  repeat
    if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
    begin
      InputIsValid := CheckInput(aNewFolderName);
      if InputIsValid then CreateTheFolder(aNewFolderName);
    end
    else
      BREAK;
  until InputIsValid;
</code>```

Also, with this method, there is no feedback for the user about the specific cause of any invalid input.

答:
No, there is no way. But there are alternatives:

Look up InputQuery's code, write similar code and then make modifications where you want them (e.g. setting an OnChange handler for the TEdit). You'll notice it has been done in a quite simple way.

Design your own form for it, instead of (like InputQuery does) creating one on the fly:

You can either use your own logic for getting the user's choice and input when the form is closed, or

you set the form's ModalResult property (via code) anytime, and you can assign a ModalResult to each button (e.g. mrCancel), so it automatically sets the form's ModalResult property. Call your own form just as if it's MessageBox():

case MyForm.ShowModal() of
  IDOK: begin
    // User wants to proceed AND no error was found
  end;
  IDCANCEL: begin
    // User gave up
  end;
else
  // Unexpected result
end;
```
</li>
</ul>
</li>
<li><p>For me it would make nearly no difference if any feedback is given with any form still visible or not, as long as it is given. And you can give it, because nothing keeps you from doing so:</p>
<pre class="lang-delphi prettyprint-override"><code>var
  aNewFolderName,
  sErrorMsg: String;
begin
  repeat
    aNewFolderName:= 'New Project Folder';

    // User cancelled: leaving loop
    if not Vcl.Dialogs.InputQuery( 'New project folder', 'Enter the name of the new project folder:', aNewFolderName ) then break;

    // Already errors before the attempt?
    sErrorMsg:= CheckInput( aNewFolderName );

    // Actual attempt, which may still go wrong for various reasons
    if sErrorMsg= '' then sErrorMsg:= CreateTheFolder( aNewFolderName );

    // Anything to report?
    if sErrorMsg<> '' then begin
      sErrorMsg:= sErrorMsg+ #13#10
      + 'Click "Retry" to try a different new project name.'+ #13#10
      + 'Click "Cancel" to not create any new project.';
      if MessageBox( sErrorMsg, 'Error', MB_RETRYCANCEL )= IDCANCEL then break;
    end else begin
      break;  // Otherwise we're done (CreateTheFolder was successful)
    end;
  until FALSE;
end;
</code>```

Body:
In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I show an INPUT DIALOG to the user:

  var aNewFolderName: string := 'New Project Folder';
  if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
  begin
    // Todo: Create the folder if everything went OK, ELSE REPEAT the input action :-(
  end;

Is there a way to VALIDATE the user's input BEFORE he clicks the OK button? (E.g., checking for not allowed characters, existing folder, etc.). Just repeating the whole input action in the case of invalid input AFTER the user clicked OK is not very smart and efficient:

  var aNewFolderName: string := 'New Project Folder';
  var InputIsValid: Boolean;
  repeat
    if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
    begin
      InputIsValid := CheckInput(aNewFolderName);
      if InputIsValid then CreateTheFolder(aNewFolderName);
    end
    else
      BREAK;
  until InputIsValid;

Also, with this method, there is no feedback for the user about the specific cause of any invalid input.

Body:
No, there is no way. But there are alternatives:

Look up InputQuery's code, write similar code and then make modifications where you want them (e.g. setting an OnChange handler for the TEdit). You'll notice it has been done in a quite simple way.

Design your own form for it, instead of (like InputQuery does) creating one on the fly:

You can either use your own logic for getting the user's choice and input when the form is closed, or

you set the form's ModalResult property (via code) anytime, and you can assign a ModalResult to each button (e.g. mrCancel), so it automatically sets the form's ModalResult property. Call your own form just as if it's MessageBox():

case MyForm.ShowModal() of
  IDOK: begin
    // User wants to proceed AND no error was found
  end;
  IDCANCEL: begin
    // User gave up
  end;
else
  // Unexpected result
end;

For me it would make nearly no difference if any feedback is given with any form still visible or not, as long as it is given. And you can give it, because nothing keeps you from doing so:

var
  aNewFolderName,
  sErrorMsg: String;
begin
  repeat
    aNewFolderName:= 'New Project Folder';

    // User cancelled: leaving loop
    if not Vcl.Dialogs.InputQuery( 'New project folder', 'Enter the name of the new project folder:', aNewFolderName ) then break;

    // Already errors before the attempt?
    sErrorMsg:= CheckInput( aNewFolderName );

    // Actual attempt, which may still go wrong for various reasons
    if sErrorMsg= '' then sErrorMsg:= CreateTheFolder( aNewFolderName );

    // Anything to report?
    if sErrorMsg<> '' then begin
      sErrorMsg:= sErrorMsg+ #13#10
      + 'Click "Retry" to try a different new project name.'+ #13#10
      + 'Click "Cancel" to not create any new project.';
      if MessageBox( sErrorMsg, 'Error', MB_RETRYCANCEL )= IDCANCEL then break;
    end else begin
      break;  // Otherwise we're done (CreateTheFolder was successful)
    end;
  until FALSE;
end;