问:
Why do we need virtual functions in C++?
I'm learning C++ and I'm just getting into virtual functions.

From what I've read (in the book and online), virtual functions are functions in the base class that you can override in derived classes.

But earlier in the book, when learning about basic inheritance, I was able to override base functions in derived classes without using virtual.

So what am I missing here? I know there is more to virtual functions, and it seems to be important so I want to be clear on what it is exactly. I just can't find a straightforward answer online.

答:
The virtual keyword forces the compiler to pick the method implementation defined in the object's class rather than in the pointer's class.

```<code>Shape *shape = new Triangle();
cout << shape->getName();
</code>```

In the above example, Shape::getName will be called by default, unless the getName() is defined as virtual in the Base class Shape. This forces the compiler to look for the getName() implementation in the Triangle class rather than in the Shape class.

The virtual table is the mechanism in which the compiler keeps track of the various virtual-method implementations of the subclasses. This is also called dynamic dispatch, and there is some overhead associated with it.

Finally, why is virtual even needed in C++, why not make it the default behavior like in Java?

C++ is based on the principles of "Zero Overhead" and "Pay for what you use". So it doesn't try to perform dynamic dispatch for you, unless you need it.

To provide more control to the interface. By making a function non-virtual, the interface/abstract class can control the behavior in all its implementations.

Body:
The virtual keyword forces the compiler to pick the method implementation defined in the object's class rather than in the pointer's class.

Shape *shape = new Triangle();
cout << shape->getName();

In the above example, Shape::getName will be called by default, unless the getName() is defined as virtual in the Base class Shape. This forces the compiler to look for the getName() implementation in the Triangle class rather than in the Shape class.

The virtual table is the mechanism in which the compiler keeps track of the various virtual-method implementations of the subclasses. This is also called dynamic dispatch, and there is some overhead associated with it.

Finally, why is virtual even needed in C++, why not make it the default behavior like in Java?

C++ is based on the principles of "Zero Overhead" and "Pay for what you use". So it doesn't try to perform dynamic dispatch for you, unless you need it.

To provide more control to the interface. By making a function non-virtual, the interface/abstract class can control the behavior in all its implementations.


来源: stackexchange

问:
How to dynamically change div text of a dynamic div
Apologies for asking something already answered. I have tried to resolve this but i am unable to get this working(Might be because i am not a javascript guy and it confuses me.)

I want to change text of a div which is generated dynamically from a js library that i am using for show error messages.

I have tried to change the element using jQuery by its class like

```<code>$('document').ready(function () {
    $('.error-message')[item_number].innerText.replace('old string','new string');
}
</code>```

I have tried checking if the element is undefined and put a condition for that and also tried to use simple javascript. But i think the problem is not that, but that the function is not running dynamically and changing the values on the fly as this works in js console.

I would appreciate if someone answers what i need to learn and use for this. I don't think this needs ajax and i should be able to do this via pure js or jquery. But please let me know if i need the delve deeper into ajax to handle this.

Please note that i am able to change the text in js console as i want. Its just the i am unable to handle this on the fly as the div which i am trying to change is also generated on the fly.

答:
Since you are using jQuery - this should work for you.</p>

```<code>$('document').ready(function () {
    $('.error-message')[item_number].text('new string');
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Apologies for asking something already answered. I have tried to resolve this but i am unable to get this working(Might be because i am not a javascript guy and it confuses me.)

I want to change text of a div which is generated dynamically from a js library that i am using for show error messages.

I have tried to change the element using jQuery by its class like

$('document').ready(function () {
    $('.error-message')[item_number].innerText.replace('old string','new string');
}

I have tried checking if the element is undefined and put a condition for that and also tried to use simple javascript. But i think the problem is not that, but that the function is not running dynamically and changing the values on the fly as this works in js console.

I would appreciate if someone answers what i need to learn and use for this. I don't think this needs ajax and i should be able to do this via pure js or jquery. But please let me know if i need the delve deeper into ajax to handle this.

Please note that i am able to change the text in js console as i want. Its just the i am unable to handle this on the fly as the div which i am trying to change is also generated on the fly.

Body:
Since you are using jQuery - this should work for you.

$('document').ready(function () {
    $('.error-message')[item_number].text('new string');
}


问:
Scraping Google Patents with requests only returns style and scripts tags
I'm trying to scrape Google Patents using the following code.

```<code>    url = 'https://patents.google.com/?q=usb'
    r = requests.get(url)
    html_doc = r.text
    soup = BeautifulSoup(html_doc)
</code>```

But when I try to inspect the document, using

```<code>    print(soup.prettify)
</code>```

I cannot get anything other than this https://pastebin.com/Xu81LdfE .
I checked the requests status and it is returning 200. Where am I going wrong?

答:
The results on that page come for a different url:
https://patents.google.com/xhr/query?url=q%3Dusb&exp=

So instead of using BeautifulSoup, you could do r.json(), and find what you want in the dictionary it creates.

Body:
I'm trying to scrape Google Patents using the following code.

    url = 'https://patents.google.com/?q=usb'
    r = requests.get(url)
    html_doc = r.text
    soup = BeautifulSoup(html_doc)

But when I try to inspect the document, using

    print(soup.prettify)

I cannot get anything other than this https://pastebin.com/Xu81LdfE .
I checked the requests status and it is returning 200. Where am I going wrong?


问:
UnsafeMutablePointer as an output argument in PyObjC
In PyObjC when the function is void I can pass None as the output argument and then I will get the output argument in the returned value but when it comes to a function that is non void I can't find an example how it's done. What I'm trying to do is to get the GlyphBuffer in the following function from an already initiated instance of a NSLayoutManager. Here is the syntax in Objective c:

```<code>NSInteger numGlyphs = [layoutManager numberOfGlyphs];
NSGlyph *glyphs = (NSGlyph *)malloc(sizeof(NSGlyph) * (numGlyphs + 1));
[layoutManager getGlyphs:glyphs range:NSMakeRange(0, numGlyphs)];
[textStorage removeLayoutManager:layoutManager];
</code>```

As you can see the glyphs is an array of NSGlyphs with a length returned by layoutManager numberOfGlyphs. I got the following method to work in python:

```<code>layoutManager.getGlyphsInRange_glyphs_properties_characterIndexes_bidiLevels_ (glyphsRange, None, None, None, None)
</code>```

But I don’t get the glyph buffer in return because the function is not void, instead it returns the number of glyphs in glyphBuffer as described here. The glyph buffer should be an UnsafeMutablePointer. I can’t find a way to pass a NSGlyph array to the second argument. When I pass a list I get a traceback:

```<code>ValueError: depythonifying 'pointer', got 'list'
</code>```

Does anyone know if it’s possible and how it could be done?

Thanks

答: Since I was trying to extract position of glyphs in the LayoutManager I used locationForGlyphAtIndex method of the LayoutManager and it worked fine for my purpose.</p>

Body:
In PyObjC when the function is void I can pass None as the output argument and then I will get the output argument in the returned value but when it comes to a function that is non void I can't find an example how it's done. What I'm trying to do is to get the GlyphBuffer in the following function from an already initiated instance of a NSLayoutManager. Here is the syntax in Objective c:

NSInteger numGlyphs = [layoutManager numberOfGlyphs];
NSGlyph *glyphs = (NSGlyph *)malloc(sizeof(NSGlyph) * (numGlyphs + 1));
[layoutManager getGlyphs:glyphs range:NSMakeRange(0, numGlyphs)];
[textStorage removeLayoutManager:layoutManager];

As you can see the glyphs is an array of NSGlyphs with a length returned by layoutManager numberOfGlyphs. I got the following method to work in python:

layoutManager.getGlyphsInRange_glyphs_properties_characterIndexes_bidiLevels_ (glyphsRange, None, None, None, None)

But I don’t get the glyph buffer in return because the function is not void, instead it returns the number of glyphs in glyphBuffer as described here. The glyph buffer should be an UnsafeMutablePointer. I can’t find a way to pass a NSGlyph array to the second argument. When I pass a list I get a traceback:

ValueError: depythonifying 'pointer', got 'list'

Does anyone know if it’s possible and how it could be done?

Thanks


问:
What's the right way to do counts in Rails?
I have a rails app with many following pieces of code:

```<code>Our active community of <%= Account.find_all_by_admin(false).count %>
</code>```

My question is is this the right way to do counts on views? It seems so "dirty" is there a more railish, way to do counts? I'm thinking named scopes perhaps, but I just want to be sure that these type of things won't have  a greater impact in performance.

Thank You,

答:
I would recommend you to avoid direct access to database in my templates because then you're losing a bit of flexibility when it comes to caching.

Try to prepare all the data you need to render in your action instead and then use meaningful instance variables like @number_of_accounts or @accounts.count.

This will make your views cleaner and easier to debug and also a bit more DRY if you render action in different formats (html, json, etc)

As to how do you get your numbers - it doesn't really matter that much, just move away from find_* methods towards scoping and write readable code

ContentLicense: CC BY-SA 2.5

Body:
I have a rails app with many following pieces of code:

Our active community of <%= Account.find_all_by_admin(false).count %>

My question is is this the right way to do counts on views? It seems so "dirty" is there a more railish, way to do counts? I'm thinking named scopes perhaps, but I just want to be sure that these type of things won't have  a greater impact in performance.

Thank You,


问:
Different site at HTTP vs HTTPS
I am taking over a multi-site Apache server, with two websites (A and B). Going to website A's url via http works fine. Going to the same url, but using https, shows website B. Why is this, and how do I make https://urlA.com go to website A?</p>

答:
I solved the problem.

The servers were set up with VirtualHosts, but there was no VirtualHost for port 443. So it looked something like this:

```<code><VirtualHost 99.9.9.999:80>
DocumentRoot /var/www/example
ServerName example.com

    <Directory "/var/www/example">
            Options Indexes
            AllowOverride None
            DirectoryIndex index.php index.html
            Order allow,deny
            Allow from all
    </Directory>
</code>```

Adding a VirtualHost listening on port 443, with the SSLCertFiles specified fixed the problem.

```<code><VirtualHost 99.9.9.999:443>
DocumentRoot /var/www/example
ServerName example.com

    <Directory "/var/www/example">
            Options Indexes
            AllowOverride None
            DirectoryIndex index.php index.html
            Order allow,deny
            Allow from all
    </Directory>

