问:
C++ typecasting vs implicit constructor
I'm implementing a c++-class representing a fraction. Here goes my code.

```<code>class Fraction
{
    public:
        Fraction(char i);
        Fraction(int i);
        Fraction(short i);
        Fraction(long int l);
#ifdef __LP64__
        Fraction(long long l);
#endif
        Fraction(float f);
        Fraction(double d);
        Fraction(double x, double y);

        Fraction operator +() const;
        Fraction operator -() const;

        Fraction& operator +=(const Fraction& other);
        Fraction& operator -=(const Fraction& other);
        Fraction& operator *=(const Fraction& other);
        Fraction& operator /=(const Fraction& other);

        bool operator ==(const Fraction& other);
        bool operator !=(const Fraction& other);
        bool operator  >(const Fraction& other);
        bool operator  <(const Fraction& other);
        bool operator >=(const Fraction& other);
        bool operator <=(const Fraction& other);

        operator double();
        operator float();

        static void commonize(Fraction& a, Fraction& b);
        void shorten();

        double getNumerator();
        double getDenominator();

        friend Fraction operator +(Fraction const& a, Fraction const& b);
        friend Fraction operator -(Fraction const& a, Fraction const& b);
        friend Fraction operator *(Fraction const& a, Fraction const& b);
        friend Fraction operator /(Fraction const& a, Fraction const& b);
        friend ostream& operator <<( ostream& o, const Fraction f);

    protected:
        double numerator, denominator;

};
</code>```

I now have two little problems.
Now trying to call

```<code>Fraction a(1, 2);
cout << (3 + a) << endl;
</code>```

simply results in this error:

```<code>fractiontest.cpp:26: error: ambiguous overload for ‘operator+’ in ‘3 + a’
fractiontest.cpp:26: note: candidates are: operator+(int, double) <built-in>
fractiontest.cpp:26: note:                 operator+(int, float) <built-in>
</code>```

All I'd really want is this:

```<code>explicit operator double();
explicit operator float();
</code>```

But apparently, this doesn't work. I'd like these two cast-operators to be called iff I use the cast notation. For example Fraction f(1, 2); double d = (double)(f);

答:
Remove the conversion operators and 3 + a should use your friend operator+ while implicitly converting 3 to Fraction via the implicit constructor Fraction(int i);.

Edit: On the case of the explicit conversion operators, C++0x specifically allows this:

12.3.2 [class.conv.fct] p2

  A conversion function may be explicit, in which case it is only considered as a user-defined conversion for direct-initialization.

The C++03 standard doesn't specifically mention this.

Title: C++ typecasting vs implicit constructor

Body:
I'm implementing a c++-class representing a fraction. Here goes my code.

class Fraction
{
    public:
        Fraction(char i);
        Fraction(int i);
        Fraction(short i);
        Fraction(long int l);
#ifdef __LP64__
        Fraction(long long l);
#endif
        Fraction(float f);
        Fraction(double d);
        Fraction(double x, double y);

        Fraction operator +() const;
        Fraction operator -() const;

        Fraction& operator +=(const Fraction& other);
        Fraction& operator -=(const Fraction& other);
        Fraction& operator *=(const Fraction& other);
        Fraction& operator /=(const Fraction& other);

        bool operator ==(const Fraction& other);
        bool operator !=(const Fraction& other);
        bool operator  >(const Fraction& other);
        bool operator  <(const Fraction& other);
        bool operator >=(const Fraction& other);
        bool operator <=(const Fraction& other);

        operator double();
        operator float();

        static void commonize(Fraction& a, Fraction& b);
        void shorten();

        double getNumerator();
        double getDenominator();

        friend Fraction operator +(Fraction const& a, Fraction const& b);
        friend Fraction operator -(Fraction const& a, Fraction const& b);
        friend Fraction operator *(Fraction const& a, Fraction const& b);
        friend Fraction operator /(Fraction const& a, Fraction const& b);
        friend ostream& operator <<( ostream& o, const Fraction f);

    protected:
        double numerator, denominator;

};

I now have two little problems.
Now trying to call

Fraction a(1, 2);
cout << (3 + a) << endl;

simply results in this error:

fractiontest.cpp:26: error: ambiguous overload for ‘operator+’ in ‘3 + a’
fractiontest.cpp:26: note: candidates are: operator+(int, double) <built-in>
fractiontest.cpp:26: note:                 operator+(int, float) <built-in>

All I'd really want is this:

explicit operator double();
explicit operator float();

But apparently, this doesn't work. I'd like these two cast-operators to be called iff I use the cast notation. For example Fraction f(1, 2); double d = (double)(f);


来源: stackexchange

问:
Why does my React form auto-refresh the page even if I put "event.preventDefault()" on handleSubmit?
I have two files which work together to render things. The first is App.js, which first renders Form.js. The form will then collect information, which on submission, changes the Form state and calls a function from App.js. This function is called "createProject." Calling "createProject" in Form.js "handleSubmit" makes the page auto-refresh. However, if I remove "createProject" from handleSubmit, the page does not auto-refresh. Here are the two files.

import React, { Component } from "react";
import Project from "./components/Project.js"
import Form from "./Form.js";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            projectList: [],
            myProjects: [],
            userList: [],
            submitted: false
        };

        this.createProject = this.createProject.bind(this);
    }

    createProject(title, desc, langs, len, exp) {
        this.setState({
            projectList: this.state.projectList.push([
                {
                    title : title,
                    description : desc,
                    language : langs,
                    length : len,
                    experience : exp
                }
            ]),
            submitted : true
        });
    }

    deleteProject(title) {
        const projects = this.state.projectList.filter(
            p => p.title !== title
        );
        this.setState({projects});
    }

    render() {
        let info;
        if (this.state.submitted) {
            info = (

cccc

            );
        } else {
            info = (

            );
        }
        return(

                <Form/>
                {info}
                {this.state.projectList.map((params) =>
                <Project {...params}/>)}

        );
    }

}

export default App;```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from "react";
import createProject from "./App.js"

class Form extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        title: "",
        description: "",
        language: "",
        length: 0,
        experience: "",
        submitted: false
      };

      this.handleSubmit = this.handleSubmit.bind(this);
      this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleSubmit(event) {

      this.setState({
        submitted: true
      })
      createProject(
        this.state.title,
        this.state.description,
        this.state.language,
        this.state.length,
        this.state.experience
      )
      event.preventDefault();
    }

    handleInputChange(event) {
      const target = event.target;
      const value = target.value;
      const name = target.name;

      this.setState({
        [name]: value
      });
    }

    render() {
      let info;
      if (this.state.submitted) {
        info = (
          <div>
            <h1>{this.state.title}</h1>
            <p>{this.state.description}</p>
            <p>{this.state.language}</p>
            <p>{this.state.length}</p>
            <p>{this.state.experience}</p>
           </div>
        );
      } else {
          info = <br/>;
      }
      return (
        <div>
            <form onSubmit={this.handleSubmit}>
            <label>
                Title:
                <input
                name="title"
                type="textbox"
                checked={this.state.title}
                onChange={this.handleInputChange} />
            </label>
            <br />
            <label>
                Description:
                <input
                name="description"
                type="textbox"
                checked={this.state.description}
                onChange={this.handleInputChange} />
            </label>
            <br />
            <label>
                Language:
                <input
                name="language"
                type="textbox"
                checked={this.state.language}
                onChange={this.handleInputChange} />
            </label>
            <br />
            <label>
                Length:
                <input
                name="length"
                type="number"
                checked={this.state.length}
                onChange={this.handleInputChange} />
            </label>
            <br />
            <label>
                Experience:
                <input
                name="experience"
                type="textbox"
                checked={this.state.experience}
                onChange={this.handleInputChange} />
            </label>
            <br />
            <input type="submit" value="Submit" />
            </form>
          {info}
        </div>
      );
    }
  }

export default Form;</code>```

I've also tried adding "new" to the "createProject" in handleSubmit, and while that does stop the auto-refresh, it will not call the createProject function. (Or maybe it does, but none of the code in the createProject function seems to be run.) Can anyone help with preventing this auto refresh while also allowing App's createProject function to run properly?

答:
The page auto refreshes because execution never gets to your event.PreventDefault() line. This is due to an error encountered when react tries to evaluate createProject. To fix this, correct handleSubmit like so.

```<code>handleSubmit(event) {

  event.preventDefault(); // moved up in execution.

  this.setState({
    submitted: true
  })
  createProject(
    this.state.title,
    this.state.description,
    this.state.language,
    this.state.length,
    this.state.experience
  )
}
</code>```

Notice that moving event.PreventDefault() to the top of your handleSubmit(event) function just before this.setState line prevents default form behaviour on submit.

You however get an error because App.js doesn't export a function called createProject. To maintain the createProject within App instance, you need to pass it as a prop which you can then reference as this.props.createProject.

See this answer on how to do call a Parent method in ReactJS.

ContentLicense: CC BY-SA 4.0

Body:
I have two files which work together to render things. The first is App.js, which first renders Form.js. The form will then collect information, which on submission, changes the Form state and calls a function from App.js. This function is called "createProject." Calling "createProject" in Form.js "handleSubmit" makes the page auto-refresh. However, if I remove "createProject" from handleSubmit, the page does not auto-refresh. Here are the two files.

import React, { Component } from "react";
import Project from "./components/Project.js"
import Form from "./Form.js";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            projectList: [],
            myProjects: [],
            userList: [],
            submitted: false
        };

        this.createProject = this.createProject.bind(this);
    }

    createProject(title, desc, langs, len, exp) {
        this.setState({
            projectList: this.state.projectList.push([
                {
                    title : title,
                    description : desc,
                    language : langs,
                    length : len,
                    experience : exp
                }
            ]),
            submitted : true
        });
    }

    deleteProject(title) {
        const projects = this.state.projectList.filter(
            p => p.title !== title
        );
        this.setState({projects});
    }

    render() {
        let info;
        if (this.state.submitted) {
            info = (

cccc

            );
        } else {
            info = (

            );
        }
        return(

                <Form/>
                {info}
                {this.state.projectList.map((params) =>
                <Project {...params}/>)}

        );
    }

}

export default App;

import React from "react";
import createProject from "./App.js"

