问:
Google Sheets: How to automatically insert a word into a cell on a new row detected?
I have searched high and low but I have been unable to find an answer (I am sure I am not explaining it right)

I have a Google Sheet that have multiple sheets (tabs) labeled TabA, TabB and TabC.

On this Google Sheet, I submit a slash command on Slack, which then auto-fills a row on one of the tabs using apps script.

What I am trying to do is simply insert a word called TabA into a specific cell each time a new row has been detected. And insert a word called TabB when a new row has been made on TabB sheet etc.

I am sure I just am typing my questions wrong which is why I am unable to find an answer.

I am not actually sure which part of the code posts to the sheet, I think it is this?

```<code>  if(sheetName) {
    sheetName = sheetName.charAt(0).toUpperCase() + sheetName.slice(1)
  } else {
    sheetName = "Current"
  }

  // Find sheet
  var sheetFlag = false;
  for (var r = 1; r < settings.length; r++) {
    if (settings[r][1] == channelID) {
      var sheetID = settings[r][2];
      var targetChannelID = settings[r][4];
      var title = settings[r][0];
      sheetFlag = true;
      break;
    }
  }

  if (sheetFlag) {
    var sheet = SpreadsheetApp.openById(sheetID).getSheetByName(sheetName);
    if(!sheet) {
      sheet = SpreadsheetApp.openById(sheetID).insertSheet(sheetName);
    }

    var lastRow = sheet.getLastRow();

    var slackDetails = ["", "", text1, "","","","","",realName, new Date(),title,text2];

    // paste the slack details to the sheet
    sheet.getRange(lastRow + 1,1,1,slackDetails.length).setValues([slackDetails]);```
Thank you in advance
```

答:
If I understood you correctly, you want to:

Keep track of new rows that are added to each sheet in your spreadsheet (TabA, TabB, TabC).

Write the name of the sheet in successive rows of column D of each sheet every time news rows are detected.

As you were told in the comments, Apps Script has no triggers to track changes made to the spreadsheet by a script. For example, onEdit trigger "runs automatically when a user changes the value of any cell in a spreadsheet".

Workaround (time-based trigger and script properties):

A possible workaround to this limitation is using a time-based trigger that will fire a function periodically. You can create this trigger manually, or programmatically, by running this function once:

function createTrigger() {
  ScriptApp.newTrigger("trackRows")
  .timeBased()
  .everyMinutes(1)
  .create();
}
```

<p>This will fire the function <code>trackRows</code> every minute. This function's purpose is to track changes to each sheet rows since last time it was fired (in this example, 1 minute ago) and write the sheet name to a certain cell if the sheet has more rows with content than during last execution.</p>

<p>To accomplish this, you can use the Properties Service, which lets you store key-value pairs and use them in later executions.</p>

<p>The function <code>trackRows</code> could be something along the following lines:</p>

<pre class="lang-js prettyprint-override"><code>function trackRows() {
  var props = PropertiesService.getScriptProperties();
  var ss = SpreadsheetApp.openById("your-spreadsheet-id"); // Please change accordingly
  var sheets = ss.getSheets();
  sheets.forEach(function(sheet) {
    var sheetName = sheet.getName();
    var currentRows = sheet.getLastRow();
    var oldRows = props.getProperty(sheetName);
    if (currentRows > oldRows) {
      var firstRow = 2;
      var column = 4;
      var numRows = sheet.getLastRow() - firstRow + 1;
      var rowIndex = sheet.getRange(firstRow, column, numRows).getValues().filter(function(value) {
        return value[0] !== "";
      }).length;
      var cell = sheet.getRange(rowIndex + firstRow, column);
      cell.setValue(sheetName);
    }
    props.setProperty(sheetName, currentRows);
  });
}
</code>```

This function does the following:

Retrieve the script properties that were stored in previous executions.

Get all the sheets in the spreadsheet.

Check the last row with content in each sheet (via Sheet.getLastRow()), and compare the value with the one previously stored in script properties.

If the current last row is higher than the one stored in properties, write the sheet name in the first empty row of column D of the corresponding (starting at D2).

Store the current last row in script properties.

Notes:

The script is adding the sheet name to the first empty row of column D once, if it detects that new rows were added. It's not taking into account how many rows were added since last execution, it only considers if rows were added. This could easily be changed though, if that's what you wanted.

If you want to start from fresh, it would be useful to delete all previously stored properties. To do that, you could run this function once:

function deleteProps() {
  var props = PropertiesService.getScriptProperties();
  props.deleteAllProperties();
}
```

Reference:

Class ClockTriggerBuilder

Class PropertiesService

Sheet.getLastRow()

Body:
I have searched high and low but I have been unable to find an answer (I am sure I am not explaining it right)

I have a Google Sheet that have multiple sheets (tabs) labeled TabA, TabB and TabC.

On this Google Sheet, I submit a slash command on Slack, which then auto-fills a row on one of the tabs using apps script.

What I am trying to do is simply insert a word called TabA into a specific cell each time a new row has been detected. And insert a word called TabB when a new row has been made on TabB sheet etc.

I am sure I just am typing my questions wrong which is why I am unable to find an answer.

I am not actually sure which part of the code posts to the sheet, I think it is this?

  if(sheetName) {
    sheetName = sheetName.charAt(0).toUpperCase() + sheetName.slice(1)
  } else {
    sheetName = "Current"
  }

  // Find sheet
  var sheetFlag = false;
  for (var r = 1; r < settings.length; r++) {
    if (settings[r][1] == channelID) {
      var sheetID = settings[r][2];
      var targetChannelID = settings[r][4];
      var title = settings[r][0];
      sheetFlag = true;
      break;
    }
  }

  if (sheetFlag) {
    var sheet = SpreadsheetApp.openById(sheetID).getSheetByName(sheetName);
    if(!sheet) {
      sheet = SpreadsheetApp.openById(sheetID).insertSheet(sheetName);
    }

    var lastRow = sheet.getLastRow();

    var slackDetails = ["", "", text1, "","","","","",realName, new Date(),title,text2];

    // paste the slack details to the sheet
    sheet.getRange(lastRow + 1,1,1,slackDetails.length).setValues([slackDetails]);```
Thank you in advance

Body:
If I understood you correctly, you want to:

Keep track of new rows that are added to each sheet in your spreadsheet (TabA, TabB, TabC).

Write the name of the sheet in successive rows of column D of each sheet every time news rows are detected.

As you were told in the comments, Apps Script has no triggers to track changes made to the spreadsheet by a script. For example, onEdit trigger "runs automatically when a user changes the value of any cell in a spreadsheet".

Workaround (time-based trigger and script properties):

A possible workaround to this limitation is using a time-based trigger that will fire a function periodically. You can create this trigger manually, or programmatically, by running this function once:

function createTrigger() {
  ScriptApp.newTrigger("trackRows")
  .timeBased()
  .everyMinutes(1)
  .create();
}

This will fire the function trackRows every minute. This function's purpose is to track changes to each sheet rows since last time it was fired (in this example, 1 minute ago) and write the sheet name to a certain cell if the sheet has more rows with content than during last execution.

To accomplish this, you can use the Properties Service, which lets you store key-value pairs and use them in later executions.

The function trackRows could be something along the following lines:

function trackRows() {
  var props = PropertiesService.getScriptProperties();
  var ss = SpreadsheetApp.openById("your-spreadsheet-id"); // Please change accordingly
  var sheets = ss.getSheets();
  sheets.forEach(function(sheet) {
    var sheetName = sheet.getName();
    var currentRows = sheet.getLastRow();
    var oldRows = props.getProperty(sheetName);
    if (currentRows > oldRows) {
      var firstRow = 2;
      var column = 4;
      var numRows = sheet.getLastRow() - firstRow + 1;
      var rowIndex = sheet.getRange(firstRow, column, numRows).getValues().filter(function(value) {
        return value[0] !== "";
      }).length;
      var cell = sheet.getRange(rowIndex + firstRow, column);
      cell.setValue(sheetName);
    }
    props.setProperty(sheetName, currentRows);
  });
}

This function does the following:

Retrieve the script properties that were stored in previous executions.

Get all the sheets in the spreadsheet.

Check the last row with content in each sheet (via Sheet.getLastRow()), and compare the value with the one previously stored in script properties.

If the current last row is higher than the one stored in properties, write the sheet name in the first empty row of column D of the corresponding (starting at D2).

Store the current last row in script properties.

Notes:

The script is adding the sheet name to the first empty row of column D once, if it detects that new rows were added. It's not taking into account how many rows were added since last execution, it only considers if rows were added. This could easily be changed though, if that's what you wanted.

If you want to start from fresh, it would be useful to delete all previously stored properties. To do that, you could run this function once:

function deleteProps() {
  var props = PropertiesService.getScriptProperties();
  props.deleteAllProperties();
}

Reference:

Class ClockTriggerBuilder

Class PropertiesService

Sheet.getLastRow()


来源: stackexchange

问:
HTTP request with axios in NodeJS not able to change header format
I have an API that accepts headers as list of strings formatted as:

```<code>headers: [
    "Content-Type: application/json"
]
</code>```

Unfortunately I'm not finding a way to send the headers this way in axios as they get formatted into a map structure like so:

```<code>headers: {
     "Content-Type": "application/json"
}
</code>```

The map structure is obviously the better structure, but I have to support the limitations of existing systems. Is there any way to change this formatting in axios?

答:
Can you try:

const headersList = {
    "Content-Type: application/json"
};

axios.post(url, data, {
    headers: headersList
})
```

ContentLicense: CC BY-SA 4.0

Body:
I have an API that accepts headers as list of strings formatted as:

headers: [
    "Content-Type: application/json"
]

Unfortunately I'm not finding a way to send the headers this way in axios as they get formatted into a map structure like so:

headers: {
     "Content-Type": "application/json"
}

The map structure is obviously the better structure, but I have to support the limitations of existing systems. Is there any way to change this formatting in axios?


问:
Why isn't flatlist not able to map through and display the data?
I am using Zomato API to get the list of restaurants, data is in the form of the array which has object restaurants in which there are different restaurant objects and then their name and other details.

It's my first time using a flat List and I am not able to display this data.

Goal: Use the search bar to display the list of restaurants in the city using flatlist.

```<code>import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { SearchBar } from 'react-native-elements';
import { FlatList } from 'react-native-gesture-handler';

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = { search: '', data: [] };
    }

    componentDidMount() {
        fetch('https://developers.zomato.com/api/v2.1/search', {
            method: 'GET',
            headers: {
                'user-key': '999999999999999999999999999'
            },
            params: JSON.stringify({
                entity_type: 'city',
                q: {this.state.search}
            }),
        }).then((response) => response.json())
            .then((responseJson) => { return this.setState({ data: responseJson.restaurants }) })
            .catch((error) => { console.warn(error) }
            );
    }

    render() {
        let data = this.state.data;
        let name = data.map(p => p.restaurant.name)
        console.warn("Check Data", name)
        return (
            <View>
                <SearchBar
                    round
                    searchIcon={{ size: 24 }}
                    placeholder='Search'
                    onChangeText={search => { this.setState({ search }) }}
                    value={this.state.search}
                />
//Using this method to display the data if any

                {name.length != 0 ?
                    <FlatList
                        data={name}
                        keyExtractor={(x, i) => x + i}
                        renderItem={({ name }) => <Text>{name}-DATA</Text>}
                    />
                    : <View style={{height:"100%", width:"100%", alignItems:"center",
                                      justifyContent:"center"}}>
                        <Text>No data found</Text>
                    </View>
                }

            </View>
        );
    }
}

export default Main;
</code>```

Maybe the way I declared state is wrong, or maybe the way I'm storing the data in the state is wrong.
I got the names of the restaurant in the console.warn successfully.

答:
Check the url link properly.

https://developers.zomato.com/api/v2.1/search/999999999999999999999999999

Just check it on web browser it is showing message : The requested url was not found

It means we are not getting any data from this URL.
That why we are not able to map any data.

Body:
I am using Zomato API to get the list of restaurants, data is in the form of the array which has object restaurants in which there are different restaurant objects and then their name and other details.

It's my first time using a flat List and I am not able to display this data.

Goal: Use the search bar to display the list of restaurants in the city using flatlist.

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { SearchBar } from 'react-native-elements';
import { FlatList } from 'react-native-gesture-handler';

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = { search: '', data: [] };
    }

    componentDidMount() {
        fetch('https://developers.zomato.com/api/v2.1/search', {
            method: 'GET',
            headers: {
                'user-key': '999999999999999999999999999'
            },
            params: JSON.stringify({
                entity_type: 'city',
                q: {this.state.search}
            }),
        }).then((response) => response.json())
            .then((responseJson) => { return this.setState({ data: responseJson.restaurants }) })
            .catch((error) => { console.warn(error) }
            );
    }

    render() {
        let data = this.state.data;
        let name = data.map(p => p.restaurant.name)
        console.warn("Check Data", name)
        return (
            <View>
                <SearchBar
                    round
                    searchIcon={{ size: 24 }}
                    placeholder='Search'
                    onChangeText={search => { this.setState({ search }) }}
                    value={this.state.search}
                />
//Using this method to display the data if any

                {name.length != 0 ?
                    <FlatList
                        data={name}
                        keyExtractor={(x, i) => x + i}
                        renderItem={({ name }) => <Text>{name}-DATA</Text>}
                    />
                    : <View style={{height:"100%", width:"100%", alignItems:"center",
                                      justifyContent:"center"}}>
                        <Text>No data found</Text>
                    </View>
                }

            </View>
        );
    }
}

