问:
'tuple' object has no attribute 'layer'
I am having many troubles trying to start training my model (a DCGAN). It is giving me the error:

```<code>'tuple' object has no attribute 'layer'
</code>```

I read that this could be due to having both the TensorFlow version 1.14.0 and the Keras version 2.2 or higher.
I tried to fix this by downgrading the Keras version to the 2.1.5, but I'm still having the same problem.

```<code>from google.colab import drive
drive.mount('/mntDrive')

import os,sys      #os es para gestionar directorios (trabajar con archivos); sys es para trabajar con variables del sistema

# numpy
import numpy as np

# data processing, CSV file I/O (e.g. pd.read_csv)
import pandas as pd
from sklearn.model_selection import train_test_split

# Charts
import matplotlib.pyplot as plt
from matplotlib.pyplot import imread
#process
from tqdm import tqdm

# Image IO
from PIL import Image
import skimage.io
import skimage.transform
from skimage.transform import resize

# Deep learning
import tensorflow as tf

from tensorflow.keras import layers
from keras import optimizers
from keras.models import Sequential, Model
from keras.layers.advanced_activations import LeakyReLU
from keras.layers import Dense, Conv2D, Flatten, MaxPool2D, Dropout, Input
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras import initializers

from __future__ import absolute_import, division, print_function, unicode_literals

# To make sure that we can reproduce the experiment and get the same results
np.random.seed(21)

# The dimension of our random noise vector.
random_dim = 100
from skimage.color import rgb2gray
import scipy.ndimage
import scipy.misc
import re
images = []
for root, dirnames, filenames in os.walk("/mntDrive/My Drive/Colab Notebooks/cubism"):
    for filename in filenames:
        if re.search("\.(jpg|jpeg|png)$", filename):
            filepath = os.path.join(root, filename)
            image = plt.imread(filepath, )
            image = (image.astype(np.float32) - 127.5)/127.5
            image_resized = resize(image, (112, 112))
            images.append(image_resized)
images = np.array(images)

print('Original image shape: {}'.format(images.shape))
im_gray = rgb2gray(images)
print('New image shape: {}'.format(im_gray.shape))
images_resized = im_gray.reshape(320,12544)

def get_optimizer():
  optimizer=tf.keras.optimizers.Adam(0.001)
  return optimizer

def make_generator_model(optimizer):
    generator = tf.keras.Sequential()
    generator.add(layers.Dense(7*7*256, use_bias=False, input_shape=(random_dim,)))
    generator.add(layers.BatchNormalization())
    generator.add(layers.LeakyReLU())

    generator.add(layers.Reshape((7, 7, 256)))
    assert generator.output_shape == (None, 7, 7, 256) # Note: None is the batch size

    generator.add(layers.Conv2DTranspose(128, (5, 5), strides=(2, 2), padding='same', use_bias=False))
    assert generator.output_shape == (None, 14, 14, 128)
    generator.add(layers.BatchNormalization())
    generator.add(layers.LeakyReLU())

    generator.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
    assert generator.output_shape == (None, 28, 28, 64)
    generator.add(layers.BatchNormalization())
    generator.add(layers.LeakyReLU())

    generator.add(layers.Conv2DTranspose(32, (5, 5), strides=(2, 2), padding='same', use_bias=False))
    assert generator.output_shape == (None, 56, 56, 32)
    generator.add(layers.BatchNormalization())
    generator.add(layers.LeakyReLU())

    generator.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
    assert generator.output_shape == (None, 112, 112, 1)
    generator.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001))

    return generator

def make_discriminator_model(optimizer):
    discriminator = tf.keras.Sequential()
    discriminator.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same', input_shape=[112, 112, 1]))
    discriminator.add(layers.LeakyReLU())
    discriminator.add(layers.Dropout(0.3))

    discriminator.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
    discriminator.add(layers.LeakyReLU())
    discriminator.add(layers.Dropout(0.3))

    discriminator.add(layers.Conv2D(256, (5, 5), strides=(2, 2), padding='same'))
    discriminator.add(layers.LeakyReLU())
    discriminator.add(layers.Dropout(0.3))

    discriminator.add(layers.Flatten())
    discriminator.add(layers.Dense(1, activation='sigmoid' ))
    discriminator.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001))

    return discriminator

def get_gan_network(discriminator, random_dim, generator, optimizer):
    # We initially set trainable to False since we only want to train either the
    # generator or discriminator at a time
    discriminator.trainable = False
    # gan input (noise) will be 100-dimensional vectors
    gan_input = Input(shape=(random_dim,))
    # the output of the generator (an image)
    x = generator(gan_input)
    # get the output of the discriminator (probability if the image is real or not)
    gan_output = discriminator(x)
    gan = Model(inputs=gan_input, outputs=gan_output)
    gan.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001))
    return gan

def plot_generated_images(epoch, generator, examples=64, dim=(10, 10), figsize=(100, 100)):
    noise = np.random.normal(0, 1, size=[examples, random_dim]) #mean, std deviation, size
    generated_images = generator.predict(noise)
    generated_images = generated_images.reshape(examples, 112, 112)

    plt.figure(figsize=figsize)
    for i in range(generated_images.shape[0]):
        plt.subplot(dim[0], dim[1], i+1)
        plt.imshow(generated_images[i], interpolation='nearest', cmap='gray_r')
        plt.axis('off')
    plt.tight_layout()
    plt.savefig('dcgan_generated_Originals_2_epoch_%d.png' % epoch)

#you can create a function which will save your generated images every 20 epochs
    # Create a wall of generated MNIST images
def train(epochs=15000, batch_size=80):
    # Get the training and testing data
    images_resized
    # Split the training data into batches of size 80
    batch_count = images_resized.shape[0] // batch_size

    # Build our GAN network
    optimizer=get_optimizer()
    generator = make_generator_model(optimizer)
    discriminator = make_discriminator_model(optimizer)
    gan = get_gan_network(discriminator, random_dim, generator, optimizer)

    for e in range(1, epochs+1):
        print ('-'*15, 'Epoch %d' % e, '-'*15)
        for _ in tqdm(range(batch_count)):
            # Get a random set of input noise and images
            noise = np.random.normal(0, 1, size=[batch_size, random_dim])
            image_batch = images_resized[np.random.randint(0, images_resized.shape[0], size=batch_size)]

            # Generate fake MNIST images
            generated_images = generator.predict(noise)
            X = np.concatenate([image_batch, generated_images])  #128x4096 --- 'a' x 4096

            # Labels for generated and real data
            y_dis = np.zeros(2*batch_size)
            y_dis[:batch_size] = 0.9    # One-sided label smoothing. Se refiere a que la mitad de y_dis seran 0.9 (reales) y la otra mitad seran 0 (falsos)

            # Train discriminator
            discriminator.trainable = True
            discriminator.train_on_batch(X, y_dis)      #Se entrena el Discriminador con dos vectores: X(tiene un batch(128) imagenes reales y un batch de imagenes generadas); y_dis(tiene un batch de 128 0.9(serian las reales) y otro batch de 128 ceros(serian las generadas). De esta manera, el algoritmo generador, aunque las genere bien, va a seguir optimizandose el numero de epochs que haga falta(seguimos en la fase de entrenamiento), ya que sus imagenes son continuamente rechazadas, comparandose con las reales y sacando continuamente diferencias. )
                                                        #Entra X(imagenes reales, imagenes generadas)--->y_dis(0.9 , 0)
                                                        #train_on_batch(x,y)---> realiza una actualizacion del gradiente en un batch----> x=array de training data (si el modelo tiene varias entradas pueden ser varios); y= array de target data (si el modelo tiene varias salidas pueden ser varios)

            # Train generator
            noise = np.random.normal(0, 1, size=[batch_size, random_dim])
            y_gen = np.ones(batch_size)
            discriminator.trainable = False
            gan.train_on_batch(noise, y_gen)            #Entra noise(pixeles desordenados)---->y_gen(todo son 1)

        if e == 1 or e % 50 == 0:
            plot_generated_images(e, generator)

if __name__ == '__main__':
   train(30000, 80)
</code>```

This is the output:

```<code>Drive already mounted at /mntDrive; to attempt to forcibly remount, call drive.mount("/mntDrive", force_remount=True).
Original image shape: (320, 112, 112, 3)
New image shape: (320, 112, 112)
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/nn_impl.py:180: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:68: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.

WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:507: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.

    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-18-6e3c9ece87ff> in <module>()
        196
        197 if __name__ == '__main__':
    --> 198    train(30000, 80)

    11 frames
    <ipython-input-18-6e3c9ece87ff> in train(epochs, batch_size)
        161     generator = make_generator_model(optimizer)
        162     discriminator = make_discriminator_model(optimizer)
    --> 163     gan = get_gan_network(discriminator, random_dim, generator, optimizer)
        164
        165     for e in range(1, epochs+1):

    <ipython-input-18-6e3c9ece87ff> in get_gan_network(discriminator, random_dim, generator, optimizer)
        128     gan_input = Input(shape=(random_dim,))
        129     # the output of the generator (an image)
    --> 130     x = generator(gan_input)
        131     # get the output of the discriminator (probability if the image is real or not)
        132     gan_output = discriminator(x)

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
        632                     outputs = base_layer_utils.mark_as_return(outputs, acd)
        633                 else:
    --> 634                   outputs = call_fn(inputs, *args, **kwargs)
        635
        636             except TypeError as e:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/sequential.py in call(self, inputs, training, mask)
        245       if not self.built:
        246         self._init_graph_network(self.inputs, self.outputs, name=self.name)
    --> 247       return super(Sequential, self).call(inputs, training=training, mask=mask)
        248
        249     outputs = inputs  # handle the corner case where self.layers is empty

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/network.py in call(self, inputs, training, mask)
        749                                 ' implement a `call` method.')
        750
    --> 751     return self._run_internal_graph(inputs, training=training, mask=mask)
        752
        753   def compute_output_shape(self, input_shape):

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/network.py in _run_internal_graph(self, inputs, training, mask)
        891
        892           # Compute outputs.
    --> 893           output_tensors = layer(computed_tensors, **kwargs)
        894
        895           # Update tensor_dict.

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
        661               kwargs.pop('training')
        662             inputs, outputs = self._set_connectivity_metadata_(
    --> 663                 inputs, outputs, args, kwargs)
        664           self._handle_activity_regularization(inputs, outputs)
        665           self._set_mask_metadata(inputs, outputs, previous_mask)

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py in _set_connectivity_metadata_(self, inputs, outputs, args, kwargs)
       1706     kwargs.pop('mask', None)  # `mask` should not be serialized.
       1707     self._add_inbound_node(
    -> 1708         input_tensors=inputs, output_tensors=outputs, arguments=kwargs)
       1709     return inputs, outputs
       1710

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py in _add_inbound_node(self, input_tensors, output_tensors, arguments)
       1793     """
       1794     inbound_layers = nest.map_structure(lambda t: t._keras_history.layer,
    -> 1795                                         input_tensors)
       1796     node_indices = nest.map_structure(lambda t: t._keras_history.node_index,
       1797                                       input_tensors)

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/nest.py in map_structure(func, *structure, **kwargs)
        513
        514   return pack_sequence_as(
    --> 515       structure[0], [func(*x) for x in entries],
        516       expand_composites=expand_composites)
        517

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/nest.py in <listcomp>(.0)
        513
        514   return pack_sequence_as(
    --> 515       structure[0], [func(*x) for x in entries],
        516       expand_composites=expand_composites)
        517

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py in <lambda>(t)
       1792             `call` method of the layer at the call that created the node.
       1793     """
    -> 1794     inbound_layers = nest.map_structure(lambda t: t._keras_history.layer,
       1795                                         input_tensors)
       1796     node_indices = nest.map_structure(lambda t: t._keras_history.node_index,
    AttributeError: 'tuple' object has no attribute 'layer'
    AttributeError: 'tuple' object has no attribute 'layer'
</code>```

