问:
What is the difference between CSS fit-content and max-content?
I'm following this article https://css-tricks.com/almanac/properties/w/width/ to try to understand how this rules work.

I have this example:

*{margin:0; padding:0}
.box{
  background: lightgreen;
  margin: 0 auto;
  width: -webkit-fit-content;
  width: -moz-fit-content;
  width: fit-content;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <img src="https://tyrannyoftradition.files.wordpress.com/2012/05/cutest-kitten-hat-ever-13727-1238540322-17.jpg" alt="" />
  <figure>Yes, put some text here that is wider than the image above to try some new rules</figure>
</div></code>```

The article says that fit-content can be used to center a div of unknown width with margin: x auto;

But if you change fit-content for max-content in this example, this is working anyway and they seem to behave always in the same way.

Does anyone know what is the difference between this two rules and in which cases should I use one or the other?

答:
It seems these two codes are the same:

```<code>.fit-content {
  width: fit-content;
}
// is same as
.fit-content {
  width: max-content;
  max-width: 100%;
  min-width: min-content;
}
</code>```

In my experience I either go with width: fit-content or width: max-content; max-width: 100%. The latter is for cases when the element shouldn't have a min-width.

Body:
I'm following this article https://css-tricks.com/almanac/properties/w/width/ to try to understand how this rules work.

I have this example:

*{margin:0; padding:0}
.box{
  background: lightgreen;
  margin: 0 auto;
  width: -webkit-fit-content;
  width: -moz-fit-content;
  width: fit-content;
}

Yes, put some text here that is wider than the image above to try some new rules

The article says that fit-content can be used to center a div of unknown width with margin: x auto;

But if you change fit-content for max-content in this example, this is working anyway and they seem to behave always in the same way.

Does anyone know what is the difference between this two rules and in which cases should I use one or the other?

Body:
It seems these two codes are the same:

.fit-content {
  width: fit-content;
}
// is same as
.fit-content {
  width: max-content;
  max-width: 100%;
  min-width: min-content;
}

In my experience I either go with width: fit-content or width: max-content; max-width: 100%. The latter is for cases when the element shouldn't have a min-width.


来源: stackexchange

问:
Replacing values with weight in a table
I have a table that holds the value of my assets and one column with the total value. I was wondering if there is a way to replace each of the absolute value with the weight

```<code>Apple Google FB MSFT Total
2       3    1    0    6
1       2    4    1    8
...
</code>```

and I want to change it to

```<code>Apple Google   FB     MSFT   Total
0.33    0.5    0.166    0      6
0.125   0.25    0.5    0.125   8
...
</code>```

Are there any elegant ways to do this with python?

Thank you

答:
Just divide all values by the corresponding value in the Total column.

```<code>df.iloc[:, :-1] = df.iloc[:, :-1].div(df['Total'], 0)
</code>```

edit: and think about what you want if the total is zero.

ContentLicense: CC BY-SA 4.0

Title: Replacing values with weight in a table

Body:
I have a table that holds the value of my assets and one column with the total value. I was wondering if there is a way to replace each of the absolute value with the weight

Apple Google FB MSFT Total
2       3    1    0    6
1       2    4    1    8
...

and I want to change it to

Apple Google   FB     MSFT   Total
0.33    0.5    0.166    0      6
0.125   0.25    0.5    0.125   8
...

Are there any elegant ways to do this with python?

Thank you

Body:
Just divide all values by the corresponding value in the Total column.

df.iloc[:, :-1] = df.iloc[:, :-1].div(df['Total'], 0)

edit: and think about what you want if the total is zero.


问:
how to migrate away from ConfigurationManager in .net 6
I am trying to migrate a legacy .net framework project to .net 6

One problem is that we have a Constants class, which contains code like this:

```<code>public static class Constants
{
   public static int MaxCodes = Convert.ToInt32(ConfigurationManager.AppSettings["MaxCodes"] ?? "250");
}
</code>```

How can I move this to .net 6? I don't think IConfiguration is Injectable in a static class, so need to change this class to a non-static one and using services.AddSingleton.

But it means lots of code changes in the referenced code. Are there other ways to do it?

答:
Are there other ways to do it?

You can stick with the static class and pass the dependencies to a custom Initialize method, which you call on bootstrap.

```<code>public static class Constants
{
    private static bool _isInitialized;

    static Constants()
    {
        _isInitialized = false;
    }

    static void Initialize(IConfiguration configurationManager)
    {
        if (!_isInitialized)
        {
            MaxCodes = Convert.ToInt32(configurationManager.AppSettings["MaxCodes"] ?? "250");
            _isInitialized = true;
        }
    }

    public static int MaxCodes { get; private set; }
}
</code>```

The _isInitialized flag and private setters ensure the state can no longer be changed after bootstrap.

Body:
I am trying to migrate a legacy .net framework project to .net 6

One problem is that we have a Constants class, which contains code like this:

public static class Constants
{
   public static int MaxCodes = Convert.ToInt32(ConfigurationManager.AppSettings["MaxCodes"] ?? "250");
}

How can I move this to .net 6? I don't think IConfiguration is Injectable in a static class, so need to change this class to a non-static one and using services.AddSingleton.

But it means lots of code changes in the referenced code. Are there other ways to do it?

Body:
Are there other ways to do it?

You can stick with the static class and pass the dependencies to a custom Initialize method, which you call on bootstrap.

public static class Constants
{
    private static bool _isInitialized;

    static Constants()
    {
        _isInitialized = false;
    }

    static void Initialize(IConfiguration configurationManager)
    {
        if (!_isInitialized)
        {
            MaxCodes = Convert.ToInt32(configurationManager.AppSettings["MaxCodes"] ?? "250");
            _isInitialized = true;
        }
    }

    public static int MaxCodes { get; private set; }
}

The _isInitialized flag and private setters ensure the state can no longer be changed after bootstrap.


问:
RandomForestClassifier with n_estimators=1 and min_impurity_decrease=0 yields 100% train accuracy on complex dataset
I have a RandomForestClassifier in sklearn with the following parameters:

clf = RandomForestClassifier(n_estimators=1,
                             min_impurity_decrease=0,
                             max_features=3,
                             bootstrap=False,
                             random_state=j,
                             criterion='entropy',
                             warm_start=False)
```
<p>Features and Labels:</p>
<ul>
<li>My feature matrix X (pd.DataFrame) has shape (100,110), i.e. 110 features.</li>
<li>The labels are vectors of length 10, i.e. I am trying to predict 10 targets.</li>
</ul>
<p>The feature matrix contains a feature x_i for i=1,...,10 from which I construct the labels:</p>
<pre class="lang-py prettyprint-override"><code>y_i = np.sign(X['x_i'].diff(1).shift(-1))
</code>```

The labels are in {-1,1} (no label value 0 possible) and they are the one-step-ahead change of the feature x_i for i=1,...,10. The label vector at each time t is then given as the set of all labels at time t:

```<code>y[t] = {y_i[t] | i=1,...,10}
</code>```

While training the classifier, I noticed that the training accuracy is 100% for min_impurity_decrease=0, and the test accuracy is between 50-60%. This happens even in the extreme case of n_estimators=1, which is just a single tree.

When I increase min_impurity_decrease>0, the training accuracy decreases, while the test accuracy remains roughly the same.

It seems to me that there is some kind of leakage going on during the training, because of which the classifier achieves such high training accuracy and overfits.

Strangely, even if I entirely remove the features x_i from the feature matrix, and just use them to construct the labels, the high training accuracy persists. Finally, even if I only predict the label for a single target x_i, i.e. y_i, the training accuracy is still 100%. Also I checked my dataset several times, it should be ok. I am out of explanations.

Why this high accuracy is achieved even with a single tree? It seems highly illogical to me.

答: Set the max_depth argument to something other than the None, which is default. It expands the tree until you rich 100% accuracy, that's the reason. It obviously overfits. Use max_depth=2, 4, 8, etc.</p>

Body:
I have a RandomForestClassifier in sklearn with the following parameters:

clf = RandomForestClassifier(n_estimators=1,
                             min_impurity_decrease=0,
                             max_features=3,
                             bootstrap=False,
                             random_state=j,
                             criterion='entropy',
                             warm_start=False)

Features and Labels:

My feature matrix X (pd.DataFrame) has shape (100,110), i.e. 110 features.

The labels are vectors of length 10, i.e. I am trying to predict 10 targets.

The feature matrix contains a feature x_i for i=1,...,10 from which I construct the labels:

y_i = np.sign(X['x_i'].diff(1).shift(-1))

The labels are in {-1,1} (no label value 0 possible) and they are the one-step-ahead change of the feature x_i for i=1,...,10. The label vector at each time t is then given as the set of all labels at time t:

y[t] = {y_i[t] | i=1,...,10}

While training the classifier, I noticed that the training accuracy is 100% for min_impurity_decrease=0, and the test accuracy is between 50-60%. This happens even in the extreme case of n_estimators=1, which is just a single tree.

When I increase min_impurity_decrease>0, the training accuracy decreases, while the test accuracy remains roughly the same.

It seems to me that there is some kind of leakage going on during the training, because of which the classifier achieves such high training accuracy and overfits.

Strangely, even if I entirely remove the features x_i from the feature matrix, and just use them to construct the labels, the high training accuracy persists. Finally, even if I only predict the label for a single target x_i, i.e. y_i, the training accuracy is still 100%. Also I checked my dataset several times, it should be ok. I am out of explanations.

Why this high accuracy is achieved even with a single tree? It seems highly illogical to me.


问:
Telegram bot - sendMessage() returns Promise object, but should be Message object
On success of sendMessage() method, the sent Message object is returned, but I'm getting Promise object instead. Source: https://core.telegram.org/bots/api#sendmessage

What should i do to get Message object?

```<code>console.log(bot.sendMessage(chatId, `some text`))
</code>```

Log result is below

```<code><ref *1> Promise [Object] {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _cancellationParent: <ref *2> Promise [Object] {
    _bitField: 1,
    _fulfillmentHandler0: undefined,
    _rejectionHandler0: [Function (anonymous)],
    _promise0: [Circular *1],
    _receiver0: undefined,
    _cancellationParent: Promise [Object] {
      _bitField: 1,
      _fulfillmentHandler0: [Function (anonymous)],
      _rejectionHandler0: undefined,
      _promise0: [Circular *2],
      _receiver0: undefined,
      _onCancelField: [Function (anonymous)],
      _branchesRemainingToCancel: 1
    },
    _branchesRemainingToCancel: 1
  }
}
</code>```

答:
You should await an async function by adding await in the beginning of your function call like this:

console.log(await bot.sendMessage(chatId, `some text`))
```

Body:
On success of sendMessage() method, the sent Message object is returned, but I'm getting Promise object instead. Source: https://core.telegram.org/bots/api#sendmessage

What should i do to get Message object?

console.log(bot.sendMessage(chatId, `some text`))

Log result is below

<ref *1> Promise [Object] {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _cancellationParent: <ref *2> Promise [Object] {
    _bitField: 1,
    _fulfillmentHandler0: undefined,
    _rejectionHandler0: [Function (anonymous)],
    _promise0: [Circular *1],
    _receiver0: undefined,
    _cancellationParent: Promise [Object] {
      _bitField: 1,
      _fulfillmentHandler0: [Function (anonymous)],
      _rejectionHandler0: undefined,
      _promise0: [Circular *2],
      _receiver0: undefined,
      _onCancelField: [Function (anonymous)],
      _branchesRemainingToCancel: 1
    },
    _branchesRemainingToCancel: 1
  }
}


问:
Quick Sort in Ruby language
I am trying to implement Quick sort in ruby but stuck in how to call recursively after the first partition of pivot. Please help me to understand on how to proceed and also let me know whether my style of coding is good so far .</p>

```<code>class QuickSort
    $array= Array.new()
    $count=0

    def add(val) #adding values to sort
        i=0
        while val != '000'.to_i
            $array[i]= val.to_i
            i=i+1
            val = gets.to_i
        end
    end

    def firstsort_aka_divide(val1,val2,val3) #first partition
        $count = $count+1
        @pivot = val1
        @left = val2
        @right =val3
        while @left!=@right do # first divide/ partition logic

            if $array[@right] > $array[@pivot] then
                @right= @right-1
            elsif $array[@right] < $array[@pivot] then
                @var = $array[@right]
                $array[@right] = $array[@pivot]
                $array[@pivot] = @var
                @pivot = @right
                @left = @left+1
            end
            if $array[@left] < $array[@pivot]
                @left= @left+1
            elsif $array[@left] > $array[@pivot]
                @var = $array[@left]
                $array[@left] = $array[@pivot]
                $array[@pivot] = @var
                @pivot =@left
            end

        end
        puts "\n"                   # printing after the first partition i.e divide
        print " Array for for divide ---> #{$array}"
        puts "\n"
        puts " pivot,left,right after first divide --> #{@pivot},#{@left},#{@right}"

        firstsort_aka_divide()  # Have to call left side of partition recursively -- need help
        firstsort_aka_divide()  # Have to call right side of partition recursively -- need help

    end
end

ob= QuickSort.new

puts " Enter the numbers you want to sort. \n Press '000' once you are done entering the values"
val = gets.to_i
ob.add(val)
puts " Sorting your list ..."
sleep(2)
ob.firstsort_aka_divide(0,0,($array.size-1)) # base condition for partitioning
</code>```

答:
def sort(ary)
  return ary if ary.size < 2

  pivot = ary[-1]
  sm_ary = []
  lg_ary = []

  ary[0..-2].each do |x|
    lg_ary.push(x) && next if x >= pivot

    sm_ary.push(x) && next if x < pivot
  end

  [*sort(sm_ary), pivot, *sort(lg_ary)]
end

arr = [10, 7, 8, 9, 7, 1, 5]
print sort(arr)
# [1, 5, 7, 7, 8, 9, 10]
```

ContentLicense: CC BY-SA 3.0

Title: Quick Sort in Ruby language

Body:
I am trying to implement Quick sort in ruby but stuck in how to call recursively after the first partition of pivot. Please help me to understand on how to proceed and also let me know whether my style of coding is good so far .

class QuickSort
    $array= Array.new()
    $count=0

    def add(val) #adding values to sort
        i=0
        while val != '000'.to_i
            $array[i]= val.to_i
            i=i+1
            val = gets.to_i
        end
    end

    def firstsort_aka_divide(val1,val2,val3) #first partition
        $count = $count+1
        @pivot = val1
        @left = val2
        @right =val3
        while @left!=@right do # first divide/ partition logic

            if $array[@right] > $array[@pivot] then
                @right= @right-1
            elsif $array[@right] < $array[@pivot] then
                @var = $array[@right]
                $array[@right] = $array[@pivot]
                $array[@pivot] = @var
                @pivot = @right
                @left = @left+1
            end
            if $array[@left] < $array[@pivot]
                @left= @left+1
            elsif $array[@left] > $array[@pivot]
                @var = $array[@left]
                $array[@left] = $array[@pivot]
                $array[@pivot] = @var
                @pivot =@left
            end

        end
        puts "\n"                   # printing after the first partition i.e divide
        print " Array for for divide ---> #{$array}"
        puts "\n"
        puts " pivot,left,right after first divide --> #{@pivot},#{@left},#{@right}"

        firstsort_aka_divide()  # Have to call left side of partition recursively -- need help
        firstsort_aka_divide()  # Have to call right side of partition recursively -- need help

    end
end

ob= QuickSort.new

puts " Enter the numbers you want to sort. \n Press '000' once you are done entering the values"
val = gets.to_i
ob.add(val)
puts " Sorting your list ..."
sleep(2)
ob.firstsort_aka_divide(0,0,($array.size-1)) # base condition for partitioning


问:
searching multiple words from dict and creating null entry check
I need to find a way to return a sentence based upon the input of the user i.e key word search.

I have a dictionary created and can return a sentence based on one word but cant figure out if I can return a sentence based on multiple words:

water damage returns a sentence on dropping your phone into water
i have a cracked screen does not return anything. I am aware that the issue is around the .split.strip functions I am using.

My next issue is that I can not seem to create a null entry check, I have tried the usual, while input_1 is None, or =='' yet the strip function removes whitespace so I am guessing there is no null entry to pick up on.

```<code>similar_words = {
    'water': 'you have let water into your phone',
    'wet': 'let your phone dry out then try to restrat the phone',
    'crack case': 'you have cracked your screen or case, this will need replacing by a specialist',
    'cracked screen': 'you have cracked your screen or case, this will need replacing by a specialist',
    'turn on': 'your battery may need replacing',
    'crack': 'your phone screen has been cracked, you need to contact the technician centre',

}

def check():
    if word.lower() in similar_words:
        print(similar_words[word.lower()])

input_1 = input("What seems to be the problem with your phone?: ").strip().split()

for word in input_1:
    check()

def close():
    print ('Please press enter to close the program')
    quit()

close_1 = input('Have we addressed your problem, please answer yes or no?: ')
if close_1=='yes':
    close()
else:
    print ('Lets us move on then')
</code>```

答:
According to your program I think that you need to display the phone problem's solution only but your program is not displaying it. So I have done some changes in the program and it is displaying it.</p>
```<code>similar_words = {
'water': 'you have let water into your phone',
'wet': 'let your phone dry out then try to restart the phone',
'crack case' : 'you have cracked your screen or case, this will need replacing by a specialist',
'cracked screen' : 'you have cracked your screen or case, this will need replacing by a specialist',
'turn on' : 'your battery may need replacing',
'crack' : 'your phone screen has been cracked, you need to contact the technician centre'
}

input_1 = input("What seems to be the problem with your phone?: ").split()
    for word in input_1:
        if word in similar_words.keys():
        print(similar_words[word])
        #similar_words[word] gives only the value of the key word

close_1 = input('Have we addressed your problem, please answer yes or no?: ')
if close_1=='yes':
    quit()
else:
    print ('Lets us move on then')
</code>```

Body:
I need to find a way to return a sentence based upon the input of the user i.e key word search.

I have a dictionary created and can return a sentence based on one word but cant figure out if I can return a sentence based on multiple words:

water damage returns a sentence on dropping your phone into water
i have a cracked screen does not return anything. I am aware that the issue is around the .split.strip functions I am using.

My next issue is that I can not seem to create a null entry check, I have tried the usual, while input_1 is None, or =='' yet the strip function removes whitespace so I am guessing there is no null entry to pick up on.

similar_words = {
    'water': 'you have let water into your phone',
    'wet': 'let your phone dry out then try to restrat the phone',
    'crack case': 'you have cracked your screen or case, this will need replacing by a specialist',
    'cracked screen': 'you have cracked your screen or case, this will need replacing by a specialist',
    'turn on': 'your battery may need replacing',
    'crack': 'your phone screen has been cracked, you need to contact the technician centre',

}

def check():
    if word.lower() in similar_words:
        print(similar_words[word.lower()])

input_1 = input("What seems to be the problem with your phone?: ").strip().split()

for word in input_1:
    check()

def close():
    print ('Please press enter to close the program')
    quit()

close_1 = input('Have we addressed your problem, please answer yes or no?: ')
if close_1=='yes':
    close()
else:
    print ('Lets us move on then')

Body:
According to your program I think that you need to display the phone problem's solution only but your program is not displaying it. So I have done some changes in the program and it is displaying it.

similar_words = {
'water': 'you have let water into your phone',
'wet': 'let your phone dry out then try to restart the phone',
'crack case' : 'you have cracked your screen or case, this will need replacing by a specialist',
'cracked screen' : 'you have cracked your screen or case, this will need replacing by a specialist',
'turn on' : 'your battery may need replacing',
'crack' : 'your phone screen has been cracked, you need to contact the technician centre'
}

input_1 = input("What seems to be the problem with your phone?: ").split()
    for word in input_1:
        if word in similar_words.keys():
        print(similar_words[word])
        #similar_words[word] gives only the value of the key word

close_1 = input('Have we addressed your problem, please answer yes or no?: ')
if close_1=='yes':
    quit()
else:
    print ('Lets us move on then')


问:
In a grails gsp template, how can I use a server side comment without sitemesh throwing an error?
When I use a standard jsp comment block in a gsp template

```<code><%-- some server-side comment --%>
</code>```

, sitemesh throws an 'unexpected token' error.  Is there another comment syntax I can use?

答:
The original question was asking how to comment out anything in the GSP file. The only one that worked for me is

<%--  some code to comment out --%>,

the other answers won't work especially if the code being commented are grails tags. %{ and <% didn't work.

Body:
When I use a standard jsp comment block in a gsp template

<%-- some server-side comment --%>

, sitemesh throws an 'unexpected token' error.  Is there another comment syntax I can use?


问:
How to optimize the time complexity when looping over two arrays
I have 2 sorted arrays of application names in the user's Android device. I now need to log an event if one array contains at least one item of the other array.

Here is my code:

```<code>  appsArray = ["cred","cult","hotstar","netflix","prime","splitwise","spotify"];
  _apps = [...]; // Apps in user's mobile

  bool _isQualityUser() {
    var result = '';
    for (var app in _apps) {
      result = appsArray.singleWhere((el) => app.appName.contains(el));
    }
    return result.isNotEmpty;
  }
</code>```

I'm looking for an optimized solution for it. If anyone can help with that.

答:
You could potentially use Set as it has O(1) complexity for read operation.</p>
```<code>var appNames = <String>{'cred', 'cult'};

bool _isQualityUser() {
    var result = '';
    for (var app in _apps) {
      result = appNames.contains(app.appName);
    }
    return result.isNotEmpty;
  }
</code>```

Body:
I have 2 sorted arrays of application names in the user's Android device. I now need to log an event if one array contains at least one item of the other array.

Here is my code:

  appsArray = ["cred","cult","hotstar","netflix","prime","splitwise","spotify"];
  _apps = [...]; // Apps in user's mobile

  bool _isQualityUser() {
    var result = '';
    for (var app in _apps) {
      result = appsArray.singleWhere((el) => app.appName.contains(el));
    }
    return result.isNotEmpty;
  }

I'm looking for an optimized solution for it. If anyone can help with that.

Body:
You could potentially use Set as it has O(1) complexity for read operation.

var appNames = <String>{'cred', 'cult'};

bool _isQualityUser() {
    var result = '';
    for (var app in _apps) {
      result = appNames.contains(app.appName);
    }
    return result.isNotEmpty;
  }


问:
Unity. Plane with sprite clips in front of ProBuilder object depending on distance of player. Might be a shader problem
I am making a game that uses 2D sprites in a 3D world. I tried to do this by putting the sprite in a material and putting that material on an plane, and choosing the shader option "Transparent (UI/Lit/Transparent)". This works great in the sense that it hides the plane, shows the sprite and interacts with lighting.

But this method makes the objects (the trees in the picture) clip in front of the ProBuilder object (the chain linked fence in the picture), when th player gets too close.

The solution I found was using the Transparent (Unlit/Transparent) shader. My guess is that this solves the problem because there is no 'UI' in the shader's name. The problem is though, that this also is "Unlit", which means that the trees do not interact with lighting.

I have also tried this by making a ProBuilder object and deleting all but one face, but this had the same effect as the example given in the pictures.

How do I make the object show the sprite with the transparent parts invisible and with it interacting with light?

答: I solved it. I put the shader back to 'standard' and then changed the rendering mode to 'cutout'.</p>


问:
How to get rid of the error `package has no attribute '_w_long'`?
Suddenly, I don't know why occurs the error for every python file in this project, let's take for example and use matplotlib.

I tried this:

```<code>import matplotlib.pyplot as plt

plt.plot([1,2,3],[1,2,3])
plt.show()
</code>```

And the error is:

```<code>Remainder of file ignored
Traceback (most recent call last):
  File "C:\Users\Idensas\PycharmProjects\protest\try.py", line 1, in <module>
    import matplotlib.pyplot as plt
  File "C:\Users\Idensas\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\__init__.py", line 89, in <module>
    import importlib
  File "C:\Users\Idensas\PycharmProjects\OneMoreTime\pypy\lib-python\3\importlib\__init__.py", line 51, in <module>
    _w_long = _bootstrap_external._w_long
AttributeError: module 'importlib._bootstrap_external' has no attribute '_w_long'
</code>```

There are more errors but I omit that, because they all same like this above, errors with:

protobuf-3.18.0-py3.9-nspkg.pth

matplotlib-3.5.1-py3.9-nspkg.pth

googleapis_common_protos-1.53.0-py3.9-nspkg.pth

distutils-precedence.pth

I took a look at some same questions like mine, but nothing helped me. I have installed only one version of python, this was years ago. I just turn on my PC, go to PyCharm and an error today is occurs. Uhh...

答: Finally! I just go to Project Dependencies and unchecked, so my project "protest" with python doesn't depend on project "OneMoreTime" with pypy.

Body:
Suddenly, I don't know why occurs the error for every python file in this project, let's take for example and use matplotlib.

I tried this:

import matplotlib.pyplot as plt

plt.plot([1,2,3],[1,2,3])
plt.show()

And the error is:

Remainder of file ignored
Traceback (most recent call last):
  File "C:\Users\Idensas\PycharmProjects\protest\try.py", line 1, in <module>
    import matplotlib.pyplot as plt
  File "C:\Users\Idensas\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\__init__.py", line 89, in <module>
    import importlib
  File "C:\Users\Idensas\PycharmProjects\OneMoreTime\pypy\lib-python\3\importlib\__init__.py", line 51, in <module>
    _w_long = _bootstrap_external._w_long
AttributeError: module 'importlib._bootstrap_external' has no attribute '_w_long'

There are more errors but I omit that, because they all same like this above, errors with:

protobuf-3.18.0-py3.9-nspkg.pth

matplotlib-3.5.1-py3.9-nspkg.pth

googleapis_common_protos-1.53.0-py3.9-nspkg.pth

distutils-precedence.pth

I took a look at some same questions like mine, but nothing helped me. I have installed only one version of python, this was years ago. I just turn on my PC, go to PyCharm and an error today is occurs. Uhh...


问:
What's the problem when trying to render the cards?
I'm trying to render multiple cards by pulling data from the API. But the return is an array, I don't understand why the map is not working.

```<code>const CharacterCard = () => {
  const [showModal, setShowModal] = useState(false)

  const openModal = () => {
    setShowModal(prev => !prev)
  }

  const characters = useRequestData([], `${BASE_URL}/characters`)

  const renderCard = characters.map((character) => {
    return (
      <CardContainer key={character._id} imageUrl={character.imageUrl} />
    )
  })

  return (
    <Container>
      {renderCard}
      <ModalScreen showModal={showModal} setShowModal={setShowModal} />
    </Container>
  )
}

export default CharacterCard
</code>```

The hook is this

```<code>import { useEffect, useState } from "react"
import axios from "axios"

const useRequestData = (initialState, url) => {
  const [data, setData] = useState(initialState)

  useEffect(() => {
    axios.get(url)
      .then((res) => {
        setData(res.data)
      })
      .catch((err) => {
        console.log(err.data)
      })
  }, [url])

  return (data)
}

export default useRequestData
</code>```

Console error:

Requisition return:

API: https://disneyapi.dev/docs

答:
If you notice the axios response schema, the data entry "is the response that was provided by the server".

Disney API response includes the data entry too.

Therefore, you actually wanted to get Disney data and not the axios response, fix it to:

```<code>setData(res.data.data)
</code>```

You could debugged it by logging console.log(res) or going backward in the error chain console.log(characters) should result {data: [...]}, which hints that you can't execute .map on an object.

Body:
I'm trying to render multiple cards by pulling data from the API. But the return is an array, I don't understand why the map is not working.

const CharacterCard = () => {
  const [showModal, setShowModal] = useState(false)

  const openModal = () => {
    setShowModal(prev => !prev)
  }

  const characters = useRequestData([], `${BASE_URL}/characters`)

  const renderCard = characters.map((character) => {
    return (
      <CardContainer key={character._id} imageUrl={character.imageUrl} />
    )
  })

  return (
    <Container>
      {renderCard}
      <ModalScreen showModal={showModal} setShowModal={setShowModal} />
    </Container>
  )
}

export default CharacterCard

The hook is this

import { useEffect, useState } from "react"
import axios from "axios"

const useRequestData = (initialState, url) => {
  const [data, setData] = useState(initialState)

  useEffect(() => {
    axios.get(url)
      .then((res) => {
        setData(res.data)
      })
      .catch((err) => {
        console.log(err.data)
      })
  }, [url])

  return (data)
}

export default useRequestData

Console error:

Requisition return:

API: https://disneyapi.dev/docs

Body:
If you notice the axios response schema, the data entry "is the response that was provided by the server".

Disney API response includes the data entry too.

Therefore, you actually wanted to get Disney data and not the axios response, fix it to:

setData(res.data.data)

You could debugged it by logging console.log(res) or going backward in the error chain console.log(characters) should result {data: [...]}, which hints that you can't execute .map on an object.


问:
Auto edit cell in nebula nattable
My nattable is a tree table  that has custom root objects. I want to edit a cell in the table. The second column is static. But row index is dynamic. Im not able to get the correct row index for nattable edit after I add an entry into the table. The new row is added based on dialog selection.

Code:

nattableprovider.getSelectionProvider().setSelection(new StructuredSelection(obj));
SelectionLayer selLayer = nattableprovider.getBodyLayer().getSelectionLayer();
PositionCoordinate pos = selLayer.getSelectionAnchor();

nattable.doCommand(newEditCellCommand(nattable, nattable.getConfugRegistry(),nattable.getCellByPosition(2,pos.rowPositon)
```

答:
First, I don't see a question. You should phrase a question if you expect an answer.

Second, you show some code that probably should trigger a selection and then activate the edit mode, but you do not show the NatTable composition. There is typically a correlation.

Third, not sure if you understand the difference of row index vs. row position. Especially because you retrieve the row position from the SelectionLayer and then want to use it on the NatTable layer. Typically there is a transformation in between, at least if you have a column header. But as you don't give an information on your NatTable composition, hard to tell.
Also if you want to edit something that is not visible, the activation of the edit mode is not possible. But again, hard to say without more details. There could be multiple issues. But I suppose each is somehow related to incorrect position handling.

Title: Auto edit cell in nebula nattable


问:
Remove UTM Parameters from URL
I use UTM parameters to track incoming links in Google Analytics.

Let's say my URL looks like this

```<code>https://www.domain.tld/shop?utm_source=newsletter&utm_medium=email&utm_campaign=spring_sale
</code>```

I want to clean the URL. The desired result is

```<code>https://www.domain.tld/shop
</code>```

On the web I found the following snippet

```<code>(function() {
    var win = window;
    var removeUtms = function(){
        var location = win.location;
        if (location.search.indexOf('utm_') != -1 && history.replaceState) {
            history.replaceState({}, '', window.location.toString().replace(/(\&|\?)utm([_a-z0-9=]+)/g, ""));
        }
    };
    ga('send', 'pageview', { 'hitCallback': removeUtms });
})();
</code>```

At the moment my Google Analytics Template in my CMS looks like this

```<code><?php
    /**
     * To use this script, please fill in your Google Analytics ID below
     */
    $GoogleAnalyticsId = 'UA-bla-bla';
    /**
     * DO NOT EDIT ANYTHING BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING!
     */
    if ($GoogleAnalyticsId != 'UA-XXXXX-X' && !BE_USER_LOGGED_IN && sha1(session_id() . (!Config::get('disableIpCheck') ? Environment::get('ip') : '') . 'BE_USER_AUTH') != Input::cookie('BE_USER_AUTH')): ?>
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
      ga('create', '<?php echo $GoogleAnalyticsId; ?>', 'auto');
      <?php if ($GLOBALS['TL_CONFIG']['privacyAnonymizeGA']): ?>
        ga('set', 'anonymizeIp', true);
      <?php endif; ?>
      ga('send', 'pageview');
    </script>
<?php endif; ?>
</code>```

...and I have no idea how to bring those codes together.

Maybe there is even a better solution to my problem?

答:
Copy urls into url.txt</p>
```<code>sed 's/?utm[^ ]*//g' url.txt
</code>```

Title: Remove UTM Parameters from URL

Body:
I use UTM parameters to track incoming links in Google Analytics.

Let's say my URL looks like this

https://www.domain.tld/shop?utm_source=newsletter&utm_medium=email&utm_campaign=spring_sale

I want to clean the URL. The desired result is

https://www.domain.tld/shop

On the web I found the following snippet

(function() {
    var win = window;
    var removeUtms = function(){
        var location = win.location;
        if (location.search.indexOf('utm_') != -1 && history.replaceState) {
            history.replaceState({}, '', window.location.toString().replace(/(\&|\?)utm([_a-z0-9=]+)/g, ""));
        }
    };
    ga('send', 'pageview', { 'hitCallback': removeUtms });
})();

At the moment my Google Analytics Template in my CMS looks like this

<?php
    /**
     * To use this script, please fill in your Google Analytics ID below
     */
    $GoogleAnalyticsId = 'UA-bla-bla';
    /**
     * DO NOT EDIT ANYTHING BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING!
     */
    if ($GoogleAnalyticsId != 'UA-XXXXX-X' && !BE_USER_LOGGED_IN && sha1(session_id() . (!Config::get('disableIpCheck') ? Environment::get('ip') : '') . 'BE_USER_AUTH') != Input::cookie('BE_USER_AUTH')): ?>

<?php endif; ?>

...and I have no idea how to bring those codes together.

Maybe there is even a better solution to my problem?

Body:
Copy urls into url.txt

sed 's/?utm[^ ]*//g' url.txt


问:
How do I stop having carriage returns added to my file output in Python?
I'm trying to parse a BMP file, do some changes and then reassemble a new BMP using Python.

The carriage return seems to be a huge problem.  When I open the bitmap file using Notepad++ and search for "\r', the character does not exist.  I read the file in Python (readData = fileIn.read()) and try searching using readData.find('\r') it returns -1.  Searching for "\n" works fine.  All is good for now.

When I try to write this exact same block of text into a new BMP using fileOut.write(readData) and I use Notepad++ to search for "\r", I am able to find it (twice, each corresponding to the preexisting "\n" characters).

Is there a way to write this block of data to a new BMP without "\r" being added automatically?  I've tried applying .strip() and .replace('\r','') to the string before writing it to the new file.

答:
You are opening the file in text mode, while you need binary mode. Find more about open() here:
http://docs.python.org/library/functions.html</p>


问:
how to use axios get method for every element in a very large array and save the result in json file without enobufs error?
I have a very large array of length 17 thousand containing integer numbers. Now for every element in the array I want to make axios.get() request and save the response in a json file.

When I do this in the following way, I get enobuf error.
My Code:

```<code>for (const id of ids) {
    axios
      .get(`${BASE_URL}/${id}?json=1`)
      .then((response) => {
          fs.writeFileSync(res)
      })
      .catch((err) => {
        console.log("error ", err);
      });
  }
</code>```

My Error:

```<code>error  Error: connect ENOBUFS 69.64.69.90:443 - Local (undefined:undefined)
    at internalConnect (net.js:934:16)
    at defaultTriggerAsyncIdScope (internal/async_hooks.js:452:18)
    at GetAddrInfoReqWrap.emitLookup [as callback] (net.js:1077:9)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:73:8) {
  errno: -4060,
  code: 'ENOBUFS',
  syscall: 'connect',
  address: '69.64.69.90',
  port: 443,
</code>```

I am realizing that maybe my approach is not convenient and efficient. Now my question is what my approach should be to solve this?

答:
First, each of the loop iterations in this code does not wait for the result of axios call.

Secord, you need to divide the whole large array into chunks of any reasonable chunk size, for instance by using lodash.chunk method if you wish to process some number of elements simultaneously.
Third, you definitely need to use asynchronous version of fs.writeFileSync, see fs.Promises

const chunks = _.chunk(ids, 10)
const writeResult = async (id) => {
  const res = await axios.get(`${BASE_URL}/${id}?json=1`)
  const fileName = id
  await fs.Promises.writeFile(fileName, res)
}
for (const chunk of chunks) {
  await Promise.all(chunk.map(x => writeResult(x))
}
```

Body:
I have a very large array of length 17 thousand containing integer numbers. Now for every element in the array I want to make axios.get() request and save the response in a json file.

When I do this in the following way, I get enobuf error.
My Code:

for (const id of ids) {
    axios
      .get(`${BASE_URL}/${id}?json=1`)
      .then((response) => {
          fs.writeFileSync(res)
      })
      .catch((err) => {
        console.log("error ", err);
      });
  }

My Error:

error  Error: connect ENOBUFS 69.64.69.90:443 - Local (undefined:undefined)
    at internalConnect (net.js:934:16)
    at defaultTriggerAsyncIdScope (internal/async_hooks.js:452:18)
    at GetAddrInfoReqWrap.emitLookup [as callback] (net.js:1077:9)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:73:8) {
  errno: -4060,
  code: 'ENOBUFS',
  syscall: 'connect',
  address: '69.64.69.90',
  port: 443,

I am realizing that maybe my approach is not convenient and efficient. Now my question is what my approach should be to solve this?


问:
What is the point of itertools.count and itertools.islice?
I've looked at a online courses, and they have examples like the following:

```<code>from itertools import count

# creates a count iterator object
iterator =(count(start = 0, step = 2))

# prints an even list of integers
print("Even list:",
      list(next(iterator) for _ in range(5)))
</code>```

... which you could write using range or np.arange. Here's another example:

```<code># list containing some strings
my_list =["x", "y", "z"]

# count spits out integers for
# each value in my list
for i in zip(count(start = 1, step = 1), my_list):
    print(i)
</code>```

... which is basically just enumerate. So my question is: can you give an example of itertools.count and itertools.islice that can't be done (or has to be done much more clunkily) using range?

答:
If you want to save memory usage you can use generators in python or a library could use generators. To slice a generator islice is convenient. count is more flexibel than enumerate.

A very simple generator

```<code>import itertools as it
import random
random.seed(42)

def fib():
    x, y = 0, 1
    while True:
        yield x
        x, y = y, x + y

x = random.randint(5, 40)
start, step = 2.5, .1
</code>```

Using count with floats and islice to slice the generator.

```<code>for c, i in zip(it.count(start, step), it.islice(fib(), x, x+5)):
    print(f'{c:.1f}', i)
</code>```

Output

```<code>2.5 144
2.6 233
2.7 377
2.8 610
2.9 987
</code>```

It's not too difficult to use a generator without itertools, but it does require a bit more effort. So it remains a personal choice of style. There are more ways to implement this, but I tried to be as expressive as itertools and the least clunky.

```<code>g = fib()
for c in range(x+5):
    n = next(g)
    if c >= x:
        print(f'{start + (c-x)*step:.1f}', n)
</code>```

Output

```<code>2.5 144
2.6 233
2.7 377
2.8 610
2.9 987
</code>```

Body:
I've looked at a online courses, and they have examples like the following:

from itertools import count

# creates a count iterator object
iterator =(count(start = 0, step = 2))

# prints an even list of integers
print("Even list:",
      list(next(iterator) for _ in range(5)))

... which you could write using range or np.arange. Here's another example:

# list containing some strings
my_list =["x", "y", "z"]

# count spits out integers for
# each value in my list
for i in zip(count(start = 1, step = 1), my_list):
    print(i)

... which is basically just enumerate. So my question is: can you give an example of itertools.count and itertools.islice that can't be done (or has to be done much more clunkily) using range?

Body:
If you want to save memory usage you can use generators in python or a library could use generators. To slice a generator islice is convenient. count is more flexibel than enumerate.

A very simple generator

import itertools as it
import random
random.seed(42)

def fib():
    x, y = 0, 1
    while True:
        yield x
        x, y = y, x + y

x = random.randint(5, 40)
start, step = 2.5, .1

Using count with floats and islice to slice the generator.

for c, i in zip(it.count(start, step), it.islice(fib(), x, x+5)):
    print(f'{c:.1f}', i)

Output

2.5 144
2.6 233
2.7 377
2.8 610
2.9 987

It's not too difficult to use a generator without itertools, but it does require a bit more effort. So it remains a personal choice of style. There are more ways to implement this, but I tried to be as expressive as itertools and the least clunky.

g = fib()
for c in range(x+5):
    n = next(g)
    if c >= x:
        print(f'{start + (c-x)*step:.1f}', n)

Output

2.5 144
2.6 233
2.7 377
2.8 610
2.9 987


问:
Print line above specific string from txt file
I have txt file contains data, i want to loop over file and print only line above "City" word.

Ex of txt file:

```<code>NEW FUSTAT TOURS
City
USA
Addres
napolean
Phone Number
************
Email
***************
PACKAGES
Test TOURS
City
UK
Addres
napolean
Phone Number
************
Email
***************
PACKAGES
</code>```

Result Expected:

```<code>NEW FUSTAT TOURS
Test TOURS
</code>```

I tried:

```<code>with open('dd.txt', 'r', encoding="utf-8") as f:
    input_file = f.readlines()
    for i, line in enumerate(input_file):
        if 'City' in line:
            f1 = (input_file[:i])
            f2 = str(f1)
            f3 = (f2.replace("['", ''))
            f4 = (f3.replace("\\n']", ''))
            print(f4)
</code>```

Result:

```<code>NEW FUSTAT TOURS
NEW FUSTAT TOURS\n', 'City\n', 'USA\n', 'Addres\n', 'napolean\n', 'Phone Number\n', '************\n', 'Email\n', '***************\n', 'PACKAGES\n', 'Test TOURS
</code>```

Any kind of help please?

答:
These are a lot of for loops, but they work:</p>
```<code>lines = []
with open('word.txt', 'r') as file:
    for line in file.readlines():
        lines.append(line.replace('\n', ''))
    file.close()
indices = []
for line in lines:
    if line == 'City':
        indices.append(lines.index(line) - 1)
        lines[lines.index(line)] = 'FOUND'

for index in indices:
    print(lines[index])
</code>```

Body:
I have txt file contains data, i want to loop over file and print only line above "City" word.

Ex of txt file:

NEW FUSTAT TOURS
City
USA
Addres
napolean
Phone Number
************
Email
***************
PACKAGES
Test TOURS
City
UK
Addres
napolean
Phone Number
************
Email
***************
PACKAGES

Result Expected:

NEW FUSTAT TOURS
Test TOURS

I tried:

with open('dd.txt', 'r', encoding="utf-8") as f:
    input_file = f.readlines()
    for i, line in enumerate(input_file):
        if 'City' in line:
            f1 = (input_file[:i])
            f2 = str(f1)
            f3 = (f2.replace("['", ''))
            f4 = (f3.replace("\\n']", ''))
            print(f4)

Result:

NEW FUSTAT TOURS
NEW FUSTAT TOURS\n', 'City\n', 'USA\n', 'Addres\n', 'napolean\n', 'Phone Number\n', '************\n', 'Email\n', '***************\n', 'PACKAGES\n', 'Test TOURS

Any kind of help please?

Body:
These are a lot of for loops, but they work:

lines = []
with open('word.txt', 'r') as file:
    for line in file.readlines():
        lines.append(line.replace('\n', ''))
    file.close()
indices = []
for line in lines:
    if line == 'City':
        indices.append(lines.index(line) - 1)
        lines[lines.index(line)] = 'FOUND'

for index in indices:
    print(lines[index])


问:
User Defined Function with Strings giving error

Date
Name

24-Jun-68
Bill

I would like to create a function that transforms this Date into a working date format. However, I am unable to get this function to return anything I am getting an error that says. AttributeError: 'str' object has no attribute 'str'. The function is below

```<code>    day=x.str.split("-")[0]
    month=x.str.split("-")[1]
    year=x.str.split("-")[2]
    return month+"/"+day+"/"+"19"+year

df['New Date'] = df['Date'].apply(get_date)```

```

答:
.split() is a string method, you can use it directly on the string you are splitting.</p>
```<code>day, month, year = x.split('-')
return f'{month}/{day}/19{year}'
</code>```

Body:
Date
Name

24-Jun-68
Bill

I would like to create a function that transforms this Date into a working date format. However, I am unable to get this function to return anything I am getting an error that says. AttributeError: 'str' object has no attribute 'str'. The function is below

    day=x.str.split("-")[0]
    month=x.str.split("-")[1]
    year=x.str.split("-")[2]
    return month+"/"+day+"/"+"19"+year

df['New Date'] = df['Date'].apply(get_date)```

Body:
.split() is a string method, you can use it directly on the string you are splitting.

day, month, year = x.split('-')
return f'{month}/{day}/19{year}'


问:
Strength of connection in between nodes
How exactly do we measure the strength of a connection between 2 nodes on a social network graph. essentially between a node and its first degree connection, can we measure the strength of connection?

What exactly is meant by "strength of connection" on a social network analysis context.

I assume first degree connection implies if a--b--c then b is first degree connection of a and c is second degree connection of a.

答:
Connection node strength is the sum of
all neighboring link weights i.e. node degree with the addition of a weight that captures how strong the communication is. You can assign some arbitrary measure of communication between two nodes on a social network making it a weighted network.

For example, the sum of inbound and outbound flights between Harare and Johannesburg makes up the weight of the established route (a fraction of all the routes that connect either of these two cities to the rest of the world) between the two cities.

Title: Strength of connection in between nodes


问:
Uncaught TypeError: Cannot read properties of undefined (reading 'deep') when upgrade to vue 3.x
After upgrade the vue to 3.x, the console shows error like this:

```<code>Uncaught TypeError: Cannot read properties of undefined (reading 'deep')
    at withDirectives (commons1.js:10679:17)
    at Proxy.render (eval at compileToFunction (commons1.js:40198:21), <anonymous>:36:7)
    at renderComponentRoot (commons1.js:7874:44)
    at ReactiveEffect.componentUpdateFn [as fn] (commons1.js:11968:57)
    at ReactiveEffect.run (commons1.js:5819:29)
    at setupRenderEffect (commons1.js:12094:9)
    at mountComponent (commons1.js:11877:9)
    at processComponent (commons1.js:11835:17)
    at patch (commons1.js:11436:21)
    at render (commons1.js:12579:13)
</code>```

I have no idea what was happen, think it may be a compatible problem. I did not know how to found where is going wrong. I could not know the line where is going wrong from the output js(from this error I could not know where is going wrong with the source code), this is the code looks like:

```<code>/**
 * Adds directives to a VNode.
 */
function withDirectives(vnode, directives) {
    const internalInstance = currentRenderingInstance;
    if (internalInstance === null) {
        ( true) && warn(`withDirectives can only be used inside render functions.`);
        return vnode;
    }
    const instance = internalInstance.proxy;
    const bindings = vnode.dirs || (vnode.dirs = []);
    for (let i = 0; i < directives.length; i++) {
        let [dir, value, arg, modifiers = _vue_shared__WEBPACK_IMPORTED_MODULE_1__.EMPTY_OBJ] = directives[i];
        if ((0,_vue_shared__WEBPACK_IMPORTED_MODULE_1__.isFunction)(dir)) {
            dir = {
                mounted: dir,
                updated: dir
            };
        }
        // here throw the error message
        if (dir.deep) {
            traverse(value);
        }
        bindings.push({
            dir,
            instance,
            value,
            oldValue: void 0,
            arg,
            modifiers
        });
    }
    return vnode;
}
</code>```

when running into the dir.deep line, throw this error, what should I do to fix this problem? I tried to search from Google seems no one facing the same problem.

答:
I had this issue today and I found out the problem was because I was trying to use an unregistered directive.

If you put a breakpoint right the invocation before where the error happens, in your case
at Proxy.render (eval at compileToFunction (commons1.js:40198:21), <anonymous>:36:7)
you will find something like const _directive_focus = _resolveDirective("focus"); and then you know what directive you are missing

Body:
After upgrade the vue to 3.x, the console shows error like this:

Uncaught TypeError: Cannot read properties of undefined (reading 'deep')
    at withDirectives (commons1.js:10679:17)
    at Proxy.render (eval at compileToFunction (commons1.js:40198:21), <anonymous>:36:7)
    at renderComponentRoot (commons1.js:7874:44)
    at ReactiveEffect.componentUpdateFn [as fn] (commons1.js:11968:57)
    at ReactiveEffect.run (commons1.js:5819:29)
    at setupRenderEffect (commons1.js:12094:9)
    at mountComponent (commons1.js:11877:9)
    at processComponent (commons1.js:11835:17)
    at patch (commons1.js:11436:21)
    at render (commons1.js:12579:13)

I have no idea what was happen, think it may be a compatible problem. I did not know how to found where is going wrong. I could not know the line where is going wrong from the output js(from this error I could not know where is going wrong with the source code), this is the code looks like:

/**
 * Adds directives to a VNode.
 */
function withDirectives(vnode, directives) {
    const internalInstance = currentRenderingInstance;
    if (internalInstance === null) {
        ( true) && warn(`withDirectives can only be used inside render functions.`);
        return vnode;
    }
    const instance = internalInstance.proxy;
    const bindings = vnode.dirs || (vnode.dirs = []);
    for (let i = 0; i < directives.length; i++) {
        let [dir, value, arg, modifiers = _vue_shared__WEBPACK_IMPORTED_MODULE_1__.EMPTY_OBJ] = directives[i];
        if ((0,_vue_shared__WEBPACK_IMPORTED_MODULE_1__.isFunction)(dir)) {
            dir = {
                mounted: dir,
                updated: dir
            };
        }
        // here throw the error message
        if (dir.deep) {
            traverse(value);
        }
        bindings.push({
            dir,
            instance,
            value,
            oldValue: void 0,
            arg,
            modifiers
        });
    }
    return vnode;
}

when running into the dir.deep line, throw this error, what should I do to fix this problem? I tried to search from Google seems no one facing the same problem.


问:
LinkButton not firing  PostBack with image and ImageMap associated with it
I'm having one hell of a time trying to figure out why I can't get the LinkButton to PostBack when I have an image with an ImageMap associated with it.

Let me describe the system a little, so you can get a basic understanding of what's happening. The LinkButton has onClick set to call window.shoModalDialog, which obviously opens a modal window where the user can select various options an an ImageMap, save, and close the window. When the window closes, a PostBack is supposed to occur so that the main landing page gets updated with the new options selected.

To add complexity, the link button needs to have an image that shows what points were selected in modal window (the image is a smaller version of the previous window). So what I've done is add an image map to the image in the LinkButton like so:

```<code><asp:Panel ID="pnlC2R1" runat="server">
    <asp:LinkButton ID="HyperLink1" runat="server">
        <img ID="SomeImage" alt="Some image"
              runat="server" src="~/Images/SomeImage.jpg" usemap="#SomeMap" />
     </asp:LinkButton>
</asp:Panel>
</code>```

The map is a regular HTML map (not the ASP.NET one, though I'm sure it's rendered the same, but I digress). Also, I'm using ImageMapster to highlight the points that have been selected, but that doesn't cause any issues as far as I can tell.

If I remove the usemap attribute, a PostBack occurs, if I add it back in, it doesn't.

Is the ImageMap overriding the events that are supposed to occur under normal conditions for the LinkButton? Is there a way to make the ImageMap do a PostBack like the `LinkButton' would under normal circustances?

I tried using the ASP.NET ImageButton control, but I couldn't figure out how to get the ImageMap on it, if that's even possible.

Any help would be greatly appreciated, and please let me know if I need to clarify anything, I'm fairly certain half of what I wrote probably doesn't make sense. :D

UPDATE
The issue had nothing to do with the ImageMap itself. It had to do with the OnClientClick closing the modal dialog before the OnClick event could be called.

答:
Use the asp:ImageMap instead

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.imagemap.aspx

Body:
I'm having one hell of a time trying to figure out why I can't get the LinkButton to PostBack when I have an image with an ImageMap associated with it.

Let me describe the system a little, so you can get a basic understanding of what's happening. The LinkButton has onClick set to call window.shoModalDialog, which obviously opens a modal window where the user can select various options an an ImageMap, save, and close the window. When the window closes, a PostBack is supposed to occur so that the main landing page gets updated with the new options selected.

To add complexity, the link button needs to have an image that shows what points were selected in modal window (the image is a smaller version of the previous window). So what I've done is add an image map to the image in the LinkButton like so:

<asp:Panel ID="pnlC2R1" runat="server">
    <asp:LinkButton ID="HyperLink1" runat="server">

     </asp:LinkButton>
</asp:Panel>

The map is a regular HTML map (not the ASP.NET one, though I'm sure it's rendered the same, but I digress). Also, I'm using ImageMapster to highlight the points that have been selected, but that doesn't cause any issues as far as I can tell.

If I remove the usemap attribute, a PostBack occurs, if I add it back in, it doesn't.

Is the ImageMap overriding the events that are supposed to occur under normal conditions for the LinkButton? Is there a way to make the ImageMap do a PostBack like the `LinkButton' would under normal circustances?

I tried using the ASP.NET ImageButton control, but I couldn't figure out how to get the ImageMap on it, if that's even possible.

Any help would be greatly appreciated, and please let me know if I need to clarify anything, I'm fairly certain half of what I wrote probably doesn't make sense. :D

UPDATE
The issue had nothing to do with the ImageMap itself. It had to do with the OnClientClick closing the modal dialog before the OnClick event could be called.


问:
How to use loop function in google sheets to past data from one sheet to other?
I have 2 sheets in my workbook sheet 1 a simple invoice and sheet 2 data sheet I update sheet2 on daily basis and record transactions for various clients In sheet1 I want to make a monthly invoice for each client based on all their transactions recorded in sheet 2 I need a script that can look up the value of "Cell 5" of sheet-1 in column-B of sheet-2 and copy all the corresponding transaction to sheet-1 column B~D I hope this make sense Thanks in advance
here is the sheet link https://docs.google.com/spreadsheets/d/1jDzmyKsLD1zzfmJ4yNrNEuzb-lCmQSBIq_ba55r-T3c/edit?usp=sharing</p>

答:
check this code

I hope this helps you

although i am not sure about your problem its not easy to understand

check your sheet for code and result

you should add expected result in your question too.

function updateInvoice() {
  const blankArr = [];

  const SS = SpreadsheetApp.getActiveSpreadsheet();
  const invoice = SS.getSheetByName("Invoice-2");
  const data = SS.getSheetByName("Sheet2").getRange(3, 2, SS.getSheetByName("Sheet2").getLastRow() - 3, 6).getValues();

  // const data = [
  //   ['client', 'Date', 'Service', 'Rate', 'Quantity', 'Unit cost'],
  //   ['abc', '2/23/2022', 'Service 1', '23', '2', '10.00'],
  // ]

  const clientName = invoice.getRange('B5').getValue();
  const startDate = new Date(invoice.getRange('C5').getValue());
  const endDate = new Date(invoice.getRange('D5').getValue());

  for (let i = 0; i < data.length; i++) {
    const r = data[i];
    if (r[0] === clientName && r[1] >= startDate && r[1] <= endDate) {
      blankArr.push(r);
    }
  }

  // if you want to use as function remve below line if you want to update onEdit then keep
  invoice.getRange(9, 2, blankArr.length, blankArr[0].length).setValues(blankArr);

  return blankArr;

}```


问:
How to detect the closest value below and above a given reference variable in a data frame in R?
Consider the following random MWE.

For every row, I am trying to determine which variable has the closest value below the constant reference_day and which variable has the closest value above the constant reference_day.

```<code>df1 <-
  structure(
    list(id = 1:5,
      gender = c("female", "male", "male", "male", "male"),
      reference_day = structure(c(18052, NA, 18052, 18052, 18052), class = "Date"),
      var1 = structure(c(16505, 17144, 18139, NA, 16639), class = "Date"),
      var2 = structure(c(NA, 18042, 16544, 16697, NA), class = "Date"),
      var3 = structure(c(17845, 18070, 17152, 16571, NA), class = "Date")),
  row.names = c(NA, -5L), class = "data.frame")

df1

  id gender reference_day       var1       var2       var3
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>
</code>```

The result I'm after is this:

```<code>  id gender reference_day       var1       var2       var3 closest_to_left closest_to_right
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10            var3             <NA>
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23            <NA>             <NA>
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17            var3             var1
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16            var2             <NA>
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>            var1             <NA>
</code>```

After much trial and error, I was actually able to find a solution to this with the case_when function of dplyr, but it took an insane amount of boilerplate code, which lead me to think that there just has to be a more clever solution.

I personally prefer to work with dplyr, but any help is greatly appreciated.

答:
Here is a base R solution. Probably there are simpler ways.

nms <- names(df1[-(1:3)])
res <- apply(df1[-(1:2)], 1, \(x){
  d <- difftime(x[1], x[-1])
  if(any(!is.na(d))){
    if(any(d > 0, na.rm = TRUE)) {
      i <- which((d > 0) & (d == min(d[d > 0], na.rm = TRUE)))
      closest_left <- nms[i]
    } else closest_left <- NA
    if(any(d < 0, na.rm = TRUE)){
      j <- which((d < 0) & (d == min(d[d < 0], na.rm = TRUE)))
      closest_right <- nms[j]
    } else closest_right <- NA
    c(closest_left = closest_left, closest_right = closest_right)
  } else c(closest_left = NA, closest_right = NA)
})

res <- cbind(df1, t(res))
res
#>   id gender reference_day       var1       var2       var3 closest_left closest_right
#> 1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10         var3          <NA>
#> 2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23         <NA>          <NA>
#> 3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17         var3          var1
#> 4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16         var2          <NA>
#> 5  5   male    2019-06-05 2015-07-23       <NA>       <NA>         var1          <NA>
```

Created on 2022-02-06 by the reprex package (v2.0.1)

Body:
Consider the following random MWE.

For every row, I am trying to determine which variable has the closest value below the constant reference_day and which variable has the closest value above the constant reference_day.

df1 <-
  structure(
    list(id = 1:5,
      gender = c("female", "male", "male", "male", "male"),
      reference_day = structure(c(18052, NA, 18052, 18052, 18052), class = "Date"),
      var1 = structure(c(16505, 17144, 18139, NA, 16639), class = "Date"),
      var2 = structure(c(NA, 18042, 16544, 16697, NA), class = "Date"),
      var3 = structure(c(17845, 18070, 17152, 16571, NA), class = "Date")),
  row.names = c(NA, -5L), class = "data.frame")

df1

  id gender reference_day       var1       var2       var3
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>

The result I'm after is this:

  id gender reference_day       var1       var2       var3 closest_to_left closest_to_right
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10            var3             <NA>
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23            <NA>             <NA>
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17            var3             var1
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16            var2             <NA>
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>            var1             <NA>

After much trial and error, I was actually able to find a solution to this with the case_when function of dplyr, but it took an insane amount of boilerplate code, which lead me to think that there just has to be a more clever solution.

I personally prefer to work with dplyr, but any help is greatly appreciated.

Body:
Here is a base R solution. Probably there are simpler ways.

nms <- names(df1[-(1:3)])
res <- apply(df1[-(1:2)], 1, \(x){
  d <- difftime(x[1], x[-1])
  if(any(!is.na(d))){
    if(any(d > 0, na.rm = TRUE)) {
      i <- which((d > 0) & (d == min(d[d > 0], na.rm = TRUE)))
      closest_left <- nms[i]
    } else closest_left <- NA
    if(any(d < 0, na.rm = TRUE)){
      j <- which((d < 0) & (d == min(d[d < 0], na.rm = TRUE)))
      closest_right <- nms[j]
    } else closest_right <- NA
    c(closest_left = closest_left, closest_right = closest_right)
  } else c(closest_left = NA, closest_right = NA)
})

res <- cbind(df1, t(res))
res
#>   id gender reference_day       var1       var2       var3 closest_left closest_right
#> 1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10         var3          <NA>
#> 2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23         <NA>          <NA>
#> 3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17         var3          var1
#> 4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16         var2          <NA>
#> 5  5   male    2019-06-05 2015-07-23       <NA>       <NA>         var1          <NA>

Created on 2022-02-06 by the reprex package (v2.0.1)


问:
Function not running but not giving syntax error

I want to edit a script to make it more automated by taking a compiled piece of code that runs when a certain combination of keyboard hotkeys and just changing it to a function

My script works but the function that i made doesnt seem to run when it's called(or there might be something wrong with my if statement) but the hotkey version works

original:

```<code>*+F::
  {
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        WinSet, AlwaysOnTop, On, ahk_pid %pid%
        WinSet, AlwaysOnTop, Off, ahk_pid %pid%
        WinMaximize, ahk_pid %pid%
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
      }
    }
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
        StartSettings(pid)
      }
    }