class Form extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        title: "",
        description: "",
        language: "",
        length: 0,
        experience: "",
        submitted: false
      };

      this.handleSubmit = this.handleSubmit.bind(this);
      this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleSubmit(event) {

      this.setState({
        submitted: true
      })
      createProject(
        this.state.title,
        this.state.description,
        this.state.language,
        this.state.length,
        this.state.experience
      )
      event.preventDefault();
    }

    handleInputChange(event) {
      const target = event.target;
      const value = target.value;
      const name = target.name;

      this.setState({
        [name]: value
      });
    }

    render() {
      let info;
      if (this.state.submitted) {
        info = (

{this.state.title}

{this.state.description}

{this.state.language}

{this.state.length}

{this.state.experience}

        );
      } else {
          info =
;
      }
      return (

            <form onSubmit={this.handleSubmit}>

                Title:
                <input
                name="title"
                type="textbox"
                checked={this.state.title}
                onChange={this.handleInputChange} />

                Description:
                <input
                name="description"
                type="textbox"
                checked={this.state.description}
                onChange={this.handleInputChange} />

                Language:
                <input
                name="language"
                type="textbox"
                checked={this.state.language}
                onChange={this.handleInputChange} />

                Length:
                <input
                name="length"
                type="number"
                checked={this.state.length}
                onChange={this.handleInputChange} />

                Experience:
                <input
                name="experience"
                type="textbox"
                checked={this.state.experience}
                onChange={this.handleInputChange} />

            <input type="submit" value="Submit" />
            </form>
          {info}

      );
    }
  }

export default Form;

I've also tried adding "new" to the "createProject" in handleSubmit, and while that does stop the auto-refresh, it will not call the createProject function. (Or maybe it does, but none of the code in the createProject function seems to be run.) Can anyone help with preventing this auto refresh while also allowing App's createProject function to run properly?

Body:
The page auto refreshes because execution never gets to your event.PreventDefault() line. This is due to an error encountered when react tries to evaluate createProject. To fix this, correct handleSubmit like so.

handleSubmit(event) {

  event.preventDefault(); // moved up in execution.

  this.setState({
    submitted: true
  })
  createProject(
    this.state.title,
    this.state.description,
    this.state.language,
    this.state.length,
    this.state.experience
  )
}

Notice that moving event.PreventDefault() to the top of your handleSubmit(event) function just before this.setState line prevents default form behaviour on submit.

You however get an error because App.js doesn't export a function called createProject. To maintain the createProject within App instance, you need to pass it as a prop which you can then reference as this.props.createProject.

See this answer on how to do call a Parent method in ReactJS.


问:
Select the First value Greater than a specific value
I have two tables first table is Stock Receiving

```<code>  Store   Item_No        Receiving_Time

   2       1         2020-05-27 13:44:27.829 UTC
   2       1         2020-05-27 17:44:28.829 UTC
   2       1         2020-05-28 14:44:28.829 UTC
   2       1         2020-05-29 14:44:28.829 UTC
</code>```

Second one is item going Out of Stock

```<code>   Store   Item_No        Out_OF_Stock_Time

       2       1         2020-05-26 13:44:27.829 UTC
       2       1         2020-05-27 18:44:28.829 UTC
       2       1         2020-05-27 20:44:28.829 UTC
</code>```

So i want to find the value when the last out of stock was filled in my case last out of stock happens on 2020-05-27 20:44:28.829 UTC so output value should be 2020-05-28 14:44:28.829 UTC
from Stock Receiving Table

SO output:

```<code>Store Item_No.    Last_OutOfStock.              Received Time                   Difference Time
2.      1        2020-05-27 20:44:28.829 UTC    2020-05-28 14:44:28.829 UTC
</code>```

My Query:

```<code>Select  o.store, o.item_No, Max(o.Out_OF_Stock_Time) as S, Min(r.Receiving_Time) as R
from Out_of_Stock o
join Stock_Receiving r on o.store = r.store and o.item_no = r.item_no
and S < R
group By o.store, o.item_No;
</code>```

So it's not getting me the right result.

答:
Please use below query, if your Receiving_Time and Out_OF_Stock_Time is in date datatype, below query will work. If not please convert the format in the query </p>

```<code>Select  o.store, o.item_No, Max(o.Out_OF_Stock_Time) as S,
Min(r.Receiving_Time) as R,
Min(r.Receiving_Time) - Max(o.Out_OF_Stock_Time) as Difference
from Out_of_Stock o
join Stock_Receiving r on o.store = r.store and o.item_no = r.item_no
group By o.store, o.item_No
having Min(r.Receiving_Time) > Max(o.Out_OF_Stock_Time);
</code>```

Body:
I have two tables first table is Stock Receiving

  Store   Item_No        Receiving_Time

   2       1         2020-05-27 13:44:27.829 UTC
   2       1         2020-05-27 17:44:28.829 UTC
   2       1         2020-05-28 14:44:28.829 UTC
   2       1         2020-05-29 14:44:28.829 UTC

Second one is item going Out of Stock

   Store   Item_No        Out_OF_Stock_Time

       2       1         2020-05-26 13:44:27.829 UTC
       2       1         2020-05-27 18:44:28.829 UTC
       2       1         2020-05-27 20:44:28.829 UTC

So i want to find the value when the last out of stock was filled in my case last out of stock happens on 2020-05-27 20:44:28.829 UTC so output value should be 2020-05-28 14:44:28.829 UTC
from Stock Receiving Table

SO output:

Store Item_No.    Last_OutOfStock.              Received Time                   Difference Time
2.      1        2020-05-27 20:44:28.829 UTC    2020-05-28 14:44:28.829 UTC

My Query:

Select  o.store, o.item_No, Max(o.Out_OF_Stock_Time) as S, Min(r.Receiving_Time) as R
from Out_of_Stock o
join Stock_Receiving r on o.store = r.store and o.item_no = r.item_no
and S < R
group By o.store, o.item_No;

So it's not getting me the right result.

Body:
Please use below query, if your Receiving_Time and Out_OF_Stock_Time is in date datatype, below query will work. If not please convert the format in the query

Select  o.store, o.item_No, Max(o.Out_OF_Stock_Time) as S,
Min(r.Receiving_Time) as R,
Min(r.Receiving_Time) - Max(o.Out_OF_Stock_Time) as Difference
from Out_of_Stock o
join Stock_Receiving r on o.store = r.store and o.item_no = r.item_no
group By o.store, o.item_No
having Min(r.Receiving_Time) > Max(o.Out_OF_Stock_Time);


问:
How do I can install pip inside virtual environment
I have created one virtual-environment. Inside that I have to install few python packages. For that I need pip package inside virtual environment. How can I install pip inside virtual-environment?</p>

答:
When you create a virtual environment for a particular python revision installed in your computer, all the libraries currently installed in your python revision would be copied inside the virtual environment.
Pip is usually default available in your python revision directory.

If not, install it first in your original python install directory.
Then copy the pip.exe to the virtual environment's Scripts directory.
After that execute the below command from your terminal (this is for Windows):

```<code>\your_venv_directory_path\Scripts\pip.exe install --upgrade pip
</code>```

Now you can just type
pip install --upgrade pip
and it should recognise the path to the pip.exe file inside your venv

ContentLicense: CC BY-SA 3.0

Body:
When you create a virtual environment for a particular python revision installed in your computer, all the libraries currently installed in your python revision would be copied inside the virtual environment.
Pip is usually default available in your python revision directory.

If not, install it first in your original python install directory.
Then copy the pip.exe to the virtual environment's Scripts directory.
After that execute the below command from your terminal (this is for Windows):

\your_venv_directory_path\Scripts\pip.exe install --upgrade pip

Now you can just type
pip install --upgrade pip
and it should recognise the path to the pip.exe file inside your venv


问:
Flutter textfield onChanged - detect if last text typed in is a taghandle '@mention'
I'm looking to create a textfield which upon onChanged detects if a user has typed the @ tagHandle and trailing text (similar to a mention taghandle in twitter) which in turn will trigger the _callToAction().

As a code example, the following code only triggers each time the @ symbol is typed in:

```<code>TextField(
  onChanged: (value) {
    if (value.endsWith("@")) {
      _callToAction();
    }
  }
)
</code>```

However this is not the desired result as i need to detect the trailing text after the @ symbol (@mention) which should work both when the user is typing into the form and when they are backspacing and come across a previously typed @mention taghandle.

答:
Here is a solution , it's not the optimized one but it does work.

Keep variable to check if @ is detected and the other 2 variables to hold the index of the @handle.

```<code>bool detected = false;
int startIndexOfTag = 0;
int endIndexOfTag = 0;
</code>```

And then in onChanged of the TextField

```<code>onChanged: (value) {
    if (value.endsWith('@')) {
      detected = true;
      startIndexOfTag = value.length - 1;
    }

    if (detected == true) {
      print(value.substring(startIndexOfTag));
    }

    if ((detected == true && value.endsWith(' ')) || startIndexOfTag == 1) {
      detected = false;
      endIndexOfTag = value.length;
    }

    if (value.length < endIndexOfTag) {
      detected = true;
      endIndexOfTag = value.length;
      startIndexOfTag = value.indexOf('@');
    }
  },
</code>```

Here is a the DartPad for the same.

Body:
I'm looking to create a textfield which upon onChanged detects if a user has typed the @ tagHandle and trailing text (similar to a mention taghandle in twitter) which in turn will trigger the _callToAction().

As a code example, the following code only triggers each time the @ symbol is typed in:

TextField(
  onChanged: (value) {
    if (value.endsWith("@")) {
      _callToAction();
    }
  }
)

However this is not the desired result as i need to detect the trailing text after the @ symbol (@mention) which should work both when the user is typing into the form and when they are backspacing and come across a previously typed @mention taghandle.

Body:
Here is a solution , it's not the optimized one but it does work.

Keep variable to check if @ is detected and the other 2 variables to hold the index of the @handle.

bool detected = false;
int startIndexOfTag = 0;
int endIndexOfTag = 0;

And then in onChanged of the TextField

onChanged: (value) {
    if (value.endsWith('@')) {
      detected = true;
      startIndexOfTag = value.length - 1;
    }

    if (detected == true) {
      print(value.substring(startIndexOfTag));
    }

    if ((detected == true && value.endsWith(' ')) || startIndexOfTag == 1) {
      detected = false;
      endIndexOfTag = value.length;
    }

    if (value.length < endIndexOfTag) {
      detected = true;
      endIndexOfTag = value.length;
      startIndexOfTag = value.indexOf('@');
    }
  },

Here is a the DartPad for the same.


问:
SAS Chars obs in Numeric column
I have a numeric column and it has Chars values. I need to extract the string but if I convert to char the column it extracts a number. How can I extract the string?</p>

