问:
Build file in Sublime Text 3 to invoke JUnit5 tests
I am trying to configure Sublime Text 3's RunJava.sublime-build file to add an option to execute JUnit 5 test on Mac OS X.

The following works for me from the Mac OS X terminal window:

$ java -jar /Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar -cp /Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/ --scan-classpath

My RunJava.sublime-build configuration file is:

```<code>{
    "selector": "source.java",
    "file_patterns": "*.java",
    "working_dir": "$file_path",
    "shell_cmd": "javac -cp .:/Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/:/Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar $file_name",
    "variants": [
        {
            "name": "Run class.jar",
            "shell_cmd": "java -cp .:/Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/:/Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar $file_base_name"
        },

        {
            "name": "JavaDoc",
            "shell_cmd": "mkdir -p documentation && javadoc -header \"<script type='text/javascript' src='http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script>\" -d documentation *.java"
        },

        {
            "name": "JAR",
            "cmd": "javac '$realpath$file' && echo \"Main-Class: $file_base_name\" > Manifest.txt && jar cfm $file_base_name.jar Manifest.txt *.class && rm *.class && java -jar $file_base_name.jar"
        },

        {
            "name": "JUnit5",
            "cmd": "java -jar /Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar -cp $file_path --scan-classpath"
        }

    ]
}
</code>```

Instead of full JUnit 5 output I just get [Finished in X.Xs].

Does JUnit get executed? If so, where is the output?

P.S. I have read Sublime is not a perfect environment for Java, but still.

答: I suspect what you are doing to trigger the unit tests is either using the ⌘B keyboard shortcut or selecting Tools → Build from the menu. The way Sublime's build systems work, this will only trigger the initial "shell_cmd" command. The way to run one of the variants is to use ⌘⇧B or select Tools → Build With…. This will display a dropdown with all the different variants available. Selecting JUnit5 should run your unit tests as specified.

Body:
I am trying to configure Sublime Text 3's RunJava.sublime-build file to add an option to execute JUnit 5 test on Mac OS X.

The following works for me from the Mac OS X terminal window:

$ java -jar /Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar -cp /Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/ --scan-classpath

My RunJava.sublime-build configuration file is:

{
    "selector": "source.java",
    "file_patterns": "*.java",
    "working_dir": "$file_path",
    "shell_cmd": "javac -cp .:/Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/:/Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar $file_name",
    "variants": [
        {
            "name": "Run class.jar",
            "shell_cmd": "java -cp .:/Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/:/Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar $file_base_name"
        },

        {
            "name": "JavaDoc",
            "shell_cmd": "mkdir -p documentation && javadoc -header \"\" -d documentation *.java"
        },

        {
            "name": "JAR",
            "cmd": "javac '$realpath$file' && echo \"Main-Class: $file_base_name\" > Manifest.txt && jar cfm $file_base_name.jar Manifest.txt *.class && rm *.class && java -jar $file_base_name.jar"
        },

        {
            "name": "JUnit5",
            "cmd": "java -jar /Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar -cp $file_path --scan-classpath"
        }

    ]
}

Instead of full JUnit 5 output I just get [Finished in X.Xs].

Does JUnit get executed? If so, where is the output?

P.S. I have read Sublime is not a perfect environment for Java, but still.


来源: stackexchange

问:
MongoDB aggregation with $lookup to show only result of one field
I'm trying to get only object pasien_docs in result of lookup, I using match, lookup and addfield but i want get result only show array of pasien_docs:

```<code>Pasien.aggregate(
  [
    {
      $match: {
        _id: ObjectId(id)
      }
    },
    {
      $lookup:
      {
          from: "data",
          localField: "_id",
          foreignField: "idPasien",
          as: "pasien_docs"
      }
    },
    { '$addFields': {
      'pasien_docs': {
        '$map': {
          'input': '$pasien_docs',
          'in': {
            'ecg': '$$this.ecg',
            'date': '$$this.date'
          }
        }
      }
    }}
  ]
)
</code>```

and the result is :

```<code>    "data": [
    {
        "_id": "5e08a79fe34fa20a302f659f",
        "username": "rizkarahayus",
        "nama": "Rizka Rahayu",
        "__v": 0,
        "pasien_docs": [
            {
                "ecg": null,
                "date": "2020-01-21T05:22:01.901Z"
            },
            {
                "ecg": 1.03,
                "date": "2020-01-21T05:22:02.979Z"
            },
</code>```

but i want result only show array of pasien_docs like this :

```<code>"pasien_docs": [
            {
                "ecg": null,
                "date": "2020-01-21T05:22:01.901Z"
            },
            {
                "ecg": 1.03,
                "date": "2020-01-21T05:22:02.979Z"
            },
</code>```

can you help me? thank you...

答:
You can simply use $project and specify the inclusion of pasien_docs computed field, the suppression of the _id field like:

```<code>Pasien.aggregate(
  [
    {
      $match: {...}
    },
    {
      $lookup: {...}
    },
    {
     '$addFields': {...}
    },
    {
      $project: { _id: 0, pasien_docs: 1 }
    }
  ]
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get only object pasien_docs in result of lookup, I using match, lookup and addfield but i want get result only show array of pasien_docs:

Pasien.aggregate(
  [
    {
      $match: {
        _id: ObjectId(id)
      }
    },
    {
      $lookup:
      {
          from: "data",
          localField: "_id",
          foreignField: "idPasien",
          as: "pasien_docs"
      }
    },
    { '$addFields': {
      'pasien_docs': {
        '$map': {
          'input': '$pasien_docs',
          'in': {
            'ecg': '$$this.ecg',
            'date': '$$this.date'
          }
        }
      }
    }}
  ]
)

and the result is :

    "data": [
    {
        "_id": "5e08a79fe34fa20a302f659f",
        "username": "rizkarahayus",
        "nama": "Rizka Rahayu",
        "__v": 0,
        "pasien_docs": [
            {
                "ecg": null,
                "date": "2020-01-21T05:22:01.901Z"
            },
            {
                "ecg": 1.03,
                "date": "2020-01-21T05:22:02.979Z"
            },

but i want result only show array of pasien_docs like this :

"pasien_docs": [
            {
                "ecg": null,
                "date": "2020-01-21T05:22:01.901Z"
            },
            {
                "ecg": 1.03,
                "date": "2020-01-21T05:22:02.979Z"
            },

can you help me? thank you...

Body:
You can simply use $project and specify the inclusion of pasien_docs computed field, the suppression of the _id field like:

Pasien.aggregate(
  [
    {
      $match: {...}
    },
    {
      $lookup: {...}
    },
    {
     '$addFields': {...}
    },
    {
      $project: { _id: 0, pasien_docs: 1 }
    }
  ]
)


问:
How to debug who is eating my touches in UIKit?
I can't figure out why tapping on text fields and buttons in my view is not working. I've checked all the obvious things like whether userInteractionEnabled is set to YES, whether a gesture recognizer is installed, and if there is an invisible view in the foreground.

Is there a best practice in iOS for tracing a touch from when it first appears to where it gets consumed?

UPDATE:

Both answers were helpful. During the course of my investigation I learned that if a subview is outside of its parent's bounds, even if the parent is not clipping subviews, the subview will not receive events. I printed out the chain of superviews from the text field that was not getting touches, and I saw that one of those views had a height of 0. I put in some constraints to stretch it out, and my problem was solved.

答:
To see more detail about which kind of gesture recognizers is source of issue from @Peter's answer, I print out the array of gestureRecognizer:</p>

```<code>class TestWindow:UIWindow {
    override func sendEvent(_ event: UIEvent) {

        event.allTouches?.forEach() { touch in
            print("touch")
            print(touch.gestureRecognizers ?? "")
            /// [<UILongPressGestureRecognizer: 0x7fb205964ab0; state = Possible; view = <UIView 0x7fb205964940>; target= <(action=_handleMenuGesture: ....
        }

        super.sendEvent(event)
    }
}

</code>```

ContentLicense: CC BY-SA 3.0

Body:
To see more detail about which kind of gesture recognizers is source of issue from @Peter's answer, I print out the array of gestureRecognizer:

class TestWindow:UIWindow {
    override func sendEvent(_ event: UIEvent) {

        event.allTouches?.forEach() { touch in
            print("touch")
            print(touch.gestureRecognizers ?? "")
            /// [<UILongPressGestureRecognizer: 0x7fb205964ab0; state = Possible; view = <UIView 0x7fb205964940>; target= <(action=_handleMenuGesture: ....
        }

        super.sendEvent(event)
    }
}


问:
How do I use C++ STL list without iterator?
I need to get to the items in the STL list. I believe those items are of type list_item or ListItem. I need 'next' and 'prev' of each item. how do I do that?</p>

答: std::list does not support next or prev by itself. The iterator is used to go from element to element, and you cannot traverse a standard list without it.


问:
TEMP_DATA value must be same but it is changing
In my application I have one function below filter TEMP_DATA(which has unfiltered list) than redraw chart with this filter.It work for first filter but for the second time it doesn't work because
el.TEMP_DATA is also changing althought it must be same.

Stackblitz Demo

```<code>perSelect(org){
    this.reports.filter(x=>x.TITLE==org).forEach(el=>{
       el.chartOptions.series[0].data= el.c_personel.length!=0 ? el.TEMP_DATA.filter(y=>el.c_personel.map(x=>{return x.id}).join(",").includes(y.sicil)) : el.TEMP_DATA
       el.updateFromInput = true;
   })
}
</code>```

this is also my class

```<code>export class Oxy{
    public TITLE:string;
    public highcharts:typeof Highcharts=Highcharts;
    public chartOptions:Highcharts.Options;
    public TEMP_DATA=[];
    public PERSONELLER=[];
    public c_personel=[];
}
</code>```

c_personel fills with dropdown. PERSONELLER and TEMP_DATA fills when page is loaded. What can be caused to change TEMP_DATA ?

As I control problem occurs with series: [{ data: datas, type: "scatter" }]
this also updates TEMP_DATA

I want to update graph related to person filter. Graph shows selected personels' result . If not selected anything, show all data.

Thanks in advance

答:
The issue arises because the default copy method is shallow. So apart from the primitive data types, changes to the the other types such as arrays, or JSON objects when shallow copied, will reflect on the original variable.

So, try deep copy methods such as JSON.parse(JSON.stringify(value));
or let var2 = [...var1];

Probably change the reference to the Chart Options.

Body:
In my application I have one function below filter TEMP_DATA(which has unfiltered list) than redraw chart with this filter.It work for first filter but for the second time it doesn't work because
el.TEMP_DATA is also changing althought it must be same.

Stackblitz Demo

perSelect(org){
    this.reports.filter(x=>x.TITLE==org).forEach(el=>{
       el.chartOptions.series[0].data= el.c_personel.length!=0 ? el.TEMP_DATA.filter(y=>el.c_personel.map(x=>{return x.id}).join(",").includes(y.sicil)) : el.TEMP_DATA
       el.updateFromInput = true;
   })
}

this is also my class

export class Oxy{
    public TITLE:string;
    public highcharts:typeof Highcharts=Highcharts;
    public chartOptions:Highcharts.Options;
    public TEMP_DATA=[];
    public PERSONELLER=[];
    public c_personel=[];
}

c_personel fills with dropdown. PERSONELLER and TEMP_DATA fills when page is loaded. What can be caused to change TEMP_DATA ?

As I control problem occurs with series: [{ data: datas, type: "scatter" }]
this also updates TEMP_DATA

I want to update graph related to person filter. Graph shows selected personels' result . If not selected anything, show all data.

Thanks in advance


问:
Trigger notification on specific Alexa device
I saw a few posts with similar question but they are all outdated and not really answered. The idea is to trigger a notification on a specific Alexa device. For example through another Alexa in the same network or over phone remotely. Before I get my hands dirty is something like this possible at all?

Here is a similar question Trigger Alexa speaking

答:
I guess what you are looking for is Proactive Events.

What you can do is use these APIs in your skill to send notification to the customers of your Alexa skill to their respective Alexa devices.

Alexa Docs for ProactiveEventsAPI :

https://developer.amazon.com/en-US/docs/alexa/smapi/proactive-events-api.html

They support a set of pre-defined templates(schemas) for different type of notifications that can be sent. These are listed here:

https://developer.amazon.com/en-US/docs/alexa/smapi/schemas-for-proactive-events.html

If you don't find the one suitable for your use case they also provide you option in the same schema listing page to submit your request to them.

Alexa's developer blog on the same with link to step-by-step building instructions for a demo skill which uses ProactiveEvents API:

https://developer.amazon.com/blogs/alexa/post/bbf23596-766a-4e7c-8d74-cbfc234b6791/how-to-send-media-event-notifications-to-your-alexa-skill-customers

Other resources I found on web for the same which might be useful:

https://www.jovo.tech/tutorials/alexa-notifications-proactive-events

https://datavizz.in/blog/alexa/2019/04/18/send-notifications-to-users-using-Alexa.html


问:
How do I make an AIML bot respond with sound? And is there a way to make this sound a custom voice?
I am making an AIML bot, but I don't want it to be only text-based conversations. I want the bot to respond with a voice that ideally I created myself.</p>

答:
If you use aiml in a java application for example. You can add a sound in java when the answer shows.
In pandora there is no such thing</p>


问:
React JS: Implementing Show/More with respect to a table
I am trying to implement a show more/show less functionality with respect to a table. Show More/ Show less link should be visible only when there are more than 2 elements and show less should set it back to default number of items(i.e.2 in my case).Show More should print rest of the items. I am using react-table for the same.There is a data grid component where I pass necessary props, and trying to implement this logic in the child.

I have tried the following. Can someone tell where I am going wrong?

Sandbox: https://codesandbox.io/s/react-table-row-table-ryiny?file=/src/index.js

```<code>import React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false,
    };
  }

  toggleState = () => {
    this.setState(prevState => ({
      showMore: !prevState.showMore
    }), () => {
      const subset: = this.state.showMore ? this.props.data : this.props.data.slice(0, 2);
    });
  }

  renderTableData = () => {
    const { data } = this.props;
    const subset = this.state.showMore ? data : data.slice(0, 2);
    return subset;
  };

  render() {
    const { showMore  } = this.state;
    const { data,columns } = this.props;
    const showLink = data.length > 2;
    return (
            <>
            {showLink && (
              <a onClick={this.toggleState}>
                Show {showMore ? "Less" : "More")}
              </a>
            )}
          <ReactTable
            showPagination={false}
            data={data}
            columns={columns}
          />
        </>
    )
  }
}

