问:
I am looking for some ideas building a product selector in jQuery
I am building a product selector and this time around I would like to build a best practice so I am curious to see what other devs think is best approach. I have a product category selector that populates a product selector.

I don't want the product selector to show until a category is picked

I don't want the product selector to show if the category has only 1
product

I wan't to assign the product ID to be assigned to a var if one of
the above conditions are met.

I considered using CSS to hide the second element or, generating dynamically in JS. I created a fiddle also. Any input would be appreciated.

https://jsfiddle.net/simplymarkb/oa4xf2zg/

```<code><label for="category" class="label">Category:</label>
    <select id="category" class="inputSelector" name="category" data-field-name="category">
    <option value="0">Select Category...</option>
</select><br><br>
<label for="productname" class="label">Product:</label>
    <select id="productname" class="inputSelector" name="productname" data-field-name="productname">
    <option value="0">Select Product...</option>
</select>

<script>
let json = [{
      "Identifier": "LOC005",
      "Category": "Soft Drink",
      "Product": "Mountain Dew",
      "ProductID": "mdew-23984987"
    },
    {
      "Identifier": "LOC005",
      "Category": "Side Dish",
      "Product": "Brown Rice",
      "ProductID": "rice-3434333"
    },
    {
      "Identifier": "LOC005",
      "Category": "Side Dish",
      "Product": "Noodles",
      "ProductID": "noodle-46ss333"
    },
    {
      "Identifier": "LOC005",
      "Category": "Soft Drink",
      "Product": "Sprite",
      "ProductID": "sprite-038033"
    },
    {
      "Identifier": "LOC005",
      "Category": "Pie",
      "Product": "Key Lime",
      "ProductID": "kl-39637623"
    },
    {
      "Identifier": "LOC005",
      "Category": "Pie",
      "Product": "Pumpkin",
      "ProductID": "pm-373768534"
    },
    {
      "Identifier": "LOC005",
      "Category": "Soft Drink",
      "Product": "Pepsi",
      "ProductID": "pepsi-39784862"
    },
    {
      "Identifier": "LOC005",
      "Category": "Soft Drink",
      "Product": "Dr. Pepper",
      "ProductID": "drpep-r34872"
    },
    {
      "Identifier": "LOC005",
      "Category": "Pie",
      "Product": "Blueberry",
      "ProductID": "bl-pie00012"
    },
    {
      "Identifier": "LOC005",
      "Category": "Pie",
      "Product": "Apple",
      "ProductID": "ap-pie9838732"
    },
    {
      "Identifier": "LOC005",
      "Category": "Soft Drink",
      "Product": "Coke",
      "ProductID": "coke-0e4801"
    },
    {
      "Identifier": "LOC005",
      "Category": "Pie",
      "Product": "Cherry",
      "ProductID": "ch-pie948001"
    }]

const prodCategory = [... new Set(json.map(data => data.Category))]
$.each(prodCategory, function(index, value) {
  $("#category").append("<option class='rsource' value='"+value+"'>"+value+"</option>");
});

$("#category").change(function(){
  $("#productname").empty();
  var selValue = $(this).val();
  let obj = json.filter(item => item.Category === selValue);
  let productval = obj.filter(item => item.Product);
  let prodcount = productval.length;

    // -- I only want to display the product selector if the category has more than one product
  if( prodcount !== 1 ){
  $.each(obj , function(index, item) {
    var Product = item.Product;
    var ProductID = item.ProductID;
    $("#productname").append("<option value='"+ProductID+"'>"+Product+"</option>");
  });
  } else {
    // something else
  }
});
</script>

</code>```

答:
Here is the answer: https://jsfiddle.net/83gzbxur/5/

Product selector is hidden on start.

Product selector is shown only when conditions are met.

When Product selector is shown, and user select a value, the value can be retrieved and use.

// ... (full code is in the fiddle)
// changes are made as follows

  $("#category").change(function(){
    // ...
    $("#selectedProduct").text('--')
    // ...
  })

  if( prodcount > 1 ){
    $("#products").show()
    // ...
  }else{
    $("#products").hide()
  }

  $("#productname").change(function(){
    $("#selectedProduct").text($("#productname").val())
  })

// ...
```

Body:
I am building a product selector and this time around I would like to build a best practice so I am curious to see what other devs think is best approach. I have a product category selector that populates a product selector.

I don't want the product selector to show until a category is picked

I don't want the product selector to show if the category has only 1
product

I wan't to assign the product ID to be assigned to a var if one of
the above conditions are met.

I considered using CSS to hide the second element or, generating dynamically in JS. I created a fiddle also. Any input would be appreciated.

https://jsfiddle.net/simplymarkb/oa4xf2zg/

Category:
    <select id="category" class="inputSelector" name="category" data-field-name="category">
    <option value="0">Select Category...</option>
</select>

Product:
    <select id="productname" class="inputSelector" name="productname" data-field-name="productname">
    <option value="0">Select Product...</option>
</select>


来源: stackexchange

问:
How to resize an image without loading into memory?
I'd like to check the dimensions of an image, and then size it down if the width exceeds a given threshold.  When I load a 6MB JPEG image with ImageIO.read(), the BufferedImage allocates about 45MB of heap space.  Is there a way to do a passthrough image resize without loading all the data into memory?  I tried passing ImageIO.read() a File object, thinking it would stream the data from disk, but it doesn't help.</p>

答: You can use ImageInfo to check the width and height of the image without loading it into memory. I do not know of a library that will allow you to re-size without loading the image in memory. 45MB is not all that much memory really. Can you just increase your heap size?  </p>

ContentLicense: CC BY-SA 3.0


问:
How to toggle classes with with Gatsby link
I am using Gatsby and Bulma css.

I can't toggle the classes on the 'navMenu' and get the to navigation (visual) change in accordance to device screen size. The changes will effect the 'a' element, but not the corresponding 'navMenu' element. The 'a' element will change the 'burger' icon to a 'cross' icon which is expected.

Here is my code

```<code>    <nav className="navbar" role="navigation" aria-label="main navigation">
      <div className="navbar-brand">
        <a href="#"
          role="button"
          className={`navbar-burger burger ${isActive? ' is-active' : ' '}`} onClick={()=> {isActive = !isActive}}
          aria-label="menu"
          data-target="navMenu"
          aria-expanded="true"
        >
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
        </a>
      </div>

      <div  id="navMenu" className="navbar-menu">
        <div className="navbar-start">
          <a className="navbar-item">Home</a>

          <a className="navbar-item">Documentation</a>

          <div className="navbar-item has-dropdown is-hoverable">
            <a className="navbar-link">More</a>

            <div className="navbar-dropdown">
              <a className="navbar-item">About</a>
              <a className="navbar-item">Jobs</a>
              <a className="navbar-item">Contact</a>
              <hr lass="navbar-divider"></hr>
              <a className="navbar-item">Report an issue</a>
            </div>
          </div>
        </div>

        <div className="navbar-end">
          <div className="navbar-item">
            <div className="buttons">
              <a className="button is-primary">
                <strong>Sign up</strong>
              </a>
              <a className="button is-light">Log in</a>
            </div>
          </div>
        </div>
      </div>
    </nav>
</code>```

I would like the 'navMenu' to show up whenever the onClick event is raised.

Thanks

答:
this should works :

```<code>import React, { Component } from "react";
import "./style.scss";

class Navbar extends Component {
  constructor(props) {
    super(props);
    this.state = { active: false };
  }
  handleClick = () => {
    this.setState({ active: !this.state.active });
   };
render() {

 return (
  <nav className="navbar" role="navigation" aria-label="main navigation">
    <div className="navbar-brand">
      <a className="navbar-item" href="https://bulma.io">
        <img
          src="https://bulma.io/images/bulma-logo.png"
          style={{ width: "112", height: "28" }}
          alt=""
        />
      </a>

      <span
        role="button"
        className={
          "navbar-burger burger " + (this.state.active ? "is-active" : "")
        }
        aria-label="menu"
        aria-expanded="false"
        data-target="navbarBasicExample"
        onClick={this.handleClick}
      >
        <span aria-hidden="true"></span>
        <span aria-hidden="true"></span>
        <span aria-hidden="true"></span>
      </span>
    </div>
    <div
      id="navbarBasicExample"
      className={"navbar-menu " + (this.state.active ? "is-active" : "")}
    >
      <div className="navbar-start">
        <a className="navbar-item">Home</a>

        <a className="navbar-item">Documentation</a>

        <div className="navbar-item has-dropdown is-hoverable">
          <a className="navbar-link">More</a>

          <div className="navbar-dropdown">
            <a className="navbar-item">About</a>
            <a className="navbar-item">Jobs</a>
            <a className="navbar-item">Contact</a>
            <hr className="navbar-divider" />
            <a className="navbar-item">Report an issue</a>
          </div>
        </div>
      </div>

      <div className="navbar-end">
        <div className="navbar-item">
          <div className="buttons">
            <a className="button is-primary">
              <strong>Sign up</strong>
            </a>
            <a className="button is-light">Log in</a>
          </div>
        </div>
      </div>
    </div>
  </nav>
    );
  }
}