答:
Are you meaning to get strings that can not be convert into numbers? Try this:</p>

```<code>if input(rawvar,??best.) = . then newvar = rawvar;
</code>```

Title: SAS Chars obs in Numeric column

Body:
Are you meaning to get strings that can not be convert into numbers? Try this:

if input(rawvar,??best.) = . then newvar = rawvar;


问:
Getting widgetId from reCAPTCHA v2 from g-recaptcha tag?
Hi this is my first attempt posting question here.

I want to know if I can ever get widgetId from the g-recaptcha tag and not from the returning value of grecaptcha.render() of reCAPTCHA v2.

The reason behind this is that I have 2 different scripts that handles each 2 forms on a same page.
I want to be able to reset the reCAPTCHA individually.

Each scripts have thier own onload callback that supposed to get their own widgetId.
But this does not work because it seems there is only 1 onload callback functions can be called by the url parameter of the google reCAPTCHA code.

I couldn't have multiple onload callback functions set to the recaptcha source url like below.

"https://www.google.com/recaptcha/api.js?onload=onloadCallback1,onloadCallback2&render=onload"

"https://www.google.com/recaptcha/api.js?onload[]=onloadCallback1&onload[]=onloadCallback2&render=onload"

So I thought maybe I can get the widget Id from the g-recaptcha tag after loaded...

Any idea or solution???

答:
Is the question how to have 2 callbacks? How about: "...onload=twoCallbacks"</p>

```<code>function twoCallbacks(...args){
  callback1(...args)
  callback2(...args)
}
</code>```

Body:
Is the question how to have 2 callbacks? How about: "...onload=twoCallbacks"

function twoCallbacks(...args){
  callback1(...args)
  callback2(...args)
}


