问:
Protocol Buffers In C#: How Are Boxed Value Types Handled
In the following examples:

```<code>public class RowData
{
    public object[] Values;
}

public class FieldData
{
    public object Value;
}
</code>```

I am curious as how either protobuf-net or dotnet-protobufs would handle such classes.  I am more familiar with protobuf-net, so what I actually have is:

```<code>[ProtoContract]
public class RowData
{
    [ProtoMember(1)]
    public object[] Values;
}
[ProtoContract]
public class FieldData
{
    [ProtoMember(1)]
    public object Value;
}
</code>```

However I get an error saying "No suitable Default Object encoding found".  Is there an easy way to treat these classes, that I am just not aware of?

To elaborate more on the use case:

This is a scaled down version of a data class used in remoting.  So essentially it looks like this:

```<code>FieldData data = new FieldData();
data.Value = 8;

remoteObject.DoSomething(data);
</code>```

Note: I've omitted the ISerializable implementation for simplicity, but it is as you'd expect.

答:
This is something like what I had in mind.  Let me know what you think.  Naturally I'd have to add a subclass for each value type I need to support.  What do you think?  Is there a better way, do you see any inefficiencies with this method?</p>

```<code>[ProtoContract, Serializable]
[ProtoInclude(1, typeof(Int32FieldData))]
public abstract class FieldDataBase : ISerializable
{
    [ProtoIgnore]
    public abstract object Value { get; set;}
    protected FieldDataBase()
    { }

    #region ISerializable Members
    protected FieldDataBase(SerializationInfo info, StreamingContext context)
    {
        Serializer.Merge<FieldDataBase>(info, this);
    }
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        Serializer.Serialize<FieldDataBase>(info, this);
    }

    #endregion
}

[ProtoContract, Serializable]
public class Int32FieldData : FieldDataBase
{
    [ProtoMember(1)]
    public int? Int32Value;

    [ProtoIgnore]
    public override object Value
    {
        get { return this.Int32Value.HasValue ? this.Int32Value : null; }
        set { this.Int32Value = (int?)value; }
    }
    public Int32FieldData() { }
    protected Int32FieldData(SerializationInfo info, StreamingContext context)
        :base(info, context)
    { }
}
</code>```

OwnerDisplayName: Greg Dean

Body:
In the following examples:

public class RowData
{
    public object[] Values;
}

public class FieldData
{
    public object Value;
}

I am curious as how either protobuf-net or dotnet-protobufs would handle such classes.  I am more familiar with protobuf-net, so what I actually have is:

[ProtoContract]
public class RowData
{
    [ProtoMember(1)]
    public object[] Values;
}
[ProtoContract]
public class FieldData
{
    [ProtoMember(1)]
    public object Value;
}

However I get an error saying "No suitable Default Object encoding found".  Is there an easy way to treat these classes, that I am just not aware of?

To elaborate more on the use case:

This is a scaled down version of a data class used in remoting.  So essentially it looks like this:

FieldData data = new FieldData();
data.Value = 8;

remoteObject.DoSomething(data);

Note: I've omitted the ISerializable implementation for simplicity, but it is as you'd expect.

LastEditorDisplayName: Greg Dean

Body:
This is something like what I had in mind.  Let me know what you think.  Naturally I'd have to add a subclass for each value type I need to support.  What do you think?  Is there a better way, do you see any inefficiencies with this method?

[ProtoContract, Serializable]
[ProtoInclude(1, typeof(Int32FieldData))]
public abstract class FieldDataBase : ISerializable
{
    [ProtoIgnore]
    public abstract object Value { get; set;}
    protected FieldDataBase()
    { }

    #region ISerializable Members
    protected FieldDataBase(SerializationInfo info, StreamingContext context)
    {
        Serializer.Merge<FieldDataBase>(info, this);
    }
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        Serializer.Serialize<FieldDataBase>(info, this);
    }

    #endregion
}

[ProtoContract, Serializable]
public class Int32FieldData : FieldDataBase
{
    [ProtoMember(1)]
    public int? Int32Value;

    [ProtoIgnore]
    public override object Value
    {
        get { return this.Int32Value.HasValue ? this.Int32Value : null; }
        set { this.Int32Value = (int?)value; }
    }
    public Int32FieldData() { }
    protected Int32FieldData(SerializationInfo info, StreamingContext context)
        :base(info, context)
    { }
}


来源: stackexchange

问:
Bing Maps streetview
I'm using Bing Maps 7.0 Ajax Control API and am wondering how to display streetview. There doesn't seem to be a way, but this can't be the case. Is there a way?

Thanks,
Chris