export default Navbar;
</code>```

Example on codesandbox.io : https://codesandbox.io/s/bulma-reactjs-toggle-menu-hxux4

ContentLicense: CC BY-SA 4.0

Body:
I am using Gatsby and Bulma css.

I can't toggle the classes on the 'navMenu' and get the to navigation (visual) change in accordance to device screen size. The changes will effect the 'a' element, but not the corresponding 'navMenu' element. The 'a' element will change the 'burger' icon to a 'cross' icon which is expected.

Here is my code

        <a href="#"
          role="button"
          className={`navbar-burger burger ${isActive? ' is-active' : ' '}`} onClick={()=> {isActive = !isActive}}
          aria-label="menu"
          data-target="navMenu"
          aria-expanded="true"
        >

          Home

          Documentation

            More

              About
              Jobs
              Contact

              Report an issue

                Sign up

              Log in

I would like the 'navMenu' to show up whenever the onClick event is raised.

Thanks

Body:
this should works :

import React, { Component } from "react";
import "./style.scss";

class Navbar extends Component {
  constructor(props) {
    super(props);
    this.state = { active: false };
  }
  handleClick = () => {
    this.setState({ active: !this.state.active });
   };
render() {

 return (
  <nav className="navbar" role="navigation" aria-label="main navigation">
    <div className="navbar-brand">
      <a className="navbar-item" href="https://bulma.io">
        <img
          src="https://bulma.io/images/bulma-logo.png"
          style={{ width: "112", height: "28" }}
          alt=""
        />
      </a>

      <span
        role="button"
        className={
          "navbar-burger burger " + (this.state.active ? "is-active" : "")
        }
        aria-label="menu"
        aria-expanded="false"
        data-target="navbarBasicExample"
        onClick={this.handleClick}
      >
        <span aria-hidden="true"></span>
        <span aria-hidden="true"></span>
        <span aria-hidden="true"></span>
      </span>
    </div>
    <div
      id="navbarBasicExample"
      className={"navbar-menu " + (this.state.active ? "is-active" : "")}
    >
      <div className="navbar-start">
        <a className="navbar-item">Home</a>

        <a className="navbar-item">Documentation</a>

        <div className="navbar-item has-dropdown is-hoverable">
          <a className="navbar-link">More</a>

          <div className="navbar-dropdown">
            <a className="navbar-item">About</a>
            <a className="navbar-item">Jobs</a>
            <a className="navbar-item">Contact</a>
            <hr className="navbar-divider" />
            <a className="navbar-item">Report an issue</a>
          </div>
        </div>
      </div>

      <div className="navbar-end">
        <div className="navbar-item">
          <div className="buttons">
            <a className="button is-primary">
              <strong>Sign up</strong>
            </a>
            <a className="button is-light">Log in</a>
          </div>
        </div>
      </div>
    </div>
  </nav>
    );
  }
}

export default Navbar;

Example on codesandbox.io : https://codesandbox.io/s/bulma-reactjs-toggle-menu-hxux4


问:
PowerShell Install-Module Local vs CurrentUser
Could someone explain this please?

```<code>Import-Module PSReadLine -Scope CurrentUser

Import-Module : Cannot validate argument on parameter 'Scope'.
The argument "CurrentUser" does not belong to the set "Local,Global"
specified by the ValidateSet attribute. Supply an argument that is in the
set and then try the command again.
At line:1 char:37
+     Import-Module PSReadLine -Scope CurrentUser
+                                     ~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Import-Module], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportModuleCommand
</code>```

But this works fine(!)

```<code>Install-Module PSScriptAnalyzer -Scope CurrentUser
</code>```

And this works fine(!)

```<code>Import-Module PSReadLine -Scope Local
</code>```

The help file for Install-Module doesn't even recognise the existence of Local|Global mentioned in the error. -Scope <String> Specifies the installation scope of the module. The acceptable values for this parameter are AllUsers and CurrentUser.

答:
These scopes differ substantially (excerpted from official learn.microsoft.com):

Import-Module -Scope

Specifies a scope into which this cmdlet imports the module.

The acceptable values for this parameter are:

Global. Available to all commands in the session. Equivalent to the Global parameter.

Local. Available only in the current scope.

By default, when Import-Module cmdlet is called from the command
  prompt, script file, or scriptblock, all the commands are imported
  into the global session state. You can use the -Scope parameter with
  the value of Local to import module content into the script or
  scriptblock scope.

When invoked from another module, Import-Module cmdlet imports the
  commands in a module, including commands from nested modules, into the
  caller's session state. Specifying -Scope Global or -Global indicates
  that this cmdlet imports modules into the global session state so they
  are available to all commands in the session.

Install-Module -Scope

Specifies the installation scope of the module. The acceptable
  values for this parameter are AllUsers and CurrentUser.

The AllUsers scope installs modules in a location that is
  accessible to all users of the computer:

```<code>$env:ProgramFiles\PowerShell\Modules
</code>```

The CurrentUser installs modules in a location that is accessible
  only to the current user of the computer:

```<code>$home\Documents\PowerShell\Modules
</code>```

When no Scope is defined, the default is set based on the
  PowerShellGet version.

In PowerShellGet versions 2.0.0 and above, the default is CurrentUser, which does not require elevation for install.

In PowerShellGet 1.x versions, the default is AllUsers, which requires elevation for install.

Body:
Could someone explain this please?

Import-Module PSReadLine -Scope CurrentUser

Import-Module : Cannot validate argument on parameter 'Scope'.
The argument "CurrentUser" does not belong to the set "Local,Global"
specified by the ValidateSet attribute. Supply an argument that is in the
set and then try the command again.
At line:1 char:37
+     Import-Module PSReadLine -Scope CurrentUser
+                                     ~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Import-Module], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportModuleCommand

But this works fine(!)

Install-Module PSScriptAnalyzer -Scope CurrentUser

And this works fine(!)

Import-Module PSReadLine -Scope Local

The help file for Install-Module doesn't even recognise the existence of Local|Global mentioned in the error. -Scope <String> Specifies the installation scope of the module. The acceptable values for this parameter are AllUsers and CurrentUser.

Body:
These scopes differ substantially (excerpted from official learn.microsoft.com):

Import-Module -Scope

Specifies a scope into which this cmdlet imports the module.

The acceptable values for this parameter are:

Global. Available to all commands in the session. Equivalent to the Global parameter.

Local. Available only in the current scope.

By default, when Import-Module cmdlet is called from the command
  prompt, script file, or scriptblock, all the commands are imported
  into the global session state. You can use the -Scope parameter with
  the value of Local to import module content into the script or
  scriptblock scope.

When invoked from another module, Import-Module cmdlet imports the
  commands in a module, including commands from nested modules, into the
  caller's session state. Specifying -Scope Global or -Global indicates
  that this cmdlet imports modules into the global session state so they
  are available to all commands in the session.

Install-Module -Scope

Specifies the installation scope of the module. The acceptable
  values for this parameter are AllUsers and CurrentUser.

The AllUsers scope installs modules in a location that is
  accessible to all users of the computer:

$env:ProgramFiles\PowerShell\Modules

The CurrentUser installs modules in a location that is accessible
  only to the current user of the computer:

$home\Documents\PowerShell\Modules

When no Scope is defined, the default is set based on the
  PowerShellGet version.

In PowerShellGet versions 2.0.0 and above, the default is CurrentUser, which does not require elevation for install.

In PowerShellGet 1.x versions, the default is AllUsers, which requires elevation for install.


问:
Regex to validate a twitter url
I'm using the jQuery validation engine to parse my form data:
https://github.com/posabsolute/jQuery-Validation-Engine

What would be the regex to validate a twitter URL (including the http://twitter.com part) Eg:

```<code>http://twitter.com/barackobama
or
http://twitter.com/#!/barackobama
</code>```

答:
I'm not familiar with jQuery but if it uses standard regex it would be something like this:

```<code>http://twitter.com/(#!/)?[a-zA-Z0-9_]{1,15}
</code>```

This bit (#!/)? is to make the #!/ optional, and this [a-zA-Z0-9_]{1,15} is because Twitter usernames can contain letters (upper or lowercase), numbers and underscores and can be up to 15 characters in length.

Title: Regex to validate a twitter url

Body:
I'm using the jQuery validation engine to parse my form data:
https://github.com/posabsolute/jQuery-Validation-Engine

What would be the regex to validate a twitter URL (including the http://twitter.com part) Eg:

http://twitter.com/barackobama
or
http://twitter.com/#!/barackobama

Body:
I'm not familiar with jQuery but if it uses standard regex it would be something like this:

http://twitter.com/(#!/)?[a-zA-Z0-9_]{1,15}

This bit (#!/)? is to make the #!/ optional, and this [a-zA-Z0-9_]{1,15} is because Twitter usernames can contain letters (upper or lowercase), numbers and underscores and can be up to 15 characters in length.


问:
Difference between getter and a regular method in Dart
I'm just getting my feet wet with the BLoC architecture of Flutter. Here, I wish to create a Bloc class, which will help me to convert the user input in the form of stream data. To do that task, let's say that first of all I create an instance of Bloc class with the name email and then,

make use of snippet 0 & then call email.emailController.sink.add(some_string)

or, make use of snippet 1 and then call email.streamEmail(some_string)

or, make use of snippet 2 code and then call email.streamEmail(some_string)

to add a string input to the stream

Code snippets:

```<code>//Snippet 0 : w/o any `method`
class Bloc{
 final emailController = StreamController<String>();
}
</code>```
```<code>//Snippet 1 : using regular 'method'
class Bloc{
 final emailController = StreamController<String>();
 void streamEmail(String value) => emailController.sink.add(value);
}
</code>```
```<code>//Snippet 2 : using 'get' based 'method'
class Bloc{
 final emailController = StreamController<String>();
 Function(String) get streamEmail => emailController.sink.add;
}
</code>```

I learned that making use of snippet 1 or 2 is a rather better to approach, in terms of code readability.
I know that snippet 1& 2 are just 2 different ways of doing the same thing. However, I'm not clear about the differences that snippet 2 brings in, by making use of the getter method.

From A tour of the Dart language,

Getters and setters are special methods that provide read and write access to an object’s properties.

At the moment, the only thing I understand about getters is that they represent an alternative approach to define methods within a class. So, to be precise my questions are :

Does usage of a getter method lead to enhancement or drop in-app. performance?

When & why should I be using snippet 2 type class definitions instead of snippet 1?

答:
Does usage of a getter method lead enhancement or drop in app. performance?

No, using getter/setter instead of methods does not impact performance.

When & why should I be using snippet 2 type class definitions instead of snippet 1?

When to use getters/setters is a question about taste and some developers are more likely to use them than others. I guess a general design goal should be that getters/setters acts like normal properties on an object and should therefore not make any additional unknown behavior than getting/setting a property. (e.g. get a property of a objects will end up saving some files to the file system).

In your example I would go with snippet 1 (and maybe with a different name of the method) since your example is not really a good use case of using properties. Snippet 2 seems like a forced clever attempt to make use a getter which ends up being a little weird since the getter ends up returning a Function.

But again, this is a question about taste and I am sure there are some developers which would go with snippet 2.

Body:
I'm just getting my feet wet with the BLoC architecture of Flutter. Here, I wish to create a Bloc class, which will help me to convert the user input in the form of stream data. To do that task, let's say that first of all I create an instance of Bloc class with the name email and then,

make use of snippet 0 & then call email.emailController.sink.add(some_string)

or, make use of snippet 1 and then call email.streamEmail(some_string)

or, make use of snippet 2 code and then call email.streamEmail(some_string)

to add a string input to the stream

Code snippets:

//Snippet 0 : w/o any `method`
class Bloc{
 final emailController = StreamController<String>();
}

//Snippet 1 : using regular 'method'
class Bloc{
 final emailController = StreamController<String>();
 void streamEmail(String value) => emailController.sink.add(value);
}

//Snippet 2 : using 'get' based 'method'
class Bloc{
 final emailController = StreamController<String>();
 Function(String) get streamEmail => emailController.sink.add;
}

I learned that making use of snippet 1 or 2 is a rather better to approach, in terms of code readability.
I know that snippet 1& 2 are just 2 different ways of doing the same thing. However, I'm not clear about the differences that snippet 2 brings in, by making use of the getter method.

From A tour of the Dart language,

Getters and setters are special methods that provide read and write access to an object’s properties.

At the moment, the only thing I understand about getters is that they represent an alternative approach to define methods within a class. So, to be precise my questions are :

Does usage of a getter method lead to enhancement or drop in-app. performance?

When & why should I be using snippet 2 type class definitions instead of snippet 1?


问:
Constrain Button Programmatically To Bottom Center Of Tab Bar
I am building a tab bar with a prominent middle button for adding a post. The issue I'm running into is that my button fits well on iPhone 11 Pro Max but is not positioned correctly on other size iPhones (see images).

I think the issue is that I'm setting the Y position absolutely instead of relative to the tabBar. I am confused on how to do this since I am adding the button programmatically instead of through the storyboard (where I know how to use relative constraints). Here is where I am setting the position:

```<code>override func viewDidLayoutSubviews() {
    button.frame = CGRect.init(x: self.tabBar.center.x - 32, y: self.view.bounds.height - 115, width: 64, height: 64)
}
</code>```

How can I set a relative position programmatically for my button so it is always half above and half below the tab bar, regardless of phone size?

答:
try this

```<code>let tabBarHeight = 64
let mainButton: UIButton = UIButton(type: .custom)
mainButton.frame = CGRect(origin: CGPoint(x: 0.0, y: win.frame.size.height),size: CGSize(width: tabBarHeight, height: tabBarHeight))
mainButton.center = CGPoint(x: win.center.x, y: win.frame.size.height - tabBar.layer.bounds.height)
</code>```

you set the size and set the center of the button to the center of the TabBar or move a little up like this code do.

Body:
I am building a tab bar with a prominent middle button for adding a post. The issue I'm running into is that my button fits well on iPhone 11 Pro Max but is not positioned correctly on other size iPhones (see images).

I think the issue is that I'm setting the Y position absolutely instead of relative to the tabBar. I am confused on how to do this since I am adding the button programmatically instead of through the storyboard (where I know how to use relative constraints). Here is where I am setting the position:

override func viewDidLayoutSubviews() {
    button.frame = CGRect.init(x: self.tabBar.center.x - 32, y: self.view.bounds.height - 115, width: 64, height: 64)
}

How can I set a relative position programmatically for my button so it is always half above and half below the tab bar, regardless of phone size?

Body:
try this

let tabBarHeight = 64
let mainButton: UIButton = UIButton(type: .custom)
mainButton.frame = CGRect(origin: CGPoint(x: 0.0, y: win.frame.size.height),size: CGSize(width: tabBarHeight, height: tabBarHeight))
mainButton.center = CGPoint(x: win.center.x, y: win.frame.size.height - tabBar.layer.bounds.height)

you set the size and set the center of the button to the center of the TabBar or move a little up like this code do.


问:
Is there any way to pass parameters to a binded variable in Vue.JS with moustache syntax
Let's say i have an HTML of the form:

```<code><div>
  {{ GREETING_MESSAGE_FROM_TO }}