答: I solved the problem. I guess it was caused by the inconsistency between keras and tensorflow. When I switch the version of keras from 2.3.1 to 2.4.3 and the version of tensorflow from 2.2 to 2.3.0, this problem will not occur.</p>

Title: 'tuple' object has no attribute 'layer'

Body:
I am having many troubles trying to start training my model (a DCGAN). It is giving me the error:

'tuple' object has no attribute 'layer'

I read that this could be due to having both the TensorFlow version 1.14.0 and the Keras version 2.2 or higher.
I tried to fix this by downgrading the Keras version to the 2.1.5, but I'm still having the same problem.

from google.colab import drive
drive.mount('/mntDrive')

import os,sys      #os es para gestionar directorios (trabajar con archivos); sys es para trabajar con variables del sistema

# numpy
import numpy as np

# data processing, CSV file I/O (e.g. pd.read_csv)
import pandas as pd
from sklearn.model_selection import train_test_split

# Charts
import matplotlib.pyplot as plt
from matplotlib.pyplot import imread
#process
from tqdm import tqdm

# Image IO
from PIL import Image
import skimage.io
import skimage.transform
from skimage.transform import resize

# Deep learning
import tensorflow as tf

from tensorflow.keras import layers
from keras import optimizers
from keras.models import Sequential, Model
from keras.layers.advanced_activations import LeakyReLU
from keras.layers import Dense, Conv2D, Flatten, MaxPool2D, Dropout, Input
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras import initializers

from __future__ import absolute_import, division, print_function, unicode_literals

# To make sure that we can reproduce the experiment and get the same results
np.random.seed(21)

# The dimension of our random noise vector.
random_dim = 100
from skimage.color import rgb2gray
import scipy.ndimage
import scipy.misc
import re
images = []
for root, dirnames, filenames in os.walk("/mntDrive/My Drive/Colab Notebooks/cubism"):
    for filename in filenames:
        if re.search("\.(jpg|jpeg|png)$", filename):
            filepath = os.path.join(root, filename)
            image = plt.imread(filepath, )
            image = (image.astype(np.float32) - 127.5)/127.5
            image_resized = resize(image, (112, 112))
            images.append(image_resized)
images = np.array(images)

print('Original image shape: {}'.format(images.shape))
im_gray = rgb2gray(images)
print('New image shape: {}'.format(im_gray.shape))
images_resized = im_gray.reshape(320,12544)

def get_optimizer():
  optimizer=tf.keras.optimizers.Adam(0.001)
  return optimizer

def make_generator_model(optimizer):
    generator = tf.keras.Sequential()
    generator.add(layers.Dense(7*7*256, use_bias=False, input_shape=(random_dim,)))
    generator.add(layers.BatchNormalization())
    generator.add(layers.LeakyReLU())

    generator.add(layers.Reshape((7, 7, 256)))
    assert generator.output_shape == (None, 7, 7, 256) # Note: None is the batch size

    generator.add(layers.Conv2DTranspose(128, (5, 5), strides=(2, 2), padding='same', use_bias=False))
    assert generator.output_shape == (None, 14, 14, 128)
    generator.add(layers.BatchNormalization())
    generator.add(layers.LeakyReLU())

    generator.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
    assert generator.output_shape == (None, 28, 28, 64)
    generator.add(layers.BatchNormalization())
    generator.add(layers.LeakyReLU())

    generator.add(layers.Conv2DTranspose(32, (5, 5), strides=(2, 2), padding='same', use_bias=False))
    assert generator.output_shape == (None, 56, 56, 32)
    generator.add(layers.BatchNormalization())
    generator.add(layers.LeakyReLU())

    generator.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
    assert generator.output_shape == (None, 112, 112, 1)
    generator.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001))

    return generator

def make_discriminator_model(optimizer):
    discriminator = tf.keras.Sequential()
    discriminator.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same', input_shape=[112, 112, 1]))
    discriminator.add(layers.LeakyReLU())
    discriminator.add(layers.Dropout(0.3))

    discriminator.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
    discriminator.add(layers.LeakyReLU())
    discriminator.add(layers.Dropout(0.3))

    discriminator.add(layers.Conv2D(256, (5, 5), strides=(2, 2), padding='same'))
    discriminator.add(layers.LeakyReLU())
    discriminator.add(layers.Dropout(0.3))

    discriminator.add(layers.Flatten())
    discriminator.add(layers.Dense(1, activation='sigmoid' ))
    discriminator.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001))

    return discriminator

def get_gan_network(discriminator, random_dim, generator, optimizer):
    # We initially set trainable to False since we only want to train either the
    # generator or discriminator at a time
    discriminator.trainable = False
    # gan input (noise) will be 100-dimensional vectors
    gan_input = Input(shape=(random_dim,))
    # the output of the generator (an image)
    x = generator(gan_input)
    # get the output of the discriminator (probability if the image is real or not)
    gan_output = discriminator(x)
    gan = Model(inputs=gan_input, outputs=gan_output)
    gan.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001))
    return gan

def plot_generated_images(epoch, generator, examples=64, dim=(10, 10), figsize=(100, 100)):
    noise = np.random.normal(0, 1, size=[examples, random_dim]) #mean, std deviation, size
    generated_images = generator.predict(noise)
    generated_images = generated_images.reshape(examples, 112, 112)

    plt.figure(figsize=figsize)
    for i in range(generated_images.shape[0]):
        plt.subplot(dim[0], dim[1], i+1)
        plt.imshow(generated_images[i], interpolation='nearest', cmap='gray_r')
        plt.axis('off')
    plt.tight_layout()
    plt.savefig('dcgan_generated_Originals_2_epoch_%d.png' % epoch)

#you can create a function which will save your generated images every 20 epochs
    # Create a wall of generated MNIST images
def train(epochs=15000, batch_size=80):
    # Get the training and testing data
    images_resized
    # Split the training data into batches of size 80
    batch_count = images_resized.shape[0] // batch_size

    # Build our GAN network
    optimizer=get_optimizer()
    generator = make_generator_model(optimizer)
    discriminator = make_discriminator_model(optimizer)
    gan = get_gan_network(discriminator, random_dim, generator, optimizer)

    for e in range(1, epochs+1):
        print ('-'*15, 'Epoch %d' % e, '-'*15)
        for _ in tqdm(range(batch_count)):
            # Get a random set of input noise and images
            noise = np.random.normal(0, 1, size=[batch_size, random_dim])
            image_batch = images_resized[np.random.randint(0, images_resized.shape[0], size=batch_size)]

            # Generate fake MNIST images
            generated_images = generator.predict(noise)
            X = np.concatenate([image_batch, generated_images])  #128x4096 --- 'a' x 4096

            # Labels for generated and real data
            y_dis = np.zeros(2*batch_size)
            y_dis[:batch_size] = 0.9    # One-sided label smoothing. Se refiere a que la mitad de y_dis seran 0.9 (reales) y la otra mitad seran 0 (falsos)

            # Train discriminator
            discriminator.trainable = True
            discriminator.train_on_batch(X, y_dis)      #Se entrena el Discriminador con dos vectores: X(tiene un batch(128) imagenes reales y un batch de imagenes generadas); y_dis(tiene un batch de 128 0.9(serian las reales) y otro batch de 128 ceros(serian las generadas). De esta manera, el algoritmo generador, aunque las genere bien, va a seguir optimizandose el numero de epochs que haga falta(seguimos en la fase de entrenamiento), ya que sus imagenes son continuamente rechazadas, comparandose con las reales y sacando continuamente diferencias. )
                                                        #Entra X(imagenes reales, imagenes generadas)--->y_dis(0.9 , 0)
                                                        #train_on_batch(x,y)---> realiza una actualizacion del gradiente en un batch----> x=array de training data (si el modelo tiene varias entradas pueden ser varios); y= array de target data (si el modelo tiene varias salidas pueden ser varios)

            # Train generator
            noise = np.random.normal(0, 1, size=[batch_size, random_dim])
            y_gen = np.ones(batch_size)
            discriminator.trainable = False
            gan.train_on_batch(noise, y_gen)            #Entra noise(pixeles desordenados)---->y_gen(todo son 1)

        if e == 1 or e % 50 == 0:
            plot_generated_images(e, generator)

if __name__ == '__main__':
   train(30000, 80)

This is the output:

Drive already mounted at /mntDrive; to attempt to forcibly remount, call drive.mount("/mntDrive", force_remount=True).
Original image shape: (320, 112, 112, 3)
New image shape: (320, 112, 112)
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/nn_impl.py:180: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:68: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.

WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:507: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.

    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-18-6e3c9ece87ff> in <module>()
        196
        197 if __name__ == '__main__':
    --> 198    train(30000, 80)

    11 frames
    <ipython-input-18-6e3c9ece87ff> in train(epochs, batch_size)
        161     generator = make_generator_model(optimizer)
        162     discriminator = make_discriminator_model(optimizer)
    --> 163     gan = get_gan_network(discriminator, random_dim, generator, optimizer)
        164
        165     for e in range(1, epochs+1):

    <ipython-input-18-6e3c9ece87ff> in get_gan_network(discriminator, random_dim, generator, optimizer)
        128     gan_input = Input(shape=(random_dim,))
        129     # the output of the generator (an image)
    --> 130     x = generator(gan_input)
        131     # get the output of the discriminator (probability if the image is real or not)
        132     gan_output = discriminator(x)

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
        632                     outputs = base_layer_utils.mark_as_return(outputs, acd)
        633                 else:
    --> 634                   outputs = call_fn(inputs, *args, **kwargs)
        635
        636             except TypeError as e:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/sequential.py in call(self, inputs, training, mask)
        245       if not self.built:
        246         self._init_graph_network(self.inputs, self.outputs, name=self.name)
    --> 247       return super(Sequential, self).call(inputs, training=training, mask=mask)
        248
        249     outputs = inputs  # handle the corner case where self.layers is empty

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/network.py in call(self, inputs, training, mask)
        749                                 ' implement a `call` method.')
        750
    --> 751     return self._run_internal_graph(inputs, training=training, mask=mask)
        752
        753   def compute_output_shape(self, input_shape):

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/network.py in _run_internal_graph(self, inputs, training, mask)
        891
        892           # Compute outputs.
    --> 893           output_tensors = layer(computed_tensors, **kwargs)
        894
        895           # Update tensor_dict.

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
        661               kwargs.pop('training')
        662             inputs, outputs = self._set_connectivity_metadata_(
    --> 663                 inputs, outputs, args, kwargs)
        664           self._handle_activity_regularization(inputs, outputs)
        665           self._set_mask_metadata(inputs, outputs, previous_mask)

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py in _set_connectivity_metadata_(self, inputs, outputs, args, kwargs)
       1706     kwargs.pop('mask', None)  # `mask` should not be serialized.
       1707     self._add_inbound_node(
    -> 1708         input_tensors=inputs, output_tensors=outputs, arguments=kwargs)
       1709     return inputs, outputs
       1710

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py in _add_inbound_node(self, input_tensors, output_tensors, arguments)
       1793     """
       1794     inbound_layers = nest.map_structure(lambda t: t._keras_history.layer,
    -> 1795                                         input_tensors)
       1796     node_indices = nest.map_structure(lambda t: t._keras_history.node_index,
       1797                                       input_tensors)

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/nest.py in map_structure(func, *structure, **kwargs)
        513
        514   return pack_sequence_as(
    --> 515       structure[0], [func(*x) for x in entries],
        516       expand_composites=expand_composites)
        517

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/nest.py in <listcomp>(.0)
        513
        514   return pack_sequence_as(
    --> 515       structure[0], [func(*x) for x in entries],
        516       expand_composites=expand_composites)
        517

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py in <lambda>(t)
       1792             `call` method of the layer at the call that created the node.
       1793     """
    -> 1794     inbound_layers = nest.map_structure(lambda t: t._keras_history.layer,
       1795                                         input_tensors)
       1796     node_indices = nest.map_structure(lambda t: t._keras_history.node_index,
    AttributeError: 'tuple' object has no attribute 'layer'
    AttributeError: 'tuple' object has no attribute 'layer'


来源: stackexchange

问:
Filtering causes both lists to delete their Items - Android RecyclerView Filtering Java
So what i want to do is simply filter all of my entries according to a searchString. This works fine but for some reason everytime i filter both lists delete the items. i will only include the (i think) important parts of code here.

Adapter.java:

```<code>@Override
    public Filter getFilter() {
        return myFilter;
    }

    private Filter myFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<Stellplatz> filteredList = new ArrayList<>();
            Log.d("TEst","Size stellplaetzeall:"+ stellplaetzeall.size());

            Log.d("TEst","Size Stellplaeztze:"+ stellplaetze.size());

            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(stellplaetzeall);
            } else {
                String filterPattern = constraint.toString().toLowerCase().trim();
                for (Stellplatz item : stellplaetzeall) {
                    if (item.getAnbieter().toLowerCase().contains(filterPattern)) {
                        filteredList.add(item);
                    }
                }
            }
            FilterResults results = new FilterResults();
            results.values = filteredList;
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            stellplaetze.clear();
            stellplaetze.addAll((ArrayList) results.values);
            notifyDataSetChanged();
        }
    };
</code>```

Fragment.java

```<code>@Override
     public void onCreateOptionsMenu(Menu menu, @NonNull MenuInflater inflater){
        inflater.inflate(R.menu.menu_itemlist, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });
     }
</code>```

I cant see why this would happen. Every example i found is basically the same as my code but for some reason it happens. i would really appreciate any answer that helps me understand this. also im not very good at android programming, first time doing this so an explanation why would be really helpful!

答:
On publish Result you are clearing the List, i think that is wrong:

```<code> @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        //stellplaetze.clear();
        stellplaetze.addAll((ArrayList) results.values);
        notifyDataSetChanged();
    }
</code>```

I have an example of my code i think this will help:

First i create 2 list:

```<code>private ArrayList<CountryPhone> objects;
private ArrayList<CountryPhone> filteredData;

 @Override
public int getCount() {
    return filteredData.size();
}

@Nullable
@Override
public CountryPhone getItem(int position) {
    return filteredData.get(position);
}
</code>```

On Filter Results:

```<code>    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();
        FilterResults filterResults = new FilterResults();
        ArrayList<CountryPhone> filterlist = new ArrayList<>();

            String name, code;
            for (int i = 0; i < objects.size(); i++) {
                CountryPhone item = objects.get(i);
                name = item.getName().toLowerCase();

                code = item.getCode();

                if (name.contains(filterString) || code.contains(filterString)){
                    filterlist.add(item);
                }
            }

            filterResults.values = filterlist;
            filterResults.count = filterlist.size();

        return filterResults;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<CountryPhone>) results.values;

            notifyDataSetChanged();

    }

};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So what i want to do is simply filter all of my entries according to a searchString. This works fine but for some reason everytime i filter both lists delete the items. i will only include the (i think) important parts of code here.

Adapter.java:

@Override
    public Filter getFilter() {
        return myFilter;
    }

    private Filter myFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<Stellplatz> filteredList = new ArrayList<>();
            Log.d("TEst","Size stellplaetzeall:"+ stellplaetzeall.size());

            Log.d("TEst","Size Stellplaeztze:"+ stellplaetze.size());

            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(stellplaetzeall);
            } else {
                String filterPattern = constraint.toString().toLowerCase().trim();
                for (Stellplatz item : stellplaetzeall) {
                    if (item.getAnbieter().toLowerCase().contains(filterPattern)) {
                        filteredList.add(item);
                    }
                }
            }
            FilterResults results = new FilterResults();
            results.values = filteredList;
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            stellplaetze.clear();
            stellplaetze.addAll((ArrayList) results.values);
            notifyDataSetChanged();
        }
    };

Fragment.java

@Override
     public void onCreateOptionsMenu(Menu menu, @NonNull MenuInflater inflater){
        inflater.inflate(R.menu.menu_itemlist, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });
     }

I cant see why this would happen. Every example i found is basically the same as my code but for some reason it happens. i would really appreciate any answer that helps me understand this. also im not very good at android programming, first time doing this so an explanation why would be really helpful!

Body:
On publish Result you are clearing the List, i think that is wrong:

 @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        //stellplaetze.clear();
        stellplaetze.addAll((ArrayList) results.values);
        notifyDataSetChanged();
    }

I have an example of my code i think this will help:

First i create 2 list:

private ArrayList<CountryPhone> objects;
private ArrayList<CountryPhone> filteredData;

 @Override
public int getCount() {
    return filteredData.size();
}

@Nullable
@Override
public CountryPhone getItem(int position) {
    return filteredData.get(position);
}

On Filter Results:

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String filterString = constraint.toString().toLowerCase();
        FilterResults filterResults = new FilterResults();
        ArrayList<CountryPhone> filterlist = new ArrayList<>();

            String name, code;
            for (int i = 0; i < objects.size(); i++) {
                CountryPhone item = objects.get(i);
                name = item.getName().toLowerCase();

                code = item.getCode();

                if (name.contains(filterString) || code.contains(filterString)){
                    filterlist.add(item);
                }
            }

            filterResults.values = filterlist;
            filterResults.count = filterlist.size();

        return filterResults;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<CountryPhone>) results.values;

            notifyDataSetChanged();

    }

};


问:
Python variable with multilines
I'm pretty new to Python and I'm trying to do the following thing:
I made this code, which works fine:

```<code>import csv
import os

#Création fichiers BD
with open('data.csv') as datas:
    reader = csv.reader(datas, delimiter=';')
    for row in reader:
        vlanid = row[0]
        vlanname = row[1]

        config = '''\
        resource "aci_bridge_domain" "vlan_%s_bd" {
          name               = "VLAN-%s-BD"
          tenant_dn          = aci_tenant.l2transit.id
          name_alias         = "%s"
          arp_flood          = "yes"
          relation_fv_rs_ctx = aci_vrf.l2transit.id
        }

        ''' % (vlanid, vlanid, vlanname)

        file_name = 'vlan-%s-bd.tf'% (vlanid)
        file_path = 'C:\iac\script_aci\\bd'
        file_complete = os.path.join(file_path, file_name)

        with open(file_complete, 'w') as f:
           f.writelines(config)
</code>```

Only thing that bother me is how variable shown in the "config" block.
Using the %s method works fine, but lets say that this block had like 100 variables in it, it would be a nightmare to understand which variable is what.

My goal here is to have the variables names in the block directly instead of the "%s"

Could you guys help a newbie in the need?

Thanks!

答:
Yes, f-strings would be an improvement.

You can use multi-line f-strings.

Title: Python variable with multilines

Body:
I'm pretty new to Python and I'm trying to do the following thing:
I made this code, which works fine:

import csv
import os

#Création fichiers BD
with open('data.csv') as datas:
    reader = csv.reader(datas, delimiter=';')
    for row in reader:
        vlanid = row[0]
        vlanname = row[1]

        config = '''\
        resource "aci_bridge_domain" "vlan_%s_bd" {
          name               = "VLAN-%s-BD"
          tenant_dn          = aci_tenant.l2transit.id
          name_alias         = "%s"
          arp_flood          = "yes"
          relation_fv_rs_ctx = aci_vrf.l2transit.id
        }

        ''' % (vlanid, vlanid, vlanname)

        file_name = 'vlan-%s-bd.tf'% (vlanid)
        file_path = 'C:\iac\script_aci\\bd'
        file_complete = os.path.join(file_path, file_name)

        with open(file_complete, 'w') as f:
           f.writelines(config)

Only thing that bother me is how variable shown in the "config" block.
Using the %s method works fine, but lets say that this block had like 100 variables in it, it would be a nightmare to understand which variable is what.

My goal here is to have the variables names in the block directly instead of the "%s"

Could you guys help a newbie in the need?

Thanks!


问:
How to check if PDF is scanned image or contains text in R
I am conducting a structural equation model on several PDF's (>1000) in R.

However, some PDF's are readable and other are scanned, i.e. I need to run them through an OCR-function.

Therefore, I need to find a way to automatically identify which PDF's contains text and which don't. Specifically, I wish to get find a way to return whether a given PDF should be ran through OCR.

Does anyone know of any functions or packages in R that might help do this - I can find a couple of solutions for Python, but haven't been able to identify some in R.

答:
You could use an approach like this (as @danlooo already suggested but I wanted to spell it out):

files <- list.files("/home/johannes/pdfs/",
                    pattern = ".pdf$",
                    full.names = TRUE)

pdfs_l <- lapply(files, function(f) {
  out <- pdftools::pdf_text(f)
  # I set the test to an arbitrary number of characters, it works for me but you want
  # to maybe fine tune it a bit
  contains_text <- nchar(out) > 15
  if (!contains_text) {
    out <- pdftools::pdf_ocr_text(f)
  }
  data.frame(text = out, ocr = !contains_text)
})

pdfs_l |>
  dplyr::bind_rows() |>
  dplyr::mutate(text = trimws(text)) |>
  tibble::as_tibble()
#> # A tibble: 22 × 2
#>    text                                                                    ocr
#>    <chr>                                                                   <lgl>
#>  1 "TEAM MEMBERS:\n                                                      … FALSE
#>  2 "WS 21/22                                                             … FALSE
#>  3 "WS 21/22                                                             … FALSE
#>  4 "TEAM MEMBERS:\n                                                      … FALSE
#>  5 "TEAM MEMBERS:\n                                                      … FALSE
#>  6 "Key Concepts in Political Communication\n    @Agenda Setting, Priming… FALSE
#>  7 "Key Concepts in Political Communication\n    @Agenda Setting, Priming… FALSE
#>  8 "ELECTIONS AND CAMPAIGNS\n                                            … FALSE
#>  9 ""                                                                      TRUE
#> 10 ""                                                                      TRUE
#> # … with 12 more rows
```

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

Body:
You could use an approach like this (as @danlooo already suggested but I wanted to spell it out):

files <- list.files("/home/johannes/pdfs/",
                    pattern = ".pdf$",
                    full.names = TRUE)

pdfs_l <- lapply(files, function(f) {
  out <- pdftools::pdf_text(f)
  # I set the test to an arbitrary number of characters, it works for me but you want
  # to maybe fine tune it a bit
  contains_text <- nchar(out) > 15
  if (!contains_text) {
    out <- pdftools::pdf_ocr_text(f)
  }
  data.frame(text = out, ocr = !contains_text)
})

pdfs_l |>
  dplyr::bind_rows() |>
  dplyr::mutate(text = trimws(text)) |>
  tibble::as_tibble()
#> # A tibble: 22 × 2
#>    text                                                                    ocr
#>    <chr>                                                                   <lgl>
#>  1 "TEAM MEMBERS:\n                                                      … FALSE
#>  2 "WS 21/22                                                             … FALSE
#>  3 "WS 21/22                                                             … FALSE
#>  4 "TEAM MEMBERS:\n                                                      … FALSE
#>  5 "TEAM MEMBERS:\n                                                      … FALSE
#>  6 "Key Concepts in Political Communication\n    @Agenda Setting, Priming… FALSE
#>  7 "Key Concepts in Political Communication\n    @Agenda Setting, Priming… FALSE
#>  8 "ELECTIONS AND CAMPAIGNS\n                                            … FALSE
#>  9 ""                                                                      TRUE
#> 10 ""                                                                      TRUE
#> # … with 12 more rows

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


问:
Join Azure AD thru PowerShell script
Is it possible remotely join multiple workstations to Azure AD thru PowerShell script? I'm trying to find it but unable to find any documentation about Azure AD join thru PowerShell scripts.

Also, if we join a workstation using an Azure AD Global Administrator, will it be registered as the owner of the device? Should we have the user join their workstations to the Azure AD?

Hope you guys can help. Thank you so much in advance!

答:
•   No, currently there is no such provision of joining multiple devices to Azure AD through a powershell script. Also, remember and consider that the user ID that is used to join the device to Azure AD becomes the default owner of that Azure AD joined device. Thus, if you are using ‘Global Administrator’ ID to join devices to Azure AD, then it will become the Owner of those devices.

Therefore, to bulk join devices to Azure AD, you would need to create a Windows Provisioning package using the Windows configuration designer app and deploy it to all those devices. Please refer to the link below for more details: -

https://learn.microsoft.com/en-us/mem/intune/enrollment/windows-bulk-enroll

•   Also, to change ownership of the device to the user using it after joining Azure AD using the Global Administrator ID, you can use the below commands: -

```<code>$credential = Get-Credential
Connect-AzureAD -Credential $credential
Add-AzureADDeviceRegisteredOwner -ObjectId 9cfabe6a-xxxx-xxxx-xxxx-xxxxxxxxxxxx -RefObjectId 35b57bc1-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Remove-AzureADDeviceRegisteredOwner -ObjectId 9cfabe6a-xxxx-xxxx-xxxx-xxxxxxxxxxxx -OwnerId 2d2c5e37-xxxx-xxxx-xxxx-xxxxxxxxxxxx ‘
</code>```

Please refer to this link below for more details: -

https://blog.matrixpost.net/change-owner-for-azure-ad-joined-windows-10-devices/#:~:text=Search%20for%20and%20select%20Azure,on%20Azure%20AD%20joined%20devices.

•   Also, to allow users using Windows devices to self-join to Azure AD, please refer to the below Microsoft documentation link below: -

https://learn.microsoft.com/en-us/azure/active-directory/enterprise-users/directory-self-service-signup

According to the above link, the users who have their email address registered in the Azure AD domain can join their assigned devices to Azure AD.

Title: Join Azure AD thru PowerShell script

Body:
•   No, currently there is no such provision of joining multiple devices to Azure AD through a powershell script. Also, remember and consider that the user ID that is used to join the device to Azure AD becomes the default owner of that Azure AD joined device. Thus, if you are using ‘Global Administrator’ ID to join devices to Azure AD, then it will become the Owner of those devices.

Therefore, to bulk join devices to Azure AD, you would need to create a Windows Provisioning package using the Windows configuration designer app and deploy it to all those devices. Please refer to the link below for more details: -

https://learn.microsoft.com/en-us/mem/intune/enrollment/windows-bulk-enroll

•   Also, to change ownership of the device to the user using it after joining Azure AD using the Global Administrator ID, you can use the below commands: -

$credential = Get-Credential
Connect-AzureAD -Credential $credential
Add-AzureADDeviceRegisteredOwner -ObjectId 9cfabe6a-xxxx-xxxx-xxxx-xxxxxxxxxxxx -RefObjectId 35b57bc1-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Remove-AzureADDeviceRegisteredOwner -ObjectId 9cfabe6a-xxxx-xxxx-xxxx-xxxxxxxxxxxx -OwnerId 2d2c5e37-xxxx-xxxx-xxxx-xxxxxxxxxxxx ‘

Please refer to this link below for more details: -

https://blog.matrixpost.net/change-owner-for-azure-ad-joined-windows-10-devices/#:~:text=Search%20for%20and%20select%20Azure,on%20Azure%20AD%20joined%20devices.

•   Also, to allow users using Windows devices to self-join to Azure AD, please refer to the below Microsoft documentation link below: -

https://learn.microsoft.com/en-us/azure/active-directory/enterprise-users/directory-self-service-signup

According to the above link, the users who have their email address registered in the Azure AD domain can join their assigned devices to Azure AD.


问:
How to detect the object being double released with Xcode - message sent to deallocated instance?
I am relatively new to Xcode4 and I would like to know how can I identify a double release with it.

In the debugger I see a line like *** -[NSConcreteMutableData release]: message sent to deallocated instance 0x60b63fe0.

The problem is that knowing the address doesn't help a lot identifying the object and also the object type doesn't help too much identifying it.

I read http://www.friday.com/bbum/2010/01/10/using-malloc-to-debug-memory-misuse-in-cocoa/ but I did not found this to be too successful.

答: You can replace the release method using categories for testing purposes, this is not designed to work like that as part of the language but in the past I have found success it trying to do  some testing, usually all you find out is that an autorelease pool is releasing you object.</p>

ContentLicense: CC BY-SA 3.0


问:
No Such Element ERROR while trying to extract the table from a website
i am trying to extract the table from the website https://www.bseindia.com/corporates/Sharehold_Searchnew.aspx?expandable=3

```<code>shell('docker pull selenium/standalone-chrome')
Sys.sleep(2)
shell('docker run -d -p 4445:4444 selenium/standalone-chrome')
Sys.sleep(2)
remDr <- remoteDriver(remoteServerAddr = "localhost" , port = 4445L, browserName = "chrome")
Sys.sleep(3)
remDr$open()
remDr$setTimeout(type = "script", milliseconds = 30000000000)
remDr$navigate("https://www.bseindia.com/corporates/Sharehold_Searchnew.aspx?expandable=3")
webelemtemp<-remDr$findElement(using = "xpath", value = "//*[@id='ContentPlaceHolder1_gvData']/tbody/tr[27]/td/table/tbody")
count<-1
</code>```

Getting an error
Error:   Summary: NoSuchElement
Detail: An element could not be located on the page using the given search parameters.
class: org.openqa.selenium.NoSuchElementException
Further Details: run errorDetails method

答:
To extract the table we can use,

```<code>library(dplyr)
library(rvest)

remDr$navigate("https://www.bseindia.com/corporates/Sharehold_Searchnew.aspx?expandable=3")

remDr$getPageSource()[[1]] %>%
  read_html() %>% html_nodes('.mGrid') %>%
  html_table()
[[1]]
# A tibble: 4 x 5
  `Security Code` `Security Name`         Industry                     `For Quarter Ending` XBRL
            <int> <chr>                   <chr>                        <chr>                <lgl>
1          509055 VISAKA INDUSTRIES LTD.  Cement & Cement Products     09 Feb 2022          NA
2          532687 REPRO INDIA LTD.        Comm.Printing/Stationery     December 2021        NA
3          538734 Ceinsys Tech Ltd        IT Consulting & Software     09 Feb 2022          NA
4          532695 CELEBRITY FASHIONS LTD. Other Apparels & Accessories 27 Jan 2022          NA
</code>```

But a faster approach would be using rvest

```<code>url %>%
  read_html() %>%
  html_nodes('.mGrid') %>%
  html_table()
</code>```

Body:
i am trying to extract the table from the website https://www.bseindia.com/corporates/Sharehold_Searchnew.aspx?expandable=3

shell('docker pull selenium/standalone-chrome')
Sys.sleep(2)
shell('docker run -d -p 4445:4444 selenium/standalone-chrome')
Sys.sleep(2)
remDr <- remoteDriver(remoteServerAddr = "localhost" , port = 4445L, browserName = "chrome")
Sys.sleep(3)
remDr$open()
remDr$setTimeout(type = "script", milliseconds = 30000000000)
remDr$navigate("https://www.bseindia.com/corporates/Sharehold_Searchnew.aspx?expandable=3")
webelemtemp<-remDr$findElement(using = "xpath", value = "//*[@id='ContentPlaceHolder1_gvData']/tbody/tr[27]/td/table/tbody")
count<-1

Getting an error
Error:   Summary: NoSuchElement
Detail: An element could not be located on the page using the given search parameters.
class: org.openqa.selenium.NoSuchElementException
Further Details: run errorDetails method

Body:
To extract the table we can use,

library(dplyr)
library(rvest)

remDr$navigate("https://www.bseindia.com/corporates/Sharehold_Searchnew.aspx?expandable=3")

remDr$getPageSource()[[1]] %>%
  read_html() %>% html_nodes('.mGrid') %>%
  html_table()
[[1]]
# A tibble: 4 x 5
  `Security Code` `Security Name`         Industry                     `For Quarter Ending` XBRL
            <int> <chr>                   <chr>                        <chr>                <lgl>
1          509055 VISAKA INDUSTRIES LTD.  Cement & Cement Products     09 Feb 2022          NA
2          532687 REPRO INDIA LTD.        Comm.Printing/Stationery     December 2021        NA
3          538734 Ceinsys Tech Ltd        IT Consulting & Software     09 Feb 2022          NA
4          532695 CELEBRITY FASHIONS LTD. Other Apparels & Accessories 27 Jan 2022          NA

But a faster approach would be using rvest

url %>%
  read_html() %>%
  html_nodes('.mGrid') %>%
  html_table()


问:
Append the lists in a DataFrame Column: Must have equal len keys and value when setting with an iterable
I have a DataFrame which has a column of lists and i'm filling this lists with new values.

```<code>df = pd.DataFrame({'col1':[1,2,3],'col2':[4,5,6], 'col3':[[],['x','y','z'],['x1','y1','z1']]}, index=['a','b','c'])

print(df)
           col1  col2          col3
        a     1     4            []
        b     2     5     [x, y, z]
        c     3     6  [x1, y1, z1]
</code>```

Here, the 'col3' column has lists, and what I'm trying to do is replace the current value with itself + the new list and using set() just to drop duplicates if exists. The new list is not always the same, I just did this way to make it easy. Observe that the order of the loop is not the same of the indexes, even though I need to put the right value in the right place.

```<code>n=0
for index in ['b','a','c']:
    n+=1
    list_to_append = ['x'+n,'y'+n,'z'+n]
    new_list = list(set(df.loc[index,'col3']+list_to_append))

    df.loc[index,'col3'] = new_list
</code>```

This is what I expect to get:

```<code>print(df)
           col1  col2                          col3
        a     1     4              ['x2','y2','z2']
        b     2     5      [x, y, z,'x1','y1','z1']
        c     3     6   [x1, y1, z1,'x3','y3','z3']
</code>```

out:

```<code>ValueError: Must have equal len keys and value when setting with an iterable
</code>```

is there any correct way to do this?

答:
Does this help. apply might not be the best approach depending on the size of df

import pandas as pd

df = pd.DataFrame({'col1':[1,2,3],'col2':[4,5,6], 'col3':[[],['x','y','z'],['x1','y1','z1']]}, index=['a','b','c'])

df['col3'] = df['col3'].apply(lambda x: list(set( x + ['x3','y3','z3'])))

print(df)

   col1  col2                      col3
a     1     4              [y3, z3, x3]
b     2     5     [x, y3, z3, z, x3, y]
c     3     6  [z1, y3, z3, y1, x1, x3]

```

Body:
I have a DataFrame which has a column of lists and i'm filling this lists with new values.

df = pd.DataFrame({'col1':[1,2,3],'col2':[4,5,6], 'col3':[[],['x','y','z'],['x1','y1','z1']]}, index=['a','b','c'])

print(df)
           col1  col2          col3
        a     1     4            []
        b     2     5     [x, y, z]
        c     3     6  [x1, y1, z1]

Here, the 'col3' column has lists, and what I'm trying to do is replace the current value with itself + the new list and using set() just to drop duplicates if exists. The new list is not always the same, I just did this way to make it easy. Observe that the order of the loop is not the same of the indexes, even though I need to put the right value in the right place.

n=0
for index in ['b','a','c']:
    n+=1
    list_to_append = ['x'+n,'y'+n,'z'+n]
    new_list = list(set(df.loc[index,'col3']+list_to_append))

    df.loc[index,'col3'] = new_list

This is what I expect to get:

print(df)
           col1  col2                          col3
        a     1     4              ['x2','y2','z2']
        b     2     5      [x, y, z,'x1','y1','z1']
        c     3     6   [x1, y1, z1,'x3','y3','z3']

out:

ValueError: Must have equal len keys and value when setting with an iterable

is there any correct way to do this?


问:
How to reset or remove Brave Wallet?
How to remove Brave browser Wallet? (It is similar to MetaMask but is baked into browser )

Page at brave://wallet/ is asking for password, that I don't remember and I don't need that,
I just need new.

Searches give no result so far.

P.S. Source of extensions are at https://github.com/brave/ethereum-remote-client
Issues there are disabled, and it looks like Brave orgnization guide to add issues into main https://github.com/brave/brave-browser repository that have 3k open issues

P.P.S.

https://community.brave.com/t/deleting-crypto-wallet/149327/3 point to https://github.com/brave/brave-browser/issues/10999 that is actually about removing account within wallet.

https://www.reddit.com/r/brave_browser/comments/9y7a06/is_there_a_way_to_delete_a_wallet/ suggest to play with (giving disclaimer) browser data folder

On you Windows machine, the bulk of your Wallet data is stored in ~/AppData/local/BraveSoftware/Brave-Browser/userdata/default in a file named ledger_state

答: In settings -> wallet, where it says 'default cryptocurrency wallet' set that to none, so that it doesn't override any other wallet you want to use.</p>

Title: How to reset or remove Brave Wallet?


问:
Flutte: Animate Goolge Map marker like native android?
im trying to animate my google maps marker with continuous LatLng from json API but the probelm is im using future to fetch data from my API so this is one time snapshot and the marker is still at the same position i tried Animation function with tween State but this isn`t working still stuck on same poisiton for marker
here is the code for GoogleMaps widget

```<code>final List<Marker> _markers = <Marker>[];
</code>```

Animation? _animation;
late GoogleMapController _controller;

final _mapMarkerSC = StreamController<List>();

StreamSink<List> get _mapMarkerSink => _mapMarkerSC.sink;
Stream<List> get mapMarkerStream =>  _mapMarkerSC.stream;

```<code>final googleMap = StreamBuilder<List<Marker>>(
  stream: mapMarkerStream,
  builder: (context, snapshot){
    return GoogleMap(
      mapType: MapType.normal,
      initialCameraPosition: CameraPosition(
        target: LatLng(lati, longi),
        zoom: 10,
      ),
      zoomControlsEnabled: false,
      onMapCreated: (GoogleMapController controller){
        _controller = controller;
      },
      markers: Set<Marker>.of(snapshot.data ?? []),
      padding: EdgeInsets.all(8),
    );
  },
);

return Scaffold(
  body: Stack(
    children: [
      googleMap,

    ],
  ),
);
</code>```

}