</code>```

答:
'columns' is in the props not the state and if that is the only functionality you need then remove the renderTableData function

Try this

```<code>...

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false,
    };
  }

  toggleState = () => {
    this.setState(prevState => ({
      showMore: !prevState.showMore
    }));
  }

  render() {
    const { showMore } = this.state;
    const { data, columns } = this.props;
    const showLink = data.length > 2;
    const subset = showMore ? data : data.slice(0, 2);
    return (
            <>
            {showLink && (
              <a onClick={this.toggleState}>
                Show {showMore ? "Less" : "More"}
              </a>
            )}
          <ReactTable
            showPagination={false}
            data={subset}
            columns={columns}
          />
        </>
    )
  }
}
</code>```

Body:
I am trying to implement a show more/show less functionality with respect to a table. Show More/ Show less link should be visible only when there are more than 2 elements and show less should set it back to default number of items(i.e.2 in my case).Show More should print rest of the items. I am using react-table for the same.There is a data grid component where I pass necessary props, and trying to implement this logic in the child.

I have tried the following. Can someone tell where I am going wrong?

Sandbox: https://codesandbox.io/s/react-table-row-table-ryiny?file=/src/index.js

import React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false,
    };
  }

  toggleState = () => {
    this.setState(prevState => ({
      showMore: !prevState.showMore
    }), () => {
      const subset: = this.state.showMore ? this.props.data : this.props.data.slice(0, 2);
    });
  }

  renderTableData = () => {
    const { data } = this.props;
    const subset = this.state.showMore ? data : data.slice(0, 2);
    return subset;
  };

  render() {
    const { showMore  } = this.state;
    const { data,columns } = this.props;
    const showLink = data.length > 2;
    return (
            <>
            {showLink && (

                Show {showMore ? "Less" : "More")}

            )}
          <ReactTable
            showPagination={false}
            data={data}
            columns={columns}
          />
        </>
    )
  }
}

Body:
'columns' is in the props not the state and if that is the only functionality you need then remove the renderTableData function

Try this

...

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false,
    };
  }

  toggleState = () => {
    this.setState(prevState => ({
      showMore: !prevState.showMore
    }));
  }

  render() {
    const { showMore } = this.state;
    const { data, columns } = this.props;
    const showLink = data.length > 2;
    const subset = showMore ? data : data.slice(0, 2);
    return (
            <>
            {showLink && (
              <a onClick={this.toggleState}>
                Show {showMore ? "Less" : "More"}
              </a>
            )}
          <ReactTable
            showPagination={false}
            data={subset}
            columns={columns}
          />
        </>
    )
  }
}


问:
Characters allowed in a URL
Does anyone know the full list of characters that can be used within a GET without being encoded? At the moment I am using A-Z a-z and 0-9... but I am looking to find out the full list.

I am also interested into if there is a specification released for the up coming addition of Chinese, Arabic url's (as obviously that will have a big impact on my question)

答:
If you like to give a special kind of experience to the users you could use pushState to bring a wide range of characters to the browser's url:

```<code>var u="";var tt=168;
for(var i=0; i< 250;i++){
 var x = i+250*tt;
console.log(x);
 var c = String.fromCharCode(x);
 u+=c;
}
history.pushState({},"",250*tt+u);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Characters allowed in a URL

Body:
If you like to give a special kind of experience to the users you could use pushState to bring a wide range of characters to the browser's url:

var u="";var tt=168;
for(var i=0; i< 250;i++){
 var x = i+250*tt;
console.log(x);
 var c = String.fromCharCode(x);
 u+=c;
}
history.pushState({},"",250*tt+u);


问:
Splitting a string with regular expressions in .NET
I am in need of a regular expression that I can use to examine a string and return specific items when I do a RegEx.Split() in .NET. I've been trying to do this on my own, but I can never seem to get what I need, and the results never make any sense. Obviously I do not have a good handle on writing regular expressions.

So here is the string...

```<code>"%date - %-5level - [%thread] - %logger - %message - %exception%newline"
</code>```

I essentially want to be returned an array that looks like the following:

```<code>"date"
"-5level"
"thread"
"logger"
"message"
"exception"
"newline"
</code>```

The following code is close, but not quite.

```<code>Regex exp = new Regex(@"\W+");
string[] s = exp.Split(@"%date - %-5level - [%thread] - %logger - %message - %exception%newline");
</code>```

I get the following:

```<code>""
"date"
"5level"
"thread"
"logger"
"message"
"exception"
"newline"
</code>```

For some reason, I have an empty string as the first index, and the 3rd index is missing the "-". I assume because it is not a part of a "word".

The "-" aside for the moment, I then want to split "5level" into an array:

```<code>"5"
"level"
</code>```

I experimented with this:

```<code>Regex exp2 = new Regex(@"(\d+)([a-zA-Z]+)");
string[] s2 = exp2.Split("5level");
</code>```

But, it returns 2 indexes with empty strings in addition to the split items I want like so:

```<code>""
"5"
"level"
""
</code>```

I'm stumped on how to format the expression to give me what I need. Any help would be appreciated.

答:
Instead of using Regex.Split, it might be easier to match the tokens you need:

```<code>MatchCollection matches = Regex.Matches(s, @"%([\w\-]+)");
string[] words = matches.Cast<Match>().Select(m => m.Groups[1].Value).ToArray();
</code>```

Split may add empty matches, as you've witnessed, that will have to be filtered out.

Body:
I am in need of a regular expression that I can use to examine a string and return specific items when I do a RegEx.Split() in .NET. I've been trying to do this on my own, but I can never seem to get what I need, and the results never make any sense. Obviously I do not have a good handle on writing regular expressions.

So here is the string...

"%date - %-5level - [%thread] - %logger - %message - %exception%newline"

I essentially want to be returned an array that looks like the following:

"date"
"-5level"
"thread"
"logger"
"message"
"exception"
"newline"

The following code is close, but not quite.

Regex exp = new Regex(@"\W+");
string[] s = exp.Split(@"%date - %-5level - [%thread] - %logger - %message - %exception%newline");

I get the following:

""
"date"
"5level"
"thread"
"logger"
"message"
"exception"
"newline"

For some reason, I have an empty string as the first index, and the 3rd index is missing the "-". I assume because it is not a part of a "word".

The "-" aside for the moment, I then want to split "5level" into an array:

"5"
"level"

I experimented with this:

Regex exp2 = new Regex(@"(\d+)([a-zA-Z]+)");
string[] s2 = exp2.Split("5level");

But, it returns 2 indexes with empty strings in addition to the split items I want like so:

""
"5"
"level"
""

I'm stumped on how to format the expression to give me what I need. Any help would be appreciated.

Body:
Instead of using Regex.Split, it might be easier to match the tokens you need:

MatchCollection matches = Regex.Matches(s, @"%([\w\-]+)");
string[] words = matches.Cast<Match>().Select(m => m.Groups[1].Value).ToArray();

Split may add empty matches, as you've witnessed, that will have to be filtered out.


问:
inserting a list as a column in dataframe at specific location depending on value in row
so I have a dataframe (tsv/csv file), using numpy, pandas and statsmodels.

In one column "medianame" the name of the media (a stimulus) will appear on screen (this stimulus is moving. Each row represents a timestamp).