问:
A proper way to Debug a Service in Android Studio?
Is there a proper way to debug a service in Android Studio? Or Android Studio could not do this? When I try to debug, it will just disconnects the sockets. ("Disconnected from the Target VM, address:'localhost:8600',transport 'socket')

Hopefully you can assist me here..

What I have done as advice by some links here, I had place the .waitForDebugger but nothing happens. Please help me.. Thank you very much.

```<code>   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent mainService = new Intent(this,MainPowerAndVolumeService.class);

    startService(mainService);
    android.os.Debug.waitForDebugger();

    finish();

}
</code>```

答:
(updated in August 2020: the button in Android Studio 4.0 has the same icon)

So it is waiting for the debugger to attach, once the service has started, but you still need to tell Android Studio to attach to the process (it doesn't happen automatically).

Press the button to attach to process (see screenshot for Android Studio 3.6 .. it is the 3rd button to the right from the debug button). You will be given a choice of processes to attach to, one of which would be the background service's separate process.

The timing of when you press the button to attach to the process, needs to be after the background service has started (while it is waiting at android.os.Debug.waitForDebugger();), otherwise the process would not exist and you would not be able to select it.

Body:
Is there a proper way to debug a service in Android Studio? Or Android Studio could not do this? When I try to debug, it will just disconnects the sockets. ("Disconnected from the Target VM, address:'localhost:8600',transport 'socket')

Hopefully you can assist me here..

What I have done as advice by some links here, I had place the .waitForDebugger but nothing happens. Please help me.. Thank you very much.

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent mainService = new Intent(this,MainPowerAndVolumeService.class);

    startService(mainService);
    android.os.Debug.waitForDebugger();

    finish();

}


问:
Parameter inside a method for javascript
```<code>function exerciseOne(){
  // Exercise One: In this exercise you are given an object called 'mathHelpers'
  // Within mathHelpers, create a method called 'double'
  // This method should take one parameter, a number,
  // and it should return that number multiplied by two.
  let mathHelpers = {
    // Create double method in here.
    double: function(myNumber){
      myNumber * 2;
    }
  };
  return mathHelpers;
}
</code>```

It's coming back it's incorrect. Been stuck on this for 90 mins. What am I doing wrong?

This is the code prior to me working on it

```<code>function exerciseOne(){
  // Exercise One: In this exercise you are given an object called 'mathHelpers'
  // Within mathHelpers, create a method called 'double'
  // This method should take one parameter, a number,
  // and it should return that number multiplied by two.
  let mathHelpers = {
    // Create double method in here.

  };
  return mathHelpers;
}
</code>```

答:
I figured thanks anyways lol</p>

```<code>function exerciseOne(){
  // Exercise One: In this exercise you are given an object called 'mathHelpers'
  // Within mathHelpers, create a method called 'double'
  // This method should take one parameter, a number,
  // and it should return that number multiplied by two.
  let mathHelpers = {
    // Create double method in here.
    double: function(myNumber = 4){
      return myNumber * 2;
    }
  };
  return mathHelpers;
}
</code>```

Body:
function exerciseOne(){
  // Exercise One: In this exercise you are given an object called 'mathHelpers'
  // Within mathHelpers, create a method called 'double'
  // This method should take one parameter, a number,
  // and it should return that number multiplied by two.
  let mathHelpers = {
    // Create double method in here.
    double: function(myNumber){
      myNumber * 2;
    }
  };
  return mathHelpers;
}

It's coming back it's incorrect. Been stuck on this for 90 mins. What am I doing wrong?

This is the code prior to me working on it

function exerciseOne(){
  // Exercise One: In this exercise you are given an object called 'mathHelpers'
  // Within mathHelpers, create a method called 'double'
  // This method should take one parameter, a number,
  // and it should return that number multiplied by two.
  let mathHelpers = {
    // Create double method in here.

  };
  return mathHelpers;
}

Body:
I figured thanks anyways lol

function exerciseOne(){
  // Exercise One: In this exercise you are given an object called 'mathHelpers'
  // Within mathHelpers, create a method called 'double'
  // This method should take one parameter, a number,
  // and it should return that number multiplied by two.
  let mathHelpers = {
    // Create double method in here.
    double: function(myNumber = 4){
      return myNumber * 2;
    }
  };
  return mathHelpers;
}


问:
How do you initialize values in SwiftUI before view is loaded?
I want to take say a stock price and then generate values within .05% in a 2D array.

I am passing the stock information such as stock name and stock price.

But when I try and run a method that creates the 2D array of values I am met with a "Cannot use instance member '' within property initializer; property initializers run before 'self' is available"

I was looking how to get around this.

Say Amazon stock is 2400. This data passes into the new view. What I want to do is create a 2D array of values near 2400, perhaps 2405 and 2395. I want a 2D array of these values generated in the new view. But I am getting an error that I cannot generate the values until the view is loaded, but I need them to generate the view.

I think I have to use init method but I am not sure how.

This is the line that is throwing the error above.

```<code>var new_prices = generateValues(price: position.stock_price)
</code>```

Here is the method

```<code>func generateValues(price: Double) -> [[Double]] {
    var values = [[Double]]()
     for x in 1...5 {
        values[0][x-1] = (price + price * 0.005 * Double(x))
    }
    return values
}
</code>```

This is what is being passed in the stock postion

```<code>struct Position : Identifiable {
    var id = UUID()
    var stock_name: String
    var stock_ticker: String
    var stock_price: Double
    var price_paid: Double

}
</code>```

Arguments passed throwing an error for no argument init().

```<code>struct PositionDetail_Previews: PreviewProvider {
    static var previews: some View {
        PositionDetail(position: Position(stock_name: "Amazon",
stock_ticker: "AMZN", stock_price : 2400, price_paid : 2300))
    }
}
</code>```

答:
If I correctly understood & replicated your code initially you have got this

so here is a solution (tested with Xcode 11.4 / iOS 13.4)

```<code>func generateValues(price: Double) -> [[Double]] {
    var values = [[Double]]()
    for x in 1...5 {
        values[0][x-1] = (price + price * 0.005 * Double(x))
    }
    return values
}

struct PositionDetail: View {
    var position: Position
    var new_prices: [[Double]]

    init(position: Position) {
        self.position = position
        self.new_prices = generateValues(price: position.stock_price)
    }

    var body: some View {
        VStack { // << just for demo
            Text("Position: \(self.position.stock_name)")
            Text("First price: \(self.new_prices[0][0])")
        }
    }
}
</code>```

other code with no changes.

Body:
I want to take say a stock price and then generate values within .05% in a 2D array.

I am passing the stock information such as stock name and stock price.

But when I try and run a method that creates the 2D array of values I am met with a "Cannot use instance member '' within property initializer; property initializers run before 'self' is available"

I was looking how to get around this.

Say Amazon stock is 2400. This data passes into the new view. What I want to do is create a 2D array of values near 2400, perhaps 2405 and 2395. I want a 2D array of these values generated in the new view. But I am getting an error that I cannot generate the values until the view is loaded, but I need them to generate the view.

I think I have to use init method but I am not sure how.

This is the line that is throwing the error above.

var new_prices = generateValues(price: position.stock_price)

Here is the method

func generateValues(price: Double) -> [[Double]] {
    var values = [[Double]]()
     for x in 1...5 {
        values[0][x-1] = (price + price * 0.005 * Double(x))
    }
    return values
}

This is what is being passed in the stock postion

struct Position : Identifiable {
    var id = UUID()
    var stock_name: String
    var stock_ticker: String
    var stock_price: Double
    var price_paid: Double

}

Arguments passed throwing an error for no argument init().

struct PositionDetail_Previews: PreviewProvider {
    static var previews: some View {
        PositionDetail(position: Position(stock_name: "Amazon",
stock_ticker: "AMZN", stock_price : 2400, price_paid : 2300))
    }
}

Body:
If I correctly understood & replicated your code initially you have got this

so here is a solution (tested with Xcode 11.4 / iOS 13.4)

func generateValues(price: Double) -> [[Double]] {
    var values = [[Double]]()
    for x in 1...5 {
        values[0][x-1] = (price + price * 0.005 * Double(x))
    }
    return values
}

struct PositionDetail: View {
    var position: Position
    var new_prices: [[Double]]

    init(position: Position) {
        self.position = position
        self.new_prices = generateValues(price: position.stock_price)
    }

    var body: some View {
        VStack { // << just for demo
            Text("Position: \(self.position.stock_name)")
            Text("First price: \(self.new_prices[0][0])")
        }
    }
}

other code with no changes.


问:
Firebase StartAt() doesn't work - it returns the same results without it
I'm trying to get the first 5 results (1-5), and then (6-10)... and so on.
I save the last value I received, in order to StartAt where I stopped,
but when I check the new values it still shows values 1-5 and not 6-10.

Also, I don't understand if I really have to use orderByChild while my keys are already sorted on DB.

My DB-

```<code>users
    +user1
    +user2
    +user3
    +user4
    +user5
    +user6
    .....
    +user50
</code>```

First 1-5:

```<code>  task = await FirebaseDatabase.DefaultInstance.GetReference("users").OrderByValue().LimitToFirst(5).GetValueAsync().ContinueWith(t => t);
</code>```

That works fine.
Now I'm trying to get users 6-10

```<code>  lastUserId= "user5"
  task=null;
  task = await FirebaseDatabase.DefaultInstance.GetReference("users").OrderByValue().StartAt(lastUserId).LimitToFirst(5).GetValueAsync().ContinueWith(t => t);
  DataSnapshot dts = task.Result;
  foreach (DataSnapshot s in dts.Children)
  {
  Debug.Log(s.Key);
  }
</code>```

output:
user1
user2
user3
user4
user5
Why does it start from user1 if my code says StartAt("user5")?? What am I missing?

答:
As per your comment, here is my (very short) answer:

You should use OrderByKey.StartAt('userId') rather than OrderByValue.

Glad I could help.

Body:
I'm trying to get the first 5 results (1-5), and then (6-10)... and so on.
I save the last value I received, in order to StartAt where I stopped,
but when I check the new values it still shows values 1-5 and not 6-10.

Also, I don't understand if I really have to use orderByChild while my keys are already sorted on DB.

My DB-

users
    +user1
    +user2
    +user3
    +user4
    +user5
    +user6
    .....
    +user50

First 1-5:

  task = await FirebaseDatabase.DefaultInstance.GetReference("users").OrderByValue().LimitToFirst(5).GetValueAsync().ContinueWith(t => t);

That works fine.
Now I'm trying to get users 6-10

  lastUserId= "user5"
  task=null;
  task = await FirebaseDatabase.DefaultInstance.GetReference("users").OrderByValue().StartAt(lastUserId).LimitToFirst(5).GetValueAsync().ContinueWith(t => t);
  DataSnapshot dts = task.Result;
  foreach (DataSnapshot s in dts.Children)
  {
  Debug.Log(s.Key);
  }

output:
user1
user2
user3
user4
user5
Why does it start from user1 if my code says StartAt("user5")?? What am I missing?


问:
How to deal with variable number of columns in dataframe
In the dataframe I have there are so many columns of which I only need a few. For instance

```<code>Col_A      Col_B      Col_C      Col_D      Col_E      Col_F
...        ...        ...      ...      ...      ...      ...
</code>```

I only need columns Col_A, Col_C and Col_E so currently what I do is df = df[['Col_A', 'Col_C', 'Col_E']] but the issue here is that not always there will columns A, C and E maybe all these wont be present. So I need if Col_A is in df.columns add to the df and so on. Is there any simple method to do this ? rather than so many if? Now if a Column is missing I get a KeyError: "['Col_C'] not in index

答:
Use Index.intersection:

```<code>df[df.columns.intersection(['Col_A','Col_A','Col_E'], sort=False)]
</code>```

Body:
In the dataframe I have there are so many columns of which I only need a few. For instance

Col_A      Col_B      Col_C      Col_D      Col_E      Col_F
...        ...        ...      ...      ...      ...      ...

I only need columns Col_A, Col_C and Col_E so currently what I do is df = df[['Col_A', 'Col_C', 'Col_E']] but the issue here is that not always there will columns A, C and E maybe all these wont be present. So I need if Col_A is in df.columns add to the df and so on. Is there any simple method to do this ? rather than so many if? Now if a Column is missing I get a KeyError: "['Col_C'] not in index

Body:
Use Index.intersection:

df[df.columns.intersection(['Col_A','Col_A','Col_E'], sort=False)]


问:
Check if a word is enclosed within quotes using javascript
I have a string like get(3,"No MATCH",obj). I want to check if the word MATCH is enclosed within quotes (either single quote or double quote). Here MATCH is enclosed within quotes, although not exactly as "MATCH", it is still a part of the text contained in quotes as "No MATCH".

I want to write a function which takes the word (MATCH) as argument and returns true if it is contained within quotes or false if not.

Following are some other input strings which needs to be checked by this
function:

* get(1101,"MATCH",obj) --> return true since MATCH is within quotes

* get(255,'NO MATCH',obj) --> return true since MATCH is a part of text contained within quotes

* get(1111,"" , MATCH) ---> return false since MATCH is not contained within quotes

答:
Have a go with this

https://regex101.com/r/Bu4LUO/2

```<code>/['"]([ \w]+)?MATCH([ \w]+)?["']/gm
</code>```

Body:
Have a go with this

https://regex101.com/r/Bu4LUO/2

/['"]([ \w]+)?MATCH([ \w]+)?["']/gm


问:
bash script to find unique value in a file with index
I have a text file ,test.txt, like

```<code>shekhar cbv
ravi cbv
ravi sdf
asd df
ravi Df
ravi dfg
ravi df
ravi dfg
ravi df
afas cvb
sdf hgh
sasdg cfg
</code>```

I want to sort based on 2nd field and want to write 2nd field only on "result.txt"
 Currently I am doing following:

sort -k 2,2 test.txt| uniq -i -f 1 | cut -d ' ' -f2 > result.txt

which is writing 2n field i.e.

```<code>cbv
cfg
cvb
df
dfg
hgh
sdf
</code>```

Corresponding to every unique 2nd field value I want its,all, index in original file.
How this is possible ?

Desired Output:

```<code>cbv 1 2
cfg 12
cvb 10
df 4 5 7 9
dfg 6 8
hgh 11
sdf 3
</code>```

One more thing if say there is 3rd field also. How to achieve the above only mean while sorting and finding uniqueness only 2nd field is used.

input With 3rd field

```<code>    shekhar cbv rg
    ravi cbv fdf
    ravi sdf dfh
    asd df dfhdfh
    ravi Df fgh
    ravi dfg dfh
    ravi df dfgh
    ravi dfg dfgh
    ravi df dfhg
    afas cvb fhfg
    sdf hgh cgfhfg
    sasdg cfg fgh
</code>```

Desired o/p same .
Thanks,
Ravi

答:
You're so close! To get the value of the second column based on what you've done so far, you should use awk. It is made for processing a stream line by line and extracting just the parts you want.

Your code: sort -k 2,2 test.txt| uniq -i -f 1 | cut -d ' ' -f2 > result.txt

With awk: sort -k 2,2 test.txt| uniq -i -f 1 | cut -d ' ' -f2 | awk '{print $2}' > result.txt

Awk will split your input by whitespace, and print $2 will take the second text block. I'd recommend looking into awk - it is great for many problems.

Body:
I have a text file ,test.txt, like

shekhar cbv
ravi cbv
ravi sdf
asd df
ravi Df
ravi dfg
ravi df
ravi dfg
ravi df
afas cvb
sdf hgh
sasdg cfg

I want to sort based on 2nd field and want to write 2nd field only on "result.txt"
 Currently I am doing following:

sort -k 2,2 test.txt| uniq -i -f 1 | cut -d ' ' -f2 > result.txt

which is writing 2n field i.e.

cbv
cfg
cvb
df
dfg
hgh
sdf

Corresponding to every unique 2nd field value I want its,all, index in original file.
How this is possible ?

Desired Output:

cbv 1 2
cfg 12
cvb 10
df 4 5 7 9
dfg 6 8
hgh 11
sdf 3

One more thing if say there is 3rd field also. How to achieve the above only mean while sorting and finding uniqueness only 2nd field is used.

input With 3rd field

    shekhar cbv rg
    ravi cbv fdf
    ravi sdf dfh
    asd df dfhdfh
    ravi Df fgh
    ravi dfg dfh
    ravi df dfgh
    ravi dfg dfgh
    ravi df dfhg
    afas cvb fhfg
    sdf hgh cgfhfg
    sasdg cfg fgh

Desired o/p same .
Thanks,
Ravi


问:
How do I edit multiple elements in a list on a conditional basis?
An assignment I'm working on for school has tasked me with writing a script in Python that will edit a list of file names. All the files that end with the "hpp" extension must be renamed to "h".

```<code>filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
</code>```

Can this be solved using a list comparision? This is what I have so far...

```<code>def newfilenames(filenames):
  elements = [ "h".format(filenames) for filenames]
</code>```

答:
```<code>def newfilenames(filenames:list):
    if not filenames:
        return filenames
    for i in range(len(filenames)):
        if filenames[i].endswith('.hpp'):
            filenames[i] = filenames[i][:-4] + '.h'
    return filenames
</code>```

Body:
An assignment I'm working on for school has tasked me with writing a script in Python that will edit a list of file names. All the files that end with the "hpp" extension must be renamed to "h".

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]

Can this be solved using a list comparision? This is what I have so far...

def newfilenames(filenames):
  elements = [ "h".format(filenames) for filenames]


问:
How to bundle install gemfile with specific version of bundler
I am trying to bundle install a project running gem 'rails', '4.2.0'.
Running Bundle install, I get :

```<code>Bundler could not find compatible versions for gem "bundler":
  In Gemfile:
    rails (= 4.2.0) was resolved to 4.2.0, which depends on
      bundler (>= 1.3.0, < 2.0)

  Current Bundler version:
    bundler (2.1.4)
This Gemfile requires a different version of Bundler.
Perhaps you need to update Bundler by running `gem install bundler`?

Could not find gem 'bundler (>= 1.3.0, < 2.0)', which is required by gem 'rails (= 4.2.0)', in any of the sources.
</code>```

Thus I then try to install bundler v 1.3.0 to successfully bundle this gemfile : gem install bundler -v 1.3.0

```<code>gem list bundler shows me that I successfully installed bundler at v 1.3.0
</code>```

Then when trying to bundle install with v 1.3.0 like this bundle _1.3.0_ install, I get Could not find command "_1.3.0_".

How can I successfully run bundle install with that specific version of bundler ?

答:
Basically, you need:

Bundler (>= 1.3.0, < 2.0) installed on your local machine.

Ability to run that Bundler version.

Run that Bundler version to install other gems required by your app (bundle install).

First, check if you have successfully install Bundler (>= 1.3.0, < 2.0) on your local machine:

```<code>$ gem list bundler
</code>```

You should see:

```<code>*** LOCAL GEMS ***
bundler (2.1.4, 1.17.3, 1.3.0)
</code>```

If not, install it:

```<code>$ gem install bundler -v "<2" -N
# Install lasted bundler below version 2
# -N: No document
</code>```

Second, check if you can run that Bundler version:

```<code>$ bundle _1.17.3_ -v
</code>```

You should see:

```<code>Bundler version 1.17.3
</code>```

If you installed Bundler 1.17.3 but cannot run "bundle 1.17.3 -v", there is something wrong with your RubyGems gem. Check if you installed updated version (latest is 3.1.3):

```<code>$ gem -v
</code>```

Try to update the RubyGems gem, because it is the one help you run a specific gem version:

```<code>$ gem update --system
</code>```

You should see:

```<code>Updating rubygems-update
...
Installing RubyGems 3.1.3
Successfully built RubyGem
    Name: bundler
    Version: 2.1.4
    File: bundler-2.1.4.gem
Bundler 2.1.4 installed
RubyGems 3.1.3 installed
Regenerating binstubs
...
------------------------------------------------------------------------------
RubyGems installed the following executables:
    /home/lqt/.rbenv/versions/2.7.1/bin/gem
    /home/lqt/.rbenv/versions/2.7.1/bin/bundle
...
RubyGems system software updated
</code>```

Check again if you can run a specific Bundler version:

```<code>$ bundle _1.17.3_ -v
</code>```

If you see:

```<code>Bundler version 1.17.3
</code>```

Then, step 3, just run Bundler 1.17.3 to install other gems:

```<code>$ bundle _1.17.3_ install
</code>```

Body:
I am trying to bundle install a project running gem 'rails', '4.2.0'.
Running Bundle install, I get :

Bundler could not find compatible versions for gem "bundler":
  In Gemfile:
    rails (= 4.2.0) was resolved to 4.2.0, which depends on
      bundler (>= 1.3.0, < 2.0)

  Current Bundler version:
    bundler (2.1.4)
This Gemfile requires a different version of Bundler.
Perhaps you need to update Bundler by running `gem install bundler`?

Could not find gem 'bundler (>= 1.3.0, < 2.0)', which is required by gem 'rails (= 4.2.0)', in any of the sources.

Thus I then try to install bundler v 1.3.0 to successfully bundle this gemfile : gem install bundler -v 1.3.0

gem list bundler shows me that I successfully installed bundler at v 1.3.0

Then when trying to bundle install with v 1.3.0 like this bundle _1.3.0_ install, I get Could not find command "_1.3.0_".

How can I successfully run bundle install with that specific version of bundler ?

Body:
Basically, you need:

Bundler (>= 1.3.0, < 2.0) installed on your local machine.

Ability to run that Bundler version.

Run that Bundler version to install other gems required by your app (bundle install).

First, check if you have successfully install Bundler (>= 1.3.0, < 2.0) on your local machine:

$ gem list bundler

You should see:

*** LOCAL GEMS ***
bundler (2.1.4, 1.17.3, 1.3.0)

If not, install it:

$ gem install bundler -v "<2" -N
# Install lasted bundler below version 2
# -N: No document

Second, check if you can run that Bundler version:

$ bundle _1.17.3_ -v

You should see:

Bundler version 1.17.3

If you installed Bundler 1.17.3 but cannot run "bundle 1.17.3 -v", there is something wrong with your RubyGems gem. Check if you installed updated version (latest is 3.1.3):

$ gem -v

Try to update the RubyGems gem, because it is the one help you run a specific gem version:

$ gem update --system

You should see:

Updating rubygems-update
...
Installing RubyGems 3.1.3
Successfully built RubyGem
    Name: bundler
    Version: 2.1.4
    File: bundler-2.1.4.gem
Bundler 2.1.4 installed
RubyGems 3.1.3 installed
Regenerating binstubs
...
------------------------------------------------------------------------------
RubyGems installed the following executables:
    /home/lqt/.rbenv/versions/2.7.1/bin/gem
    /home/lqt/.rbenv/versions/2.7.1/bin/bundle
...
RubyGems system software updated

Check again if you can run a specific Bundler version:

$ bundle _1.17.3_ -v

If you see:

Bundler version 1.17.3

Then, step 3, just run Bundler 1.17.3 to install other gems:

$ bundle _1.17.3_ install


问:
Loopback 3 - how to use an alternate method of sending emails in datasources.json
I am using Loopback 3, with it's user registration and authentication enabled.

In the system that I have to work with, they "send" emails by adding entries into an "email_queue" table. The table has fields like "to", "from", "subject", "body", "send_at_time" etc.

Then, there is a cronjob that checks for new entries each minute, and sends the email through some internal email process.

Thus, in loopback's /server/datasources.json file, I need to figure out how to connect to a mysql database, and insert a row rather than use "connector": "mail" which is what I have used in other systems.

In other words, how do I change this (and maybe other files, as needed):

```<code>{
  "emailDs": {
    "name": "emailDs",
    "connector": "mail",
    "transports": [
      {
      .... etc ...
</code>```

... so that instead of sending emails for user registration, password reminders, etc. loopback inserts rows into a database table to "send" the emails.

答:
You might try using the MySQL connector with an updated datasource config for the db (docs are here)-

```<code>lb datasource emailDS
</code>```

and then in the datasources config -

```<code>{
  ...
  "emailDS": {
    "name": "emailDS",
    "connector": "mysql",
    "host": "example.target.com",
    "port": 3306,
    "database": "target-mysql-db",
    "username": "user",
    "password": "L00pBack"
  }
}
</code>```

Body:
I am using Loopback 3, with it's user registration and authentication enabled.

In the system that I have to work with, they "send" emails by adding entries into an "email_queue" table. The table has fields like "to", "from", "subject", "body", "send_at_time" etc.

Then, there is a cronjob that checks for new entries each minute, and sends the email through some internal email process.

Thus, in loopback's /server/datasources.json file, I need to figure out how to connect to a mysql database, and insert a row rather than use "connector": "mail" which is what I have used in other systems.

In other words, how do I change this (and maybe other files, as needed):

{
  "emailDs": {
    "name": "emailDs",
    "connector": "mail",
    "transports": [
      {
      .... etc ...

... so that instead of sending emails for user registration, password reminders, etc. loopback inserts rows into a database table to "send" the emails.

Body:
You might try using the MySQL connector with an updated datasource config for the db (docs are here)-

lb datasource emailDS

and then in the datasources config -

{
  ...
  "emailDS": {
    "name": "emailDS",
    "connector": "mysql",
    "host": "example.target.com",
    "port": 3306,
    "database": "target-mysql-db",
    "username": "user",
    "password": "L00pBack"
  }
}


问:
what is difference between microsoft.aspnetcore.signalr.client and microsoft.aspnetcore.signalr.client.core?
There are two nuget packages for SignalR client:

Microsoft.AspNetCore.SignalR.Client and Microsoft.AspNetCore.SignalR.Client.Core.

Both ASP.NET Core, but I can't find any information why they both exist.

Probably Client.Core has limited functionality, but this is just my guess.

答:
Both ASP.NET Core, but I can't find any information why they both exist.

The Microsoft.AspNetCore.SignalR.Client package depends upon the Microsoft.AspNetCore.SignalR.Client.Core package.

And from doc of "ASP.NET Core SignalR .NET Client", we can find that:

The Microsoft.AspNetCore.SignalR.Client package is required for .NET clients to connect to SignalR hubs.

Besides, if you do a test with only installing the Microsoft.AspNetCore.SignalR.Client.Core package in your client app, you would find you can not call WithUrl method to configure the HubConnection to use HTTP-based transports to connect to the specified URL.

And it would cause the error, like below.

'HubConnectionBuilder' does not contain a definition for 'WithUrl' and no accessible extension method 'WithUrl' accepting a first argument of type 'HubConnectionBuilder' could be found (are you missing a using directive or an assembly reference?)


问:
How to pass filtering parameters in PoweBI C# SDK
I'm generating Power BI embed token using C# SDK.

```<code>        using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))
        {
            var workspaceId = groupId.ToString();
            var report = await client.Reports.GetReportInGroupAsync(workspaceId, reportId);
            var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");

            var tokenResponsex = await client.Reports.GenerateTokenAsync(workspaceId, reportId, generateTokenRequestParameters);

            result.EmbedToken = tokenResponsex;
            result.EmbedUrl = report.EmbedUrl;
            result.Id = report.Id;
        }
</code>```

I need to pass a parameter for filtering. But couldn't find a straightforward way to do this.
How do I get this done?

答:
You can use RLS in embedded reports implemented with app owns data scenario (a single master account for authentication) by passing EffectiveIdentity information when generating access token for this report with GenerateTokenInGroup.

To implement RLS in the report itself you need either to use USERPRINCIPALNAME() DAX function to filter the data, or define roles and filter the data based on them. If you implement it with roles, after publishing the report go to dataset's security settings and add users to the roles.

To generate the token by providing an effective identity and roles membership, use code like this:

```<code>var credentials = new TokenCredentials(accessToken, "Bearer");

using (var client = new PowerBIClient(new Uri("https://api.powerbi.com"), credentials))
{
    var datasets = new List<string>() { datasetId }; // Dataset's GUID as a string
    var roles = new List<string>();
    roles.Add('ROLE1');
    roles.Add('ROLE2');
    roles.Add('ROLE3');
    var effectiveIdentity = new EffectiveIdentity('user@example.com', datasets, roles);
    var r = new GenerateTokenRequest("view", effectiveIdentity);
    var token = client.Reports.GenerateTokenInGroup(groupId, reportId, r).Token;
}
</code>```

Body:
I'm generating Power BI embed token using C# SDK.

        using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))
        {
            var workspaceId = groupId.ToString();
            var report = await client.Reports.GetReportInGroupAsync(workspaceId, reportId);
            var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");

            var tokenResponsex = await client.Reports.GenerateTokenAsync(workspaceId, reportId, generateTokenRequestParameters);

            result.EmbedToken = tokenResponsex;
            result.EmbedUrl = report.EmbedUrl;
            result.Id = report.Id;
        }

I need to pass a parameter for filtering. But couldn't find a straightforward way to do this.
How do I get this done?

Body:
You can use RLS in embedded reports implemented with app owns data scenario (a single master account for authentication) by passing EffectiveIdentity information when generating access token for this report with GenerateTokenInGroup.

To implement RLS in the report itself you need either to use USERPRINCIPALNAME() DAX function to filter the data, or define roles and filter the data based on them. If you implement it with roles, after publishing the report go to dataset's security settings and add users to the roles.

To generate the token by providing an effective identity and roles membership, use code like this:

var credentials = new TokenCredentials(accessToken, "Bearer");

using (var client = new PowerBIClient(new Uri("https://api.powerbi.com"), credentials))
{
    var datasets = new List<string>() { datasetId }; // Dataset's GUID as a string
    var roles = new List<string>();
    roles.Add('ROLE1');
    roles.Add('ROLE2');
    roles.Add('ROLE3');
    var effectiveIdentity = new EffectiveIdentity('user@example.com', datasets, roles);
    var r = new GenerateTokenRequest("view", effectiveIdentity);
    var token = client.Reports.GenerateTokenInGroup(groupId, reportId, r).Token;
}


问:
Regular expression syntax
I have a similar problem, to a previously asked question. But similar practices apparently do not produce similar results.

Previous Question

New question - I want to match the lines beginning in T as the first match, and the following lines beginning with X as the second match (as a whole string, to be later matched by another regex)

What I have so far is (^T(\d+)\n(.*?)(?:the_problem)/m) I don't know what to replace "the_problem" with, or even if that is the issue. I assumed some rendition (?:\n|\z), but apparently not. Everything I tried, would not count the next occurrence of ^T(\d+) as the start of a new group, and continue to capture all of the lines between each occurrence, at the same time.

```<code>Sample text;
T01C0.025
T02C0.035
T03C0.055
T04C0.150
T05C0.065
T06C0.075
%
G05
G90
T01
X011200Y004700
X011200Y009700
X018500Y011200
X013500Y-011200
X023800Y019500
T02
X034800Y017800
X-033800Y-017800
X032800Y017800
T03
X036730Y003000
X038700Y003000
X040668Y-003000
X059230Y003000
T04
X110580Y017800
X023800Y027300
X095500Y028500
X005500Y-006500
X021500Y-006500
T05
X003950Y002000
X003950Y004500
X003950Y007000
T06
X026300Y027300
M30
</code>```

I only want to capture the shorter version of T01, T02,...T0n, not the longer version at the top, then the entire collection of ^X(-?\d+)Y(-?\d+) that follows it, as another match.

```<code>Result 1.
Match 1. T01
Match 2. X011200Y004700
         X011200Y009700
         X018500Y011200
         X013500Y-011200
         X023800Y019500

Result 2.
Match 1. T02
Match 2. X034800Y017800
         X-033800Y-017800
         X032800Y017800

Result 3.
Match 1. T03
Match 2. X036730Y003000
         X038700Y003000

         ....etc....
</code>```

Thanks in advance for any help ;-) Note: I prefer to use raw Ruby, without extensions or plugins. My version of ruby is 1.8.6.

答:
Try this instead:

```<code>^(T[^\s]+)[\n\r\s]((?:(?:X\S+)[\n\r\s])+)
</code>```

It makes the groups for the X lines into non-capturing groups, then puts all the repetitions of the final pattern into a single group. All the X lines will be in a single capture.

You can test this using Rubular (an indispensable tool for developing regular expressions) http://rubular.com/r/PRnurKy64Q

Title: Regular expression syntax

Body:
I have a similar problem, to a previously asked question. But similar practices apparently do not produce similar results.

Previous Question

New question - I want to match the lines beginning in T as the first match, and the following lines beginning with X as the second match (as a whole string, to be later matched by another regex)

What I have so far is (^T(\d+)\n(.*?)(?:the_problem)/m) I don't know what to replace "the_problem" with, or even if that is the issue. I assumed some rendition (?:\n|\z), but apparently not. Everything I tried, would not count the next occurrence of ^T(\d+) as the start of a new group, and continue to capture all of the lines between each occurrence, at the same time.

Sample text;
T01C0.025
T02C0.035
T03C0.055
T04C0.150
T05C0.065
T06C0.075
%
G05
G90
T01
X011200Y004700
X011200Y009700
X018500Y011200
X013500Y-011200
X023800Y019500
T02
X034800Y017800
X-033800Y-017800
X032800Y017800
T03
X036730Y003000
X038700Y003000
X040668Y-003000
X059230Y003000
T04
X110580Y017800
X023800Y027300
X095500Y028500
X005500Y-006500
X021500Y-006500
T05
X003950Y002000
X003950Y004500
X003950Y007000
T06
X026300Y027300
M30

I only want to capture the shorter version of T01, T02,...T0n, not the longer version at the top, then the entire collection of ^X(-?\d+)Y(-?\d+) that follows it, as another match.

Result 1.
Match 1. T01
Match 2. X011200Y004700
         X011200Y009700
         X018500Y011200
         X013500Y-011200
         X023800Y019500

Result 2.
Match 1. T02
Match 2. X034800Y017800
         X-033800Y-017800
         X032800Y017800

Result 3.
Match 1. T03
Match 2. X036730Y003000
         X038700Y003000

         ....etc....

Thanks in advance for any help ;-) Note: I prefer to use raw Ruby, without extensions or plugins. My version of ruby is 1.8.6.

Body:
Try this instead:

^(T[^\s]+)[\n\r\s]((?:(?:X\S+)[\n\r\s])+)

It makes the groups for the X lines into non-capturing groups, then puts all the repetitions of the final pattern into a single group. All the X lines will be in a single capture.

You can test this using Rubular (an indispensable tool for developing regular expressions) http://rubular.com/r/PRnurKy64Q


问:
Technical difference between Spring Boot with JOOQ and Spring Data JPA
When would you use Spring Data JPA over Spring Boot with JOOQ and vice versa?

I know that Spring Data JPA can be used for completing basic CRUD queries, but not really for complex join queries while using JOOQ makes it easier?

EDIT: Can you use both Spring data jpa with jooq?

答:
IMHO if you want a performing and maintainable application which uses a database at its core, you don't want to abstract away the fact that you are using a database. JOOQ gives you full control because you can read and write the actual query in your code but with type safety.

JPA embraces the OO model and this simply does not match the way a database works in all cases, which could result in unexpected queries such as N+1 because you put the wrong annotation on a field. If you are not paying enough attention this will lead to performance issues when scaling your application. JPA Criteria helps a bit but it still way harder to write and read.

As a result, with JPA you are first writing your query in SQL and then use half a day to translate it to Criteria. After years of working with both frameworks I would use JOOQ even for simple a CRUD application (because there is no such thing as a simple CRUD application :-)).

