问:
JSoup, Extract specific text or image-link from website
This is in my HTML and I need to extract either the link of the image or the fileId to create a link.

```<code>{
      "created": "2018-11-06T06:46:21.181Z",
      "inRiverId": "58515",
      "mediaInformation": {
        "bildid": 67708,
        "description": "ABC",
        "excelImportField": "ABC",
        "fileId": "41964",
        "filename": "ABC",
        "imageAccess": true,
        "imageItemType": "ABC",
        "imageStatus": "ABC",
        "imageType": "ABC",
        "itcl": "ABC",
        "photographer": "ABC",
        "projectName": "ABC",
        "projectType": "Webb",
        "type": "Bild",
        "url": "https://static.john.com/images/products/41964.jpg"
      },
</code>```

The fileId is dynamic, therefor is the link also dynamic depending on which article I'm visiting on my website. The link will always start with "https://static.john.com/images/products/" and then it adds the fileId and ".jpeg" automatically.

The code above is of course just a piece of the code on the website, so there is more images on it, so it needs to extract it specifically.

The dream would be if Jsoup could get this output:
"https://static.john.com/images/products/" + "fileId" + ".jpeg"

I'm a beginner in Android Studio, and crazy-new to JSoup.

答:
MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

public class JsoupGetImage {

    public void main( String[] args ) throws IOException {

        // Get the article number from TextView to complete link
        String articlenumber = ((TextView) recyclerView.findViewHolderForAdapterPosition(0).itemView.findViewById(R.id.holderArticle)).getText().toString();

        // My URL + article number
        String url = "https://www.john.com/api/v1.0/articles/" + articlenumber;

        // JSoup
        Document doc = Jsoup.connect(url).get();

        // Pattern - Find pattern using partial link
        Pattern p = Pattern.compile("\"url\": \"(https://static.john.com/images/products/\\d+.jp[e]*g)\"");

        // Matcher - Find match in my URL from Pattern
        Matcher m = p.matcher(url);
        if (m.find()) {
            String imageUrl = m.group(1);
            System.out.println(imageUrl);
        }
    }
}
}
</code>```

Does this look good or am I missing something. How do I get my ImageView to show the image of the created link?

Kind regards,
John

Body:
This is in my HTML and I need to extract either the link of the image or the fileId to create a link.

{
      "created": "2018-11-06T06:46:21.181Z",
      "inRiverId": "58515",
      "mediaInformation": {
        "bildid": 67708,
        "description": "ABC",
        "excelImportField": "ABC",
        "fileId": "41964",
        "filename": "ABC",
        "imageAccess": true,
        "imageItemType": "ABC",
        "imageStatus": "ABC",
        "imageType": "ABC",
        "itcl": "ABC",
        "photographer": "ABC",
        "projectName": "ABC",
        "projectType": "Webb",
        "type": "Bild",
        "url": "https://static.john.com/images/products/41964.jpg"
      },

The fileId is dynamic, therefor is the link also dynamic depending on which article I'm visiting on my website. The link will always start with "https://static.john.com/images/products/" and then it adds the fileId and ".jpeg" automatically.

The code above is of course just a piece of the code on the website, so there is more images on it, so it needs to extract it specifically.

The dream would be if Jsoup could get this output:
"https://static.john.com/images/products/" + "fileId" + ".jpeg"

I'm a beginner in Android Studio, and crazy-new to JSoup.

Body:
MainActivity.java

public class MainActivity extends AppCompatActivity {

public class JsoupGetImage {

    public void main( String[] args ) throws IOException {

        // Get the article number from TextView to complete link
        String articlenumber = ((TextView) recyclerView.findViewHolderForAdapterPosition(0).itemView.findViewById(R.id.holderArticle)).getText().toString();

        // My URL + article number
        String url = "https://www.john.com/api/v1.0/articles/" + articlenumber;

        // JSoup
        Document doc = Jsoup.connect(url).get();

        // Pattern - Find pattern using partial link
        Pattern p = Pattern.compile("\"url\": \"(https://static.john.com/images/products/\\d+.jp[e]*g)\"");

        // Matcher - Find match in my URL from Pattern
        Matcher m = p.matcher(url);
        if (m.find()) {
            String imageUrl = m.group(1);
            System.out.println(imageUrl);
        }
    }
}
}

Does this look good or am I missing something. How do I get my ImageView to show the image of the created link?

Kind regards,
John


来源: stackexchange

问:
Passing data as JSON from PHP to Python
Php code for running python script with json data:

```<code>$output = shell_exec("python php_test.py " . base64_encode(json_encode($process_data)) . " 2>&1");
</code>```

Python code for decoding json:

```<code>jdata = json.loads(base64.b64decode(sys.argv[1]))
</code>```

This is how $process_data looks like:

```<code>array (size=15)
  0 =>
    array (size=1)
      'konu' => string '{"tr":"Güvenlik amaçlarına giriş", "en":"Introduction to Security Goals."}' (length=78)
  1 =>
    array (size=1)
      'konu' => string '{"tr":"Kriptografinin Matematiği.", "en":"Mathematics of Cryptography."}' (length=73)
  2 =>
    array (size=1)
      'konu' => string '{"tr":"Geleneksel Simetrik Anahtarlı Şifreler.", "en":"Traditional Symmetric Key Ciphers."}' (length=93)
  3 =>
    array (size=1)
      'konu' => string '{"tr":"Cebirsel Yapılar.", "en":"Algebraic Structures."}' (length=57)
  4 =>
    array (size=1)
      'konu' => string '{"tr":"Modern Simetrik Anahtarlı Şifrelere Giriş.", "en":"Introduction to Modern Symmetric Key Ciphers."}' (length=108)
  5 =>
    array (size=1)
      'konu' => string '{"tr":"Gelişmiş Şifreleme Standardı.", "en":"Advanced Encryption Standard."}' (length=80)
  6 =>
    array (size=1)
      'konu' => string '{"tr":"Modern Simetrik Anahtarlı Şifrelerle Şifreleme.", "en":"Encipherment Using Modern Symmetric-Key Ciphers."}' (length=116)
  7 =>
    array (size=1)
      'konu' => string '{"tr":"Stream Ciphers", "en":"Akan Şifreleme Yöntemleri."}' (length=60)
  8 =>
    array (size=1)
      'konu' => string '{"tr":"Ara Sınav", "en":"Midterm Exam"}' (length=40)
  9 =>
    array (size=1)
      'konu' => string '{"tr":"Doğrusal ve Diferansiyel Kriptanaliz.", "en":"Linear and DifferentialCryptanalysis."}' (length=93)
  10 =>
    array (size=1)
      'konu' => string '{"tr":"Kriptografik Özet Fonsiyonları.", "en":"Cryptographic Hash Functions."}' (length=80)
  11 =>
    array (size=1)
      'konu' => string '{"tr":"Asimetrik Kriptoloji", "en":"Asymmetric Cryptography"}' (length=61)
  12 =>
    array (size=1)
      'konu' => string '{"tr":"Protokollar, Tcp/Ip Protokol ve Hizmetlerinde Güvenlik", "en":"Protocols, Security in Tcp/Ip Networks"}' (length=111)
  13 =>
    array (size=1)
      'konu' => string '{"tr":"Güvenlik Duvarları ve Sanal Özel Ağlar", "en":"Firewall and Virtual Private Networking"}' (length=99)
  14 =>
    array (size=1)
      'konu' => string '{"tr":"Saldırı Tespit Sistemleri", "en":"Intrusion Detection Systems"}' (length=72)
</code>```

I'm getting a decoder error:

UnicodeEncodeError: 'charmap' codec can't encode character '\u0131' in
  position 33: character maps to < undefined>

When I remove base64_encode, I get "Expecting ',' delimiter" error instead.

I'm guessing it is caused by the double-quotes. How can I escape them?

答:
It seems like an encoding issue on the python side of things, possibly due to a difference in encoding between your PHP script and what you have set in python.

It seems that the json encoder/decoder in python needs JSON to be represented using either UTF-8, UTF-16, or UTF-32, with UTF-8 being the recommended default for maximum interoperability. Can you confirm that everything on the PHP side is UTF-8?

Here is the source:
https://docs.python.org/3/library/json.html#character-encodings

ContentLicense: CC BY-SA 4.0

Title: Passing data as JSON from PHP to Python

Body:
Php code for running python script with json data:

$output = shell_exec("python php_test.py " . base64_encode(json_encode($process_data)) . " 2>&1");

Python code for decoding json:

jdata = json.loads(base64.b64decode(sys.argv[1]))

This is how $process_data looks like:

array (size=15)
  0 =>
    array (size=1)
      'konu' => string '{"tr":"Güvenlik amaçlarına giriş", "en":"Introduction to Security Goals."}' (length=78)
  1 =>
    array (size=1)
      'konu' => string '{"tr":"Kriptografinin Matematiği.", "en":"Mathematics of Cryptography."}' (length=73)
  2 =>
    array (size=1)
      'konu' => string '{"tr":"Geleneksel Simetrik Anahtarlı Şifreler.", "en":"Traditional Symmetric Key Ciphers."}' (length=93)
  3 =>
    array (size=1)
      'konu' => string '{"tr":"Cebirsel Yapılar.", "en":"Algebraic Structures."}' (length=57)
  4 =>
    array (size=1)
      'konu' => string '{"tr":"Modern Simetrik Anahtarlı Şifrelere Giriş.", "en":"Introduction to Modern Symmetric Key Ciphers."}' (length=108)
  5 =>
    array (size=1)
      'konu' => string '{"tr":"Gelişmiş Şifreleme Standardı.", "en":"Advanced Encryption Standard."}' (length=80)
  6 =>
    array (size=1)
      'konu' => string '{"tr":"Modern Simetrik Anahtarlı Şifrelerle Şifreleme.", "en":"Encipherment Using Modern Symmetric-Key Ciphers."}' (length=116)
  7 =>
    array (size=1)
      'konu' => string '{"tr":"Stream Ciphers", "en":"Akan Şifreleme Yöntemleri."}' (length=60)
  8 =>
    array (size=1)
      'konu' => string '{"tr":"Ara Sınav", "en":"Midterm Exam"}' (length=40)
  9 =>
    array (size=1)
      'konu' => string '{"tr":"Doğrusal ve Diferansiyel Kriptanaliz.", "en":"Linear and DifferentialCryptanalysis."}' (length=93)
  10 =>
    array (size=1)
      'konu' => string '{"tr":"Kriptografik Özet Fonsiyonları.", "en":"Cryptographic Hash Functions."}' (length=80)
  11 =>
    array (size=1)
      'konu' => string '{"tr":"Asimetrik Kriptoloji", "en":"Asymmetric Cryptography"}' (length=61)
  12 =>
    array (size=1)
      'konu' => string '{"tr":"Protokollar, Tcp/Ip Protokol ve Hizmetlerinde Güvenlik", "en":"Protocols, Security in Tcp/Ip Networks"}' (length=111)
  13 =>
    array (size=1)
      'konu' => string '{"tr":"Güvenlik Duvarları ve Sanal Özel Ağlar", "en":"Firewall and Virtual Private Networking"}' (length=99)
  14 =>
    array (size=1)
      'konu' => string '{"tr":"Saldırı Tespit Sistemleri", "en":"Intrusion Detection Systems"}' (length=72)

I'm getting a decoder error:

UnicodeEncodeError: 'charmap' codec can't encode character '\u0131' in
  position 33: character maps to < undefined>

When I remove base64_encode, I get "Expecting ',' delimiter" error instead.

I'm guessing it is caused by the double-quotes. How can I escape them?


问:
Javascript doesnt seem to be attachet to my jsp
When i load login.jsp it doesn't alert if i dont input password or username
tried checking wether i correctly attached the file but it still doesnt work for me, what could be the reason?jsp just reacts the way it would react if i wouldn't use js at all

LoginPage.js

```<code>function check()
{

     var username = document.form.username.value;
     var password = document.form.password.value;

     if (username==null || username=="")
     {
     alert("Username can't be blank");
     return false;
     }
     else if(password==null||password=="")
     {
     alert("Password must be inserted ");
     return false;
     }

 }