答:
Microsoft Street*side* (Streetview is Google's brand) is available via the Bing Maps website (www.bing.com/maps/explore), or using the Bing Maps Extended Modes dll in a Silverlight application only.

It is not currently available in the AJAX v7.0 control.

See here for information on how to add streetside view to a Bing Maps Silverlight application:
http://www.bing.com/community/site_blogs/b/maps/archive/2009/12/10/adding-streetside-and-enhanced-birds-eye-to-your-applications.aspx

ContentLicense: CC BY-SA 3.0

Title: Bing Maps streetview


问:
FIRST_VALUE and LAST_VALUE with NULL values
I want to get the top 2 expensive book and least 2 expensive book prices
using FIRST_Value & LAST_Value SQL Server

The presence of Nulls is giving incorrect Min price value, I want the Min price to ignore Nulls

```<code>Select top 2 FIRST_VALUE(price) Over(Order by price) as MinPrice,
FIRST_VALUE(title) Over (order by price) as MinName,
LAST_VALUE(price) Over (order by price desc) as MaxPrice,
LAST_VALUE(title) over (Order by price desc) as MaxName
from titles;
</code>```

Getting this output

```<code>MINPrice    MINName                        Maxprice           MaxName
NULL       The Psychology of Computer        $22.95      But is it Friendly?
NULL       The Psychology of Computer        $21.59      Computer Phobic and
</code>```

Where as the result I am expecting should be

```<code>Minprice     MinName                        Maxprice          Maxname
$2.99        The Gourmet Microwave           $22.95       But is it Friendly?
$2.99        You can Combat stress          $21.59       Computer Phobic and
</code>```

So how do I eliminate NULLs from Min price

答:
You can try with </p>

```<code>;WITH ctemin AS
(
   SELECT TOP 2 price AS minprice, title AS mintitle FROM titles WHERE price IS NOT NULL ORDER BY price
),
ctemax AS
(
   SELECT TOP 2 price AS maxprice, title AS maxtitle FROM titles WHERE price IS NOT NULL ORDER BY price DESC
)

SELECT ctemin.minprice,ctemin.mintitle,ctemax.maxprice,ctemax.maxtitle FROM ctemax
INNER JOIN ctemin ON 1=1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to get the top 2 expensive book and least 2 expensive book prices
using FIRST_Value & LAST_Value SQL Server

The presence of Nulls is giving incorrect Min price value, I want the Min price to ignore Nulls

Select top 2 FIRST_VALUE(price) Over(Order by price) as MinPrice,
FIRST_VALUE(title) Over (order by price) as MinName,
LAST_VALUE(price) Over (order by price desc) as MaxPrice,
LAST_VALUE(title) over (Order by price desc) as MaxName
from titles;

Getting this output

MINPrice    MINName                        Maxprice           MaxName
NULL       The Psychology of Computer        $22.95      But is it Friendly?
NULL       The Psychology of Computer        $21.59      Computer Phobic and

Where as the result I am expecting should be

Minprice     MinName                        Maxprice          Maxname
$2.99        The Gourmet Microwave           $22.95       But is it Friendly?
$2.99        You can Combat stress          $21.59       Computer Phobic and

So how do I eliminate NULLs from Min price

Body:
You can try with

;WITH ctemin AS
(
   SELECT TOP 2 price AS minprice, title AS mintitle FROM titles WHERE price IS NOT NULL ORDER BY price
),
ctemax AS
(
   SELECT TOP 2 price AS maxprice, title AS maxtitle FROM titles WHERE price IS NOT NULL ORDER BY price DESC
)

SELECT ctemin.minprice,ctemin.mintitle,ctemax.maxprice,ctemax.maxtitle FROM ctemax
INNER JOIN ctemin ON 1=1


问:
How to serve a static html file directly from server in React+Express?
I downloaded a pretty html page with links to required css and js from a website builder and want to use it as my landing page. I have a full blown React app and want to serve this downloaded html file as my landing page for the / route. What's the best way to go about doing this?

I've looked into
 as in the below example but it leads to the page loading slowly.

```<code>
export default class StaticContainer extends Component {
  state = {
    __html: "" // copy/paste html here
  }

  render() {
    return (
        <div dangerouslySetInnerHTML={this.state} />
    );
  }
}```

```

答:
Solved this by proxying specific paths directly to the server using http-proxy-middleware. See the section titled Configuring the proxy manually in the React documentation for more information.

Install http-proxy-middleware. Create a file src/setupProxy.js in the React client app as follows:

```<code>const proxy = require('http-proxy-middleware');

// Matches landing page at / alone
var landingPageFilter = function (pathname, req) {
    console.log(pathname);
    return pathname.match('^\/$') && req.method === 'GET';
};

module.exports = function (app) {
    // this is for APIs
    app.use(proxy('/api', { target: 'http://localhost:3001/' }));
    // this is for the landing page
    app.use(proxy(landingPageFilter, { target: 'http://localhost:3001/' }));
};

</code>```

In my case, I was using Express for my server created using express-generator. Handled these routes in app.js as seen below:

```<code>app.use('/api/', indexRouter);

app.use("/", (req, res) => {
  res.status(200).sendFile(path.resolve(__dirname, "../public", "landing_page.html"));
});
</code>```

where landing_page.html is the downloaded page that we wanted to serve without React

Edit: This only worked in dev. For prod, you'll need to build the React pages and serve them. Follow this tutorial but make sure you have the correct path to build React pages. In the tutorial, it's client/build. Might be different depending on your directory structure.

Body:
I downloaded a pretty html page with links to required css and js from a website builder and want to use it as my landing page. I have a full blown React app and want to serve this downloaded html file as my landing page for the / route. What's the best way to go about doing this?

I've looked into
 as in the below example but it leads to the page loading slowly.

export default class StaticContainer extends Component {
  state = {
    __html: "" // copy/paste html here
  }

  render() {
    return (

    );
  }
}```

Body:
Solved this by proxying specific paths directly to the server using http-proxy-middleware. See the section titled Configuring the proxy manually in the React documentation for more information.

Install http-proxy-middleware. Create a file src/setupProxy.js in the React client app as follows:

const proxy = require('http-proxy-middleware');

// Matches landing page at / alone
var landingPageFilter = function (pathname, req) {
    console.log(pathname);
    return pathname.match('^\/$') && req.method === 'GET';
};

module.exports = function (app) {
    // this is for APIs
    app.use(proxy('/api', { target: 'http://localhost:3001/' }));
    // this is for the landing page
    app.use(proxy(landingPageFilter, { target: 'http://localhost:3001/' }));
};

In my case, I was using Express for my server created using express-generator. Handled these routes in app.js as seen below:

app.use('/api/', indexRouter);

app.use("/", (req, res) => {
  res.status(200).sendFile(path.resolve(__dirname, "../public", "landing_page.html"));
});

where landing_page.html is the downloaded page that we wanted to serve without React

Edit: This only worked in dev. For prod, you'll need to build the React pages and serve them. Follow this tutorial but make sure you have the correct path to build React pages. In the tutorial, it's client/build. Might be different depending on your directory structure.


问:
How to move all elements that are zero to the end of an array?
Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

```<code>function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}
</code>```

input:

```<code>[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]
</code>```

Expected:

```<code>[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
</code>```

Actual:

```<code>[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
</code>```

Result is coming as correct but I need to do it without array.push() or array.splice()

答:
You can simply do something like this:

let data = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

let result = data.sort((a,b) => !!b-!!a)

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

<p>Where you would sort on the boolean value of each of the array entries.  We cast to boolean via the double negation operator. Since <code>!!0</code> would be false and every other number would be true and we sort in a descending order (hence <code>b-a</code> and not <code>a-b</code>) we get the desired result.</p>

<p>Please note that <code>Array.sort</code> mutates the current array and if you want to create a new one simply use <code>Array.slice</code> like this:</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>let data = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

let sortZeroesLast = arr => arr.slice().sort((a,b) => !!b-!!a)

console.log(data) // <-- original array
console.log(sortZeroesLast(data))  // <-- new sorted array</code>```

Body:
Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}

input:

[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

Expected:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Actual:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Result is coming as correct but I need to do it without array.push() or array.splice()

Body:
You can simply do something like this:

let data = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

let result = data.sort((a,b) => !!b-!!a)

console.log(result)

Where you would sort on the boolean value of each of the array entries.  We cast to boolean via the double negation operator. Since !!0 would be false and every other number would be true and we sort in a descending order (hence b-a and not a-b) we get the desired result.

Please note that Array.sort mutates the current array and if you want to create a new one simply use Array.slice like this:

let data = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

let sortZeroesLast = arr => arr.slice().sort((a,b) => !!b-!!a)

console.log(data) // <-- original array
console.log(sortZeroesLast(data))  // <-- new sorted array


问:
Why are all my component rerendering when I change an unrelated state?
I'm trying to change a state without having the entire app reload. For some reason that's not happening, and when I set the state of an object that isn't even passed down to a specific component, then that component updates for no reason.

So in the code below, I'm when I set the message, MainContent should not reload.

```<code>const [message, setMessage] = useState({});
setMessage('my message'); // This causes the entire app, including 'MyComponent' to reload

return (
    <div className='App'>
        <Header user={user} message={message} setMessage={setMessage} />

        <div id='main-site'>
            <Switch>
                // SHOULD NOT RELOAD UNLESS PASSED IN PROP CHANGED
                <Route path='/main' component={MainContent} />

            </Switch>
        </div>
    </div>
);
</code>```

Header.jsx

```<code>return (
    {message && (
        <div>
            <span>{message.text}</span>
            // This on click makes the entire app reload
            <button className='close' onClick={() => setMessage({})}>
                X
            </button>
        </div>
    )}
);
</code>```

How can I make sure the only components that have the message prop get updated, and no other components rerender?

答:
You should define the hook into the component function. that binds the variable and it setMessage update function only to that component.
In React the only way to update the dom is by recall all Pure Component or render function on React.Component and compare there return to previous return.

So to update the view after you change it by SetMessage react call again all render function to update the view.

function MyComponet(){
  return (

            <Switch>
                // SHOULD NOT RELOAD UNLESS PASSED IN PROP CHANGED
                <Route path='/main' component={MainContent} />

            </Switch>

);
}

//state that updating when props updating too
function usePropsState(initialState) {
  const [state, setState] = useState(initialState);
  useEffect(() => setState(initialState), [initialState]);
  return [state, setState]
}

function Header({user, message:initMessage}){
  // now you can update the state internally or from outside
  const [message, setMessage] = usePropsState(initMessage);
  return (
    {message && (

            {message}
            // This on click makes the entire app reload
            <button className='close' onClick={() => setMessage('')}>
                X
            </button>

    )}
  );
}
```

If you like that custom hook thumb Up this issue

Body:
I'm trying to change a state without having the entire app reload. For some reason that's not happening, and when I set the state of an object that isn't even passed down to a specific component, then that component updates for no reason.

So in the code below, I'm when I set the message, MainContent should not reload.

const [message, setMessage] = useState({});
setMessage('my message'); // This causes the entire app, including 'MyComponent' to reload

return (

            <Switch>
                // SHOULD NOT RELOAD UNLESS PASSED IN PROP CHANGED
                <Route path='/main' component={MainContent} />

            </Switch>

);

Header.jsx

return (
    {message && (

            {message.text}
            // This on click makes the entire app reload
            <button className='close' onClick={() => setMessage({})}>
                X
            </button>

    )}
);

How can I make sure the only components that have the message prop get updated, and no other components rerender?

Body:
You should define the hook into the component function. that binds the variable and it setMessage update function only to that component.
In React the only way to update the dom is by recall all Pure Component or render function on React.Component and compare there return to previous return.

So to update the view after you change it by SetMessage react call again all render function to update the view.

function MyComponet(){
  return (
    <div className='App'>
        <Header user={user} message={'my message'} />

        <div id='main-site'>
            <Switch>
                // SHOULD NOT RELOAD UNLESS PASSED IN PROP CHANGED
                <Route path='/main' component={MainContent} />

            </Switch>
        </div>
    </div>
);
}

//state that updating when props updating too
function usePropsState(initialState) {
  const [state, setState] = useState(initialState);
  useEffect(() => setState(initialState), [initialState]);
  return [state, setState]
}

function Header({user, message:initMessage}){
  // now you can update the state internally or from outside
  const [message, setMessage] = usePropsState(initMessage);
  return (
    {message && (
        <div>
            <span>{message}</span>
            // This on click makes the entire app reload
            <button className='close' onClick={() => setMessage('')}>
                X
            </button>
        </div>
    )}
  );
}

If you like that custom hook thumb Up this issue


问:
Problem with using compareTo with an arrayList
I am trying to write a program to analyze and interpret GIS data. I have the program completely coded out but am running into issues when I try to use a compareTo to sort the program on different metrics (Elevation, Latitude, etc). I keep getting an error "The method sort(List) in the type Collections is not applicable for the arguments (GISDataStructure".

The tutorials and guides I am following all have the main class adding data to the arraylist in main, whereas I am calling a different class, and using lineData to collect information from a .txt file, and looking it through, instantiating every row. I then call a method from a different class and insert the data. I currently have a basic compareTo written in my data class, where I get and set all parameters, but continuously get errors when trying different ways to use the compareTo, or even coding a basic sorting method in different classes.

```<code>import java.io.File;

import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class GISRunner {

    /**
     * @param args
     */
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("GIS.txt");
        Scanner input = new Scanner(file);
        String[] lineData = null;
        String lineRaw = null;
        String featureName, featureClass, stateCode, countyName, primaryLatitudeDMS, primaryLongitudeDMS,
                sourceLatitudeDMS, sourceLongitudeDMS, mapName;
        Integer featureId, stateId, countyId, elevationMeters, elevationFeet;
        Double primaryLatitudeDecimal, primaryLongitudeDecimal, sourceLatitudeDecimal, sourceLongitudeDecimal;

        GISDataStructure datas = new GISDataStructure();
        while (input.hasNext()) {
            lineRaw = input.nextLine();
            lineData = lineRaw.split("\\|");
            featureId = 0;
            try {
                featureId = Integer.valueOf(lineData[0]);
            } catch (NumberFormatException e) {
                featureId = Integer.valueOf(lineData[0].substring(3));
            }
            featureName = lineData[1];
            featureClass = lineData[2];
            stateCode = lineData[3];
            stateId = Integer.valueOf(lineData[4]);
            countyName = lineData[5];
            try {
                countyId = Integer.valueOf(lineData[6]);
            } catch (NumberFormatException e2) {
                countyId = null;
            }
            primaryLatitudeDMS = lineData[7];
            primaryLongitudeDMS = lineData[8];
            primaryLatitudeDecimal = Double.valueOf(lineData[9]);
            primaryLongitudeDecimal = Double.valueOf(lineData[10]);
            sourceLatitudeDMS = lineData[11];
            sourceLongitudeDMS = lineData[12];
            try {
                sourceLatitudeDecimal = Double.valueOf(lineData[13]);
            } catch (NumberFormatException e1) {
                sourceLatitudeDecimal = null;
            }
            try {
                sourceLongitudeDecimal = Double.valueOf(lineData[14]);
            } catch (NumberFormatException e1) {
                sourceLongitudeDecimal = null;
            }
            try {
                elevationMeters = Integer.valueOf(lineData[15]);
            } catch (NumberFormatException e) {
                elevationMeters = null;
            }
            try {
                elevationFeet = Integer.valueOf(lineData[16]);
            } catch (NumberFormatException e) {
                elevationFeet = null;
            }
            mapName = lineData[17];

            GISData newGISData = new GISData(featureId, featureName, featureClass, stateCode, stateId, countyName,
                    countyId, primaryLatitudeDMS, primaryLongitudeDMS, primaryLatitudeDecimal, primaryLongitudeDecimal,
                    sourceLatitudeDMS, sourceLongitudeDMS, sourceLatitudeDecimal, sourceLongitudeDecimal,
                    elevationMeters, elevationFeet, mapName);
            datas.insert(newGISData);
        }
        System.out.println(datas.toString());
        input.close();

        Collections.sort(datas);
    }
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

import edu.matc.itdev154.finalexam.GISData.SortByType;

public class GISDataStructure {

    private static Scanner sc = new Scanner(System.in);

    public ArrayList<GISData> data;

    public GISDataStructure() {
        data = new ArrayList<GISData>();
    }

    public void insert(GISData element) {
        data.add(element);
    }

    public static void searchData(ArrayList<GISData> data) {
        String state;
        GISData foundData = null;

        do {
            System.out.print("Enter state code: ");
            state = sc.next();
        } while (!state.matches("^[a-zA-Z\\s]+"));

        for (GISData datas : data) {
            if(datas.getStateCode().equals(state)) {
                foundData = datas;
            }
        }
        if(foundData != null)
            foundData.toString();
        else
            System.out.println("No data found.");
    }

    public static void sort(ArrayList<GISData> data) {
        Collections.sort(
                data, (obj1, obj2) -> obj1.getElevationFeet() - obj2.getElevationFeet()
                );
        data.forEach(System.out::println);

    }

    public static void edu(ArrayList<GISData> data) {
    GISData min1 = data.stream()
            .min(Comparator.comparingInt(GISData::getElevationFeet))
            .get();
    System.out.println("Area min elevation feet: " + min1);

    GISData max1 = data.stream()
            .max(Comparator.comparingInt(GISData::getElevationFeet))
            .get();
    System.out.println("Area max elevation feet: " + max1);
    }

    @Override
    public String toString() {
        StringBuilder retString = new StringBuilder();
        for (GISData gis : data) {
            retString.append(gis.toString());
        }
        return retString.toString();
    }

}

/**
 *
 */
package edu.matc.itdev154.finalexam;

import java.util.Date;

public class GISData implements Comparable<GISData> {
    public static enum SortByType {CountyName,
                                    FeatureName,
                                    PrimaryLatitude,
                                    PrimaryLongitude,
                                    SourceLatitude,
                                    SourceLongitude,
                                    ElevationFeet};

    private int featureId;
    private String featureName;
    private String featureClass;
    private String stateCode;
    private int stateId;
    private String countyName;
    private Integer countyId;
    private String primaryLatitudeDMS;
    private String primaryLongitudeDMS;
    private double primaryLatitudeDecimal;
    private double primaryLongitudeDecimal;
    private String sourceLatitudeDMS;
    private String sourceLongitudeDMS;
    private Double sourceLatitudeDecimal;
    private Double sourceLongitudeDecimal;
    private Integer elevationMeters;
    private Integer elevationFeet;
    private String mapName;
    private Date createdDate;
    private Date modifiedDate;
    private SortByType[] sortBy;

    public GISData() {

    }
    public GISData(int featureId, String featureName, String featureClass, String stateCode, int stateId,
            String countyName, Integer countyId, String primaryLatitudeDMS, String primaryLongitudeDMS,
            double primaryLatitudeDecimal, double primaryLongitudeDecimal, String sourceLatitudeDMS, String sourceLongitudeDMS, Double sourceLatitudeDecimal,
            Double sourceLongitudeDecimal, Integer elevationMeters, Integer elevationFeet, String mapName) {
        this.featureId = featureId;
        this.featureName = featureName;
        this.featureClass = featureClass;
        this.stateCode = stateCode;
        this.stateId = stateId;
        this.countyName = countyName;
        this.countyId = countyId;
        this.primaryLatitudeDMS = primaryLatitudeDMS;
        this.primaryLongitudeDMS = primaryLongitudeDMS;
        this.primaryLatitudeDecimal = primaryLatitudeDecimal;
        this.primaryLongitudeDecimal = primaryLongitudeDecimal;
        this.sourceLatitudeDMS = sourceLatitudeDMS;
        this.sourceLongitudeDMS = sourceLongitudeDMS;
        this.sourceLatitudeDecimal = sourceLatitudeDecimal;
        this.sourceLongitudeDecimal = sourceLongitudeDecimal;
        this.elevationMeters = elevationMeters;
        this.elevationFeet = elevationFeet;
        this.mapName = mapName;
    }

// Getters and Setters

@Override
    public int compareTo(GISData o) {
        return this.elevationFeet - o.elevationFeet;
    }
</code>```

I expect the program to loop through showing the instantiation of each row of data, then another loop after my Collections.sort is called, where I would write a for each statement.

答:
The problem is the GISDataStructure is not a list but rather contains a list. Because GISDataStructure  is not a list Collections.sort() cannot be called. If you want to sort the contained list, you need to reference it. In other words:

Collections.sort(datas.data);

Body:
I am trying to write a program to analyze and interpret GIS data. I have the program completely coded out but am running into issues when I try to use a compareTo to sort the program on different metrics (Elevation, Latitude, etc). I keep getting an error "The method sort(List) in the type Collections is not applicable for the arguments (GISDataStructure".

The tutorials and guides I am following all have the main class adding data to the arraylist in main, whereas I am calling a different class, and using lineData to collect information from a .txt file, and looking it through, instantiating every row. I then call a method from a different class and insert the data. I currently have a basic compareTo written in my data class, where I get and set all parameters, but continuously get errors when trying different ways to use the compareTo, or even coding a basic sorting method in different classes.

import java.io.File;

import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class GISRunner {

    /**
     * @param args
     */
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("GIS.txt");
        Scanner input = new Scanner(file);
        String[] lineData = null;
        String lineRaw = null;
        String featureName, featureClass, stateCode, countyName, primaryLatitudeDMS, primaryLongitudeDMS,
                sourceLatitudeDMS, sourceLongitudeDMS, mapName;
        Integer featureId, stateId, countyId, elevationMeters, elevationFeet;
        Double primaryLatitudeDecimal, primaryLongitudeDecimal, sourceLatitudeDecimal, sourceLongitudeDecimal;

        GISDataStructure datas = new GISDataStructure();
        while (input.hasNext()) {
            lineRaw = input.nextLine();
            lineData = lineRaw.split("\\|");
            featureId = 0;
            try {
                featureId = Integer.valueOf(lineData[0]);
            } catch (NumberFormatException e) {
                featureId = Integer.valueOf(lineData[0].substring(3));
            }
            featureName = lineData[1];
            featureClass = lineData[2];
            stateCode = lineData[3];
            stateId = Integer.valueOf(lineData[4]);
            countyName = lineData[5];
            try {
                countyId = Integer.valueOf(lineData[6]);
            } catch (NumberFormatException e2) {
                countyId = null;
            }
            primaryLatitudeDMS = lineData[7];
            primaryLongitudeDMS = lineData[8];
            primaryLatitudeDecimal = Double.valueOf(lineData[9]);
            primaryLongitudeDecimal = Double.valueOf(lineData[10]);
            sourceLatitudeDMS = lineData[11];
            sourceLongitudeDMS = lineData[12];
            try {
                sourceLatitudeDecimal = Double.valueOf(lineData[13]);
            } catch (NumberFormatException e1) {
                sourceLatitudeDecimal = null;
            }
            try {
                sourceLongitudeDecimal = Double.valueOf(lineData[14]);
            } catch (NumberFormatException e1) {
                sourceLongitudeDecimal = null;
            }
            try {
                elevationMeters = Integer.valueOf(lineData[15]);
            } catch (NumberFormatException e) {
                elevationMeters = null;
            }
            try {
                elevationFeet = Integer.valueOf(lineData[16]);
            } catch (NumberFormatException e) {
                elevationFeet = null;
            }
            mapName = lineData[17];

            GISData newGISData = new GISData(featureId, featureName, featureClass, stateCode, stateId, countyName,
                    countyId, primaryLatitudeDMS, primaryLongitudeDMS, primaryLatitudeDecimal, primaryLongitudeDecimal,
                    sourceLatitudeDMS, sourceLongitudeDMS, sourceLatitudeDecimal, sourceLongitudeDecimal,
                    elevationMeters, elevationFeet, mapName);
            datas.insert(newGISData);
        }
        System.out.println(datas.toString());
        input.close();

        Collections.sort(datas);
    }
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

import edu.matc.itdev154.finalexam.GISData.SortByType;

public class GISDataStructure {

    private static Scanner sc = new Scanner(System.in);

    public ArrayList<GISData> data;

    public GISDataStructure() {
        data = new ArrayList<GISData>();
    }

    public void insert(GISData element) {
        data.add(element);
    }

    public static void searchData(ArrayList<GISData> data) {
        String state;
        GISData foundData = null;

        do {
            System.out.print("Enter state code: ");
            state = sc.next();
        } while (!state.matches("^[a-zA-Z\\s]+"));

        for (GISData datas : data) {
            if(datas.getStateCode().equals(state)) {
                foundData = datas;
            }
        }
        if(foundData != null)
            foundData.toString();
        else
            System.out.println("No data found.");
    }

    public static void sort(ArrayList<GISData> data) {
        Collections.sort(
                data, (obj1, obj2) -> obj1.getElevationFeet() - obj2.getElevationFeet()
                );
        data.forEach(System.out::println);

    }

    public static void edu(ArrayList<GISData> data) {
    GISData min1 = data.stream()
            .min(Comparator.comparingInt(GISData::getElevationFeet))
            .get();
    System.out.println("Area min elevation feet: " + min1);

    GISData max1 = data.stream()
            .max(Comparator.comparingInt(GISData::getElevationFeet))
            .get();
    System.out.println("Area max elevation feet: " + max1);
    }

    @Override
    public String toString() {
        StringBuilder retString = new StringBuilder();
        for (GISData gis : data) {
            retString.append(gis.toString());
        }
        return retString.toString();
    }

}

/**
 *
 */
package edu.matc.itdev154.finalexam;

import java.util.Date;

public class GISData implements Comparable<GISData> {
    public static enum SortByType {CountyName,
                                    FeatureName,
                                    PrimaryLatitude,
                                    PrimaryLongitude,
                                    SourceLatitude,
                                    SourceLongitude,
                                    ElevationFeet};

    private int featureId;
    private String featureName;
    private String featureClass;
    private String stateCode;
    private int stateId;
    private String countyName;
    private Integer countyId;
    private String primaryLatitudeDMS;
    private String primaryLongitudeDMS;
    private double primaryLatitudeDecimal;
    private double primaryLongitudeDecimal;
    private String sourceLatitudeDMS;
    private String sourceLongitudeDMS;
    private Double sourceLatitudeDecimal;
    private Double sourceLongitudeDecimal;
    private Integer elevationMeters;
    private Integer elevationFeet;
    private String mapName;
    private Date createdDate;
    private Date modifiedDate;
    private SortByType[] sortBy;

    public GISData() {

    }
    public GISData(int featureId, String featureName, String featureClass, String stateCode, int stateId,
            String countyName, Integer countyId, String primaryLatitudeDMS, String primaryLongitudeDMS,
            double primaryLatitudeDecimal, double primaryLongitudeDecimal, String sourceLatitudeDMS, String sourceLongitudeDMS, Double sourceLatitudeDecimal,
            Double sourceLongitudeDecimal, Integer elevationMeters, Integer elevationFeet, String mapName) {
        this.featureId = featureId;
        this.featureName = featureName;
        this.featureClass = featureClass;
        this.stateCode = stateCode;
        this.stateId = stateId;
        this.countyName = countyName;
        this.countyId = countyId;
        this.primaryLatitudeDMS = primaryLatitudeDMS;
        this.primaryLongitudeDMS = primaryLongitudeDMS;
        this.primaryLatitudeDecimal = primaryLatitudeDecimal;
        this.primaryLongitudeDecimal = primaryLongitudeDecimal;
        this.sourceLatitudeDMS = sourceLatitudeDMS;
        this.sourceLongitudeDMS = sourceLongitudeDMS;
        this.sourceLatitudeDecimal = sourceLatitudeDecimal;
        this.sourceLongitudeDecimal = sourceLongitudeDecimal;
        this.elevationMeters = elevationMeters;
        this.elevationFeet = elevationFeet;
        this.mapName = mapName;
    }

// Getters and Setters

@Override
    public int compareTo(GISData o) {
        return this.elevationFeet - o.elevationFeet;
    }

I expect the program to loop through showing the instantiation of each row of data, then another loop after my Collections.sort is called, where I would write a for each statement.


问:
How to ignore SSL validation in .net core 2.1
I am trying to call a web service that is deployed on a Linux Server that has a self-signed certificate from an application developed in .net core and deployed on an IIS server (Windows server 2012).

But when I try to call the endpoint the next error is thrown:

"Message": "The SSL connection could not be established, see inner
  exception.",
      "Description": "InnerError : System.Security.Authentication.AuthenticationException: Authentication
  failed, see inner exception. --->
  System.ComponentModel.Win32Exception: Mensaje recibido inesperado, o
  bien su formato es incorrecto\r\n   --- End of inner exception stack
  trace ---\r\n   at
  System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken
  message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo
  exception)\r\n   at
  System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken
  message, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32
  count, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
  count, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32
  readBytes, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.PartialFrameCallback(AsyncProtocolRequest
  asyncRequest)\r\n--- End of stack trace from previous location where
  exception was thrown ---\r\n   at
  System.Net.Security.SslState.ThrowIfExceptional()\r\n   at
  System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult
  lazyResult)\r\n   at
  System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult
  result)\r\n   at
  System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult
  asyncResult)\r\n   at
  System.Net.Security.SslStream.<>c.b__47_1(IAsyncResult
  iar)\r\n   at
  System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult
  iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean
  requiresSynchronization)\r\n--- End of stack trace from previous
  location where exception was thrown ---\r\n   at
  System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream
  stream, SslClientAuthenticationOptions sslOptions, CancellationToken
  cancellationToken) | stackTrace :    at
  System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream
  stream, SslClientAuthenticationOptions sslOptions, CancellationToken
  cancellationToken)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage
  request, CancellationToken cancellationToken)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1
  creationTask)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage
  request, Boolean doRequestAuth, CancellationToken
  cancellationToken)\r\n   at
  System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request,
  CancellationToken cancellationToken)\r\n   at
  System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask,
  HttpRequestMessage request, CancellationTokenSource cts, Boolean
  disposeCts)\r\n   at
  ReservasProxy.Data.APIConnection.CallXMLFormDataApiPostAsyc(String
  body) in
  C:\gitProjects\ResevasProxy\ReservasProxy\ReservasProxy\Data\APIConnection.cs:line
  181\r\n

I already try the next solutions but they didn´t work.

Solution 1 :

```<code>          using (var httpClientHandler = new HttpClientHandler())
        {
            httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
            // Make your request...
            //send request
            using (var httpClient = new HttpClient(httpClientHandler))
            {

                var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
                HttpResponseMessage response = await httpClient.PostAsync(_url, content);
                //var res = await response.Content.ReadAsAsync<T>();

            }

        }
</code>```

Solution 2:

```<code>            //send request
        using (var httpClient = new HttpClient())
        {
             ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
            HttpResponseMessage response = await httpClient.PostAsync(_url, content);

        }
</code>```

Solution 3:
Trying to import the certificate and then make the call but still not working.

```<code>const string certPath = @"C:\soaProdcer.cer";
var handler = new HttpClientHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                SslProtocols = System.Security.Authentication.SslProtocols.Tls
            };
            handler.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate(certPath));

            //send request
            using (var httpClient = new HttpClient(handler))
            {
                var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
                HttpResponseMessage response = await httpClient.PostAsync(_url, content);

            }
</code>```

I got the certificate using OpenSSL

```<code>>openssl s_client -showcerts -connect serversoa:443

No client certificate CA names sent
---
SSL handshake has read 774 bytes and written 493 bytes
---
New, TLSv1/SSLv3, Cipher is RC4-SHA
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : RC4-SHA
    Session-ID: 4E0F69C75B8F041101562F7E9B3EA349
    Session-ID-ctx:
    Master-Key: 61A916A9B8AF26281B5F7A0138DF5E4C2A4B83995E0B3FDD2274BAD0D8E3C2B5E98AA7CCB48A6543F6814C2540B18848
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1558979896
    Timeout   : 300 (sec)
    Verify return code: 18 (self signed certificate)
</code>```

I imported the certificate into the IIS server into the trusted root certification authorities.

答:
I don't remember exactly the link of Microsoft tell you about this. Your above solutions work well with older asp.net core version. This is my solution with the latest ASP.NET Core that I've implemented for my project. I hope it helps you.

```<code>services.AddHttpClient<IYourService, YourService>()
    .ConfigurePrimaryHttpMessageHandler(sp => new HttpClientHandler
    {
        AllowAutoRedirect = false,
        ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true,
        SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12
    });
</code>```

Please also read about HttpClientFactory: https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

Body:
I am trying to call a web service that is deployed on a Linux Server that has a self-signed certificate from an application developed in .net core and deployed on an IIS server (Windows server 2012).

But when I try to call the endpoint the next error is thrown:

"Message": "The SSL connection could not be established, see inner
  exception.",
      "Description": "InnerError : System.Security.Authentication.AuthenticationException: Authentication
  failed, see inner exception. --->
  System.ComponentModel.Win32Exception: Mensaje recibido inesperado, o
  bien su formato es incorrecto\r\n   --- End of inner exception stack
  trace ---\r\n   at
  System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken
  message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo
  exception)\r\n   at
  System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken
  message, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32
  count, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
  count, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32
  readBytes, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.PartialFrameCallback(AsyncProtocolRequest
  asyncRequest)\r\n--- End of stack trace from previous location where
  exception was thrown ---\r\n   at
  System.Net.Security.SslState.ThrowIfExceptional()\r\n   at
  System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult
  lazyResult)\r\n   at
  System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult
  result)\r\n   at
  System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult
  asyncResult)\r\n   at
  System.Net.Security.SslStream.<>c.b__47_1(IAsyncResult
  iar)\r\n   at
  System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult
  iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean
  requiresSynchronization)\r\n--- End of stack trace from previous
  location where exception was thrown ---\r\n   at
  System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream
  stream, SslClientAuthenticationOptions sslOptions, CancellationToken
  cancellationToken) | stackTrace :    at
  System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream
  stream, SslClientAuthenticationOptions sslOptions, CancellationToken
  cancellationToken)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage
  request, CancellationToken cancellationToken)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1
  creationTask)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage
  request, Boolean doRequestAuth, CancellationToken
  cancellationToken)\r\n   at
  System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request,
  CancellationToken cancellationToken)\r\n   at
  System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask,
  HttpRequestMessage request, CancellationTokenSource cts, Boolean
  disposeCts)\r\n   at
  ReservasProxy.Data.APIConnection.CallXMLFormDataApiPostAsyc(String
  body) in
  C:\gitProjects\ResevasProxy\ReservasProxy\ReservasProxy\Data\APIConnection.cs:line
  181\r\n

I already try the next solutions but they didn´t work.

Solution 1 :

          using (var httpClientHandler = new HttpClientHandler())
        {
            httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
            // Make your request...
            //send request
            using (var httpClient = new HttpClient(httpClientHandler))
            {

                var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
                HttpResponseMessage response = await httpClient.PostAsync(_url, content);
                //var res = await response.Content.ReadAsAsync<T>();

            }

        }

Solution 2:

            //send request
        using (var httpClient = new HttpClient())
        {
             ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
            HttpResponseMessage response = await httpClient.PostAsync(_url, content);

        }

Solution 3:
Trying to import the certificate and then make the call but still not working.

const string certPath = @"C:\soaProdcer.cer";
var handler = new HttpClientHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                SslProtocols = System.Security.Authentication.SslProtocols.Tls
            };
            handler.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate(certPath));

            //send request
            using (var httpClient = new HttpClient(handler))
            {
                var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
                HttpResponseMessage response = await httpClient.PostAsync(_url, content);

            }

I got the certificate using OpenSSL

>openssl s_client -showcerts -connect serversoa:443

No client certificate CA names sent
---
SSL handshake has read 774 bytes and written 493 bytes
---
New, TLSv1/SSLv3, Cipher is RC4-SHA
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : RC4-SHA
    Session-ID: 4E0F69C75B8F041101562F7E9B3EA349
    Session-ID-ctx:
    Master-Key: 61A916A9B8AF26281B5F7A0138DF5E4C2A4B83995E0B3FDD2274BAD0D8E3C2B5E98AA7CCB48A6543F6814C2540B18848
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1558979896
    Timeout   : 300 (sec)
    Verify return code: 18 (self signed certificate)

I imported the certificate into the IIS server into the trusted root certification authorities.

Body:
I don't remember exactly the link of Microsoft tell you about this. Your above solutions work well with older asp.net core version. This is my solution with the latest ASP.NET Core that I've implemented for my project. I hope it helps you.

services.AddHttpClient<IYourService, YourService>()
    .ConfigurePrimaryHttpMessageHandler(sp => new HttpClientHandler
    {
        AllowAutoRedirect = false,
        ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true,
        SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12
    });

Please also read about HttpClientFactory: https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests


问:
Reactjs npm start causes error ELIFECYCLE/3221225477
I just installed React through the command npm init react-app client and tried to start it through npm start, but got the following error.
But some details before that, I've installed React globally through npm install -g create-react-app and I am using VS Code.

```<code>0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start'
1 verbose cli ]
2 info using npm@6.9.0
3 info using node@v12.0.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle client@0.1.0~prestart: client@0.1.0
6 info lifecycle client@0.1.0~start: client@0.1.0
7 verbose lifecycle client@0.1.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle client@0.1.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Projeto\client\node_modules\.bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\nodejs\;C:\Users\leopl\AppData\Local\Programs\Python\Python37\Scripts\;C:\Users\leopl\AppData\Local\Programs\Python\Python37\;C:\Users\leopl\AppData\Local\Microsoft\WindowsApps;;C:\Users\leopl\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\leopl\AppData\Roaming\npm
9 verbose lifecycle client@0.1.0~start: CWD: C:\Projeto\client
10 silly lifecycle client@0.1.0~start: Args: [ '/d /s /c', 'react-scripts start' ]
11 silly lifecycle client@0.1.0~start: Returned: code: 3221225477  signal: null
12 info lifecycle client@0.1.0~start: Failed to exec start script
13 verbose stack Error: client@0.1.0 start: `react-scripts start`
13 verbose stack Exit status 3221225477
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:196:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:196:13)
13 verbose stack     at maybeClose (internal/child_process.js:1000:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:267:5)
14 verbose pkgid client@0.1.0
15 verbose cwd C:\Projeto\client
16 verbose Windows_NT 10.0.17763
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v12.0.0
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 3221225477
22 error client@0.1.0 start: `react-scripts start`
22 error Exit status 3221225477
23 error Failed at the client@0.1.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 3221225477, true ]
</code>```

Package.json

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

I have tried:

Clean cache

npm cache clean --force

delete node_modules folder

delete package-lock.json file

npm install

Just deleted everything

Delete everything in the folder

Install again with npm init react-app client (but I've tried create-react-app client as well)

Uninstall React and install again

Delete everything in the folder

npm -g uninstall create-react-app --save

Install everything again

Install 2 times (I saw that this worked for one person, so I tried it too)

npm init react-app client

npm install

One additional information, but that may be important, I can not run react-scripts start. I can not describe exactly what is the error in VS Code because it is in PT-BR, but it says the term react-scripts was not recognized and had a CommandNotFoundException error.

答:
What you need to do is install create-react-app globally by using this command

npm install -g create-react-app.

After that, you can use create-react-app CLI (command line interface) like below:

create-react-app <your_app_name>

With npm version higher than 5.2, here is the shortcut:

npx create-react-app <your_app_name>

Hope this help.

Body:
I just installed React through the command npm init react-app client and tried to start it through npm start, but got the following error.
But some details before that, I've installed React globally through npm install -g create-react-app and I am using VS Code.

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start'
1 verbose cli ]
2 info using npm@6.9.0
3 info using node@v12.0.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle client@0.1.0~prestart: client@0.1.0
6 info lifecycle client@0.1.0~start: client@0.1.0
7 verbose lifecycle client@0.1.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle client@0.1.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Projeto\client\node_modules\.bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\nodejs\;C:\Users\leopl\AppData\Local\Programs\Python\Python37\Scripts\;C:\Users\leopl\AppData\Local\Programs\Python\Python37\;C:\Users\leopl\AppData\Local\Microsoft\WindowsApps;;C:\Users\leopl\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\leopl\AppData\Roaming\npm
9 verbose lifecycle client@0.1.0~start: CWD: C:\Projeto\client
10 silly lifecycle client@0.1.0~start: Args: [ '/d /s /c', 'react-scripts start' ]
11 silly lifecycle client@0.1.0~start: Returned: code: 3221225477  signal: null
12 info lifecycle client@0.1.0~start: Failed to exec start script
13 verbose stack Error: client@0.1.0 start: `react-scripts start`
13 verbose stack Exit status 3221225477
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:196:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:196:13)
13 verbose stack     at maybeClose (internal/child_process.js:1000:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:267:5)
14 verbose pkgid client@0.1.0
15 verbose cwd C:\Projeto\client
16 verbose Windows_NT 10.0.17763
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v12.0.0
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 3221225477
22 error client@0.1.0 start: `react-scripts start`
22 error Exit status 3221225477
23 error Failed at the client@0.1.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 3221225477, true ]

Package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I have tried:

Clean cache

npm cache clean --force

delete node_modules folder

delete package-lock.json file

npm install

Just deleted everything

Delete everything in the folder

Install again with npm init react-app client (but I've tried create-react-app client as well)

Uninstall React and install again

Delete everything in the folder

npm -g uninstall create-react-app --save

Install everything again

Install 2 times (I saw that this worked for one person, so I tried it too)

npm init react-app client

npm install

One additional information, but that may be important, I can not run react-scripts start. I can not describe exactly what is the error in VS Code because it is in PT-BR, but it says the term react-scripts was not recognized and had a CommandNotFoundException error.


问:
fitting first order equation with nlme and lsoda
I a trying to fit a first order differential model using nlme and lsoda.
Here is the basic idea: I first define the function allowing to generate the solution of the differential equation:

```<code>library(deSolve)