</div>
</code>```

And in my data:

```<code>data() {
  return {
      GREETING_MESSAGE_FROM_TO: 'Hello this message is for {{variable_1}} from {{variable_2}}'
  }
}
</code>```

My question is that is there any way to pass the variables for this template dynamically from within the html. Looking for something similar in Angular.. Something like this format:

```<code><div>
  {{ GREETING_MESSAGE_FROM_TO | [variable_1, variable_2] }}
</div>
</code>```

答:
I would simply use a method since variables are not being computed:

```<code>methods:{
   GREETING_MESSAGE_FROM_TO(variable_1, variable_2){
      return `Hello this message is for ${variable_1} from ${variable_2}`
   }
}
</code>```

In your template :

```<code><div>
  {{ GREETING_MESSAGE_FROM_TO(props1, props2) }}
</div>
</code>```

If those variable are needed to be computed then choose computed instead of methods hook.

Body:
Let's say i have an HTML of the form:

  {{ GREETING_MESSAGE_FROM_TO }}

And in my data:

data() {
  return {
      GREETING_MESSAGE_FROM_TO: 'Hello this message is for {{variable_1}} from {{variable_2}}'
  }
}

My question is that is there any way to pass the variables for this template dynamically from within the html. Looking for something similar in Angular.. Something like this format:

  {{ GREETING_MESSAGE_FROM_TO | [variable_1, variable_2] }}

Body:
I would simply use a method since variables are not being computed:

methods:{
   GREETING_MESSAGE_FROM_TO(variable_1, variable_2){
      return `Hello this message is for ${variable_1} from ${variable_2}`
   }
}

In your template :

<div>
  {{ GREETING_MESSAGE_FROM_TO(props1, props2) }}
</div>

If those variable are needed to be computed then choose computed instead of methods hook.


问:
Query in q-lang using qPython and Pandas in Python 3.8
I am totally new to q-language, but I need to use it in order to access a kdb server to get the data from.

I am using Python 3.8, under Windows10, with qPython installed.

I have trouble getting the query to the server.

```<code>from qpython import qconnection
import pandas as pd

tbl = 'q("h\"select from trade where date = 2007.02.28, sym = `XXXX\"")'

q = qconnection.QConnection(host=server, port=server_port, username=user, password=server_password, timeout=server_timeout)

q.open()
df = pd.DataFrame(q.sendSync('tbl'))
q.close()
</code>```

On executing the script it returns an error at line 15:

qpython.qtype.QException: b'tbl'

So I have a trouble sending the correct expression to the server. I was able to pass the expression via terminal, using q (with PyQ) under Linux Debian 10, so the query is correct.

(The server details are skipped, as well as the bond name).

答:
PyQ and qPython are being confused here. q.sendSync('tbl') will get the variable tbl from the kdb server. This error: qpython.qtype.QException: b'tbl' means tbl doesn't exist on the kdb server. I think what you wanted is the select statement to be sent to the kdb server:

```<code>from qpython import qconnection
import pandas as pd

q = qconnection.QConnection(host=server, port=server_port, username=user, password=server_password, timeout=server_timeout, pandas=True)

q.open()
df = q.sendSync('select from trade where date = 2007.02.28, sym = `XXXX')
q.close()
</code>```

It might be worth while for you to spend sometime with q itself and get up to speed with some basics here:

https://code.kx.com/q4m3/1_Q_Shock_and_Awe/

Body:
I am totally new to q-language, but I need to use it in order to access a kdb server to get the data from.

I am using Python 3.8, under Windows10, with qPython installed.

I have trouble getting the query to the server.

from qpython import qconnection
import pandas as pd

tbl = 'q("h\"select from trade where date = 2007.02.28, sym = `XXXX\"")'

q = qconnection.QConnection(host=server, port=server_port, username=user, password=server_password, timeout=server_timeout)

q.open()
df = pd.DataFrame(q.sendSync('tbl'))
q.close()

On executing the script it returns an error at line 15:

qpython.qtype.QException: b'tbl'

So I have a trouble sending the correct expression to the server. I was able to pass the expression via terminal, using q (with PyQ) under Linux Debian 10, so the query is correct.

(The server details are skipped, as well as the bond name).

Body:
PyQ and qPython are being confused here. q.sendSync('tbl') will get the variable tbl from the kdb server. This error: qpython.qtype.QException: b'tbl' means tbl doesn't exist on the kdb server. I think what you wanted is the select statement to be sent to the kdb server:

from qpython import qconnection
import pandas as pd

q = qconnection.QConnection(host=server, port=server_port, username=user, password=server_password, timeout=server_timeout, pandas=True)

q.open()
df = q.sendSync('select from trade where date = 2007.02.28, sym = `XXXX')
q.close()

It might be worth while for you to spend sometime with q itself and get up to speed with some basics here:

https://code.kx.com/q4m3/1_Q_Shock_and_Awe/


问:
Unable to push Server Work Queue Length custom metric to Cloud Watch
I am unable to publish Server Work Queue Length custom metric to Cloud Watch. I was able to figure out my mistake but unable to do it as I am clueless as to what to use there.

This is the PerformanceCounter block for this metric :

```<code>{
    "Id": "PerformanceCounter",
    "FullName": "AWS.EC2.Windows.CloudWatch.PerformanceCounterComponent.PerformanceCounterInputComponent,AWS.EC2.Windows.CloudWatch",
    "Parameters": {
         "CategoryName": "Server Work Queues",
         "CounterName": "Queue Length",
         "InstanceName": "",
         "MetricName": "QueueDepth",
         "Unit": "Count",
         "DimensionName": "InstanceId",
         "DimensionValue": "{instance_id}"
    }
},
</code>```

The problem with the above code is the InstanceName parameter.

According to AWS Documentation,

In the InstanceName parameter, enter valutes from the Add Counters
   dialog box in Performance Monitor, which can be one of the following:

Blank, if the selected object has no instances.

A single instance of the selected object.

_Total to use the aggregate of all instances.

Note: Do not use an asterisk (*) to indicate all instances because each performance    counter component only supports one metric.

Add Counters dialog box in Performance Monitor shows the following :

So the Counters Section shows All instances. AWS Documentation, as bulleted above says not to use * if the counter shows All Instances, but doesnot say what to use. I have used _Total and also left it blank. Both of them did not work.

By following the same points mentioned above, I successfully monitored Memory, Logical Disk Space, Paging File etc.

For Paging File, I used _Total as the InstanceName as it is mentioned there in the Performance Counter. Below snapshot shows that.

For Logical Disk Free Space, I used the _Total as InstanceName as the counter in the PerformanceMonitor showed up.

For Memory, I left the InstanceName value as blank as the counter in the PerformanceMonitor showed nothing.

I have been trying this from almost three days without any success. Please suggest me what to use there.

答:
Did you try high level API call like this:
https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/examples-cloudwatch-publish-custom-metrics.html

I followed this and found no issue.