</code>```

my version:

```<code>startSettingsChange() {
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        WinSet, AlwaysOnTop, On, ahk_pid %pid%
        WinSet, AlwaysOnTop, Off, ahk_pid %pid%
        WinMaximize, ahk_pid %pid%
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
      }
    }
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
        StartSettings(pid)
      }
    }
</code>```

I dont really know if I made any mistakes here but I'll add the full code of my edited version and the original

I have a if statement at the end that calls the function if a window title matches a certain state
original:

```<code>; by Specnr :)
; v0.2

; Startup all instances on title screen, run script, then once all instances are in the world, press Shift+F

#NoEnv
#SingleInstance Force

SetKeyDelay, 0
SetWinDelay, 1
SetTitleMatchMode, 2

global sprintKey := ""
global perspKey := "T"

StartSettings(pid) {
  ControlSend, ahk_parent, {Blind}{Shift Down}{F3}{Shift Up}, ahk_pid %pid%
  Sleep, 1000
  ControlSend, ahk_parent, {Blind}{1}{1}{1}, ahk_pid %pid%
  ControlSend, ahk_parent, {Blind}{%sprintKey%}{%perspKey%}{F3}, ahk_pid %pid%
  Sleep, 1000
  ControlSend, ahk_parent, {Blind}{F3 Down}{B}{Esc}{F3 Up}, ahk_pid %pid%
}