</code>```

my jsp:

```<code>
<body>

            <div class="card-body">
                <form method="get" action="LoginServlet" onsubmit="return check()">
                    <div class="input-group form-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text"><i class="fas fa-user"></i></span>
                        </div>
                        <input id="username" type="text" class="form-control" placeholder="username" name="username">

                    </div>
                    <div class="input-group form-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text"><i class="fas fa-key"></i></span>
                        </div>
                        <input id="password" type="password" class="form-control" placeholder="password" name="password">
                    </div>

                    <div class="form-group">
                        <input id="login-button" type="submit" value="Login" class="btn float-right login_btn" >
                    </div>
                </form>
            </div>
            <div class="card-footer">
                <div class="d-flex justify-content-center links">
                    Don't have an account?<a href="register.jsp">Sign Up</a>
                </div>

            </div>
        </div>
    </div>
</div>
<script src="LoginPage.js"></script>
</body>
</html>
</code>```

any suggestions ?

答:
firstly check the HTML syntax of your jsp, it seems that the html is broken because of the last three
 because of the missing opening tags.

Then, you don't have by default a document.form property so you could get your username and password in the following way:

```<code>// or you can use document.getElementById('username')
const username = document.querySelector('#username').value;
const password = document.querySelector('#password').value;
</code>```

here details about the querySelector function

Body:
When i load login.jsp it doesn't alert if i dont input password or username
tried checking wether i correctly attached the file but it still doesnt work for me, what could be the reason?jsp just reacts the way it would react if i wouldn't use js at all

LoginPage.js

function check()
{

     var username = document.form.username.value;
     var password = document.form.password.value;

     if (username==null || username=="")
     {
     alert("Username can't be blank");
     return false;
     }
     else if(password==null||password=="")
     {
     alert("Password must be inserted ");
     return false;
     }

 }

my jsp:

                <form method="get" action="LoginServlet" onsubmit="return check()">

                        <input id="username" type="text" class="form-control" placeholder="username" name="username">

                        <input id="password" type="password" class="form-control" placeholder="password" name="password">

                        <input id="login-button" type="submit" value="Login" class="btn float-right login_btn" >

                </form>

                    Don't have an account?Sign Up

any suggestions ?

Body:
firstly check the HTML syntax of your jsp, it seems that the html is broken because of the last three </div> because of the missing opening tags.

Then, you don't have by default a document.form property so you could get your username and password in the following way:

// or you can use document.getElementById('username')
const username = document.querySelector('#username').value;
const password = document.querySelector('#password').value;

here details about the querySelector function


问:
Finding out the number of days between 2 timestamps in SQL
I'm struggling to work out how to work out the time difference between 2 timestamps

My goal -

A bunch of customers order on XXXX and then proceed to cancel on XXXX (different dates), I'm interested in finding out how many customers cancel within a year. So if a customer were to cancel on day 366 they wouldn't appear in my results.

I tried a few different functions, the nearest one I could find was INTERVAL

example -
WHERE cancel date >= order_date (within 365 days)

I hope this makes sense and I'm not missing anything glaringly obvious!

Cheers
Olly (an amateur)

答:
The number of customers that cancel within a year would be:</p>

```<code>select count(*)
from t
where cancel_date <= order_date + interval '365 day';
</code>```

Body:
The number of customers that cancel within a year would be:

select count(*)
from t
where cancel_date <= order_date + interval '365 day';


问:
ValueError: Cannot convert a Tensor of dtype resource to a NumPy array
I'm trying to isolate some user specific parameters by having matrix of parameters where each array would learn parameters specific to that user.

I want to index the matrix using the user id, and concatenate the parameters to the other features.

Lastly, have some fully-connected layers to get desirable outcome.

However, I keep getting this error on the last line of the code.

```<code>
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-93de3591ccf0> in <module>
     20 # combined = tf.keras.layers.Concatenate(axis=-1)([le_param, le])
     21
---> 22 net = tf.keras.layers.Dense(128)(combined)

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    793     # framework.
    794     if build_graph and base_layer_utils.needs_keras_history(inputs):
--> 795       base_layer_utils.create_keras_history(inputs)
    796
    797     # Clear eager losses on top level model call.

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in create_keras_history(tensors)
    182     keras_tensors: The Tensors found that came from a Keras Layer.
    183   """
--> 184   _, created_layers = _create_keras_history_helper(tensors, set(), [])
    185   return created_layers
    186

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
    229               constants[i] = backend.function([], op_input)([])
    230       processed_ops, created_layers = _create_keras_history_helper(
--> 231           layer_inputs, processed_ops, created_layers)
    232       name = op.name
    233       node_def = op.node_def.SerializeToString()

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
    229               constants[i] = backend.function([], op_input)([])
    230       processed_ops, created_layers = _create_keras_history_helper(
--> 231           layer_inputs, processed_ops, created_layers)
    232       name = op.name
    233       node_def = op.node_def.SerializeToString()

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
    227           else:
    228             with ops.init_scope():
--> 229               constants[i] = backend.function([], op_input)([])
    230       processed_ops, created_layers = _create_keras_history_helper(
    231           layer_inputs, processed_ops, created_layers)

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/backend.py in __call__(self, inputs)
   3746     return nest.pack_sequence_as(
   3747         self._outputs_structure,
-> 3748         [x._numpy() for x in outputs],  # pylint: disable=protected-access
   3749         expand_composites=True)
   3750

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/backend.py in <listcomp>(.0)
   3746     return nest.pack_sequence_as(
   3747         self._outputs_structure,
-> 3748         [x._numpy() for x in outputs],  # pylint: disable=protected-access
   3749         expand_composites=True)
   3750

ValueError: Cannot convert a Tensor of dtype resource to a NumPy array.
</code>```

Code to reproduce the error:

```<code>import tensorflow as tf

num_uids = 50
input_uid = tf.keras.layers.Input(shape=(1,), dtype=tf.int32)
params = tf.Variable(tf.random.normal((num_uids, 9)), trainable=True)

param = tf.gather_nd(params, input_uid)

input_shared_features = tf.keras.layers.Input(shape=(128,), dtype=tf.float32)
combined = tf.concat([param, input_shared_features], axis=-1)

net = tf.keras.layers.Dense(128)(combined)
</code>```

There are few things I've tried:

I tried to use tf.keras.layers.Lambda to encapsulate tf.gather_nd and tf.concat.

I tried replacing tf.concat with tf.keras.layers.Concatenate.

Oddly enough if I specify the number of items and replace Input with tf.Variable, the code would work as expected:

```<code>import tensorflow as tf

num_uids = 50
input_uid = tf.Variable(tf.ones((32, 1), dtype=tf.int32))
params = tf.Variable(tf.random.normal((num_uids, 9)), trainable=True)

param = tf.gather_nd(params, input_uid)

input_shared_features = tf.Variable(tf.ones((32, 128), dtype=tf.float32))
combined = tf.concat([param, input_shared_features], axis=-1)

net = tf.keras.layers.Dense(128)(combined)
</code>```

I'm using Tensorflow 2.1 with Python 3.6.10

答:
I faced a similar issue when I was trying to use a TensorFlow table lookup (tf.lookup.StaticHashTable) in TensorFlow 2.x. I ended up solving it by keeping it inside a Custom Keras Layer. The same solution seems to have worked for this problem as well—at least until to the version that's mentioned in the question. (I tried using TensorFlow 2.0, 2.1, and 2.2 and it worked in all of these versions.)

import tensorflow as tf

num_uids = 50
input_uid = tf.keras.Input(shape=(1,), dtype=tf.int32)
input_shared_features = tf.keras.layers.Input(shape=(128,), dtype=tf.float32)

class CustomLayer(tf.keras.layers.Layer):
    def __init__(self,num_uids):
        super(CustomLayer, self).__init__(trainable=True,dtype=tf.int64)
        self.num_uids = num_uids

    def build(self,input_shape):
        self.params = tf.Variable(tf.random.normal((num_uids, 9)), trainable=True)
        self.built=True

    def call(self, input_uid,input_shared_features):
        param = tf.gather_nd(self.params, input_uid)
        combined = tf.concat([param, input_shared_features], axis=-1)
        return combined

    def get_config(self):
        config = super(CustomLayer, self).get_config()
        config.update({'num_uids': self.num_uids})
        return config

combined = CustomLayer(num_uids)(input_uid,input_shared_features)
net = tf.keras.layers.Dense(128)(combined)
model = tf.keras.Model(inputs={'input_uid':input_uid,'input_shared_features':input_shared_features},outputs=net)
model.summary()
```

<p>Here's what model summary looked like:</p>

```Model: "model"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_1 (InputLayer)            [(None, 1)]          0
__________________________________________________________________________________________________
input_2 (InputLayer)            [(None, 128)]        0
__________________________________________________________________________________________________
custom_layer (CustomLayer)      (None, 137)          450         input_1[0][0]
__________________________________________________________________________________________________
dense (Dense)                   (None, 128)          17664       custom_layer[0][0]
==================================================================================================
Total params: 18,114
Trainable params: 18,114
Non-trainable params: 0
```

For more info you can refer to the tf.keras.layers.Layer documentation.

In case you want to refer to the table lookup problem and solution, here are the links:

git issue

Sample working code for TensorFlow lookup

Body:
I'm trying to isolate some user specific parameters by having matrix of parameters where each array would learn parameters specific to that user.

I want to index the matrix using the user id, and concatenate the parameters to the other features.

Lastly, have some fully-connected layers to get desirable outcome.

However, I keep getting this error on the last line of the code.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-93de3591ccf0> in <module>
     20 # combined = tf.keras.layers.Concatenate(axis=-1)([le_param, le])
     21
---> 22 net = tf.keras.layers.Dense(128)(combined)

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    793     # framework.
    794     if build_graph and base_layer_utils.needs_keras_history(inputs):
--> 795       base_layer_utils.create_keras_history(inputs)
    796
    797     # Clear eager losses on top level model call.

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in create_keras_history(tensors)
    182     keras_tensors: The Tensors found that came from a Keras Layer.
    183   """