Edit: I don't think that you can mix JPA with JOOQ, question is, why would you want to? They are both using a different approach so just choose one. It's difficult enough to learn the intricacies of one framework.


问:
How to subscribe to an observable once?
My function access() needs to subscribe once, each and every call.

In the snippet below, $valueChanges emits data to each change made. Calling access() without const $ = ... and  $.unsubscribe(), $valueChanges observable emits unnecessary streams of values.

Is there an rxjs operator/function that emits once in subscription inside a function? Even if the function is called multiple times the subscription emits once?

```<code>access() {
  const $ = $valueChanges.pipe(
    map((res) =>
      ...
    ),
  ).subscribe((res) => {

    ...

    $.unsubscribe();
  });
}
</code>```

答:
Try shareReply(1). Then the original stream will be called only once and its emit will be shared with all subscribers. If the stream emits 2nd time - the update will go to all subscribers too.

access() {
  const $ = $valueChanges.pipe(
    map((res) =>
      ...
    ),
    // take(1), // in case if you need just 1 emit from it.
    shareReply(1), // in case if you don't want to trigger `$valueChanges` on every subscription.
  ).subscribe((res) => {

    ...

    // $.unsubscribe(); // it's useless in case of `take(1)`.
  });
}
```

Title: How to subscribe to an observable once?

Body:
My function access() needs to subscribe once, each and every call.

In the snippet below, $valueChanges emits data to each change made. Calling access() without const $ = ... and  $.unsubscribe(), $valueChanges observable emits unnecessary streams of values.

Is there an rxjs operator/function that emits once in subscription inside a function? Even if the function is called multiple times the subscription emits once?

access() {
  const $ = $valueChanges.pipe(
    map((res) =>
      ...
    ),
  ).subscribe((res) => {

    ...

    $.unsubscribe();
  });
}


问:
Java Apache poi: Word - Unable to extract specific texts from document along with numbering and tables
Unable to extract specific texts from document along with numbering and tables.

Any ideas on how to solve this?

答:
You need to set with the position to replace only the text with format

```<code>r.setText(text, 0);
</code>```

For Table u need to find this way

```<code>    for (XWPFTableRow row : tbl.getRows()) {
     for (XWPFTableCell cell : row.getTableCells()) {
      for (XWPFParagraph p : cell.getParagraphs()) {
        for (XWPFRun r : p.getRuns()) {
         .....
        }}
        // Replace values with nested table
        for (XWPFTable tbl2 : cell.getTables()) {
         for (XWPFTableRow row2 : tbl2.getRows()){
          for (XWPFTableCell cell : row.getTableCells()) {
           for (XWPFParagraph p : cell.getParagraphs()) {
            for (XWPFRun r : p.getRuns()) {
            ...
          }}
        }}}
</code>```

Body:
You need to set with the position to replace only the text with format

r.setText(text, 0);

For Table u need to find this way

    for (XWPFTableRow row : tbl.getRows()) {
     for (XWPFTableCell cell : row.getTableCells()) {
      for (XWPFParagraph p : cell.getParagraphs()) {
        for (XWPFRun r : p.getRuns()) {
         .....
        }}
        // Replace values with nested table
        for (XWPFTable tbl2 : cell.getTables()) {
         for (XWPFTableRow row2 : tbl2.getRows()){
          for (XWPFTableCell cell : row.getTableCells()) {
           for (XWPFParagraph p : cell.getParagraphs()) {
            for (XWPFRun r : p.getRuns()) {
            ...
          }}
        }}}


问:
Firebase: No Firebase App '[DEFAULT]' has been created when using Reserved Hosting URL
I've setup my firebase web project by following the guide here

I decided to use the reserved hosting URL as it seemed like a great solution for handling a local, staging, and production enviornment of my project as described here

The issue is, when trying to use firebase in one of my components:

```<code>firebase.auth()
</code>```

I get the following error

No Firebase App '[DEFAULT]' has been created- call Firebase App.initializeApp()

index.html file

```<code><body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.9.3/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.9.3/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.9.3/firebase-analytics.js"></script>
    <script src="/__/firebase/init.js"></script>
  </body>
</code>```

test.jsx file

```<code>import firebase from "firebase";

class LoginModal extends React.Component {

sendVerificationCode() {
    var phoneNumber = this.userPhoneNumber;
    console.log("sending verification code to: ", phoneNumber);
    var appVerifier = window.recaptchaVerifier;

    firebase
      .auth()
      .signInWithPhoneNumber(phoneNumber, appVerifier)
      .then(function(confirmationResult) {
        // SMS sent. Prompt user to type the code from the message, then sign the
        // user in with confirmationResult.confirm(code).
        window.confirmationResult = confirmationResult;
        console.log("confirmationResult = ", confirmationResult);
      })
      .catch(function(error) {
        // Error; SMS not sent
        console.log("error = ", error);
        // ...
      });
  }

}
</code>```

When calling that function (sendVerificationCode()), the app crashes with the following error:

```<code>FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
</code>```

Additionally, I am getting this output in console (could be related, but not sure...):

```<code>init.js:1 Uncaught SyntaxError: Unexpected token '<'
</code>```

Any deas on what I might be missing? Thanks!!

答:
If you try

```<code>window.firebase
</code>```

you will actually see the instance of firebase has been initialized.

Body:
I've setup my firebase web project by following the guide here

I decided to use the reserved hosting URL as it seemed like a great solution for handling a local, staging, and production enviornment of my project as described here

The issue is, when trying to use firebase in one of my components:

firebase.auth()

I get the following error

No Firebase App '[DEFAULT]' has been created- call Firebase App.initializeApp()

index.html file

    You need to enable JavaScript to run this app.

test.jsx file

import firebase from "firebase";

class LoginModal extends React.Component {

sendVerificationCode() {
    var phoneNumber = this.userPhoneNumber;
    console.log("sending verification code to: ", phoneNumber);
    var appVerifier = window.recaptchaVerifier;

    firebase
      .auth()
      .signInWithPhoneNumber(phoneNumber, appVerifier)
      .then(function(confirmationResult) {
        // SMS sent. Prompt user to type the code from the message, then sign the
        // user in with confirmationResult.confirm(code).
        window.confirmationResult = confirmationResult;
        console.log("confirmationResult = ", confirmationResult);
      })
      .catch(function(error) {
        // Error; SMS not sent
        console.log("error = ", error);
        // ...
      });
  }

}

When calling that function (sendVerificationCode()), the app crashes with the following error:

FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

Additionally, I am getting this output in console (could be related, but not sure...):

init.js:1 Uncaught SyntaxError: Unexpected token '<'

Any deas on what I might be missing? Thanks!!

Body:
If you try

window.firebase

you will actually see the instance of firebase has been initialized.


问:
Oracle issue with concat()
```<code>SELECT EMPLOYEE_ID, CONCAT(FIRST_NAME," ",LAST_NAME) AS EMPLOYEE_NAME, HIRE_DATE
FROM EMPLOYEES
</code>```

I tried running the above code and it's giving me error ( invalid number of arguments ) for concatenation. I am trying to add a space between FIRST_NAME and LAST_NAME.

答: it should work if the field names are correct, there is  no syntax errors. if you just want  to add a separator in between the fields, try SELECT CONCAT_WS(' ',FIRST_NAME,LAST_NAME);</p>

Title: Oracle issue with concat()

Body:
SELECT EMPLOYEE_ID, CONCAT(FIRST_NAME," ",LAST_NAME) AS EMPLOYEE_NAME, HIRE_DATE
FROM EMPLOYEES

I tried running the above code and it's giving me error ( invalid number of arguments ) for concatenation. I am trying to add a space between FIRST_NAME and LAST_NAME.


问:
Is C# a high level language?
Is C# a high level language? I see it as more like medium level, but I am still unsure about this. Would you consider it as high level as some of the popular scripting languages?

Or does it accommodate more than one level?

答: Um, yes, it is a high-level language.  And you can remove the subjective tag.  There's nothing subjective about it.</p>

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Is C# a high level language?

OwnerDisplayName: Kevin


问:
Prevent open in new tab/window
I have a website that has a music player in one of the corners. Because I didn't want the music to stop everytime the user changes part of the website, I used an iFrame for the content. So when someone clicks the menu buttons, all that changes is the source of the iFrame.

Now the only problem is if someone tries to open one of the sub-pages in a new tab/window. All they get is black text on a white background, with the content that was supposed to be in the iFrame.

Is there any way to prevent this?

Oh, and the page this is about is www.sinjabe.com  if that helps.

Thanks

答:
The most logical solution (to me...) would be to detach the music player from the page; have the music player open in a different window / tab. You can have the music player in a pop-up window when the visitor of your site requests it / clicks on it.

Other solutions like detecting if the content has a parent frame, will lead to multiple music players if someone opens a page in a new tab / window.

Title: Prevent open in new tab/window


问:
Why ConnectionError using python in docker-compose?
I have this

docker-compose:

```<code>version: '3.3'

services:
  bd_mySql:
    image: mysql:5.7
    restart: always
    ports:
      - "3306:3306"
    environment:
      MYSQL_USER: razvan
      MYSQL_PASSWORD: PepitoElDeLosPalotes
      MYSQL_ROOT_PASSWORD: PepitoElDeLosPalotes
      MYSQL_DATABASE: equipojugadores
  api:
    build: data
    restart: always
    ports:
      - "8084:8084"
  python:
    build: python
    restart: on-failure
    depends_on:
      - api
</code>```

dockerfile (python)

```<code>FROM python:latest

ADD scraper.py /

RUN pip install BeautifulSoup4
RUN pip install html5lib
RUN pip install requests
RUN pip install lxml

CMD [ "python", "scraper.py" ]
</code>```

And i have this error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8084):

why?

答:
Your py code is trying to connect with localhost for that you need provide links in python part.

After that you can call the request http://api:8084/apiname.

This worked for me:

```<code>api:
    build: data
    restart: always
    ports:
      - "8084:8084"
python:
    build: python
    restart: on-failure
    depends_on:
      - api
    links:
      - api
</code>```

Body:
I have this

docker-compose:

version: '3.3'

services:
  bd_mySql:
    image: mysql:5.7
    restart: always
    ports:
      - "3306:3306"
    environment:
      MYSQL_USER: razvan
      MYSQL_PASSWORD: PepitoElDeLosPalotes
      MYSQL_ROOT_PASSWORD: PepitoElDeLosPalotes
      MYSQL_DATABASE: equipojugadores
  api:
    build: data
    restart: always
    ports:
      - "8084:8084"
  python:
    build: python
    restart: on-failure
    depends_on:
      - api

dockerfile (python)

FROM python:latest

ADD scraper.py /

RUN pip install BeautifulSoup4
RUN pip install html5lib
RUN pip install requests
RUN pip install lxml

CMD [ "python", "scraper.py" ]

And i have this error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8084):

why?

Body:
Your py code is trying to connect with localhost for that you need provide links in python part.

After that you can call the request http://api:8084/apiname.

This worked for me:

api:
    build: data
    restart: always
    ports:
      - "8084:8084"
python:
    build: python
    restart: on-failure
    depends_on:
      - api
    links:
      - api


问:
Golang: A map Interface, how to print key and value
I get a map interface, like :

```<code>getUsersAppInfo := usersAppInfo.GetUsersAppInfo(getUserId)
</code>```

then I print :

```<code>fmt.Println(getUsersAppInfo)
</code>```

get this, like :

```<code>[map[appId:2 fcmServerKey:keyTestTest name:com.app]]
</code>```

Ask : How to just print the value, like

```<code>appId value is 2
name value is com.app
fcmServerKey:keyTestTest value is keyTestTest
</code>```

答:
I don't recommend to do this in production setup. But when I want to print out a map without too much code on my dev box, i print the JSON serialised version. This will be a crime to do in production.

```<code>package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    a := map[string]interface{}{"appId": 2, "fcmServerKey": "keyTestTest", "name": "com.app", "version": []int{1, 2, 3}, "xyz": 3}
    bs, _ := json.Marshal(a)
    fmt.Println(string(bs))
}
</code>```

Output:

{"appId":2,"fcmServerKey":"keyTestTest","name":"com.app","version":[1,2,3],"xyz":3}

Body:
I get a map interface, like :

getUsersAppInfo := usersAppInfo.GetUsersAppInfo(getUserId)

then I print :

fmt.Println(getUsersAppInfo)

get this, like :

[map[appId:2 fcmServerKey:keyTestTest name:com.app]]

Ask : How to just print the value, like

appId value is 2
name value is com.app
fcmServerKey:keyTestTest value is keyTestTest

Body:
I don't recommend to do this in production setup. But when I want to print out a map without too much code on my dev box, i print the JSON serialised version. This will be a crime to do in production.

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    a := map[string]interface{}{"appId": 2, "fcmServerKey": "keyTestTest", "name": "com.app", "version": []int{1, 2, 3}, "xyz": 3}
    bs, _ := json.Marshal(a)
    fmt.Println(string(bs))
}

Output:

{"appId":2,"fcmServerKey":"keyTestTest","name":"com.app","version":[1,2,3],"xyz":3}


问:
How to send a LatLng instance to new intent
I need to pass an instance of the LatLng class to another intent. How should I do it?
Here's the code.

```<code>LatLng fromPosition = new LatLng(23.4555453556, 11.145315551);
LatLng toPosition = new LatLng(12.1115145311, 99.333455333);

Intent i= new Intent(Maps.this, Routes.class);
        startActivity(i);
</code>```

Please help me out here.

Route class:

```<code> public class Routes extends FragmentActivity {
GoogleMap mMap;
 GMapV2Direction md;
 private String provider;
 double lati;
 double longi;
 String name;
 Location location;

Document doc;
PolylineOptions rectLine;

Bundle bundle = getIntent().getParcelableExtra("bundle");
LatLng fromPosition = bundle.getParcelable("from_position");
LatLng toPosition = bundle.getParcelable("to_position");

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.maps2);

    md = new GMapV2Direction();
    mMap = ((SupportMapFragment)getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMap();

    LatLng coordinates = fromPosition;
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));

    mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
    mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));

    new ParseXML().execute();
}