WinGet, all, list
Loop, %all%
{
  WinGet, pid, PID, % "ahk_id " all%A_Index%
  WinGetTitle, title, ahk_pid %pid%
  if (InStr(title, "Minecraft*")) {
    ControlSend, ahk_parent, {Blind}{Shift down}{Tab}{Shift up}{Enter}, ahk_pid %pid%
  }
}

*+F::
  {
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        WinSet, AlwaysOnTop, On, ahk_pid %pid%
        WinSet, AlwaysOnTop, Off, ahk_pid %pid%
        WinMaximize, ahk_pid %pid%
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
      }
    }
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
        StartSettings(pid)
      }
    }
    ExitApp
    return
  }
</code>```

my version:

```<code>; by Specnr :)
; v0.2

; Startup all instances on title screen, run script, then once all instances are in the world, press Shift+F
#NoEnv
#SingleInstance Force

SetKeyDelay, 0
SetWinDelay, 1
SetTitleMatchMode, 2

global sprintKey := ""
global perspKey := "T"

StartSettings(pid) {
  ControlSend, ahk_parent, {Blind}{Shift Down}{F3}{Shift Up}, ahk_pid %pid%
  Sleep, 1000
  ControlSend, ahk_parent, {Blind}{1}{1}{1}, ahk_pid %pid%
  ControlSend, ahk_parent, {Blind}{%sprintKey%}{%perspKey%}{F3}, ahk_pid %pid%
  Sleep, 1000
  ControlSend, ahk_parent, {Blind}{F3 Down}{B}{Esc}{F3 Up}, ahk_pid %pid%
}