--> 184   _, created_layers = _create_keras_history_helper(tensors, set(), [])
    185   return created_layers
    186

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
    229               constants[i] = backend.function([], op_input)([])
    230       processed_ops, created_layers = _create_keras_history_helper(
--> 231           layer_inputs, processed_ops, created_layers)
    232       name = op.name
    233       node_def = op.node_def.SerializeToString()

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
    229               constants[i] = backend.function([], op_input)([])
    230       processed_ops, created_layers = _create_keras_history_helper(
--> 231           layer_inputs, processed_ops, created_layers)
    232       name = op.name
    233       node_def = op.node_def.SerializeToString()

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/base_layer_utils.py in _create_keras_history_helper(tensors, processed_ops, created_layers)
    227           else:
    228             with ops.init_scope():
--> 229               constants[i] = backend.function([], op_input)([])
    230       processed_ops, created_layers = _create_keras_history_helper(
    231           layer_inputs, processed_ops, created_layers)

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/backend.py in __call__(self, inputs)
   3746     return nest.pack_sequence_as(
   3747         self._outputs_structure,
-> 3748         [x._numpy() for x in outputs],  # pylint: disable=protected-access
   3749         expand_composites=True)
   3750

~/anaconda3/envs/tam-env/lib/python3.6/site-packages/tensorflow_core/python/keras/backend.py in <listcomp>(.0)
   3746     return nest.pack_sequence_as(
   3747         self._outputs_structure,
-> 3748         [x._numpy() for x in outputs],  # pylint: disable=protected-access
   3749         expand_composites=True)
   3750

ValueError: Cannot convert a Tensor of dtype resource to a NumPy array.

Code to reproduce the error:

import tensorflow as tf

num_uids = 50
input_uid = tf.keras.layers.Input(shape=(1,), dtype=tf.int32)
params = tf.Variable(tf.random.normal((num_uids, 9)), trainable=True)

param = tf.gather_nd(params, input_uid)

input_shared_features = tf.keras.layers.Input(shape=(128,), dtype=tf.float32)
combined = tf.concat([param, input_shared_features], axis=-1)

net = tf.keras.layers.Dense(128)(combined)

There are few things I've tried:

I tried to use tf.keras.layers.Lambda to encapsulate tf.gather_nd and tf.concat.

I tried replacing tf.concat with tf.keras.layers.Concatenate.

Oddly enough if I specify the number of items and replace Input with tf.Variable, the code would work as expected:

import tensorflow as tf

num_uids = 50
input_uid = tf.Variable(tf.ones((32, 1), dtype=tf.int32))
params = tf.Variable(tf.random.normal((num_uids, 9)), trainable=True)

param = tf.gather_nd(params, input_uid)

input_shared_features = tf.Variable(tf.ones((32, 128), dtype=tf.float32))
combined = tf.concat([param, input_shared_features], axis=-1)

net = tf.keras.layers.Dense(128)(combined)

I'm using Tensorflow 2.1 with Python 3.6.10

Body:
I faced a similar issue when I was trying to use a TensorFlow table lookup (tf.lookup.StaticHashTable) in TensorFlow 2.x. I ended up solving it by keeping it inside a Custom Keras Layer. The same solution seems to have worked for this problem as well—at least until to the version that's mentioned in the question. (I tried using TensorFlow 2.0, 2.1, and 2.2 and it worked in all of these versions.)

import tensorflow as tf

num_uids = 50
input_uid = tf.keras.Input(shape=(1,), dtype=tf.int32)
input_shared_features = tf.keras.layers.Input(shape=(128,), dtype=tf.float32)

class CustomLayer(tf.keras.layers.Layer):
    def __init__(self,num_uids):
        super(CustomLayer, self).__init__(trainable=True,dtype=tf.int64)
        self.num_uids = num_uids

    def build(self,input_shape):
        self.params = tf.Variable(tf.random.normal((num_uids, 9)), trainable=True)
        self.built=True

    def call(self, input_uid,input_shared_features):
        param = tf.gather_nd(self.params, input_uid)
        combined = tf.concat([param, input_shared_features], axis=-1)
        return combined

    def get_config(self):
        config = super(CustomLayer, self).get_config()
        config.update({'num_uids': self.num_uids})
        return config

combined = CustomLayer(num_uids)(input_uid,input_shared_features)
net = tf.keras.layers.Dense(128)(combined)
model = tf.keras.Model(inputs={'input_uid':input_uid,'input_shared_features':input_shared_features},outputs=net)
model.summary()

Here's what model summary looked like:

Model: "model"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_1 (InputLayer)            [(None, 1)]          0
__________________________________________________________________________________________________
input_2 (InputLayer)            [(None, 128)]        0
__________________________________________________________________________________________________
custom_layer (CustomLayer)      (None, 137)          450         input_1[0][0]
__________________________________________________________________________________________________
dense (Dense)                   (None, 128)          17664       custom_layer[0][0]
==================================================================================================
Total params: 18,114
Trainable params: 18,114
Non-trainable params: 0

For more info you can refer to the tf.keras.layers.Layer documentation.

In case you want to refer to the table lookup problem and solution, here are the links:

git issue

Sample working code for TensorFlow lookup


问:
Python help working with packages and modules
I need some help with working with a folder structure in python. I was given an structure like this:

```<code>/main-folder
    /assets
        somefiles.txt
    /integrations
        /module-folder
            __init__.py
            ingestion.py
        __init__.py
    models.py
</code>```

Inside ingestion.py I have:

```<code>import os
from models import MyModel

PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

some_function()
    some_processing()

if __name__ == "__main__":
    some_function()
</code>```

Both __init__.py mentioned above are empty.

So I need to process some info and use the models module to store them. when trying to execute intestion.py directly from its dir it says: No module named 'models'. So I'm guessing I have to execute the whole thing as a package. I have no idea how should I import a module located above the package and can't touch the structure.

Any help woud be appreciated.

答:
What you have to do is to add the module's directory to the PYTHONPATH environment variable. If you don't want to do this however, You can modify the sys.path list in your program where the Python interpreter searches for the modules to import, the python documentation says:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

the directory containing the input script (or the current directory).

PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended.

Knowing this, you can do the following in your program:

```<code>import sys
# Add the main-folder folder path to the sys.path list
sys.path.append('/path/to/main-folder/')

# Now you can import your module
from main-folder import models
# Or just
import main-folder
</code>```

Body:
I need some help with working with a folder structure in python. I was given an structure like this:

/main-folder
    /assets
        somefiles.txt
    /integrations
        /module-folder
            __init__.py
            ingestion.py
        __init__.py
    models.py

Inside ingestion.py I have:

import os
from models import MyModel

PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

some_function()
    some_processing()

if __name__ == "__main__":
    some_function()

Both __init__.py mentioned above are empty.

So I need to process some info and use the models module to store them. when trying to execute intestion.py directly from its dir it says: No module named 'models'. So I'm guessing I have to execute the whole thing as a package. I have no idea how should I import a module located above the package and can't touch the structure.

Any help woud be appreciated.

Body:
What you have to do is to add the module's directory to the PYTHONPATH environment variable. If you don't want to do this however, You can modify the sys.path list in your program where the Python interpreter searches for the modules to import, the python documentation says:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

the directory containing the input script (or the current directory).

PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended.

Knowing this, you can do the following in your program:

import sys
# Add the main-folder folder path to the sys.path list
sys.path.append('/path/to/main-folder/')

# Now you can import your module
from main-folder import models
# Or just
import main-folder


问:
Is there any way for execute a stored procedure from an Oracle database?
I have a connection to an Oracle database, but I don't know how execute a stored procedure. Is it possible from Data Factory?</p>

答:
Can you try using a Lookup Activity, and where there is a choice of using a table or query, select query.  Since this provides a place to write your own statement, you can try writing an execute stored proc statement.

One thing to remember about Lookup activity, is it expects data to be returned.  If your stored proc does not return data, you may need to add an additional statement to return dummy data.

I have only done this with SQL before, but I see no reason it wouldn't work with Oracle as well.


问:
Trigger a jQuery Event Handler Assigned in a Different Code Block
I have a case where a click handler is defined/assigned in one jQuery code block (file) and I want to trigger it from another click event defined/assigned in a different jQuery code block.  How can I accomplish this?

The following code is a greatly simplified version of what I am trying to accomplish. The behavior I want to see is a JavaScript alert "Element One" when I click #Element2.

Example HTML:

```<code><p id="Element1">Element One</p>
<p id="Element2">Element Two</p>
</code>```

First jQuery code block:

```<code>$(document).ready(function() {
    $('#Element1').click(function() {
        alert('Element One');
    });
});
</code>```

Second jQuery code block:

```<code>$(document).ready(function() {
    $('#Element2').click(function() {
        $('#Element1').click();
    });
});
</code>```

UPDATE: My original example actually works. I was building upon my field hint jQuery UI Dialog solution, and didn't account for about the 'clickoutside' handler that I was using.  Adding a check to for the second element in my 'clickoutside' handler allows the dialog to display.

答:
EDIT: This is based on JohnP's "trigger" suggestion (so you should choose him as the right answer)...

If I load this block from an external js file...

```<code>$(document).ready(function() {

    $('#Element1').click(function () {
        alert( $(this).text() );
    });

});
</code>```

Then load this in a script tag within the HTML itself...

```<code>$(document).ready(function() {

    $('#Element2').click(function () {
        $('#Element1').trigger('click');
    });

});
</code>```

Seems to be working as intended.

Body:
I have a case where a click handler is defined/assigned in one jQuery code block (file) and I want to trigger it from another click event defined/assigned in a different jQuery code block.  How can I accomplish this?

The following code is a greatly simplified version of what I am trying to accomplish. The behavior I want to see is a JavaScript alert "Element One" when I click #Element2.

Example HTML:

Element One

Element Two

First jQuery code block:

$(document).ready(function() {
    $('#Element1').click(function() {
        alert('Element One');
    });
});