Whenever a specific media name appears in this column (for this example, let's say "stimulus1"), it is time to inset a list of lets say 5 numbers in another column, starting from this row on.

The other items in the column need to be empty (np.nan).

Another requirement is that it has to be inserted in every occasion the name appears "again" in the "medianame" column. So, it is possible that the number of items in the list is shorter than the number of consecutive occurrences of the medianame (see first occasion in the example below).

If the number of items in the list is longer than the number of consecutive occurrences of the medianame, it has to be cut off early (see second occasion in the example below).

Example:

```<code>List1 = [5, 7, 1, 8, 9] # to be inserted in column "position"
                        # when medianame "stimulus1" appears in column "medianame"

medianame
stimulus0
stimulus0
stimulus0
stimulus0
stimulus0
stimulus0
NaN
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
NaN
stimulus2
stimulus2
stimulus2
stimulus2
stimulus2
NaN
stimulus1
stimulus1
stimulus1
</code>```

After appending at the right place, hopefully it will look like:

```<code>medianame     position
stimulus0     NaN
stimulus0     NaN
stimulus0     NaN
stimulus0     NaN
stimulus0     NaN
stimulus0     NaN
NaN           NaN
stimulus1     5
stimulus1     7
stimulus1     1
stimulus1     8
stimulus1     9
stimulus1     NaN
stimulus1     NaN
stimulus1     NaN
stimulus1     NaN
stimulus1     NaN
NaN           NaN
stimulus2     NaN
stimulus2     NaN
stimulus2     NaN
stimulus2     NaN
stimulus2     NaN
NaN           NaN
stimulus1     5
stimulus1     7
stimulus1     1
</code>```

答:
Here is one way using merge with groupby, cumsum and pd.Series constructor:

```<code>df.assign(key = df.groupby((df['medianame'] != 'stimulus1').cumsum()).cumcount())\
  .merge(pd.Series(List1, index=range(1,len(List1)+1)).rename('position'),
         left_on='key',
         right_index=True,
         how='left')\
  .drop('key', axis=1)
</code>```

Output:

```<code>    medianame  position
0   stimulus0       NaN
1   stimulus0       NaN
2   stimulus0       NaN
3   stimulus0       NaN
4   stimulus0       NaN
5   stimulus0       NaN
6         NaN       NaN
7   stimulus1       5.0
8   stimulus1       7.0
9   stimulus1       1.0
10  stimulus1       8.0
11  stimulus1       9.0
12  stimulus1       NaN
13  stimulus1       NaN
14  stimulus1       NaN
15  stimulus1       NaN
16  stimulus1       NaN
17        NaN       NaN
18  stimulus2       NaN
19  stimulus2       NaN
20  stimulus2       NaN
21  stimulus2       NaN
22  stimulus2       NaN
23        NaN       NaN
24  stimulus1       5.0
25  stimulus1       7.0
26  stimulus1       1.0
</code>```

Details

Create a series, s with the index range starting at 1:

```<code>s = pd.Series(List1, index=range(1,len(List1)+1)).rename('position')
</code>```

Output:

```<code>1    5
2    7
3    1
4    8
5    9
Name: position, dtype: int64
</code>```

Now, let's join that series to the dataframe df where stimulus1, but first we need to create a join key on df.

```<code>df_key = df.assign(key = df.groupby((df['medianame'] != 'stimulus1').cumsum()).cumcount())
</code>```

Output:

```<code>    medianame  key
0   stimulus0    0
1   stimulus0    0
2   stimulus0    0
3   stimulus0    0
4   stimulus0    0
5   stimulus0    0
6         NaN    0
7   stimulus1    1
8   stimulus1    2
9   stimulus1    3
10  stimulus1    4
11  stimulus1    5
12  stimulus1    6
13  stimulus1    7
14  stimulus1    8
15  stimulus1    9
16  stimulus1   10
17        NaN    0
18  stimulus2    0
19  stimulus2    0
20  stimulus2    0
21  stimulus2    0
22  stimulus2    0
23        NaN    0
24  stimulus1    1
25  stimulus1    2
26  stimulus1    3
</code>```

Lastly, merge the df_key with s how='left' on key and s.index:

```<code>df_key.merge(s, how='left', left_on='key', right_index=True)
</code>```

Output:

```<code>    medianame  key  position
0   stimulus0    0       NaN
1   stimulus0    0       NaN
2   stimulus0    0       NaN
3   stimulus0    0       NaN
4   stimulus0    0       NaN
5   stimulus0    0       NaN
6         NaN    0       NaN
7   stimulus1    1       5.0
8   stimulus1    2       7.0
9   stimulus1    3       1.0
10  stimulus1    4       8.0
11  stimulus1    5       9.0
12  stimulus1    6       NaN
13  stimulus1    7       NaN
14  stimulus1    8       NaN
15  stimulus1    9       NaN
16  stimulus1   10       NaN
17        NaN    0       NaN
18  stimulus2    0       NaN
19  stimulus2    0       NaN
20  stimulus2    0       NaN
21  stimulus2    0       NaN
22  stimulus2    0       NaN
23        NaN    0       NaN
24  stimulus1    1       5.0
25  stimulus1    2       7.0
26  stimulus1    3       1.0
</code>```

And, if desired you can drop that key column.

Body:
so I have a dataframe (tsv/csv file), using numpy, pandas and statsmodels.

In one column "medianame" the name of the media (a stimulus) will appear on screen (this stimulus is moving. Each row represents a timestamp).

Whenever a specific media name appears in this column (for this example, let's say "stimulus1"), it is time to inset a list of lets say 5 numbers in another column, starting from this row on.

The other items in the column need to be empty (np.nan).

Another requirement is that it has to be inserted in every occasion the name appears "again" in the "medianame" column. So, it is possible that the number of items in the list is shorter than the number of consecutive occurrences of the medianame (see first occasion in the example below).

If the number of items in the list is longer than the number of consecutive occurrences of the medianame, it has to be cut off early (see second occasion in the example below).

Example:

List1 = [5, 7, 1, 8, 9] # to be inserted in column "position"
                        # when medianame "stimulus1" appears in column "medianame"

medianame
stimulus0
stimulus0
stimulus0
stimulus0
stimulus0
stimulus0
NaN
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
stimulus1
NaN
stimulus2
stimulus2
stimulus2
stimulus2
stimulus2
NaN
stimulus1
stimulus1
stimulus1

After appending at the right place, hopefully it will look like:

medianame     position
stimulus0     NaN
stimulus0     NaN
stimulus0     NaN
stimulus0     NaN
stimulus0     NaN
stimulus0     NaN
NaN           NaN
stimulus1     5
stimulus1     7
stimulus1     1
stimulus1     8
stimulus1     9
stimulus1     NaN
stimulus1     NaN
stimulus1     NaN
stimulus1     NaN
stimulus1     NaN
NaN           NaN
stimulus2     NaN
stimulus2     NaN
stimulus2     NaN
stimulus2     NaN
stimulus2     NaN
NaN           NaN
stimulus1     5
stimulus1     7
stimulus1     1

Body:
Here is one way using merge with groupby, cumsum and pd.Series constructor:

df.assign(key = df.groupby((df['medianame'] != 'stimulus1').cumsum()).cumcount())\
  .merge(pd.Series(List1, index=range(1,len(List1)+1)).rename('position'),
         left_on='key',
         right_index=True,
         how='left')\
  .drop('key', axis=1)

Output:

    medianame  position
0   stimulus0       NaN
1   stimulus0       NaN
2   stimulus0       NaN
3   stimulus0       NaN
4   stimulus0       NaN
5   stimulus0       NaN
6         NaN       NaN
7   stimulus1       5.0
8   stimulus1       7.0
9   stimulus1       1.0
10  stimulus1       8.0
11  stimulus1       9.0
12  stimulus1       NaN
13  stimulus1       NaN
14  stimulus1       NaN
15  stimulus1       NaN
16  stimulus1       NaN
17        NaN       NaN
18  stimulus2       NaN
19  stimulus2       NaN
20  stimulus2       NaN
21  stimulus2       NaN
22  stimulus2       NaN
23        NaN       NaN
24  stimulus1       5.0
25  stimulus1       7.0
26  stimulus1       1.0

Details

Create a series, s with the index range starting at 1:

s = pd.Series(List1, index=range(1,len(List1)+1)).rename('position')

Output:

1    5
2    7
3    1
4    8
5    9
Name: position, dtype: int64

Now, let's join that series to the dataframe df where stimulus1, but first we need to create a join key on df.

df_key = df.assign(key = df.groupby((df['medianame'] != 'stimulus1').cumsum()).cumcount())

Output:

    medianame  key
0   stimulus0    0
1   stimulus0    0
2   stimulus0    0
3   stimulus0    0
4   stimulus0    0
5   stimulus0    0
6         NaN    0
7   stimulus1    1
8   stimulus1    2
9   stimulus1    3
10  stimulus1    4
11  stimulus1    5
12  stimulus1    6
13  stimulus1    7
14  stimulus1    8
15  stimulus1    9
16  stimulus1   10
17        NaN    0
18  stimulus2    0
19  stimulus2    0
20  stimulus2    0
21  stimulus2    0
22  stimulus2    0
23        NaN    0
24  stimulus1    1
25  stimulus1    2
26  stimulus1    3

Lastly, merge the df_key with s how='left' on key and s.index:

df_key.merge(s, how='left', left_on='key', right_index=True)

Output:

    medianame  key  position
0   stimulus0    0       NaN
1   stimulus0    0       NaN
2   stimulus0    0       NaN
3   stimulus0    0       NaN
4   stimulus0    0       NaN
5   stimulus0    0       NaN
6         NaN    0       NaN
7   stimulus1    1       5.0
8   stimulus1    2       7.0
9   stimulus1    3       1.0
10  stimulus1    4       8.0
11  stimulus1    5       9.0
12  stimulus1    6       NaN
13  stimulus1    7       NaN
14  stimulus1    8       NaN
15  stimulus1    9       NaN
16  stimulus1   10       NaN
17        NaN    0       NaN
18  stimulus2    0       NaN
19  stimulus2    0       NaN
20  stimulus2    0       NaN
21  stimulus2    0       NaN
22  stimulus2    0       NaN
23        NaN    0       NaN
24  stimulus1    1       5.0
25  stimulus1    2       7.0
26  stimulus1    3       1.0

And, if desired you can drop that key column.


问:
My If statement is not working in Middleware
I am trying to make a middleware which can filter my http request by checking if the "$created_by" that I am passing through the request alreday exists in my "users" table

If it does I want to proceed with my "$next($request)"

And if it doesn't I wanna redirect it.

When the situation is this:-

```<code>if ($ip->uuid == $request->created_by)
</code>```

It redirects to $next($request); which is correct

But when the "$request->created_by" is not present in DB it which makes $ip null

And it shows this error "Trying to get property 'uuid' of non-object"

Here's my Middleware:-

```<code><?php

namespace App\Http\Middleware;

use Closure;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class Posts
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)

     {
      $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
        // dd($ip);
       if ($ip->uuid == $request->created_by) {
        if ($ip == null) {
             return redirect('https://www.google.com');
        }

       }

        return $next($request);

        }
    }
</code>```

答:
Edit:

You already made the comparison in DB, update handle() to be:

```<code>    public function handle($request, Closure $next)
    {
       $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();

       if (is_object($ip) {

         return $next($request);

       }

       return redirect('https://www.google.com');
    }
</code>```

Body:
I am trying to make a middleware which can filter my http request by checking if the "$created_by" that I am passing through the request alreday exists in my "users" table

If it does I want to proceed with my "$next($request)"

And if it doesn't I wanna redirect it.

When the situation is this:-

if ($ip->uuid == $request->created_by)

It redirects to $next($request); which is correct

But when the "$request->created_by" is not present in DB it which makes $ip null

And it shows this error "Trying to get property 'uuid' of non-object"

Here's my Middleware:-

<?php

namespace App\Http\Middleware;

use Closure;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class Posts
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)

     {
      $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
        // dd($ip);
       if ($ip->uuid == $request->created_by) {
        if ($ip == null) {
             return redirect('https://www.google.com');
        }

       }

        return $next($request);

        }
    }

Body:
Edit:

You already made the comparison in DB, update handle() to be:

    public function handle($request, Closure $next)
    {
       $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();

       if (is_object($ip) {

         return $next($request);

       }

       return redirect('https://www.google.com');
    }


问:
BluetoothAdapter getAddress() return 02:00:00:00:00:00
I try to return the Bluetooth mac address of my device but this is not working and return this address : 02:00:00:00:00:00 .

-I'm using API Level 28

-I can get my Bluetooth mac address in my android system settings but not programmatically in my app.

-I can get the mac address of this device programmatically from other devices.

What I understand is that access to address mac is only for system applications ,but if It's true why other devices get my mac address and not me !

```<code>BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
test.setText(adapter.getAdress());
</code>```

I try many permissions but still the same problem !

```<code><uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<uses-permission android:name="android.permission.LOCAL_MAC_ADDRESS" />
<uses-permission android:name="android.permission.INTERNET" />
</code>```

答:
Since Android 6, Marshmallow apps do not have access anymore to the bluetooth hardware MAC address. This change was made because the address was abused by many apps to identify and track smartphones. To avoid that existing apps are broken the getter method still exists but it returns a dummy address. For details see the corresponding note within Android's official release notes here

But what about visibility of the MAC address to other devices?

Bluetooth Low Energy (LE) does not use the hardware MAC address for communication. It uses a randomized variant of it (see here
for details). Since Bluetooth LE does not stop scanning for nearby devices in background even when the user explicitly disables Bluetooth this feature
is considerable ;-)

Bluetooth classic does not randomize the MAC address. But in constrast to Bluetooth LE the user can at least easily and fully disable Bluetooth.

Body:
I try to return the Bluetooth mac address of my device but this is not working and return this address : 02:00:00:00:00:00 .

-I'm using API Level 28

-I can get my Bluetooth mac address in my android system settings but not programmatically in my app.

-I can get the mac address of this device programmatically from other devices.

What I understand is that access to address mac is only for system applications ,but if It's true why other devices get my mac address and not me !

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
test.setText(adapter.getAdress());

I try many permissions but still the same problem !

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<uses-permission android:name="android.permission.LOCAL_MAC_ADDRESS" />
<uses-permission android:name="android.permission.INTERNET" />


问:
c++ Why shouldn't I unlock a mutex from a different thread
Why shouldn't I unlock a mutex from a different thread? In the c++ standard it says it pretty clearly: If the mutex is not currently locked by the calling thread, it causes undefined behavior. But as far as I can see, everything works as expected on Linux(Fedora 31 with GCC). I seriously tried everything but I could not get it to behave strangely.
All I'm asking for is an example where something, literally anything is affected by unlocking a mutex from a different thread.

Here is a quick test I wrote which is super wrong and shoudn't work but it does:

```<code>std::mutex* testEvent;

int main()
{
    testEvent = new std::mutex[1000];

    for(uint32_t i = 0; i < 1000; ++i) testEvent[i].lock();

    std::thread threads[2000];

    auto lock = [](uint32_t index) ->void { testEvent[index].lock(); assert(!testEvent[index].try_lock()); };
    auto unlock = [](uint32_t index) ->void { testEvent[index].unlock(); };

    for(uint32_t j = 0; j < 1000; ++j)
    {
        for(uint32_t i = 0; i < 1000; ++i)
        {
            threads[i]      = std::thread(lock,i);
            threads[i+1000] = std::thread(unlock,i);
        }
        for(uint32_t i = 0; i < 2000; ++i)
        {
            threads[i].join();
        }
        std::cout << j << std::endl;
    }

    delete[] testEvent;
}
</code>```

答:
I really wonder why you would want to do this in the first place ;)

Normally you would want to have something like

```<code>lock();
do_critical_task();
unlock();
</code>```

(In c++, the lock/unlock is often hidden by use of std::lock_guard or similar.)

Let's assume one thread (lets say Thread A) called this code and is inside the critical task, i.e. it is also holding the lock.
Then if you unlock the same mutex from another thread, any thread other than A can also enter the critical section simultaneously.

The main purpose of mutexes is to have mutual exclusion (hence their name), so all you would do is to erase the purpose of the mutex ;)

That said: you should always believe the standard. Only if something works out on a certain system it doesn't mean it's portable. Plus: especially in a concurrent context, a lot of things can work out a thousand times but then fail the 1001'th time as of race conditions.
In mathematics your attempt would be comparable to "proof by example".

Body:
Why shouldn't I unlock a mutex from a different thread? In the c++ standard it says it pretty clearly: If the mutex is not currently locked by the calling thread, it causes undefined behavior. But as far as I can see, everything works as expected on Linux(Fedora 31 with GCC). I seriously tried everything but I could not get it to behave strangely.
All I'm asking for is an example where something, literally anything is affected by unlocking a mutex from a different thread.

Here is a quick test I wrote which is super wrong and shoudn't work but it does:

std::mutex* testEvent;

int main()
{
    testEvent = new std::mutex[1000];

    for(uint32_t i = 0; i < 1000; ++i) testEvent[i].lock();

    std::thread threads[2000];

    auto lock = [](uint32_t index) ->void { testEvent[index].lock(); assert(!testEvent[index].try_lock()); };
    auto unlock = [](uint32_t index) ->void { testEvent[index].unlock(); };

    for(uint32_t j = 0; j < 1000; ++j)
    {
        for(uint32_t i = 0; i < 1000; ++i)
        {
            threads[i]      = std::thread(lock,i);
            threads[i+1000] = std::thread(unlock,i);
        }
        for(uint32_t i = 0; i < 2000; ++i)
        {
            threads[i].join();
        }
        std::cout << j << std::endl;
    }

    delete[] testEvent;
}

Body:
I really wonder why you would want to do this in the first place ;)

Normally you would want to have something like

lock();
do_critical_task();
unlock();

(In c++, the lock/unlock is often hidden by use of std::lock_guard or similar.)

Let's assume one thread (lets say Thread A) called this code and is inside the critical task, i.e. it is also holding the lock.
Then if you unlock the same mutex from another thread, any thread other than A can also enter the critical section simultaneously.

The main purpose of mutexes is to have mutual exclusion (hence their name), so all you would do is to erase the purpose of the mutex ;)

That said: you should always believe the standard. Only if something works out on a certain system it doesn't mean it's portable. Plus: especially in a concurrent context, a lot of things can work out a thousand times but then fail the 1001'th time as of race conditions.
In mathematics your attempt would be comparable to "proof by example".


问:
How do I perform an operation iteratively on a python list/array whithout a for loop?
Is it possible to perform the following operation on the first two elements of the list, storing the result and then performing the next operation on the previous result and the next item in the list for all items in the list without a for loop? Here F(x) is an arbitrarily defined function.
This is the working code with a for loop:

```<code>list   = [a,b,c,d,e,f,g,h]
result = F(a,b)

for i in range(2,len(list)):
    result = F(result,list[i])

print(result)
</code>```

Thank you very much in advance, the best answer gets a pancake.

答:
you can write the funcction yourself:

```<code>def split_and_compute(_list):
    if len(_list) > 2:
        return myother_fun(_list[0:2]) + split_and_compute(_list[2:])
    else:
        return myother_fun(_list)

def myother_fun(_list):
    return _list[0] + _list[1]
</code>```

Note the + in return myother_fun(_list[0:2]) + split_and_compute(_list[2:]) should be whatever acumulator you have, depending on what data you are dealing with, also this dealswith 2 elements in a very hacky way, can put some guards in there

Body:
Is it possible to perform the following operation on the first two elements of the list, storing the result and then performing the next operation on the previous result and the next item in the list for all items in the list without a for loop? Here F(x) is an arbitrarily defined function.
This is the working code with a for loop:

list   = [a,b,c,d,e,f,g,h]
result = F(a,b)

for i in range(2,len(list)):
    result = F(result,list[i])

print(result)

Thank you very much in advance, the best answer gets a pancake.

Body:
you can write the funcction yourself:

def split_and_compute(_list):
    if len(_list) > 2:
        return myother_fun(_list[0:2]) + split_and_compute(_list[2:])
    else:
        return myother_fun(_list)

def myother_fun(_list):
    return _list[0] + _list[1]

Note the + in return myother_fun(_list[0:2]) + split_and_compute(_list[2:]) should be whatever acumulator you have, depending on what data you are dealing with, also this dealswith 2 elements in a very hacky way, can put some guards in there


问:
upload image to S3 presigned url using react-native-image-picker and axios
I am trying to get an presigned url image upload working correctly. Currently the upload succeeds when selecting an image from the IOS simulator, however when I actually try to view the file it seems the file is corrupted and will not open as an image. I suspect it has something to do with my FormData but not sure.

```<code>export async function receiptUpload(file) {

  const date = new Date();
  const headers = await getAWSHeaders();

  const presignUrl = await request.post(
      urls.fileUpload.presignUpload,
      {file_name: `${date.getTime()}.jpg`},
      {headers}
    )
    .then(res => res.data);

  const formData = new FormData();
  formData.append('file', {
    name: `${date.getTime()}.jpg`,
    uri: file.uri,
    type: file.type
  });

  const fileUpload = presignUrl.presignUrl && await request.put(
      presignUrl.presignUrl,
      formData
    )
    .then(res => res.status === 200);

}
</code>```

I have tried from other fixes to change the file uri like so...

Platform.OS === 'android' ? file.uri : file.uri.replace('file://', '');

however this does not seem to work either.

答:
I had to do this recently for a project. I believe the data is a base64 string when coming directly from the file input. So the issue is your are uploading a base64 string not the image by simply passing the data field. I had to process it before uploading to the signed URL with the following method.</p>

```<code>private dataUriToBlob(dataUri) {
    const binary = atob(dataUri.split(',')[1]);
    const array = [];
    for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
}
</code>```

Body:
I am trying to get an presigned url image upload working correctly. Currently the upload succeeds when selecting an image from the IOS simulator, however when I actually try to view the file it seems the file is corrupted and will not open as an image. I suspect it has something to do with my FormData but not sure.

export async function receiptUpload(file) {

  const date = new Date();
  const headers = await getAWSHeaders();

  const presignUrl = await request.post(
      urls.fileUpload.presignUpload,
      {file_name: `${date.getTime()}.jpg`},
      {headers}
    )
    .then(res => res.data);

  const formData = new FormData();
  formData.append('file', {
    name: `${date.getTime()}.jpg`,
    uri: file.uri,
    type: file.type
  });

  const fileUpload = presignUrl.presignUrl && await request.put(
      presignUrl.presignUrl,
      formData
    )
    .then(res => res.status === 200);

}

I have tried from other fixes to change the file uri like so...

Platform.OS === 'android' ? file.uri : file.uri.replace('file://', '');

however this does not seem to work either.

Body:
I had to do this recently for a project. I believe the data is a base64 string when coming directly from the file input. So the issue is your are uploading a base64 string not the image by simply passing the data field. I had to process it before uploading to the signed URL with the following method.

private dataUriToBlob(dataUri) {
    const binary = atob(dataUri.split(',')[1]);
    const array = [];
    for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
}


问:
Kafka fetch max bytes doesn't work as expected
I have a topic worth 1 GB of messages. A. Kafka consumer decides to consume these messages. What could I do to prohibit the consumer from consuming all messages at once? I tried to set the

fetch.max.bytes on the broker

to 30 MB to allow only 30 MB of messages in each poll. The broker doesn't seem to honor that and tries to give all messages at once to the consumer causing Consumer out of memory error. How can I resolve this issue?

答:
Kafka configurations can be quite overwhelming. Typically in Kafka, multiple configurations can work together to achieve a result. This brings flexibility, but flexibility comes with a price.