WinGet, all, list
Loop, %all%
{
  WinGet, pid, PID, % "ahk_id " all%A_Index%
  WinGetTitle, title, ahk_pid %pid%
  if (InStr(title, "Minecraft*")) {
    ControlSend, ahk_parent, {Blind}{Shift down}{Tab}{Shift up}{Enter}, ahk_pid %pid%
  }
}

startSettingsChange() {
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        WinSet, AlwaysOnTop, On, ahk_pid %pid%
        WinSet, AlwaysOnTop, Off, ahk_pid %pid%
        WinMaximize, ahk_pid %pid%
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
      }
    }
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
        StartSettings(pid)
      }
    }

#IfWinActive, Minecraft
{
  WinGetPos, X, Y, W, H, Minecraft
  WinGetTitle, McTitle, Minecraft
  IfNotInString, McTitle, player
  {
       reload
   }
  Else
  {
       startSettingsChange()
   }
}

    ExitApp
    return
  }
</code>```

答:
The variable all doesn't exist in that function scope.

If you want to use a variable from outside of that function scope, you need the global(docs) keyword.

```<code>startSettingsChange()
{
    global all
    Loop, % all
    {
        ...
</code>```

Body:
I want to edit a script to make it more automated by taking a compiled piece of code that runs when a certain combination of keyboard hotkeys and just changing it to a function

My script works but the function that i made doesnt seem to run when it's called(or there might be something wrong with my if statement) but the hotkey version works

original:

*+F::
  {
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        WinSet, AlwaysOnTop, On, ahk_pid %pid%
        WinSet, AlwaysOnTop, Off, ahk_pid %pid%
        WinMaximize, ahk_pid %pid%
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
      }
    }
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
        StartSettings(pid)
      }
    }

my version:

startSettingsChange() {
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        WinSet, AlwaysOnTop, On, ahk_pid %pid%
        WinSet, AlwaysOnTop, Off, ahk_pid %pid%
        WinMaximize, ahk_pid %pid%
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
      }
    }
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
        StartSettings(pid)
      }
    }

I dont really know if I made any mistakes here but I'll add the full code of my edited version and the original

I have a if statement at the end that calls the function if a window title matches a certain state
original:

; by Specnr :)
; v0.2

; Startup all instances on title screen, run script, then once all instances are in the world, press Shift+F

#NoEnv
#SingleInstance Force

SetKeyDelay, 0
SetWinDelay, 1
SetTitleMatchMode, 2

global sprintKey := ""
global perspKey := "T"

StartSettings(pid) {
  ControlSend, ahk_parent, {Blind}{Shift Down}{F3}{Shift Up}, ahk_pid %pid%
  Sleep, 1000
  ControlSend, ahk_parent, {Blind}{1}{1}{1}, ahk_pid %pid%
  ControlSend, ahk_parent, {Blind}{%sprintKey%}{%perspKey%}{F3}, ahk_pid %pid%
  Sleep, 1000
  ControlSend, ahk_parent, {Blind}{F3 Down}{B}{Esc}{F3 Up}, ahk_pid %pid%
}

WinGet, all, list
Loop, %all%
{
  WinGet, pid, PID, % "ahk_id " all%A_Index%
  WinGetTitle, title, ahk_pid %pid%
  if (InStr(title, "Minecraft*")) {
    ControlSend, ahk_parent, {Blind}{Shift down}{Tab}{Shift up}{Enter}, ahk_pid %pid%
  }
}

*+F::
  {
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        WinSet, AlwaysOnTop, On, ahk_pid %pid%
        WinSet, AlwaysOnTop, Off, ahk_pid %pid%
        WinMaximize, ahk_pid %pid%
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
      }
    }
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
        StartSettings(pid)
      }
    }
    ExitApp
    return
  }

my version:

; by Specnr :)
; v0.2

; Startup all instances on title screen, run script, then once all instances are in the world, press Shift+F
#NoEnv
#SingleInstance Force

SetKeyDelay, 0
SetWinDelay, 1
SetTitleMatchMode, 2

global sprintKey := ""
global perspKey := "T"

StartSettings(pid) {
  ControlSend, ahk_parent, {Blind}{Shift Down}{F3}{Shift Up}, ahk_pid %pid%
  Sleep, 1000
  ControlSend, ahk_parent, {Blind}{1}{1}{1}, ahk_pid %pid%
  ControlSend, ahk_parent, {Blind}{%sprintKey%}{%perspKey%}{F3}, ahk_pid %pid%
  Sleep, 1000
  ControlSend, ahk_parent, {Blind}{F3 Down}{B}{Esc}{F3 Up}, ahk_pid %pid%
}

WinGet, all, list
Loop, %all%
{
  WinGet, pid, PID, % "ahk_id " all%A_Index%
  WinGetTitle, title, ahk_pid %pid%
  if (InStr(title, "Minecraft*")) {
    ControlSend, ahk_parent, {Blind}{Shift down}{Tab}{Shift up}{Enter}, ahk_pid %pid%
  }
}

startSettingsChange() {
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        WinSet, AlwaysOnTop, On, ahk_pid %pid%
        WinSet, AlwaysOnTop, Off, ahk_pid %pid%
        WinMaximize, ahk_pid %pid%
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
      }
    }
    Loop, %all%
    {
      WinGet, pid, PID, % "ahk_id " all%A_Index%
      WinGetTitle, title, ahk_pid %pid%
      if (InStr(title, "Minecraft*")) {
        ControlSend, ahk_parent, {Blind}{Esc}, ahk_pid %pid%
        StartSettings(pid)
      }
    }

#IfWinActive, Minecraft
{
  WinGetPos, X, Y, W, H, Minecraft
  WinGetTitle, McTitle, Minecraft
  IfNotInString, McTitle, player
  {
       reload
   }
  Else
  {
       startSettingsChange()
   }
}

    ExitApp
    return
  }

Body:
The variable all doesn't exist in that function scope.

If you want to use a variable from outside of that function scope, you need the global(docs) keyword.

startSettingsChange()
{
    global all
    Loop, % all
    {
        ...


问:
Array with only even number
for X in {18..2500} ; is one line of my script, which means to pick number one by one like: 18,19,20,21,22,23....till 2500

However I find I only need even number right now: 18,20,22,24.....2500

Then what should I do by a slight modify of the line?

Thanks

edit:
It's bash...

My script is now changed to:

```<code>#!/bin/bash

TASK=1101;

NUM=9;

TEND=1100;

for X in {18..2500};{

   if (X % 2 == 0);

   do

     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;

     NUM=$((NUM+2)) ;

     X=$((X+1)) ;

     TEND=$((TEND+100)) ;

     echo "$X      -t $TASK-$TEND jobs.sh" ;

     TASK=$((TASK+100)) ;}

done
</code>```

but got errors like:
line 15: syntax error near unexpected token `do'

答:
This is not C++. This is a bash script.

Your for-loop needs to start with a do:

```<code>for X in {18..2500}; do
</code>```

Your if-statement syntax looks off. It should probably be something like this, note the then:

```<code>    if [[ $((X % 2)) == 0 ]]; then
</code>```

if-blocks end with:

```<code>    fi
</code>```

And the for-do block ends with:

```<code>done
</code>```

Better still... do away with the if statement and use Bash's for-loop construct to generate only even numbers:

```<code>for ((X = 18; X <= 2500; X += 2)); do
     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;
     # ...
done
</code>```

Title: Array with only even number

Body:
for X in {18..2500} ; is one line of my script, which means to pick number one by one like: 18,19,20,21,22,23....till 2500

However I find I only need even number right now: 18,20,22,24.....2500

Then what should I do by a slight modify of the line?

Thanks

edit:
It's bash...

My script is now changed to:

#!/bin/bash

TASK=1101;

NUM=9;

TEND=1100;

for X in {18..2500};{

   if (X % 2 == 0);

   do

     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;

     NUM=$((NUM+2)) ;

     X=$((X+1)) ;

     TEND=$((TEND+100)) ;

     echo "$X      -t $TASK-$TEND jobs.sh" ;

     TASK=$((TASK+100)) ;}

done

but got errors like:
line 15: syntax error near unexpected token `do'

Body:
This is not C++. This is a bash script.

Your for-loop needs to start with a do:

for X in {18..2500}; do

Your if-statement syntax looks off. It should probably be something like this, note the then:

    if [[ $((X % 2)) == 0 ]]; then

if-blocks end with:

    fi

And the for-do block ends with:

done

Better still... do away with the if statement and use Bash's for-loop construct to generate only even numbers:

for ((X = 18; X <= 2500; X += 2)); do
     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;
     # ...
done


问:
SQL- Merging json with a node name
I have a table with json vaules in nvarchar columns

```<code>ID    ConfigKey     ConfigValue
1     employee      {"name":"jhon","age":"23","salary":"5000"}
2     Dept          {"name": "Marketing", "code":"12", "manager":"sam"}
3     manager       {"managername":"abc", "dept":"AB"}
</code>```

I need to get merged json for selected ConfiKey by adding ConfigKey value as node name for the ConfigValue and  also merged json as below.

For example when i want to get for employee and manager. Output should be like

```<code>{
 "employee": {
   "name": "jhon",
   "age": "23",
   "salary": "5000"
 },
 "manager": {
   "managername": "abc",
   "dept": "AB"
 }
}
</code>```

When I want to get for only ConfigKey value employee output should be

```<code>{
 "employee": {
   "name": "jhon",
   "age": "23",
   "salary": "5000"
 }
}
</code>```

I tried using JSON_MODIFY but couldn't achieve this. How I can achieve this in SQL query.

答:
You can do this with PIVOT and JSON_QUERY but the code will quickly get messy as you add more ConfigKey rows...

/*
 * Setup example type, table and data...
 */
create type ConfigKeyTableType as table (
  ConfigKey nvarchar(10)
);

create table dbo.Example (
  ID int,
  ConfigKey nvarchar(10),
  ConfigValue nvarchar(max)
);

insert dbo.Example (ID, ConfigKey, ConfigValue) values
  (1, N'employee', N'{"name":"jhon","age":"23","salary":"5000"}'),
  (2, N'Dept', N'{"name": "Marketing", "code":"12", "manager":"sam"}'),
  (3, N'manager', N'{"managername":"abc", "dept":"AB"}');
go
/*
 * Stored procedure to return the JSON based on the supplied ConfigKey values...
 */
create procedure dbo.usp_GetConfigJSON (
  @ConfigKeys ConfigKeyTableType readonly
)
as
begin
  set nocount on;
  select
    json_query(dept) as [dept],
    json_query(employee) as [employee],
    json_query(manager) as [manager]
  from (
    select Ex.ConfigKey, Ex.ConfigValue
    from dbo.Example Ex
    join @ConfigKeys keys on keys.ConfigKey=Ex.ConfigKey
  ) src
  pivot (max(ConfigValue) for ConfigKey in ([dept], [employee], [manager])) pvt
  for json auto, without_array_wrapper;
end
go
```
<p>To invoke it from SQL...</p>
<pre class="lang-sql prettyprint-override"><code>declare @ConfigKeys ConfigKeyTableType;
insert @ConfigKeys (ConfigKey) values
  (N'employee'),
  (N'manager');
exec dbo.usp_GetConfigJSON @ConfigKeys;
go
declare @ConfigKeys ConfigKeyTableType;
insert @ConfigKeys (ConfigKey) values
  (N'employee');
exec dbo.usp_GetConfigJSON @ConfigKeys;
go
</code>```

Which yields the results...

{
    "employee": {
        "name": "jhon",
        "age": "23",
        "salary": "5000"
    },
    "manager": {
        "managername": "abc",
        "dept": "AB"
    }
}
```
<p>...and...</p>
<pre class="lang-json prettyprint-override"><code>{
    "employee": {
        "name": "jhon",
        "age": "23",
        "salary": "5000"
    }
}
</code>```

Title: SQL- Merging json with a node name

Body:
I have a table with json vaules in nvarchar columns

ID    ConfigKey     ConfigValue
1     employee      {"name":"jhon","age":"23","salary":"5000"}
2     Dept          {"name": "Marketing", "code":"12", "manager":"sam"}
3     manager       {"managername":"abc", "dept":"AB"}

I need to get merged json for selected ConfiKey by adding ConfigKey value as node name for the ConfigValue and  also merged json as below.

For example when i want to get for employee and manager. Output should be like

{
 "employee": {
   "name": "jhon",
   "age": "23",
   "salary": "5000"
 },
 "manager": {
   "managername": "abc",
   "dept": "AB"
 }
}

When I want to get for only ConfigKey value employee output should be

{
 "employee": {
   "name": "jhon",
   "age": "23",
   "salary": "5000"
 }
}

I tried using JSON_MODIFY but couldn't achieve this. How I can achieve this in SQL query.

Body:
You can do this with PIVOT and JSON_QUERY but the code will quickly get messy as you add more ConfigKey rows...

/*
 * Setup example type, table and data...
 */
create type ConfigKeyTableType as table (
  ConfigKey nvarchar(10)
);

create table dbo.Example (
  ID int,
  ConfigKey nvarchar(10),
  ConfigValue nvarchar(max)
);

insert dbo.Example (ID, ConfigKey, ConfigValue) values
  (1, N'employee', N'{"name":"jhon","age":"23","salary":"5000"}'),
  (2, N'Dept', N'{"name": "Marketing", "code":"12", "manager":"sam"}'),
  (3, N'manager', N'{"managername":"abc", "dept":"AB"}');
go
/*
 * Stored procedure to return the JSON based on the supplied ConfigKey values...
 */
create procedure dbo.usp_GetConfigJSON (
  @ConfigKeys ConfigKeyTableType readonly
)
as
begin
  set nocount on;
  select
    json_query(dept) as [dept],
    json_query(employee) as [employee],
    json_query(manager) as [manager]
  from (
    select Ex.ConfigKey, Ex.ConfigValue
    from dbo.Example Ex
    join @ConfigKeys keys on keys.ConfigKey=Ex.ConfigKey
  ) src
  pivot (max(ConfigValue) for ConfigKey in ([dept], [employee], [manager])) pvt
  for json auto, without_array_wrapper;
end
go

To invoke it from SQL...

declare @ConfigKeys ConfigKeyTableType;
insert @ConfigKeys (ConfigKey) values
  (N'employee'),
  (N'manager');
exec dbo.usp_GetConfigJSON @ConfigKeys;
go
declare @ConfigKeys ConfigKeyTableType;
insert @ConfigKeys (ConfigKey) values
  (N'employee');
exec dbo.usp_GetConfigJSON @ConfigKeys;
go

Which yields the results...

{
    "employee": {
        "name": "jhon",
        "age": "23",
        "salary": "5000"
    },
    "manager": {
        "managername": "abc",
        "dept": "AB"
    }
}

...and...

{
    "employee": {
        "name": "jhon",
        "age": "23",
        "salary": "5000"
    }
}


问:
Retrieving text from Python Selenium
I'm trying to pull some Diablo II trading prices of a trading page using Selenium.

So far I've managed to locate the object I'm interested in using classes, but I can't retrieve the actual text which is what I need.

I have the following code:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get('https://traderie.com/diablo2resurrected/product/3382986705/buying?prop_Platform=PC&prop_Mode=softcore&makeOffer=false')

# Close cookie popup
driver.find_element(By.XPATH, '//*[@id="tyche_cmp_modal"]/div/div/div/div[5]/div[2]/a').click()

# Locate entire page of offers
All = driver.find_element(By.CLASS_NAME, "row")

# Locate individual offer
Offer = All.find_element(By.CLASS_NAME, "col-xs-12")

# Locate price in each offer
Price = Offer.find_element(By.CLASS_NAME, "sc-eCImPb")

# Print price
print(str(Price.text))

# Close page
driver.close()
</code>```

The print turns out empty, but it should return something like 3x Vex, or similar. What am I doing wrong?

答:
There are several issues here:

You should add waits. Preferably Expected Conditions explicit waits.

You are using a wrong locator for price element

Since there are multiple offers there you should iterate over the results in a loop.

Variable names should be lowercased according to accepted convention.

I think your code should be something like this:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
wait = WebDriverWait(driver, 20)

driver.get('https://traderie.com/diablo2resurrected/product/3382986705/buying?prop_Platform=PC&prop_Mode=softcore&makeOffer=false')

# Close cookie popup
wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="tyche_cmp_modal"]/div/div/div/div[5]/div[2]/a'))).click()

wait.until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@style,'capitalize')]")))
time.sleep(1)