Second jQuery code block:

$(document).ready(function() {
    $('#Element2').click(function() {
        $('#Element1').click();
    });
});

UPDATE: My original example actually works. I was building upon my field hint jQuery UI Dialog solution, and didn't account for about the 'clickoutside' handler that I was using.  Adding a check to for the second element in my 'clickoutside' handler allows the dialog to display.

Body:
EDIT: This is based on JohnP's "trigger" suggestion (so you should choose him as the right answer)...

If I load this block from an external js file...

$(document).ready(function() {

    $('#Element1').click(function () {
        alert( $(this).text() );
    });

});

Then load this in a script tag within the HTML itself...

$(document).ready(function() {

    $('#Element2').click(function () {
        $('#Element1').trigger('click');
    });

});

Seems to be working as intended.

ContentLicense: CC BY-SA 3.0


问:
What is the problem with importing this module?
I have a module called sinfun:

```<code>#!/usr/bin/env python
#sinfun.py

def newsin(x):
   return sin(x)/x
</code>```

and I want to use it in this program:

```<code>#!/usr/bin/env python
from math import *
import sinfun

x = input("enter x: ")
x = float(x)
y = sinfun.newsin(x)
print(y)
</code>```

What is the problem in this example and what must be done to make the code work?

答: If you put 'from math import *' into sinfun.py, this works.  Would this be the preferred setup, making 'sinfun.py' a black box of sorts?  As written, I get an error that it couldn't find 'sin'.</p>

Body:
I have a module called sinfun:

#!/usr/bin/env python
#sinfun.py

def newsin(x):
   return sin(x)/x

and I want to use it in this program:

#!/usr/bin/env python
from math import *
import sinfun

x = input("enter x: ")
x = float(x)
y = sinfun.newsin(x)
print(y)

What is the problem in this example and what must be done to make the code work?


问:
Add minutes to PHP Datetime to calculate start/end of event
I would like to calculate with PHP the start and end datetime of an event. I get the start of this event and the duration to add to get the end. So I tried the following code:

```<code>$startTime = $this->getStartTime();
$endTime = $this->getStartTime();

$endTime->add(new DateInterval('PT75M'));
</code>```

in this example I add 75 minutes to the start time and I calculate the end of the event. It works, however it edits also the start time. I read in the PHP docs that the ADD method edits the object which is called on but I don't understand how it could edit the startEdit variable. I don't use reference in any of the methods that I wrote in the example, neither in the getStartTime function

答:
If it is possible to change getStartTime() method's return type, I highly recommend changing it from \DateTime to \DateTimeImmutable.

Then the code will go as follows:

```<code>$endTime = $startTime->add(new DateInterval('PT75M'));
</code>```

More examples and advantages of this approach are described pretty well in this Nikola Poša's blog article.

Body:
I would like to calculate with PHP the start and end datetime of an event. I get the start of this event and the duration to add to get the end. So I tried the following code:

$startTime = $this->getStartTime();
$endTime = $this->getStartTime();

$endTime->add(new DateInterval('PT75M'));

in this example I add 75 minutes to the start time and I calculate the end of the event. It works, however it edits also the start time. I read in the PHP docs that the ADD method edits the object which is called on but I don't understand how it could edit the startEdit variable. I don't use reference in any of the methods that I wrote in the example, neither in the getStartTime function

Body:
If it is possible to change getStartTime() method's return type, I highly recommend changing it from \DateTime to \DateTimeImmutable.

Then the code will go as follows:

$endTime = $startTime->add(new DateInterval('PT75M'));

More examples and advantages of this approach are described pretty well in this Nikola Poša's blog article.


问:
core 3.1 error.Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection

.Net core 3.1

```<code>    `DBContext dbEntity;
    public CompanyService(DBContext _dbEntity)
    {
        dbEntity = _dbEntity;
    }
   `public async Task<string> Save(ModelCompany comp)
    {
                await dbEntity.Company.AddAsync(comp);
                await dbEntity.SaveChangesAsync();
                return "Saved";
    }
</code>```

while insert data got error on await dbEntity.SaveChangesAsync(); section

Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'DBContext'.

how can solve this.Also need to add one more table data on transaction commit and rollback base.how can do it on .net core 3.1

答: Please make sure that your context life time in startup is Singleton not scope. (i.e. services.AddSingleton)</p>

Body:
.Net core 3.1

    `DBContext dbEntity;
    public CompanyService(DBContext _dbEntity)
    {
        dbEntity = _dbEntity;
    }
   `public async Task<string> Save(ModelCompany comp)
    {
                await dbEntity.Company.AddAsync(comp);
                await dbEntity.SaveChangesAsync();
                return "Saved";
    }

while insert data got error on await dbEntity.SaveChangesAsync(); section

Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'DBContext'.

how can solve this.Also need to add one more table data on transaction commit and rollback base.how can do it on .net core 3.1


问:
How to Increase /decrease the font size In PyQt5 QLabel (Fixed Size)?
In my code, use one QLabel with fixed dimension/size. At beginning, I assign text  "Hello,Python" to that QLablel. Now I want to change the text of the QLablel to "Hai, Welcome to Python".

How to decrease the font size of the QLabel, and display full text  with that particular area/size (without any cut off / hidde /hidden) ?

```<code>import sys
from PyQt5.QtWidgets import *

class Labelexample(QWidget):
    def __init__(self):
        super().__init__()
        self.labl = QLabel("Hello,Python",self)
        self.tbox = QLineEdit(self)
        self.labl.setFixedSize(150,30)
        self.tbox.setFixedSize(200,30)
        self.labl.move(50,50)
        self.tbox.move(140,50)
        self.labl.setText("Hai, welcome to Python")
        # self.labl.adjustsize()

app = QApplication(sys.argv)
mywin = Labelexample()
mywin.show()
sys.exit(app.exec_())
</code>```

答:
The QFontMetrics class provides font metrics information. https://doc.qt.io/qt-5/qfontmetrics.html#QFontMetrics

Try it:

```<code>import sys
from PyQt5.Qt import *

class Labelexample(QWidget):
    def __init__(self):
        super().__init__()

        text = "Hello,Python"
        self.labl = QLabel(text, self)
#        self.labl.setFixedSize(150,30)
        self.labl.setFixedWidth(150)                            # +++
        self.labl.setMinimumHeight(30)                          # +++

        self.labl.move(50,50)
        self.labl.setStyleSheet("background-color: yellow;")

        self.tbox = QLineEdit(self)
        self.tbox.setFixedSize(200,30)
#        self.tbox.move(140,50)
        self.tbox.move(200,50)
        self.tbox.returnPressed.connect(self.return_pressed)    # +++

        self.pointSize = 20                                     # 20
        self.fontD = self.font()
        self.fontD.setPointSize(self.pointSize)
        self.metrics = QFontMetrics(self.fontD)
        self.width = self.metrics.width(text)
        self.height = self.metrics.height()
        self.labl.setFixedWidth(self.width)
        self.labl.setFont(self.fontD)

#        text = "Hai, welcome to Python"
#        self.labl.setText(text)                                 #         v             v
        self.labl.adjustSize()                                   # - adjustsize  + adjustSize

    def return_pressed(self):                                    # +++
        if not self.tbox.text():
            self.labl.setText('')
            self.labl.setFont(self.fontD)
            self.labl.adjustSize()
            return
        width = self.metrics.width(self.tbox.text())
        height = self.metrics.height()

        if not width:
            width = 1

        koef = self.width / width
        pointSize = int(self.pointSize * koef)
        font = self.font()
        font.setPointSize(pointSize)
        self.labl.setFont(font)
        height = self.metrics.height()
        self.labl.setText(self.tbox.text())
        self.labl.adjustSize()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mywin = Labelexample()
    mywin.resize(450, 415)
    mywin.show()
    sys.exit(app.exec_())
</code>```

Body:
In my code, use one QLabel with fixed dimension/size. At beginning, I assign text  "Hello,Python" to that QLablel. Now I want to change the text of the QLablel to "Hai, Welcome to Python".

How to decrease the font size of the QLabel, and display full text  with that particular area/size (without any cut off / hidde /hidden) ?

import sys
from PyQt5.QtWidgets import *

class Labelexample(QWidget):
    def __init__(self):
        super().__init__()
        self.labl = QLabel("Hello,Python",self)
        self.tbox = QLineEdit(self)
        self.labl.setFixedSize(150,30)
        self.tbox.setFixedSize(200,30)
        self.labl.move(50,50)
        self.tbox.move(140,50)
        self.labl.setText("Hai, welcome to Python")
        # self.labl.adjustsize()

app = QApplication(sys.argv)
mywin = Labelexample()
mywin.show()
sys.exit(app.exec_())

Body:
The QFontMetrics class provides font metrics information. https://doc.qt.io/qt-5/qfontmetrics.html#QFontMetrics

Try it:

import sys
from PyQt5.Qt import *

class Labelexample(QWidget):
    def __init__(self):
        super().__init__()

        text = "Hello,Python"
        self.labl = QLabel(text, self)
#        self.labl.setFixedSize(150,30)
        self.labl.setFixedWidth(150)                            # +++
        self.labl.setMinimumHeight(30)                          # +++

        self.labl.move(50,50)
        self.labl.setStyleSheet("background-color: yellow;")

        self.tbox = QLineEdit(self)
        self.tbox.setFixedSize(200,30)
#        self.tbox.move(140,50)
        self.tbox.move(200,50)
        self.tbox.returnPressed.connect(self.return_pressed)    # +++

        self.pointSize = 20                                     # 20
        self.fontD = self.font()
        self.fontD.setPointSize(self.pointSize)
        self.metrics = QFontMetrics(self.fontD)
        self.width = self.metrics.width(text)
        self.height = self.metrics.height()
        self.labl.setFixedWidth(self.width)
        self.labl.setFont(self.fontD)

#        text = "Hai, welcome to Python"
#        self.labl.setText(text)                                 #         v             v
        self.labl.adjustSize()                                   # - adjustsize  + adjustSize

    def return_pressed(self):                                    # +++
        if not self.tbox.text():
            self.labl.setText('')
            self.labl.setFont(self.fontD)
            self.labl.adjustSize()
            return
        width = self.metrics.width(self.tbox.text())
        height = self.metrics.height()

        if not width:
            width = 1

        koef = self.width / width
        pointSize = int(self.pointSize * koef)
        font = self.font()
        font.setPointSize(pointSize)
        self.labl.setFont(font)
        height = self.metrics.height()
        self.labl.setText(self.tbox.text())
        self.labl.adjustSize()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mywin = Labelexample()
    mywin.resize(450, 415)
    mywin.show()
    sys.exit(app.exec_())