SSLCertificateFile /etc/httpd/conf/example.crt
SSLCertificateKeyFile /etc/httpd/conf/_.example.key
SSLCertificateChainFile /etc/httpd/conf/gd_example.crt
SSLEngine on

</VirtualHost>
</code>```

Title: Different site at HTTP vs HTTPS

Body:
I solved the problem.

The servers were set up with VirtualHosts, but there was no VirtualHost for port 443. So it looked something like this:

<VirtualHost 99.9.9.999:80>
DocumentRoot /var/www/example
ServerName example.com

    <Directory "/var/www/example">
            Options Indexes
            AllowOverride None
            DirectoryIndex index.php index.html
            Order allow,deny
            Allow from all
    </Directory>

Adding a VirtualHost listening on port 443, with the SSLCertFiles specified fixed the problem.

<VirtualHost 99.9.9.999:443>
DocumentRoot /var/www/example
ServerName example.com

    <Directory "/var/www/example">
            Options Indexes
            AllowOverride None
            DirectoryIndex index.php index.html
            Order allow,deny
            Allow from all
    </Directory>

SSLCertificateFile /etc/httpd/conf/example.crt
SSLCertificateKeyFile /etc/httpd/conf/_.example.key
SSLCertificateChainFile /etc/httpd/conf/gd_example.crt
SSLEngine on

</VirtualHost>


问:
.htaccess redirect URL starts with /?/
Google Search Console is saying that a site we recently rebuilt has a bunch of 404s, which all start with /?/, for example, /?/AboutUs.

When I redirect like:

```<code>RewriteRule ^?/AboutUs$ /about [L,R=301]
</code>```

I get internal server error.

I tried it with the query string answer, that didn't help either (the URL I want to direct is not a query, I don't believe).

All of my server errors are of this kind, so a solution would be great.

答:
?/text is part of QueryString in your url. You can not match against querystring in RewriteRule's pattern. You need to use a RewriteCond

```<code>RewriteEngine on