prices = driver.find_elements(By.XPATH, "//a[contains(@style,'capitalize')]")

for price in prices:
    print(price.text)

# Close page
driver.close()
```
<p><strong>UPD</strong><br />
To iterate over offers and get each offer seller's name and the price you can do something like this:</p>
<pre class="lang-py prettyprint-override"><code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
wait = WebDriverWait(driver, 20)

driver.get('https://traderie.com/diablo2resurrected/product/3382986705/buying?prop_Platform=PC&prop_Mode=softcore&makeOffer=false')

# Close cookie popup
wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="tyche_cmp_modal"]/div/div/div/div[5]/div[2]/a'))).click()

wait.until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@style,'capitalize')]")))
time.sleep(1)

offers = driver.find_elements(By.CLASS_NAME, "col-xs-12")

for offer in offers:
    name = offer.find_element(By.XPATH, ".//a[contains(@href,'profile')]")
    prices = offer.find_elements(By.XPATH, ".//a[contains(@style,'capitalize')]")
    #now you can extract texts from name with name.text
    #and iterate over prices with
    for price in prices:
        price_text = price.text
    #You can put all these in dictionary etc.

# Close page
driver.close()
</code>```

Title: Retrieving text from Python Selenium

Body:
I'm trying to pull some Diablo II trading prices of a trading page using Selenium.