Body:
I am unable to publish Server Work Queue Length custom metric to Cloud Watch. I was able to figure out my mistake but unable to do it as I am clueless as to what to use there.

This is the PerformanceCounter block for this metric :

{
    "Id": "PerformanceCounter",
    "FullName": "AWS.EC2.Windows.CloudWatch.PerformanceCounterComponent.PerformanceCounterInputComponent,AWS.EC2.Windows.CloudWatch",
    "Parameters": {
         "CategoryName": "Server Work Queues",
         "CounterName": "Queue Length",
         "InstanceName": "",
         "MetricName": "QueueDepth",
         "Unit": "Count",
         "DimensionName": "InstanceId",
         "DimensionValue": "{instance_id}"
    }
},

The problem with the above code is the InstanceName parameter.

According to AWS Documentation,

In the InstanceName parameter, enter valutes from the Add Counters
   dialog box in Performance Monitor, which can be one of the following:

Blank, if the selected object has no instances.

A single instance of the selected object.

_Total to use the aggregate of all instances.

Note: Do not use an asterisk (*) to indicate all instances because each performance    counter component only supports one metric.

Add Counters dialog box in Performance Monitor shows the following :

So the Counters Section shows All instances. AWS Documentation, as bulleted above says not to use * if the counter shows All Instances, but doesnot say what to use. I have used _Total and also left it blank. Both of them did not work.

By following the same points mentioned above, I successfully monitored Memory, Logical Disk Space, Paging File etc.

For Paging File, I used _Total as the InstanceName as it is mentioned there in the Performance Counter. Below snapshot shows that.

For Logical Disk Free Space, I used the _Total as InstanceName as the counter in the PerformanceMonitor showed up.

For Memory, I left the InstanceName value as blank as the counter in the PerformanceMonitor showed nothing.

I have been trying this from almost three days without any success. Please suggest me what to use there.


问:
How do you load .js files with ASP.NET?
```<code><%@ Page Language="VB"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
  <script runat="server">

Sub Page_Load(ByVal e As System.EventArgs)
Page.ClientScript.RegisterClientScriptInclude("basicjs", "basic.js")
End Sub

</script>
    <title>RegisterClientScriptBlock Example</title>
  </head>
  <body>
<form runat="server">
    <input type="button" id="button1" value="clickme" onclick="click()"/>
</form>
  </body>
</html>
</code>```

I'm using ASP.net (just learning) with VB. I can't seem to get Javascript code to work with ASP VB code. My main problem seems to be that .js files are not loading. In the example, basic.js just contains a function click() that calls an alert() message. How do I get .js files to load with ASP code?

答:
You need to include as follow

```<code><script type="text/javascript">
  // your code goes here.
</script>
</code>```

if javascript is in file then follow

```<code><script type="text/javascript" src="javascript_file_path">
      // your code goes here.
    </script>
</code>```

Title: How do you load .js files with ASP.NET?

Body:
<%@ Page Language="VB"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>RegisterClientScriptBlock Example</title>

<form runat="server">
    <input type="button" id="button1" value="clickme" onclick="click()"/>
</form>

I'm using ASP.net (just learning) with VB. I can't seem to get Javascript code to work with ASP VB code. My main problem seems to be that .js files are not loading. In the example, basic.js just contains a function click() that calls an alert() message. How do I get .js files to load with ASP code?

Body:
You need to include as follow

<script type="text/javascript">
  // your code goes here.
</script>

if javascript is in file then follow

<script type="text/javascript" src="javascript_file_path">
      // your code goes here.
    </script>


问:
Can glReadPixels be used to read layers from GL_TEXTURE_3D?
I'm trying to read a 3D texture I rendered using an FBO. This texture is so large that glGetTexImage results in GL_OUT_OF_MEMORY error due to failure of nvidia driver to allocate memory for intermediate storage* (needed, I suppose, to avoid changing destination buffer in case of error).

So I then thought of getting this texture layer by layer, using glReadPixels after I render each layer. But glReadPixels doesn't have layer index as a parameter. The only place where it actually appears as something that directs I/O to the particular layer is gl_Layer output in the geometry shader. And that is for the writing stage, not reading.

As I tried simply doing the calls to glReadPixels anyway after I render each layer, I only got the texels for layer 0. So glReadPixels at least doesn't fail to get something.

But the question is: can I get arbitrary layer of a 3D texture using glReadPixels? And if not, what should I use instead, given the above described memory constraints? Do I have to sample the layer from 3D texture in a shader to render the result to a 2D texture, and read this 2D texture afterwards?

*It's not a guess, I've actually tracked it down to a failing malloc call (with the size of the texture as argument) from within the nvidia driver's shared library.

答:
If you have access to GL 4.5 or ARB_get_texture_sub_image, you can employ glGetTextureSubImage. As the function name suggests, it's for querying a sub-section of a texture's image data. This allows you to read slices of the texture without having to get the whole thing in one go.

The extension seems fairly widely supported, available on any implementation that's still being supported by its IHV.


问:
Type of argument/value that is passed in a AsyncTask
Just 3 simple questions about AsyncTasks.
If we declare this AsyncTask:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long>

1- What type of value is passed to doInBackground() method? Is it URL?

2- What type of value is passed to the callback that informs the task progress?

3- What type of value is passed to the callback that is executed when the task ends?

Thank you all. Rest of a good day

答:
The three types used by an asynchronous task are the following:

Params, the type of the parameters sent to the task upon execution.

Progress, the type of the progress units published during the background computation.

Result, the type of the result of the background computation.

private class MyTask extends AsyncTask<Params, Progress, Result> { ... }

So, to answer your question, URL is passed to doInBackground and Long is the return type.

Read more https://stackoverflow.com/a/6053673/5644761


问:
Bazel cc_library with no srcs doesn't compile on its own
I have a cc_library that is header-only. Whenever I try to compile such library by itself, it won't actually compile anything. I purposely put some errors to try to get such errors on compilation, but bazel doesn't actually compile anything. Here's a small example.

// test.h

This should not compile fdsafdsafdsa
int foo() { return 1; }
```

<pre class="lang-py prettyprint-override"><code># BUILD

cc_library(
  name = 'test',
  hdrs = ['test.h']
)
</code>```

```<code>// bazel build :test
INFO: Analyzed target //:test (2 packages loaded, 3 targets configured).
INFO: Found 1 target...
Target //:test up-to-date (nothing to build)
INFO: Elapsed time: 0.083s, Critical Path: 0.00s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action
</code>```

Is this behavior intended?

I also ran the same experiment but splitting the .h and .cc files, and in that case, I got the error when I compiled.

答:
cc_library (other rules as well incl. pkg_tar for instance) does not have to have any sources. This is also valid:

```<code>cc_library(
    name = "empty",
    srcs = [],
)
</code>```

And it is actually quite useful too. You may have configurable attributes such as deps (or srcs) where actual content is only applicable for certain conditions:

```<code>cc_binary(
    name = "mybinary",
    srcs = ["main.c"],
    deps = select({
        ":platform1": [":some_plat1_only_lib"],
        ":platform2": [":empty"],  # as defined in the above snippet
    }),
)
</code>```

Or (since above you could have just as well used [] for :platform2 deps) where you have a larger tree and you expect developers to just depend on //somelib:somelib, you could use this empty library through an alias to give them a single label without having to worry about all the platform specific details and how providing certain function is handled where:

```<code># somelib/BUILD:
alias(
    name = "somelib",
    actual = select({
        ":platform1": [":some_plat1_only_lib"],
        ":platform2": [":empty"],  # as defined in the above snippet
    }),
    visibility = ["//visibility:public"],  # set appropriately
)
</code>```

And mybinary or any other target could now say:

```<code>cc_binary(
    name = "mybinary",
    srcs = ["main.c"],
    deps = ["//somelib"],
)
</code>```

And of course, as the other answer here states, there are header only libraries.

Also in the example you've used in your question. (bazel or not) you would normally not (and it would not be very useful either) compile a header file on its own. You would only use its content and only then see the compiler fails as you attempt to build a source the header is #included from. That is for bazel build to fail, another target would have to depend on test and #include "test.h".

Body:
I have a cc_library that is header-only. Whenever I try to compile such library by itself, it won't actually compile anything. I purposely put some errors to try to get such errors on compilation, but bazel doesn't actually compile anything. Here's a small example.

// test.h

This should not compile fdsafdsafdsa
int foo() { return 1; }

# BUILD

cc_library(
  name = 'test',
  hdrs = ['test.h']
)

// bazel build :test
INFO: Analyzed target //:test (2 packages loaded, 3 targets configured).
INFO: Found 1 target...
Target //:test up-to-date (nothing to build)
INFO: Elapsed time: 0.083s, Critical Path: 0.00s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action

Is this behavior intended?

I also ran the same experiment but splitting the .h and .cc files, and in that case, I got the error when I compiled.

Body:
cc_library (other rules as well incl. pkg_tar for instance) does not have to have any sources. This is also valid:

cc_library(
    name = "empty",
    srcs = [],
)

And it is actually quite useful too. You may have configurable attributes such as deps (or srcs) where actual content is only applicable for certain conditions:

cc_binary(
    name = "mybinary",
    srcs = ["main.c"],
    deps = select({
        ":platform1": [":some_plat1_only_lib"],
        ":platform2": [":empty"],  # as defined in the above snippet
    }),
)

Or (since above you could have just as well used [] for :platform2 deps) where you have a larger tree and you expect developers to just depend on //somelib:somelib, you could use this empty library through an alias to give them a single label without having to worry about all the platform specific details and how providing certain function is handled where:

# somelib/BUILD:
alias(
    name = "somelib",
    actual = select({
        ":platform1": [":some_plat1_only_lib"],
        ":platform2": [":empty"],  # as defined in the above snippet
    }),
    visibility = ["//visibility:public"],  # set appropriately
)

And mybinary or any other target could now say:

cc_binary(
    name = "mybinary",
    srcs = ["main.c"],
    deps = ["//somelib"],
)

And of course, as the other answer here states, there are header only libraries.

Also in the example you've used in your question. (bazel or not) you would normally not (and it would not be very useful either) compile a header file on its own. You would only use its content and only then see the compiler fails as you attempt to build a source the header is #included from. That is for bazel build to fail, another target would have to depend on test and #include "test.h".


问:
update Axios Url with Onclick event in react
I am working on an API using axios:

```<code>  constructor(props) {
    super(props);
    this.state = {
      url:[],
      title:'anime',
      limit:6,
    }
    this.more_button.bind(this)
  }

  componentDidMount() {

  //limit is on the end of the url
  const limit= this.state.limit

     axios.get(`http://api.giphy.com/v1/gifs/search?q=sth&api_key=MY_KEY&limit=` + limit)
      .then(res => {
        const url= res.data.data;
        this.setState({ url });
      })

  }
</code>```

I want to change limit when i click on a button;
and i do it like this:

```<code>  more_button=()=>{

      this.setState((previousState) => {
        return { limit: previousState.limit + 6 };
    });

    this.componentDidMount();

  }
</code>```

The problem is that i should click that button twice in order to work.

render part:

```<code>  render(){
    return(
      <div className="container">
              <button
              onClick={this.more_button} >
              Give me More!
              </button>
  )
    }
}
</code>```

答:
ComponentDidMount is a lifecycle method. Don't call this function manually,Try below code.

```<code>componentDidMount() {
  //limit is on the end of the url
  this.apiCall();
  }

 apiCall() {
      const limit= this.state.limit
      axios.get(`http://api.giphy.com/v1/gifs/search?q=sth&api_key=MY_KEY&limit=` + limit)
      .then(res => {
        const url= res.data.data;
        this.setState({ url });
      })
 }

more_button = () => {

  this.setState((previousState) => {
    return { limit: previousState.limit + 6 };
});
this.apiCall();
}
</code>```

Change your render onClick method like:

```<code>onClick={()=>this.more_button}
</code>```

Finally add extra line in constructor:

```<code>constructor(props) {
    super(props);
    this.state = {
      url:[],
      title:'anime',
      limit:6,
    }
     this.apiCall = this.apiCall.bind(this);
     this.more_button = this.more_button.bind(this);
  }
</code>```

Body:
I am working on an API using axios:

  constructor(props) {
    super(props);
    this.state = {
      url:[],
      title:'anime',
      limit:6,
    }
    this.more_button.bind(this)
  }

  componentDidMount() {

  //limit is on the end of the url
  const limit= this.state.limit

     axios.get(`http://api.giphy.com/v1/gifs/search?q=sth&api_key=MY_KEY&limit=` + limit)
      .then(res => {
        const url= res.data.data;
        this.setState({ url });
      })

  }

I want to change limit when i click on a button;
and i do it like this:

  more_button=()=>{

      this.setState((previousState) => {
        return { limit: previousState.limit + 6 };
    });

    this.componentDidMount();

  }

The problem is that i should click that button twice in order to work.

render part:

  render(){
    return(

              <button
              onClick={this.more_button} >
              Give me More!
              </button>
  )
    }
}

Body:
ComponentDidMount is a lifecycle method. Don't call this function manually,Try below code.

componentDidMount() {
  //limit is on the end of the url
  this.apiCall();
  }

 apiCall() {
      const limit= this.state.limit
      axios.get(`http://api.giphy.com/v1/gifs/search?q=sth&api_key=MY_KEY&limit=` + limit)
      .then(res => {
        const url= res.data.data;
        this.setState({ url });
      })
 }

more_button = () => {

  this.setState((previousState) => {
    return { limit: previousState.limit + 6 };
});
this.apiCall();
}

Change your render onClick method like:

onClick={()=>this.more_button}

Finally add extra line in constructor:

constructor(props) {
    super(props);
    this.state = {
      url:[],
      title:'anime',
      limit:6,
    }
     this.apiCall = this.apiCall.bind(this);
     this.more_button = this.more_button.bind(this);
  }


问:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured
I am working on a Spring Boot Batch example with MongoDB and I have already started the mongod server.

When I launch my application, I am getting the error below.