问:
How to create classes in specs without polluting global namespace?
What's the best way to define a class within the context of a spec, and not have it pollute the global namespace? How does the other file even get access to that constant?

bowling_spec.rb

require "spec_helper"

describe Bowling do
  context "when validate is defined" do
    let(:dummy_class) {
      Class.new(described_class) do
        METRICS_NAMESPACE = "ExtendedClass.Metrics.namespace"
      end
    }

    it "does nothing" do
      dummy_class
    end
  end
end
```

<p>Spec - batting_spec.rb</p>

<pre class="lang-rb prettyprint-override"><code>require "spec_helper"

describe Batting do
  context do
    it "does weird thing" do
      expect { self.class.const_get(:METRICS_NAMESPACE) }.to raise_error(NameError)
    end
  end
end
</code>```

If you run the individual spec file

```<code>rspec spec/batting_spec.rb
.

Finished in 0.00285 seconds (files took 0.12198 seconds to load)
1 example, 0 failures
</code>```

If you run the spec which defines the dummy class

```<code>rspec spec/bowling_spec.rb spec/batting_spec.rb
.F

Failures:

  1) Batting  does weird thing
     Failure/Error: expect { self.class.const_get(:METRICS_NAMESPACE) }.to raise_error(NameError)
       expected NameError but nothing was raised
     # ./spec/batting_spec.rb:6:in `block (3 levels) in <top (required)>'

Finished in 0.01445 seconds (files took 0.12715 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/batting_spec.rb:5 # Batting  does weird thing
</code>```

To reproduce the error: I created a repo: https://github.com/pratik60/rspec-pollution with updated Readme

答:
Running  rspec spec/batting_spec.rb spec/bowling_spec.rb

2 examples, 0 failures

Running rspec spec/bowling_spec.rb spec/batting_spec.rb
Gives the error you mention.

Using binding.pry:

```<code>describe Batting do
  context do
    it "does weird thing" do
      require 'pry'
      binding.pry
      expect { self.class.const_get(:METRICS_NAMESPACE) }.to raise_error(NameError)
    end
  end
end
</code>```

self.class.ancestors

```<code>[RSpec::ExampleGroups::Batting::Anonymous,
 RSpec::ExampleGroups::Batting::Anonymous::LetDefinitions,
 RSpec::ExampleGroups::Batting::Anonymous::NamedSubjectPreventSuper,
 RSpec::ExampleGroups::Batting,
 RSpec::ExampleGroups::Batting::LetDefinitions,
 RSpec::ExampleGroups::Batting::NamedSubjectPreventSuper,
 RSpec::Core::ExampleGroup,
</code>```

Going down the inheritance tree

```<code>RSpec::Core::ExampleGroup::METRICS_NAMESPACE
(pry):4: warning: toplevel constant METRICS_NAMESPACE referenced by RSpec::Core::ExampleGroup::METRICS_NAMESPACE
=> "ExtendedClass.Metrics.namespace"
</code>```

Checking the first object on the chain

Object::METRICS_NAMESPACE

```<code>=>"ExtendedClass.Metrics.namespace"
</code>```

Even further

```<code>Class::METRICS_NAMESPACE
(pry):2: warning: toplevel constant METRICS_NAMESPACE referenced by Class::METRICS_NAMESPACE
=> "ExtendedClass.Metrics.namespace"
</code>```

TL ; DR

As you said, when you did METRICS_NAMESPACE = "ExtendedClass.Metrics.namespace", you created a global namespace constant. (That is, a constant inside the uppermost ruby constant, Class)

Simply do this instead

```<code>Class.new(described_class) do
        self.const_set('METRICS_NAMESPACE', "ExtendedClass.Metrics.namespace")
      end
</code>```

rspec spec/bowling_spec.rb spec/batting_spec.rb

```<code>Finished in 1.55 seconds (files took 0.08012 seconds to load)
2 examples, 0 failures
</code>```

Body:
What's the best way to define a class within the context of a spec, and not have it pollute the global namespace? How does the other file even get access to that constant?

bowling_spec.rb

require "spec_helper"

describe Bowling do
  context "when validate is defined" do
    let(:dummy_class) {
      Class.new(described_class) do
        METRICS_NAMESPACE = "ExtendedClass.Metrics.namespace"
      end
    }

    it "does nothing" do
      dummy_class
    end
  end
end

Spec - batting_spec.rb

require "spec_helper"

describe Batting do
  context do
    it "does weird thing" do
      expect { self.class.const_get(:METRICS_NAMESPACE) }.to raise_error(NameError)
    end
  end
end

If you run the individual spec file

rspec spec/batting_spec.rb
.

Finished in 0.00285 seconds (files took 0.12198 seconds to load)
1 example, 0 failures

If you run the spec which defines the dummy class

rspec spec/bowling_spec.rb spec/batting_spec.rb
.F

Failures:

  1) Batting  does weird thing
     Failure/Error: expect { self.class.const_get(:METRICS_NAMESPACE) }.to raise_error(NameError)
       expected NameError but nothing was raised
     # ./spec/batting_spec.rb:6:in `block (3 levels) in <top (required)>'

Finished in 0.01445 seconds (files took 0.12715 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/batting_spec.rb:5 # Batting  does weird thing

To reproduce the error: I created a repo: https://github.com/pratik60/rspec-pollution with updated Readme

Body:
Running  rspec spec/batting_spec.rb spec/bowling_spec.rb

2 examples, 0 failures

Running rspec spec/bowling_spec.rb spec/batting_spec.rb
Gives the error you mention.

Using binding.pry:

describe Batting do
  context do
    it "does weird thing" do
      require 'pry'
      binding.pry
      expect { self.class.const_get(:METRICS_NAMESPACE) }.to raise_error(NameError)
    end
  end
end

self.class.ancestors

[RSpec::ExampleGroups::Batting::Anonymous,
 RSpec::ExampleGroups::Batting::Anonymous::LetDefinitions,
 RSpec::ExampleGroups::Batting::Anonymous::NamedSubjectPreventSuper,
 RSpec::ExampleGroups::Batting,
 RSpec::ExampleGroups::Batting::LetDefinitions,
 RSpec::ExampleGroups::Batting::NamedSubjectPreventSuper,
 RSpec::Core::ExampleGroup,

Going down the inheritance tree

RSpec::Core::ExampleGroup::METRICS_NAMESPACE
(pry):4: warning: toplevel constant METRICS_NAMESPACE referenced by RSpec::Core::ExampleGroup::METRICS_NAMESPACE
=> "ExtendedClass.Metrics.namespace"

Checking the first object on the chain

Object::METRICS_NAMESPACE

=>"ExtendedClass.Metrics.namespace"

Even further

Class::METRICS_NAMESPACE
(pry):2: warning: toplevel constant METRICS_NAMESPACE referenced by Class::METRICS_NAMESPACE
=> "ExtendedClass.Metrics.namespace"

TL ; DR

As you said, when you did METRICS_NAMESPACE = "ExtendedClass.Metrics.namespace", you created a global namespace constant. (That is, a constant inside the uppermost ruby constant, Class)

Simply do this instead

Class.new(described_class) do
        self.const_set('METRICS_NAMESPACE', "ExtendedClass.Metrics.namespace")
      end

rspec spec/bowling_spec.rb spec/batting_spec.rb

Finished in 1.55 seconds (files took 0.08012 seconds to load)
2 examples, 0 failures


问:
Using filter() with across() to keep all rows of a data frame that include a missing value for any variable
Sometimes I want to view all rows in a data frame that will be dropped if I drop all rows that have a missing value for any variable. In this case, I'm specifically interested in how to do this with dplyr 1.0's across() function used inside of the filter() verb.

Here is an example data frame:

```<code>df <- tribble(
  ~id, ~x, ~y,
  1, 1, 0,
  2, 1, 1,
  3, NA, 1,
  4, 0, 0,
  5, 1, NA
)
</code>```

Code for keeping rows that DO NOT include any missing values is provided on the tidyverse website. Specifically, I can use:

```<code>df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ !is.na(.x)
    )
  )
</code>```

Which returns:

```<code># A tibble: 3 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     1     1     0
2     2     1     1
3     4     0     0
</code>```

However, I can't figure out how to return the opposite -- rows with a missing value in any variable. The result I'm looking for is:

```<code># A tibble: 2 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     3    NA     1
2     5     1    NA
</code>```

My first thought was just to remove the !:

```<code>df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ is.na(.x)
    )
  )
</code>```

But, that returns zero rows.

Of course, I can get the answer I want with this code if I know all variables that have a missing value ahead of time:

```<code>df %>%
  filter(is.na(x) | is.na(y))
</code>```

But, I'm looking for a solution that doesn't require me to know which variables have a missing value ahead of time. Additionally, I'm aware of how to do this with the filter_all() function:

```<code>df %>%
  filter_all(any_vars(is.na(.)))
</code>```

But, the filter_all() function has been superseded by the use of across() in an existing verb. See https://dplyr.tidyverse.org/articles/colwise.html

Other unsuccessful attempts I've made are:

```<code>df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.))
    )
  )
</code>```

答:
We can use reduce

```<code>library(dplyr)
library(purrr)
df %>%
      filter(across(everything(), is.na) %>% reduce(`|`))
# A tibble: 2 x 3
#     id     x     y
#  <dbl> <dbl> <dbl>
#1     3    NA     1
#2     5     1    NA
</code>```

Body:
Sometimes I want to view all rows in a data frame that will be dropped if I drop all rows that have a missing value for any variable. In this case, I'm specifically interested in how to do this with dplyr 1.0's across() function used inside of the filter() verb.

Here is an example data frame:

df <- tribble(
  ~id, ~x, ~y,
  1, 1, 0,
  2, 1, 1,
  3, NA, 1,
  4, 0, 0,
  5, 1, NA
)

Code for keeping rows that DO NOT include any missing values is provided on the tidyverse website. Specifically, I can use:

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ !is.na(.x)
    )
  )

Which returns:

# A tibble: 3 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     1     1     0
2     2     1     1
3     4     0     0

However, I can't figure out how to return the opposite -- rows with a missing value in any variable. The result I'm looking for is:

# A tibble: 2 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     3    NA     1
2     5     1    NA

My first thought was just to remove the !:

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ is.na(.x)
    )
  )

But, that returns zero rows.

Of course, I can get the answer I want with this code if I know all variables that have a missing value ahead of time:

df %>%
  filter(is.na(x) | is.na(y))

But, I'm looking for a solution that doesn't require me to know which variables have a missing value ahead of time. Additionally, I'm aware of how to do this with the filter_all() function:

df %>%
  filter_all(any_vars(is.na(.)))

But, the filter_all() function has been superseded by the use of across() in an existing verb. See https://dplyr.tidyverse.org/articles/colwise.html