So far I've managed to locate the object I'm interested in using classes, but I can't retrieve the actual text which is what I need.

I have the following code:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get('https://traderie.com/diablo2resurrected/product/3382986705/buying?prop_Platform=PC&prop_Mode=softcore&makeOffer=false')

# Close cookie popup
driver.find_element(By.XPATH, '//*[@id="tyche_cmp_modal"]/div/div/div/div[5]/div[2]/a').click()

# Locate entire page of offers
All = driver.find_element(By.CLASS_NAME, "row")

# Locate individual offer
Offer = All.find_element(By.CLASS_NAME, "col-xs-12")

# Locate price in each offer
Price = Offer.find_element(By.CLASS_NAME, "sc-eCImPb")

# Print price
print(str(Price.text))

# Close page
driver.close()

The print turns out empty, but it should return something like 3x Vex, or similar. What am I doing wrong?

Body:
There are several issues here:

You should add waits. Preferably Expected Conditions explicit waits.

You are using a wrong locator for price element

Since there are multiple offers there you should iterate over the results in a loop.

Variable names should be lowercased according to accepted convention.

I think your code should be something like this:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
wait = WebDriverWait(driver, 20)

driver.get('https://traderie.com/diablo2resurrected/product/3382986705/buying?prop_Platform=PC&prop_Mode=softcore&makeOffer=false')