Any pointers for this issue?

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
</code>```

application.properties:

```<code># Mongo database URI. Cannot be set with host, port and credentials.
spring.data.mongodb.uri=mongodb://localhost/test
</code>```

pom.xml

```<code><dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</code>```

I have started mongod with the following output:

```<code>C:\Users\pc>mongod
2018-07-07T14:39:39.223+0530 I JOURNAL  [initandlisten] journal dir=C:\data\db\journal
2018-07-07T14:39:39.230+0530 I JOURNAL  [initandlisten] recover : no journal files present, no recovery needed
2018-07-07T14:39:39.478+0530 I JOURNAL  [durability] Durability thread started
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] MongoDB starting : pid=11992 port=27017 dbpath=C:\data\db\ 64-bit host=DESKTOP-NQ639DU
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2018-07-07T14:39:39.591+0530 I CONTROL  [initandlisten] db version v3.0.5
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] git version: 8bc4ae20708dbb493cb09338d9e7be6698e4a3a3
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2018-07-07T14:39:39.593+0530 I CONTROL  [initandlisten] options: {}
2018-07-07T14:39:39.595+0530 I JOURNAL  [journal writer] Journal writer thread started
2018-07-07T14:39:40.485+0530 I NETWORK  [initandlisten] waiting for connections on port 27017
2018-07-07T14:40:39.140+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51340 #1 (1 connection now open)
2018-07-07T14:40:41.663+0530 I NETWORK  [conn1] end connection 127.0.0.1:51340 (0 connections now open)
2018-07-07T14:45:12.421+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51578 #2 (1 connection now open)
2018-07-07T14:45:12.870+0530 I NETWORK  [conn2] end connection 127.0.0.1:51578 (0 connections now open)
2018-07-07T14:46:21.734+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51591 #3 (1 connection now open)
2018-07-07T14:46:22.041+0530 I NETWORK  [conn3] end connection 127.0.0.1:51591 (0 connections now open)
2018-07-07T14:57:47.523+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:52534 #4 (1 connection now open)
2018-07-07T14:57:47.910+0530 I NETWORK  [conn4] end connection 127.0.0.1:52534 (0 connections now open)
</code>```

答:
Excluding the DataSourceAutoConfiguration.class worked for me:

```<code>@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
</code>```

Body:
I am working on a Spring Boot Batch example with MongoDB and I have already started the mongod server.

When I launch my application, I am getting the error below.

Any pointers for this issue?

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

application.properties:

# Mongo database URI. Cannot be set with host, port and credentials.
spring.data.mongodb.uri=mongodb://localhost/test

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

I have started mongod with the following output:

C:\Users\pc>mongod
2018-07-07T14:39:39.223+0530 I JOURNAL  [initandlisten] journal dir=C:\data\db\journal
2018-07-07T14:39:39.230+0530 I JOURNAL  [initandlisten] recover : no journal files present, no recovery needed
2018-07-07T14:39:39.478+0530 I JOURNAL  [durability] Durability thread started
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] MongoDB starting : pid=11992 port=27017 dbpath=C:\data\db\ 64-bit host=DESKTOP-NQ639DU
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2018-07-07T14:39:39.591+0530 I CONTROL  [initandlisten] db version v3.0.5
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] git version: 8bc4ae20708dbb493cb09338d9e7be6698e4a3a3
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2018-07-07T14:39:39.593+0530 I CONTROL  [initandlisten] options: {}
2018-07-07T14:39:39.595+0530 I JOURNAL  [journal writer] Journal writer thread started
2018-07-07T14:39:40.485+0530 I NETWORK  [initandlisten] waiting for connections on port 27017
2018-07-07T14:40:39.140+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51340 #1 (1 connection now open)
2018-07-07T14:40:41.663+0530 I NETWORK  [conn1] end connection 127.0.0.1:51340 (0 connections now open)
2018-07-07T14:45:12.421+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51578 #2 (1 connection now open)
2018-07-07T14:45:12.870+0530 I NETWORK  [conn2] end connection 127.0.0.1:51578 (0 connections now open)
2018-07-07T14:46:21.734+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51591 #3 (1 connection now open)
2018-07-07T14:46:22.041+0530 I NETWORK  [conn3] end connection 127.0.0.1:51591 (0 connections now open)
2018-07-07T14:57:47.523+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:52534 #4 (1 connection now open)
2018-07-07T14:57:47.910+0530 I NETWORK  [conn4] end connection 127.0.0.1:52534 (0 connections now open)

Body:
Excluding the DataSourceAutoConfiguration.class worked for me:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })


问:
Get the error of a JSON Validation List in ReactJS
On my api test, it was able to run as the image below. but, when I try to code in React.JS, the user Id cannot be pass in. What is the problem of this?

But when I try to code in front end, the user Id cannot be pass in to api.
Consider the code below:

```<code>  constructor (props){
    super(props);
    const Users_id = localStorage.getItem('id');
    this.state ={
      users_id: Users_id,
      event_name: '',
      event_email: '',
      event_description: '',
      event_type: '',
      event_location: '',
      start_date: '',
      end_date: '',
      history: PropTypes.object.isRequired
    }
    this.create = this.create.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  create(){
    // const loginEmail = localStorage.getItem('loginEmail');
    const Users_id = localStorage.getItem('id');
    this.setState({Users_id})
    // console.log(loginEmail)
    PostData('api/event/submit', this.state).then ((result) => {
        let responseJSON = result;
        console.log(responseJSON);
        console.log(this.state)

      });
   }
</code>```

The error show in console.log(responseJSON):

//Updated PostData

```<code>    return new Promise((resolve, reject) => {
        fetch( BaseUrl+type, {
            method: "POST",
            body: JSON.stringify(userData),
            Accept: 'application/json',
            // mode: 'no-cors',
            headers:
                {
                    'Content-Type': 'application/json'
                },
          })
        .then((response) => response.json())
        .then((responseJson) => {
            resolve(responseJson);
        })
        .catch((error)=>{
            console.error('Error:', error);
        })

    });
</code>```

答:
you need to check if the user id exists in local storage before inserting it into props

```<code>    super(props);
    const Users_id = localStorage.getItem('id') || '';
    this.state ={
      users_id: Users_id,
      event_name: '',
      event_email: '',
      event_description: '',
      event_type: '',
      event_location: '',
      start_date: '',
      end_date: '',
      history: PropTypes.object.isRequired
    }
</code>```

and when you want to setState you need to pass the same name you used in the state

```<code>const Users_id = localStorage.getItem('id');
if(Users_id){
this.setState({users_id: Users_id})
}
</code>```

Body:
On my api test, it was able to run as the image below. but, when I try to code in React.JS, the user Id cannot be pass in. What is the problem of this?

But when I try to code in front end, the user Id cannot be pass in to api.
Consider the code below:

  constructor (props){
    super(props);
    const Users_id = localStorage.getItem('id');
    this.state ={
      users_id: Users_id,
      event_name: '',
      event_email: '',
      event_description: '',
      event_type: '',
      event_location: '',
      start_date: '',
      end_date: '',
      history: PropTypes.object.isRequired
    }
    this.create = this.create.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  create(){
    // const loginEmail = localStorage.getItem('loginEmail');
    const Users_id = localStorage.getItem('id');
    this.setState({Users_id})
    // console.log(loginEmail)
    PostData('api/event/submit', this.state).then ((result) => {
        let responseJSON = result;
        console.log(responseJSON);
        console.log(this.state)

      });
   }

The error show in console.log(responseJSON):

//Updated PostData

    return new Promise((resolve, reject) => {
        fetch( BaseUrl+type, {
            method: "POST",
            body: JSON.stringify(userData),
            Accept: 'application/json',
            // mode: 'no-cors',
            headers:
                {
                    'Content-Type': 'application/json'
                },
          })
        .then((response) => response.json())
        .then((responseJson) => {
            resolve(responseJson);
        })
        .catch((error)=>{
            console.error('Error:', error);
        })

    });

Body:
you need to check if the user id exists in local storage before inserting it into props

    super(props);
    const Users_id = localStorage.getItem('id') || '';
    this.state ={
      users_id: Users_id,
      event_name: '',
      event_email: '',
      event_description: '',
      event_type: '',
      event_location: '',
      start_date: '',
      end_date: '',
      history: PropTypes.object.isRequired
    }

and when you want to setState you need to pass the same name you used in the state

const Users_id = localStorage.getItem('id');
if(Users_id){
this.setState({users_id: Users_id})
}


问:
Distinguish between one-, two- and three-word commands
Right now, I am using this method to check if the user just typed in a command with wrong arguments:

```<code>    private boolean relatedCommand(String input) {
        // make sure the split afterwards has at least size one
        if (input.matches(" .*")) {
            return false;
        }
        final String command = input.split(" ".toString())[0];
        return COMMAND_PACKAGE
                .keySet()
                .stream()
                .map(Pattern::toString)
                .anyMatch(patternText -> patternText.startsWith(command + " ");
    }
</code>```

(COMMAND_PACKAGE contains all registered commands)

Now, this works perfectly fine for one-word commands. E. g. get <argument1> <argument2>, remove <argument1>.

However, I am currently working on a project that has both one-word and two-word commands.
Here is a range of commands that doesn't really work with this method:
add track <argument1>, add switch <argument1>, step <argument>. In this case, for the command add track <argument1>, "track" is seen as an argument but it really belongs to the command itself.

If the use just types in "add" the error message is "invalid arguments". Instead, the error message should be more precise and tell him that this command doesn't exist (as there is only "add track" or "add switch").

Does anyone have any idea how to distinguish between one-word and two-word commands? The user can also use the command delete rolling stock <argument> which consists of a three-word command.

All in all, it is therefore necessary to differentiate between commands of one, two and three words.

答:
You might want to try using a LinkedHashMap and then putting the commands in order of most complex (w/ spaces) first.  That way they will be matched first.

A LinkedHashMap preserves the order in which you add keys.

Body:
Right now, I am using this method to check if the user just typed in a command with wrong arguments:

    private boolean relatedCommand(String input) {
        // make sure the split afterwards has at least size one
        if (input.matches(" .*")) {
            return false;
        }
        final String command = input.split(" ".toString())[0];
        return COMMAND_PACKAGE
                .keySet()
                .stream()
                .map(Pattern::toString)
                .anyMatch(patternText -> patternText.startsWith(command + " ");
    }

(COMMAND_PACKAGE contains all registered commands)

Now, this works perfectly fine for one-word commands. E. g. get <argument1> <argument2>, remove <argument1>.

However, I am currently working on a project that has both one-word and two-word commands.
Here is a range of commands that doesn't really work with this method:
add track <argument1>, add switch <argument1>, step <argument>. In this case, for the command add track <argument1>, "track" is seen as an argument but it really belongs to the command itself.

If the use just types in "add" the error message is "invalid arguments". Instead, the error message should be more precise and tell him that this command doesn't exist (as there is only "add track" or "add switch").

Does anyone have any idea how to distinguish between one-word and two-word commands? The user can also use the command delete rolling stock <argument> which consists of a three-word command.

All in all, it is therefore necessary to differentiate between commands of one, two and three words.


问:
Populating several values in an empty column in a row, based on a value from another column
I already have an idea as to how I'm going to do this - I'm just curious about whether my method is the most efficient.

So for instance, let's say that for whatever reason, I have the following table:

The first 4 columns in the table are all repeated - they just say info about the employee. The reason these rows repeat is because that employee handles multiple clients.

In some cases, I am missing info on the Age and Employee duration of an employee. Another colleague gave me this information in an excel sheet.

So now, I have info on Brian's and Dennis' age and employment duration, and I need to fill all rows with their employee IDs based on the information. My plan for doing that is this:

```<code>data = {"14": # Brian's Employee ID
{"Age":31,
:"Employment Duration":3},
"21": # Dennis' Employee ID
{"Age":45,
"Employment Duratiaon":12}
}
</code>```

After making the above dictionary of dictionaries with the necessary values, my plan is to iterate over each row in the above dataframe, and fill in the 'Age' and 'Employment Duration' columns based on the value in 'Employee ID':

```<code>for index, row in df.iterrows:
if row["Employee ID"] in data:
    row["Age"] = data["Employee ID"]["Age"]
    row["Employment Duration"] = data["Employee ID"]["Employement Duration"]
</code>```

That's my plan for populating the missing values!

I'm curious about whether there's a simpler way that's just not presenting itself to me, because this was the first thing that sprang to mind!

答:
Don't iterate over rows in pandas when you can avoid it. Instead maximize the pandas library with actions like this:

Assume we have a dataframe:

```<code>data = pd.DataFrame({
    'name' : ['john', 'john', 'mary', 'mary'],
    'age'  : ['', '', 25, 25]
})
</code>```

Which looks like:

```<code>   name age
0  john
1  john
2  mary  25
3  mary  25
</code>```

We can apply a lambda function like so:

```<code>data['age'] = data.apply(lambda x: 27 if x.name == 'john' else x.age, axis=1)
</code>```

Or we can use pandas .loc:

```<code>data['age'].loc[data.name == 'john'] = 27
</code>```

Test them out and compare how long each take to execute vs. iterating over rows.

Body:
I already have an idea as to how I'm going to do this - I'm just curious about whether my method is the most efficient.

So for instance, let's say that for whatever reason, I have the following table:

The first 4 columns in the table are all repeated - they just say info about the employee. The reason these rows repeat is because that employee handles multiple clients.

In some cases, I am missing info on the Age and Employee duration of an employee. Another colleague gave me this information in an excel sheet.

So now, I have info on Brian's and Dennis' age and employment duration, and I need to fill all rows with their employee IDs based on the information. My plan for doing that is this:

data = {"14": # Brian's Employee ID
{"Age":31,
:"Employment Duration":3},
"21": # Dennis' Employee ID
{"Age":45,
"Employment Duratiaon":12}
}

After making the above dictionary of dictionaries with the necessary values, my plan is to iterate over each row in the above dataframe, and fill in the 'Age' and 'Employment Duration' columns based on the value in 'Employee ID':

for index, row in df.iterrows:
if row["Employee ID"] in data:
    row["Age"] = data["Employee ID"]["Age"]
    row["Employment Duration"] = data["Employee ID"]["Employement Duration"]

That's my plan for populating the missing values!

I'm curious about whether there's a simpler way that's just not presenting itself to me, because this was the first thing that sprang to mind!

Body:
Don't iterate over rows in pandas when you can avoid it. Instead maximize the pandas library with actions like this:

Assume we have a dataframe:

data = pd.DataFrame({
    'name' : ['john', 'john', 'mary', 'mary'],
    'age'  : ['', '', 25, 25]
})

Which looks like:

   name age
0  john
1  john
2  mary  25
3  mary  25

We can apply a lambda function like so:

data['age'] = data.apply(lambda x: 27 if x.name == 'john' else x.age, axis=1)

Or we can use pandas .loc:

data['age'].loc[data.name == 'john'] = 27

Test them out and compare how long each take to execute vs. iterating over rows.


问:
How can I change the Bootstrap 4 navbar button icon color?
I have a Bootstrap website where the hamburger toggler is added when the screen size is less than 992px. The code is like so:

```<code><button class="navbar-toggler navbar-toggler-right"
        type="button" data-toggle="collapse"
        data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent"
        aria-expanded="false"
        aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
</button>
</code>```

Is there any possibility to change the color of the hamburger toggler button?

答:
If you downloaded bootstrap, go to bootstrap-4.4.1-dist/css/bootstrap.min.css

find the .navbar-light .navbar-toggler-icon or the .navbar-dark .navbar-toggler-icon selector

select the background-image attribute and its value. The snippet looks like this:

```<code>.navbar-light .navbar-toggler-icon {
     background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
}
</code>```

copy the snippet and paste it in your custom CSS

change the stroke='rgba(0, 0, 0, 0.5)' value to your preferred rgba value

Body:
I have a Bootstrap website where the hamburger toggler is added when the screen size is less than 992px. The code is like so:

<button class="navbar-toggler navbar-toggler-right"
        type="button" data-toggle="collapse"
        data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent"
        aria-expanded="false"
        aria-label="Toggle navigation">

</button>

Is there any possibility to change the color of the hamburger toggler button?

Body:
If you downloaded bootstrap, go to bootstrap-4.4.1-dist/css/bootstrap.min.css

find the .navbar-light .navbar-toggler-icon or the .navbar-dark .navbar-toggler-icon selector

select the background-image attribute and its value. The snippet looks like this:

.navbar-light .navbar-toggler-icon {
     background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
}

copy the snippet and paste it in your custom CSS

change the stroke='rgba(0, 0, 0, 0.5)' value to your preferred rgba value


问:
Checking for positions in square shapes of varying sizes, related to the middle position in 2D-array?
```<code>array[i-1][j-1]
array[i-1][j]
array[i-1][j+1]

array[i][j-1]
array[i][j+1]

array[i+1][j-1]
array[i+1][j]
array[i+1][j+1]
</code>```

<p>I've found out a way to check the 8 neighboring elements(above) but i'm looking if there is a way to make it non-hard-coded so that i could extend the checking for, say 2-3 or more cells away? I have an intuition that a nested for-loop might do it, but i can't seem to get it working </p>

答:
This is the solution in C++. ^^</p>

```<code>// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{

    int m[5][5]={1, 2, 3, 4,5,
                 6, 7, 8, 9, 10,
                11, 12, 13, 14, 15,
                16, 17, 18, 19, 20,
                21, 22, 23, 24, 25};

    int n = 2; //number of cells you want to "move" from the origin
    int k=2;//for a cell in m[k][k]
    for(int i=1;i<=n;i++) //this is for the size of the "square" you form around the initial cell
    {
        cout<<i<<endl;
        for(int j=i;j>=-i;j--)
        {
            cout<<m[k-i][k-j]<<" ";//cell of the first line, on top of the new formed "square"
        }
        cout<<endl;
        for(int j=-i+1;j<=i-1;j++)
        {

        cout<< m[k+j][k-i]<<" ";//on the left side of the "square"
        cout<< m[k+j][k+i]<<endl;//on the right side of the "square"
        }
        for(int j=i;j>=-i;j--)
        {
            cout<<m[k+i][k-j]<<" ";//cell of the first line, on the bottom of the new formed "square"
        }
        cout<<endl;
    }
}

/**Result:
1
7 8 9
12 14
17 18 19
2
1 2 3 4 5
6 10
11 15
16 20
21 22 23 24 25 */
</code>```

Body:
array[i-1][j-1]
array[i-1][j]
array[i-1][j+1]

array[i][j-1]
array[i][j+1]

array[i+1][j-1]
array[i+1][j]
array[i+1][j+1]

I've found out a way to check the 8 neighboring elements(above) but i'm looking if there is a way to make it non-hard-coded so that i could extend the checking for, say 2-3 or more cells away? I have an intuition that a nested for-loop might do it, but i can't seem to get it working

Body:
This is the solution in C++. ^^

// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{

    int m[5][5]={1, 2, 3, 4,5,
                 6, 7, 8, 9, 10,
                11, 12, 13, 14, 15,
                16, 17, 18, 19, 20,
                21, 22, 23, 24, 25};

    int n = 2; //number of cells you want to "move" from the origin
    int k=2;//for a cell in m[k][k]
    for(int i=1;i<=n;i++) //this is for the size of the "square" you form around the initial cell
    {
        cout<<i<<endl;
        for(int j=i;j>=-i;j--)
        {
            cout<<m[k-i][k-j]<<" ";//cell of the first line, on top of the new formed "square"
        }
        cout<<endl;
        for(int j=-i+1;j<=i-1;j++)
        {

        cout<< m[k+j][k-i]<<" ";//on the left side of the "square"
        cout<< m[k+j][k+i]<<endl;//on the right side of the "square"
        }
        for(int j=i;j>=-i;j--)
        {
            cout<<m[k+i][k-j]<<" ";//cell of the first line, on the bottom of the new formed "square"
        }
        cout<<endl;
    }
}

/**Result:
1
7 8 9
12 14
17 18 19
2
1 2 3 4 5
6 10
11 15
16 20
21 22 23 24 25 */


问:
Remove reference from realm object
I am new in Realm. Following, I am struggling with reference in Realm.

I read data from Realm Database using JavaScript and receive an error: "Cannot modify managed objects outside of a write transaction" whenever I want to change something.

I know the error appear because the object is still linking with Realm DB and we have to open a transaction to modify it.

Is there anyway to get rid of reference in Realm? I just want to get the object only.

Note:

I search around and find out there is a way to do it using:

```<code>JSON.parse(JSON.stringify(Object));
</code>```

However, it will change all the variable with type Date inside the object and we have to re-format it later, which cause a lot of effort.

答:
What you might look for is the method Realm.copyFromRealm(RealmObject).

In the documentation it is stated as follows:

copyFromRealm:

public <E extends RealmModel> E copyFromRealm(E realmObject)

Makes an unmanaged in-memory copy of an already persisted RealmObject. This is a deep copy that will copy all referenced objects.

But bear in mind, that changes to this unmanaged copy of the managed RealmObject will not update the RealmObject. To bring all your changes back into the RealmObject you have to explicitly do this via a RealmTransaction, where you can update the RealmObject.

Furthermore you may check with RealmObject.isManaged() if your chosen object is currently managed by Realm. If not, you don't need to create an unmanaged copy.

Title: Remove reference from realm object

Body:
I am new in Realm. Following, I am struggling with reference in Realm.

I read data from Realm Database using JavaScript and receive an error: "Cannot modify managed objects outside of a write transaction" whenever I want to change something.

I know the error appear because the object is still linking with Realm DB and we have to open a transaction to modify it.

Is there anyway to get rid of reference in Realm? I just want to get the object only.

Note:

I search around and find out there is a way to do it using:

JSON.parse(JSON.stringify(Object));

However, it will change all the variable with type Date inside the object and we have to re-format it later, which cause a lot of effort.


问:
Calling mysql procedure in python with parameter and getting errors
I use pymysql to connect to db. Here is the way I call the procedure.

cur.execute("call delete_shop_tables(?,?,?,?,?)", args)

The procedure expects 5 string variables.

args has five string variables in an array (args = ["one","two","three","four", "five"])

I get the following errors when the above line is executed.

TypeError: not all arguments converted during string formatting

What could I be missing?

答: It's a db we recently inherited. Once I collated the columns in WHERE clause to match with the collation what's in the column definition, it all worked.</p>


问:
Not Throwing an error, but not logging to console to test
Morning. I'm trying to calculate population density using for loop and if/else statements. When logging the results I get no errors but also get no log results for the variable density. Wonder if folks might be able to see what I'm missing in my functions. Thanks!</p>

```<code>        var cityCoords = [[30.5833302, -114.2666702], [48.864716, 2.349014],[40.730610, -73.935242 ]] // city coords
        var cityPops = [8266000, 10958000, 19491339] // city populations
        var cityAreas = [3280, 41, 303]// city areas in sq. miles
        //    NOTE. You can use the arrays you built in Lab 3, just make sure you keep track of your variable names

        var button = document.getElementById("map-cities");

        button.addEventListener("click", function () {

            var units = prompt('Enter the units for calculating population density', 'Enter "miles" or "km"');

            var mapCities = function(){ // assign function to variable mapCities
            mapCities(units); // call mapCities function  units variable as an argument
        }
            // call a function named mapCities, and send the units variable as an argument

        }); // addEventListener callback function ends here

        // Define function
            function mapCities(units) {
                for (var i = 0; i < cities.length; i++) {
                    var cityName = cities[i] ;
                    var cityNumPeeps = cityPops[i];
                    var cityZone = cityAreas[i];

                    var density = calcPopDensity(CityNumPeeps, CityZone, units); // call calcPopDensity passing population, cityZone and units as arguments

                    console.log(density);

                }

            };

        function calcPopDensity(pop,area,unit){
            if (units == "miles"){
                cityZone/cityNumPeeps
                return

            } else if (units == "km"){
                cityZone * 1.60934 / cityNumPeeps
                return
            }

        };
</code>```

答:
There's... a few issues here. But, we all learn from our mistakes!</p>

```<code>    var cityCoords = [[30.5833302, -114.2666702], [48.864716, 2.349014],[40.730610, -73.935242 ]]
    var cityPops = [8266000, 10958000, 19491339]
    var cityAreas = [3280, 41, 303]

    var button = document.getElementById("map-cities");

    button.addEventListener("click", function () {

        var units = prompt('Enter the units for calculating population density', 'Enter "miles" or "km"');

        mapCities(units); // <= You just want to call the function here, no need to do the function-wrapping you had!
    }

    });

    function mapCities(units) {
        for (var i = 0; i < cities.length; i++) { // <= You don't actually have this array defined (cities)?
            var cityName = cities[i] ;
            var cityNumPeeps = cityPops[i];
            var cityZone = cityAreas[i];

            var density = calcPopDensity(CityNumPeeps, CityZone, units); // <= match case - 'cityNumPeeps' vs 'CityNumPeeps' etc

            console.log(density);

        }

    };

    function calcPopDensity(pop,area,unit){
        if (units == "miles"){
            return cityZone/cityNumPeeps // <= move the return to this line - we want the result of the calculation back!

        } else if (units == "km"){
            return cityZone * 1.60934 / cityNumPeeps  // <= again, return statement
        }

    };