ODE1 <- function(time, x, parms) {with(as.list(c(parms, x)), {
  import <- excfunc(time)
  dS <- import*k/tau - (S-yo)/tau
  res <- c(dS)
  list(res)})}

solution_ODE1 = function(tau1,k1,yo1,excitation,time){
  excfunc <- approxfun(time, excitation, rule = 2)
  parms  <- c(tau = tau1, k = k1, yo = yo1, excfunc = excfunc)
  xstart = c(S = yo1)
  out <-  lsoda(xstart, time, ODE1, parms)
  return(out[,2])
}
</code>```

I then generate data following the equation for two IDs:

```<code>time <- 0:49
excitation <- c(rep(0,10),rep(1,10),rep(0,10),rep(1,10),rep(0,10))
simu_data <- data.frame(signal = c(solution_ODE1(3,2,0.1,excitation,time)+rnorm(length(time),0,0.1),
                                   solution_ODE1(3.2,1.5,0.3,excitation,time)+rnorm(length(time),0,0.1)),
                        time = rep(time,2),
                        excitation = rep(excitation,2),
                        ID = rep(c("A","B"),each = length(time)))
</code>```

Here  is what it looks like :

```<code>library(ggplot2)
ggplot(simu_data)+
  geom_point(aes(time,signal,color = "signal"),size = 2)+
  geom_line(aes(time,excitation,color = "excitation"))+
  facet_wrap(~ID)
