问:
Filtering Data about Salary in pySpark
I've been struggling for so long with this, and I'd be happy if someone could help me find a resolve the next issue.

I have this table:

```<code>+-----+---+------------+
|index|  Salary        |
+-----+---+------------+
|    1|  200 - 300 PA. |
|    2|  400 PA.       |
|    3|  100 - 200 PA. |
|    4|  700 - 800 PA. |
+-----+---+-----+------+
</code>```

The salary column is String Type. I want to replace each String in the Salary, with the average of the range in contains (if no range, just the number) so the data will be numeric and not String. Want to create this table:

```<code>+-----+---+-------+
|index|  Salary   |
+-----+---+-------+
|    1|  250      |
|    2|  400      |
|    3|  150      |
|    4|  750      |
+-----+---+--+----+
</code>```

I tried doing it by first creating an array of the Salary so it looks like this:

```<code> ["100", "-", "300", "PA."] -
</code>```

so I could extract the number from the whole string. I tried this but it looks bad and it's not working:

```<code>curr = outDF.rdd.map(lambda rec: rec[:]).map(lambda rec : rec[0])
curr  = curr.map(lambda t : (t[1], t[3])).toDF()
new_df = curr.withColumn("_1", custProdSpending["_1"].cast(IntegerType()))
</code>```

答:
Use regex to clean, trun cleaned column into array and mean using reduce.Reduce does the same thing with aggregate. Code below</p>
```<code>actual_df = (df.withColumn("all_numbers",regexp_replace(F.col("Salary"), '\D[^\-]',''))#Replace all non alphanumeric characters except '-' with nothing
               .withColumn("all_numbers",split(col("all_numbers"),"\s"))#Create an array by spliting by space
               .withColumn('avg_all_numbers',F.expr("reduce(all_numbers, cast(0 as double), (x, i) -> x +i, x -> x / size(all_numbers))"))#Compute avarage using reduce
            )
actual_df.show()

+-----+-------------+-----------+---------------+
|index|       Salary|all_numbers|avg_all_numbers|
+-----+-------------+-----------+---------------+
|    1|200 - 300 PA.| [200, 300]|          250.0|
|    2|      400 PA.|      [400]|          400.0|
+-----+-------------+-----------+---------------+
</code>```

Title: Filtering Data about Salary in pySpark

Body:
I've been struggling for so long with this, and I'd be happy if someone could help me find a resolve the next issue.

I have this table:

+-----+---+------------+
|index|  Salary        |
+-----+---+------------+
|    1|  200 - 300 PA. |
|    2|  400 PA.       |
|    3|  100 - 200 PA. |
|    4|  700 - 800 PA. |
+-----+---+-----+------+

The salary column is String Type. I want to replace each String in the Salary, with the average of the range in contains (if no range, just the number) so the data will be numeric and not String. Want to create this table:

+-----+---+-------+
|index|  Salary   |
+-----+---+-------+
|    1|  250      |
|    2|  400      |
|    3|  150      |
|    4|  750      |
+-----+---+--+----+

I tried doing it by first creating an array of the Salary so it looks like this:

 ["100", "-", "300", "PA."] -

so I could extract the number from the whole string. I tried this but it looks bad and it's not working:

curr = outDF.rdd.map(lambda rec: rec[:]).map(lambda rec : rec[0])
curr  = curr.map(lambda t : (t[1], t[3])).toDF()
new_df = curr.withColumn("_1", custProdSpending["_1"].cast(IntegerType()))

Body:
Use regex to clean, trun cleaned column into array and mean using reduce.Reduce does the same thing with aggregate. Code below

actual_df = (df.withColumn("all_numbers",regexp_replace(F.col("Salary"), '\D[^\-]',''))#Replace all non alphanumeric characters except '-' with nothing
               .withColumn("all_numbers",split(col("all_numbers"),"\s"))#Create an array by spliting by space
               .withColumn('avg_all_numbers',F.expr("reduce(all_numbers, cast(0 as double), (x, i) -> x +i, x -> x / size(all_numbers))"))#Compute avarage using reduce
            )
actual_df.show()

+-----+-------------+-----------+---------------+
|index|       Salary|all_numbers|avg_all_numbers|
+-----+-------------+-----------+---------------+
|    1|200 - 300 PA.| [200, 300]|          250.0|
|    2|      400 PA.|      [400]|          400.0|
+-----+-------------+-----------+---------------+


来源: stackexchange

问:
Error in ifelse(new_lf$State %in% c("01", "02", "04", "05", "12", "13", : argument "yes" is missing, with no default
I'm trying to create the dummies for my data, the data I have is for 50 states in America and I want to set 25 states' dummy equals to 1 and the other 25 states' dummy equal 0, the code below is that I have now

```<code>project_path <- "C:/Users/85384/Desktop/Capstone"
setwd(project_path)
lf <- read_excel("Labor force data by county.xlsx")
new_lf <- na.omit(lf)
names(new_lf)[names(new_lf) == 'Column1'] <- 'LAUS_Area_Code'
names(new_lf)[names(new_lf) == 'Column2'] <- 'State'
names(new_lf)[names(new_lf) == 'Column3'] <- 'County'
names(new_lf)[names(new_lf) == 'Column4'] <- 'Area_Title'
names(new_lf)[names(new_lf) == 'Column5'] <- 'Period'
names(new_lf)[names(new_lf) == 'Column6'] <- 'Civilian_Labor_Force'
names(new_lf)[names(new_lf) == 'Column7'] <- 'Employed'
names(new_lf)[names(new_lf) == 'Column8'] <- 'Unemployed_level'
names(new_lf)[names(new_lf) == 'Column9'] <- 'Unemployed_rate'
View(new_lf)
is.data.frame(new_lf)
is.numeric(new_lf)

new_lf$early <- ifelse(new_lf$State %in%
c('01','02','04','05','12','13','16','18','19',
'24','28','29','30','31','33','38','39','40',
'46','45','47','48','49','54','56',1,0))
</code>```

And I got
"Error in ifelse(new_lf$State %in% c("01", "02", "04", "05", "12", "13",  :
argument "yes" is missing, with no default".
By the way, my dataset is a data frame but it's not numeric, I tried to make both data frame and numeric, but it did not work, that is why I put the numbers in quotations, and the numbers in quotations are represented as state FIPS code.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create the dummies for my data, the data I have is for 50 states in America and I want to set 25 states' dummy equals to 1 and the other 25 states' dummy equal 0, the code below is that I have now

project_path <- "C:/Users/85384/Desktop/Capstone"
setwd(project_path)
lf <- read_excel("Labor force data by county.xlsx")
new_lf <- na.omit(lf)
names(new_lf)[names(new_lf) == 'Column1'] <- 'LAUS_Area_Code'
names(new_lf)[names(new_lf) == 'Column2'] <- 'State'
names(new_lf)[names(new_lf) == 'Column3'] <- 'County'
names(new_lf)[names(new_lf) == 'Column4'] <- 'Area_Title'
names(new_lf)[names(new_lf) == 'Column5'] <- 'Period'
names(new_lf)[names(new_lf) == 'Column6'] <- 'Civilian_Labor_Force'
names(new_lf)[names(new_lf) == 'Column7'] <- 'Employed'
names(new_lf)[names(new_lf) == 'Column8'] <- 'Unemployed_level'
names(new_lf)[names(new_lf) == 'Column9'] <- 'Unemployed_rate'
View(new_lf)
is.data.frame(new_lf)
is.numeric(new_lf)

new_lf$early <- ifelse(new_lf$State %in%
c('01','02','04','05','12','13','16','18','19',
'24','28','29','30','31','33','38','39','40',
'46','45','47','48','49','54','56',1,0))

And I got
"Error in ifelse(new_lf$State %in% c("01", "02", "04", "05", "12", "13",  :
argument "yes" is missing, with no default".
By the way, my dataset is a data frame but it's not numeric, I tried to make both data frame and numeric, but it did not work, that is why I put the numbers in quotations, and the numbers in quotations are represented as state FIPS code.

Body:
You simply made a typo. It should be

new_lf$early <- ifelse(new_lf$State %in%
c('01','02','04','05','12','13','16','18','19',
'24','28','29','30','31','33','38','39','40',
'46','45','47','48','49','54','56'),1,0)

Note the placement of the parentheses.


问:
How to use Python to edit the text value of a line of code in Python file?
I have the following code in the file called stacktest.py inside my work folder in Visual Studio Code:

```<code>a = 'home'
b = 'hotel'
c = 'flat'

print(b)
</code>```

And I would like to use another Python file to edit this previous file, for example change:

```<code>b = 'hotel'
</code>```

For:

```<code>b = 'new value'
</code>```

So the new saved file would look like this:

```<code>a = 'home'
b = 'new value'
c = 'flat'

print(b)
</code>```

How should I go about doing this?

答:
You can, of course, do what you ask, as you presented:

```<code># read file and assign lines as list to variable stacktest_dict
#   stripping line feed from each line
with open('stacktest.py') as stacktest:
 stacktest_list = [line.strip() for line in stacktest.readlines()]

# replace string in chosen line with new string
for line in stacktest_list:
    if line == "b = 'hotel'":
        index = stacktest_list.index(line)
        line = line.replace('hotel', 'new value')
        stacktest_list[index] = line

# write lines with linefeeds added back to file
#  using an f-string
with open('stacktest.py', 'w') as stacktest:
    stacktest.writelines([f"{line}\n" for line in stacktest_list])
</code>```

This is a very basic, rudimentary solution, meant to show that it can be done.

However, Python offers much better, and much more efficient and performative approaches. Personally, assuming you are creating everything, and there aren't esoteric reasons for doing things as presented in the question, I'd use a dictionary, stored as JSON, along the following lines:

```<code># Create dict and write to file stacktest_dict.py
stacktest_list = {'a': 'home', 'b': 'hotel', 'c':'flat'}
with open('stacktest_dict.py', 'w') as stacktest_dict:
    json.dump(stacktest_list, stacktest_dict)

# read file and assign to variable stacktest_dict
with open('stacktest_dict.py', 'r') as stacktest_dict_in:
    stacktest_dict = json.load(stacktest_dict_in)

# assign new value for key 'b' in dict
stacktest_list['b'] = 'new value'

# write dict back to file
with open('stacktest_dict.py', 'w') as stacktest_dict:
    json.dump(stacktest_list, stacktest_dict)

# read file and assign to variable stacktest_dict
with open('stacktest_dict.py', 'r') as stacktest_dict_in:
    stacktest_dict = json.load(stacktest_dict_in)

# print the dict
print(stacktest_list)

# print the value of dict key 'b'
print(stacktest_list['b'])
</code>```

In this scenario, you are reading and writing a JSON file, and working with the data as a native object that Python understands (a dictionary). This approach will save you time, both personally and computationally, and headaches going forward.

The scenario you've suggested, I'd present, is a perfect case for using a dictionary, stored, and read, as JSON. For further reference, see:

https://docs.python.org/3/tutorial/datastructures.html#dictionaries

OwnerDisplayName: Brondby IF

Body:
I have the following code in the file called stacktest.py inside my work folder in Visual Studio Code:

a = 'home'
b = 'hotel'
c = 'flat'

print(b)

And I would like to use another Python file to edit this previous file, for example change:

b = 'hotel'

For:

b = 'new value'

So the new saved file would look like this:

a = 'home'
b = 'new value'
c = 'flat'

print(b)

How should I go about doing this?

Body:
You can, of course, do what you ask, as you presented:

# read file and assign lines as list to variable stacktest_dict
#   stripping line feed from each line
with open('stacktest.py') as stacktest:
 stacktest_list = [line.strip() for line in stacktest.readlines()]

# replace string in chosen line with new string
for line in stacktest_list:
    if line == "b = 'hotel'":
        index = stacktest_list.index(line)
        line = line.replace('hotel', 'new value')
        stacktest_list[index] = line

# write lines with linefeeds added back to file
#  using an f-string
with open('stacktest.py', 'w') as stacktest:
    stacktest.writelines([f"{line}\n" for line in stacktest_list])

This is a very basic, rudimentary solution, meant to show that it can be done.

However, Python offers much better, and much more efficient and performative approaches. Personally, assuming you are creating everything, and there aren't esoteric reasons for doing things as presented in the question, I'd use a dictionary, stored as JSON, along the following lines:

# Create dict and write to file stacktest_dict.py
stacktest_list = {'a': 'home', 'b': 'hotel', 'c':'flat'}
with open('stacktest_dict.py', 'w') as stacktest_dict:
    json.dump(stacktest_list, stacktest_dict)

# read file and assign to variable stacktest_dict
with open('stacktest_dict.py', 'r') as stacktest_dict_in:
    stacktest_dict = json.load(stacktest_dict_in)

# assign new value for key 'b' in dict
stacktest_list['b'] = 'new value'

# write dict back to file
with open('stacktest_dict.py', 'w') as stacktest_dict:
    json.dump(stacktest_list, stacktest_dict)

# read file and assign to variable stacktest_dict
with open('stacktest_dict.py', 'r') as stacktest_dict_in:
    stacktest_dict = json.load(stacktest_dict_in)

# print the dict
print(stacktest_list)

# print the value of dict key 'b'
print(stacktest_list['b'])

In this scenario, you are reading and writing a JSON file, and working with the data as a native object that Python understands (a dictionary). This approach will save you time, both personally and computationally, and headaches going forward.

The scenario you've suggested, I'd present, is a perfect case for using a dictionary, stored, and read, as JSON. For further reference, see:

https://docs.python.org/3/tutorial/datastructures.html#dictionaries


问:
Jquery get to another page
I know that there is simple solution which i know but i couldn't remember now.

I want to use get method of jquery but not asynchronous or synchronous. I want to post whole page.
Below i go to 'myurladress'.

```<code>$('<a>').attr('href','myurladress').trigger('click');
/// :) i want to achieve same effect but shortly :))
</code>```

答:
```<code>$("<a>").click(function(e){
e.preventDefault();  //prevent the default behaviour of the link
window.location="http://www.whereEverYouWntToGo.com";
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jquery get to another page

Body:
I know that there is simple solution which i know but i couldn't remember now.

I want to use get method of jquery but not asynchronous or synchronous. I want to post whole page.
Below i go to 'myurladress'.

$('').attr('href','myurladress').trigger('click');
/// :) i want to achieve same effect but shortly :))


问:
tick data at specific time in daylight saving timezone
I have a Synology NAS mariadb has huge tick data. I want to create a table with price at 16:00 US/Eastern everyday.

It is easy to get the table with ticks at 10:05 GMT everyday without timezone consideration:

```<code>SELECT
    TIMESTAMP,
    DATE(FROM_UNIXTIME(TIMESTAMP / 1000)) DATE,
    TIME(FROM_UNIXTIME(TIMESTAMP / 1000)) TIME,
    PRICE
FROM DATASET.TICK
WHERE
    # 10:05:00 <= GMT < 10:07:00
    MOD(TIMESTAMP, 86400000) >= 79500000
    AND
    MOD(TIMESTAMP, 86400000) <  79620000
GROUP BY DATE;
</code>```

seem the easiest way is to use mysql_tzinfo_to_sql then with CONVERT_TZ(Timestamp, 'UTC', 'US/Eastern'). But I have the command in my NAS.

```<code>-sh: mysql_tzinfo_to_sql: command not found
-sh: mariadb-tzinfo-to-sql: command not found
</code>```

Since there would be no data between 17:00 and 18:00 in US/Eastern, I might come up with a dumb and slow way to do it (maybe not in mysql). But I wish to see if there is any smarter way of doing it in my setup via mysql?

UPDATED v1:

For the mysql_tzinfo_to_sql: command not found issue. I have dealt with it with my Ubuntu machine.

Setup:

Synology NAS (ssh, mariadb)

Ubuntu machine (ssh, mysql-server-core-8.0, mysql client)

Steps:

copy zoneinfo directory from NAS to your machine: e.g.

scp -r user@192.168.1.2:/usr/share/zoneinfo ~/Documents

run the command in your machine and update the mysql database: e.g.

mysql_tzinfo_to_sql zoneinfo | mysql -u root -h 192.168.1.2 -p mysql

Now, CONVERT_TZ() can be used. Since 'US/Eastern' does not exist in timezone table, I had chosen America/New_York instead. So the straight conversion from my previous code became:

```<code>SELECT
    TIMESTAMP,
    DATE(CONVERT_TZ(FROM_UNIXTIME(TIMESTAMP / 1000), 'SYSTEM', 'America/New_York')) DATE,
    TIME(CONVERT_TZ(FROM_UNIXTIME(TIMESTAMP / 1000), 'SYSTEM', 'America/New_York')) TIME,
    PRICE
FROM DATASET.TICK
WHERE
    # 16:00:00 <= America/New_York < 16:00:05
    TIME(CONVERT_TZ(FROM_UNIXTIME(TIMESTAMP / 1000), 'SYSTEM', 'America/New_York')) BETWEEN CAST('16:00:00' AS TIME) AND CAST('16:00:05' AS TIME)
GROUP BY DATE, CODE
</code>```

TIME column can show 16:00 everyday. Although this part is solved, this works only for a small table and I now suffer from

error 1206: The number of locks exceeds the lock table size.

I can see this conversion is tedious and inefficient. However, my best guess or next move is to add Timezone based Date and Time columns to the table.

答:
Let's solve the second problem at the same time.

You want the last entry before, say, 10:07:00.  [Perhaps you meant 'pm'?]  That gets rid of the missing entry issue.  And the multiple entries in an artificial time range.

But it raises another ugly situation -- how to get not just the timestamp in that range and get it for every stock, but get the rest of each matching row.  That is a "groupwise-max" problem; see the tag I added.

Or see which of the efficient algorithms I describe in Groupwise-Max will suit your situation best.  Note, you will need to add an INDEX for any solution, and that operation will take a bunch of time.

You mentioned DST, but let's get rid of that by simply asking for the last entry before 23:59:59 for each day.  This assumes that you want the "market close" and that there are no trades after the close.  And it does not care if [the stupid] Daylight Savings is in effect.

Body:
I have a Synology NAS mariadb has huge tick data. I want to create a table with price at 16:00 US/Eastern everyday.

It is easy to get the table with ticks at 10:05 GMT everyday without timezone consideration:

SELECT
    TIMESTAMP,
    DATE(FROM_UNIXTIME(TIMESTAMP / 1000)) DATE,
    TIME(FROM_UNIXTIME(TIMESTAMP / 1000)) TIME,
    PRICE
FROM DATASET.TICK
WHERE
    # 10:05:00 <= GMT < 10:07:00
    MOD(TIMESTAMP, 86400000) >= 79500000
    AND
    MOD(TIMESTAMP, 86400000) <  79620000
GROUP BY DATE;

seem the easiest way is to use mysql_tzinfo_to_sql then with CONVERT_TZ(Timestamp, 'UTC', 'US/Eastern'). But I have the command in my NAS.

-sh: mysql_tzinfo_to_sql: command not found
-sh: mariadb-tzinfo-to-sql: command not found

Since there would be no data between 17:00 and 18:00 in US/Eastern, I might come up with a dumb and slow way to do it (maybe not in mysql). But I wish to see if there is any smarter way of doing it in my setup via mysql?

UPDATED v1:

For the mysql_tzinfo_to_sql: command not found issue. I have dealt with it with my Ubuntu machine.

Setup:

Synology NAS (ssh, mariadb)

Ubuntu machine (ssh, mysql-server-core-8.0, mysql client)

Steps:

copy zoneinfo directory from NAS to your machine: e.g.

scp -r user@192.168.1.2:/usr/share/zoneinfo ~/Documents

run the command in your machine and update the mysql database: e.g.

mysql_tzinfo_to_sql zoneinfo | mysql -u root -h 192.168.1.2 -p mysql

Now, CONVERT_TZ() can be used. Since 'US/Eastern' does not exist in timezone table, I had chosen America/New_York instead. So the straight conversion from my previous code became:

SELECT
    TIMESTAMP,
    DATE(CONVERT_TZ(FROM_UNIXTIME(TIMESTAMP / 1000), 'SYSTEM', 'America/New_York')) DATE,
    TIME(CONVERT_TZ(FROM_UNIXTIME(TIMESTAMP / 1000), 'SYSTEM', 'America/New_York')) TIME,
    PRICE
FROM DATASET.TICK
WHERE
    # 16:00:00 <= America/New_York < 16:00:05
    TIME(CONVERT_TZ(FROM_UNIXTIME(TIMESTAMP / 1000), 'SYSTEM', 'America/New_York')) BETWEEN CAST('16:00:00' AS TIME) AND CAST('16:00:05' AS TIME)
GROUP BY DATE, CODE

TIME column can show 16:00 everyday. Although this part is solved, this works only for a small table and I now suffer from

error 1206: The number of locks exceeds the lock table size.

I can see this conversion is tedious and inefficient. However, my best guess or next move is to add Timezone based Date and Time columns to the table.


问:
Why does Visual Studio compile my HTTP server app to run on port 5001 when I set it to 443/80?
Is there a separate place from launchsettings.json I need to set the applicationUrl?

Here's the launch setting

```<code>"applicationUrl": "https://127.0.0.1:443;http://127.0.0.1:80"
</code>```

Here's a picture of the app when running inside Visual Studio

Here's a picture of it running from the compiled exe (release & debug)

答:
launchSettings.json used during development, for example, run from the visual studio or using dotnet run command.

If you want to configure the URL when run compiled exe, could add this:

```<code>"Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://127.0.0.1:80"
      },
      "Https": {
        "Url": "https://127.0.0.1:443"
      }
    }
  }
</code>```

to the file appsettings.json or Program.cs.

Body:
Is there a separate place from launchsettings.json I need to set the applicationUrl?

Here's the launch setting

"applicationUrl": "https://127.0.0.1:443;http://127.0.0.1:80"

Here's a picture of the app when running inside Visual Studio

Here's a picture of it running from the compiled exe (release & debug)

Body:
launchSettings.json used during development, for example, run from the visual studio or using dotnet run command.

If you want to configure the URL when run compiled exe, could add this:

"Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://127.0.0.1:80"
      },
      "Https": {
        "Url": "https://127.0.0.1:443"
      }
    }
  }

to the file appsettings.json or Program.cs.


问:
How to display console.log to html with jQuery?
I am unable to show my input through html but it shows through console.log(). It is not showing up below on my list. My delete button also is not working as well. Not sure what is going on.

$(document).ready(function(){
  $('#addButton').click(function(){
    var task = $(".note").val();
    console.log(task);
    $(".todo-list").append('

<button id="delButton">Delete</button><button id="editButtton">Edit</button>

');
  });
});

$('#delButton').click(function(){
  var deleteNote = $('ul').children().length;
  $('ul').children()[deleteNote - 1].remove();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <header data-role="header"><h1>To Do List</h1>
    Home
  </header>

  <div role="main" class="todo-container">
      <div class="input">
        <input type="text" class="note" placeholder="Input new note..">
        <button id="addButton">Add</button>
    </div>
  </div>

<ul class="todo-list">
    <li>
        <div class ="button-center">
            <button id="delButton">Delete</button>
            <button id="editButtton">Edit</button>
        </div>
    </li>
</ul>
</body></code>```

答:
In the solution below, the task content is dynamically inserted into the HTML code; the easiest way to do this is to use `${variable}`. Improved the click event to delete the related
 element when the delete <button> is clicked.

$(document).ready(function(){
  $('#addButton').click(function() {
    var task = $(".note").val();

    /* New
 should not be added when task is not entered. */
    if(task.length == 0) {
      alert("Please enter a task.");
      return;
    }

    /* Task content is added to dynamic content. */
    $(".todo-list").append(`<li><span>Task: ${task}</span><div class="button-center"><button class="deleteButton">Delete</button><button class="editButtton">Edit</button></div></li>`);

    /* After clicking the Add button, the <input> element is cleared. */
    $(".note").val("");
  });

  /* Fires when clicking the <button> element with the ".deleteButton" class style applied. */
  $(document).on('click', '.deleteButton', function () {
      /* The two parents of the <button> element are the
 element. */
      $(this).parent().parent().remove();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}
ul {
  margin: 0;
  padding: 0;
}
ul li {
  cursor: pointer;
  position: relative;
  background: #eee;
  font-size: 18px;
  transition: 0.2s;
  user-select: none;
}
ul li:nth-child(odd) {
  background: #f9f9f9;
}
ul li:hover {
  background: #ddd;
}
button {
  margin-right: 10px;
}</code>```

    <input type="text" class="note" placeholder="Input new note..">
    <button id="addButton">Add</button>

```

Body:
I am unable to show my input through html but it shows through console.log(). It is not showing up below on my list. My delete button also is not working as well. Not sure what is going on.

$(document).ready(function(){
  $('#addButton').click(function(){
    var task = $(".note").val();
    console.log(task);
    $(".todo-list").append('

<button id="delButton">Delete</button><button id="editButtton">Edit</button>

');
  });
});

$('#delButton').click(function(){
  var deleteNote = $('ul').children().length;
  $('ul').children()[deleteNote - 1].remove();
});

To Do List

    Home

        <input type="text" class="note" placeholder="Input new note..">
        <button id="addButton">Add</button>

            <button id="delButton">Delete</button>
            <button id="editButtton">Edit</button>

Body:
In the solution below, the task content is dynamically inserted into the HTML code; the easiest way to do this is to use `${variable}`. Improved the click event to delete the related <li> element when the delete <button> is clicked.

$(document).ready(function(){
  $('#addButton').click(function() {
    var task = $(".note").val();

    /* New <li> should not be added when task is not entered. */
    if(task.length == 0) {
      alert("Please enter a task.");
      return;
    }

    /* Task content is added to dynamic content. */
    $(".todo-list").append(`<li><span>Task: ${task}</span><div class="button-center"><button class="deleteButton">Delete</button><button class="editButtton">Edit</button></div></li>`);

    /* After clicking the Add button, the <input> element is cleared. */
    $(".note").val("");
  });

  /* Fires when clicking the <button> element with the ".deleteButton" class style applied. */
  $(document).on('click', '.deleteButton', function () {
      /* The two parents of the <button> element are the <li> element. */
      $(this).parent().parent().remove();
  });
});

* {
  box-sizing: border-box;
}
ul {
  margin: 0;
  padding: 0;
}
ul li {
  cursor: pointer;
  position: relative;
  background: #eee;
  font-size: 18px;
  transition: 0.2s;
  user-select: none;
}
ul li:nth-child(odd) {
  background: #f9f9f9;
}
ul li:hover {
  background: #ddd;
}
button {
  margin-right: 10px;
}

<!-- jQuery Reference -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div role="main" class="todo-container">
  <div class="input">
    <input type="text" class="note" placeholder="Input new note..">
    <button id="addButton">Add</button>
  </div>

  <ul class="todo-list"></ul>
</div>


问:
Conditionally rendering when useEffect runs
I am making an application in which I am calling 2 APIS on one screen. I want to call the first one when the screen renders for the first time and set response to some state values when it's done I am starting a count down function for approximately 3mins and when the count down ends I am calling the second API with data which are fetched from the first one and repeat the same process again for another cont down and re-renders the screen but I don't want to run the first API every time when screen re-renders.
Currently, I don't have code with me so hope you understood my problem any help will be appreciated.

first api call

```<code>
const [stopTime, setStopTime] = useState('')

[period, setPeriod] = useState('')

const [minutes Left, setMinutes Left] = useState (null);

const [seconds Left, setSeconds Left]

= useState (null);

const [isTimeron, setTimeron] = useState (false);

const [issecondTime, setIsSecondTime] = useState(false) =

const userToken = user.userToken;

// console.log(userToken);

// function to get current period and result time
const getGameData = ({token}) => {

const formdata = new FormData();

formdata.append('token', token);

axios({

method: 'POST',

url: BASE_URL + '/color_game.php',

data: formdata,

}).then (res ⇒>{

//console.log('first ${res.data. response.currentTimer}

setPeriod (res.data. response.timerId);
setStopTime (res.data.response.currentTimer);

setIsSecond Time (true)

setTimeron (true);

}
</code>```

Second api call

```<code> const formdata = new FormData();

formdata.append('token', token);
 formdata.append('currentTimer', currentTimer);
formdata, append('timerId', timerId);

axios({

method: 'POST',

url: BASE_URL + '/color_game.php',

data: formdata,

}).then (res => {

// console.log('second");

console.log('second ${res.data.response.currentTimer} ');
if (res.data. response.timerId != null) {
 setStopTime (res.data. response.currentTimer);
setPeriod (res.data.response.timerId);
setTimeron (true);

} else {

console.log('nothing');

} });

};

</code>```

Cony down fuction

```<code>const countdown = () => {
if(isTimerOn){

var resultTime = new Date stopTime).getTime();

const time Interval=setInterval (() => {

var now = new Date().getTime();

var duration = resultTime - now; console.log(duration);

setMinutes Left (Math.floor( (duration % (1000 * 60

setSeconds Left (Math.floor( (duration % (1000 * 60)

if (duration <= 0) {
clearInterval (timeInterval);

getGameDataSecondTime ({

token: userToken, timerId: period,

currentTimer: stopTime,

});

}

}, 1000);

}

};
</code>```

答:
You can handle 2 different actions in the same process using closure concept.

Here's an example (dependency is the trigger which could be a state value inside a timeout or anything):

```<code>import { useEffect } from 'react';

// First fetch function
const firstFetch=async()=>{};
// Second fetch function
const anotherFetch=async()=>{};

// An IIFE to handle the closure easily
const fetchFunction = (()=>{
  let firstTimeCall=true;

  // fetchFunction will be the below returned function with a closure(firstTimeCall)
  return ()=>{
    if(firstTimeCall){
      firstFetch();
      firstTimeCall=false;
    }else{
      anotherFetch();
    }
  }

})();

const MyComponent = () => {
  useEffect(() => {
    fetchFunction()
  }, [dependency]);

  return (....)
};
</code>```

Body:
I am making an application in which I am calling 2 APIS on one screen. I want to call the first one when the screen renders for the first time and set response to some state values when it's done I am starting a count down function for approximately 3mins and when the count down ends I am calling the second API with data which are fetched from the first one and repeat the same process again for another cont down and re-renders the screen but I don't want to run the first API every time when screen re-renders.
Currently, I don't have code with me so hope you understood my problem any help will be appreciated.

first api call

const [stopTime, setStopTime] = useState('')

[period, setPeriod] = useState('')

const [minutes Left, setMinutes Left] = useState (null);

const [seconds Left, setSeconds Left]

= useState (null);

const [isTimeron, setTimeron] = useState (false);

const [issecondTime, setIsSecondTime] = useState(false) =

const userToken = user.userToken;

// console.log(userToken);

// function to get current period and result time
const getGameData = ({token}) => {

const formdata = new FormData();

formdata.append('token', token);

axios({

method: 'POST',

url: BASE_URL + '/color_game.php',

data: formdata,

}).then (res ⇒>{

//console.log('first ${res.data. response.currentTimer}

setPeriod (res.data. response.timerId);
setStopTime (res.data.response.currentTimer);

setIsSecond Time (true)

setTimeron (true);

}

Second api call

 const formdata = new FormData();

formdata.append('token', token);
 formdata.append('currentTimer', currentTimer);
formdata, append('timerId', timerId);

axios({

method: 'POST',

url: BASE_URL + '/color_game.php',

data: formdata,

}).then (res => {

// console.log('second");

console.log('second ${res.data.response.currentTimer} ');
if (res.data. response.timerId != null) {
 setStopTime (res.data. response.currentTimer);
setPeriod (res.data.response.timerId);
setTimeron (true);

} else {

console.log('nothing');

} });

};

Cony down fuction

const countdown = () => {
if(isTimerOn){

var resultTime = new Date stopTime).getTime();

const time Interval=setInterval (() => {

var now = new Date().getTime();

var duration = resultTime - now; console.log(duration);

setMinutes Left (Math.floor( (duration % (1000 * 60

setSeconds Left (Math.floor( (duration % (1000 * 60)

if (duration <= 0) {
clearInterval (timeInterval);

getGameDataSecondTime ({

token: userToken, timerId: period,

currentTimer: stopTime,

});

}

}, 1000);

}

};

Body:
You can handle 2 different actions in the same process using closure concept.

Here's an example (dependency is the trigger which could be a state value inside a timeout or anything):

import { useEffect } from 'react';

// First fetch function
const firstFetch=async()=>{};
// Second fetch function
const anotherFetch=async()=>{};

// An IIFE to handle the closure easily
const fetchFunction = (()=>{
  let firstTimeCall=true;

  // fetchFunction will be the below returned function with a closure(firstTimeCall)
  return ()=>{
    if(firstTimeCall){
      firstFetch();
      firstTimeCall=false;
    }else{
      anotherFetch();
    }
  }

})();

const MyComponent = () => {
  useEffect(() => {
    fetchFunction()
  }, [dependency]);

  return (....)
};


问:
Google AdMob iOS - No Ads to Show
I am facing this issue for very long time now.

Test Ads Appearing on Simulator and Actual Phone.

Implementation is Correct and Latest.

AdMob Account is approved, payment info added.

App is also live as well.

Still saying no No Ads to Show. Please help me on this.

Here is code functions

```<code>func addBannerViewToView(_ bannerView: GADBannerView) {
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bannerView)
    view.addConstraints(
        [NSLayoutConstraint(item: bannerView,
                            attribute: .bottom,
                            relatedBy: .equal,
                            toItem: bottomLayoutGuide,
                            attribute: .top,
                            multiplier: 1,
                            constant: 0),
         NSLayoutConstraint(item: bannerView,
                            attribute: .centerX,
                            relatedBy: .equal,
                            toItem: view,
                            attribute: .centerX,
                            multiplier: 1,
                            constant: 0)
    ])
}
</code>```

I Tried this as well instead of adSize

```<code> let request = GADRequest()
    //request.testDevices = ["e217e5a45bc6b1042b5ea044243894c0" ]
</code>```

//        GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = [(kGADSimulatorID as! String)]

//        let bannerSize = UIDevice.current.isPad ? kGADAdSizeFullBanner : kGADAdSizeBanner

```<code>let adSize = GADAdSizeFromCGSize(CGSize(width: UIScreen.main.bounds.width,
                                            height: UIDevice.current.isPad ? 90 : 50))

    banner = GADBannerView(adSize: adSize)
    addBannerViewToView(banner)
    banner.adUnitID = AD_MOB_BANNER
    banner.rootViewController = self
    banner.delegate = self
    banner.load(request)
</code>```

答:
Seems like it was a Google Ads issue. My Code was correct and ads started appearing. It took time but ads started appearing.

Hope this helps. You can reach out to me if you are facing similar issue

Title: Google AdMob iOS - No Ads to Show

Body:
I am facing this issue for very long time now.

Test Ads Appearing on Simulator and Actual Phone.

Implementation is Correct and Latest.

AdMob Account is approved, payment info added.

App is also live as well.

Still saying no No Ads to Show. Please help me on this.

Here is code functions

func addBannerViewToView(_ bannerView: GADBannerView) {
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bannerView)
    view.addConstraints(
        [NSLayoutConstraint(item: bannerView,
                            attribute: .bottom,
                            relatedBy: .equal,
                            toItem: bottomLayoutGuide,
                            attribute: .top,
                            multiplier: 1,
                            constant: 0),
         NSLayoutConstraint(item: bannerView,
                            attribute: .centerX,
                            relatedBy: .equal,
                            toItem: view,
                            attribute: .centerX,
                            multiplier: 1,
                            constant: 0)
    ])
}

I Tried this as well instead of adSize

 let request = GADRequest()
    //request.testDevices = ["e217e5a45bc6b1042b5ea044243894c0" ]

//        GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = [(kGADSimulatorID as! String)]

//        let bannerSize = UIDevice.current.isPad ? kGADAdSizeFullBanner : kGADAdSizeBanner

let adSize = GADAdSizeFromCGSize(CGSize(width: UIScreen.main.bounds.width,
                                            height: UIDevice.current.isPad ? 90 : 50))

    banner = GADBannerView(adSize: adSize)
    addBannerViewToView(banner)
    banner.adUnitID = AD_MOB_BANNER
    banner.rootViewController = self
    banner.delegate = self
    banner.load(request)


问:
Allowing user to select text in word vba macro
In VBA for Word 2007, I want to be able to open a document, highlight sections of text and replace those sections with fields linked to a docvariables. The process would be:

Open document.

Select text.

Select docvariable from list.

Insert field linked to selected docvariable.

Repeat steps 1-4 as required.

There is no way to know beforehand what the text to be selected is or which docvariable is going to be linked to which field or how many times these steps are going to be repeated.

Only with Microsoft could the most absolutely fundamental, simple task of allowing the user to make a selection at run-time and pass this selection back to sub-routine be so tortuous and surreal. I have spent 2 days trying to figure this out. If anyone can help, I will name my next child after you.

答:
I think "tortuous and surreal" is a misconception.

Create a small form with a dropdown (named "selVarName", for example) that lets you select all document variable names available. Link the form to a custom button in the Quick Access Toolbar.

Upon clicking "OK" in this form do something like this:

```<code>Private Sub btnOK_Click()
  Dim v As Word.Variable
  Dim n As String

  n = Me.selVarName.Value
  With Selection
    For Each v In .Document.Variables
      If v.Name = n Then v.Delete: Exit For
    Next v
    .Document.Variables.Add n, .Range.Text
  End With
End Sub
</code>```

And this has bells and whistles already. You can do additional checking like "no text selected", for example.

OwnerDisplayName: david

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Tomalak

Body:
I think "tortuous and surreal" is a misconception.

Create a small form with a dropdown (named "selVarName", for example) that lets you select all document variable names available. Link the form to a custom button in the Quick Access Toolbar.

Upon clicking "OK" in this form do something like this:

Private Sub btnOK_Click()
  Dim v As Word.Variable
  Dim n As String

  n = Me.selVarName.Value
  With Selection
    For Each v In .Document.Variables
      If v.Name = n Then v.Delete: Exit For
    Next v
    .Document.Variables.Add n, .Range.Text
  End With
End Sub

And this has bells and whistles already. You can do additional checking like "no text selected", for example.

OwnerDisplayName: Tomalak


问:
Lightweight Delaunay trianguation library (for c++)
I'd like to play around with some (2D) Delaunay triangulations, and am looking for a reasonably small library to work with.  I'm aware of CGAL, but I was wondering if there was something fairly simple and straightforward out there.

Things I would like to do:

create a triangulation of an arbitrary set of points

find triangle an arbitrary point is in, and fetch the vertices

create an image of the triangulation (optional)

Suggestions?

答: I've used the Gnu Triangulated Surface library for 2D Delaunay triangulation and it worked well.  Slightly strange to call because it uses that OOP-in-C GLib style, but it can easily be wrapped up.</p>


问:
Trying to read JSON from URL and parse into CSV format
I am trying to loop through four URLs in a list, scrape the contents of each URL, and save each as a separate CSV. I think my code below is close, but it doesn't really seem to parse the JSON strings into a human-readable format. Also, the headers are missing.

Here is my hacked together code.

```<code>import urllib
import requests
import json
import pandas as pd
from pandas.io.json import json_normalize

all_links = ['https://www.baptisthealthsystem.com/docs/global/standard-charges/474131755_abrazomaranahospital_standardcharges.json?sfvrsn=9a27928_2',
  'https://www.baptisthealthsystem.com/docs/global/standard-charges/621861138_abrazocavecreekhospital_standardcharges.json?sfvrsn=674fd6f_2',
  'https://www.baptisthealthsystem.com/docs/global/standard-charges/621809851_abrazomesahospital_standardcharges.json?sfvrsn=13953222_2',
  'https://www.baptisthealthsystem.com/docs/global/standard-charges/621811285_abrazosurprisehospital_standardcharges.json?sfvrsn=c8113dcf_2']
for item in all_links:
    #print(item)
    try:
        length = len(item)
        first_under = item.find('_') + 1
        last_under = item.rfind('?') - 21
        file_name = item[first_under:last_under]
        r = requests.get(item)
        print(r.json)
        df = pd.DataFrame(r)
        df.head()
        DOWNLOAD_PATH = 'C:\\Users\\ryans\\Desktop\\hospital_data\\' + file_name + '.csv'
        #urllib.request.urlretrieve(df,DOWNLOAD_PATH)
        r = requests.get(item)
        with open(DOWNLOAD_PATH,'wb') as f:
            f.write(r.content)
    except Exception as e: print(e)

</code>```

This is what the data looks like. Is this right? I thought the data would look a lot cleaner if it was converted from JSON to CSV.

答:
I am not sure if you are asking for opinion. Is CSV necessary? Or are you just trying to save it in a readable (and preferrably, programmably extractable) format?

Anyways, here is the way to export one result to a .csv file:

# Required imports
import json
import csv

"""I am assuming you already made the request and got the response"""
data_set = r.json()   # An iterable of python dict objects
DOWNLOAD_PATH = 'C:\\Users\\ryans\\Desktop\\hospital_data\\' + file_name + '.csv'
# (Please take enough care to not reveal personal info above)

# getting the headers
headers = data_set[0].keys()

with open(DOWNLOAD_PATH, "wt", newline="") as file:
    writer = csv.writer(file)

    writer.writerow(headers)    # writing the headers

    for data in data_set:    # writing the values
        write.writerow(data.values())
```
<hr>
<p>And here is the way to export one result to a <code>.json</code> file:</p>
<pre class="lang-py prettyprint-override"><code>import json

data_set = r.json()
DOWNLOAD_PATH = 'C:\\Users\\ryans\\Desktop\\hospital_data\\' + file_name + '.json'

with open(DOWNLOAD_PATH, "wt") as file:
    json.dump(data_set, file)
</code>```

You can use whichever file is more readable to you. Note that the above methods were for a single request result. You will have to do the above for each result you extract from the website.

Credits for the CSV method: GeeksforGeeks

Body:
I am trying to loop through four URLs in a list, scrape the contents of each URL, and save each as a separate CSV. I think my code below is close, but it doesn't really seem to parse the JSON strings into a human-readable format. Also, the headers are missing.

Here is my hacked together code.

import urllib
import requests
import json
import pandas as pd
from pandas.io.json import json_normalize

all_links = ['https://www.baptisthealthsystem.com/docs/global/standard-charges/474131755_abrazomaranahospital_standardcharges.json?sfvrsn=9a27928_2',
  'https://www.baptisthealthsystem.com/docs/global/standard-charges/621861138_abrazocavecreekhospital_standardcharges.json?sfvrsn=674fd6f_2',
  'https://www.baptisthealthsystem.com/docs/global/standard-charges/621809851_abrazomesahospital_standardcharges.json?sfvrsn=13953222_2',
  'https://www.baptisthealthsystem.com/docs/global/standard-charges/621811285_abrazosurprisehospital_standardcharges.json?sfvrsn=c8113dcf_2']
for item in all_links:
    #print(item)
    try:
        length = len(item)
        first_under = item.find('_') + 1
        last_under = item.rfind('?') - 21
        file_name = item[first_under:last_under]
        r = requests.get(item)
        print(r.json)
        df = pd.DataFrame(r)
        df.head()
        DOWNLOAD_PATH = 'C:\\Users\\ryans\\Desktop\\hospital_data\\' + file_name + '.csv'
        #urllib.request.urlretrieve(df,DOWNLOAD_PATH)
        r = requests.get(item)
        with open(DOWNLOAD_PATH,'wb') as f:
            f.write(r.content)
    except Exception as e: print(e)

This is what the data looks like. Is this right? I thought the data would look a lot cleaner if it was converted from JSON to CSV.

Body:
I am not sure if you are asking for opinion. Is CSV necessary? Or are you just trying to save it in a readable (and preferrably, programmably extractable) format?

Anyways, here is the way to export one result to a .csv file:

# Required imports
import json
import csv

"""I am assuming you already made the request and got the response"""
data_set = r.json()   # An iterable of python dict objects
DOWNLOAD_PATH = 'C:\\Users\\ryans\\Desktop\\hospital_data\\' + file_name + '.csv'
# (Please take enough care to not reveal personal info above)

# getting the headers
headers = data_set[0].keys()

with open(DOWNLOAD_PATH, "wt", newline="") as file:
    writer = csv.writer(file)

    writer.writerow(headers)    # writing the headers

    for data in data_set:    # writing the values
        write.writerow(data.values())

And here is the way to export one result to a .json file:

import json

data_set = r.json()
DOWNLOAD_PATH = 'C:\\Users\\ryans\\Desktop\\hospital_data\\' + file_name + '.json'

with open(DOWNLOAD_PATH, "wt") as file:
    json.dump(data_set, file)

You can use whichever file is more readable to you. Note that the above methods were for a single request result. You will have to do the above for each result you extract from the website.

Credits for the CSV method: GeeksforGeeks


答:
You are close, here's what you need to change:

You can use pandas dataframes to read json using df = pd.read_json(text, lines=True) - for this make sure to specify lines=True because some of your data contains \n characters

You can use the same dataframe to output to a csv using df.to_csv(file)

All in all, there are some things in your code that could be removed, e.g. you're calling requests.get twice for no real reason, which slows your code down substantially.

import requests
import pandas as pd

all_links = ['https://www.baptisthealthsystem.com/docs/global/standard-charges/474131755_abrazomaranahospital_standardcharges.json?sfvrsn=9a27928_2',
  'https://www.baptisthealthsystem.com/docs/global/standard-charges/621861138_abrazocavecreekhospital_standardcharges.json?sfvrsn=674fd6f_2',
  'https://www.baptisthealthsystem.com/docs/global/standard-charges/621809851_abrazomesahospital_standardcharges.json?sfvrsn=13953222_2',
  'https://www.baptisthealthsystem.com/docs/global/standard-charges/621811285_abrazosurprisehospital_standardcharges.json?sfvrsn=c8113dcf_2']
for item in all_links:
    try:
        length = len(item)
        first_under = item.find('_') + 1
        last_under = item.rfind('?') - 21
        file_name = item[first_under:last_under]
        r = requests.get(item)
        df = pd.read_json(r.text, lines=True)
        DOWNLOAD_PATH = 'C:\\Users\\ryans\\Desktop\\hospital_data\\' + file_name + '.csv'
        with open(DOWNLOAD_PATH,'wb') as f:
            df.to_csv(f)
    except Exception as e: print(e)
```

Title: Trying to read JSON from URL and parse into CSV format


问:
flutter: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() Other responses are not helping me out
I tried using an answer to the same question but I am not sure what else I have to do in my case

```<code>import 'package:auduo/routes/routes.dart';
import 'package:auduo/opening_Screen.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: AppRoutes.define(),
      home: OpeningScreen(),
    );
  }
}
</code>```

Let me know if you need to see other .dart files

Below is the Requested Code From The Comments

```<code>import 'package:flutter/material.dart';
import 'package:auduo/routes/routes.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
// Bleyl Dev Vid 2 - 7:49

class Register extends StatefulWidget {
  @override
  _RegisterViewState createState() => _RegisterViewState();
}

class _RegisterViewState extends State<Register> {
  final _formKey = GlobalKey<FormState>();
  TextEditingController _usernameController = TextEditingController();
  TextEditingController _emailController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  TextEditingController _repasswordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final mq = MediaQuery.of(context);

    final logo = Image.asset(
      "assets/Auduo Logo V 1.0.png",
      height: mq.size.height / 4,
    );

    final usernameField = TextFormField(
      controller: _usernameController,
      style: TextStyle(color: Colors.white),
      cursorColor: Colors.white,
      decoration: InputDecoration(
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.yellow),
        ),
        hintText: "NiceSound259",
        labelText: "Username",
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(
          color: Colors.white,
        ),
      ),
    );

    final emailField = TextFormField(
      controller: _emailController,
      keyboardType: TextInputType.emailAddress,
      style: TextStyle(color: Colors.white),
      cursorColor: Colors.white,
      decoration: InputDecoration(
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.yellow),
        ),
        hintText: "Something@example.com",
        labelText: "Email",
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(
          color: Colors.white,
        ),
      ),
    );

    final passwordField = TextFormField(
      obscureText: true,
      controller: _passwordController,
      style: TextStyle(color: Colors.white),
      cursorColor: Colors.white,
      decoration: InputDecoration(
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.yellow),
        ),
        hintText: "password",
        labelText: "Password",
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(
          color: Colors.white,
        ),
      ),
    );

    final repasswordField = TextFormField(
      obscureText: true,
      controller: _repasswordController,
      style: TextStyle(color: Colors.white),
      cursorColor: Colors.white,
      decoration: InputDecoration(
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.yellow),
        ),
        hintText: "re-enter password",
        labelText: "Re-Enter Password",
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(
          color: Colors.white,
        ),
      ),
    );

    final fields = Padding(
      padding: EdgeInsets.only(top: 10.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          usernameField,
          emailField,
          passwordField,
          repasswordField
        ],
      ),
    );

    final registerButton = Material(
      elevation: 5,
      borderRadius: BorderRadius.circular(25),
      color: Colors.white,
      child: MaterialButton(
        minWidth: mq.size.width / 1.2,
        padding: EdgeInsets.fromLTRB(10, 15, 10, 15),
        child: Text(
          "Register",
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 20,
            color: Colors.black,
            fontWeight: FontWeight.bold,
          ),
        ),
        onPressed: () async {
          try {
            User user =
                (await FirebaseAuth.instance.createUserWithEmailAndPassword(
              email: _emailController.text,
              password: _passwordController.text,
            )) as User;
            if (user != null) {
              user.updateDisplayName(_usernameController.text);
              Navigator.of(context).pushNamed(AppRoutes.home);
            }
          } catch (e) {
            print(e);
            _usernameController.text = "";
            _passwordController.text = "";
            _repasswordController.text = "";
            _emailController.text = "";
            //TODO alert dialog with error
          }
        },
      ),
    );

    final bottom = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        //loginButton,
        Padding(
          padding: EdgeInsets.all(8.0),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              "Already have an account?",
              style: Theme.of(context).textTheme.subtitle1?.copyWith(
                    color: Colors.white,
                  ),
            ),
            MaterialButton(
              onPressed: () {
                Navigator.of(context).pushNamed(AppRoutes.authLogin);
              },
              child: Text(
                "Sign In",
                style: Theme.of(context).textTheme.subtitle1?.copyWith(
                      color: Colors.white,
                      decoration: TextDecoration.underline,
                    ),
              ),
            ),
          ],
        ),
      ],
    );

    return Scaffold(
      backgroundColor: Colors.black,
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: EdgeInsets.all(36),
          child: Container(
            height: mq.size.height,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                logo,
                fields,
                registerButton,
                Padding(
                  padding: EdgeInsets.only(bottom: 150),
                  child: bottom,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

Above is the Requested Code From The Comments,
This is the register.dart code the functions are pretty similar to login.dart so hopefully this is enough.

答:
Try running flutter clean and run the app again. another known fix would be to add the optional parameters name and options to the

```<code>await Firebase.initializeApp(name: ....., options: .....)
</code>```

You could also try to minimally reproduce the error by creating the default counter app, add firebase initializations and see if the error persists.

Body:
I tried using an answer to the same question but I am not sure what else I have to do in my case

import 'package:auduo/routes/routes.dart';
import 'package:auduo/opening_Screen.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: AppRoutes.define(),
      home: OpeningScreen(),
    );
  }
}

Let me know if you need to see other .dart files

Below is the Requested Code From The Comments

import 'package:flutter/material.dart';
import 'package:auduo/routes/routes.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
// Bleyl Dev Vid 2 - 7:49

class Register extends StatefulWidget {
  @override
  _RegisterViewState createState() => _RegisterViewState();
}

class _RegisterViewState extends State<Register> {
  final _formKey = GlobalKey<FormState>();
  TextEditingController _usernameController = TextEditingController();
  TextEditingController _emailController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  TextEditingController _repasswordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final mq = MediaQuery.of(context);

    final logo = Image.asset(
      "assets/Auduo Logo V 1.0.png",
      height: mq.size.height / 4,
    );

    final usernameField = TextFormField(
      controller: _usernameController,
      style: TextStyle(color: Colors.white),
      cursorColor: Colors.white,
      decoration: InputDecoration(
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.yellow),
        ),
        hintText: "NiceSound259",
        labelText: "Username",
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(
          color: Colors.white,
        ),
      ),
    );

    final emailField = TextFormField(
      controller: _emailController,
      keyboardType: TextInputType.emailAddress,
      style: TextStyle(color: Colors.white),
      cursorColor: Colors.white,
      decoration: InputDecoration(
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.yellow),
        ),
        hintText: "Something@example.com",
        labelText: "Email",
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(
          color: Colors.white,
        ),
      ),
    );

    final passwordField = TextFormField(
      obscureText: true,
      controller: _passwordController,
      style: TextStyle(color: Colors.white),
      cursorColor: Colors.white,
      decoration: InputDecoration(
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.yellow),
        ),
        hintText: "password",
        labelText: "Password",
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(
          color: Colors.white,
        ),
      ),
    );

    final repasswordField = TextFormField(
      obscureText: true,
      controller: _repasswordController,
      style: TextStyle(color: Colors.white),
      cursorColor: Colors.white,
      decoration: InputDecoration(
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.yellow),
        ),
        hintText: "re-enter password",
        labelText: "Re-Enter Password",
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(
          color: Colors.white,
        ),
      ),
    );

    final fields = Padding(
      padding: EdgeInsets.only(top: 10.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          usernameField,
          emailField,
          passwordField,
          repasswordField
        ],
      ),
    );

    final registerButton = Material(
      elevation: 5,
      borderRadius: BorderRadius.circular(25),
      color: Colors.white,
      child: MaterialButton(
        minWidth: mq.size.width / 1.2,
        padding: EdgeInsets.fromLTRB(10, 15, 10, 15),
        child: Text(
          "Register",
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 20,
            color: Colors.black,
            fontWeight: FontWeight.bold,
          ),
        ),
        onPressed: () async {
          try {
            User user =
                (await FirebaseAuth.instance.createUserWithEmailAndPassword(
              email: _emailController.text,
              password: _passwordController.text,
            )) as User;
            if (user != null) {
              user.updateDisplayName(_usernameController.text);
              Navigator.of(context).pushNamed(AppRoutes.home);
            }
          } catch (e) {
            print(e);
            _usernameController.text = "";
            _passwordController.text = "";
            _repasswordController.text = "";
            _emailController.text = "";
            //TODO alert dialog with error
          }
        },
      ),
    );

    final bottom = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        //loginButton,
        Padding(
          padding: EdgeInsets.all(8.0),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              "Already have an account?",
              style: Theme.of(context).textTheme.subtitle1?.copyWith(
                    color: Colors.white,
                  ),
            ),
            MaterialButton(
              onPressed: () {
                Navigator.of(context).pushNamed(AppRoutes.authLogin);
              },
              child: Text(
                "Sign In",
                style: Theme.of(context).textTheme.subtitle1?.copyWith(
                      color: Colors.white,
                      decoration: TextDecoration.underline,
                    ),
              ),
            ),
          ],
        ),
      ],
    );

    return Scaffold(
      backgroundColor: Colors.black,
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: EdgeInsets.all(36),
          child: Container(
            height: mq.size.height,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                logo,
                fields,
                registerButton,
                Padding(
                  padding: EdgeInsets.only(bottom: 150),
                  child: bottom,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Above is the Requested Code From The Comments,
This is the register.dart code the functions are pretty similar to login.dart so hopefully this is enough.

Body:
Try running flutter clean and run the app again. another known fix would be to add the optional parameters name and options to the

await Firebase.initializeApp(name: ....., options: .....)

You could also try to minimally reproduce the error by creating the default counter app, add firebase initializations and see if the error persists.


问:
Java Jar run as Daemon cant issue exec()
I have a java socket server I wrote to allow me to keep a web clusters code base in sync. When I run the init.d script from a shell login like so

```<code>[root@web11 www]# /etc/init.d/servermngr start
</code>```

Logout and all will work fine but if the server reboots or I run the init.d using services like so

```<code>[root@web11 www]# service servermngr start
</code>```

Any of the exec() commands passed to the socket server will not get executed on the linux box. I am assuming it has to do with the JVM having no real shell.  If I login and run

```<code>[root@web11 www]# /etc/init.d/servermngr start
</code>```

...and logout all runs nice all CVS commands are executed.

Another note when run as a service the socket server responds to status checks so it is running

Here is the init.d script

```<code>#!/bin/sh
# chkconfig: 2345 95 1
# description: Starts Daemon Using ServerManager.jar.
#
# Source function library.
. /etc/init.d/functions

start () {
    echo -n $"Starting ServerManager: "

    # start daemon
    cd /www/servermanager/
    daemon java -jar ServerManager.jar > /www/logs/ServerManager.log &
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch /var/lock/subsys/cups
    echo "";
    return $RETVAL
}

stop () {
    # stop daemon
    echo -n $"Stopping $prog: "
    kill `ps uax | grep -i "java -jar ServerManager.ja[r]" | head -n 1 | awk '{print $2}'`
    RETVAL=$?
    echo "";
    return $RETVAL
}

restart() {
    stop
    start
}

case $1 in
    start)
        start
    ;;
    stop)
        stop
    ;;
    *)

    echo $"Usage: servermngr {start|stop}"
    exit 3
esac

exit $RETVAL
</code>```

And the Java responsible for actually executing the code:

```<code>// Build cmd Array of Strings
            String[] cmd = {"/bin/sh", "-c", "cd /www;cvs up -d htdocs/;cvs up -d phpinclude/"};
            final Process process;
            try {
                process = Runtime.getRuntime().exec(cmd);

                BufferedReader buf = new BufferedReader(new InputStreamReader(
                        process.getInputStream()));

                // Since this is a CVS UP we return the Response to PHP
                if(input.matches(".*(cvs up).*")){
                    String line1;
                    out.println("cvsupdate-start");
                    System.out.println("CVS Update" + input);
                    while ((line1 = buf.readLine()) != null) {
                        out.println(line1);
                        System.out.println("CVS:" + line1);
                    }
                    out.println("cvsupdate-end");
                }

            } catch (IOException ex) {
                System.out.println("IOException on Run cmd " + CommandFactory.class.getName() + " " + ex);
                Logger.getLogger(CommandFactory.class.getName()).log(Level.SEVERE, null, ex);
            }
</code>```

Thx for any help

答: Are you starting the process as root?  What version of (bash?) is running on the system?  You may want to give csh a whirl just to rule out issues with the shell itself.  I'd also suggest chaining the commands with '&' instead of ';'.  Finally you may find it easier to create a shell script which contains all your commands and is called by your java process.  You may also want to investigate nohup and check /etc/security/limits</p>

Body:
I have a java socket server I wrote to allow me to keep a web clusters code base in sync. When I run the init.d script from a shell login like so

[root@web11 www]# /etc/init.d/servermngr start

Logout and all will work fine but if the server reboots or I run the init.d using services like so

[root@web11 www]# service servermngr start

Any of the exec() commands passed to the socket server will not get executed on the linux box. I am assuming it has to do with the JVM having no real shell.  If I login and run

[root@web11 www]# /etc/init.d/servermngr start

...and logout all runs nice all CVS commands are executed.

Another note when run as a service the socket server responds to status checks so it is running

Here is the init.d script

#!/bin/sh
# chkconfig: 2345 95 1
# description: Starts Daemon Using ServerManager.jar.
#
# Source function library.
. /etc/init.d/functions

start () {
    echo -n $"Starting ServerManager: "

    # start daemon
    cd /www/servermanager/
    daemon java -jar ServerManager.jar > /www/logs/ServerManager.log &
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch /var/lock/subsys/cups
    echo "";
    return $RETVAL
}

stop () {
    # stop daemon
    echo -n $"Stopping $prog: "
    kill `ps uax | grep -i "java -jar ServerManager.ja[r]" | head -n 1 | awk '{print $2}'`
    RETVAL=$?
    echo "";
    return $RETVAL
}

restart() {
    stop
    start
}

case $1 in
    start)
        start
    ;;
    stop)
        stop
    ;;
    *)

    echo $"Usage: servermngr {start|stop}"
    exit 3
esac

exit $RETVAL

And the Java responsible for actually executing the code:

// Build cmd Array of Strings
            String[] cmd = {"/bin/sh", "-c", "cd /www;cvs up -d htdocs/;cvs up -d phpinclude/"};
            final Process process;
            try {
                process = Runtime.getRuntime().exec(cmd);

                BufferedReader buf = new BufferedReader(new InputStreamReader(
                        process.getInputStream()));

                // Since this is a CVS UP we return the Response to PHP
                if(input.matches(".*(cvs up).*")){
                    String line1;
                    out.println("cvsupdate-start");
                    System.out.println("CVS Update" + input);
                    while ((line1 = buf.readLine()) != null) {
                        out.println(line1);
                        System.out.println("CVS:" + line1);
                    }
                    out.println("cvsupdate-end");
                }

            } catch (IOException ex) {
                System.out.println("IOException on Run cmd " + CommandFactory.class.getName() + " " + ex);
                Logger.getLogger(CommandFactory.class.getName()).log(Level.SEVERE, null, ex);
            }

Thx for any help


问:
SDL_RenderCopy-ing to another texture results in subtly darker image
I've been chasing this visual bug for a while, and I've concluded that the process of renderCopying from one texture to another results in a slightly darkened image.

```<code>#include "basics.h"

#include <SDL.h>
#include <SDL_ttf.h>

#ifdef WIN32
#define _WIN32_WINNT 0x0500
#include <windows.h>
#endif

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O~~~~~~~~~~| M A I N |~~~~~~~~~~~O~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int main(int argc, char *argv[]){

    SDL_Window *window;
    SDL_Renderer *renderer;
    int width = 640;
    int height = 480;
    int loop = 1;
    int mouseX, mouseY, pmouseX, pmouseY;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError());
        return 3;
    }
    if (SDL_CreateWindowAndRenderer(width, height, SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED, &window, &renderer)) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window and renderer: %s", SDL_GetError());
        return 3;
    }

    SDL_GetWindowSize( window, &width, &height );

    const SDL_Color black = {0, 0, 0, 255};
    const SDL_Color white = {255, 255, 255, 255};

    char font_filename [] = "fonts/FreeSerif.ttf";//AveriaLibre-Regular
    int size = 20;

    if(TTF_Init() == -1){
        printf("TTF_Init: %s\n", TTF_GetError());
    }
    TTF_Font *font = TTF_OpenFont( font_filename, size );

    char str [] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

    SDL_Rect dst1 = (SDL_Rect){ 100, 100, 400, 200 };
    SDL_Rect dst2 = (SDL_Rect){ 515, 100, 400, 200 };

    SDL_Texture *buffer = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height );
    SDL_SetTextureBlendMode( buffer, SDL_BLENDMODE_BLEND );

    SDL_SetRenderDrawColor( renderer, 0, 0, 0, 255);
    SDL_RenderClear( renderer );

    SDL_Surface *surf = TTF_RenderText_Blended_Wrapped( font, str, white, dst1.w );
    dst1.w = surf->w; dst1.h = surf->h;
    SDL_Texture *texture = SDL_CreateTextureFromSurface( renderer, surf );
    SDL_RenderCopy( renderer, texture, NULL, &dst1 );

    SDL_SetRenderTarget( renderer, buffer );
    dst2.w = surf->w; dst2.h = surf->h;
    SDL_RenderCopy( renderer, texture, NULL, &dst2 );
    SDL_SetRenderTarget( renderer, NULL );
    SDL_RenderCopy( renderer, buffer, NULL, &(SDL_Rect){0, 0, width, height} );

    SDL_FreeSurface( surf );
    SDL_DestroyTexture( texture );

    char ascii [] = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

    surf = TTF_RenderText_Blended( font, ascii, white );
    texture = SDL_CreateTextureFromSurface( renderer, surf );
    SDL_RenderCopy( renderer, texture, NULL, &(SDL_Rect){100, 500, surf->w, surf->h} );

    SDL_SetRenderTarget( renderer, buffer );
    SDL_RenderCopy( renderer, texture, NULL, &(SDL_Rect){100, 530, surf->w, surf->h} );
    SDL_SetRenderTarget( renderer, NULL );
    SDL_RenderCopy( renderer, buffer, NULL, &(SDL_Rect){0, 0, width, height} );

    SDL_RenderPresent(renderer);

    while( 1 ) {
        SDL_Event event;
        while( SDL_PollEvent(&event) ){
            if(event.type == SDL_QUIT) {
                goto exit;
            }
        }
    }
    exit:

    SDL_DestroyTexture( buffer );
    SDL_DestroyTexture( texture );
    SDL_FreeSurface( surf );
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    SDL_Quit();

    return 0;
}
</code>```

this program results in this:
text rendering output

Like I say, it's a subtle effect, you might need to zoom in, but for my purposes it's really awful. Anyone know what could be the cause, or some workaround perhaps? thanks.

答:
You recursively apply blend operation multiple times on the same data.

Your render texture have the same size as your window. You didn't clear it, so let's presume it is zeroed by default, including alpha (it may be implementation-dependant, i don't see documentation states that anywyere; explicit clear with required colour may be a good idea).

SDL_ttf gives you surface with alpha channel. Then you render your first text fragment to that texture with blendmode=blend, blending it atop of zeroes. If you look at the formulas for blend operations - alpha values of your render target gets overwritten by your text texture (dstA = srcA + (dstA * (1-srcA)), and dstA is 0, so it is just srcA), but colour values are multiplied by your source alpha, so srcRGB = srcRGB * srcA.

Then you blend this target texture on top of your screen, which is cleared to (0, 0, 0, 255), applying the same blend operation again, resulting in another blending by the same srcA, so your colours are now srcRGB = srcRGB * srcA * srcA. This is obviously incorrect.

It gets worse with your second text fragment, because you do all that again, but never clear your render target. So when you use your render target again, you do another rendering of entire texture, including what was rendered at first text fragment, applying another blend on top of that.

You need to do blending only once. There are multiple ways to do so, and you'll have to decide what's best for your case. I don't know how you want to use your render texture, so presuming you want to keep alpha values, you need to do blending at last stage. That can be achieved by drawing into render target with blendmode=none, and then blitting your render texture onto screen, but only once. For example:

```<code>SDL_Texture *buffer = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height );
SDL_SetTextureBlendMode( buffer, SDL_BLENDMODE_BLEND );

SDL_SetRenderDrawColor( renderer, 0, 0, 0, 255);
SDL_RenderClear( renderer );

// first text fragment, rendering directly to screen
SDL_Surface *surf = TTF_RenderText_Blended_Wrapped( font, str, white, dst1.w );
dst1.w = surf->w; dst1.h = surf->h;
SDL_Texture *texture = SDL_CreateTextureFromSurface( renderer, surf );
SDL_RenderCopy( renderer, texture, NULL, &dst1 );

// first text fragment, rendering to render texture. blendmode=none to avoid
// pre-blending
SDL_SetRenderTarget( renderer, buffer );
dst2.w = surf->w; dst2.h = surf->h;
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_NONE);
SDL_RenderCopy( renderer, texture, NULL, &dst2 );
SDL_SetRenderTarget( renderer, NULL );
// NOT copying render target to screen. It is not finished yet, need to do
// that only once

SDL_FreeSurface( surf );
SDL_DestroyTexture( texture );

char ascii [] = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

// second text fragment, rendering directly to screen
surf = TTF_RenderText_Blended( font, ascii, white );
texture = SDL_CreateTextureFromSurface( renderer, surf );
SDL_RenderCopy( renderer, texture, NULL, &(SDL_Rect){100, 500, surf->w, surf->h} );

// second text fragment, rendering to render texture, blendmode=none
SDL_SetRenderTarget( renderer, buffer );
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_NONE);
SDL_RenderCopy( renderer, texture, NULL, &(SDL_Rect){100, 530, surf->w, surf->h} );
SDL_SetRenderTarget( renderer, NULL );

// render texture finished, now it is time to blend it with screen contents
SDL_RenderCopy( renderer, buffer, NULL, &(SDL_Rect){0, 0, width, height} );

SDL_RenderPresent(renderer);
</code>```

Body:
I've been chasing this visual bug for a while, and I've concluded that the process of renderCopying from one texture to another results in a slightly darkened image.

#include "basics.h"

#include <SDL.h>
#include <SDL_ttf.h>

#ifdef WIN32
#define _WIN32_WINNT 0x0500
#include <windows.h>
#endif

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O~~~~~~~~~~| M A I N |~~~~~~~~~~~O~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int main(int argc, char *argv[]){

    SDL_Window *window;
    SDL_Renderer *renderer;
    int width = 640;
    int height = 480;
    int loop = 1;
    int mouseX, mouseY, pmouseX, pmouseY;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError());
        return 3;
    }
    if (SDL_CreateWindowAndRenderer(width, height, SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED, &window, &renderer)) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window and renderer: %s", SDL_GetError());
        return 3;
    }

    SDL_GetWindowSize( window, &width, &height );

    const SDL_Color black = {0, 0, 0, 255};
    const SDL_Color white = {255, 255, 255, 255};

    char font_filename [] = "fonts/FreeSerif.ttf";//AveriaLibre-Regular
    int size = 20;

    if(TTF_Init() == -1){
        printf("TTF_Init: %s\n", TTF_GetError());
    }
    TTF_Font *font = TTF_OpenFont( font_filename, size );

    char str [] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

    SDL_Rect dst1 = (SDL_Rect){ 100, 100, 400, 200 };
    SDL_Rect dst2 = (SDL_Rect){ 515, 100, 400, 200 };

    SDL_Texture *buffer = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height );
    SDL_SetTextureBlendMode( buffer, SDL_BLENDMODE_BLEND );

    SDL_SetRenderDrawColor( renderer, 0, 0, 0, 255);
    SDL_RenderClear( renderer );

    SDL_Surface *surf = TTF_RenderText_Blended_Wrapped( font, str, white, dst1.w );
    dst1.w = surf->w; dst1.h = surf->h;
    SDL_Texture *texture = SDL_CreateTextureFromSurface( renderer, surf );
    SDL_RenderCopy( renderer, texture, NULL, &dst1 );

    SDL_SetRenderTarget( renderer, buffer );
    dst2.w = surf->w; dst2.h = surf->h;
    SDL_RenderCopy( renderer, texture, NULL, &dst2 );
    SDL_SetRenderTarget( renderer, NULL );
    SDL_RenderCopy( renderer, buffer, NULL, &(SDL_Rect){0, 0, width, height} );

    SDL_FreeSurface( surf );
    SDL_DestroyTexture( texture );

    char ascii [] = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

    surf = TTF_RenderText_Blended( font, ascii, white );
    texture = SDL_CreateTextureFromSurface( renderer, surf );
    SDL_RenderCopy( renderer, texture, NULL, &(SDL_Rect){100, 500, surf->w, surf->h} );

    SDL_SetRenderTarget( renderer, buffer );
    SDL_RenderCopy( renderer, texture, NULL, &(SDL_Rect){100, 530, surf->w, surf->h} );
    SDL_SetRenderTarget( renderer, NULL );
    SDL_RenderCopy( renderer, buffer, NULL, &(SDL_Rect){0, 0, width, height} );

    SDL_RenderPresent(renderer);

    while( 1 ) {
        SDL_Event event;
        while( SDL_PollEvent(&event) ){
            if(event.type == SDL_QUIT) {
                goto exit;
            }
        }
    }
    exit:

    SDL_DestroyTexture( buffer );
    SDL_DestroyTexture( texture );
    SDL_FreeSurface( surf );
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    SDL_Quit();

    return 0;
}

this program results in this:
text rendering output

Like I say, it's a subtle effect, you might need to zoom in, but for my purposes it's really awful. Anyone know what could be the cause, or some workaround perhaps? thanks.

Body:
You recursively apply blend operation multiple times on the same data.

Your render texture have the same size as your window. You didn't clear it, so let's presume it is zeroed by default, including alpha (it may be implementation-dependant, i don't see documentation states that anywyere; explicit clear with required colour may be a good idea).

SDL_ttf gives you surface with alpha channel. Then you render your first text fragment to that texture with blendmode=blend, blending it atop of zeroes. If you look at the formulas for blend operations - alpha values of your render target gets overwritten by your text texture (dstA = srcA + (dstA * (1-srcA)), and dstA is 0, so it is just srcA), but colour values are multiplied by your source alpha, so srcRGB = srcRGB * srcA.

Then you blend this target texture on top of your screen, which is cleared to (0, 0, 0, 255), applying the same blend operation again, resulting in another blending by the same srcA, so your colours are now srcRGB = srcRGB * srcA * srcA. This is obviously incorrect.

It gets worse with your second text fragment, because you do all that again, but never clear your render target. So when you use your render target again, you do another rendering of entire texture, including what was rendered at first text fragment, applying another blend on top of that.

You need to do blending only once. There are multiple ways to do so, and you'll have to decide what's best for your case. I don't know how you want to use your render texture, so presuming you want to keep alpha values, you need to do blending at last stage. That can be achieved by drawing into render target with blendmode=none, and then blitting your render texture onto screen, but only once. For example:

SDL_Texture *buffer = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height );
SDL_SetTextureBlendMode( buffer, SDL_BLENDMODE_BLEND );

SDL_SetRenderDrawColor( renderer, 0, 0, 0, 255);
SDL_RenderClear( renderer );

// first text fragment, rendering directly to screen
SDL_Surface *surf = TTF_RenderText_Blended_Wrapped( font, str, white, dst1.w );
dst1.w = surf->w; dst1.h = surf->h;
SDL_Texture *texture = SDL_CreateTextureFromSurface( renderer, surf );
SDL_RenderCopy( renderer, texture, NULL, &dst1 );

// first text fragment, rendering to render texture. blendmode=none to avoid
// pre-blending
SDL_SetRenderTarget( renderer, buffer );
dst2.w = surf->w; dst2.h = surf->h;
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_NONE);
SDL_RenderCopy( renderer, texture, NULL, &dst2 );
SDL_SetRenderTarget( renderer, NULL );
// NOT copying render target to screen. It is not finished yet, need to do
// that only once

SDL_FreeSurface( surf );
SDL_DestroyTexture( texture );

char ascii [] = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

// second text fragment, rendering directly to screen
surf = TTF_RenderText_Blended( font, ascii, white );
texture = SDL_CreateTextureFromSurface( renderer, surf );
SDL_RenderCopy( renderer, texture, NULL, &(SDL_Rect){100, 500, surf->w, surf->h} );

// second text fragment, rendering to render texture, blendmode=none
SDL_SetRenderTarget( renderer, buffer );
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_NONE);
SDL_RenderCopy( renderer, texture, NULL, &(SDL_Rect){100, 530, surf->w, surf->h} );
SDL_SetRenderTarget( renderer, NULL );

// render texture finished, now it is time to blend it with screen contents
SDL_RenderCopy( renderer, buffer, NULL, &(SDL_Rect){0, 0, width, height} );

SDL_RenderPresent(renderer);


问:
Writing data in Service Worker to Cloud Firestore
I'm working on a Firebase project and I want to receive firebase cloud messages (send from a Node.js server) in my service worker in my javascript project. This works fine, but now I want to save some data in my firebase cloud firestore from my service worker after receiving the notification. And there is the problem, I'm running in the error listed below:

```<code> Uncaught ReferenceError: XMLHttpRequest is not defined at Ln.<anonymous> (xmlhttp.js:167) at Me (channelrequest.js:512) at Ce (webchannelbase.js:1249) at Kn.xa (webchannelbase.js:1251) at re (run.js:124)
</code>```

Since a few days I'm trying to find the error, but could not find a solution until now. Therefore I hope that you can help me now. I've tried to save the data in the firebase realtime database which works, but because I need to have offline persistence, I had to switch to cloud firestore which runs in the error above.

Here is the code from my node.js server for sending the notification (userID and registrationToken is defined before):

```<code>payload = {
     data: {
     "title": "This is a Notification",
     "body": "This is the body of the notification message."
     },
};

options = {
     priority: "high",
     timeToLive: 7200
};

// send message to the registration token
admin.messaging().sendToDevice(registrationToken, payload, options).then(function(response) {
     admin.firestore().collection("Logging").doc(userID).set({active: "true"});
}).catch(function(error) {
     console.log("Error sending message:", error);
});
</code>```

And here is the code for receiving the notification in my firebase-messagins service worker file (userID is defined before):

```<code>self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  const keepAlive = async() => {
      firebase.firestore().collection("Logging").doc(userID).update({"open": "true"});
  }
  event.waitUntil(keepAlive());
});
</code>```

Can anyone help me, please? I have no more ideas for solving my problem :/

答: Since version 9 the Firebase Web SDK uses fetch instead of XMLHttpRequest. So it works inside a service worker.

Body:
I'm working on a Firebase project and I want to receive firebase cloud messages (send from a Node.js server) in my service worker in my javascript project. This works fine, but now I want to save some data in my firebase cloud firestore from my service worker after receiving the notification. And there is the problem, I'm running in the error listed below:

 Uncaught ReferenceError: XMLHttpRequest is not defined at Ln.<anonymous> (xmlhttp.js:167) at Me (channelrequest.js:512) at Ce (webchannelbase.js:1249) at Kn.xa (webchannelbase.js:1251) at re (run.js:124)

Since a few days I'm trying to find the error, but could not find a solution until now. Therefore I hope that you can help me now. I've tried to save the data in the firebase realtime database which works, but because I need to have offline persistence, I had to switch to cloud firestore which runs in the error above.

Here is the code from my node.js server for sending the notification (userID and registrationToken is defined before):

payload = {
     data: {
     "title": "This is a Notification",
     "body": "This is the body of the notification message."
     },
};

options = {
     priority: "high",
     timeToLive: 7200
};

// send message to the registration token
admin.messaging().sendToDevice(registrationToken, payload, options).then(function(response) {
     admin.firestore().collection("Logging").doc(userID).set({active: "true"});
}).catch(function(error) {
     console.log("Error sending message:", error);
});

And here is the code for receiving the notification in my firebase-messagins service worker file (userID is defined before):

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  const keepAlive = async() => {
      firebase.firestore().collection("Logging").doc(userID).update({"open": "true"});
  }
  event.waitUntil(keepAlive());
});

Can anyone help me, please? I have no more ideas for solving my problem :/


问:
why am I not able to compare a space in string after splitting to a space?

def str_to_list(str):
    # Insert your code here
    new = list(str)
    for i in new:
        if i ==  or (i.isdigit() and int(i) > 5):
            new.remove(i)
    return new
```

I expect out to be ['d', 'o', 'l', 'l', 'a', 'r']

But I get [' ', 'd', 'o', 'l', 'l', 'a', 'r']

答:
I suppose there was a typo

if i ==  or (i.isdigit() and int(i) > 5)

As this should result into a syntax error.

So I guess it was meant to be?

if i == " " or (i.isdigit() and int(i) > 5)

In that case, I would suspect that it is due to indices in your array  getting shifted while you were iterating over it and at the same time removing elements from it.
It is generally not recommended to modify a list in such a way that indices shift, while iterating over it.
Like in this example, where you are trying to remove spaces and specific numbers. And it would mean that after removing the "5" from array, you are ended up with two " " str spaces in your array. But iterator is not going to reset it's counter. It only does a number of iterators that was determined at the very start of the process. So there are not resets to previous positions. But at the same time we are being left with a our " " " str which ended up there after  "6" was removed. It basically shifted it position to the one that "6" had before. While spefici checks were perfmored at the position from which " " had moved away.
Tried my best to explain it. But yeah, there is a reason why it is considered a bad practice. It really makes things difficult to follow. Well it does for me for sure.
Instead I would suggest something like this:

```<code>def str_to_list(x):
    formatted = [i for i in [s for s in list(x)
                    if not(s.isdigit() and int(s) > 5)]
                    if not i.ispace()]]
    return formatted
</code>```

or less concise, but easier to follow:

```<code>def str_to_list(x):
    new_lst = []
    for i in list(x):
        if i.isspace():
            pass
        elif (i.isdigit() and int(i) > 5):
            pass
        else:
            new_lst.append(i)
    return new_lst
</code>```

It is a much more safer option and makes the whole thing less complicated in general if instead there is new array prepared while iterating over the original one.

I hope it helped.

Body:
def str_to_list(str):
    # Insert your code here
    new = list(str)
    for i in new:
        if i ==  or (i.isdigit() and int(i) > 5):
            new.remove(i)
    return new

I expect out to be ['d', 'o', 'l', 'l', 'a', 'r']

But I get [' ', 'd', 'o', 'l', 'l', 'a', 'r']

Body:
I suppose there was a typo

if i ==  or (i.isdigit() and int(i) > 5)

As this should result into a syntax error.

So I guess it was meant to be?

if i == " " or (i.isdigit() and int(i) > 5)

In that case, I would suspect that it is due to indices in your array  getting shifted while you were iterating over it and at the same time removing elements from it.
It is generally not recommended to modify a list in such a way that indices shift, while iterating over it.
Like in this example, where you are trying to remove spaces and specific numbers. And it would mean that after removing the "5" from array, you are ended up with two " " str spaces in your array. But iterator is not going to reset it's counter. It only does a number of iterators that was determined at the very start of the process. So there are not resets to previous positions. But at the same time we are being left with a our " " " str which ended up there after  "6" was removed. It basically shifted it position to the one that "6" had before. While spefici checks were perfmored at the position from which " " had moved away.
Tried my best to explain it. But yeah, there is a reason why it is considered a bad practice. It really makes things difficult to follow. Well it does for me for sure.
Instead I would suggest something like this:

def str_to_list(x):
    formatted = [i for i in [s for s in list(x)
                    if not(s.isdigit() and int(s) > 5)]
                    if not i.ispace()]]
    return formatted

or less concise, but easier to follow:

def str_to_list(x):
    new_lst = []
    for i in list(x):
        if i.isspace():
            pass
        elif (i.isdigit() and int(i) > 5):
            pass
        else:
            new_lst.append(i)
    return new_lst

It is a much more safer option and makes the whole thing less complicated in general if instead there is new array prepared while iterating over the original one.

I hope it helped.


问:
SSlv3 open.urllib handshake failure
so I have some software who uses webscraping, but for some reason it doesn't seem to work. It's bizarre because when I run it in Google Colab, the code works fine and the url's can open and be scraped, but when I run it in my web application (and run it on my console using python3 run.py) it doesn't work.

Here is the code that is returning errors :

```<code>      b = searchgoogle(query, num)
      c = []
      print(b)
      for i in b:
          extractor = extractors.ArticleExtractor()
          headers = {
              'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) '
                            'Chrome/50.0.2661.102 Safari/537.36'
          }
          extractor = extractors.ArticleExtractor()
          req = Request(url=i, headers=headers)
          d = urlopen(req)
          try:
            if d.info()['content-type'].startswith('text/html'):
                  print ('its html')
                  resp = requests.get(i, headers=headers)
                  if resp.ok:
                      doc = extractor.get_content(resp.text)
                      c.append(comparetexts(text,doc,i))
                  else:
                      print(f'Failed to get URL: {resp.status_code}')
            else:
                    print ('its not html')
          except KeyError:
            print( 'its not html')
          print(i)
  return c
</code>```

The code returning errors is the "d = urlopen(req)"

There is code above the section I just put here but it has nothing to do with the errors. Anyways, thanks for your time!

(By the way, I checked my OPEN SSL version on python3 and it says : 'OpenSSL 1.1.1m  14 Dec 2021' so I think it's up to date)

答:
This happens because your web application does not have SSL certification, so you should tell your script to ignore SSL verification when making the request, as specified here:
Python 3 urllib ignore SSL certificate verification</p>

Title: SSlv3 open.urllib handshake failure

Body:
so I have some software who uses webscraping, but for some reason it doesn't seem to work. It's bizarre because when I run it in Google Colab, the code works fine and the url's can open and be scraped, but when I run it in my web application (and run it on my console using python3 run.py) it doesn't work.

Here is the code that is returning errors :

      b = searchgoogle(query, num)
      c = []
      print(b)
      for i in b:
          extractor = extractors.ArticleExtractor()
          headers = {
              'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) '
                            'Chrome/50.0.2661.102 Safari/537.36'
          }
          extractor = extractors.ArticleExtractor()
          req = Request(url=i, headers=headers)
          d = urlopen(req)
          try:
            if d.info()['content-type'].startswith('text/html'):
                  print ('its html')
                  resp = requests.get(i, headers=headers)
                  if resp.ok:
                      doc = extractor.get_content(resp.text)
                      c.append(comparetexts(text,doc,i))
                  else:
                      print(f'Failed to get URL: {resp.status_code}')
            else:
                    print ('its not html')
          except KeyError:
            print( 'its not html')
          print(i)
  return c

The code returning errors is the "d = urlopen(req)"

There is code above the section I just put here but it has nothing to do with the errors. Anyways, thanks for your time!

(By the way, I checked my OPEN SSL version on python3 and it says : 'OpenSSL 1.1.1m  14 Dec 2021' so I think it's up to date)


问:
How do we store different language words in redis as values?
I want to store the data received from API and store it as a value in Redis.The response would be in different languages
eg:
I want to store the response ದಿನಾಂಕ .But whenever i try to access the value throug key the response would be something like "\xe0\xb2\xa6\xe0\xb2\xbf\xe0\xb2\xa8\xe0\xb2\xbe\xe0\xb2\x82\xe0\xb2\x95" .
Please help if possible :)</p>

答:
That's simply the array of bytes (hexadecimal representation) of your string (UTF-8 representation).

For example, input e0 b2 a6 e0 b2 bf e0 b2 a8 e0 b2 be e0 b2 82 e0 b2 95 in https://onlineutf8tools.com/convert-bytes-to-utf8.

All you should do is use a function (depending on your programming language or Redis client) to convert an array of bytes into its UTF-8 string representation.

See Python-redis keys() returns list of bytes objects instead of strings.