</code>```

Body:
Morning. I'm trying to calculate population density using for loop and if/else statements. When logging the results I get no errors but also get no log results for the variable density. Wonder if folks might be able to see what I'm missing in my functions. Thanks!

        var cityCoords = [[30.5833302, -114.2666702], [48.864716, 2.349014],[40.730610, -73.935242 ]] // city coords
        var cityPops = [8266000, 10958000, 19491339] // city populations
        var cityAreas = [3280, 41, 303]// city areas in sq. miles
        //    NOTE. You can use the arrays you built in Lab 3, just make sure you keep track of your variable names

        var button = document.getElementById("map-cities");

        button.addEventListener("click", function () {

            var units = prompt('Enter the units for calculating population density', 'Enter "miles" or "km"');

            var mapCities = function(){ // assign function to variable mapCities
            mapCities(units); // call mapCities function  units variable as an argument
        }
            // call a function named mapCities, and send the units variable as an argument

        }); // addEventListener callback function ends here

        // Define function
            function mapCities(units) {
                for (var i = 0; i < cities.length; i++) {
                    var cityName = cities[i] ;
                    var cityNumPeeps = cityPops[i];
                    var cityZone = cityAreas[i];

                    var density = calcPopDensity(CityNumPeeps, CityZone, units); // call calcPopDensity passing population, cityZone and units as arguments

                    console.log(density);

                }

            };

        function calcPopDensity(pop,area,unit){
            if (units == "miles"){
                cityZone/cityNumPeeps
                return

            } else if (units == "km"){
                cityZone * 1.60934 / cityNumPeeps
                return
            }

        };

Body:
There's... a few issues here. But, we all learn from our mistakes!

    var cityCoords = [[30.5833302, -114.2666702], [48.864716, 2.349014],[40.730610, -73.935242 ]]
    var cityPops = [8266000, 10958000, 19491339]
    var cityAreas = [3280, 41, 303]

    var button = document.getElementById("map-cities");

    button.addEventListener("click", function () {

        var units = prompt('Enter the units for calculating population density', 'Enter "miles" or "km"');

        mapCities(units); // <= You just want to call the function here, no need to do the function-wrapping you had!
    }

    });

    function mapCities(units) {
        for (var i = 0; i < cities.length; i++) { // <= You don't actually have this array defined (cities)?
            var cityName = cities[i] ;
            var cityNumPeeps = cityPops[i];
            var cityZone = cityAreas[i];

            var density = calcPopDensity(CityNumPeeps, CityZone, units); // <= match case - 'cityNumPeeps' vs 'CityNumPeeps' etc

            console.log(density);

        }

    };

    function calcPopDensity(pop,area,unit){
        if (units == "miles"){
            return cityZone/cityNumPeeps // <= move the return to this line - we want the result of the calculation back!

        } else if (units == "km"){
            return cityZone * 1.60934 / cityNumPeeps  // <= again, return statement
        }

    };


问:
How to add a new specializer to cl-defmethod apply to multiple major-modes?
How can I extend a cl-defmethod to match on multiple major-modes?  There is a little documentation in cl-generic, but I don't understand what is going on with the generalizer macros.

As an example,

```<code>(cl-defgeneric my-gen-fun (arg)
  (message "%S" arg))