the animation function

```<code>setUpMarker() async {
  for(int i = 0; i < testList.length; i++){
    _setMarkerIcon() async {
      _carIcon = await BitmapDescriptor.fromAssetImage(
          ImageConfiguration(size:  Size(0.5, 0.5)),
          "asset/icons/green1.png"
      );
    }

    var currentLocationCamera = LatLng(testList[i].latitude!.toDouble(), testList[i].longitude!.toDouble());
    final pickUpMarker = Marker(
      markerId: MarkerId(testList[i].regNo!.toString()),
      position: LatLng(currentLocationCamera.latitude, currentLocationCamera.longitude),
      icon: _carIcon,
        /*BitmapDescriptor.fromBytes(await getBytesFromAsset('assets/icons/green1.png', 70)),*/
      infoWindow: InfoWindow(
        title: testList[i].regNo!.toString(),
      )
    );

    await Future.delayed(const Duration(milliseconds: 500));
    _markers.add(pickUpMarker);
    _mapMarkerSink.add(_markers);
  }
}

animateCar(
    double fromLat,
    double fromLong,
    StreamSink<List<Marker>> mapMarkerSink,
    TickerProvider Provider,
    GoogleMapController controller,
    ) async {
   for(int i = 0; i < testList.length; i++){
    setState(() {
      _markers.clear();

      getMarkers() {
        _setMarkerIcon() async {
          _carIcon = await BitmapDescriptor.fromAssetImage(
              ImageConfiguration(size:  Size(0.5, 0.5)),
              "asset/icons/green1.png"
          );
        }
      }

      var carMarker = Marker(
        markerId: MarkerId("driverMakrer"),
        position: LatLng(testList[i].latitude!.toDouble(), testList[i].longitude!.toDouble()),
        icon:  _carIcon,
</code>```