# Close cookie popup
wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="tyche_cmp_modal"]/div/div/div/div[5]/div[2]/a'))).click()

wait.until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@style,'capitalize')]")))
time.sleep(1)

prices = driver.find_elements(By.XPATH, "//a[contains(@style,'capitalize')]")

for price in prices:
    print(price.text)

# Close page
driver.close()

UPD

To iterate over offers and get each offer seller's name and the price you can do something like this:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
wait = WebDriverWait(driver, 20)

driver.get('https://traderie.com/diablo2resurrected/product/3382986705/buying?prop_Platform=PC&prop_Mode=softcore&makeOffer=false')

# Close cookie popup
wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="tyche_cmp_modal"]/div/div/div/div[5]/div[2]/a'))).click()

wait.until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@style,'capitalize')]")))
time.sleep(1)

offers = driver.find_elements(By.CLASS_NAME, "col-xs-12")

for offer in offers:
    name = offer.find_element(By.XPATH, ".//a[contains(@href,'profile')]")
    prices = offer.find_elements(By.XPATH, ".//a[contains(@style,'capitalize')]")
    #now you can extract texts from name with name.text
    #and iterate over prices with
    for price in prices:
        price_text = price.text
    #You can put all these in dictionary etc.

# Close page
driver.close()


问:
Visual Studio Code not opening with 'code' command
When I try to open VSCode from the command line with code ., I get the error ./MacOS/Electron: No such file or directory. How can I fix this?