export default Main;

Maybe the way I declared state is wrong, or maybe the way I'm storing the data in the state is wrong.
I got the names of the restaurant in the console.warn successfully.


问:
How to construct an empty data.table with the colum names of an existing data.table?
I would like to create an empty data.table in R with colum names from another existing data.table.
Somehow I could not find a solution for that.

I would like to do something like that:

```<code>require(data.table)

dt1 <- data.table(fn = c("A","B","C"), x = c(1,2,3), y = c(2,3,4), a = 1, b = 2, c = 3)
dt2 <- data.table(names=colnames(dt1)) # Gives 6 rows instead of 6 cols
</code>```

How can this be achieved?

Thanks!

答:
One option could be:</p>

```<code>dt2 <- setnames(data.table(matrix(nrow = 0, ncol = length(dt1))), names(dt1))

Empty data.table (0 rows and 6 cols): fn,x,y,a,b,c
</code>```

Body:
I would like to create an empty data.table in R with colum names from another existing data.table.
Somehow I could not find a solution for that.

I would like to do something like that:

require(data.table)

dt1 <- data.table(fn = c("A","B","C"), x = c(1,2,3), y = c(2,3,4), a = 1, b = 2, c = 3)
dt2 <- data.table(names=colnames(dt1)) # Gives 6 rows instead of 6 cols

How can this be achieved?

Thanks!

Body:
One option could be:

dt2 <- setnames(data.table(matrix(nrow = 0, ncol = length(dt1))), names(dt1))

Empty data.table (0 rows and 6 cols): fn,x,y,a,b,c


问:
GCP flush redis if memory above 90%
Is there a way to flush my GCP Redis when a trigger is triggered?

In my specific case, I'm using the Google StackDriver metrics to monitor and get notified. I want that when my Redis memory is above 90% it will automatically flush.
Is there a way to perform this?

答:
Scaling a Basic Tier instance flushes the cache so my suggestion is to configure the instance with a smaller cap (& appropriate eviction policy) then have it scale as needed.

gcloud redis instances update instance-id --update-redis-config maxmemory-policy=policy

Alternatively, you can setup a web service to make the appropriate CLI command, but this requires a little more effort.

Title: GCP flush redis if memory above 90%


问:
PHP and ESB (with Mule) (ESB: Enterprise Service Bus)
Where, when and why did you use ESB in a PHP-project?

Where, when and why do you think that it would make sense to use ESB in a PHP-project?

Does ESB (and ESB-facilitators like Mule) do provide any capability PHP and native LAMP-technologies are lacking?

Edit

My motivation for this question is stemming from my assumption that you actually never really need Mule. Mule will facilitate communication with external services which you could handle without mule. At the end of the day also Mule will create costs and overhead. So my question is steering at having somebody tell me about scenarios where you really benefit of ESB and tools like Mule or to second my guess with solid knowledge.

Edit 2

regarding Houcem's reply to my comment to his post ... what would be a native LAMP-answer to ESB/Mule?

Edit 3

Seems like Tuxedo might be a more PHP-native alternative to Mule/ESB. Somebody got experience using this tool?

答:
ESB could be used in different ways :

Providing asynchronous processing : Example : If you have a web site that does a lot of emailing .. and sending an email takes a lot of time which may block the execution of your page : you may use an ESB to send the email data to Mule and route it to an Email outbound channel, this way you can say that you have implemented a mail message queue. Another form of asynchronous processing : using mule to execute php scripts (using command line) in a non blocking way.

Integration with java applications : You can send Messages to mule using php and implement some java business using mule API in java, php messages will be received by your java business components. This is used in big web sites which does a lot of complex  processing and need flexible and powerful language like java.

What you need to know : ESB should be used like a Bus which means collecting data from heterogenous environments in a standard form (Mule messages) .. do business logic and then output data (after routing) to different environment

There is no native php integration with Mule in PHP world. To do it you should use web services (SOAP)

ContentLicense: CC BY-SA 3.0


问:
Validation allow only number and characters in edit text in android
In my application I have to validate the EditText. It should only allow character, digits, underscores, and hyphens.

Here is my code:

```<code>edittext.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {
        // validation codes here

        location_name=s.toString();
        Toast.makeText(getApplicationContext(),location_name, Toast.LENGTH_SHORT).show();

        if (location_name.matches(".*[^a-z^0-9].*")) {
            location_name = location_name.replaceAll("[^a-z^0-9]", "");
            s.append(location_name);
            s.clear();
            Toast.makeText(getApplicationContext(),"Only lowercase letters and numbers are allowed!",Toast.LENGTH_SHORT).show();
        }
    }

});

location.add(location_name);
</code>```

When I enter input into EditText, the application is force closed.

答:
```<code>InputFilter filter = new InputFilter() {
    public CharSequence filter(CharSequence source, int start,
        int end, Spanned dest, int dstart, int dend) {

        for (int i = start; i < end; i++) {
            if (!Character.toString(source.charAt(i)).matches("[a-zA-Z0-9-_]+")) {
                return "";
                edittext.setError("Only letters, digits, _ and - allowed");
            }
        }
        return null;
    }
};
edittext.setFilters(new InputFilter[] { filter });
</code>```

Body:
In my application I have to validate the EditText. It should only allow character, digits, underscores, and hyphens.

Here is my code:

edittext.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {
        // validation codes here

        location_name=s.toString();
        Toast.makeText(getApplicationContext(),location_name, Toast.LENGTH_SHORT).show();

        if (location_name.matches(".*[^a-z^0-9].*")) {
            location_name = location_name.replaceAll("[^a-z^0-9]", "");
            s.append(location_name);
            s.clear();
            Toast.makeText(getApplicationContext(),"Only lowercase letters and numbers are allowed!",Toast.LENGTH_SHORT).show();
        }
    }

});

location.add(location_name);

When I enter input into EditText, the application is force closed.


问:
Calculate date time duration with condition
I want to calculate DateTime duration with condition : IF "STATUSIN" > 08:00:00 then "LATECOME" = "STATUSIN" - 08.00.00
and I've been trying this code but it's doesn't work.

```<code>DataTable dtDaily = new DataTable();
string time1 = "08:00:00";
var result = Convert.ToDateTime(time1);
string test = result.ToString("hh:mm:ss");

foreach (DataRow pRow in dtDaily.Rows)
{
   DateTime.ParseExact(pRow["STATUSIN"].ToString(), "hh:mm:ss", CultureInfo.InvariantCulture);
   if (pRow["STATUSIN"] > time1)
   {
      pRow["LATECOME"] = pRow["STATUSIN"] - time1.ToString();
   }
}
</code>```

This is my code to display the value in table:

```<code><asp:Repeater ID="rptrSUMMARYDATA" runat="server">
    <HeaderTemplate>
        <table class="table">
            <thead>
                <tr>
                    <th>IN</th>
                    <th>LATECOME</th>
                </tr>
            </thead>
            <tbody>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td><%# Eval("STATUSIN") %></td>
            <td><%# Eval("LATECOME") %></td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
            </tbody>
        </table>
    </FooterTemplate>
</asp:Repeater>
</code>```

答:
The reason why your code is not working is due to the comparison of string data. You can check if the strings are greater than each other but not how you are thinking.

If you want to compare the two dates, you have to convert the strings to DateTime first, then check which is earlier or later than the other one.

```<code>DataTable dtDaily = new DataTable();

// If you want to compare the Time, use TimeSpan
TimeSpan time1 = new TimeSpan(8, 0, 0);

foreach (DataRow pRow in dtDaily.Rows)
{
   if (pRow.Field<DateTime>("STATUSIN").TimeOfDay > time1)
   {
      // This will ONLY be the time portion.. not the full datetime. Notice the
      // parenthesis around the the statement on the right. You want to convert the resulting
      // Time (after subtraction) to string.
      pRow["LATECOME"] = (pRow.Field<DateTime>("STATUSIN").TimeOfDay  - time1).ToString();
   }
}
</code>```

pRow.Field<DateTime>("field) takes the string representation of the data and converts it to DateTime. This is similar to DateTime.Parse(pRow["field"]) but takes away the step of doing the conversions.

See Documentation on TimeSpan

public TimeSpan (int hours, int minutes, int seconds);

Body:
I want to calculate DateTime duration with condition : IF "STATUSIN" > 08:00:00 then "LATECOME" = "STATUSIN" - 08.00.00
and I've been trying this code but it's doesn't work.

DataTable dtDaily = new DataTable();
string time1 = "08:00:00";
var result = Convert.ToDateTime(time1);
string test = result.ToString("hh:mm:ss");

foreach (DataRow pRow in dtDaily.Rows)
{
   DateTime.ParseExact(pRow["STATUSIN"].ToString(), "hh:mm:ss", CultureInfo.InvariantCulture);
   if (pRow["STATUSIN"] > time1)
   {
      pRow["LATECOME"] = pRow["STATUSIN"] - time1.ToString();
   }
}

This is my code to display the value in table:

<asp:Repeater ID="rptrSUMMARYDATA" runat="server">
    <HeaderTemplate>

                    IN
                    LATECOME

    </HeaderTemplate>
    <ItemTemplate>

            <%# Eval("STATUSIN") %>
            <%# Eval("LATECOME") %>

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

Body:
The reason why your code is not working is due to the comparison of string data. You can check if the strings are greater than each other but not how you are thinking.

If you want to compare the two dates, you have to convert the strings to DateTime first, then check which is earlier or later than the other one.

DataTable dtDaily = new DataTable();

// If you want to compare the Time, use TimeSpan
TimeSpan time1 = new TimeSpan(8, 0, 0);

foreach (DataRow pRow in dtDaily.Rows)
{
   if (pRow.Field<DateTime>("STATUSIN").TimeOfDay > time1)
   {
      // This will ONLY be the time portion.. not the full datetime. Notice the
      // parenthesis around the the statement on the right. You want to convert the resulting
      // Time (after subtraction) to string.
      pRow["LATECOME"] = (pRow.Field<DateTime>("STATUSIN").TimeOfDay  - time1).ToString();
   }
}

pRow.Field<DateTime>("field) takes the string representation of the data and converts it to DateTime. This is similar to DateTime.Parse(pRow["field"]) but takes away the step of doing the conversions.

See Documentation on TimeSpan

public TimeSpan (int hours, int minutes, int seconds);


问:
VBA; run macro (overwrite default shortcut) only in workbook that contains it
I am overwriting the paste shortcut (ctrl-v) with a macro to only paste values.
However, I only want this to happen in the actual workbook the macro is in.

This is my code:

```<code>Sub paste_values_only()
If Not ActiveWorkbook Is ThisWorkbook Then Exit Sub
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
End Sub

</code>```

It seems to work, except that when I now ctr-v in another workbook, it just won't paste at all.. I want the ctrl-v to work like a normal paste action in another workbook.

To make things worse.. There's multiple workbooks that will have this paste-overwrite macro.

If there's an easier way to limit pasting in a certain workbook to values only, I'd be happy to hear about it too! I just want to prevent my colleagues pasting formatting/conditional rules/formulas/etc. into this workbook.

答:
After some more elbow grease, I got a solution. Not very elegant, but it works:

Since all files that need to have this paste-protection have 'storage' in the name, I was able to limit the paste-limitation to these workbooks. Using Selection.PasteSpecial without features for the else clause I worked around the problem..

```<code>
Sub paste_values_only()

Dim wbname As String

wbname = ActiveWorkbook.Name

If wbname Like "*storage*" Then
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
Else
    Selection.PasteSpecial
End If

End Sub

</code>```

Body:
I am overwriting the paste shortcut (ctrl-v) with a macro to only paste values.
However, I only want this to happen in the actual workbook the macro is in.

This is my code:

Sub paste_values_only()
If Not ActiveWorkbook Is ThisWorkbook Then Exit Sub
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
End Sub

It seems to work, except that when I now ctr-v in another workbook, it just won't paste at all.. I want the ctrl-v to work like a normal paste action in another workbook.

To make things worse.. There's multiple workbooks that will have this paste-overwrite macro.

If there's an easier way to limit pasting in a certain workbook to values only, I'd be happy to hear about it too! I just want to prevent my colleagues pasting formatting/conditional rules/formulas/etc. into this workbook.

Body:
After some more elbow grease, I got a solution. Not very elegant, but it works:

Since all files that need to have this paste-protection have 'storage' in the name, I was able to limit the paste-limitation to these workbooks. Using Selection.PasteSpecial without features for the else clause I worked around the problem..

Sub paste_values_only()

Dim wbname As String

wbname = ActiveWorkbook.Name

If wbname Like "*storage*" Then
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
Else
    Selection.PasteSpecial
End If

End Sub


问:
How to disable previous month in date-range picker
I am using JQuery DateRange Picker, and I am looking for disabling previous months i.e. Jan 2020, Dec 2019, Nov and so on..

I tried this:

```<code><asp:TextBox ID="txtPunchDate" class="form-control" runat="server" autocomplete="off"></asp:TextBox>

 $('#<%= txtDate.ClientID%>').daterangepicker({
   locale: {
            format: 'YYYY-MM-DD',
            "separator": " to "
   },
   changeMonth: false,
   changeYear: false,
   stepMonths: 0
 });
</code>```

But it doesn't seem to be working.. Nothing happens..

Can anybody help me here?

答:
Add

```<code>minDate: moment().startOf('month'),
</code>```

Example:

jQuery(function($) {

  $('input[name="daterange"]').daterangepicker({
    locale: {
      format: 'YYYY-MM-DD',
      "separator": " to "
    },
    minDate: moment().startOf('month'),
    changeMonth: false,
    changeYear: false,
    stepMonths: 0
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

<input type="text" name="daterange" />

<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script></code>```

Body:
I am using JQuery DateRange Picker, and I am looking for disabling previous months i.e. Jan 2020, Dec 2019, Nov and so on..

I tried this:

<asp:TextBox ID="txtPunchDate" class="form-control" runat="server" autocomplete="off"></asp:TextBox>

 $('#<%= txtDate.ClientID%>').daterangepicker({
   locale: {
            format: 'YYYY-MM-DD',
            "separator": " to "
   },
   changeMonth: false,
   changeYear: false,
   stepMonths: 0
 });

But it doesn't seem to be working.. Nothing happens..

Can anybody help me here?

Body:
Add

minDate: moment().startOf('month'),

Example:

jQuery(function($) {

  $('input[name="daterange"]').daterangepicker({
    locale: {
      format: 'YYYY-MM-DD',
      "separator": " to "
    },
    minDate: moment().startOf('month'),
    changeMonth: false,
    changeYear: false,
    stepMonths: 0
  });

});

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

<input type="text" name="daterange" />

<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>


问:
Invalid data when creating mkv container with h264 stream because extradata is null
I need to encode raw frames into an h264 stream inside an mkv container using ffmpeg's c api.
All the examples I could find copy existing codec parameters from a decoder so I had to modify it a bit.

#include <cstdio>
#include <cstring>
#include <iostream>

extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libswscale/swscale.h>
}

static char error_msg[4096] = "";

int main(int argc, char **argv) {
  int err;
  char *filename = (char *)av_malloc(4096);
  AVCodec *codec = nullptr;
  SwsContext *color_converter = nullptr;
  AVCodecContext *encoder = nullptr;
  AVFormatContext *container = nullptr;
  AVStream *stream = nullptr;

  std::snprintf(filename, sizeof(filename), "%s", "out.mkv");

  // Create encoder
  codec = avcodec_find_encoder_by_name("libx264");
  if (codec == NULL) {
    std::cerr << "codec not found" << std::endl;
    goto cleanup;
  }

  encoder = avcodec_alloc_context3(codec);
  if (encoder == nullptr) {
    std::cerr << "failed to allocate encoder" << std::endl;
    goto cleanup;
  }

  // Configure encoder
  encoder->color_range = AVCOL_RANGE_JPEG;
  encoder->height = 1024;
  encoder->width = 1280;
  encoder->sample_aspect_ratio = {1, 1};
  encoder->pix_fmt = AV_PIX_FMT_YUVJ420P;
  encoder->time_base = {1, 10};
  encoder->framerate = {10, 1};

  err = av_opt_set_double(encoder->priv_data, "crf", 0.0, 0);
  if (err < 0) {
    av_make_error_string(error_msg, sizeof(error_msg), err);
    std::cerr << "failed to initialize encoder: " << error_msg << std::endl;
    goto cleanup;
  }

  err = avcodec_open2(encoder, codec, nullptr);
  if (err < 0) {
    av_make_error_string(error_msg, sizeof(error_msg), err);
    std::cerr << "failed to initialize encoder: " << error_msg << std::endl;
    goto cleanup;
  }

  // Create container
  avformat_alloc_output_context2(&container, NULL, NULL, filename);
  if (container == NULL) {
    std::cerr << "failed to allocate container" << std::endl;
    goto cleanup;
  }

  // Add stream
  stream = avformat_new_stream(container, nullptr);
  if (stream == NULL) {
    std::cerr << "failed to create new stream" << std::endl;
    goto cleanup;
  }

  stream->time_base = encoder->time_base;
  err = avcodec_parameters_from_context(stream->codecpar, encoder);
  if (err < 0) {
    av_make_error_string(error_msg, sizeof(error_msg), err);
    std::cerr << "failed to configure stream: " << error_msg << std::endl;
    goto cleanup;
  }

  // encoder->extradata_size == 0 at this point!

  // Open file and write file header
  err = avio_open(&container->pb, filename, AVIO_FLAG_WRITE);
  if (err < 0) {
    av_make_error_string(error_msg, sizeof(error_msg), err);
    std::cerr << "failed to open output file: " << error_msg << std::endl;
    goto cleanup;
  }

  err = avformat_write_header(container, nullptr);
  // fails in ff_isom_write_avcc because stream->codecpar->extradata is null.
  if (err < 0) {
    av_make_error_string(error_msg, sizeof(error_msg), err);
    std::cerr << "failed to set-up container: " << error_msg << std::endl;
    goto cleanup;
  }

cleanup:
  avcodec_close(encoder);
  if (container != nullptr) {
    avio_closep(&container->pb);
  }
  avcodec_free_context(&encoder);
  sws_freeContext(color_converter);
  avformat_free_context(container);
  av_free(filename);

  return 0;
}
```

This fails with EINVAL (Invalid data found when processing input) at the avformat_write_header line (more precisely in ff_isom_write_avcc inside the ffmpeg library) because stream->codecpar->extradata is null. The same code works for an mp4 container and I have no clue how to initialize stream->codecpar->extradata (or encoder->extradata) manually.

I have checked similar questions about that problem but could not find a conclusive answer:

https://stackoverflow.com/a/22231863/5786475 says extradata can be null when h264 is in annex b format

https://stackoverflow.com/a/27471912/5786475 says it shouldn't be null.

答: Set AV_CODEC_FLAG_GLOBAL_HEADER for encoder->flags before opening. This will tell x264 to add extradata to the encoder context instead of sending it as in-band within the encoded bitstream. The Matroska muxer only looks at AVStream codec parameters for this extradata and it is copied there from encoder context and not any packets in your code.</p>

Body:
I need to encode raw frames into an h264 stream inside an mkv container using ffmpeg's c api.
All the examples I could find copy existing codec parameters from a decoder so I had to modify it a bit.

#include <cstdio>
#include <cstring>
#include <iostream>

extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libswscale/swscale.h>
}

static char error_msg[4096] = "";

int main(int argc, char **argv) {
  int err;
  char *filename = (char *)av_malloc(4096);
  AVCodec *codec = nullptr;
  SwsContext *color_converter = nullptr;
  AVCodecContext *encoder = nullptr;
  AVFormatContext *container = nullptr;
  AVStream *stream = nullptr;

  std::snprintf(filename, sizeof(filename), "%s", "out.mkv");

  // Create encoder
  codec = avcodec_find_encoder_by_name("libx264");
  if (codec == NULL) {
    std::cerr << "codec not found" << std::endl;
    goto cleanup;
  }

  encoder = avcodec_alloc_context3(codec);
  if (encoder == nullptr) {
    std::cerr << "failed to allocate encoder" << std::endl;
    goto cleanup;
  }

  // Configure encoder
  encoder->color_range = AVCOL_RANGE_JPEG;
  encoder->height = 1024;
  encoder->width = 1280;
  encoder->sample_aspect_ratio = {1, 1};
  encoder->pix_fmt = AV_PIX_FMT_YUVJ420P;
  encoder->time_base = {1, 10};
  encoder->framerate = {10, 1};

  err = av_opt_set_double(encoder->priv_data, "crf", 0.0, 0);
  if (err < 0) {
    av_make_error_string(error_msg, sizeof(error_msg), err);
    std::cerr << "failed to initialize encoder: " << error_msg << std::endl;
    goto cleanup;
  }

  err = avcodec_open2(encoder, codec, nullptr);
  if (err < 0) {
    av_make_error_string(error_msg, sizeof(error_msg), err);
    std::cerr << "failed to initialize encoder: " << error_msg << std::endl;
    goto cleanup;
  }

  // Create container
  avformat_alloc_output_context2(&container, NULL, NULL, filename);
  if (container == NULL) {
    std::cerr << "failed to allocate container" << std::endl;
    goto cleanup;
  }

  // Add stream
  stream = avformat_new_stream(container, nullptr);
  if (stream == NULL) {
    std::cerr << "failed to create new stream" << std::endl;
    goto cleanup;
  }

  stream->time_base = encoder->time_base;
  err = avcodec_parameters_from_context(stream->codecpar, encoder);
  if (err < 0) {
    av_make_error_string(error_msg, sizeof(error_msg), err);
    std::cerr << "failed to configure stream: " << error_msg << std::endl;
    goto cleanup;
  }

  // encoder->extradata_size == 0 at this point!

  // Open file and write file header
  err = avio_open(&container->pb, filename, AVIO_FLAG_WRITE);
  if (err < 0) {
    av_make_error_string(error_msg, sizeof(error_msg), err);
    std::cerr << "failed to open output file: " << error_msg << std::endl;
    goto cleanup;
  }

  err = avformat_write_header(container, nullptr);
  // fails in ff_isom_write_avcc because stream->codecpar->extradata is null.
  if (err < 0) {
    av_make_error_string(error_msg, sizeof(error_msg), err);
    std::cerr << "failed to set-up container: " << error_msg << std::endl;
    goto cleanup;
  }

cleanup:
  avcodec_close(encoder);
  if (container != nullptr) {
    avio_closep(&container->pb);
  }
  avcodec_free_context(&encoder);
  sws_freeContext(color_converter);
  avformat_free_context(container);
  av_free(filename);

  return 0;
}

This fails with EINVAL (Invalid data found when processing input) at the avformat_write_header line (more precisely in ff_isom_write_avcc inside the ffmpeg library) because stream->codecpar->extradata is null. The same code works for an mp4 container and I have no clue how to initialize stream->codecpar->extradata (or encoder->extradata) manually.

I have checked similar questions about that problem but could not find a conclusive answer:

https://stackoverflow.com/a/22231863/5786475 says extradata can be null when h264 is in annex b format

https://stackoverflow.com/a/27471912/5786475 says it shouldn't be null.


问:
Selenium ChromeDriver ssl_client_socket_impl.cc(941) handshake failed
I'm currently using Python3.7 under Windows 32-bit with Chrome Version 80.0.3987.100 under an enterprise controlled environment. It actually opens Chrome with the selected user profile but DevTools is not able to establish the connection, thus the code is interrupted before navigating to the selected url.
I've already checked for the correct version of ChromeDriver.

My actual code:

```<code>from selenium import webdriver

woptions = webdriver.ChromeOptions()
woptions.add_argument("--user-data-dir=C:\\Users\\xxx\\AppData\\Local\\Google\\Chrome\\User Data2")
woptions.add_argument("--profile-directory=pySelenium")
woptions.add_argument("--disable-popup-blocking")
woptions.add_argument("--disable-default-apps")
woptions.add_argument("--disable-dev-shm-usage")
woptions.add_argument("--disable-gpu")
woptions.add_argument("-no-sandbox")
woptions.add_argument("--disable-infobars")
woptions.add_argument("--dns-prefetch-disable")
woptions.add_argument("--disable-extensions")
woptions.add_argument("--disable-notifications")
woptions.add_argument("--ignore-certificate-errors-spki-list")
woptions.add_argument("--ignore-certificate-errors")
woptions.add_argument("--ignore-ssl-errors")
woptions.add_argument("--allow-insecure-localhost")
woptions.add_argument("--ignore-urlfetcher-cert-requests")
woptions.add_experimental_option('useAutomationExtension',False)

w = webdriver.Chrome(options=woptions)
w.Navigate().GoToUrl("http://www.uol.com.br")
</code>```

Error message:

```<code>[12532:12892:0214/160407.330:ERROR:ssl_client_socket_impl.cc(941)] handshake failed; returned -1, SSL error code 1, net_error -101
</code>```

followed by other errors which I think are derived from this one.

It seems I have to handle the SSL certificate somehow instead of just trying to ignore it, but I'm lost.

答: I am using a Selenium, python and Chrome80. What I've noticed is that those "ssl error code 1" appear simultaneously as some console errors, that have to do with some deprecation in Chrome. You might wanna check your console to see if it happens to you too

Body:
I'm currently using Python3.7 under Windows 32-bit with Chrome Version 80.0.3987.100 under an enterprise controlled environment. It actually opens Chrome with the selected user profile but DevTools is not able to establish the connection, thus the code is interrupted before navigating to the selected url.
I've already checked for the correct version of ChromeDriver.

My actual code:

from selenium import webdriver

woptions = webdriver.ChromeOptions()
woptions.add_argument("--user-data-dir=C:\\Users\\xxx\\AppData\\Local\\Google\\Chrome\\User Data2")
woptions.add_argument("--profile-directory=pySelenium")
woptions.add_argument("--disable-popup-blocking")
woptions.add_argument("--disable-default-apps")
woptions.add_argument("--disable-dev-shm-usage")
woptions.add_argument("--disable-gpu")
woptions.add_argument("-no-sandbox")
woptions.add_argument("--disable-infobars")
woptions.add_argument("--dns-prefetch-disable")
woptions.add_argument("--disable-extensions")
woptions.add_argument("--disable-notifications")
woptions.add_argument("--ignore-certificate-errors-spki-list")
woptions.add_argument("--ignore-certificate-errors")
woptions.add_argument("--ignore-ssl-errors")
woptions.add_argument("--allow-insecure-localhost")
woptions.add_argument("--ignore-urlfetcher-cert-requests")
woptions.add_experimental_option('useAutomationExtension',False)

w = webdriver.Chrome(options=woptions)
w.Navigate().GoToUrl("http://www.uol.com.br")

Error message:

[12532:12892:0214/160407.330:ERROR:ssl_client_socket_impl.cc(941)] handshake failed; returned -1, SSL error code 1, net_error -101

followed by other errors which I think are derived from this one.

It seems I have to handle the SSL certificate somehow instead of just trying to ignore it, but I'm lost.


问:
Flutter: CheckboxListTile remove default padding
I'm looking to remove this padding around my row of CheckboxListTiles, but haven't found any information on how to do this without making my own version of a checkbox.

Is there any way to (using the CheckboxListTile):

Remove the (blue) left and right padding of the CheckboxListTile

Increase the width of the text area (I've tried sizedbox, containers, etc with no luck)

答:
There are couple ways:

Create a stack and place the checkboxes with Positioned widget (basically your own variation of CheckboxListTile)

Copy the flutter checkbox widget code into your own file
(custom_checkbox.dart), find the part where they added the padding/ margin, set it to 0. 3)

Try out other checkbox packages existing
on pub.dev like flare_checkbox or circular_chekbox.

All of those approaches have its advantages and disadvantages as you can imagine.

Edit

I have created for you a custom checkbox list tile, where the padding is much smaller.

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          color: Colors.grey,
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
            checkboxTile('Charger'),
            checkboxTile('Bag'),
            checkboxTile('Mouse'),
          ]),
        ),
      ),
    );
  }

  Widget checkboxTile(String title) {
    return Row(children: [
      Text(title),
      Checkbox(value: true, onChanged: (v) => null),
    ]);
  }
}
</code>```

Make sure to convert checkboxTile into a stateless widget if you wanna use that implementation.

click here to see custom checkbox list tile as image

Body:
There are couple ways:

Create a stack and place the checkboxes with Positioned widget (basically your own variation of CheckboxListTile)

Copy the flutter checkbox widget code into your own file
(custom_checkbox.dart), find the part where they added the padding/ margin, set it to 0. 3)

Try out other checkbox packages existing
on pub.dev like flare_checkbox or circular_chekbox.

All of those approaches have its advantages and disadvantages as you can imagine.

Edit

I have created for you a custom checkbox list tile, where the padding is much smaller.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          color: Colors.grey,
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
            checkboxTile('Charger'),
            checkboxTile('Bag'),
            checkboxTile('Mouse'),
          ]),
        ),
      ),
    );
  }

  Widget checkboxTile(String title) {
    return Row(children: [
      Text(title),
      Checkbox(value: true, onChanged: (v) => null),
    ]);
  }
}

Make sure to convert checkboxTile into a stateless widget if you wanna use that implementation.

click here to see custom checkbox list tile as image


问:
randomForest::importance() : type=2 is working, but not type=1
I'm using randomForest package. In order to get variable importances, I'm using importance() function.
I want to change the type of importance measure. It's determined by "type" argument, which have 2 possible values : type=1 or type=2. Here is an example :

```<code>library(randomForest)

Y = runif(100, 0.0, 1.0)
X1 = runif(100, 0.0, 1.0)
X2 = runif(100, 0.0, 1.0)

rf.model = randomForest::randomForest(Y~X1+X2)

# type 2 : mean decrease in node impurity
imp2 = randomForest::importance(x=rf.model,type=2)

# type 1 : mean decrease in accuracy
imp1 = randomForest::importance(x=rf.model,type=1)
</code>```

imp2 output :

```<code>      IncNodePurity
X1      3.130248
X2      3.023091
</code>```

imp1 output :

```<code>X1
X2
</code>```

As you can see, type=2 (mean decrease in node impurity) is working, but not type=1 (mean decrease in accuracy). Do you know how to solve this problem ?

答:
You have to enable it in your model first

```<code>rf.model = randomForest::randomForest(Y~X1+X2,importance=T)
</code>```

then it will work.

Body:
I'm using randomForest package. In order to get variable importances, I'm using importance() function.
I want to change the type of importance measure. It's determined by "type" argument, which have 2 possible values : type=1 or type=2. Here is an example :

library(randomForest)

Y = runif(100, 0.0, 1.0)
X1 = runif(100, 0.0, 1.0)
X2 = runif(100, 0.0, 1.0)

rf.model = randomForest::randomForest(Y~X1+X2)

# type 2 : mean decrease in node impurity
imp2 = randomForest::importance(x=rf.model,type=2)

# type 1 : mean decrease in accuracy
imp1 = randomForest::importance(x=rf.model,type=1)

imp2 output :

      IncNodePurity
X1      3.130248
X2      3.023091

imp1 output :

X1
X2

As you can see, type=2 (mean decrease in node impurity) is working, but not type=1 (mean decrease in accuracy). Do you know how to solve this problem ?

Body:
You have to enable it in your model first

rf.model = randomForest::randomForest(Y~X1+X2,importance=T)

then it will work.


问:
merge multiple txt file to csv - add header
I have multiple txt file, only one column in each and I'm trying to merge them all into one csv. Ideally I want each column to have the name of the file where they come from, and I am stuck at this last part.

text files look like this (2 examples but I got many more):

```<code>c.Daphnia.txt
geneA
geneB
geneC

c.Drosophila.txt
geneA
geneD
geneE

c.Mouse.txt
geneA
geneV
geneX
</code>```

Desired output:

At the moment im doing this:
paste -d',' c* > all.csv
The output looks like this, it got all the columns but no header.

Could you help me please?

Thanks

答:
```<code>custom_paste() (
  IFS=$(printf ',') # or IFS=$','
  printf '%s\n' "$*"
  paste -- "$@"
)

custom_paste c* > all.csv
</code>```

Body:
I have multiple txt file, only one column in each and I'm trying to merge them all into one csv. Ideally I want each column to have the name of the file where they come from, and I am stuck at this last part.

text files look like this (2 examples but I got many more):

c.Daphnia.txt
geneA
geneB
geneC

c.Drosophila.txt
geneA
geneD
geneE

c.Mouse.txt
geneA
geneV
geneX

Desired output:

At the moment im doing this:
paste -d',' c* > all.csv
The output looks like this, it got all the columns but no header.

Could you help me please?

Thanks


问:
Pandas columns to array
I have a df with the following structure:

```<code>date      country  value

20200215  Austria  123.32
20200215  Finland  321.21
20200216  Austria  123.32
20200216  Finland  321.21
</code>```

What I like to achieve is this:

```<code>
date     CountryValue

20200215  ['Austria':123.32,'Finland':321.21]
20200216  ['Austria':123.32,'Finland':321.21]
</code>```

I don't manage to get a solution, so any help is appreciated.

答:
If want dictionaries use zip with dict per groups in GroupBy.apply in lambda function:

```<code>f1 = lambda x: dict(zip(x['country'], x['value']))
df1 = df.groupby('date')['country','value'].apply(f1).reset_index(name='CountryValue')
print (df1)
       date                            CountryValue
0  20200215  {'Austria': 123.32, 'Finland': 321.21}
1  20200216  {'Austria': 123.32, 'Finland': 321.21}
</code>```

If want lists use flattening lists in list comprehension:

```<code>f2 = lambda x: [z for y in x.values for z in y]
df2 = df.groupby('date')['country','value'].apply(f2).reset_index(name='CountryValue')
print (df2)

       date                        CountryValue
0  20200215  [Austria, 123.32, Finland, 321.21]
1  20200216  [Austria, 123.32, Finland, 321.21]
</code>```

Title: Pandas columns to array

Body:
I have a df with the following structure:

date      country  value

20200215  Austria  123.32
20200215  Finland  321.21
20200216  Austria  123.32
20200216  Finland  321.21

What I like to achieve is this:

date     CountryValue

20200215  ['Austria':123.32,'Finland':321.21]
20200216  ['Austria':123.32,'Finland':321.21]

I don't manage to get a solution, so any help is appreciated.

Body:
If want dictionaries use zip with dict per groups in GroupBy.apply in lambda function:

f1 = lambda x: dict(zip(x['country'], x['value']))
df1 = df.groupby('date')['country','value'].apply(f1).reset_index(name='CountryValue')
print (df1)
       date                            CountryValue
0  20200215  {'Austria': 123.32, 'Finland': 321.21}
1  20200216  {'Austria': 123.32, 'Finland': 321.21}

If want lists use flattening lists in list comprehension:

f2 = lambda x: [z for y in x.values for z in y]
df2 = df.groupby('date')['country','value'].apply(f2).reset_index(name='CountryValue')
print (df2)

       date                        CountryValue
0  20200215  [Austria, 123.32, Finland, 321.21]
1  20200216  [Austria, 123.32, Finland, 321.21]


问:
Django-Tagging - count and ordering top "tags" (Is there a cleaner solution to mine?)
I'm using Django-Tagging, and I don't exactly need a cloud, I just want a limited list of the most popular tags used in my blog entries.

Using the following:

```<code>[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]
</code>```

It returns an array (note I'm using Lorem Ipsum while I develop):

```<code>[(u'deposit', 5), (u'escorol', 1), (u'gratuitous', 8), (u'marquee', 2)]
</code>```

But then to order and limit it I need to then do this:

```<code>sorted([(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)], key=lambda k:k[1], reverse=True)[:10]
</code>```

Is there a neater way to do this? I feel like there must be.

答:
I use raw sql for this:</p>

```<code>trends = Tag.objects.raw("select tagging_tag.id, count(object_id) as counter from tagging_tag left join tagging_taggeditem on tagging_tag.id = tagging_taggeditem.tag_id group by tagging_tag.id order by counter DESC limit 10")
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using Django-Tagging, and I don't exactly need a cloud, I just want a limited list of the most popular tags used in my blog entries.

Using the following:

[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]

It returns an array (note I'm using Lorem Ipsum while I develop):

[(u'deposit', 5), (u'escorol', 1), (u'gratuitous', 8), (u'marquee', 2)]

But then to order and limit it I need to then do this:

sorted([(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)], key=lambda k:k[1], reverse=True)[:10]

Is there a neater way to do this? I feel like there must be.

Body:
I use raw sql for this:

trends = Tag.objects.raw("select tagging_tag.id, count(object_id) as counter from tagging_tag left join tagging_taggeditem on tagging_tag.id = tagging_taggeditem.tag_id group by tagging_tag.id order by counter DESC limit 10")


问:
How is this javascript object destructuring working?
I am trying to understand this React redux example on : https://codesandbox.io/s/f2ded

In reducer.js, the initial state is :

```<code>const initialState = {
  taskName: "",
  tasks: []
};
</code>```

In App.js, we have :

```<code>const mapStateToProps = state => {
  return {
    ...state.list
  };
};
</code>```

The state does not have a property list and it state.list should be an empty object {}. But, it actually holds

Appreciate any help in understanding how exactly this works. Thank you.

答:
To understand it more deeply you need to learn about combineReducers

Example

```<code>rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
// This would produce the following state object
{
    potato: {
        // ... potatoes, and other state managed by the potatoReducer ...
    },
    tomato: {
        // ... tomatoes, and other state managed by the tomatoReducer, maybe some nice
        // sauce? ...
    }
}
</code>```

You can control state key names by using different keys for the reducers in the passed object. For example, you may call combineReducers({ todos: myTodosReducer, counter: myCounterReducer }) for the state shape to be { todos, counter }.

A popular convention is to name reducers after the state slices they manage, so you can use ES6 property shorthand notation: combineReducers({ counter, todos }). This is equivalent to writing combineReducers({ counter: counter, todos: todos }).

So when you are using ...state.list you are getting it because of combineReducers({ list: listReducer }) or simply combineReducers({ list})

To know more please follow: combineReducers

Body:
I am trying to understand this React redux example on : https://codesandbox.io/s/f2ded

In reducer.js, the initial state is :

const initialState = {
  taskName: "",
  tasks: []
};

In App.js, we have :

const mapStateToProps = state => {
  return {
    ...state.list
  };
};

The state does not have a property list and it state.list should be an empty object {}. But, it actually holds

Appreciate any help in understanding how exactly this works. Thank you.

Body:
To understand it more deeply you need to learn about combineReducers

Example

rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
// This would produce the following state object
{
    potato: {
        // ... potatoes, and other state managed by the potatoReducer ...
    },
    tomato: {
        // ... tomatoes, and other state managed by the tomatoReducer, maybe some nice
        // sauce? ...
    }
}

You can control state key names by using different keys for the reducers in the passed object. For example, you may call combineReducers({ todos: myTodosReducer, counter: myCounterReducer }) for the state shape to be { todos, counter }.

A popular convention is to name reducers after the state slices they manage, so you can use ES6 property shorthand notation: combineReducers({ counter, todos }). This is equivalent to writing combineReducers({ counter: counter, todos: todos }).

So when you are using ...state.list you are getting it because of combineReducers({ list: listReducer }) or simply combineReducers({ list})

To know more please follow: combineReducers


问:
Yahoo sign in with Selenium, missing click
I am trying to write a login function. When I try to login into my yahoo account, I send the correct keys for my email address, which works, but then when I click "next" it 'misses' the click and instead clicks the banner which opens up some sort of advertisement be it travel related or Norton anti-security, or something. I've been working on this issue intermittently throughout the past week surfing and digging through forums before finally making my first post.

I am aware of the different ways of element selectors via css, id, class name, xpath, etc... I tried sleep(), implicit_wait(), things along those lines. I also tried something with wait until clickable with the expected conditions module from selenium.webdriver.

I've attached an image of what I have so far. My python version is up-to-date as are my selenium and chrome driver installations. I saw a similar post already up, but the OP didn't seem to be encountering my issue. (how to click on the yahoo sign in link using selenium web driver?)

I tried this as well, and it opens the advertisement; in my executions, Norton seems to be the most frequently appearing advertisement. (login to Yahoo using Python Selenium)

I've looked at the API documentation, but there doesn't seem to be any clear direction on what I could do. I've attached screenshots of what happens on the running of the script as well as the code I have.

I got it to work for some runs where I was able to go to the next form to send my password keys, but it happened randomly and inexplicably.

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from login import password, email
from time import sleep

class yahoo():

def __init__(self):

    # INITIALIZE CHROME WEBDRIVER
    self.driver = webdriver.Chrome()
    self.driver.maximize_window()

def login(self):

    # OPEN BROWSER TO LOGIN PAGE AND MAXIMIZE
    self.driver.get("https://login.yahoo.com/config/login?.\
    src=fpctx&.intl=us&.lang=en-US&.done=https://www.yahoo.com")
    # LOGIN ACTIONS

    {# 1. send email address and click next
    self.driver.find_element_by_id('login-username').send_keys(email)
    element = WebDriverWait(self.driver, 10).until(\
            EC.presence_of_element_located((By.ID, "login-signin")))
    element.click()

    # 2. send password and click sign in
    self.driver.find_element_by_xpath('//*[@id="login-passwd"]').send_keys(password)
    self.driver.find_element_by_id('login-signin').click()}`enter code here

x = yfscreeners()
x.login()
</code>```

Any help is well appreciated.

答:
Use WebDriverWait for the email field as well

```<code>wait = WebDriverWait(self.driver, 10)
wait.until(EC.visibility_of_element_located((By.ID, 'login-username'))).send_keys(email)
wait.until(EC.visibility_of_element_located((By.ID, 'login-signin'))).click()
</code>```

Body:
I am trying to write a login function. When I try to login into my yahoo account, I send the correct keys for my email address, which works, but then when I click "next" it 'misses' the click and instead clicks the banner which opens up some sort of advertisement be it travel related or Norton anti-security, or something. I've been working on this issue intermittently throughout the past week surfing and digging through forums before finally making my first post.

I am aware of the different ways of element selectors via css, id, class name, xpath, etc... I tried sleep(), implicit_wait(), things along those lines. I also tried something with wait until clickable with the expected conditions module from selenium.webdriver.

I've attached an image of what I have so far. My python version is up-to-date as are my selenium and chrome driver installations. I saw a similar post already up, but the OP didn't seem to be encountering my issue. (how to click on the yahoo sign in link using selenium web driver?)

I tried this as well, and it opens the advertisement; in my executions, Norton seems to be the most frequently appearing advertisement. (login to Yahoo using Python Selenium)

I've looked at the API documentation, but there doesn't seem to be any clear direction on what I could do. I've attached screenshots of what happens on the running of the script as well as the code I have.

I got it to work for some runs where I was able to go to the next form to send my password keys, but it happened randomly and inexplicably.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from login import password, email
from time import sleep

class yahoo():

def __init__(self):

    # INITIALIZE CHROME WEBDRIVER
    self.driver = webdriver.Chrome()
    self.driver.maximize_window()

def login(self):

    # OPEN BROWSER TO LOGIN PAGE AND MAXIMIZE
    self.driver.get("https://login.yahoo.com/config/login?.\
    src=fpctx&.intl=us&.lang=en-US&.done=https://www.yahoo.com")
    # LOGIN ACTIONS

    {# 1. send email address and click next
    self.driver.find_element_by_id('login-username').send_keys(email)
    element = WebDriverWait(self.driver, 10).until(\
            EC.presence_of_element_located((By.ID, "login-signin")))
    element.click()

    # 2. send password and click sign in
    self.driver.find_element_by_xpath('//*[@id="login-passwd"]').send_keys(password)
    self.driver.find_element_by_id('login-signin').click()}`enter code here

x = yfscreeners()
x.login()

Any help is well appreciated.

Body:
Use WebDriverWait for the email field as well

wait = WebDriverWait(self.driver, 10)
wait.until(EC.visibility_of_element_located((By.ID, 'login-username'))).send_keys(email)
wait.until(EC.visibility_of_element_located((By.ID, 'login-signin'))).click()


问:
gremlin - show query execution time
How do you show the query execution time for a gremlin query while running it a console such as Datastax Studio?

I tried

```<code>clockWithResult(100) { myquery }
</code>```

But I get an error saying "cannot convert from int to Supplier"

答:
I'm pretty sure that clockWithResult() is a function provided only by Gremlin Console and is not part of the Gremlin language itself. Other Gremlin tools (like DS Studio) don't have that specific feature that I'm aware of. If you really want to use that feature you should connect Gremlin Console to DataStax Graph and execute your query from there.

That said, clockWithResult() is just a member of TimeUtil which can be found here. You could either:

Try to modify the DS Graph sandbox whitelist to allow that class to be used and then use it through Studio OR

If that approach doesn't work for some reason, just copy/paste that function code to a Studio cell and use it directly (I'm mostly sure that would work, but haven't tried).

Title: gremlin - show query execution time

Body:
How do you show the query execution time for a gremlin query while running it a console such as Datastax Studio?

I tried

clockWithResult(100) { myquery }

But I get an error saying "cannot convert from int to Supplier"


问:
Create LINQ request
I have some collections:

Dictionary<InvoceHeader, List<InvoiceHierarchy>> where

```<code>public class InvoceHeader
{
    public int InvoiceId { get; set; }
    public string DocumentNumber { get; set; }
    public string DocumentDate { get; set; }
    public string DocumentReference { get; set; }
}

public class InvoiceHierarchi
{
    public string SerialNumber { get; set; }
    public string ProductCode { get; set; }
    public string Certificate { get; set; }
    public string Description { get; set; }
}
</code>```

I need to write a LINQ request to get such a collection from the original collection --> Dictionary<string, List<string>>, where key --> InvoceHeader.DocumentNumber, value --> List two elements from InvoiceHierarchi such as the SerialNumber and Certificate.

答:
That should be the query that you are looking for, only that you can replace the anonymous types that I am using in the query with a custom type that you created.

```<code>var newCollection = originalCollection.Select(x => new
                {
                    Key = x.Key.DocumentNumber,
                    Value = x.Value.Select(y => new
                    {
                        y.SerialNumber,
                        y.Certificate
                    }).ToList()
                });
</code>```

If you want again to convert it to Dictionary, you can also add that line:

```<code> var newDictionary = newCollection.ToDictionary(x => x.Key, y => y.Value);
</code>```

Title: Create LINQ request

Body:
I have some collections:

Dictionary<InvoceHeader, List<InvoiceHierarchy>> where

public class InvoceHeader
{
    public int InvoiceId { get; set; }
    public string DocumentNumber { get; set; }
    public string DocumentDate { get; set; }
    public string DocumentReference { get; set; }
}

public class InvoiceHierarchi
{
    public string SerialNumber { get; set; }
    public string ProductCode { get; set; }
    public string Certificate { get; set; }
    public string Description { get; set; }
}

I need to write a LINQ request to get such a collection from the original collection --> Dictionary<string, List<string>>, where key --> InvoceHeader.DocumentNumber, value --> List two elements from InvoiceHierarchi such as the SerialNumber and Certificate.

Body:
That should be the query that you are looking for, only that you can replace the anonymous types that I am using in the query with a custom type that you created.

var newCollection = originalCollection.Select(x => new
                {
                    Key = x.Key.DocumentNumber,
                    Value = x.Value.Select(y => new
                    {
                        y.SerialNumber,
                        y.Certificate
                    }).ToList()
                });

If you want again to convert it to Dictionary, you can also add that line:

 var newDictionary = newCollection.ToDictionary(x => x.Key, y => y.Value);


问:
Searching versus Filtering in Restful API
I have started reading some references about API design (Amazon, Microsoft, Github, Apigee..) and I encountered this sentence:

"A better API must implement search and filter functionality."
  (something like that ..)

I did not figure out:

What's the difference between Filtering and Searching in Restful context?

Cordially

答:
May be its too late to answer this question but search is bit different then filter. Filter is used to narrow down result set with exact match while the search uses its weight.
For example if I want to find user in India then we can use country filter and narrow down the result set. But at the same time I want to see how many Rafael in this result set.
Search may response with Rafaela, rafaelb or Rafael but filter will remain exact country Indaa not Indiaa or Indiab.

This is basic difference between two.


问:
Is there a function in Archer that could draw a line separating two outputs in a single field?
I am trying to concatenate 2 outputs in calculated text field. But I would like to draw a line in between them or at least give them a heading, so that the users will be able to identify them easily. I could make different fields and have them calculated. But the requirement is to concatenate 15 fields into one field. So, I do not want to create 15 fields and write separate calcs. See below example

Example 1)

Hello, this is an example of what I am trying to explain with an example (o/p 1)

Hello, this is how I would like to present to the end users avoiding confusion (o/p 2)

As you see above, I was able to concatenate 2 o/p's, but I would like to draw a line. This one scenario that would work for me.

Example 2)enter image description here

Users Watch
Hello, this is an example of what I am trying to explain with an example (o/p 1)
Admin Watch
Hello, this is how I would like to present to the end users avoiding confusion (o/p 2)

As you see in 2nd example, I would like to put a heading for o/p 1 as "users watch" and "Admin Watch" for o/p 2, so that the users can differentiate it.

I have tried sub-string function for example 2, it looks 'OK' but it would be of more help if anyone has better solution.

答:
The beauty of Archer is that you can use HTML in the calculation; providing that the calculated field is a text field and that its display is set as text area.

You can use the following calculation:

```<code>CONCATENATE("<H3>Header 1</H3>", [Field 1], "<H3>Header 2</H3>", [Field 2])
</code>```

Body:
The beauty of Archer is that you can use HTML in the calculation; providing that the calculated field is a text field and that its display is set as text area.

You can use the following calculation:

CONCATENATE("<H3>Header 1</H3>", [Field 1], "<H3>Header 2</H3>", [Field 2])


问:
How to create narrowed typescript interfaces from existing interface which has optional fields?
I have an interface with optional field(s) like this one:

interface Config {
  foo: Foo
  bar?: Bar
}
```

<p>In a function I check whether they are not <code>undefined</code>, then call another function: </p>

<pre class="lang-js prettyprint-override"><code>function doSomething(config: Config) {
  // ...
  if(config.bar) {
    const result = calculateSomethingUsingFooAndBar(config)
    // ...
  }
  // ...
}
</code>```

Of course inside the if's scope the bar is narrowed which means we know that it exists and is not optional anymore. So I want to call the function calculateSomethingUsingFooAndBar without defining a new interface just for making bar required, but telling the compiler that when this method is called it should already have bar. Also if I want to call the function from somewhere else, where the bar was not narrowed, that should cause a compile-time error, as we are not sure if bar was defined.

function calculateSomethingUsingFooAndBar(config: Narrowed<Config>) {
   // config.bar (and every other optional field) is defined here, we can use it.
}
```

Is there such a thing or a neat but not hacky workaround for this? I have checked the advanced typescript types but could not figure out if they can help me or not.

答:
https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredt</p>

```<code>type RequiredConfig = Required<Config>;

function calculateSomethingUsingFooAndBar(config: RequiredConfig) {
   // config.bar (and every other optional field) is defined here, we can use it.
}
</code>```

Body:
I have an interface with optional field(s) like this one:

interface Config {
  foo: Foo
  bar?: Bar
}

In a function I check whether they are not undefined, then call another function:

function doSomething(config: Config) {
  // ...
  if(config.bar) {
    const result = calculateSomethingUsingFooAndBar(config)
    // ...
  }
  // ...
}

Of course inside the if's scope the bar is narrowed which means we know that it exists and is not optional anymore. So I want to call the function calculateSomethingUsingFooAndBar without defining a new interface just for making bar required, but telling the compiler that when this method is called it should already have bar. Also if I want to call the function from somewhere else, where the bar was not narrowed, that should cause a compile-time error, as we are not sure if bar was defined.

function calculateSomethingUsingFooAndBar(config: Narrowed<Config>) {
   // config.bar (and every other optional field) is defined here, we can use it.
}

Is there such a thing or a neat but not hacky workaround for this? I have checked the advanced typescript types but could not figure out if they can help me or not.

Body:
https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredt

type RequiredConfig = Required<Config>;

function calculateSomethingUsingFooAndBar(config: RequiredConfig) {
   // config.bar (and every other optional field) is defined here, we can use it.
}


问:
C# using an object as an Type in SQLite for UWP
I'm trying to make one function that can take an object as a parameter

```<code>    public static List<T> Get_DataList_DataFromSystem<T>(object DataNeeded, string BaseTypeString)
    {
          Type baseType = DataNeeded.GetType();
          SQliteConnector.GetInstance.conn.Table<baseType>();
    }
</code>```

using SQliteConnector.GetInstance.conn.Table(); i want to able to use the parameter DataNeeded that is passed into the function.

SQliteConnector.GetInstance gets an instance of the (SQLiteConnection( new SQLitePlatformWinRT(), path );)

SQliteConnector.GetInstance.conn.Table(); requires a class to be passed in

答:
Generic methods require the type to be known at compile time, whereas GetType() is executed at runtime.

This is what you're after:

```<code>public static List<T> Get_DataList_DataFromSystem<T>(T DataNeeded, string BaseTypeString) where T : class
{
      SQliteConnector.GetInstance.conn.Table<T>();
}
</code>```

The type of DataNeeded can then be inferred at compile time, based on the type of object that is passed to the method.

Body:
I'm trying to make one function that can take an object as a parameter

    public static List<T> Get_DataList_DataFromSystem<T>(object DataNeeded, string BaseTypeString)
    {
          Type baseType = DataNeeded.GetType();
          SQliteConnector.GetInstance.conn.Table<baseType>();
    }

using SQliteConnector.GetInstance.conn.Table(); i want to able to use the parameter DataNeeded that is passed into the function.

SQliteConnector.GetInstance gets an instance of the (SQLiteConnection( new SQLitePlatformWinRT(), path );)

SQliteConnector.GetInstance.conn.Table(); requires a class to be passed in

Body:
Generic methods require the type to be known at compile time, whereas GetType() is executed at runtime.

This is what you're after:

public static List<T> Get_DataList_DataFromSystem<T>(T DataNeeded, string BaseTypeString) where T : class
{
      SQliteConnector.GetInstance.conn.Table<T>();
}

The type of DataNeeded can then be inferred at compile time, based on the type of object that is passed to the method.


问:
Entity Framework - Id of loaded entity not being assigned
I have the following POCO class:

```<code>public class Person : Entity
    {
        public string FirstName { get; set; }
        public string MiddleName1 { get; set; }
        public string MiddleName2 { get; set; }
        public string LastName { get; set; }
        public byte? DayOfBirth { get; set; }
        public byte? MonthOfBirth { get; set; }
        public Int16? YearOfBirth { get; set; }
        public string MobileNumber { get; set; }
    }

public abstract class Entity
{
    public int Id { get; set; }
}
</code>```

Here is the corresponding edmx xml:

```<code><edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">
  <!-- EF Runtime content -->
  <edmx:Runtime>
    <!-- SSDL content -->
    <edmx:StorageModels>
      <Schema Namespace="EntityFramework.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
        <EntityContainer Name="EntityFrameworkStoreContainer">
          <EntitySet Name="People" EntityType="EntityFramework.Store.People" store:Type="Tables" Schema="dbo" />
        </EntityContainer>
        <EntityType Name="People">
          <Key>
            <PropertyRef Name="Id" />
          </Key>
          <Property Name="Id" Type="int" Nullable="false" />
          <Property Name="FirstName" Type="nvarchar" Nullable="false" MaxLength="50" />
          <Property Name="MiddleName1" Type="nvarchar" MaxLength="50" />
          <Property Name="MiddleName2" Type="nvarchar" MaxLength="50" />
          <Property Name="LastName" Type="nvarchar" Nullable="false" MaxLength="50" />
          <Property Name="DayOfBirth" Type="tinyint" />
          <Property Name="MonthOfBirth" Type="tinyint" />
          <Property Name="YearOfBirth" Type="smallint" />
          <Property Name="MobileNumber" Type="varchar" MaxLength="20" />
        </EntityType>
      </Schema>
    </edmx:StorageModels>
    <!-- CSDL content -->
    <edmx:ConceptualModels>
      <Schema Namespace="EntityFramework" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
        <EntityContainer Name="TheCleavesEntities" annotation:LazyLoadingEnabled="true">
          <EntitySet Name="People" EntityType="EntityFramework.Person" />
        </EntityContainer>
        <EntityType Name="Person">
          <Key>
            <PropertyRef Name="Id" />
          </Key>
          <Property Name="Id" Type="Int32" Nullable="false" />
          <Property Name="FirstName" Type="String" Nullable="false" MaxLength="50" Unicode="true" FixedLength="false" />
          <Property Name="MiddleName1" Type="String" MaxLength="50" Unicode="true" FixedLength="false" />
          <Property Name="MiddleName2" Type="String" MaxLength="50" Unicode="true" FixedLength="false" />
          <Property Name="LastName" Type="String" Nullable="false" MaxLength="50" Unicode="true" FixedLength="false" />
          <Property Name="DayOfBirth" Type="Byte" Nullable="true" />
          <Property Name="MonthOfBirth" Type="Byte" Nullable="true" />
          <Property Name="YearOfBirth" Type="Int16" Nullable="true" />
          <Property Name="MobileNumber" Type="String" MaxLength="20" Unicode="false" FixedLength="false" />
        </EntityType>
      </Schema>
    </edmx:ConceptualModels>
    <!-- C-S mapping content -->
    <edmx:Mappings>
      <Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
        <EntityContainerMapping StorageEntityContainer="EntityFrameworkStoreContainer" CdmEntityContainer="TheCleavesEntities">
          <EntitySetMapping Name="People"><EntityTypeMapping TypeName="EntityFramework.Person"><MappingFragment StoreEntitySet="People">
            <ScalarProperty Name="Id" ColumnName="Id" />
            <ScalarProperty Name="FirstName" ColumnName="FirstName" />
            <ScalarProperty Name="MiddleName1" ColumnName="MiddleName1" />
            <ScalarProperty Name="MiddleName2" ColumnName="MiddleName2" />
            <ScalarProperty Name="LastName" ColumnName="LastName" />
            <ScalarProperty Name="DayOfBirth" ColumnName="DayOfBirth" />
            <ScalarProperty Name="MonthOfBirth" ColumnName="MonthOfBirth" />
            <ScalarProperty Name="YearOfBirth" ColumnName="YearOfBirth" />
            <ScalarProperty Name="MobileNumber" ColumnName="MobileNumber" />
          </MappingFragment></EntityTypeMapping></EntitySetMapping>
        </EntityContainerMapping>
      </Mapping>
    </edmx:Mappings>
  </edmx:Runtime>
  <!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
  <Designer xmlns="http://schemas.microsoft.com/ado/2008/10/edmx">
    <Connection>
      <DesignerInfoPropertySet>
        <DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
      </DesignerInfoPropertySet>
    </Connection>
    <Options>
      <DesignerInfoPropertySet>
        <DesignerProperty Name="ValidateOnBuild" Value="true" />
        <DesignerProperty Name="EnablePluralization" Value="True" />
        <DesignerProperty Name="IncludeForeignKeysInModel" Value="False" />
      </DesignerInfoPropertySet>
    </Options>
    <!-- Diagram content (shape and connector positions) -->
    <Diagrams>
      <Diagram Name="TheCleaves">
        <EntityTypeShape EntityType="EntityFramework.Person" Width="1.5" PointX="0.75" PointY="0.75" Height="2.7494921874999996" IsExpanded="true" />
      </Diagram>
    </Diagrams>
  </Designer>
</edmx:Edmx>
</code>```

When I load up an entity (there's only one row in the database at present) with the code:

```<code>IEnumerable<Person> people = context.People.Where(x => true);
</code>```

I'm finding that the Id property of the returned Person object is 0 (it's 1 in the database). Anyone have any idea why it appears not to be set?

Thanks

答:
Ok it is not problem with inheritance as I initially thought - the inheritance will work. This is most probably combination of two problems:

Id is generated in the database but EF doesn't know about them. Both SSDL and CSDL part of EDMX should define Id with StoreGeneratedPattern.Identity. This will force EF to reload Id when entity is inserted.

I believe you are using same context instance for saving entity and calling the query. Now you meet identity map pattern. Despite the data retrieved from the query EF will use instance internally stored in its per-context cache. Because of the first problem the cached instance has Id with default int value = 0.

Body:
I have the following POCO class:

public class Person : Entity
    {
        public string FirstName { get; set; }
        public string MiddleName1 { get; set; }
        public string MiddleName2 { get; set; }
        public string LastName { get; set; }
        public byte? DayOfBirth { get; set; }
        public byte? MonthOfBirth { get; set; }
        public Int16? YearOfBirth { get; set; }
        public string MobileNumber { get; set; }
    }

public abstract class Entity
{
    public int Id { get; set; }
}

Here is the corresponding edmx xml:

<edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">

  <edmx:Runtime>

    <edmx:StorageModels>
      <Schema Namespace="EntityFramework.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
        <EntityContainer Name="EntityFrameworkStoreContainer">
          <EntitySet Name="People" EntityType="EntityFramework.Store.People" store:Type="Tables" Schema="dbo" />
        </EntityContainer>
        <EntityType Name="People">
          <Key>
            <PropertyRef Name="Id" />
          </Key>
          <Property Name="Id" Type="int" Nullable="false" />
          <Property Name="FirstName" Type="nvarchar" Nullable="false" MaxLength="50" />
          <Property Name="MiddleName1" Type="nvarchar" MaxLength="50" />
          <Property Name="MiddleName2" Type="nvarchar" MaxLength="50" />
          <Property Name="LastName" Type="nvarchar" Nullable="false" MaxLength="50" />
          <Property Name="DayOfBirth" Type="tinyint" />
          <Property Name="MonthOfBirth" Type="tinyint" />
          <Property Name="YearOfBirth" Type="smallint" />
          <Property Name="MobileNumber" Type="varchar" MaxLength="20" />
        </EntityType>
      </Schema>
    </edmx:StorageModels>

    <edmx:ConceptualModels>
      <Schema Namespace="EntityFramework" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
        <EntityContainer Name="TheCleavesEntities" annotation:LazyLoadingEnabled="true">
          <EntitySet Name="People" EntityType="EntityFramework.Person" />
        </EntityContainer>
        <EntityType Name="Person">
          <Key>
            <PropertyRef Name="Id" />
          </Key>
          <Property Name="Id" Type="Int32" Nullable="false" />
          <Property Name="FirstName" Type="String" Nullable="false" MaxLength="50" Unicode="true" FixedLength="false" />
          <Property Name="MiddleName1" Type="String" MaxLength="50" Unicode="true" FixedLength="false" />
          <Property Name="MiddleName2" Type="String" MaxLength="50" Unicode="true" FixedLength="false" />
          <Property Name="LastName" Type="String" Nullable="false" MaxLength="50" Unicode="true" FixedLength="false" />
          <Property Name="DayOfBirth" Type="Byte" Nullable="true" />
          <Property Name="MonthOfBirth" Type="Byte" Nullable="true" />
          <Property Name="YearOfBirth" Type="Int16" Nullable="true" />
          <Property Name="MobileNumber" Type="String" MaxLength="20" Unicode="false" FixedLength="false" />
        </EntityType>
      </Schema>
    </edmx:ConceptualModels>

    <edmx:Mappings>
      <Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
        <EntityContainerMapping StorageEntityContainer="EntityFrameworkStoreContainer" CdmEntityContainer="TheCleavesEntities">
          <EntitySetMapping Name="People"><EntityTypeMapping TypeName="EntityFramework.Person"><MappingFragment StoreEntitySet="People">
            <ScalarProperty Name="Id" ColumnName="Id" />
            <ScalarProperty Name="FirstName" ColumnName="FirstName" />
            <ScalarProperty Name="MiddleName1" ColumnName="MiddleName1" />
            <ScalarProperty Name="MiddleName2" ColumnName="MiddleName2" />
            <ScalarProperty Name="LastName" ColumnName="LastName" />
            <ScalarProperty Name="DayOfBirth" ColumnName="DayOfBirth" />
            <ScalarProperty Name="MonthOfBirth" ColumnName="MonthOfBirth" />
            <ScalarProperty Name="YearOfBirth" ColumnName="YearOfBirth" />
            <ScalarProperty Name="MobileNumber" ColumnName="MobileNumber" />
          </MappingFragment></EntityTypeMapping></EntitySetMapping>
        </EntityContainerMapping>
      </Mapping>
    </edmx:Mappings>
  </edmx:Runtime>

  <Designer xmlns="http://schemas.microsoft.com/ado/2008/10/edmx">
    <Connection>
      <DesignerInfoPropertySet>
        <DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
      </DesignerInfoPropertySet>
    </Connection>
    <Options>
      <DesignerInfoPropertySet>
        <DesignerProperty Name="ValidateOnBuild" Value="true" />
        <DesignerProperty Name="EnablePluralization" Value="True" />
        <DesignerProperty Name="IncludeForeignKeysInModel" Value="False" />
      </DesignerInfoPropertySet>
    </Options>

    <Diagrams>
      <Diagram Name="TheCleaves">
        <EntityTypeShape EntityType="EntityFramework.Person" Width="1.5" PointX="0.75" PointY="0.75" Height="2.7494921874999996" IsExpanded="true" />
      </Diagram>
    </Diagrams>
  </Designer>
</edmx:Edmx>

When I load up an entity (there's only one row in the database at present) with the code:

IEnumerable<Person> people = context.People.Where(x => true);

I'm finding that the Id property of the returned Person object is 0 (it's 1 in the database). Anyone have any idea why it appears not to be set?

Thanks


问:
Inverse of php array_column function?
Given an array like

```<code>$x = array(array('a', 'aa'), array('b', 'bb'), array('c', 'cc'));
</code>```

There is array_column that returns either

```<code>array_column($x, 0) === array('a', 'b', 'c')

or

array_column($x, 1) === array('aa', 'bb', 'cc')
</code>```

Now, is there an inverse? A function that would do:

```<code>array_putoneaftertheother(array('a', 'b', 'c'), array('aa', 'bb', 'cc')) === array(array('a', 'aa'), array('b', 'bb'), array('c', 'cc'))
</code>```

None come to my mind...

It's pretty easy to implement, but I'm surprised that with so many array_* functions, PHP has no native version of this?!

答:
You can do multiple arrays with array_map and no callback:

```<code>$result = array_map(null, array('a', 'b', 'c'), array('aa', 'bb', 'cc'));
</code>```

Or with one larger array the same way with Argument unpacking via ... (splat operator):

```<code>$result = array_map(null, ...array(array('a', 'b', 'c'), array('aa', 'bb', 'cc')));
</code>```

Title: Inverse of php array_column function?

Body:
Given an array like

$x = array(array('a', 'aa'), array('b', 'bb'), array('c', 'cc'));

There is array_column that returns either

array_column($x, 0) === array('a', 'b', 'c')

or

array_column($x, 1) === array('aa', 'bb', 'cc')

Now, is there an inverse? A function that would do:

array_putoneaftertheother(array('a', 'b', 'c'), array('aa', 'bb', 'cc')) === array(array('a', 'aa'), array('b', 'bb'), array('c', 'cc'))

None come to my mind...

It's pretty easy to implement, but I'm surprised that with so many array_* functions, PHP has no native version of this?!

Body:
You can do multiple arrays with array_map and no callback:

$result = array_map(null, array('a', 'b', 'c'), array('aa', 'bb', 'cc'));

Or with one larger array the same way with Argument unpacking via ... (splat operator):

$result = array_map(null, ...array(array('a', 'b', 'c'), array('aa', 'bb', 'cc')));


问:
Can't give default value to database text field in laravel app (mysql)
in my laravel app I have a Post "body" field of text type, I'm trying to give the field a default value like "This sis the default text for a blog post, feel free to change it" but mysql is throwing an error.

```<code>$table->text('body')->default('This is the default text for a blog post, feel free to change it.');
</code>```

This isn't working...

According to docs BLOB/TEXT fields CAN'T have default values, this is pretty weird tbh.

https://dev.mysql.com/doc/refman/5.7/en/blob.html

I guess I could change the field type from text to string but afaik string won't have as many characters as string type and I knpw for certain that my Blog posts will be loooong. How could I approach this?

Thanks in advance.

答:
you can set it to nullable $table->text('body')->nullable(true);
And in your view just give it a default text if it is NULL.

Body:
in my laravel app I have a Post "body" field of text type, I'm trying to give the field a default value like "This sis the default text for a blog post, feel free to change it" but mysql is throwing an error.

$table->text('body')->default('This is the default text for a blog post, feel free to change it.');

This isn't working...

According to docs BLOB/TEXT fields CAN'T have default values, this is pretty weird tbh.

https://dev.mysql.com/doc/refman/5.7/en/blob.html

I guess I could change the field type from text to string but afaik string won't have as many characters as string type and I knpw for certain that my Blog posts will be loooong. How could I approach this?

Thanks in advance.


问:
Best Practises for developing a TCP Communicator
We are developing a Vehicle Tracking System. In this system, we fix a GPS device into the vehicle which sends the location data to our server using TCP communication. There can be more than 1000's of devices sending data at any given time. Please suggest me the best practices I should follow to build the TCP communicator. We are using java as programming language and MySQL as database server.

I need your suggestions on best practices I should follow along with the reasons. e.g. I should follow Thread-per-connection model or Thread-on-event model of multi-threading? Why that model? How should I implement connection pooling? Shall I implement messaging queue?,etc..

Thanks,
Saurabh

答:
I have built a similar system. I used Mule3 for the tcp server listener and then after reading the data I just forwarded the data using JMS to an ActiveMQ server.

I had around 10-20 listeners on each queue processing the data, putting it in my database, running rules over the data to determine if alarms need to be sent etc.

This resultet in a very stable an easy to work environment. Small modules with specific tasks.


问:
grep extract specific pattern from a large file of 190GB
I need to extract the email addresses from a large 190GB flat file (only error log) that I cut into a 5mb files. (with 152,353,216 lines)

The grep command works well, but the memory quickly becomes saturated and I end up getting errors.

The content of the files is not formatted, so I have to use regexp.

```<code>grep -r -E -h -o "\b(pattern)\b" /dir/* > outs.txt
</code>```

How to process files one by one?

答:
The simplest (but probably not the quickest) way to process all the files would be to do so one by one, using a loop:

```<code>for file in /dir/*; do
  grep -r -E -h -o '\b(pattern)\b' "$file"
done > outs.txt
</code>```

The overhead of launching all those greps is potentially quite significant, though, so maybe you could use xargs to help:

```<code>find /dir/ -maxdepth 1 -type f -print0 |
  xargs -0 -n 1000 grep -r -E -h -o '\b(pattern)\b' > outs.txt
</code>```

This uses find to produce the list of files in dir and passes them safely to xargs, separated by a null byte \0 (a character guaranteed not to be in a filename). xargs then passes the files to grep in batches of 1000.

(I'm assuming that you have GNU versions of find and xargs here, for find -print0 and xargs -0)

Body:
I need to extract the email addresses from a large 190GB flat file (only error log) that I cut into a 5mb files. (with 152,353,216 lines)

The grep command works well, but the memory quickly becomes saturated and I end up getting errors.

The content of the files is not formatted, so I have to use regexp.

grep -r -E -h -o "\b(pattern)\b" /dir/* > outs.txt

How to process files one by one?

Body:
The simplest (but probably not the quickest) way to process all the files would be to do so one by one, using a loop:

for file in /dir/*; do
  grep -r -E -h -o '\b(pattern)\b' "$file"
done > outs.txt

The overhead of launching all those greps is potentially quite significant, though, so maybe you could use xargs to help:

find /dir/ -maxdepth 1 -type f -print0 |
  xargs -0 -n 1000 grep -r -E -h -o '\b(pattern)\b' > outs.txt

This uses find to produce the list of files in dir and passes them safely to xargs, separated by a null byte \0 (a character guaranteed not to be in a filename). xargs then passes the files to grep in batches of 1000.

(I'm assuming that you have GNU versions of find and xargs here, for find -print0 and xargs -0)