private class ParseXML extends AsyncTask<Void, Void, Document> {
  @Override
  protected Document doInBackground(Void... params) {
    doc = md.getDocument(fromPosition, toPosition,
    GMapV2Direction.MODE_DRIVING);
    ArrayList<LatLng> directionPoint = md.getDirection(doc);
    rectLine = new PolylineOptions().width(3).color(Color.RED);

    for (int i = 0; i < directionPoint.size(); i++) {
        rectLine.add(directionPoint.get(i));
    }
    return null;
  }

   @Override
   protected void onPostExecute(Document result) {
            // TODO Auto-generated method stub
       mMap.addPolyline(rectLine);
   }
}
}
</code>```

This is my route class. I don't know the problem. Help me out here. It seems to send the bundle fine but there's an error while receiving it.

答:
We have another alternative to get LatLng using intent in the  activity</p>

```<code>   intent.putExtra(Constants.LOCATION, latLng);

   LatLng latLng = getIntent().getParcelableExtra(Constants.LOCATION);
</code>```

Body:
I need to pass an instance of the LatLng class to another intent. How should I do it?
Here's the code.

LatLng fromPosition = new LatLng(23.4555453556, 11.145315551);
LatLng toPosition = new LatLng(12.1115145311, 99.333455333);

Intent i= new Intent(Maps.this, Routes.class);
        startActivity(i);

Please help me out here.

Route class:

 public class Routes extends FragmentActivity {
GoogleMap mMap;
 GMapV2Direction md;
 private String provider;
 double lati;
 double longi;
 String name;
 Location location;

Document doc;
PolylineOptions rectLine;

Bundle bundle = getIntent().getParcelableExtra("bundle");
LatLng fromPosition = bundle.getParcelable("from_position");
LatLng toPosition = bundle.getParcelable("to_position");

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.maps2);

    md = new GMapV2Direction();
    mMap = ((SupportMapFragment)getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMap();

    LatLng coordinates = fromPosition;
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));

    mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
    mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));

    new ParseXML().execute();
}

private class ParseXML extends AsyncTask<Void, Void, Document> {
  @Override
  protected Document doInBackground(Void... params) {
    doc = md.getDocument(fromPosition, toPosition,
    GMapV2Direction.MODE_DRIVING);
    ArrayList<LatLng> directionPoint = md.getDirection(doc);
    rectLine = new PolylineOptions().width(3).color(Color.RED);

    for (int i = 0; i < directionPoint.size(); i++) {
        rectLine.add(directionPoint.get(i));
    }
    return null;
  }

   @Override
   protected void onPostExecute(Document result) {
            // TODO Auto-generated method stub
       mMap.addPolyline(rectLine);
   }
}
}

This is my route class. I don't know the problem. Help me out here. It seems to send the bundle fine but there's an error while receiving it.

Body:
We have another alternative to get LatLng using intent in the  activity

   intent.putExtra(Constants.LOCATION, latLng);

   LatLng latLng = getIntent().getParcelableExtra(Constants.LOCATION);


问:
Git Plugin with Jenkins is failing in "git reset --hard" after particular number of fetches
After upgrade of jenkins and git plugins, we are facing the below issues,

Jenkins version -  2.190.3 Git plugin in jenkins - 4.0.0 git change
  log - 2.21 Git client - 3.0.0

I am using jenkins share library

Once this issue happens, it will never checkout till we clean up the workspace.
After every couple of runs, this happens and keeps failing after that.
Log is below. Please see if this is something already known.

What i have tried for this is, I tried continous runs and tried increasing timeouts from git client side. ALso tried to check if there is any issue with commits,  Things seem to be normal. Console log of Jenkins Pipeline is below.

```<code>git rev-parse --is-inside-work-tree # timeout=10
Setting origin to ssh://<XXXX>@gerrit.ext.net.<XXXX>.com:29418/FNMS/ee-environment
 > git config remote.origin.url ssh://<XXXX>@gerrit.ext.net.<XXXX>.com:29418/FNMS/ee-environment # timeout=10