RewriteCond %{QUERY_STRING} ^/aboutUs [NC]
RewriteRule ^ /about [L,R=301]
</code>```

Title: .htaccess redirect URL starts with /?/

Body:
Google Search Console is saying that a site we recently rebuilt has a bunch of 404s, which all start with /?/, for example, /?/AboutUs.

When I redirect like:

RewriteRule ^?/AboutUs$ /about [L,R=301]

I get internal server error.

I tried it with the query string answer, that didn't help either (the URL I want to direct is not a query, I don't believe).

All of my server errors are of this kind, so a solution would be great.

Body:
?/text is part of QueryString in your url. You can not match against querystring in RewriteRule's pattern. You need to use a RewriteCond

RewriteEngine on

RewriteCond %{QUERY_STRING} ^/aboutUs [NC]
RewriteRule ^ /about [L,R=301]


问:
React.js: Set a Default value into a prop
Fellows I have made this Component that creates a simple Button:

```<code>class AppButton extends Component {

  setOnClick() {
    if(!this.props.onClick && typeof this.props.onClick == 'function') {
      this.props.onClick=function(){ alert("Hello"); }
    }
  }

  setMessage() {
    if(!this.props.message){
        this.props.message="Hello"
    }
  }

  render(){
    this.setOnClick()
    this.setMessage()
    return (
      <button onClick={this.props.onClick}>{this.props.message}</button>
    )
  }
}
</code>```

And I have an another Component that renders 2 Buttons:

```<code>class App extends Component {
  render() {
    return (
          <AppButton onClick={function(){ alert('Test Alert') } } message="My Button" />
          <AppButton />
    );
  }
}
</code>```

But I get the following error:

TypeError: can't define property "message": Object is not extensible

On the line that says:

```<code>        this.props.message="Hello"
</code>```

in method setMessage of the AppButton class.

Edit 1

I generated the react application using npm and me package.json has the following content

```<code>{
  "name": "sample",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "react-scripts": "1.0.7"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
</code>```

答:
You cant set props, you must use state instead.

If you need to change the value, then it should be stored in the state due to props are static.

You should do it in this way:

```<code>this.setState({message: 'your message'});
</code>```

And in the render method use it as:

```<code>{this.state.message}
</code>```

As a recomendation, you should also initialize the state with that value in the constructor:

```<code>constructor(props){
  super(props);

  this.state = {
    message: ''
  }
}
</code>```

The same will happend to setOnClick

You will find here a good explanation about this.

ContentLicense: CC BY-SA 4.0

Body:
Fellows I have made this Component that creates a simple Button:

class AppButton extends Component {

  setOnClick() {
    if(!this.props.onClick && typeof this.props.onClick == 'function') {
      this.props.onClick=function(){ alert("Hello"); }
    }
  }

  setMessage() {
    if(!this.props.message){
        this.props.message="Hello"
    }
  }

  render(){
    this.setOnClick()
    this.setMessage()
    return (
      <button onClick={this.props.onClick}>{this.props.message}</button>
    )
  }
}

And I have an another Component that renders 2 Buttons:

class App extends Component {
  render() {
    return (
          <AppButton onClick={function(){ alert('Test Alert') } } message="My Button" />
          <AppButton />
    );
  }
}

But I get the following error:

TypeError: can't define property "message": Object is not extensible

On the line that says:

        this.props.message="Hello"

in method setMessage of the AppButton class.

Edit 1

I generated the react application using npm and me package.json has the following content

{
  "name": "sample",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "react-scripts": "1.0.7"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Body:
You cant set props, you must use state instead.

If you need to change the value, then it should be stored in the state due to props are static.

You should do it in this way:

this.setState({message: 'your message'});

And in the render method use it as:

{this.state.message}

As a recomendation, you should also initialize the state with that value in the constructor:

constructor(props){
  super(props);

  this.state = {
    message: ''
  }
}

The same will happend to setOnClick

You will find here a good explanation about this.


问:
Change group in Django admin is very slow
Django 1.11

If I click Groups in Django admin site, I can see a list of groups. Namely, the address is http://localhost:8000/admin/auth/group/

I monitor the CPU usage in terminal. Python is consuming 4-5 % now.

I have organized 4 groups. So, if I click any group, the server just calculating something for several minutes. The address now is like http://localhost:8000/admin/auth/group/6/change/
Maybe about 5 minutes the server is calculating something. And Python is now consuming 100 % of CPU resources.

Well, Django admin is analyzing something.

I have about 23-25 models. Well, this is not a very big number of models.

Each model is 3 standard permissions (add, change, delete). And I created one permission myself in the Meta class of a model.

So, as soon as "Change group" page is in front of me with available permissions and chosen permissions, CPU consumption by Python is again 4-5 %.

Could you comment on this? Is it curable?

答:
I've encountered the same problem when adding a new group with Debug=True in settings.py.

The same code works fine with Debug=False.

Some background information:

We use Django 1.11

We use custom user model inheriting from AbstractBaseUser

There are ~30 models registered on the admin site

Django debug toolbar output:


问:
NetBSD build failing due to .DS_Store file Macintosh
I am trying to build the NetBSD kernel using

```<code>$ ./build.sh -O ../obj.amd64 -U -u -m amd64 -j4 tools release iso-image
</code>```

It fails with the output

```<code>=======  1 extra files in DESTDIR  =========
Files in DESTDIR but missing from flist.
File is obsolete or flist is out of date ?
------------------------------------------
./.DS_Store
=========  end of 1 extra files  ===========
*** [checkflist] Error code 1

nbmake[2]: stopped in /Volumes/NetBSDImage/src/distrib/sets
1 error
</code>```

Even when I do an
rm .DS_Store in /Volumes/NetBSDImage/src/distrib/sets, it fails with the same message.
Earlier, when I compiled the kernel without the iso-image option, it build successfully, but now, even that fails. Some help?

答:
The best I could come up with is a work around and not a solution.

The DS_Store files are generated only when you open them in the Finder app of Mac systems.
So, on deleting and recloning the entire repository, it built successfully.

Body:
I am trying to build the NetBSD kernel using

$ ./build.sh -O ../obj.amd64 -U -u -m amd64 -j4 tools release iso-image

It fails with the output

=======  1 extra files in DESTDIR  =========
Files in DESTDIR but missing from flist.
File is obsolete or flist is out of date ?
------------------------------------------
./.DS_Store
=========  end of 1 extra files  ===========
*** [checkflist] Error code 1

nbmake[2]: stopped in /Volumes/NetBSDImage/src/distrib/sets
1 error

Even when I do an
rm .DS_Store in /Volumes/NetBSDImage/src/distrib/sets, it fails with the same message.
Earlier, when I compiled the kernel without the iso-image option, it build successfully, but now, even that fails. Some help?


问:
NoReverseMatch when href name in urls
I get NoReverseMatch when using

```<code>{% url 'detail' a.id %}
</code>```

in my template.

I have not included $ in my urls. Found that on a google search.

This is my main urls

```<code>urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^item/', include('item.urls')),
    url(r'^status/', include('status.urls')),
]
</code>```

and my status.urls

```<code>urlpatterns = [
    # /status/
    url(r'^$', views.index, name='index'),
    # /status/<status_id>/
    url(r'^(?P<status_id>[0-9]+)/$', views.detail, name='detail'),
]
</code>```

It work if I remove {% url 'detail' a.id %}and hardcode status/{{ a.id }}

I don't understand where I'm going wrong.

答:
You need a keyword argument. Try this:

```<code>{% url 'detail' status_id=a.id %}
</code>```

The reason is that your detail view receives a keyword argument according to your urls.py: (?P<status_id>[0-9]+)

Title: NoReverseMatch when href name in urls

Body:
I get NoReverseMatch when using

{% url 'detail' a.id %}

in my template.

I have not included $ in my urls. Found that on a google search.

This is my main urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^item/', include('item.urls')),
    url(r'^status/', include('status.urls')),
]

and my status.urls

urlpatterns = [
    # /status/
    url(r'^$', views.index, name='index'),
    # /status/<status_id>/
    url(r'^(?P<status_id>[0-9]+)/$', views.detail, name='detail'),
]

It work if I remove {% url 'detail' a.id %}and hardcode status/{{ a.id }}

I don't understand where I'm going wrong.

Body:
You need a keyword argument. Try this:

{% url 'detail' status_id=a.id %}

The reason is that your detail view receives a keyword argument according to your urls.py: (?P<status_id>[0-9]+)


问:
BAT script that sends commands to program it starts
So I'm trying to do something like this:

```<code>ftp my.ip.add.ress
(user id)
(password)
cd /the/directory
send C:/code/project1/*
bye
</code>```

I know you can send Windows ftp commands through the command line when you first start it like -send, but the question is can I use a .bat script to act interactively with the program it starts?  By default what happens is the first line:

```<code>ftp my.ip
</code>```

Starts ftp, but the subsequent lines never run until ftp exits.

edit

Another way to phrase this question is "Is it possible to use a .bat file to queue lines of text to feed to stdin when stdin is next checked for input?"

答:
As far as I know, the command shell is not multi-threaded, so there is no way for a batch to continue executing while another interactive shell program is executing within it.

You need to move the FTP commands into their own file, and pass that to the FTP program so it can run them as its own internal script.

```<code>ftp -s:filename
</code>```

Specifies a text file containing FTP commands; the commands will run automatically after FTP starts.

Body:
So I'm trying to do something like this:

ftp my.ip.add.ress
(user id)
(password)
cd /the/directory
send C:/code/project1/*
bye

I know you can send Windows ftp commands through the command line when you first start it like -send, but the question is can I use a .bat script to act interactively with the program it starts?  By default what happens is the first line:

ftp my.ip

Starts ftp, but the subsequent lines never run until ftp exits.

edit

Another way to phrase this question is "Is it possible to use a .bat file to queue lines of text to feed to stdin when stdin is next checked for input?"

Body:
As far as I know, the command shell is not multi-threaded, so there is no way for a batch to continue executing while another interactive shell program is executing within it.

You need to move the FTP commands into their own file, and pass that to the FTP program so it can run them as its own internal script.

ftp -s:filename

Specifies a text file containing FTP commands; the commands will run automatically after FTP starts.


答:
I believe that defaultProps should do what you need:

```<code>import PropTypes from 'prop-types';

class AppButton extends Component {
 render(){
    return (
      <button onClick={this.props.onClick}>{this.props.message}</button>
    )
  }
};

AppButton.propTypes = {
  message: PropTypes.string,
  onClick: PropTypes.func
};

AppButton.defaultProps = {
  message: 'Hello',
  onClick: function(){ alert("Hello"); }
};
</code>```

From the docs:

The defaultProps will be used to ensure that this.props.name will have a value if it was not specified by the parent component. The propTypes typechecking happens after defaultProps are resolved, so typechecking will also apply to the defaultProps.

Edit for clarity: There should be no need for you setMessage in this instance.

Title: React.js: Set a Default value into a prop

Body:
I believe that defaultProps should do what you need:

import PropTypes from 'prop-types';

class AppButton extends Component {
 render(){
    return (
      <button onClick={this.props.onClick}>{this.props.message}</button>
    )
  }
};

AppButton.propTypes = {
  message: PropTypes.string,
  onClick: PropTypes.func
};

AppButton.defaultProps = {
  message: 'Hello',
  onClick: function(){ alert("Hello"); }
};

From the docs:

The defaultProps will be used to ensure that this.props.name will have a value if it was not specified by the parent component. The propTypes typechecking happens after defaultProps are resolved, so typechecking will also apply to the defaultProps.

Edit for clarity: There should be no need for you setMessage in this instance.


问:
control PC using alexa
I have got a requirement of controlling PC/Computer using Alexa skill, i.e if I want to open an excel file on PC then if I simply say Alexa, ask openexcel to open excel file then excel file should be opened.

Can someone please guide me on how to proceed on this requirement.

Thanks
Varun

答:
Short overview:

You need a webserver on your local machine to answer Alexa's requests (I'd suggest Python's simplehttpserver)

Have the handlers on your webserver control Excel or whatever you need to do (that depends a lot on your os, you didn't mention which you use).

You need an SSL endpoint to your local webserver (the easy solution is to run ngrok, check ngrok.com

Title: control PC using alexa


问:
HTML5 Video in Chrome: forward/rewind not working
It is an ASP.NET MVC app - using a lot of HTML5 Videos.

What happens: when I try in other browsers to move forward the video with the mouse (manually), it works perfectly; even if I click pause, move the video circle on the track and click play, it works again.

In Chrome it works just sometimes (if the Video is cached I guess?), but the most time when I try to move the circle with the mouse, it just goes back on the place where it was. Even with paused video, I cannot play the video from wherever I want.

For example it happens with this Video. I have a feeling it happens only when I delete browser history and the video loads from zero. If I try several times, later it works (refreshing page or something).

Open this example: jsfiddle.net/1b9749et/

Any experience? Thanks.

答:
So, I re-encoded your video using ffmpeg to place the MOOV atom at the front (see below), uploaded it to Azure blob storage and the sample now seems to work correctly.

```<code>./ffmpeg -y -i 9f99b62e-7d56-4816-993b-286239f243bc_x264.mp4 -movflags faststart DestFile.mp4
</code>```

The MOOV atom in an mp4 is the metadata that tells the browser where the frames are (amongst other things) so the sooner it's loaded and available the sooner the browser can allow scrubbing etc

If you want to test quickly I'll leave the video hosted at https://jecathblob.blob.core.windows.net/samples/destfile.mp4 for the next 48 hours

[EDIT:] Updated the defaultStorageVersion for my BlobStorage to the latest which seems to support ByteRangeRequests better (to do that I used this utility, can share a pre-compiled .exe if that's easier)

[EDIT2:] I've uploaded the compiled version to https://1drv.ms/u/s!AhulbaZgpLZTjNhE_QaT4ET5xX1B-w (link will expire in 5 days). Just run per instructions at https://github.com/Plasma/AzureBlobUtility to set DefaultStorageVersion to 2016-05-31 (https://learn.microsoft.com/en-us/rest/api/storageservices/versioning-for-the-azure-storage-services)

Body:
So, I re-encoded your video using ffmpeg to place the MOOV atom at the front (see below), uploaded it to Azure blob storage and the sample now seems to work correctly.

./ffmpeg -y -i 9f99b62e-7d56-4816-993b-286239f243bc_x264.mp4 -movflags faststart DestFile.mp4

The MOOV atom in an mp4 is the metadata that tells the browser where the frames are (amongst other things) so the sooner it's loaded and available the sooner the browser can allow scrubbing etc

If you want to test quickly I'll leave the video hosted at https://jecathblob.blob.core.windows.net/samples/destfile.mp4 for the next 48 hours

[EDIT:] Updated the defaultStorageVersion for my BlobStorage to the latest which seems to support ByteRangeRequests better (to do that I used this utility, can share a pre-compiled .exe if that's easier)

[EDIT2:] I've uploaded the compiled version to https://1drv.ms/u/s!AhulbaZgpLZTjNhE_QaT4ET5xX1B-w (link will expire in 5 days). Just run per instructions at https://github.com/Plasma/AzureBlobUtility to set DefaultStorageVersion to 2016-05-31 (https://learn.microsoft.com/en-us/rest/api/storageservices/versioning-for-the-azure-storage-services)


问:
How to build XPath with [0-9] regex expression
Hi is there anyone can help me how to build the xpath for below 2 different XPath values?

```<code>//*[@id="EditorPanel"]/div[3]/div/table[1]/tbody/tr/td/table[1]
//*[@id="EditorPanel"]/div[4]/div/table[1]/tbody/tr/td/table[1]
</code>```

Im thinking something like

```<code>//*[@id="EditorPanel"]/div[3-4]/div/table[1]/tbody/tr/td/table[1]
</code>```

答:
div[3] is just an abbreviation of div[position() = 3], so you can use

```<code>//*[@id="EditorPanel"]/div[position() = 3 or position() = 4]/div/table[1]/tbody/tr/td/table[1]
</code>```

Body:
Hi is there anyone can help me how to build the xpath for below 2 different XPath values?

//*[@id="EditorPanel"]/div[3]/div/table[1]/tbody/tr/td/table[1]
//*[@id="EditorPanel"]/div[4]/div/table[1]/tbody/tr/td/table[1]

Im thinking something like

//*[@id="EditorPanel"]/div[3-4]/div/table[1]/tbody/tr/td/table[1]

Body:
div[3] is just an abbreviation of div[position() = 3], so you can use

//*[@id="EditorPanel"]/div[position() = 3 or position() = 4]/div/table[1]/tbody/tr/td/table[1]


问:
How do I use the NSString draw functionality to create a UIImage from text
I would like to draw the content of a NSString variable in a UIImage, but I have absolutely no idea how to do this. I need to write a method that would receive a NSString as parameter and return a UIImage with the text drawn into it.

答:
Swift 3.1

```<code>func sizeOfAttributeString(str: NSAttributedString, maxWidth: CGFloat) -> CGSize {
    let size = str.boundingRect(with: CGSize(width: maxWidth, height: 1000), options:(NSStringDrawingOptions.usesLineFragmentOrigin), context:nil).size
    return size
}

func imageFromText(text:NSString, font:UIFont, maxWidth:CGFloat, color:UIColor) -> UIImage {
    let paragraph = NSMutableParagraphStyle()
    paragraph.lineBreakMode = NSLineBreakMode.byWordWrapping
    paragraph.alignment = .center

    let attributedString = NSAttributedString(string: text as String, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName:paragraph])

    let size = sizeOfAttributeString(str: attributedString, maxWidth: maxWidth)
    UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
    attributedString.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}
</code>```

Credit goes to Bao Lei for the beautiful answer.

Body:
Swift 3.1

func sizeOfAttributeString(str: NSAttributedString, maxWidth: CGFloat) -> CGSize {
    let size = str.boundingRect(with: CGSize(width: maxWidth, height: 1000), options:(NSStringDrawingOptions.usesLineFragmentOrigin), context:nil).size
    return size
}

func imageFromText(text:NSString, font:UIFont, maxWidth:CGFloat, color:UIColor) -> UIImage {
    let paragraph = NSMutableParagraphStyle()
    paragraph.lineBreakMode = NSLineBreakMode.byWordWrapping
    paragraph.alignment = .center

    let attributedString = NSAttributedString(string: text as String, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName:paragraph])

    let size = sizeOfAttributeString(str: attributedString, maxWidth: maxWidth)
    UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
    attributedString.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

Credit goes to Bao Lei for the beautiful answer.


问:
Java: XML to Object (or Array)
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:

```<code>DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();
</code>```

Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?

答:
I would look at JAX/B, which gives a way to "bind" between Java objects and XML representations.

I've got a tiny write-up of doing it with Rational Eclipse-based tooling here, but there appear to be (never used them myself) straight Eclipse plugins too, for example this.

Indeed writing JAX/B by hand is possible, gets a bit dull for complex XML, but annotations are quite easy.

Title: Java: XML to Object (or Array)

Body:
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:

DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();

Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?


问:
How to create a new joined table record without creating a new instance of either record. Rails
I have a three tables: User, fruits, user_fruits

There are set number of users and fruits in the world. I cannot create duplicate fruits. Say the fruits already exist in the database, and I want to use them, so I'm not creating new fruits.

Assume we're in a controller and all I want to do is create a new instance of user_fruits. I also want to delete the joined table instance in the destroy action but not the actual fruit itself. Is this the way to do it?

```<code>def create
   user.user_fruits.create!(fruit: fruit)
end

def destroy
   user.user_fruits.find_by(fruit: fruit).destroy!
end

private

attr_reader :fruit

def load_fruit
@fruit = Fruit.find_by(color: red, sweetness: 100)
end
</code>```

I also want my destroy and create to raise an error if it fails.

答:
If you just want to create a new instance then you can simply use new or build

```<code>def create
  @new_fruit = user.fruits.new # or fruits.build
end
</code>```

Update

New instance of user_fruits?
Then you should try something like..

```<code>user.user_fruits.new

def create
  user.user_fruits.create!(fruit_id: @fruit.id)
end

def destroy
 user.user_fruits.find_by_fruit_id(@fruit.id).destroy!
end
</code>```

And if you want to use reader anyway then replace @fruit with fruit

Body:
I have a three tables: User, fruits, user_fruits

There are set number of users and fruits in the world. I cannot create duplicate fruits. Say the fruits already exist in the database, and I want to use them, so I'm not creating new fruits.

Assume we're in a controller and all I want to do is create a new instance of user_fruits. I also want to delete the joined table instance in the destroy action but not the actual fruit itself. Is this the way to do it?

def create
   user.user_fruits.create!(fruit: fruit)
end

def destroy
   user.user_fruits.find_by(fruit: fruit).destroy!
end

private

attr_reader :fruit

def load_fruit
@fruit = Fruit.find_by(color: red, sweetness: 100)
end

I also want my destroy and create to raise an error if it fails.

Body:
If you just want to create a new instance then you can simply use new or build

def create
  @new_fruit = user.fruits.new # or fruits.build
end

Update

New instance of user_fruits?
Then you should try something like..

user.user_fruits.new

def create
  user.user_fruits.create!(fruit_id: @fruit.id)
end

def destroy
 user.user_fruits.find_by_fruit_id(@fruit.id).destroy!
end

And if you want to use reader anyway then replace @fruit with fruit


问:
How to generate date range sequence without temp table in SQL
I want to convert some line of code from Oracle query to MSSQL.

```<code>   WITH DATE_MONTHS AS
(
  SELECT TO_CHAR(ADD_MONTHS(TO_DATE(TRUNC(TO_DATE(P_REQUIRED_DATE),'MON')), - LEVEL
  +1),'DD-MON-YYYY') MONTHS FROM DUAL
  CONNECT BY LEVEL <= P_MONTH_RANG
)
SELECT * from DATE_MONTHS
</code>```

Parameters:

P_REQUIRED_DATE i.e sysdate

P_MONTH_RANG  i.e 4

Result:

01-05-2017

01-04-2017

01-03-2017

01-02-2017

答:
One simple way is to use tally table and generate like below:

```<code>declare @P_Required_Date date = '2015-05-01'
declare @P_Month_Rang int = 4

Select top (@P_Month_Rang) Dts = DateAdd(month, -(Row_Number() over(order by (Select NULL))-1), @P_Required_Date) from
        master..spt_values s1, master..spt_values s2
</code>```

Output as below:

```<code>    +------------+
    |    Dts     |
    +------------+
    | 2015-05-01 |
    | 2015-04-01 |
    | 2015-03-01 |
    | 2015-02-01 |
    +------------+
</code>```

Your CTE approach:

```<code>declare @P_Required_Date date = '2015-05-01'
declare @P_Month_Rang int = 4

;with Date_Months as
(
    Select @P_Required_Date as Dates, 1 as Levl

    Union all

    Select DateAdd(MONTH,-1, Dates), Levl+1 as Levl  from Date_Months
        where Levl < @P_Month_Rang
)
Select convert(varchar(10), dates, 103) from Date_Months
</code>```

For converting to your dd-mm-yyyy format one way is to do convert with option 103 or use Format.

Body:
I want to convert some line of code from Oracle query to MSSQL.

   WITH DATE_MONTHS AS
(
  SELECT TO_CHAR(ADD_MONTHS(TO_DATE(TRUNC(TO_DATE(P_REQUIRED_DATE),'MON')), - LEVEL
  +1),'DD-MON-YYYY') MONTHS FROM DUAL
  CONNECT BY LEVEL <= P_MONTH_RANG
)
SELECT * from DATE_MONTHS

Parameters:

P_REQUIRED_DATE i.e sysdate

P_MONTH_RANG  i.e 4

Result:

01-05-2017

01-04-2017

01-03-2017

01-02-2017

Body:
One simple way is to use tally table and generate like below:

declare @P_Required_Date date = '2015-05-01'
declare @P_Month_Rang int = 4

Select top (@P_Month_Rang) Dts = DateAdd(month, -(Row_Number() over(order by (Select NULL))-1), @P_Required_Date) from
        master..spt_values s1, master..spt_values s2

Output as below:

    +------------+
    |    Dts     |
    +------------+
    | 2015-05-01 |
    | 2015-04-01 |
    | 2015-03-01 |
    | 2015-02-01 |
    +------------+

Your CTE approach:

declare @P_Required_Date date = '2015-05-01'
declare @P_Month_Rang int = 4

;with Date_Months as
(
    Select @P_Required_Date as Dates, 1 as Levl

    Union all

    Select DateAdd(MONTH,-1, Dates), Levl+1 as Levl  from Date_Months
        where Levl < @P_Month_Rang
)
Select convert(varchar(10), dates, 103) from Date_Months

For converting to your dd-mm-yyyy format one way is to do convert with option 103 or use Format.


问:
Discarding the output of a function that accepts an output iterator
Suppose there´s a template function in C++ that does some useful work but also outputs a sequence of values via an output iterator. Now suppose that the sequence of values sometimes is interesting, but at others is not useful. Is there a ready-to-use iterator class in the STL that can be instantiated and passed to the function and will ignore any value the function tries to assign to it? To put in another way, send all data to /dev/null?</p>

答:
I based mine on std::back_insert_iterator, but without the container:

```<code>#include <iterator>

template<typename T>
class NullOutputIter
    : public std::iterator<std::output_iterator_tag,void,void,void,void>
{
public:
    NullOutputIter &operator=(const T &) { return *this; }
    NullOutputIter &operator*() { return *this; }
    NullOutputIter &operator++() { return *this; }
    NullOutputIter operator++(int) { return *this; }
};
</code>```

This is similar to Johannes's answer, but without the template operator= that takes whatever. I like strong typing; I want *it = wrong_type_thing to be a compile-time error. Also this uses void for the various template parameters to std::iterator, like the output iterators in the standard library.

This is also similar to Mark's solution, but (a) it properly inherits from std::iterator and (b) it does not have the unneeded internal state variable.

OwnerDisplayName: David Reis

LastEditorDisplayName: Chris Jester-Young

Body:
I based mine on std::back_insert_iterator, but without the container:

#include <iterator>

template<typename T>
class NullOutputIter
    : public std::iterator<std::output_iterator_tag,void,void,void,void>
{
public:
    NullOutputIter &operator=(const T &) { return *this; }
    NullOutputIter &operator*() { return *this; }
    NullOutputIter &operator++() { return *this; }
    NullOutputIter operator++(int) { return *this; }
};

This is similar to Johannes's answer, but without the template operator= that takes whatever. I like strong typing; I want *it = wrong_type_thing to be a compile-time error. Also this uses void for the various template parameters to std::iterator, like the output iterators in the standard library.

This is also similar to Mark's solution, but (a) it properly inherits from std::iterator and (b) it does not have the unneeded internal state variable.


问:
Django autocomplete Light in list filters for admin
I have successfully setup the Autocomplete Registry and have my django admin forms where if you go to the form, the auto completes works. I would like to be able to extend the autocompletes to work on the list_filter view as well. So when you are looking at the view generated by Admin.py -- that the list_filter inputs that are generated would also use the autocomplete jquery + service URL.

I didn't see anything listed in the documentation, anyone have any pointers?

答:
You should define your own admin filter that inherits from django.contrib.admin.SimpleListFilter. Then should provide your own HTML template for this filter which will use one of django-autocomplete-light widgets. As a parameter for widget you should define required autocomplete URL. And do not forget to include proper JS and CSS for it.

All of this is done in special app for this: dal-admin-filters


问:
How to get view to fill remaining width in JavaFX
I'm using fxml in JavaFX and I want a list master/detail view. A list on the left of a fixed size, and a detail of a TextArea where the width grows with the window size.

This is my fxml:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <top>
      <MenuBar prefWidth="671.0" BorderPane.alignment="CENTER">
        <menus>
          <Menu mnemonicParsing="false" text="File">
            <items>
              <MenuItem mnemonicParsing="false" text="Close" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Edit">
            <items>
              <MenuItem mnemonicParsing="false" text="Delete" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Help">
            <items>
              <MenuItem mnemonicParsing="false" text="About" />
            </items>
          </Menu>
        </menus>
      </MenuBar>
   </top>
   <center>
      <HBox BorderPane.alignment="CENTER">
         <children>
            <ListView prefHeight="754.0" prefWidth="236.0" />
            <TextArea />
         </children>
      </HBox>
   </center>
</BorderPane>
</code>```

This sample fxml looks like this:

You can see that the list is correct, and the textArea is showing and growing in height but not in width.

EDIT

Modified due to an answer.

This is the full code now. I only changed the max width and height of -Infinity to -1 but still no luck.

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>

<BorderPane maxHeight="-1" maxWidth="-1" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
    <top>
        <MenuBar prefWidth="671.0" BorderPane.alignment="CENTER">
            <menus>
                <Menu mnemonicParsing="false" text="File">
                    <items>
                        <MenuItem mnemonicParsing="false" text="Close" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Edit">
                    <items>
                        <MenuItem mnemonicParsing="false" text="Delete" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Help">
                    <items>
                        <MenuItem mnemonicParsing="false" text="About" />
                    </items>
                </Menu>
            </menus>
        </MenuBar>
    </top>
    <center>
        <HBox BorderPane.alignment="CENTER">
            <children>
                <ListView prefHeight="754.0" prefWidth="236.0" />
                <TextArea />
            </children>
        </HBox>
    </center>
</BorderPane>
</code>```

答:
The value of negative infinity is the constant USE_PREF_SIZE, which means your BorderPane will never be larger than its preferred size (which in your case is 1280x800).

Changing the maximum width and height to USE_COMPUTED_SIZE (-1) should solve your problem. As this is the default value, you could just remove the maxHeight and maxWidth attributes.

Body:
I'm using fxml in JavaFX and I want a list master/detail view. A list on the left of a fixed size, and a detail of a TextArea where the width grows with the window size.

This is my fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <top>
      <MenuBar prefWidth="671.0" BorderPane.alignment="CENTER">
        <menus>
          <Menu mnemonicParsing="false" text="File">
            <items>
              <MenuItem mnemonicParsing="false" text="Close" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Edit">
            <items>
              <MenuItem mnemonicParsing="false" text="Delete" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Help">
            <items>
              <MenuItem mnemonicParsing="false" text="About" />
            </items>
          </Menu>
        </menus>
      </MenuBar>
   </top>

      <HBox BorderPane.alignment="CENTER">
         <children>
            <ListView prefHeight="754.0" prefWidth="236.0" />
            <TextArea />
         </children>
      </HBox>

</BorderPane>

This sample fxml looks like this:

You can see that the list is correct, and the textArea is showing and growing in height but not in width.

EDIT

Modified due to an answer.

This is the full code now. I only changed the max width and height of -Infinity to -1 but still no luck.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>

<BorderPane maxHeight="-1" maxWidth="-1" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
    <top>
        <MenuBar prefWidth="671.0" BorderPane.alignment="CENTER">
            <menus>
                <Menu mnemonicParsing="false" text="File">
                    <items>
                        <MenuItem mnemonicParsing="false" text="Close" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Edit">
                    <items>
                        <MenuItem mnemonicParsing="false" text="Delete" />
                    </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Help">
                    <items>
                        <MenuItem mnemonicParsing="false" text="About" />
                    </items>
                </Menu>
            </menus>
        </MenuBar>
    </top>

        <HBox BorderPane.alignment="CENTER">
            <children>
                <ListView prefHeight="754.0" prefWidth="236.0" />
                <TextArea />
            </children>
        </HBox>

</BorderPane>


问:
Two nested update panels on same aspx page
I have two nested UpdatePanel controls on apsx page. The outer one is for the whole page and displays "Loading Page..." img, while the purpose of inner one is to load a grid on dropdownlist selectedIndexChanged

I get this error while both have different names:
JavaScript runtime error: Sys.InvalidOperationException: Two components with the same id 'cphMainContent_Updprog3' can't be added to the application.

Please guide. Here is the code structure:

```<code>     <asp:content id="HeaderContent" runat="server" contentplaceholderid="head">

    <script language="javascript" type="text/javascript">
            function showProgress() {
                var updateProgress = $get("<%=Updprog3.ClientID %>");
                updateProgress.style.display = "block";
            }

        </script>
    </asp:content>

    <asp:content id="BodyContent" runat="server" contentplaceholderid="cphMainContent">
        <div style="padding-left:36px; padding-top:10px;">
            <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
                <ContentTemplate>
    <table align="left">

           <tr>
                <td style="border: none; width:120px">
                    Call Category Group:
                </td>
                <td>
                    <asp:DropDownList ID="ddlGroup" runat="server"
                        onChange="javascript:showProgress()"
                        OnSelectedIndexChanged="ddlGroup_SelectedIndexChanged" Width="400px">
                        <asp:ListItem Value="-1">--- Select Group ---</asp:ListItem>
                        <asp:ListItem Value="Group 1"> Group 1</asp:ListItem>
                        <asp:ListItem Value="Group 2">Group 2</asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>

      <!--2nd update panel-->
    <asp:UpdatePanel ID="UpdPnl" runat="server" UpdateMode="Conditional">
       <Triggers>
            <asp:AsyncPostBackTrigger ControlID="ddlCallCategoryGroup" EventName="SelectedIndexChanged"/>
        </Triggers>
    <ContentTemplate>

    <asp:GridView ID="gridView1" runat="server">
    </asp:GridView>
    </ContentTemplate>
    </asp:UpdatePanel>

    <asp:Panel runat="server" ID="pnlgvSecondLevelLoading" CssClass="modalwindow">
    <asp:UpdateProgress ID="Updprog3" runat="server" AssociatedUpdatePanelID="UpdPnl">
        <ProgressTemplate>
                        <table>
                        <tr>
                            <td align="right" width="35%">
                                <asp:Image ID="imgSubCallCategory_Wait3" runat="server" ImageUrl="ProjectImages/Wait_Small.gif" />
                            </td>
                            <td width="2%">
                            </td>
                            <td align="center" width="73%">
                                Loading data . . .
                            </td>
                        </tr>
                    </table>

        </ProgressTemplate>
    </asp:UpdateProgress>
    </asp:Panel>

    <asp:Panel runat="server" ID="pnlLoading" CssClass="modalwindow">
        <asp:UpdateProgress ID="UpdateProgress2" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
            <ProgressTemplate>
                <div class="container2">
                    <div class="content">
                        <br />
                        <table>
                            <tr>
                                <td align="right" width="35%">
                                    <asp:Image ID="imgSubCallCategory_Wait2" runat="server" ImageUrl="ProjectImages/30-1.gif" />
                                </td>
                                <td width="2%">
                                </td>
                                <td align="center" width="73%">
                                    Loading Page . . .
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </ProgressTemplate>
        </asp:UpdateProgress>
    </asp:Panel>
         </ContentTemplate>
        </asp:UpdatePanel>
    </div>
</asp:content>
</code>```

答:
```<code><asp:ScriptManager ID="WebApp" runat="server" AsyncPostBackTimeout="36000" ScriptMode="Release"></asp:ScriptManager>
</code>```

Body:
I have two nested UpdatePanel controls on apsx page. The outer one is for the whole page and displays "Loading Page..." img, while the purpose of inner one is to load a grid on dropdownlist selectedIndexChanged

I get this error while both have different names:
JavaScript runtime error: Sys.InvalidOperationException: Two components with the same id 'cphMainContent_Updprog3' can't be added to the application.

Please guide. Here is the code structure:

     <asp:content id="HeaderContent" runat="server" contentplaceholderid="head">

    </asp:content>

    <asp:content id="BodyContent" runat="server" contentplaceholderid="cphMainContent">

            <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
                <ContentTemplate>

                    Call Category Group:

                    <asp:DropDownList ID="ddlGroup" runat="server"
                        onChange="javascript:showProgress()"
                        OnSelectedIndexChanged="ddlGroup_SelectedIndexChanged" Width="400px">
                        <asp:ListItem Value="-1">--- Select Group ---</asp:ListItem>
                        <asp:ListItem Value="Group 1"> Group 1</asp:ListItem>
                        <asp:ListItem Value="Group 2">Group 2</asp:ListItem>
                    </asp:DropDownList>

    <asp:UpdatePanel ID="UpdPnl" runat="server" UpdateMode="Conditional">
       <Triggers>
            <asp:AsyncPostBackTrigger ControlID="ddlCallCategoryGroup" EventName="SelectedIndexChanged"/>
        </Triggers>
    <ContentTemplate>

    <asp:GridView ID="gridView1" runat="server">
    </asp:GridView>
    </ContentTemplate>
    </asp:UpdatePanel>

    <asp:Panel runat="server" ID="pnlgvSecondLevelLoading" CssClass="modalwindow">
    <asp:UpdateProgress ID="Updprog3" runat="server" AssociatedUpdatePanelID="UpdPnl">
        <ProgressTemplate>

                                <asp:Image ID="imgSubCallCategory_Wait3" runat="server" ImageUrl="ProjectImages/Wait_Small.gif" />

                                Loading data . . .

        </ProgressTemplate>
    </asp:UpdateProgress>
    </asp:Panel>

    <asp:Panel runat="server" ID="pnlLoading" CssClass="modalwindow">
        <asp:UpdateProgress ID="UpdateProgress2" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
            <ProgressTemplate>

                                    <asp:Image ID="imgSubCallCategory_Wait2" runat="server" ImageUrl="ProjectImages/30-1.gif" />

                                    Loading Page . . .

            </ProgressTemplate>
        </asp:UpdateProgress>
    </asp:Panel>
         </ContentTemplate>
        </asp:UpdatePanel>

</asp:content>


答:
```<code>return (
      <button onClick={this.props.onClick}>{this.props.message || "Default text"}</button>
);
</code>```

<p>This will check the value of prop and if it is undefined or null, the default message will replace the prop. </p>

Body:
Fellows I have made this Component that creates a simple Button:

class AppButton extends Component {

  setOnClick() {
    if(!this.props.onClick && typeof this.props.onClick == 'function') {
      this.props.onClick=function(){ alert("Hello"); }
    }
  }

  setMessage() {
    if(!this.props.message){
        this.props.message="Hello"
    }
  }

  render(){
    this.setOnClick()
    this.setMessage()
    return (
      <button onClick={this.props.onClick}>{this.props.message}</button>
    )
  }
}

And I have an another Component that renders 2 Buttons:

class App extends Component {
  render() {
    return (
          <AppButton onClick={function(){ alert('Test Alert') } } message="My Button" />
          <AppButton />
    );
  }
}

But I get the following error:

TypeError: can't define property "message": Object is not extensible

On the line that says:

        this.props.message="Hello"

in method setMessage of the AppButton class.

Edit 1

I generated the react application using npm and me package.json has the following content

{
  "name": "sample",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "react-scripts": "1.0.7"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Body:
return (
      <button onClick={this.props.onClick}>{this.props.message || "Default text"}</button>
);

This will check the value of prop and if it is undefined or null, the default message will replace the prop.


问:
How to give the Constraints for the UIImageView besides the UITextField?
I have the SignIn Page where we need to put the UIImage (Say Mobile Number) besides the UITextField. So the constraints which i am putting is like this:

For Mobile Number

UIImage: Leading to the container, Width and Height, Horizontal spacing to UITextField

UITextField : Trailing to the Container, Vertical spacing to the UIImageView for Profile Picture, height and width.

Similarly For Password

UIImage: Leading to the container, Width and Height, Horizontal spacing to UITextField

UITextField : Trailing to the Container, Vertical spacing to the UITextField (Mobile Number), height and width.

But still the constraints are not getting satisfied with the Iphone for all the screens.

答:
It sounds like you have only one thing wrong...

Do not set width constraints on your UITextFields.

The Horizontal Spacing from image to textfield sets the "left edge" of the textfield, and the textfield's Trailing to the Container constraint sets the "right edge" of the textfield.

So, on different width screens, the textfield will stretch to fill the space.


问:
How to dynamically change div text of a dynamic div
Apologies for asking something already answered. I have tried to resolve this but i am unable to get this working(Might be because i am not a javascript guy and it confuses me.)

I want to change text of a div which is generated dynamically from a js library that i am using for show error messages.

I have tried to change the element using jQuery by its class like

```<code>$('document').ready(function () {
    $('.error-message')[item_number].innerText.replace('old string','new string');
}
</code>```

I have tried checking if the element is undefined and put a condition for that and also tried to use simple javascript. But i think the problem is not that, but that the function is not running dynamically and changing the values on the fly as this works in js console.

I would appreciate if someone answers what i need to learn and use for this. I don't think this needs ajax and i should be able to do this via pure js or jquery. But please let me know if i need the delve deeper into ajax to handle this.

Please note that i am able to change the text in js console as i want. Its just the i am unable to handle this on the fly as the div which i am trying to change is also generated on the fly.

答:
The vanilla js code would be:</p>

```<code>document.getElementsByClassName("error-message")[item_number].innerHTML = "something else here"
</code>```

Body:
Apologies for asking something already answered. I have tried to resolve this but i am unable to get this working(Might be because i am not a javascript guy and it confuses me.)

I want to change text of a div which is generated dynamically from a js library that i am using for show error messages.

I have tried to change the element using jQuery by its class like

$('document').ready(function () {
    $('.error-message')[item_number].innerText.replace('old string','new string');
}

I have tried checking if the element is undefined and put a condition for that and also tried to use simple javascript. But i think the problem is not that, but that the function is not running dynamically and changing the values on the fly as this works in js console.

I would appreciate if someone answers what i need to learn and use for this. I don't think this needs ajax and i should be able to do this via pure js or jquery. But please let me know if i need the delve deeper into ajax to handle this.

Please note that i am able to change the text in js console as i want. Its just the i am unable to handle this on the fly as the div which i am trying to change is also generated on the fly.

Body:
The vanilla js code would be:

document.getElementsByClassName("error-message")[item_number].innerHTML = "something else here"


问:
Open/Edit/Save from on the host with app running in container
We recently have a lot of problem deploying the Linux version of our app for the client (updated libraries, missing libraries, install path), and we are looking to use Docker for deployment.

Our app as a UI, so we naturally map that using

```<code>-e DISPLAY:$DISPLAY -v /tmp/X11-unix:/tmp/X11-unix
</code>```

and we can actually see the UI popping up.

But when it's time to open a file, the problem start there. We want to only browse the host system and save any output file on the host (output directory is determined by the location of the opened file).

Which strategy would you suggest for this?

We want the client to not see the difference between the app running locally or inside Docker. We are working on a launch script so it looks like the client would still be double-clicking on it to start the app. We can add all the configuration we need in there for the docker run command.

答:
After recommendations by @CFrei and @Robert here's a solution that seems to work well:

```<code>docker run                                \
       -ti                                \
       -u $(id -u):$(id -g)               \
       -v /home/$(id -un):/home/$(id -un) \
       -v /etc/passwd:/etc/passwd         \
       -w $(pwd)                          \
       MyDockerImage
</code>```

And now, every file created inside that container is perfectly located in the right directory on the host with the ownership by the user.

And from inside the container, it really looks like the host, which will be very useful for the client.

Thanks again for your help guys!

And I hope this can help someone else.

Body:
We recently have a lot of problem deploying the Linux version of our app for the client (updated libraries, missing libraries, install path), and we are looking to use Docker for deployment.

Our app as a UI, so we naturally map that using

-e DISPLAY:$DISPLAY -v /tmp/X11-unix:/tmp/X11-unix

and we can actually see the UI popping up.

But when it's time to open a file, the problem start there. We want to only browse the host system and save any output file on the host (output directory is determined by the location of the opened file).

Which strategy would you suggest for this?

We want the client to not see the difference between the app running locally or inside Docker. We are working on a launch script so it looks like the client would still be double-clicking on it to start the app. We can add all the configuration we need in there for the docker run command.

Body:
After recommendations by @CFrei and @Robert here's a solution that seems to work well:

docker run                                \
       -ti                                \
       -u $(id -u):$(id -g)               \
       -v /home/$(id -un):/home/$(id -un) \
       -v /etc/passwd:/etc/passwd         \
       -w $(pwd)                          \
       MyDockerImage

And now, every file created inside that container is perfectly located in the right directory on the host with the ownership by the user.

And from inside the container, it really looks like the host, which will be very useful for the client.

Thanks again for your help guys!

And I hope this can help someone else.


问:
Integrating Mail Chimp API into Django Application.
Any one has got idea about,How to Integrate mail chimp api into django app? i have installed django-mailchimp-v1.3 on my app, but not able to proceed with the rest(views an all), How to add contacts(list) to the mailing list? Mail chimp documentation has got less details.

答:
Instead of using django-mailchimp package use mailchimp package for integrating MailChimp to your Django site.

First, you have create an account on MailChimp, create the List there, and thereafter get the List Key and API key of your account.

Install the package to integrate MailChimp into your Django site

```<code>pip install mailchimp
</code>```

Then send a request to connect with your list in MailChimp

```<code>import mailchimp

API_KEY = <<Your MailChimp API Key>>
LIST_ID = <<Your List Key>>
api = mailchimp.Mailchimp(API_KEY)
api.lists.subscribe(LIST_ID, {'email': 'xyz@gmail.com'})
</code>```

Full Tutorial on this Topic: https://djangopy.org/package-of-week/how-to-integrate-mailchimp-on-django-to-increase-subscribers/

Body:
Instead of using django-mailchimp package use mailchimp package for integrating MailChimp to your Django site.

First, you have create an account on MailChimp, create the List there, and thereafter get the List Key and API key of your account.

Install the package to integrate MailChimp into your Django site

pip install mailchimp

Then send a request to connect with your list in MailChimp

import mailchimp

API_KEY = <<Your MailChimp API Key>>
LIST_ID = <<Your List Key>>
api = mailchimp.Mailchimp(API_KEY)
api.lists.subscribe(LIST_ID, {'email': 'xyz@gmail.com'})

Full Tutorial on this Topic: https://djangopy.org/package-of-week/how-to-integrate-mailchimp-on-django-to-increase-subscribers/


问:
Best practice for running a daily Python screen-scraping script 50 times (8.3 minutes total) per user?
On the front-end, I have a PHP webapp that allows users to create a list of their websites (5 max).

On the back-end, a Python script runs daily (and has ~10 iterations) for each website that the user registers. Each script per website takes about 10 seconds to run through all iterations and finish its scraping. It then makes a CSV file with its findings.

So, in total, that's up to (5 websites * 10 iterations =) 50 iterations at 8.3 total minutes per user.

Right now, the script works when I manually feed it a URL, so I'm wondering how to make it dynamically part of the webapp.

How do I programmatically add and remove scripts that run daily depending on the number of users and the websites each user has each day?

How would I schedule this script to run for each website of each user, passing in the appropriate parameters?

I'm somewhat acquainted with cronjobs, as it's the only thing I know of that is made for routine processes.

答:
You can make the PHP app place the URLs into a database (MySQL, Sqlite, etc.) or text file.  Then, loop through the database/text file in your Python script.  Use Cron to run the Python script every day.

There are lots of resources for learning the Cron syntax:

http://google.com/search?q=cron+tutorial


问:
How to check if there is an item in an array that exists in another array?
I have the following React code that I want to use to disable a button:

```<code>todos.filter(todo => todo.completed === true)
  .map(todo => todo.id)
  .includes(this.state.checkedIds)
</code>```

My problem is it always returns false. I want to compare two arrays here. If there is an item present in both arrays of this.state.checkedIds and todo.ids it should return true or else false.

答:
You can just use a simple loop for this:

```<code>function arraysIntersect(arr1, arr2) {
    for (var i = 0; i < arr1.length; ++i) {
        if (arr2.includes(arr1[i])) return true;
    }
    return false;
}
</code>```

I assume state.checkedIds is an array. If that's true, your code doesn't work because you are checking whether your filtered and mapped todos include checkedIds (which it doesn't) instead of checking whether it includes any of the elements of the array checkedIds (which it might).

You can use my code like this:

```<code>var doneTodoIds = todos.filter(todo => todo.completed === true ).map( todo => todo.id).includes(this.state.checkedIds);
var result = arraysIntersect(doneTodoIds, this.state.checkedIds);
</code>```

You could also solve this with a higher level data structure (Alejandro's suggestion), but that might not be necessary (depending on the context of your code fragment).

Body:
I have the following React code that I want to use to disable a button:

todos.filter(todo => todo.completed === true)
  .map(todo => todo.id)
  .includes(this.state.checkedIds)

My problem is it always returns false. I want to compare two arrays here. If there is an item present in both arrays of this.state.checkedIds and todo.ids it should return true or else false.

Body:
You can just use a simple loop for this:

function arraysIntersect(arr1, arr2) {
    for (var i = 0; i < arr1.length; ++i) {
        if (arr2.includes(arr1[i])) return true;
    }
    return false;
}

I assume state.checkedIds is an array. If that's true, your code doesn't work because you are checking whether your filtered and mapped todos include checkedIds (which it doesn't) instead of checking whether it includes any of the elements of the array checkedIds (which it might).

You can use my code like this:

var doneTodoIds = todos.filter(todo => todo.completed === true ).map( todo => todo.id).includes(this.state.checkedIds);
var result = arraysIntersect(doneTodoIds, this.state.checkedIds);

You could also solve this with a higher level data structure (Alejandro's suggestion), but that might not be necessary (depending on the context of your code fragment).


问:
Start a detached background process in PowerShell
I have a Java program which I would like to launch as a background process from a PowerShell script, similar to the way a daemon runs on Linux.  The PowerShell script needs to do a couple of things:

Run the program as a separate and detached process in the background, meaning the parent window can be closed and the process keeps running.

Redirect the program's standard output and standard error to files.

Save the PID of the background process to a file so it can be terminated later by another script.

I have a shell script on Linux which starts the program like so:

```<code>$ java -jar MyProgram.jar >console.out 2>console.err &
</code>```

I'm hoping to replicate the same behavior on Windows using a PowerShell script.  I have tried using Start-Process with various combinations of options, as well as creating System.Diagnostics.ProcessStartInfo and System.Diagnostics.Process objects, but so far I am not having any luck.  PowerShell starts the program as a background process, but the program abruptly terminates when the DOS window which started the PowerShell session is closed.  I would like it to start in the background and be independent of the command window which started it.

The output redirection has also been troublesome, as it seems that the output and error streams can only be redirected in the process is being run in the same window (e.g., using -NoNewWindow).

Is this sort of thing possible in PowerShell?

答:
This is an old post but since I have it working fine thought it might help to share. Its the call to 'java' instead of 'javaw' that is likely your issue. Ran it out myself using my JEdit java program through powershell to launch it.

```<code>#Requires -Version 3.0
$MyDriveRoot = (Get-Location).Drive.Root
$JEditDir = $($mydriveroot + "jEdit") ;# Should be C:\jEdit or wherever you want. JEdit is a sub-directory.
$jEdit = $($JEditDir + "\jedit.jar" )
$jEditSettings = $($JEditDir + "\settings")
$JEditLogs = $($JEditDir + "\logs")

Start-Process -FilePath javaw -ArgumentList ( '-jar',"$jEdit", '-settings="$JEditSettings"' ) -RedirectStandardOutput "$JEditLogs\console.out" -RedirectStandardError "$JEditLogs\console.err"
</code>```

Which you can turn into a little function and then an alias to make it easy to launch in Powershell.

```<code>If ( ( Test-Path $jedit) ) {
    Function Start-JEdit() {
        Start-Process -FilePath javaw -ArgumentList ( '-jar',"$jEdit", '-settings="$($mydriveroot + "jEdit\settings")"' ) -RedirectStandardOutput "$JEditLogs\console.out" -RedirectStandardError "$JEditLogs\console.err"
    }
New-Alias -Name jedit  -Force Start-JEdit  -Description "Start JEdit programmers text editor"
}
</code>```

Body:
I have a Java program which I would like to launch as a background process from a PowerShell script, similar to the way a daemon runs on Linux.  The PowerShell script needs to do a couple of things:

Run the program as a separate and detached process in the background, meaning the parent window can be closed and the process keeps running.

Redirect the program's standard output and standard error to files.

Save the PID of the background process to a file so it can be terminated later by another script.

I have a shell script on Linux which starts the program like so:

$ java -jar MyProgram.jar >console.out 2>console.err &

I'm hoping to replicate the same behavior on Windows using a PowerShell script.  I have tried using Start-Process with various combinations of options, as well as creating System.Diagnostics.ProcessStartInfo and System.Diagnostics.Process objects, but so far I am not having any luck.  PowerShell starts the program as a background process, but the program abruptly terminates when the DOS window which started the PowerShell session is closed.  I would like it to start in the background and be independent of the command window which started it.

The output redirection has also been troublesome, as it seems that the output and error streams can only be redirected in the process is being run in the same window (e.g., using -NoNewWindow).

Is this sort of thing possible in PowerShell?

Body:
This is an old post but since I have it working fine thought it might help to share. Its the call to 'java' instead of 'javaw' that is likely your issue. Ran it out myself using my JEdit java program through powershell to launch it.

#Requires -Version 3.0
$MyDriveRoot = (Get-Location).Drive.Root
$JEditDir = $($mydriveroot + "jEdit") ;# Should be C:\jEdit or wherever you want. JEdit is a sub-directory.
$jEdit = $($JEditDir + "\jedit.jar" )
$jEditSettings = $($JEditDir + "\settings")
$JEditLogs = $($JEditDir + "\logs")

Start-Process -FilePath javaw -ArgumentList ( '-jar',"$jEdit", '-settings="$JEditSettings"' ) -RedirectStandardOutput "$JEditLogs\console.out" -RedirectStandardError "$JEditLogs\console.err"

Which you can turn into a little function and then an alias to make it easy to launch in Powershell.

If ( ( Test-Path $jedit) ) {
    Function Start-JEdit() {
        Start-Process -FilePath javaw -ArgumentList ( '-jar',"$jEdit", '-settings="$($mydriveroot + "jEdit\settings")"' ) -RedirectStandardOutput "$JEditLogs\console.out" -RedirectStandardError "$JEditLogs\console.err"
    }
New-Alias -Name jedit  -Force Start-JEdit  -Description "Start JEdit programmers text editor"
}


问:
Powershell force 5 digit format in a string pattern
So what I have now will (below) will search for XX-##-# and force it to XX-##-#0000.

How can I do this to return XX-##-0000#?

Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##, XX-##-###, XX-##-####)? As opposed to copying this 4 times, slightly adjusting for each.

```<code>$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ |
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) |
     Set-Content $_
}
</code>```

Thanks.

EDIT: I would like to do the following

```<code>Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####
</code>```

答:
Unfortunately, PowerShell's -replace operator doesn't support passing an expression (script block) as the replacement string, which a succinct solution would require here.

However, you can use the appropriate [regex] .NET type's .Replace() method overload:

Note: This solution focuses just on the regex-based replacement part, but it's easy to embed it into the larger pipeline from the question.

```<code># Define sample array.
$lines = @'
Line 1 AB-00-0 and also AB-01-1
Line 2 CD-02-22 after
Line 3 EF-03-333 it
Line 4 GH-04-4444 goes
Line 5 IJ-05-55555 on
'@ -split "`n"

# Loop over lines...
$lines | ForEach-Object {
  # ... and use a regex with 2 capture groups to capture the substrings of interest
  #     and use a script block to piece them together with number padding
  #     applied to the 2nd group
  ([regex] '\b([a-zA-Z]{2}-[0-9]{2}-)([0-9]+)').Replace($_, {
    param($match)
    $match.Groups[1].Value + '{0:D5}' -f [int] $match.Groups[2].Value
  })
}
</code>```

The above yields:

```<code>Line 1 AB-00-00000 and also AB-01-00001
Line 2 CD-02-00022 after
Line 3 EF-03-00333 it
Line 4 GH-04-04444 goes
Line 5 IJ-05-55555 on
</code>```

Body:
So what I have now will (below) will search for XX-##-# and force it to XX-##-#0000.

How can I do this to return XX-##-0000#?

Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##, XX-##-###, XX-##-####)? As opposed to copying this 4 times, slightly adjusting for each.

$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ |
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) |
     Set-Content $_
}

Thanks.

EDIT: I would like to do the following

Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####

Body:
Unfortunately, PowerShell's -replace operator doesn't support passing an expression (script block) as the replacement string, which a succinct solution would require here.

However, you can use the appropriate [regex] .NET type's .Replace() method overload:

Note: This solution focuses just on the regex-based replacement part, but it's easy to embed it into the larger pipeline from the question.

# Define sample array.
$lines = @'
Line 1 AB-00-0 and also AB-01-1
Line 2 CD-02-22 after
Line 3 EF-03-333 it
Line 4 GH-04-4444 goes
Line 5 IJ-05-55555 on
'@ -split "`n"

# Loop over lines...
$lines | ForEach-Object {
  # ... and use a regex with 2 capture groups to capture the substrings of interest
  #     and use a script block to piece them together with number padding
  #     applied to the 2nd group
  ([regex] '\b([a-zA-Z]{2}-[0-9]{2}-)([0-9]+)').Replace($_, {
    param($match)
    $match.Groups[1].Value + '{0:D5}' -f [int] $match.Groups[2].Value
  })
}

The above yields:

Line 1 AB-00-00000 and also AB-01-00001
Line 2 CD-02-00022 after
Line 3 EF-03-00333 it
Line 4 GH-04-04444 goes
Line 5 IJ-05-55555 on


问:
Run Search on Webpage Dynamically
I'm trying to dynamically submit a search form on BBB (Better Business Bureau) then load the results as if you were to go to the web page and enter the search criteria yourself. So far I dont have much, but...

```<code>$.post('https://www.bbb.org/search/', {input:"car", location:"New York, NY"}, function(data){ $( "#results" ).empty().append( data ); });
</code>```

Basically I send the input and location and attempt the load the results in to a div container. I can load the results in to the current page OR just re-route to the page that would load had you manually ran the search. Any ideas on how to do this? I know pages like youtube have search api's for developers but BBB does not (to my knowledge)

答:
You can form the query string for the main search page with "input" and "location". e.g for input : "car" and location : "New York, NY" query strings looks like this

```<code>queryString = type=name&input=car&location=New York,NY&tobid=&filter=business&source=bbbse&default-source=bbbad&radius=&country=&language=&codeType="
</code>```

append this query string to the url. "https://www.bbb.org/search/?" + queryString

which is equivalent to https://www.bbb.org/search/?type=name&input=car&location=New+York%2C+NY&tobid=&filter=combined&source=bbbse&default-source=bbbad&radius=&country=USA&language=en&codeType=YPPA

Now you can set browser window.location (javascript) equal to above url which will route you to desired page with search results.

Title: Run Search on Webpage Dynamically

Body:
I'm trying to dynamically submit a search form on BBB (Better Business Bureau) then load the results as if you were to go to the web page and enter the search criteria yourself. So far I dont have much, but...

$.post('https://www.bbb.org/search/', {input:"car", location:"New York, NY"}, function(data){ $( "#results" ).empty().append( data ); });

Basically I send the input and location and attempt the load the results in to a div container. I can load the results in to the current page OR just re-route to the page that would load had you manually ran the search. Any ideas on how to do this? I know pages like youtube have search api's for developers but BBB does not (to my knowledge)

Body:
You can form the query string for the main search page with "input" and "location". e.g for input : "car" and location : "New York, NY" query strings looks like this

queryString = type=name&input=car&location=New York,NY&tobid=&filter=business&source=bbbse&default-source=bbbad&radius=&country=&language=&codeType="

append this query string to the url. "https://www.bbb.org/search/?" + queryString

which is equivalent to https://www.bbb.org/search/?type=name&input=car&location=New+York%2C+NY&tobid=&filter=combined&source=bbbse&default-source=bbbad&radius=&country=USA&language=en&codeType=YPPA

Now you can set browser window.location (javascript) equal to above url which will route you to desired page with search results.


问:
How to test a web service with different configurations?
I want to automatically test http://localhost/api.ashx.

api.ashx reads configurations from web.config and acts differently.

For example one key is AllowDuplicatedQueryParameter. If web.config has

<appSettings>
  <add key="AllowDuplicatedQueryParameter" value="false" />
</appSettings>
```

requesting to http://localhost/api.ashx?name=hello&name=world will throw error.

How do I have an automated test that tests different configurations, namely when AllowDuplicatedQueryParameter=true and AllowDuplicatedQueryParameter=false?

答:
It depends a bit on what kind of automated testing you want to do. Under the circumstances, unit testing or integration testing against a in-process version of your application seems like it would make sense.

Your best option in these cases is to abstract the reading of the configuration into a class that can be mocked. For example, imagine the configuration you change is in your AppSettings you might do something similar to this

```<code>public interface IConfigurationWrapper
{
    string GetAppSetting(string key);
}

public class ConfigurationWrapper : IConfigurationWrapper
{
     public string GetAppSetting(string key)
     {
         return ConfigurationManager.AppSettings[key]
     }
}
</code>```

Your components should take a dependency on an

IConfigurationWrapper, and use it whenever you need to access configuration to determine behavior. In your test, you can use a mocking library like Moq or NSubstitute, or roll your own stub implementation of the IConfigurationWrapper and use that to controll the behavior of the system under test, like this:

```<code>public class MyThingDoer
{
    public MyThingDoer(IConfigurationWrapper config)
    {
         _config = config
    }

    public string SaySomething()
    {
        var thingToSay = _config.GetAppSetting("ThingToSay");
        return thingToSay;
    }
}
</code>```

And then in your test

```<code>[Fact]
public void ThingDoerSaysWhatConfigTellsItToSay()
{
    var configWrapper = new FakeConfigWrapper(thingToSay:"Hello");
    var doer = new MyThingDoer(configWrapper);
    Assert.Equal("Hello", doer.SaySomething());
}
</code>```

Obviously that's a toy example, but it should get at the basic idea. Write an abstraction around the external dependency, then stub the dependency.

Body:
I want to automatically test http://localhost/api.ashx.

api.ashx reads configurations from web.config and acts differently.

For example one key is AllowDuplicatedQueryParameter. If web.config has

<appSettings>
  <add key="AllowDuplicatedQueryParameter" value="false" />
</appSettings>

requesting to http://localhost/api.ashx?name=hello&name=world will throw error.

How do I have an automated test that tests different configurations, namely when AllowDuplicatedQueryParameter=true and AllowDuplicatedQueryParameter=false?

Body:
It depends a bit on what kind of automated testing you want to do. Under the circumstances, unit testing or integration testing against a in-process version of your application seems like it would make sense.

Your best option in these cases is to abstract the reading of the configuration into a class that can be mocked. For example, imagine the configuration you change is in your AppSettings you might do something similar to this

public interface IConfigurationWrapper
{
    string GetAppSetting(string key);
}

public class ConfigurationWrapper : IConfigurationWrapper
{
     public string GetAppSetting(string key)
     {
         return ConfigurationManager.AppSettings[key]
     }
}

Your components should take a dependency on an

IConfigurationWrapper, and use it whenever you need to access configuration to determine behavior. In your test, you can use a mocking library like Moq or NSubstitute, or roll your own stub implementation of the IConfigurationWrapper and use that to controll the behavior of the system under test, like this:

public class MyThingDoer
{
    public MyThingDoer(IConfigurationWrapper config)
    {
         _config = config
    }

    public string SaySomething()
    {
        var thingToSay = _config.GetAppSetting("ThingToSay");
        return thingToSay;
    }
}

And then in your test

[Fact]
public void ThingDoerSaysWhatConfigTellsItToSay()
{
    var configWrapper = new FakeConfigWrapper(thingToSay:"Hello");
    var doer = new MyThingDoer(configWrapper);
    Assert.Equal("Hello", doer.SaySomething());
}

Obviously that's a toy example, but it should get at the basic idea. Write an abstraction around the external dependency, then stub the dependency.


问:
Can I put a src attribute in an i or span tag?
On my website in my footer I have a bunch of font awesome icons that lead to my profiles on different social media site. I have also created a modal on my webpage that when you click on an image it basically focuses in on it. So my idea was users can click on the Snapchat icon and my Snapcode would pop up so that users can get it. Unlike normal social media, Snapchat does not use URL links in order to find a user profile. Below is the line of code I have written I will also leave a link to my site so that you can see the problem I am having.

```<code><i class="fa fa-snapchat w3-hover-text-yellow" src="apps/images/snapchat.png" onclick="onClick(this);" class="w3-hover-opacity"></i>
</code>```

My question is, Is it possible to do something like this? I can get my function to work properly I just can't figure out how to hide the image so that it is only visible when the user clicks on the link.

I have also tried something like this with still no avail. The toggleFunction() just changes the class name from w3-hide to w3-show and works fine with other elements.

```<code><i class="fa fa-snapchat w3-hover-text-yellow">
<img src="apps/images/snapchat.png" class="w3-hide" style="width:100%" onclick="toggleFunction();onClick(this);" class="w3-hover-opacity" alt="">
</i>
</code>```

If anyone could help me out it would be greatly appreciated. The problem gives me an undefined error whenever you click on the Snapchat icon.

Here is a link to the page. It is in the footer. Snapchat icon.

Nerdislander.com

答:
Data-src attribute is the answer. A big thank you goes out to @Yulio for pointing it out.

I modified the code slightly as well as modified my existing function.

```<code><i class="fa fa-snapchat w3-hover-text-yellow" data-src="apps/images/snapchat.png" onclick="onClick2(this);" class="w3-hover-opacity" data-alt="Take a snap of my snapcode to add me on Snapchat!"></i>
</code>```

Next I changed my onClick function to look for dataset.* instead of using src which looks like this

```<code>function onClick(element) {
document.getElementById("img01").src = element.src;
document.getElementById("modal01").style.display = "block";
var captionText = document.getElementById("caption");
captionText.innerHTML = element.alt;
}

function onClick2(element) {
document.getElementById("img01").src = element.dataset.src;
document.getElementById("modal01").style.display = "block";
var captionText = document.getElementById("caption");
captionText.innerHTML = element.dataset.alt;
}
</code>```

Body:
On my website in my footer I have a bunch of font awesome icons that lead to my profiles on different social media site. I have also created a modal on my webpage that when you click on an image it basically focuses in on it. So my idea was users can click on the Snapchat icon and my Snapcode would pop up so that users can get it. Unlike normal social media, Snapchat does not use URL links in order to find a user profile. Below is the line of code I have written I will also leave a link to my site so that you can see the problem I am having.

My question is, Is it possible to do something like this? I can get my function to work properly I just can't figure out how to hide the image so that it is only visible when the user clicks on the link.

I have also tried something like this with still no avail. The toggleFunction() just changes the class name from w3-hide to w3-show and works fine with other elements.

If anyone could help me out it would be greatly appreciated. The problem gives me an undefined error whenever you click on the Snapchat icon.

Here is a link to the page. It is in the footer. Snapchat icon.

Nerdislander.com

Body:
Data-src attribute is the answer. A big thank you goes out to @Yulio for pointing it out.

I modified the code slightly as well as modified my existing function.

<i class="fa fa-snapchat w3-hover-text-yellow" data-src="apps/images/snapchat.png" onclick="onClick2(this);" class="w3-hover-opacity" data-alt="Take a snap of my snapcode to add me on Snapchat!"></i>

Next I changed my onClick function to look for dataset.* instead of using src which looks like this

function onClick(element) {
document.getElementById("img01").src = element.src;
document.getElementById("modal01").style.display = "block";
var captionText = document.getElementById("caption");
captionText.innerHTML = element.alt;
}

function onClick2(element) {
document.getElementById("img01").src = element.dataset.src;
document.getElementById("modal01").style.display = "block";
var captionText = document.getElementById("caption");
captionText.innerHTML = element.dataset.alt;
}


问:
Convert PDF to byte array and viceversa android
I'm trying to create an Android app able to upload and download PDF files to a server, I've already included in my code a method able to download a PDF from an URL such as "http://www.aaaa.com/myfile.pdf" and display it by using intent.
But I want to know if there is a way to encode a Pdf into a byte array and viceversa decode a byte array to PDF file (I'm using mongoDB)
Thanks to everyone :)</p>

答:
```<code>import java.nio.file.*;

Path pdfFilePath = Paths.get("/file/path/your_file.pdf");

// Read file to byte array
byte[] pdfByteArray = Files.readAllBytes(pdfFilePath );

// Write byte array to file
Files.write(pdfFilePath , pdfByteArray);
</code>```