Other unsuccessful attempts I've made are:

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.))
    )
  )

Body:
We can use reduce

library(dplyr)
library(purrr)
df %>%
      filter(across(everything(), is.na) %>% reduce(`|`))
# A tibble: 2 x 3
#     id     x     y
#  <dbl> <dbl> <dbl>
#1     3    NA     1
#2     5     1    NA


问:
In Angular how can I pass the response of my post request as one of the parameters to go into another post request?
I have a form with two sections, that dispatch two post request actions, the second request needs parameters from the first one to be successfully sent. But I'm not sure how :( I have the request and response of the first action working fine but I'm just not sure how or where to implement the logic - should it be in the service? a reducer? I tried forkjoin then realised I had no idea what I was doing. Thanks in advance for any help!

My component :

```<code>
    const newArtist = this.store.dispatch(new CreateArtist({
      ...generalDetails,
      hometown,
    }))

    const newArtistExtraInfo = this.store.dispatch(new CreateDiscography({
      ...songCatalogue
    }
    ));

    forkJoin([newArtist, newArtistExtraInfo]).subscribe(result => {
      console.log(`the results are in : ${result}`)
    })
</code>```

答:
In this case you could pipe in the second request with the RxJS switchMap operator. Try the following

firstRequest().pipe(
  switchMap(responseFirst => secondRequest(responseFirst)),
  catchError(errorFirst => of(errorFirst))
).subscribe(
  responseSecond => { },
  errorSecond => { }
);
```

Now the first request will be completed and it's response will be used as the argument for the second request. There are other higher order mapping operators like mergeMap, concatMap and exhaustMap that are used for specific purposes.

Body:
I have a form with two sections, that dispatch two post request actions, the second request needs parameters from the first one to be successfully sent. But I'm not sure how :( I have the request and response of the first action working fine but I'm just not sure how or where to implement the logic - should it be in the service? a reducer? I tried forkjoin then realised I had no idea what I was doing. Thanks in advance for any help!

My component :

    const newArtist = this.store.dispatch(new CreateArtist({
      ...generalDetails,
      hometown,
    }))

    const newArtistExtraInfo = this.store.dispatch(new CreateDiscography({
      ...songCatalogue
    }
    ));

    forkJoin([newArtist, newArtistExtraInfo]).subscribe(result => {
      console.log(`the results are in : ${result}`)
    })

Body:
In this case you could pipe in the second request with the RxJS switchMap operator. Try the following

firstRequest().pipe(
  switchMap(responseFirst => secondRequest(responseFirst)),
  catchError(errorFirst => of(errorFirst))
).subscribe(
  responseSecond => { },
  errorSecond => { }
);

Now the first request will be completed and it's response will be used as the argument for the second request. There are other higher order mapping operators like mergeMap, concatMap and exhaustMap that are used for specific purposes.


问:
autosummary generated documentation missing all dunder methods except for `__init__`
I am using Sphinx's autosummary to automatically generate individual rst files for each member of my module. The documentation is created as expected, except that the generated rst files are missing all dunder methods except for __init__.

In my conf.py I've got the following lines:

```<code>extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
]

autosummary_generate = True
autosummary_imported_members = True
</code>```

Consider the dummy class below, which contains both dunder and regular public methods:

```<code>class MyClassA:

    def __init__(self):
        r'__init__ docstring'
        pass

    def __call__(self):
        r'__call__ docstring'
        pass

    def __len__(self):
        r'__len__ docstring'
        pass

    def public_method_1(self):
        r'public_method_1 docstring'
        pass

    def public_method_2(self):
        r'public_method_2 docstring'
        pass

</code>```

In my main rst file, I set up autosummary as follows:

```<code>.. autosummary::
    :toctree: my_module_members

    my_module.MyClassA
    my_module.MyClassB
</code>```

As expected, autosummary creates a subdirectory named /my_module_members with individual rst files for each member of the module. But only __init__ is listed in the Methods section of these automatically generated rst files. E.g.:

```<code>my_module.MyClassA
==================

.. currentmodule:: my_module

.. autoclass:: MyClassA

   .. rubric:: Methods

   .. autosummary::

      ~MyClassA.__init__
      ~MyClassA.public_method_1
      ~MyClassA.public_method_2
</code>```

Thus, in the html documentation generated, only those three methods are listed in the methods table, and __call__ and __len__ are not there:

So my question is how to include all special methods when using autosummary in this way?

答:
The issue is with the default template that autosummary uses for classes.  This is the relevant page in the documentation, but it's more helpful to look at the default template directly:

# In the sphinx v3.0.4 source code:
# sphinx/ext/autosummary/templates/autosummary/class.rst
{{ fullname | escape | underline}}

.. currentmodule:: {{ module }}

.. autoclass:: {{ objname }}

   {% block methods %}
   .. automethod:: __init__

   {% if methods %}
   .. rubric:: Methods

   .. autosummary::
   {% for item in methods %}
      ~{{ name }}.{{ item }}
   {%- endfor %}
   {% endif %}
   {% endblock %}

   {% block attributes %}
   {% if attributes %}
   .. rubric:: Attributes

   .. autosummary::
   {% for item in attributes %}
      ~{{ name }}.{{ item }}
   {%- endfor %}
   {% endif %}
   {% endblock %}
```