</code>```

I am then trying to fit using nlme:

```<code>fit1 <- nlme(signal ~ solution_ODE1(damping,gain,eq,excitation,time),
             data = simu_data,
             fixed = damping + gain + eq ~1,
             random =  damping   ~ 1 ,
             groups = ~ ID,
             start = c(damping = 5, gain = 1,eq = 0))
</code>```

I am getting this eror, that I don't get:

Error in eval(substitute(expr), data, enclos = parent.frame()) :
    object 'k' not found

The traceback shows that the error comes from the ODE1 model, which works when generating values.

```<code>16.    eval(substitute(expr), data, enclos = parent.frame())
15.    eval(substitute(expr), data, enclos = parent.frame())
14.    with.default(as.list(c(parms, x)), {
    import <- excfunc(time)
    dS <- import * k/tau - (S - yo)/tau
    res <- c(dS) ...
13.    with(as.list(c(parms, x)), {
    import <- excfunc(time)
    dS <- import * k/tau - (S - yo)/tau
    res <- c(dS) ...
12.    func(time, state, parms, ...)
11.    Func2(times[1], y)
10.    eval(Func2(times[1], y), rho)
9.    checkFunc(Func2, times, y, rho)
8.    lsoda(xstart, time, ODE1, parms)
7.    solution_ODE1(damping, gain, eq, excitation, time)
6.    eval(model, data.frame(data, pars))
5.    eval(model, data.frame(data, pars))
4.    eval(modelExpression[[2]], envir = nlEnv)
3.    eval(modelExpression[[2]], envir = nlEnv)
2.    nlme.formula(signal ~ solution_ODE1(damping, gain, eq, excitation,
    time), data = simu_data, fixed = damping + gain + eq ~ 1,
    random = damping ~ 1, groups = ~ID, start = c(damping = 5,
        gain = 1, eq = 0))
1.    nlme(signal ~ solution_ODE1(damping, gain, eq, excitation, time),
    data = simu_data, fixed = damping + gain + eq ~ 1, random = damping ~
        1, groups = ~ID, start = c(damping = 5, gain = 1, eq = 0))
</code>```

Does anyone have an idea How I should proceed ?

Edit

I tried to modify following the advise of mikeck:

```<code>ODE1 <- function(time, x, parms) {
  import <- parms$excfunc(time)
  dS <- import*parms$k/parms$tau - (x["S"]-parms$yo)/parms$tau
  res <- c(dS)
  list(res)}
</code>```

Generating the data works without problems. But use of nlme gives now:

Error in checkFunc(Func2, times, y, rho) :
    The number of derivatives returned by func() (0) must equal the length of the initial conditions vector (100)

with the following traceback:

```<code>> traceback()
10: stop(paste("The number of derivatives returned by func() (",
        length(tmp[[1]]), ") must equal the length of the initial conditions vector (",
        length(y), ")", sep = ""))
9: checkFunc(Func2, times, y, rho)
8: lsoda(xstart, time, ODE1, parms) at #5
7: solution_ODE1(damping, gain, eq, excitation, time)
6: eval(model, data.frame(data, pars))
5: eval(model, data.frame(data, pars))
4: eval(modelExpression[[2]], envir = nlEnv)
3: eval(modelExpression[[2]], envir = nlEnv)
2: nlme.formula(signal ~ solution_ODE1(damping, gain, eq, excitation,
       time), data = simu_data, fixed = damping + gain + eq ~ 1,
       random = damping ~ 1, groups = ~ID, start = c(damping = 5,
           gain = 1, eq = 0))
1: nlme(signal ~ solution_ODE1(damping, gain, eq, excitation, time),
       data = simu_data, fixed = damping + gain + eq ~ 1, random = damping ~
           1, groups = ~ID, start = c(damping = 5, gain = 1, eq = 0))
</code>```

答:
In your example, your times vector doesn't run monotonically.  I think that messes with lsoda.  What is the context/meaning of the way that time works here?  It doesn't really make sense to fit a random-effects model with two groups.  Are you trying to fit the same curve to two independent time series?

Here's a stripped-down example, with some adjustments (not everything can be collapsed to a numeric vector without losing necessary structure):

```<code>library(deSolve)
ODE1 <- function(time, x, parms) {
    with(as.list(parms), {
        import <- excfunc(time)
        dS <- import*k/tau - (x-yo)/tau
        res <- c(dS)
        list(res)
    })
}
solution_ODE1 = function(tau1,k1,yo1,excitation,time){
    excfunc <- approxfun(time, excitation, rule = 2)
    parms  <- list(tau = tau1, k = k1, yo = yo1, excfunc = excfunc)
    xstart = yo1
    out <-  lsoda(xstart, time, ODE1, parms)
    return(out[,2])
}
time <- 0:49
excitation <- c(rep(0,10),rep(1,10),rep(0,10),rep(1,10),rep(0,10))
simu_data <- data.frame(time = rep(time,2),
                        excitation = rep(excitation,2))
svec <- c(damping = 3, gain = 1.75, eq = 0.2)
</code>```

This works:

```<code>with(c(simu_data, as.list(svec)),
     solution_ODE1(damping,gain,eq,excitation[1:50],time[1:50]))
</code>```

But if we include one more step (so that time resets to 0), it fails:

```<code>with(c(simu_data, as.list(svec)),
     solution_ODE1(damping,gain,eq,excitation[1:51],time[1:51]))
</code>```

Error in lsoda(xstart, time, ODE1, parms) :
    illegal input detected before taking any integration steps - see written message

Body:
I a trying to fit a first order differential model using nlme and lsoda.
Here is the basic idea: I first define the function allowing to generate the solution of the differential equation:

library(deSolve)

ODE1 <- function(time, x, parms) {with(as.list(c(parms, x)), {
  import <- excfunc(time)
  dS <- import*k/tau - (S-yo)/tau
  res <- c(dS)
  list(res)})}

solution_ODE1 = function(tau1,k1,yo1,excitation,time){
  excfunc <- approxfun(time, excitation, rule = 2)
  parms  <- c(tau = tau1, k = k1, yo = yo1, excfunc = excfunc)
  xstart = c(S = yo1)
  out <-  lsoda(xstart, time, ODE1, parms)
  return(out[,2])
}

I then generate data following the equation for two IDs:

time <- 0:49
excitation <- c(rep(0,10),rep(1,10),rep(0,10),rep(1,10),rep(0,10))
simu_data <- data.frame(signal = c(solution_ODE1(3,2,0.1,excitation,time)+rnorm(length(time),0,0.1),
                                   solution_ODE1(3.2,1.5,0.3,excitation,time)+rnorm(length(time),0,0.1)),
                        time = rep(time,2),
                        excitation = rep(excitation,2),
                        ID = rep(c("A","B"),each = length(time)))

Here  is what it looks like :

library(ggplot2)
ggplot(simu_data)+
  geom_point(aes(time,signal,color = "signal"),size = 2)+
  geom_line(aes(time,excitation,color = "excitation"))+
  facet_wrap(~ID)

I am then trying to fit using nlme:

fit1 <- nlme(signal ~ solution_ODE1(damping,gain,eq,excitation,time),
             data = simu_data,
             fixed = damping + gain + eq ~1,
             random =  damping   ~ 1 ,
             groups = ~ ID,
             start = c(damping = 5, gain = 1,eq = 0))

I am getting this eror, that I don't get:

Error in eval(substitute(expr), data, enclos = parent.frame()) :
    object 'k' not found

The traceback shows that the error comes from the ODE1 model, which works when generating values.

16.    eval(substitute(expr), data, enclos = parent.frame())
15.    eval(substitute(expr), data, enclos = parent.frame())
14.    with.default(as.list(c(parms, x)), {
    import <- excfunc(time)
    dS <- import * k/tau - (S - yo)/tau
    res <- c(dS) ...
13.    with(as.list(c(parms, x)), {
    import <- excfunc(time)
    dS <- import * k/tau - (S - yo)/tau
    res <- c(dS) ...
12.    func(time, state, parms, ...)
11.    Func2(times[1], y)
10.    eval(Func2(times[1], y), rho)
9.    checkFunc(Func2, times, y, rho)
8.    lsoda(xstart, time, ODE1, parms)
7.    solution_ODE1(damping, gain, eq, excitation, time)
6.    eval(model, data.frame(data, pars))
5.    eval(model, data.frame(data, pars))
4.    eval(modelExpression[[2]], envir = nlEnv)
3.    eval(modelExpression[[2]], envir = nlEnv)
2.    nlme.formula(signal ~ solution_ODE1(damping, gain, eq, excitation,
    time), data = simu_data, fixed = damping + gain + eq ~ 1,
    random = damping ~ 1, groups = ~ID, start = c(damping = 5,
        gain = 1, eq = 0))
1.    nlme(signal ~ solution_ODE1(damping, gain, eq, excitation, time),
    data = simu_data, fixed = damping + gain + eq ~ 1, random = damping ~
        1, groups = ~ID, start = c(damping = 5, gain = 1, eq = 0))

Does anyone have an idea How I should proceed ?

Edit

I tried to modify following the advise of mikeck:

ODE1 <- function(time, x, parms) {
  import <- parms$excfunc(time)
  dS <- import*parms$k/parms$tau - (x["S"]-parms$yo)/parms$tau
  res <- c(dS)
  list(res)}

Generating the data works without problems. But use of nlme gives now:

Error in checkFunc(Func2, times, y, rho) :
    The number of derivatives returned by func() (0) must equal the length of the initial conditions vector (100)

with the following traceback:

> traceback()
10: stop(paste("The number of derivatives returned by func() (",
        length(tmp[[1]]), ") must equal the length of the initial conditions vector (",
        length(y), ")", sep = ""))
9: checkFunc(Func2, times, y, rho)
8: lsoda(xstart, time, ODE1, parms) at #5
7: solution_ODE1(damping, gain, eq, excitation, time)
6: eval(model, data.frame(data, pars))
5: eval(model, data.frame(data, pars))
4: eval(modelExpression[[2]], envir = nlEnv)
3: eval(modelExpression[[2]], envir = nlEnv)
2: nlme.formula(signal ~ solution_ODE1(damping, gain, eq, excitation,
       time), data = simu_data, fixed = damping + gain + eq ~ 1,
       random = damping ~ 1, groups = ~ID, start = c(damping = 5,
           gain = 1, eq = 0))
1: nlme(signal ~ solution_ODE1(damping, gain, eq, excitation, time),
       data = simu_data, fixed = damping + gain + eq ~ 1, random = damping ~
           1, groups = ~ID, start = c(damping = 5, gain = 1, eq = 0))

Body:
In your example, your times vector doesn't run monotonically.  I think that messes with lsoda.  What is the context/meaning of the way that time works here?  It doesn't really make sense to fit a random-effects model with two groups.  Are you trying to fit the same curve to two independent time series?

Here's a stripped-down example, with some adjustments (not everything can be collapsed to a numeric vector without losing necessary structure):

library(deSolve)
ODE1 <- function(time, x, parms) {
    with(as.list(parms), {
        import <- excfunc(time)
        dS <- import*k/tau - (x-yo)/tau
        res <- c(dS)
        list(res)
    })
}
solution_ODE1 = function(tau1,k1,yo1,excitation,time){
    excfunc <- approxfun(time, excitation, rule = 2)
    parms  <- list(tau = tau1, k = k1, yo = yo1, excfunc = excfunc)
    xstart = yo1
    out <-  lsoda(xstart, time, ODE1, parms)
    return(out[,2])
}
time <- 0:49
excitation <- c(rep(0,10),rep(1,10),rep(0,10),rep(1,10),rep(0,10))
simu_data <- data.frame(time = rep(time,2),
                        excitation = rep(excitation,2))
svec <- c(damping = 3, gain = 1.75, eq = 0.2)

This works:

with(c(simu_data, as.list(svec)),
     solution_ODE1(damping,gain,eq,excitation[1:50],time[1:50]))

But if we include one more step (so that time resets to 0), it fails:

with(c(simu_data, as.list(svec)),
     solution_ODE1(damping,gain,eq,excitation[1:51],time[1:51]))

Error in lsoda(xstart, time, ODE1, parms) :
    illegal input detected before taking any integration steps - see written message


问:
How do I convert a string to a dictionary which appears to already be a dictionary?
I have a dictionary that appears as:

```<code>my_string = "{'C': [(1, 2, 'string'), (3, 4, 'second string')]}"
</code>```

for some reason, even though it appears to be a dict, when I check type(my_string) it appears to be a string.

When I try converting it to a dictionary by dict(my_string) I am met with the error:

ValueError: dictionary update sequence element #0 has length 1; 2 is
  required

答:
You can use ast.literal_eval available from python 2.6:

```<code>import ast

my_string = "{'C': [(1, 2, 'string'), (3, 4, 'second string')]}"
my_dic = ast.literal_eval(my_string)
print(type(my_dic))
print(my_dic)
</code>```

output:

```<code>$ python conv_dic.py
<type 'dict'>
{'C': [(1, 2, 'string'), (3, 4, 'second string')]}
</code>```

Body:
I have a dictionary that appears as:

my_string = "{'C': [(1, 2, 'string'), (3, 4, 'second string')]}"

for some reason, even though it appears to be a dict, when I check type(my_string) it appears to be a string.

When I try converting it to a dictionary by dict(my_string) I am met with the error:

ValueError: dictionary update sequence element #0 has length 1; 2 is
  required

Body:
You can use ast.literal_eval available from python 2.6:

import ast

my_string = "{'C': [(1, 2, 'string'), (3, 4, 'second string')]}"
my_dic = ast.literal_eval(my_string)
print(type(my_dic))
print(my_dic)

output:

$ python conv_dic.py
<type 'dict'>
{'C': [(1, 2, 'string'), (3, 4, 'second string')]}


问:
bash scripting: Can I get sed to output the original line, then a space, then the modified line?
I'm new to Unix in all its forms, so please go easy on me!
I have a bash script that will pipe an ls command with arbitrary filenames into sed, which will use an arbitrary replacement pattern on the files, and then this will be piped into awk for some processing. The catch is, awk needs to know both the original file name and the new one.

I've managed everything except getting the original file names into awk. For instance, let's say my files are test.* and my replacement pattern is 's:es:ar;', which would change every occurrence of "test" to "tart". For testing purposes I'm just using awk to print what it's receiving:

```<code>ls "$@" | sed "$pattern" | awk '{printf "0: %s\n1: %s\n2: %s\n", $0,$1,$2}'
</code>```

where test.* is in $@ and the pattern is stored in $pattern.
Clearly, this doesn't get me to where I want to be. The output is obviously

```<code>0: tart.c
1: tart.c
2:
</code>```

If I could get sed to output "test.c tart.c", then I'd have two parameters for awk. I've played around with the pattern to no avail, even hardcoding "test.c" into the replacement. But of course that just gave me amateur results like "ttest.c art.c". Is it possible for sed to remember the input, then work it into the beginning of the output? Do I even have the right ideas? Thanks in advance!

答:
```<code>$ echo 'foo' | awk '{old=$0; gsub(/o/,"e"); print old, $0}'
foo fee
</code>```

Body:
I'm new to Unix in all its forms, so please go easy on me!
I have a bash script that will pipe an ls command with arbitrary filenames into sed, which will use an arbitrary replacement pattern on the files, and then this will be piped into awk for some processing. The catch is, awk needs to know both the original file name and the new one.

I've managed everything except getting the original file names into awk. For instance, let's say my files are test.* and my replacement pattern is 's:es:ar;', which would change every occurrence of "test" to "tart". For testing purposes I'm just using awk to print what it's receiving:

ls "$@" | sed "$pattern" | awk '{printf "0: %s\n1: %s\n2: %s\n", $0,$1,$2}'

where test.* is in $@ and the pattern is stored in $pattern.
Clearly, this doesn't get me to where I want to be. The output is obviously

0: tart.c
1: tart.c
2:

If I could get sed to output "test.c tart.c", then I'd have two parameters for awk. I've played around with the pattern to no avail, even hardcoding "test.c" into the replacement. But of course that just gave me amateur results like "ttest.c art.c". Is it possible for sed to remember the input, then work it into the beginning of the output? Do I even have the right ideas? Thanks in advance!


问:
Inserting only new data from one table to another with different structures
Inserting only new data from one table to another with different structures

Hi everyone,
I'm trying to insert in the table "userhr.nucleofam_ris" only the extra data present in "userhr.paghe_nucleo_fam".
But the error appears:

 "Subquery returned more than 1 value. This is not permitted when the subquery follows =,! =, <, <=,>,> = Or when the subquery is used as an expression."

the problem is that I'm trying to enter a higher +1 kint for each more found record.

```<code>SELECT distinct
       (select ROW_NUMBER() OVER (ORDER BY kint ASC) + 11000 from userhr.nucleofam_ris) as kint,
       hr01.kint as [kpadre]
      ,hr01.kint as [risorsa]
      ,hr05.parentela
      ,null as [gradoparentela]
      ,hr05.codfisc as [codfisc]
      ,hr05.cognome as [cognome]
      ,hr05.nome as [nome]
      ,concat(hr05.cognome,' ',hr05.nome) as [nominativo]
      ,hr05.sesso as [sesso]
      ,hr05.datanasc as [nasc_data]
      ,null as [comune]
      ,null as [codice]
      ,null as [provincia]
      ,null as [stato]
      ,'NO' [disabile]
      ,null as [percdisab]
      ,'NO' AS [parto_plurimo]
      ,null as  [data_decesso]
      ,null as [data_presnascita_figlio]
      ,'NO' AS [acarico]
      ,'NO' AS [flessibilita]
      ,'NO' AS [sost_coniuge]
  FROM userhr.ris_umane hr01 INNER JOIN
       userhr.wwrapp_ris hr03 ON (hr01.kint = hr03.kpar) INNER JOIN
       userhr.rapp_lavoro_ris hr04 ON (hr03.karr = hr04.kint) INNER JOIN
       userhr.paghe_nucleo_fam hr05 ON (hr04.kint = hr05.kpadre)
where hr05.codfisc is not null
      and hr05.cognome is not null
      and hr05.nome is not null
      and NOT EXISTS (SELECT 1
                      FROM userhr.nucleofam_ris hr02
                      WHERE hr02.codfisc = hr05.codfisc)
</code>```

can you help me?

答:
I think from your description that you want to create the next set of keys so that the rows you return can be inserted after the last row in your existing table.

This is an example that will do that, using two temporary table variables. It should point you in the right direction.

```<code>declare @t1 table(k int, txt1 varchar(10))
insert @t1 values (1,'firstrow'),(2,'second'),(3,'third')

declare @t2 table(txt2 varchar(10))
insert @t2 values ('a'),('b'),('c')

select row_number() over(order by txt2)
    +(select max(k) from @t1) NewKey,
    txt2
from @t2 t2
</code>```

Result is:

```<code>NewKey  txt2
4       a
5       b
6       c
</code>```

Body:
Inserting only new data from one table to another with different structures

Hi everyone,
I'm trying to insert in the table "userhr.nucleofam_ris" only the extra data present in "userhr.paghe_nucleo_fam".
But the error appears:

 "Subquery returned more than 1 value. This is not permitted when the subquery follows =,! =, <, <=,>,> = Or when the subquery is used as an expression."

the problem is that I'm trying to enter a higher +1 kint for each more found record.

SELECT distinct
       (select ROW_NUMBER() OVER (ORDER BY kint ASC) + 11000 from userhr.nucleofam_ris) as kint,
       hr01.kint as [kpadre]
      ,hr01.kint as [risorsa]
      ,hr05.parentela
      ,null as [gradoparentela]
      ,hr05.codfisc as [codfisc]
      ,hr05.cognome as [cognome]
      ,hr05.nome as [nome]
      ,concat(hr05.cognome,' ',hr05.nome) as [nominativo]
      ,hr05.sesso as [sesso]
      ,hr05.datanasc as [nasc_data]
      ,null as [comune]
      ,null as [codice]
      ,null as [provincia]
      ,null as [stato]
      ,'NO' [disabile]
      ,null as [percdisab]
      ,'NO' AS [parto_plurimo]
      ,null as  [data_decesso]
      ,null as [data_presnascita_figlio]
      ,'NO' AS [acarico]
      ,'NO' AS [flessibilita]
      ,'NO' AS [sost_coniuge]
  FROM userhr.ris_umane hr01 INNER JOIN
       userhr.wwrapp_ris hr03 ON (hr01.kint = hr03.kpar) INNER JOIN
       userhr.rapp_lavoro_ris hr04 ON (hr03.karr = hr04.kint) INNER JOIN
       userhr.paghe_nucleo_fam hr05 ON (hr04.kint = hr05.kpadre)
where hr05.codfisc is not null
      and hr05.cognome is not null
      and hr05.nome is not null
      and NOT EXISTS (SELECT 1
                      FROM userhr.nucleofam_ris hr02
                      WHERE hr02.codfisc = hr05.codfisc)

can you help me?

Body:
I think from your description that you want to create the next set of keys so that the rows you return can be inserted after the last row in your existing table.

This is an example that will do that, using two temporary table variables. It should point you in the right direction.

declare @t1 table(k int, txt1 varchar(10))
insert @t1 values (1,'firstrow'),(2,'second'),(3,'third')

declare @t2 table(txt2 varchar(10))
insert @t2 values ('a'),('b'),('c')

select row_number() over(order by txt2)
    +(select max(k) from @t1) NewKey,
    txt2
from @t2 t2

Result is:

NewKey  txt2
4       a
5       b
6       c


答:
If it's a string, you should be able to use ast.literal_eval from the Abstract Syntax Tree library to parse it into a dict.

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

```<code>import ast.literal_eval()

s =  "{'C': [(1, 2, 'string'), (3, 4, 'second string')]}"
d = ast.literal_eval(s)

print(type(d))
# dict

print(d)
# {'C': [(1, 2, 'string'), (3, 4, 'second string')]}
</code>```

Title: How do I convert a string to a dictionary which appears to already be a dictionary?

Body:
If it's a string, you should be able to use ast.literal_eval from the Abstract Syntax Tree library to parse it into a dict.

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

import ast.literal_eval()

s =  "{'C': [(1, 2, 'string'), (3, 4, 'second string')]}"
d = ast.literal_eval(s)

print(type(d))
# dict

print(d)
# {'C': [(1, 2, 'string'), (3, 4, 'second string')]}


问:
IBM Watson STT: How to use Websocket interface with multiple chunks?
I have developed an application for streaming speech recognition in c++ using another API and IBM Watson Speech to Text service API.

In both these programs, I am using the same file which contains this audio

several tornadoes touch down as a line of severe thunderstorms swept through Colorado on Sunday

This file is 641,680 bytes in size and I am sending 100,000 bytes (max) chunks at a time to the Speech to text servers.

Now, with the other API I am able to have everything recognized as a whole. With the IBM Watson API I couldn't. Here is what I have done:

Connect to IBM Watson web server (Speech to text API)

Send start frame {"action":"start","content-type":"audio/mulaw;rate=8000"}

Send binary 100,000 bytes

Send stop frame {"action":"stop"}

...Repeat binary and stop until the last byte.

The IBM Watson Speech API could only recognize the chunks individually

e.g.

several tornadoes touch down

     a line of severe thunder

     swept through Colorado

     Sunday

This seems to be the output of individual chunks and the words coming in between the chunk division (for eg here, "thunderstorm" is partially present in the end of a chunk and partially in the starting of the next chunk) are thus incorrectly recognized or dropped.

What am I doing wrong?

EDIT (I am using c++ with boost library for websocket interface)

```<code>//Do the websocket handshake
void IbmWebsocketSession::on_ssl_handshake(beast::error_code ec) {

    auto mToken = mSttServiceObject->GetToken(); // Get the authentication token

    //Complete the websocket handshake and call back the "send_start" function
    mWebSocket.async_handshake_ex(mHost, mUrlEndpoint, [mToken](request_type& reqHead) {reqHead.insert(http::field::authorization,mToken);},
            bind(&IbmWebsocketSession::send_start, shared_from_this(), placeholders::_1));
}

//Sent the start frame
void IbmWebsocketSession::send_start(beast::error_code ec) {

    //Send the START_FRAME and call back the "read_resp" function to receive the "state: listening" message
    mWebSocket.async_write(net::buffer(START_FRAME),
            bind(&IbmWebsocketSession::read_resp, shared_from_this(), placeholders::_1, placeholders::_2));
}

//Sent the binary data
void IbmWebsocketSession::send_binary(beast::error_code ec) {

    streamsize bytes_read = mFilestream.rdbuf()->sgetn(&chunk[0], chunk.size()); //gets the binary data chunks from a file (which is being written at run time

    // Send binary data
    if (bytes_read > mcMinsize) {  //Minimum size defined by IBM  is 100 bytes.
                                   // If chunk size is greater than 100 bytes, then send the data and then callback "send_stop" function
        mWebSocket.binary(true);

        /**********************************************************************
         *  Wait a second before writing the next chunk.
         **********************************************************************/
        this_thread::sleep_for(chrono::seconds(1));

        mWebSocket.async_write(net::buffer(&chunk[0], bytes_read),
                bind(&IbmWebsocketSession::send_stop, shared_from_this(), placeholders::_1));
    } else {                     //If chunk size is less than 100 bytes, then DO NOT send the data only call "send_stop" function
        shared_from_this()->send_stop(ec);
    }

}

void IbmWebsocketSession::send_stop(beast::error_code ec) {

    mWebSocket.binary(false);
    /*****************************************************************
     * Send the Stop message
     *****************************************************************/
    mWebSocket.async_write(net::buffer(mTextStop),
            bind(&IbmWebsocketSession::read_resp, shared_from_this(), placeholders::_1, placeholders::_2));
}

void IbmWebsocketSession::read_resp(beast::error_code ec, size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);
        if(mWebSocket.is_open())
        {
            // Read the websocket response and call back the "display_buffer" function
            mWebSocket.async_read(mBuffer, bind(&IbmWebsocketSession::display_buffer, shared_from_this(),placeholders::_1));
        }
        else
            cerr << "Error: " << e->what() << endl;

}

void IbmWebsocketSession::display_buffer(beast::error_code ec) {

    /*****************************************************************
     * Get the buffer into stringstream
     *****************************************************************/
    msWebsocketResponse << beast::buffers(mBuffer.data());

    mResponseTranscriptIBM = ParseTranscript(); //Parse the response transcript

    mBuffer.consume(mBuffer.size()); //Clear the websocket buffer

    if ("Listening" == mResponseTranscriptIBM && true != mSttServiceObject->IsGstFileWriteDone()) { // IsGstFileWriteDone -> checks if the user has stopped speaking
        shared_from_this()->send_binary(ec);
    } else {
        shared_from_this()->close_websocket(ec, 0);
    }
}
</code>```

答:
@data_henrik is correct, the flow is wrong, it should be: ...START FRAME >> binary data >> binary data >> binary data >> ... >> STOP FRAME

you only need to send the {"action":"stop"} message when there are no more audio chunks to send

Body:
I have developed an application for streaming speech recognition in c++ using another API and IBM Watson Speech to Text service API.

In both these programs, I am using the same file which contains this audio

several tornadoes touch down as a line of severe thunderstorms swept through Colorado on Sunday

This file is 641,680 bytes in size and I am sending 100,000 bytes (max) chunks at a time to the Speech to text servers.

Now, with the other API I am able to have everything recognized as a whole. With the IBM Watson API I couldn't. Here is what I have done:

Connect to IBM Watson web server (Speech to text API)

Send start frame {"action":"start","content-type":"audio/mulaw;rate=8000"}

Send binary 100,000 bytes

Send stop frame {"action":"stop"}

...Repeat binary and stop until the last byte.

The IBM Watson Speech API could only recognize the chunks individually

e.g.

several tornadoes touch down

     a line of severe thunder

     swept through Colorado

     Sunday

This seems to be the output of individual chunks and the words coming in between the chunk division (for eg here, "thunderstorm" is partially present in the end of a chunk and partially in the starting of the next chunk) are thus incorrectly recognized or dropped.

What am I doing wrong?

EDIT (I am using c++ with boost library for websocket interface)

//Do the websocket handshake
void IbmWebsocketSession::on_ssl_handshake(beast::error_code ec) {

    auto mToken = mSttServiceObject->GetToken(); // Get the authentication token

    //Complete the websocket handshake and call back the "send_start" function
    mWebSocket.async_handshake_ex(mHost, mUrlEndpoint, [mToken](request_type& reqHead) {reqHead.insert(http::field::authorization,mToken);},
            bind(&IbmWebsocketSession::send_start, shared_from_this(), placeholders::_1));
}

//Sent the start frame
void IbmWebsocketSession::send_start(beast::error_code ec) {

    //Send the START_FRAME and call back the "read_resp" function to receive the "state: listening" message
    mWebSocket.async_write(net::buffer(START_FRAME),
            bind(&IbmWebsocketSession::read_resp, shared_from_this(), placeholders::_1, placeholders::_2));
}

//Sent the binary data
void IbmWebsocketSession::send_binary(beast::error_code ec) {

    streamsize bytes_read = mFilestream.rdbuf()->sgetn(&chunk[0], chunk.size()); //gets the binary data chunks from a file (which is being written at run time

    // Send binary data
    if (bytes_read > mcMinsize) {  //Minimum size defined by IBM  is 100 bytes.
                                   // If chunk size is greater than 100 bytes, then send the data and then callback "send_stop" function
        mWebSocket.binary(true);

        /**********************************************************************
         *  Wait a second before writing the next chunk.
         **********************************************************************/
        this_thread::sleep_for(chrono::seconds(1));

        mWebSocket.async_write(net::buffer(&chunk[0], bytes_read),
                bind(&IbmWebsocketSession::send_stop, shared_from_this(), placeholders::_1));
    } else {                     //If chunk size is less than 100 bytes, then DO NOT send the data only call "send_stop" function
        shared_from_this()->send_stop(ec);
    }

}

void IbmWebsocketSession::send_stop(beast::error_code ec) {

    mWebSocket.binary(false);
    /*****************************************************************
     * Send the Stop message
     *****************************************************************/
    mWebSocket.async_write(net::buffer(mTextStop),
            bind(&IbmWebsocketSession::read_resp, shared_from_this(), placeholders::_1, placeholders::_2));
}

void IbmWebsocketSession::read_resp(beast::error_code ec, size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);
        if(mWebSocket.is_open())
        {
            // Read the websocket response and call back the "display_buffer" function
            mWebSocket.async_read(mBuffer, bind(&IbmWebsocketSession::display_buffer, shared_from_this(),placeholders::_1));
        }
        else
            cerr << "Error: " << e->what() << endl;

}

void IbmWebsocketSession::display_buffer(beast::error_code ec) {

    /*****************************************************************
     * Get the buffer into stringstream
     *****************************************************************/
    msWebsocketResponse << beast::buffers(mBuffer.data());

    mResponseTranscriptIBM = ParseTranscript(); //Parse the response transcript

    mBuffer.consume(mBuffer.size()); //Clear the websocket buffer

    if ("Listening" == mResponseTranscriptIBM && true != mSttServiceObject->IsGstFileWriteDone()) { // IsGstFileWriteDone -> checks if the user has stopped speaking
        shared_from_this()->send_binary(ec);
    } else {
        shared_from_this()->close_websocket(ec, 0);
    }
}