/BitmapDescriptor.fromBytes(await getBytesFromAsset('assets/icons/green1.png', 60)),/
anchor: const Offset(0.5,0.5),
rotation: testList[i].heading!.toDouble(),
draggable: false,
);

```<code>      _markers.add(carMarker);
      mapMarkerSink.add(_markers);

      final animationController = AnimationController(
        duration: const Duration(seconds: 1),
        vsync: Provider,
      );

      Tween<double> tween  = Tween(begin: 0, end: 1);

      _animation = tween.animate(animationController)
        ..addListener(() async {

          getMarkers() {
            _setMarkerIcon() async {
              _carIcon = await BitmapDescriptor.fromAssetImage(
                  ImageConfiguration(size:  Size(0.5, 0.5)),
                  "asset/icons/green1.png"
              );
            }
          }

          final v  = _animation!.value;
          double lng = v * testList[i].longitude!.toDouble() + (1 - v) * testList[i].longitude!.toDouble();
          double lat = v * testList[i].latitude!.toDouble() + (1 - v) * testList[i].latitude!.toDouble();
          LatLng newPos = LatLng(lat, lng);
          if(_markers.contains(carMarker)) _markers.remove(carMarker);
          carMarker = Marker(
            markerId: MarkerId("driverMarker"),
            position: newPos,/*LatLng(testList[i].latitude!.toDouble(), testList[i].longitude!.toDouble()),*/
            icon: _carIcon,
            /*BitmapDescriptor.fromBytes(await getBytesFromAsset('assets/icons/green1.png', 50)),*/
            anchor: const Offset(0.5,0.5),
            flat: true,
            rotation: testList[i].latitude!.toDouble(),
            draggable: false,
          );

          _markers.add(carMarker);
          mapMarkerSink.add(_markers);

          controller.animateCamera(CameraUpdate.newCameraPosition(
              CameraPosition(
                  target: newPos,/*LatLng(testList[i].latitude!.toDouble(), testList[i].longitude!.toDouble()),*/
                  zoom: 15.5
              ))
          );
        });
      animationController.forward();
    });
  }

}

Future.delayed(const Duration(seconds: 1)).then((value) {
  for(int i = 0; i < testList.length; i++){
    double latI;
    double longI;
    setState(() {
      latI = testList[i].latitude!.toDouble();
      longI = testList[i].longitude!.toDouble();
      animateCar(
        latI,
        longI,
        _mapMarkerSink,
        this,
        _controller,
      );
    });
  }
});
</code>```