From the documentation of fetch.max.bytes:

Records are fetched in batches by the consumer, and if the first record batch in the first non-empty partition of the fetch is larger than this value, the record batch will still be returned to ensure that the consumer can make progress.

Only on the consumer side, there are more configurations to consider for bounding the consumer memory usage, including:

max.poll.records: limits the number of records retrieved in a single call to poll. Default is 500.

max.partition.fetch.bytes: limits the number of bytes fetched per partition. This should not be a problem as the default is 1MB.

As per the information in KIP-81, the memory usage in practice should be something like min(num brokers * max.fetch.bytes,  max.partition.fetch.bytes * num_partitions).

Also, in the same KIP:

The consumer (Fetcher) delays decompression until the records are returned to the user, but because of max.poll.records, it may end up holding onto the decompressed data from a single partition for a few iterations.

I'd suggest you to also tune these parameters and hopefully this will get you into the desired state.


问:
Add and implement a spinner in fragment
I have seen guides and tutorials implementing spinner for activities. However the same method doesn't work for fragments. This was my code inside the onCreateView method of a fragment class

```<code>val personnames = arrayOf("akshat" , "mourya")
    val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, personnames)
    spinner.adapter = arrayAdapter
    spinner.onItemSelectedListener = object :

    AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {

        }

        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View?,
            position: Int,
            id: Long
        ) {

            spinnerText.text = personnames[position]
        }
</code>```

When the ArrayAdapter method is called on line 2, I get a type mismatch error because the first parameter requires a context and in my code it is a fragment.
I tried doing the same thing in the activity and it worked.
Fragment are supposed to be like mini activities, so why this error propping up?

Also is there any way I can add spinner to my Fragment?

答:
Use requireContext() in place of this in line 2.

Like this:

```<code>val arrayAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, personnames)
</code>```

Title: Add and implement a spinner in fragment

Body:
I have seen guides and tutorials implementing spinner for activities. However the same method doesn't work for fragments. This was my code inside the onCreateView method of a fragment class

val personnames = arrayOf("akshat" , "mourya")
    val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, personnames)
    spinner.adapter = arrayAdapter
    spinner.onItemSelectedListener = object :

    AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {

        }

        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View?,
            position: Int,
            id: Long
        ) {

            spinnerText.text = personnames[position]
        }

When the ArrayAdapter method is called on line 2, I get a type mismatch error because the first parameter requires a context and in my code it is a fragment.
I tried doing the same thing in the activity and it worked.
Fragment are supposed to be like mini activities, so why this error propping up?

Also is there any way I can add spinner to my Fragment?

Body:
Use requireContext() in place of this in line 2.

Like this:

val arrayAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, personnames)


问:
MVC3 - Model empty on post
I have two models - category and article. I have pretty much the same delete views and controllers for both of them. The only difference is that it works for categories, but with articles I get empty model on HttpPost.

Categories:

```<code>    public ActionResult DeleteCat(int id)
    {
        Category cat = db.CategoryByID(id);
        if (cat != null)
        {
            return View(cat);
        }

        return RedirectToAction("Index");
    }

    [HttpPost]
    public ActionResult DeleteCat(Category model)
    {
        db.DeleteCategory(model.CategoryID);

        return RedirectToAction("Index");
    }
</code>```

Articles:

```<code>    public ActionResult Delete(int id)
    {
        Article art = db.ArticleByID(id);
        if (art != null)
        {
            return View(art);
        }

        return RedirectToAction("Index");

    }

    [HttpPost]
    public ActionResult Delete(Article model)
    {
        db.DeleteArticle(model.ArticleID);

        return RedirectToAction("Index");
    }
</code>```

Both views are generated by Visual Studio and I haven't changed them. When I want to delete a category, everything goes well. But when I want to delete an article, it first gets selected properly from database, then the view is displayed (everything is OK) but when I click the delete button the model is empty (all properties are either 0, null or false) and so the db.DeleteArticle throws an exception (there's no article with ArticleID = 0). Could anyone please provide me with any hints as to what should I check or how should I work around this?

答:
There are two primary ways this can happen.

One way is that you have custom model binding that is not working. I assume you are doing everything out-of-the-box so this wouldn't apply.

The most likely issue is that the data is not getting POSTed. Ensure that the fields exist inside the same Form that the Delete button is POSTing.

Title: MVC3 - Model empty on post

Body:
I have two models - category and article. I have pretty much the same delete views and controllers for both of them. The only difference is that it works for categories, but with articles I get empty model on HttpPost.

Categories:

    public ActionResult DeleteCat(int id)
    {
        Category cat = db.CategoryByID(id);
        if (cat != null)
        {
            return View(cat);
        }

        return RedirectToAction("Index");
    }

    [HttpPost]
    public ActionResult DeleteCat(Category model)
    {
        db.DeleteCategory(model.CategoryID);

        return RedirectToAction("Index");
    }

Articles:

    public ActionResult Delete(int id)
    {
        Article art = db.ArticleByID(id);
        if (art != null)
        {
            return View(art);
        }

        return RedirectToAction("Index");

    }

    [HttpPost]
    public ActionResult Delete(Article model)
    {
        db.DeleteArticle(model.ArticleID);

        return RedirectToAction("Index");
    }

Both views are generated by Visual Studio and I haven't changed them. When I want to delete a category, everything goes well. But when I want to delete an article, it first gets selected properly from database, then the view is displayed (everything is OK) but when I click the delete button the model is empty (all properties are either 0, null or false) and so the db.DeleteArticle throws an exception (there's no article with ArticleID = 0). Could anyone please provide me with any hints as to what should I check or how should I work around this?


问:
How to lookup the value of a dictionary inside a dictionary in C#?
I have this transitionMap: Dictionary<Dictionary<int, char>, int> transitionMap;

And I also have this dictionary: Dictionary<int, char> dictionary = new Dictionary<int, char> {{0, 'a'}};.

How do I get the value inside transitionMap that corresponds to dictionary1.

This is what I've tried:

```<code>        Dictionary<int, char> dictionary = new Dictionary<int, char> {{stateNum, symbol}};

        if (this.transitionMap.ContainsKey(dictionary))
        {
            int nextState = this.transitionMap[dictionary];
            Console.WriteLine("nextstate {0}", nextState);
        }
</code>```

答:
If you want to compare two dictionaries for equality then having a "super dictionary" will not help you in any way. You will have to manually compare all elements in two dictionaries.

First, compare the number of elements. Then run a loop through one dictionary, and with the key find the value in second dictionary, and if exists compare two values.

Body:
I have this transitionMap: Dictionary<Dictionary<int, char>, int> transitionMap;

And I also have this dictionary: Dictionary<int, char> dictionary = new Dictionary<int, char> {{0, 'a'}};.

How do I get the value inside transitionMap that corresponds to dictionary1.

This is what I've tried:

        Dictionary<int, char> dictionary = new Dictionary<int, char> {{stateNum, symbol}};

        if (this.transitionMap.ContainsKey(dictionary))
        {
            int nextState = this.transitionMap[dictionary];
            Console.WriteLine("nextstate {0}", nextState);
        }


问:
Xamarin Forms Post Request Body
```<code>public async static Task<RootUserData> getUSerLoggedIn(string userName, string password)
    {
        RootUserData rootUserData = new RootUserData();
        var url = URlConstants.LOGIN_URL;
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Authorization =  new AuthenticationHeaderValue("Bearer", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{userName}:{password}");
            httpClient.DefaultRequestHeaders.Add("content-type", "application/json");
            httpClient.DefaultRequestHeaders.Add("cache-control", "no-cache");

        } ;
    }
</code>```

I am using above code to make one Service call. I have to pass userEmailAddress in body as plain as shown in Postman Picture. Can You Please help me How to achieve this?

答:
Content-Type should not be added like that, It didn't work in my case, and gave a wrong response, instead

Pass content-Type like this -

```<code>httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
</code>```

Title: Xamarin Forms Post Request Body

Body:
public async static Task<RootUserData> getUSerLoggedIn(string userName, string password)
    {
        RootUserData rootUserData = new RootUserData();
        var url = URlConstants.LOGIN_URL;
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Authorization =  new AuthenticationHeaderValue("Bearer", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{userName}:{password}");
            httpClient.DefaultRequestHeaders.Add("content-type", "application/json");
            httpClient.DefaultRequestHeaders.Add("cache-control", "no-cache");

        } ;
    }

I am using above code to make one Service call. I have to pass userEmailAddress in body as plain as shown in Postman Picture. Can You Please help me How to achieve this?

Body:
Content-Type should not be added like that, It didn't work in my case, and gave a wrong response, instead

Pass content-Type like this -

httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");


问:
Query Builder return null for join result and raw query in AdonisJS
I want to get count result by Database.raw in a select query of the query builder but when my main table is empty, all fields of my query are null except Database.raw result.

Here is my query:

```<code>const jobs = await Database.table('jobs')
  .leftJoin('job_offers', 'jobs.id', 'job_offers.job_id')
  .select([
    Database.raw(`'job' as type`),
    Database.raw('COUNT(jobs.id) as offers_count'),
    'jobs.id', 'title', 'jobs.description', 'jobs.created_at',
  ])
  .limit(limit).offset(offset)
</code>```

and my query result is:

```<code>[
    {
        "type": "job",
        "offers_count": 0,
        "id": null,
        "title": null,
        "description": null,
        "created_at": null
    }
]
</code>```

In the above query, the result must be [] when there are not any row in my job table.

Update:

Here is the SQL command of above query builder methods, that return [] as result

SELECT
    'job' AS type,
    jobs.id, jobs.title, description, jobs.created_at,
    COUNT(job_offers.id) as offers_count

    FROM jobs
LEFT JOIN job_offers ON jobs.id = job_offers.id
```

What is wrong in my query?

答:
You are using leftJoin, if you don't want null results you should use innerJoin or join (both do the same thing).

const jobs = await Database.table('jobs')
  .join('job_offers', 'jobs.id', 'job_offers.job_id')
  .select([
    Database.raw(`'job' as type`),
    Database.raw('COUNT(jobs.id) as offers_count'),
    'jobs.id', 'title', 'jobs.description', 'jobs.created_at',
  ])
  .limit(limit).offset(offset)```

Body:
I want to get count result by Database.raw in a select query of the query builder but when my main table is empty, all fields of my query are null except Database.raw result.

Here is my query:

const jobs = await Database.table('jobs')
  .leftJoin('job_offers', 'jobs.id', 'job_offers.job_id')
  .select([
    Database.raw(`'job' as type`),
    Database.raw('COUNT(jobs.id) as offers_count'),
    'jobs.id', 'title', 'jobs.description', 'jobs.created_at',
  ])
  .limit(limit).offset(offset)

and my query result is:

[
    {
        "type": "job",
        "offers_count": 0,
        "id": null,
        "title": null,
        "description": null,
        "created_at": null
    }
]

In the above query, the result must be [] when there are not any row in my job table.

Update:

Here is the SQL command of above query builder methods, that return [] as result

SELECT
    'job' AS type,
    jobs.id, jobs.title, description, jobs.created_at,
    COUNT(job_offers.id) as offers_count

    FROM jobs
LEFT JOIN job_offers ON jobs.id = job_offers.id

What is wrong in my query?