Seen 1,117 remote branches
Obtained pipeline/Altiplano-SuperFB/Jenkinsfile from 9a9ecac103bb02f5882d44c94332ea9fa667699f
Running in Durability level: PERFORMANCE_OPTIMIZED
Loading library jenkins-shared-library@master
Attempting to resolve master from remote references...
 > git --version # timeout=10
 > git ls-remote -h ssh://<XXXX>@gerrit.ext.net.<XXXX>.com:29418/FNMS/jenkin-common-lib # timeout=10
Found match: refs/heads/master revision 47e77fb305c3f39cb83dc5d3b382ced2e6a3871b
No credentials specified
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url ssh://<XXXX>@gerrit.ext.net.<XXXX>.com:29418/FNMS/jenkin-common-lib # timeout=10
Cleaning workspace
 > git rev-parse --verify HEAD # timeout=10
Resetting working tree
 > git reset --hard # timeout=10
ERROR: Error fetching remote repo 'origin'
hudson.plugins.git.GitException: Failed to fetch from ssh://<XXXX>@gerrit.ext.net.<XXXX>.com:29418/FNMS/jenkin-common-lib
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:899)
    at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1114)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1145)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:124)
    at org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever.lambda$doRetrieve$1(SCMSourceRetriever.java:154)
    at org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever.retrySCMOperation(SCMSourceRetriever.java:104)
    at org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever.doRetrieve(SCMSourceRetriever.java:153)
    at org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever.retrieve(SCMSourceRetriever.java:93)
    at org.jenkinsci.plugins.workflow.libs.LibraryAdder.retrieve(LibraryAdder.java:157)
    at org.jenkinsci.plugins.workflow.libs.LibraryAdder.add(LibraryAdder.java:138)
    at org.jenkinsci.plugins.workflow.libs.LibraryDecorator$1.call(LibraryDecorator.java:125)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1065)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:561)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:522)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:327)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Caused by: hudson.plugins.git.GitException: Command "git reset --hard" returned status code 128:
stdout:
stderr: fatal: unable to read tree 6a23ff423d86f1b9e8e9649f136a99da90f1ef44

    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2372)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2302)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2298)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommand(CliGitAPIImpl.java:1857)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.reset(CliGitAPIImpl.java:625)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.clean(CliGitAPIImpl.java:972)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.clean(CliGitAPIImpl.java:987)
    at hudson.plugins.git.GitAPI.clean(GitAPI.java:311)
    at hudson.plugins.git.extensions.impl.CleanBeforeCheckout.decorateFetchCommand(CleanBeforeCheckout.java:30)
    at hudson.plugins.git.extensions.GitSCMExtension.decorateFetchCommand(GitSCMExtension.java:288)
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:895)
    ... 25 more
ERROR: Error fetching remote repo 'origin'
ERROR: Maximum checkout retry attempts reached, aborting
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: Loading libraries failed

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:561)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:522)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:327)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE
</code>```

答: Answer from that post helped me: https://stackoverflow.com/a/47783130/2483702. You have to wipe out repository and clone again.</p>

Body:
After upgrade of jenkins and git plugins, we are facing the below issues,

Jenkins version -  2.190.3 Git plugin in jenkins - 4.0.0 git change
  log - 2.21 Git client - 3.0.0

I am using jenkins share library

Once this issue happens, it will never checkout till we clean up the workspace.
After every couple of runs, this happens and keeps failing after that.
Log is below. Please see if this is something already known.

What i have tried for this is, I tried continous runs and tried increasing timeouts from git client side. ALso tried to check if there is any issue with commits,  Things seem to be normal. Console log of Jenkins Pipeline is below.

git rev-parse --is-inside-work-tree # timeout=10
Setting origin to ssh://<XXXX>@gerrit.ext.net.<XXXX>.com:29418/FNMS/ee-environment
 > git config remote.origin.url ssh://<XXXX>@gerrit.ext.net.<XXXX>.com:29418/FNMS/ee-environment # timeout=10
Seen 1,117 remote branches
Obtained pipeline/Altiplano-SuperFB/Jenkinsfile from 9a9ecac103bb02f5882d44c94332ea9fa667699f
Running in Durability level: PERFORMANCE_OPTIMIZED
Loading library jenkins-shared-library@master
Attempting to resolve master from remote references...
 > git --version # timeout=10
 > git ls-remote -h ssh://<XXXX>@gerrit.ext.net.<XXXX>.com:29418/FNMS/jenkin-common-lib # timeout=10
Found match: refs/heads/master revision 47e77fb305c3f39cb83dc5d3b382ced2e6a3871b
No credentials specified
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url ssh://<XXXX>@gerrit.ext.net.<XXXX>.com:29418/FNMS/jenkin-common-lib # timeout=10
Cleaning workspace
 > git rev-parse --verify HEAD # timeout=10
Resetting working tree
 > git reset --hard # timeout=10
ERROR: Error fetching remote repo 'origin'
hudson.plugins.git.GitException: Failed to fetch from ssh://<XXXX>@gerrit.ext.net.<XXXX>.com:29418/FNMS/jenkin-common-lib
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:899)
    at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1114)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1145)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:124)
    at org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever.lambda$doRetrieve$1(SCMSourceRetriever.java:154)
    at org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever.retrySCMOperation(SCMSourceRetriever.java:104)
    at org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever.doRetrieve(SCMSourceRetriever.java:153)
    at org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever.retrieve(SCMSourceRetriever.java:93)
    at org.jenkinsci.plugins.workflow.libs.LibraryAdder.retrieve(LibraryAdder.java:157)
    at org.jenkinsci.plugins.workflow.libs.LibraryAdder.add(LibraryAdder.java:138)
    at org.jenkinsci.plugins.workflow.libs.LibraryDecorator$1.call(LibraryDecorator.java:125)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1065)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:561)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:522)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:327)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Caused by: hudson.plugins.git.GitException: Command "git reset --hard" returned status code 128:
stdout:
stderr: fatal: unable to read tree 6a23ff423d86f1b9e8e9649f136a99da90f1ef44

    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2372)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2302)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2298)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommand(CliGitAPIImpl.java:1857)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.reset(CliGitAPIImpl.java:625)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.clean(CliGitAPIImpl.java:972)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.clean(CliGitAPIImpl.java:987)
    at hudson.plugins.git.GitAPI.clean(GitAPI.java:311)
    at hudson.plugins.git.extensions.impl.CleanBeforeCheckout.decorateFetchCommand(CleanBeforeCheckout.java:30)
    at hudson.plugins.git.extensions.GitSCMExtension.decorateFetchCommand(GitSCMExtension.java:288)
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:895)
    ... 25 more
ERROR: Error fetching remote repo 'origin'
ERROR: Maximum checkout retry attempts reached, aborting
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: Loading libraries failed

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:561)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:522)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:327)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE