问:
Firebase to HTML page: how to not print 'undefined' when there is no value in the database
I hope I 'm providing all that is needed to explain my issue. I'm totally not good at scripts so forgive me my stupidity ... teach me to get better please. ˆˆ

So you will find my script here.

I want to show all the records that meet the 'today or in the future' date.
Going well so far.

Now some records do not have the field artists. And then the output is 'undefined'. Is there a way to cover this... just not print anything when the value and the field is not present?

```<code>    <script src="https://www.gstatic.com/firebasejs/7.2.0/firebase.js"></script>

    <script>
    // Set the configuration for your app

    var config = {
      apiKey: "xxx",
      authDomain: "xxx",
      databaseURL: "xxx",
      storageBucket: "xxx"
      };
      firebase.initializeApp(config);

    // Get a reference to the database service

    //var db = firebase.database();
    const preObject = document.getElementById('Agenda');
    const ulList = document.getElementById('AgendaList');

    // Create references

    const dbRefObject = firebase.database().ref().child('Event');

    // Synch object changes

    dbRefObject.orderByChild("Date").startAt(new Date().toISOString().slice(0,10)).on('child_added', snap => {

    var data = [];
    const li = document.createElement('li');
    var JSONValue = snap.val();

    // create a variable that checks wheater or not there is a picture. If there is a picture print the picture if not do not print anything
    var photo = "";
    if (JSONValue['Photo']!==undefined) {
      photo='<img class="photo" src="'+JSONValue['Photo']+'">';
    }

    // check the value of the status field. If the status is Cancelled, print the status. else do not print anything
    var status = "";
    if (JSONValue['Status']==='Geannuleerd') {
      status='<span class="status">'+JSONValue['Status']+'</span>';
    }

    // check the value of the message field. If the message is nieuwsbericht then do not print the date. Else print the date.
    var date = "";
    if (JSONValue['Message']==='Concert') {
      date=JSONValue['FullDate'] + '-' + JSONValue['ShortTime'];
    }

    // check the value of the message field. If the message is nieuwsbericht then do not print the date. Else print the date.
    var title = "";
    if (JSONValue['Message']==='Concert') {
      title=JSONValue['Concert'];
    }

    li.innerHTML = '<div class="event">'+photo+'<h3>' +date+ '</h3>' + '<h1>' +title+ '</h1>' + JSONValue['Artists'] + '</div>';
    li.id = snap.key;
    ulList.appendChild(li);

    });
    </script>
</code>```

enter image description here

答:
You can use the logical "OR" operator (written as ||) to conditionally display something else in case JSONValue['Artists'] is undefined.

JSONValue['Artists'] || ""
```
<p>This basically means "get the value of <code>JSONValue['Artists']</code>, or if its value is falsy (undefined, null, empty, zero, false) use an empty string instead".</p>
<p>The relevant line in your code will be:</p>
<pre class="lang-js prettyprint-override"><code>li.innerHTML = '<div class="event">'+photo+'<h3>' +date+ '</h3>' + '<h1>' +title+ '</h1>' + (JSONValue['Artists'] || "") + '</div>';
</code>```

I've added parenthesis around JSONValue['Artists'] || "" to make the order of operations explicit.

You can also use something else as a fallback:

JSONValue['Artists'] || "No artists for this concert"
```
<p>You can read more about logical operators here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators</p>
<p>NB: If valid artist names include "" (a blank string), "0", and <code>0</code>, this technique may give you unintended results. All of these values are falsy.</p>
<p>In other words, the following code will evaluate to "No artists for this concert":</p>
<pre class="lang-js prettyprint-override"><code>"0" || "No artists for this concert"
</code>```

To mitigate this you can use the Nullish coalescing operator (??)

Body:
I hope I 'm providing all that is needed to explain my issue. I'm totally not good at scripts so forgive me my stupidity ... teach me to get better please. ˆˆ

So you will find my script here.

I want to show all the records that meet the 'today or in the future' date.
Going well so far.

Now some records do not have the field artists. And then the output is 'undefined'. Is there a way to cover this... just not print anything when the value and the field is not present?

enter image description here

Body:
You can use the logical "OR" operator (written as ||) to conditionally display something else in case JSONValue['Artists'] is undefined.

JSONValue['Artists'] || ""

This basically means "get the value of JSONValue['Artists'], or if its value is falsy (undefined, null, empty, zero, false) use an empty string instead".

The relevant line in your code will be:

li.innerHTML = '<div class="event">'+photo+'<h3>' +date+ '</h3>' + '<h1>' +title+ '</h1>' + (JSONValue['Artists'] || "") + '</div>';

I've added parenthesis around JSONValue['Artists'] || "" to make the order of operations explicit.

You can also use something else as a fallback:

JSONValue['Artists'] || "No artists for this concert"

You can read more about logical operators here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

NB: If valid artist names include "" (a blank string), "0", and 0, this technique may give you unintended results. All of these values are falsy.

In other words, the following code will evaluate to "No artists for this concert":

"0" || "No artists for this concert"

To mitigate this you can use the Nullish coalescing operator (??)


来源: stackexchange

问:
How to make Mute role override others
I have a discord bot, it has a mute command. The mute command works in theory, but when I tested it in a proper server, I noticed an issue. The role "Muted" was placed right at the bottom of the list of roles, meaning that all other roles above it override the mute, making it effectively useless. Would there be a method to make the role "Muted" created to the highest possible level the bot can assign, so the mute can be in effect?

Here is the code:

if (command === 'mute') {
  if (!message.member.hasPermission("MANAGE_ROLES") || !message.guild.owner) return message.channel.send("You don't have enough authority to do this.");

  if (!message.guild.me.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"]))
    return message.channel.send("Give me the permissions first.")

  let role = message.guild.roles.find(x => x.name === "Muted");
  let member = message.mentions.members.first() || message.guild.members.get(args[0]);
  if (!member) return message.reply(`I can't find the user ` + member)

  let duration = ms(args[1]);
  let reason = args.slice(2).join(' ');
  if (!reason) reason = "No reason provided";
  if (!role) {
    try {
      role = await message.guild.createRole({
        name: "Muted",
        color: "#000000",
        permissions: []
      })
      message.guild.channels.forEach(async(channel, id) => {
        message.channel.overwritePermission(role, {
          SEND_MESSAGES: false,
          ADD_REACTIONS: false,
          SEND_TTS_MESSAGES: false,
          ATTACH_FILES: false,
          SPEAK: false
        });
      });
    } catch (e) {
      console.log(e);
    }
  }

  member.addRole(role).catch(console.error);
  message.channel.send(`<@${member.id}> , you have been muted for ${duration}.`)

  setTimeout(function() {
    member.removeRole(role.id);
    message.channel.send(`${member} has been automatically unmuted.`);
  }, duration);
}
```

答:
Disclaimer: you seem to be using discord.js@v11, I'll reply with code for that version.

You should use the position option when creating the role:

role = await message.guild.createRole({
  name: "Muted",
  color: "#000000",
  permissions: [],
  position: 1
})
```

You can find a list of all the options you can use when creating a role here.

ContentLicense: CC BY-SA 4.0

Title: How to make Mute role override others

Body:
Disclaimer: you seem to be using discord.js@v11, I'll reply with code for that version.

You should use the position option when creating the role:

role = await message.guild.createRole({
  name: "Muted",
  color: "#000000",
  permissions: [],
  position: 1
})

You can find a list of all the options you can use when creating a role here.


问:
How can I reduce the app.js size of my vuejs web app?
I am having app.js size of 1.76 MB and web app takes so much time to response.I'm using laravel in backend.</p>

答: Try minifying using uglify.js https://www.npmjs.com/package/uglify-js and make sure you have compression enabled</p>


问:
Google Chrome window.open with name opening new window
So let say you have a page named daddy that opens a child window named testbug:

```<code><html>
    <head>
        <title>daddy: Window.open bug</title>
    </head>
    <body>
        <script type="text/javascript">
            var new_win = window.open('', "testbug", 'toolbar=1, menubar=1, status=1, left=0, top=0', true);
        </script>
    </body>
</html>
</code>```

If the user focuses on something other than the window with daddy tab and opens this page again the new daddy window opens up a new testbug child window. So now instead of having two daddy windows and one testbug window (as is the behaviour in IE && ff) there is two daddy windows and two testbug windows.

So my question is what do I need to keep this from happening?

PS: This is an internal application and is a very simple version of what we have on the real app.

UPDATE

I submitted this issue to google chrome team and will wait to see their response before deciding what to do with this question.

答:
The only time I see a second testbug window being opened is if I close the daddy window and then reopen it. If I focus on another window and then refresh the daddy window, the same testbug window remains open.

Could you perhaps elaborate some more on which version of Chrome you are using, and your operating system? Your best bet might be to file a bug and work directly with the Chromium support team. They would be able to troubleshoot the scenario and determine if it is replicable.

ContentLicense: CC BY-SA 3.0

Body:
So let say you have a page named daddy that opens a child window named testbug:

        <title>daddy: Window.open bug</title>

If the user focuses on something other than the window with daddy tab and opens this page again the new daddy window opens up a new testbug child window. So now instead of having two daddy windows and one testbug window (as is the behaviour in IE && ff) there is two daddy windows and two testbug windows.

So my question is what do I need to keep this from happening?

PS: This is an internal application and is a very simple version of what we have on the real app.

UPDATE

I submitted this issue to google chrome team and will wait to see their response before deciding what to do with this question.


Title: Extract rows from dataframe which were absent on certain days

Body:
I have a dataframe:

Date          Agent
2020-02-10    A
2020-02-11    A
2020-02-12    A
2020-02-13    A
2020-02-14    A
2020-02-10    B
2020-02-12    B
2020-02-10    C
2020-02-11    C
2020-02-14    C

I want to get a data frame with those row which were absent at certain days from 2020-02-10 to 2020-02-14. So desired output is:

Agent  Days_absent
B      2020-02-11; 2020-02-13; 2020-02-14
C      2020-02-12; 2020-02-13

or

Date          Agent
2020-02-11    B
2020-02-13    B
2020-02-14    B
2020-02-12    C
2020-02-13    C

How could i do that?

Body:
A dplyr solution:

     df %>%
   group_by(Agent) %>%
   group_modify(~data.frame(setdiff(df$Date,.$Date))) %>%
  rename(Date=2)
# A tibble: 5 x 2
# Groups:   Agent [2]
  Agent Date
  <chr> <chr>
1 B     2020-02-11
2 B     2020-02-13
3 B     2020-02-14
4 C     2020-02-12
5 C     2020-02-13

Data

df<- structure(list(Date = c("2020-02-10", "2020-02-11", "2020-02-12",
"2020-02-13", "2020-02-14", "2020-02-10", "2020-02-12", "2020-02-10",
"2020-02-11", "2020-02-14"), Agent = c("A", "A", "A", "A", "A",
"B", "B", "C", "C", "C")), class = "data.frame", row.names = c(NA,
-10L))


问:
Variable Not In Scope for Lambda
I'm trying to diagnose a timing issue on a multi-core processor [Xeon Silver].  I think that the clocks have not been configured or synced between the processor.  I'm using Eli Bendersky's [credited in the code snippet] threading examples to build a test instrument.  I have made three changes.  I made made the sleep occur first, and I added a call to std::chrono::system_clock::now() and tried to print it out.  I'm building with gcc 4.8.5 on CentOS 7.5.

The code is as follows:

```<code>// // Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
#include <algorithm>
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <pthread.h>

int main(int argc, const char** argv) {
  unsigned num_cpus = std::thread::hardware_concurrency();
  std::cout << "Launching " << num_cpus << " threads\n";

  // A mutex ensures orderly access to std::cout from multiple threads.
  std::mutex iomutex;
  std::vector<std::thread> threads(num_cpus);
  for (unsigned i = 0; i < num_cpus; ++i)
  {
    threads[i] = std::thread([&iomutex, i]
    {
       // Simulate important work done by the tread by sleeping for a bit...
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
      {
         std::chrono::time_point ti = std::chrono::system_clock::now();
         // Use a lexical scope and lock_guard to safely lock the mutex only for
         // the duration of std::cout usage.
         std::lock_guard<std::mutex> iolock(iomutex);
         std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
       }
    });
  }

  for (auto& t : threads) {
      t.join();
  }
  return 0;
}
</code>```

I build with make:

```<code>CXX = g++
CXXFLAGS = -std=c++11 -Wall -O3 -g -DNDEBUG -pthread
LDFLAGS = -lpthread -pthread

clock-check: clock-check.cpp
    $(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)
</code>```

GCC gives me the following error:

```<code>[user@sbc1 concur]$ make clock-check
g++ -std=c++11 -Wall -O3 -g -DNDEBUG -pthread clock-check.cpp -o clock-check -lpthread -pthread
clock-check.cpp: In lambda function:
clock-check.cpp:32:67: error: ‘ti’ was not declared in this scope
      std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
                                                               ^
make: *** [clock-check] Error 1
</code>```

ti is clearly in the same block scope as the print statement, and I'm baffled why the compiler is complaining.  I have not found any restrictions on variables local to the lambda.  Most of what I have found has been references to captures.

答:
It seems to be a bug in older gcc versions. With gcc 10.1 (--std=c++11) I get the error:

```<code><source>: In lambda function:
<source>:23:34: error: missing template arguments before 'ti'
   23 |          std::chrono::time_point ti = std::chrono::system_clock::now();
      |                                  ^~
<source>:27:67: error: 'ti' was not declared in this scope; did you mean 'i'?
   27 |          std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
      |                                                                   ^~
      |
</code>```

The error about the missing template parameter (which is missing with gcc 4.5.8) on the declaration explains the second error.

Strangely gcc 4.8.5 with -std=c++11 happily compiles the code if you remove the line with std::cout: https://godbolt.org/z/6LREHF

Title: Variable Not In Scope for Lambda

Body:
I'm trying to diagnose a timing issue on a multi-core processor [Xeon Silver].  I think that the clocks have not been configured or synced between the processor.  I'm using Eli Bendersky's [credited in the code snippet] threading examples to build a test instrument.  I have made three changes.  I made made the sleep occur first, and I added a call to std::chrono::system_clock::now() and tried to print it out.  I'm building with gcc 4.8.5 on CentOS 7.5.

The code is as follows:

// // Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
#include <algorithm>
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <pthread.h>

int main(int argc, const char** argv) {
  unsigned num_cpus = std::thread::hardware_concurrency();
  std::cout << "Launching " << num_cpus << " threads\n";

  // A mutex ensures orderly access to std::cout from multiple threads.
  std::mutex iomutex;
  std::vector<std::thread> threads(num_cpus);
  for (unsigned i = 0; i < num_cpus; ++i)
  {
    threads[i] = std::thread([&iomutex, i]
    {
       // Simulate important work done by the tread by sleeping for a bit...
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
      {
         std::chrono::time_point ti = std::chrono::system_clock::now();
         // Use a lexical scope and lock_guard to safely lock the mutex only for
         // the duration of std::cout usage.
         std::lock_guard<std::mutex> iolock(iomutex);
         std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
       }
    });
  }

  for (auto& t : threads) {
      t.join();
  }
  return 0;
}

I build with make:

CXX = g++
CXXFLAGS = -std=c++11 -Wall -O3 -g -DNDEBUG -pthread
LDFLAGS = -lpthread -pthread

clock-check: clock-check.cpp
    $(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)

GCC gives me the following error:

[user@sbc1 concur]$ make clock-check
g++ -std=c++11 -Wall -O3 -g -DNDEBUG -pthread clock-check.cpp -o clock-check -lpthread -pthread
clock-check.cpp: In lambda function:
clock-check.cpp:32:67: error: ‘ti’ was not declared in this scope
      std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
                                                               ^
make: *** [clock-check] Error 1

ti is clearly in the same block scope as the print statement, and I'm baffled why the compiler is complaining.  I have not found any restrictions on variables local to the lambda.  Most of what I have found has been references to captures.

Body:
It seems to be a bug in older gcc versions. With gcc 10.1 (--std=c++11) I get the error:

<source>: In lambda function:
<source>:23:34: error: missing template arguments before 'ti'
   23 |          std::chrono::time_point ti = std::chrono::system_clock::now();
      |                                  ^~
<source>:27:67: error: 'ti' was not declared in this scope; did you mean 'i'?
   27 |          std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
      |                                                                   ^~
      |

The error about the missing template parameter (which is missing with gcc 4.5.8) on the declaration explains the second error.

Strangely gcc 4.8.5 with -std=c++11 happily compiles the code if you remove the line with std::cout: https://godbolt.org/z/6LREHF


问:
Alert deprecated: Stdlib.String.set
The following code returns an error and says that the syntax is deprecated. What is the correct way to change a character in a string?

let hello = "Hello!" ;;
hello.[1] <- 'a' ;;
```

```Alert deprecated: Stdlib.String.set
Use Bytes.set instead.
Error: This expression has type string but an expression was expected of type
         bytes
```

答:
Strings are immutable (or at least soon they will be), so you can't change their contents. You can, of course, create a copy of a string with the one character different, e.g.,

```<code>let with_nth_char m c =
  String.mapi (fun i b -> if i = m then c else b)
</code>```

and

```<code># with_nth_char 1 'E' "hello";;
- : string = "hEllo"
</code>```

But if you need to change characters in an array then you shouldn't use the string data type but instead rely on bytes which is a type for mutable strings.  You can use Bytes.of_strings and Bytes.to_string to translate strings to bytes and vice verse.

Title: Alert deprecated: Stdlib.String.set

Body:
The following code returns an error and says that the syntax is deprecated. What is the correct way to change a character in a string?

let hello = "Hello!" ;;
hello.[1] <- 'a' ;;

Alert deprecated: Stdlib.String.set
Use Bytes.set instead.
Error: This expression has type string but an expression was expected of type
         bytes

Body:
Strings are immutable (or at least soon they will be), so you can't change their contents. You can, of course, create a copy of a string with the one character different, e.g.,

let with_nth_char m c =
  String.mapi (fun i b -> if i = m then c else b)

and

# with_nth_char 1 'E' "hello";;
- : string = "hEllo"

But if you need to change characters in an array then you shouldn't use the string data type but instead rely on bytes which is a type for mutable strings.  You can use Bytes.of_strings and Bytes.to_string to translate strings to bytes and vice verse.


问:
How to print a variableName(String) of ListTile in flutter
How can i print String of a ListTile with onTap,

In this case "image_caption" is the string.

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

class HorizontalList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 85.0,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: <Widget>[
          Catagory(
            image_location: 'Images/Icons/smartphone.png',
            image_caption: 'Electronics',
          ),
          Catagory(
            image_location: 'Images/Icons/car.png',
            image_caption: 'Vehicles',
          ),
          Catagory(
            image_location: 'Images/Icons/car.png',
            image_caption: 'Vehicles',
          ),
          Catagory(
            image_location: 'Images/Icons/car.png',
            image_caption: 'Vehicles',
          ),
          Catagory(
            image_location: 'Images/Icons/car.png',
            image_caption: 'Vehicles',
          ),
        ],
      ),
    );
  }
}

class Catagory extends StatelessWidget {
  final String image_location;
  final String image_caption;
  Catagory({this.image_location, this.image_caption});
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(0.0),
      child: GestureDetector(
        onTap: () {
          print("image_caption"); //Print tapped image_caption
        },
        child: Container(
          width: 101.0,
          color: Color(0xFF051622),
          child: ListTile(
            title: CircleAvatar(
              //Circle with gold border
              radius: 32.0,
              backgroundColor: Color(0xFFDEB992),
              child: CircleAvatar(
                //Circle which containes the icon
                radius: 29.0,
                backgroundColor: Colors.white,
                child: Image.asset(image_location),
              ),
            ),
            subtitle: Container(
              alignment: Alignment.topCenter,
              height: 15.0,
              child: Text(
                image_caption,
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
</code>```

答: Use string interpolation inside quotes print(' Tapped image is $image_caption'); or directly print(image_caption); without single quotes.

Body:
How can i print String of a ListTile with onTap,

In this case "image_caption" is the string.

import 'package:flutter/material.dart';

class HorizontalList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 85.0,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: <Widget>[
          Catagory(
            image_location: 'Images/Icons/smartphone.png',
            image_caption: 'Electronics',
          ),
          Catagory(
            image_location: 'Images/Icons/car.png',
            image_caption: 'Vehicles',
          ),
          Catagory(
            image_location: 'Images/Icons/car.png',
            image_caption: 'Vehicles',
          ),
          Catagory(
            image_location: 'Images/Icons/car.png',
            image_caption: 'Vehicles',
          ),
          Catagory(
            image_location: 'Images/Icons/car.png',
            image_caption: 'Vehicles',
          ),
        ],
      ),
    );
  }
}

class Catagory extends StatelessWidget {
  final String image_location;
  final String image_caption;
  Catagory({this.image_location, this.image_caption});
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(0.0),
      child: GestureDetector(
        onTap: () {
          print("image_caption"); //Print tapped image_caption
        },
        child: Container(
          width: 101.0,
          color: Color(0xFF051622),
          child: ListTile(
            title: CircleAvatar(
              //Circle with gold border
              radius: 32.0,
              backgroundColor: Color(0xFFDEB992),
              child: CircleAvatar(
                //Circle which containes the icon
                radius: 29.0,
                backgroundColor: Colors.white,
                child: Image.asset(image_location),
              ),
            ),
            subtitle: Container(
              alignment: Alignment.topCenter,
              height: 15.0,
              child: Text(
                image_caption,
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}


问:
git - pushing only the top most commit to server
I have a situation where I:

(1) Merged a patch by user X

(2) Made some changes to some other code and committed.

Now I want to push my commit to the server. However, when I do

```<code>git push origin HEAD:refs/for/mybranch
</code>```

I get an error regarding the patch that I merged, saying that I am not the author. Is there a way to do what I'm trying to accomplish? If not, is there a way to save my commit, then revert everything and push my commit back in?

答:
Why not just commit the patch, then convert your "changes to some other code" separately? Git is telling the truth, you are not the author of the patch, "user X" is.

Also, is there a reason you are doing this command:

```<code>git push origin HEAD:refs/for/mybranch
</code>```

instead of just

```<code>git push origin mybranch
</code>```

Body:
I have a situation where I:

(1) Merged a patch by user X

(2) Made some changes to some other code and committed.

Now I want to push my commit to the server. However, when I do

git push origin HEAD:refs/for/mybranch

I get an error regarding the patch that I merged, saying that I am not the author. Is there a way to do what I'm trying to accomplish? If not, is there a way to save my commit, then revert everything and push my commit back in?

Body:
Why not just commit the patch, then convert your "changes to some other code" separately? Git is telling the truth, you are not the author of the patch, "user X" is.

Also, is there a reason you are doing this command:

git push origin HEAD:refs/for/mybranch

instead of just

git push origin mybranch


问:
CaseInsensitiveSearch in swift5?
```<code>tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
</code>```

I want to use the above code in swift5
But can't use

```<code>tmp.range (of: searchText, options: NSString.CompareOptions.caseInsensitive)
</code>```

I changed it as above, but is the same code correct?

Thanks for reading

答:
You can do like this </p>

```<code>let range = tmp.range(of: searchText, options: .caseInsensitive)
</code>```

Title: CaseInsensitiveSearch in swift5?

Body:
tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)

I want to use the above code in swift5
But can't use

tmp.range (of: searchText, options: NSString.CompareOptions.caseInsensitive)

I changed it as above, but is the same code correct?

Thanks for reading

Body:
You can do like this

let range = tmp.range(of: searchText, options: .caseInsensitive)


问:
is postgres UPSERT fully atomic/thread safe?
We're trying to stream data to postgres 11, using the following query:

```<code>INSERT INTO identifier_to_item
values (:id, :identifier_value, :identifier_type, :identifier_manufacturer, :delivery_timestamp_utc, :item)
ON CONFLICT (identifier_value, manufacturer, type) DO UPDATE
SET item = :item, delivery_timestamp_utc = :delivery_timestamp_utc
WHERE identifier_to_item.delivery_timestamp_utc < :delivery_timestamp_utc
</code>```

Basically "insert record in the table, if it already exists -> optionally override some fields based on the data already stored in the database".

We would like to hook this query to message queue and run it in high concurrent environment within several instances. It is possible that the same row will be accessed from different connections using this query. For us it's critical that only items with highest delivery timestamp will eventually make it to the table

According to documentation:

ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency.

but is also accessing the fields in UPDATE WHERE part atomic and thread safe? Is this statement using some kind of pessimistic row/table locking?

答:
PostgreSQL is not using threads on the server side.

PostgreSQL does not implement pessimistic/optimistic row level locking : it is the left to the application to decide to implement pessimistic or optimistic locking.

PostgreSQL does not escalate row level locks to table lock.

Body:
We're trying to stream data to postgres 11, using the following query:

INSERT INTO identifier_to_item
values (:id, :identifier_value, :identifier_type, :identifier_manufacturer, :delivery_timestamp_utc, :item)
ON CONFLICT (identifier_value, manufacturer, type) DO UPDATE
SET item = :item, delivery_timestamp_utc = :delivery_timestamp_utc
WHERE identifier_to_item.delivery_timestamp_utc < :delivery_timestamp_utc

Basically "insert record in the table, if it already exists -> optionally override some fields based on the data already stored in the database".

We would like to hook this query to message queue and run it in high concurrent environment within several instances. It is possible that the same row will be accessed from different connections using this query. For us it's critical that only items with highest delivery timestamp will eventually make it to the table

According to documentation:

ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency.

but is also accessing the fields in UPDATE WHERE part atomic and thread safe? Is this statement using some kind of pessimistic row/table locking?


问:
ListView footer not center
Any idea why the footer of my list view is always on the left? Here's my xml layout. Footer just added and removed as more data needs loaded. I want theTextView and ProgressBar to be center</p>

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:orientation="horizontal"
android:gravity="center">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="12sp"
    android:textColor="@color/author_text"
    android:text="LOADING DATA..."
    />

<ProgressBar
    android:layout_width="15dp"
    android:layout_height="15dp"
    android:layout_marginLeft="10dp"
    />
</LinearLayout>
</code>```

答:
Okay, so the problem was NOT with the footer view shown in the OP; it indeed works just fine. The problem was my ListView had the layout_width attribute set to wrap_content. This works just fine for all the list renderers, but not for the footer. Changing the ListView to fill_parent fixed it

```<code><ListView
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    style="@style/MyList"
    />
</code>```

thanks gang
[SOLVED]

Title: ListView footer not center

Body:
Any idea why the footer of my list view is always on the left? Here's my xml layout. Footer just added and removed as more data needs loaded. I want theTextView and ProgressBar to be center

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:orientation="horizontal"
android:gravity="center">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="12sp"
    android:textColor="@color/author_text"
    android:text="LOADING DATA..."
    />

<ProgressBar
    android:layout_width="15dp"
    android:layout_height="15dp"
    android:layout_marginLeft="10dp"
    />
</LinearLayout>

Body:
Okay, so the problem was NOT with the footer view shown in the OP; it indeed works just fine. The problem was my ListView had the layout_width attribute set to wrap_content. This works just fine for all the list renderers, but not for the footer. Changing the ListView to fill_parent fixed it

<ListView
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    style="@style/MyList"
    />

thanks gang
[SOLVED]


问:
Declaring array in C++ like array[1-00] by mistake but still code works, output is incorrect?
When i declare array as array[1-00] by mistake i didn't get the right answer. But when i change it to normal declaration like array[100] i clear all the test cases.
Can anyone provide any explanation for this type of problem?
Please.</p>

答:
You declared the array with a size of 1.

```<code>int arr[100]; //100 elements
int arr2[1]; //1 element
int arr3[1-00] // 1 - 0 = 1 element
</code>```

accessing elements outside the array is undefined behavior, which means that the compiler can do whatever it wants.
Read this for more information about undefined behavior.

Body:
You declared the array with a size of 1.

int arr[100]; //100 elements
int arr2[1]; //1 element
int arr3[1-00] // 1 - 0 = 1 element

accessing elements outside the array is undefined behavior, which means that the compiler can do whatever it wants.
Read this for more information about undefined behavior.


问:
How to insert a image created by decode of a string to a pdf in pdfbox
I'm trying to insert an image (which needs to be converted from a string by java.util.Base64.getDecoder().decode(imageInputString)) to a certain position of a pdf file.

The main logic of the code will be:

```<code>  //create a PDImageXObject myImage first (or something that could be used in addImage method.
  //And this is what I could not figure out how to accomplish.

  //open the pdf file and use addImage to insert the image to the specific page at specific position.
  PDDocument document = PDDocument.load(pdfFile);
  PDPageContentStream contentStream = new PDPageContentStream(document, pageNumber);
  contentStream.addImage(myImage,x,y);
  document.save();
</code>```

Most of the tutorial I found created the myImage from reading an image file. Could someone help me to see if I could do the same thing but with a byte [], which is the output of  java.util.Base64.getDecoder().decode(imageInputString)?

Thanks!

答: You can use the static method PDImageXObject.createFromByteArray(), which detects the file type based on contents and will decide which PDF image type / image compression is best. (javadoc)

Body:
I'm trying to insert an image (which needs to be converted from a string by java.util.Base64.getDecoder().decode(imageInputString)) to a certain position of a pdf file.

The main logic of the code will be:

  //create a PDImageXObject myImage first (or something that could be used in addImage method.
  //And this is what I could not figure out how to accomplish.

  //open the pdf file and use addImage to insert the image to the specific page at specific position.
  PDDocument document = PDDocument.load(pdfFile);
  PDPageContentStream contentStream = new PDPageContentStream(document, pageNumber);
  contentStream.addImage(myImage,x,y);
  document.save();

Most of the tutorial I found created the myImage from reading an image file. Could someone help me to see if I could do the same thing but with a byte [], which is the output of  java.util.Base64.getDecoder().decode(imageInputString)?

Thanks!


问:
How do I handle an error after match function
is there a way to handle an error in a loop
I use a match function to match a cottage with the right size and class as it is reserved. But if there is no cottage_size available, the match function returns an error, after which I want to upgrade the cottage(cottage_size=cottage_size+1) and search for a match again..

My question is how do i go back to the match function after the error and after I upgraded the size..

```<code> If som = 0 And iDklasse = class And iDpers = cottage_size Then

                        Set klasseKolom = cottagesheet.UsedRange.Columns(3)
                        Set SizeKolom = cottagesheet.UsedRange.Columns(2)

                        For k = 4 To 1 Step -1
                            For p = 2 To 12

                                cottageId = (Evaluate("MATCH(1,(" & klasseKolom.Address(External:=True) & "=" & zoekklasse & ")*(" & SizeKolom.Address(External:=True) & "=" & cottage_size & "),0)"))
                                If Not IsError(cottageId) Then
                                huisnr = cottageId
                                    If Application.CountIf(validatorsheet.Range("B:B"), huisnr) = 0 Then                               'cottage beschikbaarheid (gaat niet goed)
                                        validatorsheet.Cells(iD, 2).Value = cottagesheet.Cells(cottageId, 1).Value                      'invullen in validatorsheet
                                        stay = Reservationsheet.Cells(iD, 3).Value
                                        arrival_date = Reservationsheet.Cells(iD, 2).Value
                                        For datumkolom = 2 To laatstekolom
                                            If arrival_date = roostersheet.Cells(1, datumkolom).Value Then
                                                 'If Application.CountBlank(Range(roostersheet.Cells(huisnr, datumkolom), roostersheet.Cells(huisnr, datumkolom + stay - 1))) = Range(roostersheet.Cells(huisnr, datumkolom), roostersheet.Cells(huisnr, datumkolom + stay - 1)).Cells.Count Then

                                                    Range(roostersheet.Cells(huisnr, datumkolom), roostersheet.Cells(huisnr, datumkolom + stay - 1)).Value = Reservationsheet.Cells(iD, 1).Value
                                                End If
                                            'End If
                                        Next datumkolom
                                    End If
                                ElseIf IsError(cottageId) Then zoekklasse = zoekklasse + k And cottage_size = cottage_size + p And klasseKolom = klasseKolom + k And SizeKolom = SizeKolom + p
                                                    cottageId = (Evaluate("MATCH(1,(" & klasseKolom.Address(External:=True) & "=" & zoekklasse & ")*(" & SizeKolom.Address(External:=True) & "=" & cottage_size & "),0)"))
                                                    huisnr = cottageId                  'indien er geen match is??
                                End If
                            Next p
                        Next k

</code>```

thanks in advance

答:
Normally to run worksheet functions you would use the WorksheetFunction API.

Early-bound, Application.WorksheetFunction.Match gives you compile-time validation and idiomatic VBA runtime errors in case of mismatch (i.e. you can handle a mismatch with an On Error statement).

Late-bound, Application.Match loses compile-time validation, but now you get a Variant/Error result instead of a VBA runtime error in case of mismatch.

Using the late-bound version, you would have to validate that the result is usable before you consume it. The IsError standard library function returns true given a Variant/Error argument, so here:

```<code>If IfError(cottageId) Then
    '...
End If
</code>```

Try changing it to:

```<code>If IsError(cottageId) Then
    '...
End If
</code>```

That makes your control flow look something like this:

```<code>For i = 1 To iterations
    Dim result As Variant
    result = Evaluate("complicated Excel formula string")
    If Not IsError(result) Then
        'TODO process valid result here
        Exit For 'we're done, no need to keep looping
    End If
Next
</code>```

Consider heeding Darren's advice though: it does seem Range.Find could be a better tool here. Loop logic remains the same: last thing you want is to GoTo-jump and increment i until the counter overflows its data type - with a For loop you can cap the maximum number of attempts beyond which you just gotta admit that you didn't get a match for the given cottage_size; Range.Find/Range.FindNext have mechanisms that kind of already implement this for you.

Body:
is there a way to handle an error in a loop
I use a match function to match a cottage with the right size and class as it is reserved. But if there is no cottage_size available, the match function returns an error, after which I want to upgrade the cottage(cottage_size=cottage_size+1) and search for a match again..

My question is how do i go back to the match function after the error and after I upgraded the size..

 If som = 0 And iDklasse = class And iDpers = cottage_size Then

                        Set klasseKolom = cottagesheet.UsedRange.Columns(3)
                        Set SizeKolom = cottagesheet.UsedRange.Columns(2)

                        For k = 4 To 1 Step -1
                            For p = 2 To 12

                                cottageId = (Evaluate("MATCH(1,(" & klasseKolom.Address(External:=True) & "=" & zoekklasse & ")*(" & SizeKolom.Address(External:=True) & "=" & cottage_size & "),0)"))
                                If Not IsError(cottageId) Then
                                huisnr = cottageId
                                    If Application.CountIf(validatorsheet.Range("B:B"), huisnr) = 0 Then                               'cottage beschikbaarheid (gaat niet goed)
                                        validatorsheet.Cells(iD, 2).Value = cottagesheet.Cells(cottageId, 1).Value                      'invullen in validatorsheet
                                        stay = Reservationsheet.Cells(iD, 3).Value
                                        arrival_date = Reservationsheet.Cells(iD, 2).Value
                                        For datumkolom = 2 To laatstekolom
                                            If arrival_date = roostersheet.Cells(1, datumkolom).Value Then
                                                 'If Application.CountBlank(Range(roostersheet.Cells(huisnr, datumkolom), roostersheet.Cells(huisnr, datumkolom + stay - 1))) = Range(roostersheet.Cells(huisnr, datumkolom), roostersheet.Cells(huisnr, datumkolom + stay - 1)).Cells.Count Then

                                                    Range(roostersheet.Cells(huisnr, datumkolom), roostersheet.Cells(huisnr, datumkolom + stay - 1)).Value = Reservationsheet.Cells(iD, 1).Value
                                                End If
                                            'End If
                                        Next datumkolom
                                    End If
                                ElseIf IsError(cottageId) Then zoekklasse = zoekklasse + k And cottage_size = cottage_size + p And klasseKolom = klasseKolom + k And SizeKolom = SizeKolom + p
                                                    cottageId = (Evaluate("MATCH(1,(" & klasseKolom.Address(External:=True) & "=" & zoekklasse & ")*(" & SizeKolom.Address(External:=True) & "=" & cottage_size & "),0)"))
                                                    huisnr = cottageId                  'indien er geen match is??
                                End If
                            Next p
                        Next k

thanks in advance

Body:
Normally to run worksheet functions you would use the WorksheetFunction API.

Early-bound, Application.WorksheetFunction.Match gives you compile-time validation and idiomatic VBA runtime errors in case of mismatch (i.e. you can handle a mismatch with an On Error statement).

Late-bound, Application.Match loses compile-time validation, but now you get a Variant/Error result instead of a VBA runtime error in case of mismatch.

Using the late-bound version, you would have to validate that the result is usable before you consume it. The IsError standard library function returns true given a Variant/Error argument, so here:

If IfError(cottageId) Then
    '...
End If

Try changing it to:

If IsError(cottageId) Then
    '...
End If

That makes your control flow look something like this:

For i = 1 To iterations
    Dim result As Variant
    result = Evaluate("complicated Excel formula string")
    If Not IsError(result) Then
        'TODO process valid result here
        Exit For 'we're done, no need to keep looping
    End If
Next

Consider heeding Darren's advice though: it does seem Range.Find could be a better tool here. Loop logic remains the same: last thing you want is to GoTo-jump and increment i until the counter overflows its data type - with a For loop you can cap the maximum number of attempts beyond which you just gotta admit that you didn't get a match for the given cottage_size; Range.Find/Range.FindNext have mechanisms that kind of already implement this for you.


问:
How to center an svg <pattern> inside a larger responsive container at all possible widths?
I have a responsive SVG container and I need my <pattern> to appear centered on every situation.

I mean:

The <pattern> triangle should be centered at all possible widths

And the space on left/right must repeat the triangle <pattern>

Is this possible? I know it's possible dynamically recalculating the pattern position with JS. But I would like to do it using svg properties only.

.mySvg1 {
  width: 600px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

.mySvg2 {
  width: 400px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

.mySvg3 {
  width: 200px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

span {
  font-weight: bold;
  color: red;
}

.myDiv1 {
  margin-bottom: 16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="myDiv1">
   SEE THAT THE TRIANGLE IS <span>NOT</span> CENTERED. I WOULD LIKE IT TO ALWAYS BE CENTERED
 </div>

<div>
  <svg class="mySvg1">
    <defs>
      <pattern
        id="wave"
        width="150"
        height="50"
        patternUnits="userSpaceOnUse"
      >
        <path d="M 0 50 l 75 -50 l 75 50" stroke="black" stroke-width="2"/>
      </pattern>
    </defs>
    <rect x="0" y="0" width="100%" height="100%" fill="url(#wave)"/>
  </svg>
</div>

<div>
  <svg class="mySvg2">
    <rect x="0" y="0" width="100%" height="100%" fill="url(#wave)"/>
  </svg>
</div>

<div>
  <svg class="mySvg3">
    <rect x="0" y="0" width="100%" height="100%" fill="url(#wave)"/>
  </svg>
 </div></code>```

EXTRA:

It's easy to do it with background-image. I would like to do the same using <svg> only. Is this possible?

div {
  margin-bottom: 16px;
}

.myDiv1 {
  width: 600px;
  height: 50px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 -2 150 52"><path d="M 0 50 l 75 -50 l 75 50" stroke="black" /></svg>');
  background-position: center;
}

.myDiv2 {
  width: 400px;
  height: 50px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 -2 150 52"><path d="M 0 50 l 75 -50 l 75 50" stroke="black" /></svg>');
  background-position: center;
}

.myDiv3 {
  width: 200px;
  height: 50px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 -2 150 52"><path d="M 0 50 l 75 -50 l 75 50" stroke="black" /></svg>');
  background-position: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  SEE THAT THE TRIANGLE IS ALWAYS CENTERED
</div>

<div class="myDiv1">
</div>

<div class="myDiv2">
</div>

<div class="myDiv3">
</div></code>```

答:
Here is an idea where you need to:

set a big width to the rect considering the width of path (an odd multiplier of the width of the path)

you make the width of the pattern using percentage (100/n where n is the multiplier). You also remove patternUnits="userSpaceOnUse"

You place the rect at 50% and you translate it back with 50% to have it in the middle

In other words, we make the rect very big and we center it inside the SVG. The odd multiplier is to make sure the center of rect is the centre of a triangle and not the between two triangles.

.mySvg1 {
  width: 600px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

.mySvg2 {
  width: 400px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

.mySvg3 {
  width: 200px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

span {
  font-weight: bold;
  color: red;
}

.myDiv1 {
  margin-bottom: 16px;
}

rect {
  transform:translate(-50%);
  transform-box:fill-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myDiv1">
   SEE THAT THE TRIANGLE IS <span>NOT</span> CENTERED. I WOULD LIKE IT TO ALWAYS BE CENTERED
 </div>

<div>
  <svg class="mySvg1">
    <defs>
      <pattern
        id="wave"
        width="9.1%"
        height="50"
      >
        <path d="M 0 50 l 75 -50 l 75 50" stroke="black" stroke-width="2"/>
      </pattern>
    </defs>
    <rect x="50%" y="0" width="1672" height="100%" fill="url(#wave)" />
  </svg>
</div>

<div>
  <svg class="mySvg2">
    <rect x="50%" y="0" width="1672" height="100%" fill="url(#wave)"/>
  </svg>
</div>

<div>
  <svg class="mySvg3">
    <rect x="50%" y="0" width="1672" height="100%" fill="url(#wave)"/>
  </svg>
 </div></code>```

Body:
I have a responsive SVG container and I need my <pattern> to appear centered on every situation.

I mean:

The <pattern> triangle should be centered at all possible widths

And the space on left/right must repeat the triangle <pattern>

Is this possible? I know it's possible dynamically recalculating the pattern position with JS. But I would like to do it using svg properties only.

.mySvg1 {
  width: 600px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

.mySvg2 {
  width: 400px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

.mySvg3 {
  width: 200px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

span {
  font-weight: bold;
  color: red;
}

.myDiv1 {
  margin-bottom: 16px;
}

   SEE THAT THE TRIANGLE IS NOT CENTERED. I WOULD LIKE IT TO ALWAYS BE CENTERED

  <svg class="mySvg1">
    <defs>
      <pattern
        id="wave"
        width="150"
        height="50"
        patternUnits="userSpaceOnUse"
      >
        <path d="M 0 50 l 75 -50 l 75 50" stroke="black" stroke-width="2"/>
      </pattern>
    </defs>
    <rect x="0" y="0" width="100%" height="100%" fill="url(#wave)"/>
  </svg>

  <svg class="mySvg2">
    <rect x="0" y="0" width="100%" height="100%" fill="url(#wave)"/>
  </svg>

  <svg class="mySvg3">
    <rect x="0" y="0" width="100%" height="100%" fill="url(#wave)"/>
  </svg>

EXTRA:

It's easy to do it with background-image. I would like to do the same using <svg> only. Is this possible?

div {
  margin-bottom: 16px;
}

.myDiv1 {
  width: 600px;
  height: 50px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 -2 150 52"><path d="M 0 50 l 75 -50 l 75 50" stroke="black" /></svg>');
  background-position: center;
}

.myDiv2 {
  width: 400px;
  height: 50px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 -2 150 52"><path d="M 0 50 l 75 -50 l 75 50" stroke="black" /></svg>');
  background-position: center;
}

.myDiv3 {
  width: 200px;
  height: 50px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 -2 150 52"><path d="M 0 50 l 75 -50 l 75 50" stroke="black" /></svg>');
  background-position: center;
}

  SEE THAT THE TRIANGLE IS ALWAYS CENTERED

Body:
Here is an idea where you need to:

set a big width to the rect considering the width of path (an odd multiplier of the width of the path)

you make the width of the pattern using percentage (100/n where n is the multiplier). You also remove patternUnits="userSpaceOnUse"

You place the rect at 50% and you translate it back with 50% to have it in the middle

In other words, we make the rect very big and we center it inside the SVG. The odd multiplier is to make sure the center of rect is the centre of a triangle and not the between two triangles.

.mySvg1 {
  width: 600px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

.mySvg2 {
  width: 400px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

.mySvg3 {
  width: 200px;
  height: 50px;
  border: 1px dotted red;
  margin-bottom: 16px;
}

span {
  font-weight: bold;
  color: red;
}

.myDiv1 {
  margin-bottom: 16px;
}

rect {
  transform:translate(-50%);
  transform-box:fill-box;
}

<div class="myDiv1">
   SEE THAT THE TRIANGLE IS <span>NOT</span> CENTERED. I WOULD LIKE IT TO ALWAYS BE CENTERED
 </div>

<div>
  <svg class="mySvg1">
    <defs>
      <pattern
        id="wave"
        width="9.1%"
        height="50"
      >
        <path d="M 0 50 l 75 -50 l 75 50" stroke="black" stroke-width="2"/>
      </pattern>
    </defs>
    <rect x="50%" y="0" width="1672" height="100%" fill="url(#wave)" />
  </svg>
</div>

<div>
  <svg class="mySvg2">
    <rect x="50%" y="0" width="1672" height="100%" fill="url(#wave)"/>
  </svg>
</div>

<div>
  <svg class="mySvg3">
    <rect x="50%" y="0" width="1672" height="100%" fill="url(#wave)"/>
  </svg>
 </div>


问:
How to remove the first character of a variable
HI All,

In my js file i am getting an array of records (negetive values ) like this

```<code>deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });
</code>```

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

答:
try this:</p>

```<code>deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? Math.abs(e) : null; });
</code>```

Body:
HI All,

In my js file i am getting an array of records (negetive values ) like this

deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

Body:
try this:

deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? Math.abs(e) : null; });


问:
pandas replace values condition based on another column
I have a dataframe that looks like this:

```<code>col1 col2
Yes  23123
No   23423423
Yes  34234
No   13213
</code>```

I want to replace values in col2 so that if 'Yes' in col1 then return blank and if 'No' return the initial value

I want to see this:

```<code> col1 col2
 Yes
 No   23423423
 Yes
 No   13213
</code>```

I have tried this but 'No' is returning None:

```<code>   def map_value(x):
      if x in ['Yes']:
         return ''
      else:
         return None

   df['col2'] = df['col1'].apply(map_value)
</code>```

答:
You can use numpy for this</p>

```<code>import pandas as pd
import numpy as np
d = {'col1': ['yes', 'no', 'yes', 'no'], 'col2': [23123,23423423,34234,13213]}
df = pd.DataFrame(data=d)
df['col2'] = np.where(df.col1 == 'yes', '', df.col2)
df
</code>```

Body:
I have a dataframe that looks like this:

col1 col2
Yes  23123
No   23423423
Yes  34234
No   13213

I want to replace values in col2 so that if 'Yes' in col1 then return blank and if 'No' return the initial value

I want to see this:

 col1 col2
 Yes
 No   23423423
 Yes
 No   13213

I have tried this but 'No' is returning None:

   def map_value(x):
      if x in ['Yes']:
         return ''
      else:
         return None

   df['col2'] = df['col1'].apply(map_value)

Body:
You can use numpy for this

import pandas as pd
import numpy as np
d = {'col1': ['yes', 'no', 'yes', 'no'], 'col2': [23123,23423423,34234,13213]}
df = pd.DataFrame(data=d)
df['col2'] = np.where(df.col1 == 'yes', '', df.col2)
df


问:
How do i set a date to locale with react-moment?
I have to format a date in ReactJs, so i decided to import Moment.js in my project. So I import Moment as a component :

```<code>import Moment from 'react-moment';
</code>```

In my return :

```<code>return(
    <Moment locale="fr" format="ll">{item.Date}</Moment>
)
</code>```

But this doesn't work and always return the english date format.
Any idea ?

Thannks

答:
You need to import the language you want like:

```<code>import 'moment/locale/en';
</code>```

And for each new moment just set -

```<code>moment().locale('en')
</code>```

Body:
I have to format a date in ReactJs, so i decided to import Moment.js in my project. So I import Moment as a component :

import Moment from 'react-moment';

In my return :

return(
    <Moment locale="fr" format="ll">{item.Date}</Moment>
)

But this doesn't work and always return the english date format.
Any idea ?

Thannks

Body:
You need to import the language you want like:

import 'moment/locale/en';

And for each new moment just set -

moment().locale('en')


问:
how add click event and get the dom in the iframe with react-frame-component?
i use the react-frame-component create a iframe,i want to bind a click event on the iframe and get the dom that id is abc in the iframe. how do that?

above is my code,it's will output null, get the element is not working.what wrong with my code.Help will be appreciated.Thanks.

```<code>...
componentDidMount() {

    var iframe = document.getElementById("ccc");
    console.log(iframe);

    var iwindow = iframe.contentWindow;

    console.log(iwindow);

    var idoc = iwindow.document;

    console.log(idoc);

    console.log(idoc.getElementById('abc'));

  }
return (
      <div>
        <Frame id="ccc">
          <div id="abc">
            <div>this.state.show is true and now I'm visible</div>
          </div>
        </Frame>
      </div>
    );
</code>```

答:
You need to use contentDidMount prop (not componentDidMount).

contentDidMount and contentDidUpdate are conceptually equivalent to componentDidMount and componentDidUpdate, respectively. The reason these are needed is because internally we call ReactDOM.render which starts a new set of lifecycle calls. This set of lifecycle calls are sometimes triggered after the lifecycle of the parent component, so these callbacks provide a hook to know when the frame contents are mounted and updated.

This code should print console.log properly

export default class App extends Component {
  componentDidMount() {}

  contentMounted() {
    console.log("---------1");
    var iframe = document.getElementById("ccc");
    console.log("1", iframe);

    var iwindow = iframe.contentWindow;

    console.log("2", iwindow);

    var idoc = iwindow.document;

    console.log("3", idoc);

    console.log("4", idoc.getElementById("abc"));
  }

  render() {
    return (

        <Frame id="ccc" contentDidMount={this.contentMounted}>

this.state.show is true and now I'm visible

        </Frame>

    );
  }
}
```

Body:
i use the react-frame-component create a iframe,i want to bind a click event on the iframe and get the dom that id is abc in the iframe. how do that?

above is my code,it's will output null, get the element is not working.what wrong with my code.Help will be appreciated.Thanks.

...
componentDidMount() {

    var iframe = document.getElementById("ccc");
    console.log(iframe);

    var iwindow = iframe.contentWindow;

    console.log(iwindow);

    var idoc = iwindow.document;

    console.log(idoc);

    console.log(idoc.getElementById('abc'));

  }
return (

        <Frame id="ccc">

this.state.show is true and now I'm visible

        </Frame>

    );

Body:
You need to use contentDidMount prop (not componentDidMount).

contentDidMount and contentDidUpdate are conceptually equivalent to componentDidMount and componentDidUpdate, respectively. The reason these are needed is because internally we call ReactDOM.render which starts a new set of lifecycle calls. This set of lifecycle calls are sometimes triggered after the lifecycle of the parent component, so these callbacks provide a hook to know when the frame contents are mounted and updated.

This code should print console.log properly

export default class App extends Component {
  componentDidMount() {}

  contentMounted() {
    console.log("---------1");
    var iframe = document.getElementById("ccc");
    console.log("1", iframe);

    var iwindow = iframe.contentWindow;

    console.log("2", iwindow);

    var idoc = iwindow.document;

    console.log("3", idoc);

    console.log("4", idoc.getElementById("abc"));
  }

  render() {
    return (
      <div className="App">
        <Frame id="ccc" contentDidMount={this.contentMounted}>
          <div id="abc">
            <div>this.state.show is true and now I'm visible</div>
          </div>
        </Frame>
      </div>
    );
  }
}


问:
Devops Pull Request workflow validations
We are using Azure devops with the workflow for each task as:

Task branch to Release branch

Then Release branch to master

The reviewer will approve each pull request.

However, a user creating a PR can also create one from task branch directly to master.

Is there any way, by policies/validations that the system can prevent creation of the PR itself, which is from task to master.

答: If you only want a subset of users to manage the merge to master, you can setup branch security on the master branch that prevents contributing to pull requests that would target that branch.


问:
ERROR RangeError: Maximum call stack size exceeded at Object.getApps
I was trying to filter list of titles using Ng2SearchPipeModule. I have imported this module in app.module.ts and then generated new searchbar component

searchbar.component.ts

```<code>import { FirebaseService } from './../../firebase.service';
import { AngularFirestore } from '@angular/fire/firestore';
import { Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-searchbar',
  templateUrl: './searchbar.component.html',
  styleUrls: ['./searchbar.component.css']
})

export class SearchbarComponent implements OnInit{
constructor(private fireService:FirebaseService){}

titles:Array<any>;
  InputText:string;
  ngOnInit(){
    this.gettitles();
  }

  gettitles(){
    this.fireService.read_titles().subscribe(result =>{
      this.titles = result;
      console.log(this.titles);
    })
  }
}
</code>```

And my searchbar.component.html looks like this

```<code>  <div class="search-field">
    <mat-form-field>
      <mat-label>Search</mat-label>
      <input id="input" type="text" matInput placeholder="" autocomplete="off" [(ngModel)]=InputText>
      <div><i class="fas fa-search"></i></div>
    </mat-form-field>
  </div>

  <div class="SearchTitles">
    <tbody>
      <tr *ngFor="let title of titles | filter:InputText">
        <td>{{title.payload.doc.data().title}}</td>
      </tr>
    </tbody>
  </div>
</code>```

I get correct output from my Firebase Firestore.
But Whenever I type any key on the input element I get this error (I have entered 7 characters and I am getting this error 7 times) and also filtering does not happen

It seems this error is due to filer Module. I could get any info about how to fix this error...

Thank you for your Answer

答:
I think the problem is that your titles aren't a array of strings.
Change the title array to an array of strings:

The function in the service could return actual titles:

SERVICE

```<code>constructor(private afs: AngularFirestore) { }

read_titles() {
    return this.afs.collection<{title: string}>('here-your-table').valueChanges().pipe(
        map(list => list.map(v => v.title))
    )
}
</code>```

TS of your component:

```<code>  gettitles(){
    this.fireService.read_titles()
  }
</code>```

And in your html:

```<code>  <tr *ngFor="let title of titles | async | filter:InputText">
    <td>{{title}}</td>
  </tr>
</code>```

Body:
I was trying to filter list of titles using Ng2SearchPipeModule. I have imported this module in app.module.ts and then generated new searchbar component

searchbar.component.ts

import { FirebaseService } from './../../firebase.service';
import { AngularFirestore } from '@angular/fire/firestore';
import { Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-searchbar',
  templateUrl: './searchbar.component.html',
  styleUrls: ['./searchbar.component.css']
})

export class SearchbarComponent implements OnInit{
constructor(private fireService:FirebaseService){}

titles:Array<any>;
  InputText:string;
  ngOnInit(){
    this.gettitles();
  }

  gettitles(){
    this.fireService.read_titles().subscribe(result =>{
      this.titles = result;
      console.log(this.titles);
    })
  }
}

And my searchbar.component.html looks like this

    <mat-form-field>
      <mat-label>Search</mat-label>
      <input id="input" type="text" matInput placeholder="" autocomplete="off" [(ngModel)]=InputText>

    </mat-form-field>

        {{title.payload.doc.data().title}}

I get correct output from my Firebase Firestore.
But Whenever I type any key on the input element I get this error (I have entered 7 characters and I am getting this error 7 times) and also filtering does not happen

It seems this error is due to filer Module. I could get any info about how to fix this error...

Thank you for your Answer

Body:
I think the problem is that your titles aren't a array of strings.
Change the title array to an array of strings:

The function in the service could return actual titles:

SERVICE

constructor(private afs: AngularFirestore) { }

read_titles() {
    return this.afs.collection<{title: string}>('here-your-table').valueChanges().pipe(
        map(list => list.map(v => v.title))
    )
}

TS of your component:

  gettitles(){
    this.fireService.read_titles()
  }

And in your html:

  <tr *ngFor="let title of titles | async | filter:InputText">
    <td>{{title}}</td>
  </tr>


问:
How to call math.factorial from numba with nopython mode?
I need to compute factorials of large integers inside of a for loop that I would like to compile using numba. The factorial function in Python's math module seems to be fast. How can I call this function from numba using nopython mode? Unfortunately this function is not supported by numba currently https://numba.pydata.org/numba-doc/0.17.0/reference/pysupported.html.

```<code>import math
from numba import njit

@njit
def factorial(n):
    return math.factorial(n)

factorial(2)
</code>```

throws a TypingError:

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Unknown attribute 'factorial' of type Module(<module 'math' from '/anaconda3/envs/minimalcondaforge/lib/python3.8/lib-dynload/math.cpython-38-darwin.so'>)

Is there a way to call this function? Can I use @overload or get_cython_function_address as described here http://numba.pydata.org/numba-doc/latest/extending/high-level.html? (I was not able to make it work so far, I am new to numba so I might just not be doing it right.) Also open to other suggestions for a fast factorial function in numba, but it needs to be able to handle large integers.

答:
Numba can't compile Python's arbitrary-precision integers, so if you want to find exact factorials of integers larger than 20—which at 2432902008176640000 is the most that can fit in a 64-bit integer—then Numba unfortunately won't be helpful.

If you don't need the exact integer for large factorials, then you could define your factorial function as the equivalent math.gamma(n+1), which does compile under Numba and has floating-point output. Even this only works up to 170!, though, which is the largest that can fit in a 64-bit float.

Without arbitrary-precision numbers, larger factorials need to be represented in log form. For this you can use math.lgamma(n+1), which also compiles under Numba and can return log(n!) for very high n.

Body:
I need to compute factorials of large integers inside of a for loop that I would like to compile using numba. The factorial function in Python's math module seems to be fast. How can I call this function from numba using nopython mode? Unfortunately this function is not supported by numba currently https://numba.pydata.org/numba-doc/0.17.0/reference/pysupported.html.

import math
from numba import njit

@njit
def factorial(n):
    return math.factorial(n)

factorial(2)

throws a TypingError:

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Unknown attribute 'factorial' of type Module(<module 'math' from '/anaconda3/envs/minimalcondaforge/lib/python3.8/lib-dynload/math.cpython-38-darwin.so'>)

Is there a way to call this function? Can I use @overload or get_cython_function_address as described here http://numba.pydata.org/numba-doc/latest/extending/high-level.html? (I was not able to make it work so far, I am new to numba so I might just not be doing it right.) Also open to other suggestions for a fast factorial function in numba, but it needs to be able to handle large integers.


问:
Python Kind of "State Variable"
Does anyone know, if its possible to define a data type in Python to do the following:

```<code>something = variable.OPEN
if something == variable.OPEN:
    print('open')
elif something == variable.BLOCKED:
    print('blocked')
elif something == variable.CLOSED:
    print('closed')
</code>```

I know that I did something familiar a couple of years ago, but I cant remember how :(

Thanks!

答:
I was looking for Enums in Python.

Thanks to @Samwise

Title: Python Kind of "State Variable"

Body:
Does anyone know, if its possible to define a data type in Python to do the following:

something = variable.OPEN
if something == variable.OPEN:
    print('open')
elif something == variable.BLOCKED:
    print('blocked')
elif something == variable.CLOSED:
    print('closed')

I know that I did something familiar a couple of years ago, but I cant remember how :(

Thanks!


问:
Given a periphery of island mark its interior in matrix (Algorithm)
We are given a matrix of size N which is completely filled with 0's and we are also given a list of coordinates which contains the coordinates of the periphery of an island. Now we have to mark the island (periphery + area that is part of the island) as 1's.

I am having trouble coming up with a solution to this problem, I thought of bfs/dfs but can't think of a way to implement this.
(Please assume that there is 1 island only and the input is correct i.e. all input coordinates form a closed shape and are valid

```<code>N = 5
coordinates =
0,2
1,1
1,3
2,0
2,4
3,1
3,3
4,2
</code>```

So this is what output should look like ---

```<code>    0 1 2 3 4
  0 0 0 1 0 0
  1 0 1 1 1 0
  2 1 1 1 1 1
  3 0 1 1 1 0
  4 0 0 1 0 0
</code>```

All the coordinates marked and the square boxes inside them marked which are a part of the island.

答:
If you know a point that is inside the island, then you can solve this with a DFS or BFS-based flood fill starting at that point.

It's a little bit tricky to find such a point reliably, though, so I suggest an easier way: Instead of using a flood fill to find the points that are inside the island, start the flood fill at all the 0 points along the matrix boundary to find the points that are not inside the island.  Then set all the points you didn't find to 1.

Body:
We are given a matrix of size N which is completely filled with 0's and we are also given a list of coordinates which contains the coordinates of the periphery of an island. Now we have to mark the island (periphery + area that is part of the island) as 1's.

I am having trouble coming up with a solution to this problem, I thought of bfs/dfs but can't think of a way to implement this.
(Please assume that there is 1 island only and the input is correct i.e. all input coordinates form a closed shape and are valid

N = 5
coordinates =
0,2
1,1
1,3
2,0
2,4
3,1
3,3
4,2

So this is what output should look like ---

    0 1 2 3 4
  0 0 0 1 0 0
  1 0 1 1 1 0
  2 1 1 1 1 1
  3 0 1 1 1 0
  4 0 0 1 0 0

All the coordinates marked and the square boxes inside them marked which are a part of the island.


问:
Unreal 4.24.3 : How to Declare UPROPERTY() inside .cpp file
What I want to do:

Create a USceneComponent at Runtime in an Actor class

```<code>    USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID));
</code>```

What works:

Defining UnitDesign at Header File(.h) works without issues..

```<code>UPROPERTY(VisibleAnywhere)  //I can see UnitDesign in World Outliner
USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID));
</code>```

What does not work for me:

Defining UnitDesign at CPP File(.cpp) inside BeginPlay() of Actor class-

```<code>UPROPERTY(VisibleAnywhere)  //I can NOT see UnitDesign in World Outliner
USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID));
</code>```

Any pointers appreciated.

答:
If you always want to create the UnitDesign SceneComponent then you can use CreateDefaultSubobject (c'tor only) :

```<code>/* .h */
UCLASS()
class AYourActor : public AActor
{
    GENERATED_BODY()

public:
    AYourActor(FObjectInitializer const& ObjectInitializer);

    UPROPERTY(VisibleAnywhere)
    USceneComponent* UnitDesign;
};

/* .cpp */
AYourActor::AYourActor(FObjectInitializer const& ObjectInitializer) :
    UnitDesign(nullptr) /* this is only needed if UnitDesign is not initialized below */
{
    UnitDesign = CreateDefaultSubobject<USceneComponent>(TEXT("Unit Design"));
}
</code>```

If it's an optional thing then that's a bit more complicated, you can create a component later than the c'tor but you'll need to be a bit more conscious about when to get it to play nice with VisibleAnywhere. The code for that would just be

```<code>UnitDesign = NewObject<USceneComponent>(this, FName(*ID));
UnitDesign->RegisterComponent();
</code>```

The sneaky way to refresh the property panel is to call :

```<code>GEditor->SelectActor(this, true, true);
GEditor->SelectNone(true, true);
</code>```

The "proper" way is to call SDetailsView::ForceRefresh from a IDetailCustomization. Fair warning, it's a huge arse.

Side note that UPROPERTY() can only be used in a .h file as it needs to be visible to the Unreal Header Tool.

Body:
What I want to do:

Create a USceneComponent at Runtime in an Actor class

    USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID));

What works:

Defining UnitDesign at Header File(.h) works without issues..

UPROPERTY(VisibleAnywhere)  //I can see UnitDesign in World Outliner
USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID));

What does not work for me:

Defining UnitDesign at CPP File(.cpp) inside BeginPlay() of Actor class-

UPROPERTY(VisibleAnywhere)  //I can NOT see UnitDesign in World Outliner
USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID));

Any pointers appreciated.

Body:
If you always want to create the UnitDesign SceneComponent then you can use CreateDefaultSubobject (c'tor only) :

/* .h */
UCLASS()
class AYourActor : public AActor
{
    GENERATED_BODY()

public:
    AYourActor(FObjectInitializer const& ObjectInitializer);

    UPROPERTY(VisibleAnywhere)
    USceneComponent* UnitDesign;
};

/* .cpp */
AYourActor::AYourActor(FObjectInitializer const& ObjectInitializer) :
    UnitDesign(nullptr) /* this is only needed if UnitDesign is not initialized below */
{
    UnitDesign = CreateDefaultSubobject<USceneComponent>(TEXT("Unit Design"));
}

If it's an optional thing then that's a bit more complicated, you can create a component later than the c'tor but you'll need to be a bit more conscious about when to get it to play nice with VisibleAnywhere. The code for that would just be

UnitDesign = NewObject<USceneComponent>(this, FName(*ID));
UnitDesign->RegisterComponent();

The sneaky way to refresh the property panel is to call :

GEditor->SelectActor(this, true, true);
GEditor->SelectNone(true, true);

The "proper" way is to call SDetailsView::ForceRefresh from a IDetailCustomization. Fair warning, it's a huge arse.

Side note that UPROPERTY() can only be used in a .h file as it needs to be visible to the Unreal Header Tool.


问:
Can fitness functions be of the type "minimum-value as best-value" in GA?
I have implemented a genetic algorithm, in which the fitness function considers the coefficient of variation of the data as the fitness value, and so the closer the COV is to zero, the better. Will it still be called the fitness function? Usually the fitness value is defined such that the greater the value, the better.

答:
An abstract & direct answer would be fitness function is a measure for your solutions and it should be well defined to drive the search space to a near-optimal solution you want to achieve for your problem instance. You can find more for designing fitness function here: A guide for fitness function design

You can definitely have an EA for the maximization or minimization problem. A general evolutionary cycle is shown in the image below (from one of the text book-Introduction to Evolutionary Computing). As per the EA cycle, you need to evaluate your solutions after the population is created, and after offsprings are created. Basically, survivor selection is the process where you would like to focus on maximization or minimization, and your problem is minimization. For your problem, you might want to adopt one of the following approaches:

When you create your fitness function, you can negate the fitness. And make sure in this approach you have to choose the highest fitness individuals for next-generation (aka in survivor selection).

Let your fitness function be positive. But as you want to approach as a minimization problem, you have to choose the lowest fitness individuals for next-generation (aka in survivor selection).


问:
How to querying in Snowflake using Python (SSO Authentication)?
I tried to connect snowflake(SSO Authentication) and get data from table.
But, When i run the code, i can login with my credentials in the pop-up browser window and it connect Snowflake, no response after that(the program neither terminate nor provide result).
Not sure, where am doing mistake, Pls help.

'''

```<code>import snowflake.connector
# Connecting to Snowflake using SAML 2.0-compliant IdP federated authentication
conn = snowflake.connector.connect(
  user='G*****K',
  account='abcdf',
  authenticator='externalbrowser',
  warehouse='abcdf',
  database='abcdf',
  schema='abcdf'
)
cur = conn.cursor()
sql = "select * from abcdf.ACCT limit 10"
x=cur.execute(sql)
cur.close()
print(x)
'''
</code>```

答:
I believe you are closing the cursor before the print;

```<code>    try:
    cur.execute("SELECT col1, col2 FROM test_table ORDER BY col1")
    for (col1, col2) in cur:
        print('{0}, {1}'.format(col1, col2))
    finally:
    cur.close()
</code>```

Details: https://docs.snowflake.com/en/user-guide/python-connector-example.html#using-cursor-to-fetch-values

Body:
I tried to connect snowflake(SSO Authentication) and get data from table.
But, When i run the code, i can login with my credentials in the pop-up browser window and it connect Snowflake, no response after that(the program neither terminate nor provide result).
Not sure, where am doing mistake, Pls help.

'''

import snowflake.connector
# Connecting to Snowflake using SAML 2.0-compliant IdP federated authentication
conn = snowflake.connector.connect(
  user='G*****K',
  account='abcdf',
  authenticator='externalbrowser',
  warehouse='abcdf',
  database='abcdf',
  schema='abcdf'
)
cur = conn.cursor()
sql = "select * from abcdf.ACCT limit 10"
x=cur.execute(sql)
cur.close()
print(x)
'''

Body:
I believe you are closing the cursor before the print;

    try:
    cur.execute("SELECT col1, col2 FROM test_table ORDER BY col1")
    for (col1, col2) in cur:
        print('{0}, {1}'.format(col1, col2))
    finally:
    cur.close()

Details: https://docs.snowflake.com/en/user-guide/python-connector-example.html#using-cursor-to-fetch-values


问:
How to find the minimum sum and the corresponding index by iterations?
I need to determine the minimum value and the corresponding index when it is achieved according to the equation that divides the time series by two parts:

In this equation, n1 and n2 are the sizes of the two parts of the time series which constitute the original time series of the size n. The following additional conditions are set to the equation: the minimum size of the first part of the time series is set to be n1 = 10 for which n2 = n – n1, and then the size is increased: n1 = 11, 12,…, k, where k = n – 10 at which n2 = 10.

I have tried to program this equation to find the minimum sum by iterations, but I am not sure that the script is correct. In particular, are the loops correctly applied? Also, it seems like n2=11 here at the end, but it has to be 10 when the iterations finish.

```<code>n=66; % The size of the original time series for the characteristic Y (e.g., temperature)
n1=n-20; % This operation is needed for the loops below
minsum=10000000; % Declaration of the variable needed for the "if" operator at the end of the script.
for j=1:n1
    ik=10+j-1;  % This is from 10 to 55
    s31=0; % This is preallocation
    for i=1:ik  % This is from 1 to 10, 11,...,55
        s31=s31+Y(i); % The values are taken from 1 to 10,11,...,55
        cn=ik; % This is from 10 to 55
        Mean1=s31/cn; % Finding of the means from 1 to 10,11,...,55. So, the minimum size of the sample over which the mean is found is 10 years
        s32=0;
        s32=s32+(Y(i)-Mean1).^2; % This is the first term of the equation
        s41=0;
        in1=ik+1; % This is from 11 to 56
        for k=in1:n % This is from 11 to 66
            s41=s41+Y(k);
            mn=n-in1+1; % This is from 56 to 11
            Mean2=s41/mn; % Finding of the means from 66 to 11,12,...,56 or from 11,12,...,56 to 66 to be consistent with the notation in the formula. So, the minimum size of the sample over which the mean is found is 11 years
            s42=0;
            s42=s42+(Y(k)-Mean2).^2; % This is the second term of the equation
            summation=s32+s42; % Finding the sums between all possible sizes of the two parts of the time series
            if summation<minsum
                minsum=summation % The minimum sum is displayed in the last output among the iterated values.
                imin=in1 % Finding the index in the original time series for which the minimum sum is achieved.
            end
        end
    end
end
</code>```

答:
The task is actually simpler and requires a shorter code. Suppose that we have monthly temperature data for a range of years. Then, it is enough to use two 'for' loops to solve the problem:</p>

```<code>a=load('filename.txt');
JanT=a(:,2); % Monthy temperature data for January
Years=a(:,1); % Years in the time series
n=length(JanT); % The size of the original time series
n1=n-19; % This operation is needed for the 'for' loop below
n2=n-9; % This operation is needed for the 'for' loop below

S1=[]; % Initialisation of the sum for the first term of the equation (in the vector form)
for i=1:n1
    A=sum((JanT(1:i+9)-mean(JanT(1:i+9))).^2); % Finding of the sums from 1 to 10, 11,...56.
S1=[S1,A]; % Writing of the obtained results into the array
end

S2=[]; % Initialisation of the sum for the second term of the equation (in the vector form)
for j=11:n2
    B=sum((JanT(j:n)-mean(JanT(j:n))).^2); % Finding of the sums from 66 to 11, 12,...57
S2=[S2,B]; % Writing of the obtained results into the array
end

Sum=S1+S2; % Finding the sums between all possible sizes of the two parts of the time series

[minsum,imin]=min(Sum) % Finding the minimum sum and the corresponding index when it is achieved
Years=Years+10; % Shifting the years properly to find the year when the minimum sum is achieved
imin=Years(imin) % Attribution of the found index to the year in the original time series
</code>```

Body:
I need to determine the minimum value and the corresponding index when it is achieved according to the equation that divides the time series by two parts:

In this equation, n1 and n2 are the sizes of the two parts of the time series which constitute the original time series of the size n. The following additional conditions are set to the equation: the minimum size of the first part of the time series is set to be n1 = 10 for which n2 = n – n1, and then the size is increased: n1 = 11, 12,…, k, where k = n – 10 at which n2 = 10.

I have tried to program this equation to find the minimum sum by iterations, but I am not sure that the script is correct. In particular, are the loops correctly applied? Also, it seems like n2=11 here at the end, but it has to be 10 when the iterations finish.

n=66; % The size of the original time series for the characteristic Y (e.g., temperature)
n1=n-20; % This operation is needed for the loops below
minsum=10000000; % Declaration of the variable needed for the "if" operator at the end of the script.
for j=1:n1
    ik=10+j-1;  % This is from 10 to 55
    s31=0; % This is preallocation
    for i=1:ik  % This is from 1 to 10, 11,...,55
        s31=s31+Y(i); % The values are taken from 1 to 10,11,...,55
        cn=ik; % This is from 10 to 55
        Mean1=s31/cn; % Finding of the means from 1 to 10,11,...,55. So, the minimum size of the sample over which the mean is found is 10 years
        s32=0;
        s32=s32+(Y(i)-Mean1).^2; % This is the first term of the equation
        s41=0;
        in1=ik+1; % This is from 11 to 56
        for k=in1:n % This is from 11 to 66
            s41=s41+Y(k);
            mn=n-in1+1; % This is from 56 to 11
            Mean2=s41/mn; % Finding of the means from 66 to 11,12,...,56 or from 11,12,...,56 to 66 to be consistent with the notation in the formula. So, the minimum size of the sample over which the mean is found is 11 years
            s42=0;
            s42=s42+(Y(k)-Mean2).^2; % This is the second term of the equation
            summation=s32+s42; % Finding the sums between all possible sizes of the two parts of the time series
            if summation<minsum
                minsum=summation % The minimum sum is displayed in the last output among the iterated values.
                imin=in1 % Finding the index in the original time series for which the minimum sum is achieved.
            end
        end
    end
end

Body:
The task is actually simpler and requires a shorter code. Suppose that we have monthly temperature data for a range of years. Then, it is enough to use two 'for' loops to solve the problem:

a=load('filename.txt');
JanT=a(:,2); % Monthy temperature data for January
Years=a(:,1); % Years in the time series
n=length(JanT); % The size of the original time series
n1=n-19; % This operation is needed for the 'for' loop below
n2=n-9; % This operation is needed for the 'for' loop below

S1=[]; % Initialisation of the sum for the first term of the equation (in the vector form)
for i=1:n1
    A=sum((JanT(1:i+9)-mean(JanT(1:i+9))).^2); % Finding of the sums from 1 to 10, 11,...56.
S1=[S1,A]; % Writing of the obtained results into the array
end

S2=[]; % Initialisation of the sum for the second term of the equation (in the vector form)
for j=11:n2
    B=sum((JanT(j:n)-mean(JanT(j:n))).^2); % Finding of the sums from 66 to 11, 12,...57
S2=[S2,B]; % Writing of the obtained results into the array
end

Sum=S1+S2; % Finding the sums between all possible sizes of the two parts of the time series

[minsum,imin]=min(Sum) % Finding the minimum sum and the corresponding index when it is achieved
Years=Years+10; % Shifting the years properly to find the year when the minimum sum is achieved
imin=Years(imin) % Attribution of the found index to the year in the original time series


问:
Pandas read_csv huge file (50gb) issue
I'm trying to open a huge csv file (ca. 50gb) through Pandas.read_csv.
I saw other question in which the solution is to use chunks, but it is not a good way for me.
This file contains lot of data (I don't know how many) from '95 to present. Actually, I need to use just the ending rows (eg. from 2010) that probably allow me to read the file.
Many thanks for your support </p>

答:
Try Dask. I just started using this wonderful library as I was running into similar issues. It is very similar to pandas (although a litlle bit limited on all of the functions) but allows you to read in much more data and do a lot of basic functions like merge, groupby, and many more.

https://docs.dask.org/en/latest/dataframe.html

From the linked documentation above, below is how you would read in a file with dask. It is the same code as pandas.

```<code>import dask.dataframe as dd
df = dd.read_csv('2014-*.csv')
df.head()
</code>```

Title: Pandas read_csv huge file (50gb) issue

Body:
Try Dask. I just started using this wonderful library as I was running into similar issues. It is very similar to pandas (although a litlle bit limited on all of the functions) but allows you to read in much more data and do a lot of basic functions like merge, groupby, and many more.

https://docs.dask.org/en/latest/dataframe.html

From the linked documentation above, below is how you would read in a file with dask. It is the same code as pandas.

import dask.dataframe as dd
df = dd.read_csv('2014-*.csv')
df.head()