问:
How to reset couchbase docker container password
I have installed 3 couchbase nodes of docker containers. After a couple of weeks when i tried to log in i could not remember my admin password. After a research i can not find a way to reset password. I am a newcomer to docker world so maybe i missed something. There is a source below but i believe that does not compromise my problem. How can i reset admin password ?

source

答:
The only way to reset your admin password that I'm aware of is to use couchbase-cli's reset-admin-password option, which must be run locally.

Since you are in docker, one option would be to execute bash inside of Docker, and run couchbase-cli there. For instance:

```<code>docker exec -it db /bin/bash
</code>```

At that point, you should have a bash prompt, and you can run couchbase-cli there.

Body:
The only way to reset your admin password that I'm aware of is to use couchbase-cli's reset-admin-password option, which must be run locally.

Since you are in docker, one option would be to execute bash inside of Docker, and run couchbase-cli there. For instance:

docker exec -it db /bin/bash

At that point, you should have a bash prompt, and you can run couchbase-cli there.


问:
Performance on import packages in ReactJS
I am trying to understand about "import" on React. I have already read the doc.

Who can explain to me why THE COST is different between using "{" or not use it.

In this particular case, should I use it or not?

Cheers

答:
Most of your questions can be answered in the documentation of your package here - https://material-ui.com/guides/minimizing-bundle-size/

tl;dr: If your current framework doesn't optimize it automatically via tree-shaking, do either Option 1 or 2, preferably Option 2.


问:
Lotus Notes - CreateMIMEEntity not releasing the control of .NSF file
I am using Interop.Domino to work with .NSF file. To generate the html mime entity I used the nnote but in some case it failed to generate it so in that case I took the RTFTEXT / PLIAN TEXT as output.
so I used CreateMIMEEntity for it.

NotesMIMEEntity MIMEBody = NoteDocument.CreateMIMEEntity("Body");

It works but it holds the control on the Database (.nsf file), file is getting mark as being used in another process.
By troubleshooting it it clear that above statement holds the control.
I have released all the Note objects assigned with it.Still problem remains same.
Is there are proper way to use it or release it?

答:
The Notes core DLLs that are underneath the COM classes keep databases open in cache. The only way that I know of to close them is to terminate the process that loaded the DLLs. One option is to design code using the COM API so that it dispatches short-term worker processes to open the database, do the work, and terminate. Yeah, it's ugly and slow, but if you need a long-running service and you're using the COM API instead of the Notes C API, it's the best way.

In any case, the cached open databases should not cause a sharing violation if you are opening the database through the Domino server. If you are using "" instead of the server name when opening the database however, it's going to be a problem -- and you shouldn't even do that in short-running worker processes.


问:
How to write a CASE statement in the WHERE clause in Snowflake
I am trying to rewrite a piece of SQL code that was initially written for Vertica. Vertica has the AGE_IN_YEARS() built-in function which was great to get someone's age. But, now, I need to find a way to have it to work in Snowflake and I did.

An equivalent statement that replaces AGE_IN_YEARS(DateOfBirth) in Snowflake can be:

```<code>case when dateadd(year, datediff(years, DateOfBirth, CURRENT_DATE), DateOfBirth) > CURRENT_DATE
then datediff(years, DateOfBirth, CURRENT_DATE) -1
else datediff(years, DateOfBirth, CURRENT_DATE)
end as AGE
</code>```

The issue is when I have to use this in a WHERE clause. The original Vertica code is:

```<code>SELECT name, dob,
(SELECT AgeRangeCode
   FROM AgeRangeTable
   WHERE AGE_IN_YEARS(DateOfBirth) BETWEEN MinAge AND MaxAge) AS AgeRangeCode,
CURRENT_DATE as TODAY
from MemberInfoTable
</code>```

and if i add the AGE_IN_YEARS() replacement to the above query, I get

SQL compilation error: Unsupported subquery type cannot be evaluated

How do I go about writing this case in the WHERE clause

答:
If you have Age column in your agerange table and you want to compare each customer/participant age with that and also in the min and max range of the age range table then you can simply do it in 2 ways.

```<code>SELECT name, dob,
       [AgeRangeCode] = (SELECT AgeRangeCode FROM AgeRangeTable WHERE DATEDIFF(Year,mi.dob,CURRENT_DATE) = mi.age
                                                         AND DATEDIFF(Year,mi.dob,CURRENT_DATE) BETWEEN MinAge AND MaxAge),
       CURRENT_DATE as TODAY
from MemberInfoTable mi
</code>```

or with a simple join like below

```<code>SELECT mi.name, mi.dob, art.AgeRangeCode,
       CURRENT_DATE as TODAY
FROM  MemberInfoTable mi
JOIN  AgeRangeTable art ON art.age = DATEDIFF(Year,mi.dob,CURRENT_DATE)
WHERE DATEDIFF(Year,mi.dob,CURRENT_DATE) BETWEEN art.MinAge AND art.MaxAge
</code>```

Body:
I am trying to rewrite a piece of SQL code that was initially written for Vertica. Vertica has the AGE_IN_YEARS() built-in function which was great to get someone's age. But, now, I need to find a way to have it to work in Snowflake and I did.

An equivalent statement that replaces AGE_IN_YEARS(DateOfBirth) in Snowflake can be:

case when dateadd(year, datediff(years, DateOfBirth, CURRENT_DATE), DateOfBirth) > CURRENT_DATE
then datediff(years, DateOfBirth, CURRENT_DATE) -1
else datediff(years, DateOfBirth, CURRENT_DATE)
end as AGE

The issue is when I have to use this in a WHERE clause. The original Vertica code is:

SELECT name, dob,
(SELECT AgeRangeCode
   FROM AgeRangeTable
   WHERE AGE_IN_YEARS(DateOfBirth) BETWEEN MinAge AND MaxAge) AS AgeRangeCode,
CURRENT_DATE as TODAY
from MemberInfoTable

and if i add the AGE_IN_YEARS() replacement to the above query, I get

SQL compilation error: Unsupported subquery type cannot be evaluated

How do I go about writing this case in the WHERE clause

Body:
If you have Age column in your agerange table and you want to compare each customer/participant age with that and also in the min and max range of the age range table then you can simply do it in 2 ways.

SELECT name, dob,
       [AgeRangeCode] = (SELECT AgeRangeCode FROM AgeRangeTable WHERE DATEDIFF(Year,mi.dob,CURRENT_DATE) = mi.age
                                                         AND DATEDIFF(Year,mi.dob,CURRENT_DATE) BETWEEN MinAge AND MaxAge),
       CURRENT_DATE as TODAY
from MemberInfoTable mi

or with a simple join like below

SELECT mi.name, mi.dob, art.AgeRangeCode,
       CURRENT_DATE as TODAY
FROM  MemberInfoTable mi
JOIN  AgeRangeTable art ON art.age = DATEDIFF(Year,mi.dob,CURRENT_DATE)
WHERE DATEDIFF(Year,mi.dob,CURRENT_DATE) BETWEEN art.MinAge AND art.MaxAge


问:
Does calling the erase() function changes the iterator value before the element being erased too?
So my doubt is simple, when we call erase() function for some range in a container,we know that the iterators following those element change (i'm talking about the iterators used to specify the range of the container as the arguments to the erase() function)
But my question is does the iterators before that elements change too? </p>

答:
when we call erase() function for some range in a container,we know that the iterators following those element change

I think you mean that those iterators become invalid. Note that this is not universally true for all containers. For example, iterators to elements after the erased one in std::list remain valid.

Which iterators are invalidated and when depends on the container. You'll need to consult the documentation of the container that you are using. One thing common to all standard containers is that iterators to the erased element are invalidated.


答:
If you passed -g to gcc when building the program, it should have DWARF debug information compiled in:

$ objdump -t prog | grep debug
0000000000000000 l    d  .debug_aranges 0000000000000000              .debug_aranges
0000000000000000 l    d  .debug_info    0000000000000000              .debug_info
0000000000000000 l    d  .debug_abbrev  0000000000000000              .debug_abbrev
0000000000000000 l    d  .debug_line    0000000000000000              .debug_line
0000000000000000 l    d  .debug_str     0000000000000000              .debug_str
```

<p>Then you can read it with <code>objdump</code>:</p>

<pre class="lang-sh prettyprint-override"><code>$ objdump --dwarf=info prog
[...]
 <1><65>: Abbrev Number: 5 (DW_TAG_base_type)
    <66>   DW_AT_byte_size   : 4
    <67>   DW_AT_encoding    : 5        (signed)
    <68>   DW_AT_name        : int
[...]
 <1><2f8>: Abbrev Number: 8 (DW_TAG_structure_type)
    <2f9>   DW_AT_name        : (indirect string, offset: 0x22f): global_struct
    <2fd>   DW_AT_byte_size   : 8
    <2fe>   DW_AT_decl_file   : 1
    <2ff>   DW_AT_decl_line   : 3
    <300>   DW_AT_decl_column : 16
    <301>   DW_AT_sibling     : <0x31c>
 <2><305>: Abbrev Number: 17 (DW_TAG_member)
    <306>   DW_AT_name        : a
    <308>   DW_AT_decl_file   : 1
    <309>   DW_AT_decl_line   : 4
    <30a>   DW_AT_decl_column : 9
    <30b>   DW_AT_type        : <0x65>
    <30f>   DW_AT_data_member_location: 0
 <2><310>: Abbrev Number: 17 (DW_TAG_member)
    <311>   DW_AT_name        : c
    <313>   DW_AT_decl_file   : 1
    <314>   DW_AT_decl_line   : 5
    <315>   DW_AT_decl_column : 9
    <316>   DW_AT_type        : <0x65>
    <31a>   DW_AT_data_member_location: 4
 <2><31b>: Abbrev Number: 0
 <1><31c>: Abbrev Number: 2 (DW_TAG_typedef)
    <31d>   DW_AT_name        : (indirect string, offset: 0x22f): global_struct
    <321>   DW_AT_decl_file   : 1
    <322>   DW_AT_decl_line   : 6
    <323>   DW_AT_decl_column : 2
    <324>   DW_AT_type        : <0x2f8>
[...]
</code>```

Here we can see that global_struct's DIE (Debug Information Entry) has two leaves (two DW_TAG_members, look at <2> prefixes which I believe it level in the tree).  The members are called a and c.  Both of the members reference type 0x65, which is defined above as a signed int.

A good place to learn more about DWARF is this official tutorial: http://www.dwarfstd.org/doc/Debugging%20using%20DWARF-2012.pdf

Title: Structure member details from object symbol table

Body:
Trying to use objdump command in linux to display symbol table information in executable.
i have tried a simple program below.

#include<stdio.h>
int global = 0;
typedef struct global_struct{
    int a;
    int c;
}global_struct;

global_struct gs;
int main()
{
    printf("%d\n",global);
    printf("%d\n",gs.a);
    return 0;
}

compiled with -g option in gcc compiler
The output of objdump looks like

00000000004005b0 l     F .text  0000000000000000              __do_global_ctors_aux
0000000000000000 l    df *ABS*  0000000000000000              symboltable.c
0000000000600870 l     O .got.plt       0000000000000000              _GLOBAL_OFFSET_TABLE_
00000000006006ac l       .ctors 0000000000000000              __init_array_end
00000000006006ac l       .ctors 0000000000000000              __init_array_start
00000000006006d8 l     O .dynamic       0000000000000000              _DYNAMIC
0000000000600898  w      .data  0000000000000000              data_start
00000000006008b4 g     O .bss   0000000000000008              gs
0000000000000000       F *UND*  0000000000000000              printf@@GLIBC_2.2.5
0000000000400510 g     F .text  0000000000000002              __libc_csu_fini
00000000004003e0 g     F .text  0000000000000000              _start
0000000000000000  w      *UND*  0000000000000000              __gmon_start__
0000000000000000  w      *UND*  0000000000000000              _Jv_RegisterClasses
00000000004005e8 g     F .fini  0000000000000000              _fini
0000000000000000       F *UND*  0000000000000000              __libc_start_main@@GLIBC_2.2
00000000006008b0 g     O .bss   0000000000000004              global
00000000004005f8 g     O .rodata        0000000000000004              _IO_stdin_used
0000000000600898 g       .data  0000000000000000              __data_start
0000000000400600 g     O .rodata        0000000000000000              .hidden __dso_handle
00000000006006c8 g     O .dtors 0000000000000000              .hidden __DTOR_END__
0000000000400520 g     F .text  0000000000000089              __libc_csu_init
000000000060089c g       *ABS*  0000000000000000              __bss_start
00000000006008c0 g       *ABS*  0000000000000000              _end

My requirement is gs being C structure, I want to know the data members of gs{a,b}. How can i know structure member details from object files. Thanks for your support

Body:
If you passed -g to gcc when building the program, it should have DWARF debug information compiled in:

$ objdump -t prog | grep debug
0000000000000000 l    d  .debug_aranges 0000000000000000              .debug_aranges
0000000000000000 l    d  .debug_info    0000000000000000              .debug_info
0000000000000000 l    d  .debug_abbrev  0000000000000000              .debug_abbrev
0000000000000000 l    d  .debug_line    0000000000000000              .debug_line
0000000000000000 l    d  .debug_str     0000000000000000              .debug_str

Then you can read it with objdump:

$ objdump --dwarf=info prog
[...]
 <1><65>: Abbrev Number: 5 (DW_TAG_base_type)
    <66>   DW_AT_byte_size   : 4
    <67>   DW_AT_encoding    : 5        (signed)
    <68>   DW_AT_name        : int
[...]
 <1><2f8>: Abbrev Number: 8 (DW_TAG_structure_type)
    <2f9>   DW_AT_name        : (indirect string, offset: 0x22f): global_struct
    <2fd>   DW_AT_byte_size   : 8
    <2fe>   DW_AT_decl_file   : 1
    <2ff>   DW_AT_decl_line   : 3
    <300>   DW_AT_decl_column : 16
    <301>   DW_AT_sibling     : <0x31c>
 <2><305>: Abbrev Number: 17 (DW_TAG_member)
    <306>   DW_AT_name        : a
    <308>   DW_AT_decl_file   : 1
    <309>   DW_AT_decl_line   : 4
    <30a>   DW_AT_decl_column : 9
    <30b>   DW_AT_type        : <0x65>
    <30f>   DW_AT_data_member_location: 0
 <2><310>: Abbrev Number: 17 (DW_TAG_member)
    <311>   DW_AT_name        : c
    <313>   DW_AT_decl_file   : 1
    <314>   DW_AT_decl_line   : 5
    <315>   DW_AT_decl_column : 9
    <316>   DW_AT_type        : <0x65>
    <31a>   DW_AT_data_member_location: 4
 <2><31b>: Abbrev Number: 0
 <1><31c>: Abbrev Number: 2 (DW_TAG_typedef)
    <31d>   DW_AT_name        : (indirect string, offset: 0x22f): global_struct
    <321>   DW_AT_decl_file   : 1
    <322>   DW_AT_decl_line   : 6
    <323>   DW_AT_decl_column : 2
    <324>   DW_AT_type        : <0x2f8>
[...]

Here we can see that global_struct's DIE (Debug Information Entry) has two leaves (two DW_TAG_members, look at <2> prefixes which I believe it level in the tree).  The members are called a and c.  Both of the members reference type 0x65, which is defined above as a signed int.

A good place to learn more about DWARF is this official tutorial: http://www.dwarfstd.org/doc/Debugging%20using%20DWARF-2012.pdf


问:
Install gcc and build-essential offline rhel
I am trying to install GCC in a rhel 7 server

But I'm getting this error.

```<code># sudo rpm -ivh gcc-4.8.5-39.el7.x86_64.rpm
error: Failed dependencies:
        cpp = 4.8.5-39.el7 is needed by gcc-4.8.5-39.el7.x86_64
        glibc-devel >= 2.2.90-12 is needed by gcc-4.8.5-39.el7.x86_64
        libmpc.so.3()(64bit) is needed by gcc-4.8.5-39.el7.x86_64
        libmpfr.so.4()(64bit) is needed by gcc-4.8.5-39.el7.x86_64
</code>```

How to solve this error. Is there a guide to install gcc and do ubuntu's build-essential equivalent in rhel  7 offline

Any suggestion would help me

Thanks in advance

答:
You should install the Red Hat productized version called Developer Toolset (DTS). Instructions are here. This installs the additional version alongside the original (because if you replace the original it can break the OS). Enable the channels per step 1, then check which versions are available to you. DTS is part of your subscription including the developer sub that is mentioned above.

[added] FYI GCC 9 is now available

Body:
I am trying to install GCC in a rhel 7 server

But I'm getting this error.

# sudo rpm -ivh gcc-4.8.5-39.el7.x86_64.rpm
error: Failed dependencies:
        cpp = 4.8.5-39.el7 is needed by gcc-4.8.5-39.el7.x86_64
        glibc-devel >= 2.2.90-12 is needed by gcc-4.8.5-39.el7.x86_64
        libmpc.so.3()(64bit) is needed by gcc-4.8.5-39.el7.x86_64
        libmpfr.so.4()(64bit) is needed by gcc-4.8.5-39.el7.x86_64

How to solve this error. Is there a guide to install gcc and do ubuntu's build-essential equivalent in rhel  7 offline

Any suggestion would help me

Thanks in advance


问:
Transfer regression output to a .cvs or .txt table
I am trying to export the output of my regression model into a .txt or .csv file. I was able to export the main information from summary() the terms (e.g., intercept), p-values etc. However, the exported file does not give me residuals standard information, R2 and F statistics, which appears at the bottom of the output.

Here is the code that I am using
 model = lm(cs~group + sex, data = metadata) #adjusting for sex.

Output

Call: lm(formula = cs ~ group + sex, data = metadata)

Residuals:
      Min      1Q  Median      3Q     Max
  -16.917  -7.733  -2.506   6.934  32.494

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)     (Intercept)        14.051      3.767   3.731 0.000555 * groupHFD           -3.987      4.853  -0.822 0.415880     groupHFD +Exe       1.571      4.853   0.324 0.747817     groupHFD+Exe+Gen    4.874      4.989   0.977 0.334131     groupHFD+Gen       -1.189      4.853  -0.245 0.807610     sexMale             9.633      3.104   3.103 0.003378

  --- Signif. codes:  0 ‘*’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 10.85 on 43 degrees of freedom Multiple
  R-squared:  0.2286,   Adjusted R-squared:  0.139  F-statistic: 2.549 on
  5 and 43 DF,  p-value: 0.04168

#Save the regression output as table in cvs table.
write.table(csregression, file = 'csregression.csv', sep = ",", row.names = F, col.names = T)

The .csv file shows the following

```<code>               Estimate Std. Error t value Pr(>|t|)     (Intercept)        14.051      3.767   3.731 0.000555  groupHFD
</code>```

-3.987      4.853  -0.822 0.415880     groupHFD +Exe       1.571      4.853   0.324 0.747817     groupHFD+Exe+Gen    4.874      4.989   0.977 0.334131     groupHFD+Gen       -1.189      4.853  -0.245 0.807610     sexMale             9.633      3.104   3.103 0.003378

Does someone experience the same issue? How could I export the information missing, the F-statistic and R-squared information?

答: You might want to check out the broom package. You can use it for transferring regression output to csv as shown here</p>

Body:
I am trying to export the output of my regression model into a .txt or .csv file. I was able to export the main information from summary() the terms (e.g., intercept), p-values etc. However, the exported file does not give me residuals standard information, R2 and F statistics, which appears at the bottom of the output.

Here is the code that I am using
 model = lm(cs~group + sex, data = metadata) #adjusting for sex.

Output

Call: lm(formula = cs ~ group + sex, data = metadata)

Residuals:
      Min      1Q  Median      3Q     Max
  -16.917  -7.733  -2.506   6.934  32.494

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)     (Intercept)        14.051      3.767   3.731 0.000555 * groupHFD           -3.987      4.853  -0.822 0.415880     groupHFD +Exe       1.571      4.853   0.324 0.747817     groupHFD+Exe+Gen    4.874      4.989   0.977 0.334131     groupHFD+Gen       -1.189      4.853  -0.245 0.807610     sexMale             9.633      3.104   3.103 0.003378

  --- Signif. codes:  0 ‘*’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 10.85 on 43 degrees of freedom Multiple
  R-squared:  0.2286,   Adjusted R-squared:  0.139  F-statistic: 2.549 on
  5 and 43 DF,  p-value: 0.04168

#Save the regression output as table in cvs table.
write.table(csregression, file = 'csregression.csv', sep = ",", row.names = F, col.names = T)

The .csv file shows the following

               Estimate Std. Error t value Pr(>|t|)     (Intercept)        14.051      3.767   3.731 0.000555  groupHFD

-3.987      4.853  -0.822 0.415880     groupHFD +Exe       1.571      4.853   0.324 0.747817     groupHFD+Exe+Gen    4.874      4.989   0.977 0.334131     groupHFD+Gen       -1.189      4.853  -0.245 0.807610     sexMale             9.633      3.104   3.103 0.003378

Does someone experience the same issue? How could I export the information missing, the F-statistic and R-squared information?


问:
pySpark iterating repetitive variables
I have a code that currently works, however I'm looking to make it more efficient and avoid hard coding:

1) avoid hard coding: for NotDefined_filterDomainLookup  will like to reference the default_reference df for the corresponding Code and Name when Id = 4. Instead of hard coding the Code and Name value.

Question 1

list of columns name and corresponding new column names

```<code>test_matchedAttributeName_List =dict(matchedDomains.agg(collect_set(array('DomainName', 'TargetAttributeForName')).alias('m')).first().m)

Output: {'LeaseType': 'ConformedLeaseTypeName', 'LeaseRecoveryType': 'ConformedLeaseRecoveryTypeName', 'LeaseStatus': 'ConformedLeaseStatusName'}
</code>```

working code, except looking to avoid hard coding. Specifically, I will like to reference the default_reference df for the corresponding Code and Name when Id = 4

```<code>cond = col('PrimaryLookupAttributeName').isNull() & col('SecondaryLookupAttributeName').isNull()

NotDefined_filterDomainLookup = filterDomainLookup \
    .withColumn('OutputItemIdByAttribute', when(cond, lit('4')).otherwise(col('OutputItemIdByAttribute'))) \
    .withColumn('OutputItemCodeByAttribute', when(cond, lit('N/D')).otherwise(col('OutputItemCodeByAttribute'))) \
    .withColumn('OutputItemNameByAttribute', when(cond, lit('Not Defined')).otherwise(col('OutputItemNameByAttribute')))
</code>```

------------+-----------------------+-------------------------+----------------

答:
For the Question-2, based on your code, I'd advise some adjustments as below:

Set up item_keys including Id, Name and Code and merge the same logic using list comprehensions

Use struct instead of array to implement the above logic

No need to create Python dictionary for NotDefned_Attribute_List, list of tuples are enough and better

See below steps:

(1) Set up two aggregate functions to calculate item_map used for testing_mappings and NotDefined_Attribute_List. check named_struct and struct (two methods for the same task for your exercises)

```<code>from itertools import chain
from pyspark.sql.functions import expr, collect_set, struct, col

item_keys = ['Id', 'Name', 'Code']

# use SQL expression
m1_by_sql_expr = expr("""
  collect_set(
    named_struct(
      'attr_name', PrimaryLookupAttributeName,
      'attr_value', PrimaryLookupAttributeValue,
      'Id', OutputItemIdByValue,
      'Name', OutputItemNameByValue,
      'Code', OutputItemCodeByValue
    )
  ) as item_map
""")

# use PySpark API functions
m2_by_func = collect_set(
    struct(
      col('DomainName').alias('domain'),
      col('TargetAttributeForId').alias('Id'),
      col('TargetAttributeForName').alias('Name'),
      col('TargetAttributeForCode').alias('Code')
    )
  ).alias('item_map')
</code>```

(2) Set up ItemKey(Id, Code or Name) + PrimaryLookupAttributeName + PrimaryLookupAttributeValue mapping to ItemValue

```<code>  m1 = NotDefined_filterDomainLookup.agg(m1_by_sql_expr).first().item_map

  """create a list of tuples of (map_key, map_value) to create MapType column:
     | map_key = concat_ws('\0', item_key, attr_name, attr_value)
     | map_value = item_value
  """
  testingId = [('\0'.join([k, row.attr_name, row.attr_value]), row[k]) for row in m1 for k in item_keys if row[k]]
  #[('Id\x00LeaseRecoveryType\x00Gross w/base year', '18'),
  # ('Name\x00LeaseRecoveryType\x00Gross w/base year', 'Modified Gross'),
  # ('Id\x00LeaseStatus\x00Abandoned', '10'),
  # ('Name\x00LeaseStatus\x00Abandoned', 'Active'),
  # ('Id\x00LeaseStatus\x00Draft', '10'),
  # ('Name\x00LeaseStatus\x00Draft', 'Pending'),
  # ('Id\x00LeaseStatus\x00Archive', '11'),
  # ('Name\x00LeaseStatus\x00Archive', 'Expired'),
  # ('Id\x00LeaseStatus\x00Terminated', '10'),
  # ('Name\x00LeaseStatus\x00Terminated', 'Terminated'),
  # ('Id\x00LeaseRecoveryType\x00Gross', '11'),
  # ('Name\x00LeaseRecoveryType\x00Gross', 'Gross'),
  # ('Id\x00LeaseRecoveryType\x00Gross-modified', '15'),
  # ('Name\x00LeaseRecoveryType\x00Gross-modified', 'Modified Gross')]

  # this could be a problem for too many entries.
  testing_mappings = create_map([lit(i) for i in chain.from_iterable(testingId)])
</code>```

(3) Create NotDefined_AttributeCode_List (same logic as in (2), use PySpark API functions for m2)

```<code>  m2 = matchedDomains.agg(m2_by_func).first().item_map

  NotDefned_Attribute_List = [(k, row.domain, row[k]) for row in m2 for k in item_keys if row[k]]
</code>```

(4) Get a list of additional columns based on NotDefined_Attribute_List:

```<code>  additional_cols = [
    testing_mappings[concat_ws('\0', lit(k), lit(c), col(c))].alias(c_name)
      for k,c,c_name in NotDefined_Attribute_List
  ]
</code>```

(5) select the additional columns

```<code>if count_ND > 0:

  # move code above in (2), (3) and (4) here

  # set up testing_NotDefined
  testing_NotDefined = datasetMatchedPortfolio.select("*", *additional_cols)

else:
  print("no Not Defines exist")
</code>```

Title: pySpark iterating repetitive variables

Body:
I have a code that currently works, however I'm looking to make it more efficient and avoid hard coding:

1) avoid hard coding: for NotDefined_filterDomainLookup  will like to reference the default_reference df for the corresponding Code and Name when Id = 4. Instead of hard coding the Code and Name value.

Question 1

list of columns name and corresponding new column names

test_matchedAttributeName_List =dict(matchedDomains.agg(collect_set(array('DomainName', 'TargetAttributeForName')).alias('m')).first().m)

Output: {'LeaseType': 'ConformedLeaseTypeName', 'LeaseRecoveryType': 'ConformedLeaseRecoveryTypeName', 'LeaseStatus': 'ConformedLeaseStatusName'}

working code, except looking to avoid hard coding. Specifically, I will like to reference the default_reference df for the corresponding Code and Name when Id = 4

cond = col('PrimaryLookupAttributeName').isNull() & col('SecondaryLookupAttributeName').isNull()

NotDefined_filterDomainLookup = filterDomainLookup \
    .withColumn('OutputItemIdByAttribute', when(cond, lit('4')).otherwise(col('OutputItemIdByAttribute'))) \
    .withColumn('OutputItemCodeByAttribute', when(cond, lit('N/D')).otherwise(col('OutputItemCodeByAttribute'))) \
    .withColumn('OutputItemNameByAttribute', when(cond, lit('Not Defined')).otherwise(col('OutputItemNameByAttribute')))

------------+-----------------------+-------------------------+----------------

Body:
For the Question-2, based on your code, I'd advise some adjustments as below:

Set up item_keys including Id, Name and Code and merge the same logic using list comprehensions

Use struct instead of array to implement the above logic

No need to create Python dictionary for NotDefned_Attribute_List, list of tuples are enough and better

See below steps:

(1) Set up two aggregate functions to calculate item_map used for testing_mappings and NotDefined_Attribute_List. check named_struct and struct (two methods for the same task for your exercises)

from itertools import chain
from pyspark.sql.functions import expr, collect_set, struct, col

item_keys = ['Id', 'Name', 'Code']

# use SQL expression
m1_by_sql_expr = expr("""
  collect_set(
    named_struct(
      'attr_name', PrimaryLookupAttributeName,
      'attr_value', PrimaryLookupAttributeValue,
      'Id', OutputItemIdByValue,
      'Name', OutputItemNameByValue,
      'Code', OutputItemCodeByValue
    )
  ) as item_map
""")

# use PySpark API functions
m2_by_func = collect_set(
    struct(
      col('DomainName').alias('domain'),
      col('TargetAttributeForId').alias('Id'),
      col('TargetAttributeForName').alias('Name'),
      col('TargetAttributeForCode').alias('Code')
    )
  ).alias('item_map')

(2) Set up ItemKey(Id, Code or Name) + PrimaryLookupAttributeName + PrimaryLookupAttributeValue mapping to ItemValue

  m1 = NotDefined_filterDomainLookup.agg(m1_by_sql_expr).first().item_map

  """create a list of tuples of (map_key, map_value) to create MapType column:
     | map_key = concat_ws('\0', item_key, attr_name, attr_value)
     | map_value = item_value
  """
  testingId = [('\0'.join([k, row.attr_name, row.attr_value]), row[k]) for row in m1 for k in item_keys if row[k]]
  #[('Id\x00LeaseRecoveryType\x00Gross w/base year', '18'),
  # ('Name\x00LeaseRecoveryType\x00Gross w/base year', 'Modified Gross'),
  # ('Id\x00LeaseStatus\x00Abandoned', '10'),
  # ('Name\x00LeaseStatus\x00Abandoned', 'Active'),
  # ('Id\x00LeaseStatus\x00Draft', '10'),
  # ('Name\x00LeaseStatus\x00Draft', 'Pending'),
  # ('Id\x00LeaseStatus\x00Archive', '11'),
  # ('Name\x00LeaseStatus\x00Archive', 'Expired'),
  # ('Id\x00LeaseStatus\x00Terminated', '10'),
  # ('Name\x00LeaseStatus\x00Terminated', 'Terminated'),
  # ('Id\x00LeaseRecoveryType\x00Gross', '11'),
  # ('Name\x00LeaseRecoveryType\x00Gross', 'Gross'),
  # ('Id\x00LeaseRecoveryType\x00Gross-modified', '15'),
  # ('Name\x00LeaseRecoveryType\x00Gross-modified', 'Modified Gross')]

  # this could be a problem for too many entries.
  testing_mappings = create_map([lit(i) for i in chain.from_iterable(testingId)])

(3) Create NotDefined_AttributeCode_List (same logic as in (2), use PySpark API functions for m2)

  m2 = matchedDomains.agg(m2_by_func).first().item_map

  NotDefned_Attribute_List = [(k, row.domain, row[k]) for row in m2 for k in item_keys if row[k]]

(4) Get a list of additional columns based on NotDefined_Attribute_List:

  additional_cols = [
    testing_mappings[concat_ws('\0', lit(k), lit(c), col(c))].alias(c_name)
      for k,c,c_name in NotDefined_Attribute_List
  ]

(5) select the additional columns

if count_ND > 0:

  # move code above in (2), (3) and (4) here

  # set up testing_NotDefined
  testing_NotDefined = datasetMatchedPortfolio.select("*", *additional_cols)

else:
  print("no Not Defines exist")


问:
Error consuming an Endpoint api-football.com (CORS related)
I'm trying to consume this endpoint at the api-football.com

Here is their documentation: https://www.api-football.com/documentation-beta#section/Authentication

The error is: Access to XMLHttpRequest at 'https://v3.football.api-sports.io/teams?id=40' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field x-rapidapi-host is not allowed by Access-Control-Allow-Headers in preflight response.

Here is my code:

```<code>    httpOptions.headers = new HttpHeaders({
     // 'Access-Control-Allow-Origin': '*',
     // 'Access-Control-Allow-Methods': 'GET',
     // 'Accept': '*/*',
     'Content-Type': 'application/json',
     'x-rapidapi-host': 'v3.api-football.com',
     'x-rapidapi-key': this._publicKey,
    });

    const url = 'https://v3.football.api-sports.io/teams?id=40';

    return this.http.get<any>(url, httpOptions)
     .pipe(
       catchError(this.handleError('getLiverpool', []))
    );
</code>```

I understand what CORS is, but not how to fix it in this case? I am using Angular 9.

答:
the problem is the server, it needs to accept your request.

If once deployed they are going to be in the same server, you can disable cors in your browser, if not, you have to update the server

Body:
I'm trying to consume this endpoint at the api-football.com

Here is their documentation: https://www.api-football.com/documentation-beta#section/Authentication

The error is: Access to XMLHttpRequest at 'https://v3.football.api-sports.io/teams?id=40' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field x-rapidapi-host is not allowed by Access-Control-Allow-Headers in preflight response.

Here is my code:

    httpOptions.headers = new HttpHeaders({
     // 'Access-Control-Allow-Origin': '*',
     // 'Access-Control-Allow-Methods': 'GET',
     // 'Accept': '*/*',
     'Content-Type': 'application/json',
     'x-rapidapi-host': 'v3.api-football.com',
     'x-rapidapi-key': this._publicKey,
    });

    const url = 'https://v3.football.api-sports.io/teams?id=40';

    return this.http.get<any>(url, httpOptions)
     .pipe(
       catchError(this.handleError('getLiverpool', []))
    );

I understand what CORS is, but not how to fix it in this case? I am using Angular 9.