and here is the future for fetchData()

```<code>List<SingleVehicleProvider> testList = [];
</code>```

Future<List>? _future;

Future<List> fetchData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();

```<code>var secretKey = await prefs.get('secretKey') ??  null;
var customID = customervehiclesID;

var url = "http://api75.trackcaronline.com/api/Vehicle/GetSingleVehicleInfo/$customervehiclesID";
var result = await http.get(Uri.parse(url),
    headers: {
      'Authorization' : 'bearer $secretKey'
    }
);

var jsonData = json.decode(result.body);

jsonData.forEach((e) async {
  SingleVehicleProvider provider = await SingleVehicleProvider.fromJson(e);
  testList.add(provider);
});
return testList;
</code>```

}

i`m stuck at this probelm for 2 weeks i tried using animarker package and also tried fetching data using Stream but it gave me errors please help me on this

i`m trying to create my screen like in this GIF URL
but my screen is static

答:
```<code> Map<MarkerId, Marker> markers = {};

  @override
     Widget build(BuildContext context) {

            return Scaffold(
    body:
     GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition: _kGooglePlex,
        myLocationEnabled: true,
        tiltGesturesEnabled: true,
        compassEnabled: true,
        scrollGesturesEnabled: true,
        zoomGesturesEnabled: true,

        markers: Set<Marker>.of(markers.values),
        onMapCreated: (GoogleMapController controller) {
          usermap = controller;

        },
      ),
     )
   );
  }
     _addMarker(LatLng position, String id, BitmapDescriptor descriptor)
 {
   MarkerId markerId = MarkerId(id);
    Marker marker =
    Marker(markerId: markerId, icon: descriptor, position: position);
markers[markerId] = marker;
    }
</code>```

that is simple that i used to do all thing this will help you and always call allways call  setState(() { _addMarker( LatLng(event.latitude, event.longitude), "origin", BitmapDescriptor.defaultMarker, );

}
that is code i use to update marker according to stream

Body:
im trying to animate my google maps marker with continuous LatLng from json API but the probelm is im using future to fetch data from my API so this is one time snapshot and the marker is still at the same position i tried Animation function with tween State but this isn`t working still stuck on same poisiton for marker
here is the code for GoogleMaps widget

final List<Marker> _markers = <Marker>[];

Animation? _animation;
late GoogleMapController _controller;

final _mapMarkerSC = StreamController<List>();

StreamSink<List> get _mapMarkerSink => _mapMarkerSC.sink;
Stream<List> get mapMarkerStream =>  _mapMarkerSC.stream;

final googleMap = StreamBuilder<List<Marker>>(
  stream: mapMarkerStream,
  builder: (context, snapshot){
    return GoogleMap(
      mapType: MapType.normal,
      initialCameraPosition: CameraPosition(
        target: LatLng(lati, longi),
        zoom: 10,
      ),
      zoomControlsEnabled: false,
      onMapCreated: (GoogleMapController controller){
        _controller = controller;
      },
      markers: Set<Marker>.of(snapshot.data ?? []),
      padding: EdgeInsets.all(8),
    );
  },
);

return Scaffold(
  body: Stack(
    children: [
      googleMap,

    ],
  ),
);

}

the animation function

setUpMarker() async {
  for(int i = 0; i < testList.length; i++){
    _setMarkerIcon() async {
      _carIcon = await BitmapDescriptor.fromAssetImage(
          ImageConfiguration(size:  Size(0.5, 0.5)),
          "asset/icons/green1.png"
      );
    }

    var currentLocationCamera = LatLng(testList[i].latitude!.toDouble(), testList[i].longitude!.toDouble());
    final pickUpMarker = Marker(
      markerId: MarkerId(testList[i].regNo!.toString()),
      position: LatLng(currentLocationCamera.latitude, currentLocationCamera.longitude),
      icon: _carIcon,
        /*BitmapDescriptor.fromBytes(await getBytesFromAsset('assets/icons/green1.png', 70)),*/
      infoWindow: InfoWindow(
        title: testList[i].regNo!.toString(),
      )
    );

    await Future.delayed(const Duration(milliseconds: 500));
    _markers.add(pickUpMarker);
    _mapMarkerSink.add(_markers);
  }
}

animateCar(
    double fromLat,
    double fromLong,
    StreamSink<List<Marker>> mapMarkerSink,
    TickerProvider Provider,
    GoogleMapController controller,
    ) async {
   for(int i = 0; i < testList.length; i++){
    setState(() {
      _markers.clear();

      getMarkers() {
        _setMarkerIcon() async {
          _carIcon = await BitmapDescriptor.fromAssetImage(
              ImageConfiguration(size:  Size(0.5, 0.5)),
              "asset/icons/green1.png"
          );
        }
      }

      var carMarker = Marker(
        markerId: MarkerId("driverMakrer"),
        position: LatLng(testList[i].latitude!.toDouble(), testList[i].longitude!.toDouble()),
        icon:  _carIcon,

/BitmapDescriptor.fromBytes(await getBytesFromAsset('assets/icons/green1.png', 60)),/
anchor: const Offset(0.5,0.5),
rotation: testList[i].heading!.toDouble(),
draggable: false,
);

      _markers.add(carMarker);
      mapMarkerSink.add(_markers);

      final animationController = AnimationController(
        duration: const Duration(seconds: 1),
        vsync: Provider,
      );

      Tween<double> tween  = Tween(begin: 0, end: 1);

      _animation = tween.animate(animationController)
        ..addListener(() async {

          getMarkers() {
            _setMarkerIcon() async {
              _carIcon = await BitmapDescriptor.fromAssetImage(
                  ImageConfiguration(size:  Size(0.5, 0.5)),
                  "asset/icons/green1.png"
              );
            }
          }

          final v  = _animation!.value;
          double lng = v * testList[i].longitude!.toDouble() + (1 - v) * testList[i].longitude!.toDouble();
          double lat = v * testList[i].latitude!.toDouble() + (1 - v) * testList[i].latitude!.toDouble();
          LatLng newPos = LatLng(lat, lng);
          if(_markers.contains(carMarker)) _markers.remove(carMarker);
          carMarker = Marker(
            markerId: MarkerId("driverMarker"),
            position: newPos,/*LatLng(testList[i].latitude!.toDouble(), testList[i].longitude!.toDouble()),*/
            icon: _carIcon,
            /*BitmapDescriptor.fromBytes(await getBytesFromAsset('assets/icons/green1.png', 50)),*/
            anchor: const Offset(0.5,0.5),
            flat: true,
            rotation: testList[i].latitude!.toDouble(),
            draggable: false,
          );

          _markers.add(carMarker);
          mapMarkerSink.add(_markers);

          controller.animateCamera(CameraUpdate.newCameraPosition(
              CameraPosition(
                  target: newPos,/*LatLng(testList[i].latitude!.toDouble(), testList[i].longitude!.toDouble()),*/
                  zoom: 15.5
              ))
          );
        });
      animationController.forward();
    });
  }

}

Future.delayed(const Duration(seconds: 1)).then((value) {
  for(int i = 0; i < testList.length; i++){
    double latI;
    double longI;
    setState(() {
      latI = testList[i].latitude!.toDouble();
      longI = testList[i].longitude!.toDouble();
      animateCar(
        latI,
        longI,
        _mapMarkerSink,
        this,
        _controller,
      );
    });
  }
});

and here is the future for fetchData()

List<SingleVehicleProvider> testList = [];

Future<List>? _future;

Future<List> fetchData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();

var secretKey = await prefs.get('secretKey') ??  null;
var customID = customervehiclesID;

var url = "http://api75.trackcaronline.com/api/Vehicle/GetSingleVehicleInfo/$customervehiclesID";
var result = await http.get(Uri.parse(url),
    headers: {
      'Authorization' : 'bearer $secretKey'
    }
);

var jsonData = json.decode(result.body);

jsonData.forEach((e) async {
  SingleVehicleProvider provider = await SingleVehicleProvider.fromJson(e);
  testList.add(provider);
});
return testList;

}

i`m stuck at this probelm for 2 weeks i tried using animarker package and also tried fetching data using Stream but it gave me errors please help me on this

i`m trying to create my screen like in this GIF URL
but my screen is static

Body:
 Map<MarkerId, Marker> markers = {};

  @override
     Widget build(BuildContext context) {

            return Scaffold(
    body:
     GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition: _kGooglePlex,
        myLocationEnabled: true,
        tiltGesturesEnabled: true,
        compassEnabled: true,
        scrollGesturesEnabled: true,
        zoomGesturesEnabled: true,

        markers: Set<Marker>.of(markers.values),
        onMapCreated: (GoogleMapController controller) {
          usermap = controller;

        },
      ),
     )
   );
  }
     _addMarker(LatLng position, String id, BitmapDescriptor descriptor)
 {
   MarkerId markerId = MarkerId(id);
    Marker marker =
    Marker(markerId: markerId, icon: descriptor, position: position);
markers[markerId] = marker;
    }

that is simple that i used to do all thing this will help you and always call allways call  setState(() { _addMarker( LatLng(event.latitude, event.longitude), "origin", BitmapDescriptor.defaultMarker, );

}
that is code i use to update marker according to stream


问:
Access to 'viewBinding' exceeds its access rights

After updating Android Studio to Arctic Fox and Android Gradle plugin to 7.0.0 I'm facing this warning, I mean the app can be built successfully nonetheless of this warning but what I am missing here? What's the problem here?

According to the official View Binding reference, I'm enabling it the right way.
here is my build.gradle if anyone is interested in checking.

There are some related questions but I don't think they are relevant in this situation.

Build.gradle: Access to 'project' exceeds its access rights

Enable viewBinding feature failed (Android Studio 3.6)

答:
Try to rename your file 'build.gradle' to 'build.gradle.kts'.
And change its content to the appropriate Kotlin DSL syntax where necessary.</p>


问:
UTF-8 to Unicode Code Points
Is there a function that will change UTF-8 to Unicode leaving non special characters as normal letters and numbers?

ie the German word "tchüß" would be rendered as something like "tch\20AC\21AC" (please note that I am making the Unicode codes up).

EDIT: I am experimenting with the following function, but although this one works well with ASCII 32-127, it seems to fail for double byte chars:

```<code>function strToHex ($string)
{
    $hex = '';
    for ($i = 0; $i < mb_strlen ($string, "utf-8"); $i++)
    {
        $id = ord (mb_substr ($string, $i, 1, "utf-8"));
        $hex .= ($id <= 128) ? mb_substr ($string, $i, 1, "utf-8") : "&#" . $id . ";";
}

    return ($hex);
}
</code>```

Any ideas?

EDIT 2: Found solution: The PHP ord() function does not work for double byte chars. Use instead: http://nl.php.net/manual/en/function.ord.php#78032

答:
I guess you're going to print out your strings on a website?

I'm storing all my databases in uft8, using html_entities($string) before output.

Maybe you have to try
html_entities(utf8_encode($string));

Title: UTF-8 to Unicode Code Points

Body:
Is there a function that will change UTF-8 to Unicode leaving non special characters as normal letters and numbers?

ie the German word "tchüß" would be rendered as something like "tch\20AC\21AC" (please note that I am making the Unicode codes up).

EDIT: I am experimenting with the following function, but although this one works well with ASCII 32-127, it seems to fail for double byte chars:

function strToHex ($string)
{
    $hex = '';
    for ($i = 0; $i < mb_strlen ($string, "utf-8"); $i++)
    {
        $id = ord (mb_substr ($string, $i, 1, "utf-8"));
        $hex .= ($id <= 128) ? mb_substr ($string, $i, 1, "utf-8") : "&#" . $id . ";";
}

    return ($hex);
}

Any ideas?

EDIT 2: Found solution: The PHP ord() function does not work for double byte chars. Use instead: http://nl.php.net/manual/en/function.ord.php#78032


问:
PDF Couldn't Load From Network?
```<code>      body: SfPdfViewer.network(
    'https://sajhaguides.files.wordpress.com/2022/02/class10optmath-1.pdf',
    key: _pdfViewerKey,
  ),
</code>```

The Above Code Doesn't Show any output? Why Please Help

答:
There are many possibilities:

Check your internet connection permission in main folder/ AndroidManifest.xml.

Confirm that have you added android:usesCleartextTraffic="true" into

Check dependency settings which you have used.

If it doesn't work, please post the whole code or logs and screenshot of your app.

Title: PDF Couldn't Load From Network?

Body:
      body: SfPdfViewer.network(
    'https://sajhaguides.files.wordpress.com/2022/02/class10optmath-1.pdf',
    key: _pdfViewerKey,
  ),

The Above Code Doesn't Show any output? Why Please Help


问:
go struct with generics implementing comparable
Consider the following code snippet for version go1.18beta2 linux/amd64

    type Vector[T comparable] struct {
       data_ []T
    }

    func (v *Vector[T]) Contains(e T) bool {
       for _, x := range v.data_ {
          if x == e {
             return true
          }
       }
       return false
    }

    func TestVector(t *testing.T) {
       v2 := Vector[Vector[int]]{}
    }
```

This does not compile and gives error: “Vector[int] does not implement comparable” simply because Vector has no equality operators defined. However, I cannot find how to define them.

Question: Is this approach of creating a comparable struct not allowed, and why; or is the documentation not written yet?

答:
The constraint comparable is predeclared and supported by the language specifications. You can't "manually" make a type implement it. The documentation is available in the specs (under Type Constraints):

The predeclared interface type comparable denotes the set of all concrete (non-interface) types that are comparable. Specifically, a type T implements comparable if:

T is not an interface type and T supports the operations == and !=; or

T is an interface type and each type in T's type set implements comparable.

Your type Vector[T comparable] doesn't meet any of those conditions. It is not an interface type, and it does not otherwise support the equality operations, because one of its fields data_ []T is not comparable due to being a slice — even if element type is constrained by comparable.

The purpose of the comparable constraint is really just to allow writing generic code with == and != operators. If a type is not comparable by design, you can't write such code. That would be true even if Vector didn't have a type parameter.

If your goal is instantiating Vector[Vector[T]] and allow equality tests between instances of Vector[T], you might want to add an Equal method that takes care of this specific use case — only vectors instantiated with the same type parameter as the receiver will be allowed:

```<code>func (v *Vector[T]) Equal(e Vector[T]) bool {
    // test equality in a way that makes sense for this type
}
</code>```

Worth mentioning that there is a way to make Vector[T comparable] comparable itself, i.e. change the data_ field to be a pointer-to-slice:

```<code>type Vector[T comparable] struct {
    data_ *[]T
}
</code>```

Now instantiation with Vector[Vector[int]] compiles. However, beside being very cumbersome to initialize with struct literals (playground), it comes with all caveats of pointer comparison. More specifically:

Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct zero-size variables may or may not be equal.

Now the comparison x == e tests that the memory address stored in the data_ field in x and e is the same. This might skew the semantics of comparing two Vector[T] instances — is it correct to say that two vector instances are equal if they hold a reference to the same slice? Maybe. It depends on the assumptions your program wants to make. Personally, I don't think this is actually better than having a separate Equal method and/or redesigning your data types, but as usual, YMMV.

Note also that if you instantiate as Vector[float64] and compare NaN values, the comparison will be false.

Body:
Consider the following code snippet for version go1.18beta2 linux/amd64

    type Vector[T comparable] struct {
       data_ []T
    }

    func (v *Vector[T]) Contains(e T) bool {
       for _, x := range v.data_ {
          if x == e {
             return true
          }
       }
       return false
    }

    func TestVector(t *testing.T) {
       v2 := Vector[Vector[int]]{}
    }

This does not compile and gives error: “Vector[int] does not implement comparable” simply because Vector has no equality operators defined. However, I cannot find how to define them.

Question: Is this approach of creating a comparable struct not allowed, and why; or is the documentation not written yet?

Body:
The constraint comparable is predeclared and supported by the language specifications. You can't "manually" make a type implement it. The documentation is available in the specs (under Type Constraints):

The predeclared interface type comparable denotes the set of all concrete (non-interface) types that are comparable. Specifically, a type T implements comparable if:

T is not an interface type and T supports the operations == and !=; or

T is an interface type and each type in T's type set implements comparable.

Your type Vector[T comparable] doesn't meet any of those conditions. It is not an interface type, and it does not otherwise support the equality operations, because one of its fields data_ []T is not comparable due to being a slice — even if element type is constrained by comparable.

The purpose of the comparable constraint is really just to allow writing generic code with == and != operators. If a type is not comparable by design, you can't write such code. That would be true even if Vector didn't have a type parameter.

If your goal is instantiating Vector[Vector[T]] and allow equality tests between instances of Vector[T], you might want to add an Equal method that takes care of this specific use case — only vectors instantiated with the same type parameter as the receiver will be allowed:

func (v *Vector[T]) Equal(e Vector[T]) bool {
    // test equality in a way that makes sense for this type
}

Worth mentioning that there is a way to make Vector[T comparable] comparable itself, i.e. change the data_ field to be a pointer-to-slice:

type Vector[T comparable] struct {
    data_ *[]T
}

Now instantiation with Vector[Vector[int]] compiles. However, beside being very cumbersome to initialize with struct literals (playground), it comes with all caveats of pointer comparison. More specifically:

Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct zero-size variables may or may not be equal.

Now the comparison x == e tests that the memory address stored in the data_ field in x and e is the same. This might skew the semantics of comparing two Vector[T] instances — is it correct to say that two vector instances are equal if they hold a reference to the same slice? Maybe. It depends on the assumptions your program wants to make. Personally, I don't think this is actually better than having a separate Equal method and/or redesigning your data types, but as usual, YMMV.

Note also that if you instantiate as Vector[float64] and compare NaN values, the comparison will be false.


问:
reinterpret<char**> from new char[]
So I saw this piece of code that's confusing me:

```<code>class DynamicBuffer
{
    private:

        char* _buf = nullptr;

    public:
        void Resize(size_t size)
        {
            char* resizeBuf = new char[size];
            char **ptr = reinterpret_cast<char**>(resizeBuf);
            *ptr = _buf;
            _buf = resizeBuf;
        }
}
</code>```

I'm hung up on:

```<code>char **ptr = reinterpret_cast<char**>(resizeBuf);
*ptr = _buf;
</code>```

Am I right in thinking the author was trying to make the first sizeof(char) bytes to point the older buffer?
How is this not undefined behavior?

Why not just do this:

```<code>char** resizeBuf = new char*[size];
</code>```

答:
This seems like a roundabout version of basically writing:

```<code>void Resize(size_t size)
{
    assert(size >= sizeof(char*));
    char* resizeBuf = new char[size];
    memcpy((void*)resizeBuf, (void*)&_buf, sizeof(_buf));
    _buf = resizeBuf;
}
</code>```

Or using placement new to do essentially the same thing.

```<code>void Resize(size_t size)
{
    assert(size >= sizeof(char*));
    char* resizeBuf = new char[size];
    char** firstPointer = new(resizeBuf) char*;
    *firstPointer = _buf;
    _buf = resizeBuf;
}
</code>```

I think the memcpy version happens to be well-defined because the default alignment for memory allocated with new __STDCPP_DEFAULT_NEW_ALIGNMENT__ should accomodate pointers.

Memcpy is also allowed to implicitly create new objects, which just a regular assignment is not allowed to do without the prior placement new.

Title: reinterpret<char**> from new char[]

Body:
So I saw this piece of code that's confusing me:

class DynamicBuffer
{
    private:

        char* _buf = nullptr;

    public:
        void Resize(size_t size)
        {
            char* resizeBuf = new char[size];
            char **ptr = reinterpret_cast<char**>(resizeBuf);
            *ptr = _buf;
            _buf = resizeBuf;
        }
}

I'm hung up on:

char **ptr = reinterpret_cast<char**>(resizeBuf);
*ptr = _buf;

Am I right in thinking the author was trying to make the first sizeof(char) bytes to point the older buffer?
How is this not undefined behavior?

Why not just do this:

char** resizeBuf = new char*[size];

Body:
This seems like a roundabout version of basically writing:

void Resize(size_t size)
{
    assert(size >= sizeof(char*));
    char* resizeBuf = new char[size];
    memcpy((void*)resizeBuf, (void*)&_buf, sizeof(_buf));
    _buf = resizeBuf;
}

Or using placement new to do essentially the same thing.

void Resize(size_t size)
{
    assert(size >= sizeof(char*));
    char* resizeBuf = new char[size];
    char** firstPointer = new(resizeBuf) char*;
    *firstPointer = _buf;
    _buf = resizeBuf;
}

I think the memcpy version happens to be well-defined because the default alignment for memory allocated with new __STDCPP_DEFAULT_NEW_ALIGNMENT__ should accomodate pointers.

Memcpy is also allowed to implicitly create new objects, which just a regular assignment is not allowed to do without the prior placement new.


问:
apps script : how can I simplify to avoid multiple calls to server?
I cannot find the way to properly simplify the nested loops to build an array of values and data validations and then set them all in the sheet in a single call to the server.
Is it even possible  ??

```<code>function onEdit(){
  testValidation()
}

function testValidation() {

  var sheet = SpreadsheetApp.getActiveSheet();

  var source = SpreadsheetApp.getActive().getRange('A3:J4').getValues()
  var destination = SpreadsheetApp.getActive().getRange('M3:V4');
  destination.clearDataValidations();

  var validationRule = SpreadsheetApp.newDataValidation().requireCheckbox().build(); // checkbox

  for(var r = 0; r <= source.length - 1; r++) {
    for(var c = 0; c <= source[0].length - 1; c++) {
      if(source[r][c] ===""  ){
        sheet.getRange(r + 3,c + 14).clearDataValidations().setValue(null)
      }else{
        sheet.getRange(r + 3,c + 14).setDataValidation(validationRule).setValue("true")
      }
    }
  }
}
</code>```

Link to shared spreadsheet :
https://docs.google.com/spreadsheets/d/1fyFPIssp3zUjRmWxU9LqHvpowH8SHdMQYizNOZ3xKsA/edit?usp=sharing

答:
In your situation, how about the following modified script?

Modified script 1:

function testValidation() {
  var check = SpreadsheetApp.newDataValidation().requireCheckbox().build();
  var sheet = SpreadsheetApp.getActiveSheet();
  var source = sheet.getRange('A3:J4').getValues();
  var values = source.map(r => r.map(c => c != "" ? check : null));
  sheet.getRange('M3:V4').clearContent().setDataValidations(values).check();
}
```
<ul>
<li>In this modification, the checkboxes and the clear are set by <code>setDataValidations</code>.
<ul>
<li>I thought that this method might be low process cost.</li>
</ul>
</li>
</ul>
<h3>Modified script 2:</h3>
<pre class="lang-js prettyprint-override"><code>function testValidation() {
  // Ref: https://stackoverflow.com/a/21231012/7108653
  const columnToLetter = column => {
    let temp,
      letter = "";
    while (column > 0) {
      temp = (column - 1) % 26;
      letter = String.fromCharCode(temp + 65) + letter;
      column = (column - temp - 1) / 26;
    }
    return letter;
  };

  var sheet = SpreadsheetApp.getActiveSheet();
  var source = sheet.getRange('A3:J4').getValues();
  var rangeList = source.flatMap((r, i) => r.flatMap((c, j) => c != "" ? `${columnToLetter(j + 14)}${i + 3}` : []));
  sheet.getRange('M3:V4').clearDataValidations().setValue(null);
  if (rangeList.length == 0) return;
  sheet.getRangeList(rangeList).insertCheckboxes().check();
}
</code>```

I thought that the cells of M3:V4 can be cleared using sheet.getRange('M3:V4').clearDataValidations().setValue(null).

In this modification, the checkboxes are put using insertCheckboxes() method of Class RangeList.

References:

insertCheckboxes()

setDataValidations()

Body:
I cannot find the way to properly simplify the nested loops to build an array of values and data validations and then set them all in the sheet in a single call to the server.
Is it even possible  ??

function onEdit(){
  testValidation()
}

function testValidation() {

  var sheet = SpreadsheetApp.getActiveSheet();

  var source = SpreadsheetApp.getActive().getRange('A3:J4').getValues()
  var destination = SpreadsheetApp.getActive().getRange('M3:V4');
  destination.clearDataValidations();

  var validationRule = SpreadsheetApp.newDataValidation().requireCheckbox().build(); // checkbox

  for(var r = 0; r <= source.length - 1; r++) {
    for(var c = 0; c <= source[0].length - 1; c++) {
      if(source[r][c] ===""  ){
        sheet.getRange(r + 3,c + 14).clearDataValidations().setValue(null)
      }else{
        sheet.getRange(r + 3,c + 14).setDataValidation(validationRule).setValue("true")
      }
    }
  }
}

Link to shared spreadsheet :
https://docs.google.com/spreadsheets/d/1fyFPIssp3zUjRmWxU9LqHvpowH8SHdMQYizNOZ3xKsA/edit?usp=sharing

Body:
In your situation, how about the following modified script?

Modified script 1:

function testValidation() {
  var check = SpreadsheetApp.newDataValidation().requireCheckbox().build();
  var sheet = SpreadsheetApp.getActiveSheet();
  var source = sheet.getRange('A3:J4').getValues();
  var values = source.map(r => r.map(c => c != "" ? check : null));
  sheet.getRange('M3:V4').clearContent().setDataValidations(values).check();
}

In this modification, the checkboxes and the clear are set by setDataValidations.

I thought that this method might be low process cost.

Modified script 2:

function testValidation() {
  // Ref: https://stackoverflow.com/a/21231012/7108653
  const columnToLetter = column => {
    let temp,
      letter = "";
    while (column > 0) {
      temp = (column - 1) % 26;
      letter = String.fromCharCode(temp + 65) + letter;
      column = (column - temp - 1) / 26;
    }
    return letter;
  };

  var sheet = SpreadsheetApp.getActiveSheet();
  var source = sheet.getRange('A3:J4').getValues();
  var rangeList = source.flatMap((r, i) => r.flatMap((c, j) => c != "" ? `${columnToLetter(j + 14)}${i + 3}` : []));
  sheet.getRange('M3:V4').clearDataValidations().setValue(null);
  if (rangeList.length == 0) return;
  sheet.getRangeList(rangeList).insertCheckboxes().check();
}

I thought that the cells of M3:V4 can be cleared using sheet.getRange('M3:V4').clearDataValidations().setValue(null).

In this modification, the checkboxes are put using insertCheckboxes() method of Class RangeList.

References:

insertCheckboxes()

setDataValidations()


答:
You could use apply with help of a set difference:

```<code>S = set(list_to_append)
df['col3'] = df['col3'].apply(lambda x: x+list(S.difference(x)))
</code>```

output (with a new column for clarity):

```<code>   col1  col2          col3                      col4
a     1     4            []              [z3, y3, x3]
b     2     5     [x, y, z]     [x, y, z, z3, y3, x3]
c     3     6  [x1, y1, z1]  [x1, y1, z1, z3, y3, x3]
</code>```

For a variable input use a Series:

```<code>s = pd.Series([list((f'x{n}',f'y{n}',f'z{n}')) for n in range(len(df))],
              index=['b','a','c'])

df['col4'] = (df['col3']+s).apply(lambda x: list(dict.fromkeys(x)))
</code>```

output:

```<code>   col1  col2          col3                      col4
a     1     4            []              [x1, y1, z1]
b     2     5     [x, y, z]     [x, y, z, x0, y0, z0]
c     3     6  [x1, y1, z1]  [x1, y1, z1, x2, y2, z2]
</code>```

Title: Append the lists in a DataFrame Column: Must have equal len keys and value when setting with an iterable

Body:
You could use apply with help of a set difference:

S = set(list_to_append)
df['col3'] = df['col3'].apply(lambda x: x+list(S.difference(x)))

output (with a new column for clarity):

   col1  col2          col3                      col4
a     1     4            []              [z3, y3, x3]
b     2     5     [x, y, z]     [x, y, z, z3, y3, x3]
c     3     6  [x1, y1, z1]  [x1, y1, z1, z3, y3, x3]

For a variable input use a Series:

s = pd.Series([list((f'x{n}',f'y{n}',f'z{n}')) for n in range(len(df))],
              index=['b','a','c'])

df['col4'] = (df['col3']+s).apply(lambda x: list(dict.fromkeys(x)))

output:

   col1  col2          col3                      col4
a     1     4            []              [x1, y1, z1]
b     2     5     [x, y, z]     [x, y, z, x0, y0, z0]
c     3     6  [x1, y1, z1]  [x1, y1, z1, x2, y2, z2]


问:
Is there any way to upload files via postman into a GraphQL API?
Currently I'm using Altair to upload files (in my case it's just for images) to my GraphQL API. However, all my other routes are stored in postman and it'd be nice if I could use just one application - Postman - for everything.

In Altair I can simply select an image and store that as a variable that I put as the value for my GraphQL Upload field.

Does anyone know if Postman supports that (or a similiar) feature?

Thank you!

答:
I ran into this issue using graphene-file-upload==1.2.2 as the upload handler and found it extremely complex to prepare the correct payload as the request included additional parameters to the upload file, so I hope this helps:

This is the curl equivalent request for reference:

```<code>curl --location --request POST '<REDACTED>/graphql' \
--header 'Authorization: Bearer <REDACTED>' \
--form '0=@"/home/user/Downloads/Five.pdf"' \
--form 'map="{\"0\": [\"variables.data.attachments\"]}"' \
--form 'operations="{
    \"query\": \"mutation AddPOAttachments($data: AddProductAttachmentsInput!) { add_product_attachments(data: $data) { attachments { id url purpose file_info { name type size_in_bytes} __typename } __typename }}\",
    \"variables\":
    {
        \"data\":
        {
            \"sku\": \"123456sku\",
            \"attachments\": null,
            \"purpose\": \"Test\"
        }
    }
}"'
</code>```

Body:
I ran into this issue using graphene-file-upload==1.2.2 as the upload handler and found it extremely complex to prepare the correct payload as the request included additional parameters to the upload file, so I hope this helps:

This is the curl equivalent request for reference:

curl --location --request POST '<REDACTED>/graphql' \
--header 'Authorization: Bearer <REDACTED>' \
--form '0=@"/home/user/Downloads/Five.pdf"' \
--form 'map="{\"0\": [\"variables.data.attachments\"]}"' \
--form 'operations="{
    \"query\": \"mutation AddPOAttachments($data: AddProductAttachmentsInput!) { add_product_attachments(data: $data) { attachments { id url purpose file_info { name type size_in_bytes} __typename } __typename }}\",
    \"variables\":
    {
        \"data\":
        {
            \"sku\": \"123456sku\",
            \"attachments\": null,
            \"purpose\": \"Test\"
        }
    }
}"'