<p>You can see how this template corresponds to the stub files that were generated for your project (although I'm not sure why yours is missing the <code>.. automethod:: __init__</code> line; maybe we have different versions of sphinx).  The important part is the <code>{% for item in methods %}</code> loop.  The docs linked above briefly mention that <code>methods</code> only include "public" methods, which means methods that don't begin with an underscore.  <code>__init__()</code> is also considered public, as per line 242 of <code>sphinx/ext/autosummary/generate.py</code>, although this doesn't seem to be documented anywhere.  So hopefully that explains the behavior you're seeing.</p>

<p>With that in mind, I can think of three ways to include all of the special methods in the documentation:</p>

<ol>
<li><p>Provide a custom template that uses <code>members</code> instead of <code>methods</code>.  This should document everything, but will eliminate the distinction between methods, attributes, inherited members, inner classes, etc.</p></li>
<li><p>This isn't documented and I haven't tried it, it looks like you might be able to replace <code>methods</code> with <code>all_methods</code> to include all methods in the autosummary (see line 242 again).  There won't be any distinction between public and private methods, though.</p></li>
<li><p>Try using autoclasstoc.  Full disclosure: this is a package I wrote to do a better job of summarizing class methods in sphinx docs.  It's much more configurable than autosummary, and it includes every method by default.  It also collapses inherited methods, which can be really nice for big classes, although that may or may not be relevant to you.</p>

<p>This page describes how to use autoclasstoc in conjunction with autosummary, but the gist of it is that you need a custom template that looks something like this:</p>

<pre class="lang-py prettyprint-override"><code>{{ fullname | escape | underline}}

.. currentmodule:: {{ module }}

.. autoclass:: {{ objname }}
   :members:
   :special-members:

    .. autoclasstoc::
</code>```

Body:
I am using Sphinx's autosummary to automatically generate individual rst files for each member of my module. The documentation is created as expected, except that the generated rst files are missing all dunder methods except for __init__.

In my conf.py I've got the following lines:

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
]

autosummary_generate = True
autosummary_imported_members = True

Consider the dummy class below, which contains both dunder and regular public methods:

class MyClassA:

    def __init__(self):
        r'__init__ docstring'
        pass

    def __call__(self):
        r'__call__ docstring'
        pass

    def __len__(self):
        r'__len__ docstring'
        pass

    def public_method_1(self):
        r'public_method_1 docstring'
        pass

    def public_method_2(self):
        r'public_method_2 docstring'
        pass

In my main rst file, I set up autosummary as follows:

.. autosummary::
    :toctree: my_module_members

    my_module.MyClassA
    my_module.MyClassB

As expected, autosummary creates a subdirectory named /my_module_members with individual rst files for each member of the module. But only __init__ is listed in the Methods section of these automatically generated rst files. E.g.:

my_module.MyClassA
==================

.. currentmodule:: my_module

.. autoclass:: MyClassA

   .. rubric:: Methods

   .. autosummary::

      ~MyClassA.__init__
      ~MyClassA.public_method_1
      ~MyClassA.public_method_2

Thus, in the html documentation generated, only those three methods are listed in the methods table, and __call__ and __len__ are not there:

So my question is how to include all special methods when using autosummary in this way?

Body:
The issue is with the default template that autosummary uses for classes.  This is the relevant page in the documentation, but it's more helpful to look at the default template directly:

# In the sphinx v3.0.4 source code:
# sphinx/ext/autosummary/templates/autosummary/class.rst
{{ fullname | escape | underline}}

.. currentmodule:: {{ module }}

.. autoclass:: {{ objname }}

   {% block methods %}
   .. automethod:: __init__

   {% if methods %}
   .. rubric:: Methods

   .. autosummary::
   {% for item in methods %}
      ~{{ name }}.{{ item }}
   {%- endfor %}
   {% endif %}
   {% endblock %}

   {% block attributes %}
   {% if attributes %}
   .. rubric:: Attributes

   .. autosummary::
   {% for item in attributes %}
      ~{{ name }}.{{ item }}
   {%- endfor %}
   {% endif %}
   {% endblock %}

You can see how this template corresponds to the stub files that were generated for your project (although I'm not sure why yours is missing the .. automethod:: __init__ line; maybe we have different versions of sphinx).  The important part is the {% for item in methods %} loop.  The docs linked above briefly mention that methods only include "public" methods, which means methods that don't begin with an underscore.  __init__() is also considered public, as per line 242 of sphinx/ext/autosummary/generate.py, although this doesn't seem to be documented anywhere.  So hopefully that explains the behavior you're seeing.

With that in mind, I can think of three ways to include all of the special methods in the documentation:

Provide a custom template that uses members instead of methods.  This should document everything, but will eliminate the distinction between methods, attributes, inherited members, inner classes, etc.

This isn't documented and I haven't tried it, it looks like you might be able to replace methods with all_methods to include all methods in the autosummary (see line 242 again).  There won't be any distinction between public and private methods, though.

Try using autoclasstoc.  Full disclosure: this is a package I wrote to do a better job of summarizing class methods in sphinx docs.  It's much more configurable than autosummary, and it includes every method by default.  It also collapses inherited methods, which can be really nice for big classes, although that may or may not be relevant to you.

This page describes how to use autoclasstoc in conjunction with autosummary, but the gist of it is that you need a custom template that looks something like this:

{{ fullname | escape | underline}}

.. currentmodule:: {{ module }}

.. autoclass:: {{ objname }}
   :members:
   :special-members:

    .. autoclasstoc::


问:
How to get roles in an azure ad multi-tenant dotnet web app?
I've set up a multi-tenant authentication web app that goes through the /common issuer using openid. I am able to sign in from the different tenants. However, the user roles claims are not being sent in the id token when authenticating this way.

I've used
https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-convert-app-to-be-multi-tenant and https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps as the primary references to complete this, but after attempting to follow all the steps, the roles still do not show up.

If I switch the application to use single tenant, and use the tenant specific issuer, the roles do show up in the claim token as I'd expect, so I don't believe it is a configuration problem when setting up the roles. How do I get the roles to show up when using /common or is there a different approach needed entirely to access the roles when doing a multitenant application?

答:
i assume you set up the app roles in the manifest and assigned the user to one of the app roles you put in manifest? and tested with that user?
because it is supposed to work.
have a read here: pretty good write-up about it.
https://goodworkaround.com/2019/12/06/building-a-multi-tenant-azure-ad-application-with-roles/</p>


问:
Is there a way to use a selenium webdriver without showing the browser?
I tried searching for a solution on this site because there is a question that is almost the same as mine. This sadly this didn't work for me. The code below is what I have right now... Is it possible to start the webdriver without actually showing the process?

```<code># Options
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')

# Gegevens
password = input("Please give us a password you want to use for all your account(s): ")

# Start de driver
url = 'https://twitter.com/?lang=en-gb'
driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver')
driver = webdriver.Chrome(chrome_options=options)
driver.set_window_size(1600, 800)
driver.get(url)
</code>```

Edit:
I fixed it by replacing with the code in the answer:

```<code>driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver')
driver = webdriver.Chrome(chrome_options=options)
</code>```

I still get an error:

```<code>C:/Users/ducov/PycharmProjects/bot/app.py:18: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver', chrome_options=options)
</code>```

But I don't think that matters

答:
You were close enough.

First of all, chrome_options is deprecated now and you have to use optionsinstead.

Implementation:

```<code>if chrome_options:
    warnings.warn('use options instead of chrome_options', DeprecationWarning)
    options = chrome_options
</code>```

Second, you want to initialize a single Chrome browsing context only, so you need to pass both the arguments within a single ChromeDriver / Chrome initializer as follows:

```<code># Options
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')

# Gegevens
password = input("Please give us a password you want to use for all your account(s): ")

# Start de driver
url = 'https://twitter.com/?lang=en-gb'
driver = webdriver.Chrome(executable_path='/Users/ducov/Downloads/chromedriver', options=chrome_options)
driver.set_window_size(1600, 800)
driver.get(url)
</code>```

Body:
I tried searching for a solution on this site because there is a question that is almost the same as mine. This sadly this didn't work for me. The code below is what I have right now... Is it possible to start the webdriver without actually showing the process?

# Options
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')

# Gegevens
password = input("Please give us a password you want to use for all your account(s): ")

# Start de driver
url = 'https://twitter.com/?lang=en-gb'
driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver')
driver = webdriver.Chrome(chrome_options=options)
driver.set_window_size(1600, 800)
driver.get(url)

Edit:
I fixed it by replacing with the code in the answer:

driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver')
driver = webdriver.Chrome(chrome_options=options)

I still get an error:

C:/Users/ducov/PycharmProjects/bot/app.py:18: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver', chrome_options=options)

But I don't think that matters

Body:
You were close enough.

First of all, chrome_options is deprecated now and you have to use optionsinstead.

Implementation:

if chrome_options:
    warnings.warn('use options instead of chrome_options', DeprecationWarning)
    options = chrome_options

Second, you want to initialize a single Chrome browsing context only, so you need to pass both the arguments within a single ChromeDriver / Chrome initializer as follows:

# Options
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')

# Gegevens
password = input("Please give us a password you want to use for all your account(s): ")

# Start de driver
url = 'https://twitter.com/?lang=en-gb'
driver = webdriver.Chrome(executable_path='/Users/ducov/Downloads/chromedriver', options=chrome_options)
driver.set_window_size(1600, 800)
driver.get(url)


问:
c# Azure Cannot set the blob tier
CloudBlockBlob doesn't have any method to set the blob tier to hot/cool/archive. I have also checked the other blob types and they do not have a method that allows this either.

I.E this method: https://learn.microsoft.com/en-us/rest/api/storageservices/set-blob-tier

Is their any way to change the blob tier in code from hot to cold in C# with azure storage?

答:
Using Azure Blob storage client library v12 for .NET, replace myaccount with the name of your storage account, mycontainer with your container name and myblob with the blob name for which the tier is to be changed:

```<code>var sharedKeyCredential = new StorageSharedKeyCredential("myaccount", storageAccountKey);
var baseBlobContainerUrl = string.Format("{0}.blob.core.windows.net", "myaccount");
var blobServiceClient = new BlobServiceClient(new Uri($"https://{baseBlobContainerUrl}"), sharedKeyCredential);
var containerClient = blobServiceClient.GetBlobContainerClient("mycontainer");
BlobClient blobClient = containerClient.GetBlobClient("myblob");
// Set access tier to cool.
await blobClient.SetAccessTierAsync(AccessTier.Cool);
</code>```

If you are working with Azure Gov, use this url insteadl "{0}.blob.core.usgovcloudapi.net"

Keep in mind, your storage account should support Cool Storage.

Title: c# Azure Cannot set the blob tier

Body:
Using Azure Blob storage client library v12 for .NET, replace myaccount with the name of your storage account, mycontainer with your container name and myblob with the blob name for which the tier is to be changed:

var sharedKeyCredential = new StorageSharedKeyCredential("myaccount", storageAccountKey);
var baseBlobContainerUrl = string.Format("{0}.blob.core.windows.net", "myaccount");
var blobServiceClient = new BlobServiceClient(new Uri($"https://{baseBlobContainerUrl}"), sharedKeyCredential);
var containerClient = blobServiceClient.GetBlobContainerClient("mycontainer");
BlobClient blobClient = containerClient.GetBlobClient("myblob");
// Set access tier to cool.
await blobClient.SetAccessTierAsync(AccessTier.Cool);

If you are working with Azure Gov, use this url insteadl "{0}.blob.core.usgovcloudapi.net"

Keep in mind, your storage account should support Cool Storage.


问:
LuisRecognizer Constructor is deprecated. Please use LuisRecognizerOptions
I am using a Microsoft bot builder SDKv4 for creating a Chat bot using LUIS.ai for getting the top intent.
I used the following code to configure luis in my .net core 2.1 project.

```<code>public BotServices(IConfiguration configuration)
    {
        // Read the setting for cognitive services from the appsettings.json
        Dispatch = new LuisRecognizer(new LuisApplication(
            configuration["LuisAppId"],
            configuration["LuisAPIKey"],
            $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com"),
            new LuisPredictionOptions { IncludeAllIntents = true, IncludeInstanceData = true },
            true);
    }
</code>```

But I am getting this warning : "LuisRecognizer,LuisRecognizer ... is obsolete: ... please use LuisRecognizer(LuisRecognizerOptions recognizer)".

I followed this Microsoft tutorial to set it up. Even following the tutorial also gives the same "obsolete" error at line:

```<code>Dispatch = new LuisRecognizer(luisApplication);
</code>```

https://learn.microsoft.com/en-us/azure/cognitive-services/luis/luis-csharp-tutorial-bf-v4

How can I configure luis in this case?

Thanks :)

答:
The tutorial appears to be out of date.  Please refer to the samples for the most up-to-date code.  https://github.com/microsoft/BotBuilder-Samples/blob/master/samples/csharp_dotnetcore/13.core-bot/FlightBookingRecognizer.cs#L27

```<code>var luisApplication = new LuisApplication(
    configuration["LuisAppId"],
    configuration["LuisAPIKey"],
    "https://" + configuration["LuisAPIHostName"]);

var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
{
    PredictionOptions = new Bot.Builder.AI.LuisV3.LuisPredictionOptions
    {
        IncludeInstanceData = true,
    }
};

Dispatch = new LuisRecognizer(recognizerOptions);
</code>```

With app setting:

```<code>"LuisAPIHostName": "westus.api.cognitive.microsoft.com"
</code>```

Body:
I am using a Microsoft bot builder SDKv4 for creating a Chat bot using LUIS.ai for getting the top intent.
I used the following code to configure luis in my .net core 2.1 project.

public BotServices(IConfiguration configuration)
    {
        // Read the setting for cognitive services from the appsettings.json
        Dispatch = new LuisRecognizer(new LuisApplication(
            configuration["LuisAppId"],
            configuration["LuisAPIKey"],
            $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com"),
            new LuisPredictionOptions { IncludeAllIntents = true, IncludeInstanceData = true },
            true);
    }

But I am getting this warning : "LuisRecognizer,LuisRecognizer ... is obsolete: ... please use LuisRecognizer(LuisRecognizerOptions recognizer)".

I followed this Microsoft tutorial to set it up. Even following the tutorial also gives the same "obsolete" error at line:

Dispatch = new LuisRecognizer(luisApplication);

https://learn.microsoft.com/en-us/azure/cognitive-services/luis/luis-csharp-tutorial-bf-v4

How can I configure luis in this case?

Thanks :)

Body:
The tutorial appears to be out of date.  Please refer to the samples for the most up-to-date code.  https://github.com/microsoft/BotBuilder-Samples/blob/master/samples/csharp_dotnetcore/13.core-bot/FlightBookingRecognizer.cs#L27

var luisApplication = new LuisApplication(
    configuration["LuisAppId"],
    configuration["LuisAPIKey"],
    "https://" + configuration["LuisAPIHostName"]);

var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
{
    PredictionOptions = new Bot.Builder.AI.LuisV3.LuisPredictionOptions
    {
        IncludeInstanceData = true,
    }
};

Dispatch = new LuisRecognizer(recognizerOptions);

With app setting:

"LuisAPIHostName": "westus.api.cognitive.microsoft.com"


问:
Select delete and insert at the same time PHP and SQL Server
What I want to do is first Select if the Cardindex Column has the values 0.1 and 2. with the same UserIndex (id) if those values exist (The 3 are mandatory), then we proceed to delete the 3 themselves and then Insert in the same table a new value. as long as the previous condition is met, if it is not met, it is not inserted.

In the query that I show the first query works well, it removes the data 0,1,2, until there everything is perfect, but then when inserting the new row it does it, but without respecting the previous condition. if in case it was not fulfilled it inserts it anyway.

It seems very easy but it has been impossible for me to continue moving forward,
Sorry for my bad English

Imagen Description

```<code>include('Login/Conexion.php');
$id = $_SESSION['id'];

$query = "with cte as (SELECT count(*) over() cnt FROM CardData where UserIndex = $id and CardIndex in (0, 1, 2)) delete from cte where cnt = 3";
$resultados = sqlsrv_query($conn,$query);

if($resultados){
    $insert = sqlsrv_query($conn,"INSERT INTO CardData (UserIndex, CardIndex, Mode ) VALUES ('$id', '5' ,'1')");
    }
    else{
        echo 'Error';
        }
</code>```

答:
sqlsrv_query() only returns FALSE if there was an error. Your logic is assuming that if the first query has no matches, $resultados will be false, but that's not correct.

You could try checking the number of affected rows instead:

```<code>$query = "with cte as (SELECT count(*) over() cnt FROM CardData where UserIndex = $id and CardIndex in (0, 1, 2)) delete from cte where cnt = 3";
$resultados = sqlsrv_query($conn,$query);

if( sqlsrv_num_fields($resultados) ) {
    $insert = sqlsrv_query($conn,"INSERT INTO CardData (UserIndex, CardIndex, Mode ) VALUES ('$id', '5' ,'1')");
    }
else {
   echo 'Error';
}
</code>```

Body:
What I want to do is first Select if the Cardindex Column has the values 0.1 and 2. with the same UserIndex (id) if those values exist (The 3 are mandatory), then we proceed to delete the 3 themselves and then Insert in the same table a new value. as long as the previous condition is met, if it is not met, it is not inserted.

In the query that I show the first query works well, it removes the data 0,1,2, until there everything is perfect, but then when inserting the new row it does it, but without respecting the previous condition. if in case it was not fulfilled it inserts it anyway.

It seems very easy but it has been impossible for me to continue moving forward,
Sorry for my bad English

Imagen Description

include('Login/Conexion.php');
$id = $_SESSION['id'];

$query = "with cte as (SELECT count(*) over() cnt FROM CardData where UserIndex = $id and CardIndex in (0, 1, 2)) delete from cte where cnt = 3";
$resultados = sqlsrv_query($conn,$query);

if($resultados){
    $insert = sqlsrv_query($conn,"INSERT INTO CardData (UserIndex, CardIndex, Mode ) VALUES ('$id', '5' ,'1')");
    }
    else{
        echo 'Error';
        }

Body:
sqlsrv_query() only returns FALSE if there was an error. Your logic is assuming that if the first query has no matches, $resultados will be false, but that's not correct.

You could try checking the number of affected rows instead:

$query = "with cte as (SELECT count(*) over() cnt FROM CardData where UserIndex = $id and CardIndex in (0, 1, 2)) delete from cte where cnt = 3";
$resultados = sqlsrv_query($conn,$query);

if( sqlsrv_num_fields($resultados) ) {
    $insert = sqlsrv_query($conn,"INSERT INTO CardData (UserIndex, CardIndex, Mode ) VALUES ('$id', '5' ,'1')");
    }
else {
   echo 'Error';
}


问:
Application.OpenForms[0].InvokeRequired equivalent in WPF
I need equivalent for Application.OpenForms[0].InvokeRequired in WinForms for wpf.I tried with

```<code>var dispatcher = myDispatcherObject.Dispatcher;
if (dispatcher.CheckAccess()) { /* ... */ }
</code>```

but no luck

答:
Try the following extension method:</p>

```<code>    public static void TryToExecuteOnUI(this Action uiAction)
    {
        var uiDispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
        if (uiDispatcher.CheckAccess() == false)
        {
            uiDispatcher.Invoke(uiAction);
            return;
        }

        uiAction();
    }
</code>```

Body:
I need equivalent for Application.OpenForms[0].InvokeRequired in WinForms for wpf.I tried with

var dispatcher = myDispatcherObject.Dispatcher;
if (dispatcher.CheckAccess()) { /* ... */ }

but no luck

Body:
Try the following extension method:

    public static void TryToExecuteOnUI(this Action uiAction)
    {
        var uiDispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
        if (uiDispatcher.CheckAccess() == false)
        {
            uiDispatcher.Invoke(uiAction);
            return;
        }

        uiAction();
    }


问:
Appstoreconnect Api user update
I can’t understand how to create the http body of the Modify User Account api:

PATCH
https://api.appstoreconnect.apple.com/v1/users/{id}

In particular the:

[UserUpdateRequest.Data.Relationships.VisibleApps.Data]

What are the required id and type properties of Data object? Could somebody provide a code or postman example of a request ?

This is the url of the topic:

Appstoreconnect Api - Update User

答:
The PATCH request should look like this:

```<code>PATCH /v1/users/XXX
{
  "data": {
    "type": "users",
    "id": "XXX",
    "attributes": {
      "allAppsVisible": false
    },
    "relationships": {
      "visibleApps": {
        "data": [
          {"type": "apps", "id": "AAA"},
          {"type": "apps", "id": "BBB"}
        ]
      }
    }
  }
}
</code>```

Where AAA and BBB are Apple IDs of your apps. You can find these on the App Information page, or in response to the /v1/apps API calls.

Title: Appstoreconnect Api user update

Body:
The PATCH request should look like this:

PATCH /v1/users/XXX
{
  "data": {
    "type": "users",
    "id": "XXX",
    "attributes": {
      "allAppsVisible": false
    },
    "relationships": {
      "visibleApps": {
        "data": [
          {"type": "apps", "id": "AAA"},
          {"type": "apps", "id": "BBB"}
        ]
      }
    }
  }
}

Where AAA and BBB are Apple IDs of your apps. You can find these on the App Information page, or in response to the /v1/apps API calls.


问:
Cannot read File from fs with FileReader
Hi i am trying to read a file and i am having trouble with the fileReader readAsArrayBuffer function in nodejs.

```<code>var FileReader = require("filereader");

let p12_path = __dirname + "/file.p12";

var p12xxx = fs.readFileSync(p12_path, "utf-8");

var reader = new FileReader();

reader.readAsArrayBuffer(p12xxx);//The problem is here
reader.onloadend = function() {
  arrayBuffer = reader.result;
  var arrayUint8 = new Uint8Array(arrayBuffer);
  var p12B64 = forge.util.binary.base64.encode(arrayUint8);
  var p12Der = forge.util.decode64(p12B64);
  var p12Asn1 = forge.asn1.fromDer(p12Der);

  ............
}
</code>```

-------The error

```<code>Error: cannot read as File: "0�6�\.............
</code>```

答: You are reading a PDF file which is not a text based format and should not have an encoding specified. As per the fs docs "If the encoding option is specified then this function returns a string" but because its mostly a binary file its reading invalid UTF8 characters. When you exclude the encoding it should give you a Buffer object instead which is what you most likely want.</p>

Body:
Hi i am trying to read a file and i am having trouble with the fileReader readAsArrayBuffer function in nodejs.

var FileReader = require("filereader");

let p12_path = __dirname + "/file.p12";

var p12xxx = fs.readFileSync(p12_path, "utf-8");

var reader = new FileReader();

reader.readAsArrayBuffer(p12xxx);//The problem is here
reader.onloadend = function() {
  arrayBuffer = reader.result;
  var arrayUint8 = new Uint8Array(arrayBuffer);
  var p12B64 = forge.util.binary.base64.encode(arrayUint8);
  var p12Der = forge.util.decode64(p12B64);
  var p12Asn1 = forge.asn1.fromDer(p12Der);

  ............
}

-------The error

Error: cannot read as File: "0�6�\.............


问:
SQL Developer File Open & Export very slow to display dialog box
In Oracle SQL Developer, all directory interaction takes 40 seconds to a minute:

File | Open takes over a minute to display the dialog box

Export from the results grid takes 40 seconds to display the dialog box, and then another 40 seconds in Export Wizard when clicking the Browse... button next to File:

File I/O speed is very fast, for example exporting the records, or saving query files.

This has been consistently now for several months, and all other applications are immediate to the same file locations.

Any help would be much appreciated.

答: Oracle is working on a fix for this, and hopes to have that included in release 20.2 by end of June 2020.</p>


问:
Plotnine's scale fill and axis position
I would like to move the x-axis to the top of my plot and manually fill the colors. However, the usual method in ggplot does not work in plotnine. When I provide the position='top' in my scale_x_continuous() I receive the warning: PlotnineWarning: scale_x_continuous could not recognize parameter 'position'. I understand position is not in plotnine's scale_x_continuous, but what is the replacement? Also, scale_fill_manual() results in an Invalid RGBA argument: 'color' error. Specifically, the value requires an array-like object. Thus I provided the array of colors, but still had an issue. How do I manually set the colors for a scale_fill object?

```<code>import pandas as pd
from plotnine import *
lst = [[1,1,'a'],[2,2,'a'],[3,3,'a'],[4,4,'b'],[5,5,'b']]
df = pd.DataFrame(lst, columns =['xx', 'yy','lbls'])

fill_clrs = {'a': 'goldenrod1',
 'b': 'darkslategray3'}
ggplot()+\
  geom_tile(aes(x='xx', y='yy', fill = 'lbls'), df) +\
  geom_text(aes(x='xx', y='yy', label='lbls'),df, color='white')+\
  scale_x_continuous(expand=(0,0), position = "top")+\
   scale_fill_manual(values = np.array(list(fill_clrs.values())))
</code>```

答:
Plotnine does not support changing the position of any axis.

You can pass a list or a dict of colour values to scale_fill_manual provided they are recognisable colour names. The colours you have are obscure and they are not recognised. To see that it works try 'red' and 'green', see https://matplotlib.org/gallery/color/named_colors.html for all the named colors. Otherwise, you can also use hex colors e.g. #ff00cc.

Title: Plotnine's scale fill and axis position

Body:
I would like to move the x-axis to the top of my plot and manually fill the colors. However, the usual method in ggplot does not work in plotnine. When I provide the position='top' in my scale_x_continuous() I receive the warning: PlotnineWarning: scale_x_continuous could not recognize parameter 'position'. I understand position is not in plotnine's scale_x_continuous, but what is the replacement? Also, scale_fill_manual() results in an Invalid RGBA argument: 'color' error. Specifically, the value requires an array-like object. Thus I provided the array of colors, but still had an issue. How do I manually set the colors for a scale_fill object?

import pandas as pd
from plotnine import *
lst = [[1,1,'a'],[2,2,'a'],[3,3,'a'],[4,4,'b'],[5,5,'b']]
df = pd.DataFrame(lst, columns =['xx', 'yy','lbls'])

fill_clrs = {'a': 'goldenrod1',
 'b': 'darkslategray3'}
ggplot()+\
  geom_tile(aes(x='xx', y='yy', fill = 'lbls'), df) +\
  geom_text(aes(x='xx', y='yy', label='lbls'),df, color='white')+\
  scale_x_continuous(expand=(0,0), position = "top")+\
   scale_fill_manual(values = np.array(list(fill_clrs.values())))