;; define this so it wouldn't affect other cc-derived modes, eg. java, awk, etc.
(cl-defmethod my-gen-fun (&context (major-mode c-mode c++-mode) arg)
  (message "c-%S" arg))
</code>```

I would want (my-gen-fun arg) to only print "c-" in both c-mode and c++-mode, but not other cc-derived modes like java-mode or awk-mode.  How can I add a new specializer to handle this case?

答:
The &context is like %optional in that it applies too all the subsequent args, so it has to come after the arguments.

But the (major-mode <foo>-mode) thingy does not extend to (major-mode <foo>-mode <bar>-mode) like you suggest (although it admittedly would be a natural extension).  So instead you have to call cl-defmethod twice.  If the body is large, you shoud probably put it into a separate function:

```<code>(defun my-gen-fun-c-body (arg)
  (message "c-%S" arg))

;; define this so it wouldn't affect other cc-derived modes, eg. java, awk, etc.
(cl-defmethod my-gen-fun (arg &context (major-mode c-mode))
   (my-gen-fun-c-body arg))
(cl-defmethod my-gen-fun (arg &context (major-mode c++-mode))
   (my-gen-fun-c-body arg))
</code>```

I do have a local patch to cl-generic.el which adds the "multiple major modes" functionality you suggest, but after reviewing it I see that it's kind of a hack and introduces various corner-case problems.

Some of the corner case problems are related to the fact that CLOS does not offer something like or or and specializers like:

```<code>(defmethod foo ((x (or (eql 4) cons))) ...)
</code>```

this is because it can make it "impossible" to find a sound ordering of the applicable methods (e.g.,is the above specializer more or less specific than (x list) or (x (or (eql 5) cons))?).

Body:
How can I extend a cl-defmethod to match on multiple major-modes?  There is a little documentation in cl-generic, but I don't understand what is going on with the generalizer macros.

As an example,

(cl-defgeneric my-gen-fun (arg)
  (message "%S" arg))

;; define this so it wouldn't affect other cc-derived modes, eg. java, awk, etc.
(cl-defmethod my-gen-fun (&context (major-mode c-mode c++-mode) arg)
  (message "c-%S" arg))

I would want (my-gen-fun arg) to only print "c-" in both c-mode and c++-mode, but not other cc-derived modes like java-mode or awk-mode.  How can I add a new specializer to handle this case?

Body:
The &context is like %optional in that it applies too all the subsequent args, so it has to come after the arguments.

But the (major-mode <foo>-mode) thingy does not extend to (major-mode <foo>-mode <bar>-mode) like you suggest (although it admittedly would be a natural extension).  So instead you have to call cl-defmethod twice.  If the body is large, you shoud probably put it into a separate function:

(defun my-gen-fun-c-body (arg)
  (message "c-%S" arg))

;; define this so it wouldn't affect other cc-derived modes, eg. java, awk, etc.
(cl-defmethod my-gen-fun (arg &context (major-mode c-mode))
   (my-gen-fun-c-body arg))
(cl-defmethod my-gen-fun (arg &context (major-mode c++-mode))
   (my-gen-fun-c-body arg))

I do have a local patch to cl-generic.el which adds the "multiple major modes" functionality you suggest, but after reviewing it I see that it's kind of a hack and introduces various corner-case problems.

Some of the corner case problems are related to the fact that CLOS does not offer something like or or and specializers like:

(defmethod foo ((x (or (eql 4) cons))) ...)

this is because it can make it "impossible" to find a sound ordering of the applicable methods (e.g.,is the above specializer more or less specific than (x list) or (x (or (eql 5) cons))?).


问:
How does String.toLowerCase() actually work? How can one create that functionality manually?
To set a String to lowercase, we just need to call the function toLowerCase() on it. But, for a language I am working in right now, there is no such function, so I would need to create one myself. How is Javascript able to achieve that manually?

答:
This sample code as @VLAZ mentioned and without hardcoding the difference (26).
Hope this helps.

const toLowerCase = str => {
  let updated = "";
  const [upp_start, upp_end, low_start] = "AZa"
    .split("")
    .map(x => x.charCodeAt(0));

  for (let i = 0; i < str.length; i++) {
    const charCode = str[i].charCodeAt(0);
    const diff =
      charCode >= upp_start && charCode <= upp_end ? low_start - upp_start : 0;
    updated = updated + String.fromCharCode(charCode + diff);
  }
  return updated;
};

console.log(toLowerCase("Stack"));
console.log(toLowerCase("OVERFLOW"));```


问:
adding sound to an OpenGL app
i am creating an OpenGL application and decided to look into adding sound...
what is the best sound(api?) i was thinking about using OpenAL but i had issues finding any good resources...
if possible could you please provide tutorial/info of some sort.</p>

答:
OpenAL is another choice, plus it resembles OpenGL:

http://connect.creativelabs.com/openal/default.aspx

Title: adding sound to an OpenGL app


问:
Conditional execution of 'getInitialProps' in Next.js
I have global state management using useContext and useReducer I want to check whether the user is authenticated or not. to do so, what occurred to me, was to check inside getInitialProps in this way:

```<code>DashboardPage.getInitialProps = async () => {
  const [globalState, dispatch] = useContext(STORE.storeContext);
  let auth = globalState.isAuthed
  if (!auth) {
    auth = axiox.get('/authenticateThisUser');
  }
  return {
    auth,
  }
}
</code>```

However, when I execute this snippet, it throws Error: Invalid hook call. Hooks can only be called inside of the body of a function component. how can I use useContext inside getInitialProps?

What I'm looking for is a way to prevent components from sending redundant auth requests to
 the server.

It would be great if there were some methods to conditionally execute getInitialProps
like this:

```<code>if(globalState.isAuthed){
    //dont execute getInitialProps of this component
}else {
    //execute getInitialProps of this component
}
</code>```

答:
Actually what I wanted to accomplish could be done using code below:

```<code>DashboardPage.getInitialProps = async ({ req, query, asPath }) => {

    // only in server-side
    if (req) {
        const userUrl = `http://localhost:3000${userConfig.ROUTES.user.getUser}`;
        const isMeUrl = `http://localhost:3000${userConfig.ROUTES.isMe}`;
        const result = await axios.all([axios.get(isMeUrl), axios.get(userUrl)]);

        return {
            me: result[0].data.payload,
            user: result[1].data.payload,
        };
     }
     // only in client-side
     // since we've done authenticating, it is set in the global state management
     // therefore, no need to send any request to the auth API endpoint.
     return {};

};
</code>```

This way we make sure auth requests will be sent only on the server-side (first request) and prevent the component from redundant requests to be sent.

Body:
I have global state management using useContext and useReducer I want to check whether the user is authenticated or not. to do so, what occurred to me, was to check inside getInitialProps in this way:

DashboardPage.getInitialProps = async () => {
  const [globalState, dispatch] = useContext(STORE.storeContext);
  let auth = globalState.isAuthed
  if (!auth) {
    auth = axiox.get('/authenticateThisUser');
  }
  return {
    auth,
  }
}

However, when I execute this snippet, it throws Error: Invalid hook call. Hooks can only be called inside of the body of a function component. how can I use useContext inside getInitialProps?

What I'm looking for is a way to prevent components from sending redundant auth requests to
 the server.

It would be great if there were some methods to conditionally execute getInitialProps
like this:

if(globalState.isAuthed){
    //dont execute getInitialProps of this component
}else {
    //execute getInitialProps of this component
}

Body:
Actually what I wanted to accomplish could be done using code below:

DashboardPage.getInitialProps = async ({ req, query, asPath }) => {

    // only in server-side
    if (req) {
        const userUrl = `http://localhost:3000${userConfig.ROUTES.user.getUser}`;
        const isMeUrl = `http://localhost:3000${userConfig.ROUTES.isMe}`;
        const result = await axios.all([axios.get(isMeUrl), axios.get(userUrl)]);

        return {
            me: result[0].data.payload,
            user: result[1].data.payload,
        };
     }
     // only in client-side
     // since we've done authenticating, it is set in the global state management
     // therefore, no need to send any request to the auth API endpoint.
     return {};

};

This way we make sure auth requests will be sent only on the server-side (first request) and prevent the component from redundant requests to be sent.


问:
Could not increase number of max_open_files to more than 4096 (request: 4214)
I have MariaDB + Nginx on Linux Debian 9(stretch).
After installing MariaDB it and trying to start it, I got the error saying:
[Warning] Could not increase number of max_open_files to more than 4096 (request: 4214).
So I googled it and it told me that I should change LimiNOFILE to 10000 in /etc/systemd/system/mysql.service. I did that, did deamon-reload and it did absolutely nothing. I am still getting the same error message. I tried reinstalling MariaDB but that didn't help either. I also added LimitMEMLOCK=10000 at the very end of my file, that didn't change anything.

Full traceback:

Link

Thank you in advance

答:
It is not enough to change it at service level

You must also edit

/etc/mysql/conf.d/limits.cnf

And have these lines in them

```<code>[mysqld]
open_files_limit = 10000
</code>```

Then,

service mysql restart

And you could increase the number  to 1000000  in limits.conf and mysql.service

Body:
It is not enough to change it at service level

You must also edit

/etc/mysql/conf.d/limits.cnf

And have these lines in them

[mysqld]
open_files_limit = 10000

Then,

service mysql restart

And you could increase the number  to 1000000  in limits.conf and mysql.service