答:
If you're getting following Error:

/usr/local/bin/code: line 6: /usr/bin/python: No such file or directory

/usr/local/bin/code: line 10: ./MacOS/Electron: No such file or directory

Update python to python3 in following File:

/Applications/Visual\ Studio\ Code.app/Contents/Resources/app/bin/code


问:
Write a program that takes a character as input (string length 1) the output is the next character in the alphabet. If input is 'Z', output is 'A'
Write a program that takes a character as input (a string of length 1), which you should assume is an upper-case character; the output should be the next character in the alphabet.

If the input is 'Z', your output should be 'A'.

Here's what i've done so far but I’m not getting A when I input Z. I’m getting [.

Please help, what am I doing wrong?

```<code>input = (input()).upper()
for character in input:
   number = ord(character) + 1
   number1 = chr(number)
   if ord('z'):
       new_number = ord(character) - 25
        number2 = chr(new_number)

print(number1)
</code>```

答:
A way of doing this may be via a match statement:

```<code>match (letter):
    case 'A':
        print('B')
    case 'B':
        print('C')
</code>```

But you will need around 30 cases...

A better idea is to use a list:

```<code>letters = ['A', 'B', 'C'...]
</code>```

then to get the letter

```<code>letter = input().upper()
</code>```

and then to get the next element in the list:

```<code>print(letters[letters.find(letter)+1])
</code>```

but there will be an error raised for 'Z', so you will need a try/except block for IndexError:

```<code>try:
    print(letters[letters.find(letter)+1])
except IndexError:
    print('A')
</code>```

Body:
Write a program that takes a character as input (a string of length 1), which you should assume is an upper-case character; the output should be the next character in the alphabet.

If the input is 'Z', your output should be 'A'.

Here's what i've done so far but I’m not getting A when I input Z. I’m getting [.

Please help, what am I doing wrong?

input = (input()).upper()
for character in input:
   number = ord(character) + 1
   number1 = chr(number)
   if ord('z'):
       new_number = ord(character) - 25
        number2 = chr(new_number)

print(number1)

Body:
A way of doing this may be via a match statement:

match (letter):
    case 'A':
        print('B')
    case 'B':
        print('C')

But you will need around 30 cases...

A better idea is to use a list:

letters = ['A', 'B', 'C'...]

then to get the letter

letter = input().upper()

and then to get the next element in the list:

print(letters[letters.find(letter)+1])

but there will be an error raised for 'Z', so you will need a try/except block for IndexError:

try:
    print(letters[letters.find(letter)+1])
except IndexError:
    print('A')


问:
Grails and OAuth
I am using a REST JSON webservice which I want to secure. The service is secured with very basic Spring security and the session is stored on the server. So before the user can access the url "/api/resource" he/she needs to login first.

I want know how to:

Only allow registered users to access my rest api

Only allow registered clients with registered users to access my rest api(e.g. GWT, Android, iOS).  I dont want to let the users access my api if the client is not registered.

With a lot of googleing I saw the concept of OAuth which has the three way authentication method.

I am using grails in my project but I did not find any support for OAuth. Does anyone have experience using OAuth with grails? Is it easy to implement using Grails?

Thanks for help

答:
Check this plugin:

http://grails.org/plugin/spring-social-core

https://github.com/synergyj/grails-spring-social-core

They already have 2 implementations, Twitter and Facebook! Now you just have to create your own implementation!

Title: Grails and OAuth