问:
Convert a Keras NN to a Pytorch NN
I'm a beginner with constructing neural networks in pytorch and Keras. I have the following Keras code for a variation of the AlexNet model:

```<code>def shallownet(nb_classes):
    global img_size
    model = Sequential()
    model.add(Conv2D(64, (5, 5), input_shape=img_size, data_format='channels_first'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='same', data_format='channels_first'))

    model.add(Conv2D(64, (5, 5), padding='same', data_format='channels_first'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='same', data_format='channels_first'))

    model.add(Flatten())
    model.add(Dense(384))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(192))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(nb_classes, activation='softmax'))
    return model
</code>```

This is based on the C1/C3 model described on page 12 of this paper:
https://arxiv.org/pdf/1609.04836.pdf
And I want to convert this to the Pytorch version of the NN. Specifically I'm trying to get it in the form of:

```<code>class AlexNetOWT_BN(nn.Module):

    def __init__(self, num_classes=1000):
        super(AlexNetOWT_BN, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2,
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(64, 192, kernel_size=5, padding=2, bias=False),
            nn.BatchNorm2d(192),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(192, 384, kernel_size=3, padding=1, bias=False),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(384),
            nn.Conv2d(384, 256, kernel_size=3, padding=1, bias=False),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(256),
            nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(256)
        )
        self.classifier = nn.Sequential(
            nn.Linear(256 * 6 * 6, 4096, bias=False),
            nn.BatchNorm1d(4096),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(4096, 4096, bias=False),
            nn.BatchNorm1d(4096),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(4096, num_classes)
        )

        #self.regime = {
        #    0: {'optimizer': 'SGD', 'lr': 1e-2,
        #        'weight_decay': 5e-4, 'momentum': 0.9},
        #    10: {'lr': 5e-3},
        #    15: {'lr': 1e-3, 'weight_decay': 0},
        #    20: {'lr': 5e-4},
        #    25: {'lr': 1e-4}
        #}
        self.regime = {
            0: {'optimizer': 'SGD', 'lr': 1e-2,
                'weight_decay': 5e-4, 'momentum': 0.9},
            20: {'lr': 1e-3},
            40: {'lr': 1e-4}
        }
        normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                         std=[0.229, 0.224, 0.225])
        self.input_transform = {
            'train': transforms.Compose([
                transforms.Scale(256),
                transforms.RandomCrop(224),
                transforms.RandomHorizontalFlip(),
                transforms.ToTensor(),
                normalize
            ]),
            'eval': transforms.Compose([
                transforms.Scale(256),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                normalize
            ])
        }

    def forward(self, x):
        x = self.features(x)
        x = x.view(-1, 256 * 6 * 6)
        x = self.classifier(x)
        return x
</code>```

The original AlexNet code for self.features is here (I switched the order of things above; not sure if that's allowed or not):

```<code>self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2,
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(64, 192, kernel_size=5, padding=2, bias=False),
            nn.BatchNorm2d(192),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(192, 384, kernel_size=3, padding=1, bias=False),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(384),
            nn.Conv2d(384, 256, kernel_size=3, padding=1, bias=False),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(256),
            nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(256)
        )
</code>```

I am specifically confused about how to change the features and the classifier. The description of the model I want is here:
https://arxiv.org/pdf/1609.04836.pdf on page 12, section B.3.

Thanks so much

答:
Here's the code:

```<code>class AlexNet(nn.Module):

    def __init__(self, num_classes=10):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=5, padding=2,
                      bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, kernel_size=5, padding=2, bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
        )
        self.classifier = nn.Sequential(
            nn.Linear(64 * 7 * 7, 384, bias=False),
            nn.BatchNorm1d(384),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(384, 192, bias=False),
            nn.BatchNorm1d(192),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(192, num_classes)
        )
        self.regime = {
            0: {'optimizer': 'SGD', 'lr': 1e-3,
                'weight_decay': 5e-4, 'momentum': 0.9},
            60: {'lr': 1e-2},
            120: {'lr': 1e-3},
            180: {'lr': 1e-4}
        }

    def forward(self, x):
        x = self.features(x)
        x = x.view(-1, 64 * 7 * 7)
        x = self.classifier(x)
        return F.log_softmax(x)

def cifar10_shallow(**kwargs):
    num_classes = getattr(kwargs, 'num_classes', 10)
    return AlexNet(num_classes)

def cifar100_shallow(**kwargs):
    num_classes = getattr(kwargs, 'num_classes', 100)
    return AlexNet(num_classes)

</code>```

Written by Wei Wen. smoothout repository

Title: Convert a Keras NN to a Pytorch NN

Body:
I'm a beginner with constructing neural networks in pytorch and Keras. I have the following Keras code for a variation of the AlexNet model:

def shallownet(nb_classes):
    global img_size
    model = Sequential()
    model.add(Conv2D(64, (5, 5), input_shape=img_size, data_format='channels_first'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='same', data_format='channels_first'))

    model.add(Conv2D(64, (5, 5), padding='same', data_format='channels_first'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='same', data_format='channels_first'))

    model.add(Flatten())
    model.add(Dense(384))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(192))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(nb_classes, activation='softmax'))
    return model

This is based on the C1/C3 model described on page 12 of this paper:
https://arxiv.org/pdf/1609.04836.pdf
And I want to convert this to the Pytorch version of the NN. Specifically I'm trying to get it in the form of:

class AlexNetOWT_BN(nn.Module):

    def __init__(self, num_classes=1000):
        super(AlexNetOWT_BN, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2,
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(64, 192, kernel_size=5, padding=2, bias=False),
            nn.BatchNorm2d(192),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(192, 384, kernel_size=3, padding=1, bias=False),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(384),
            nn.Conv2d(384, 256, kernel_size=3, padding=1, bias=False),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(256),
            nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(256)
        )
        self.classifier = nn.Sequential(
            nn.Linear(256 * 6 * 6, 4096, bias=False),
            nn.BatchNorm1d(4096),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(4096, 4096, bias=False),
            nn.BatchNorm1d(4096),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(4096, num_classes)
        )

        #self.regime = {
        #    0: {'optimizer': 'SGD', 'lr': 1e-2,
        #        'weight_decay': 5e-4, 'momentum': 0.9},
        #    10: {'lr': 5e-3},
        #    15: {'lr': 1e-3, 'weight_decay': 0},
        #    20: {'lr': 5e-4},
        #    25: {'lr': 1e-4}
        #}
        self.regime = {
            0: {'optimizer': 'SGD', 'lr': 1e-2,
                'weight_decay': 5e-4, 'momentum': 0.9},
            20: {'lr': 1e-3},
            40: {'lr': 1e-4}
        }
        normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                         std=[0.229, 0.224, 0.225])
        self.input_transform = {
            'train': transforms.Compose([
                transforms.Scale(256),
                transforms.RandomCrop(224),
                transforms.RandomHorizontalFlip(),
                transforms.ToTensor(),
                normalize
            ]),
            'eval': transforms.Compose([
                transforms.Scale(256),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                normalize
            ])
        }

    def forward(self, x):
        x = self.features(x)
        x = x.view(-1, 256 * 6 * 6)
        x = self.classifier(x)
        return x

The original AlexNet code for self.features is here (I switched the order of things above; not sure if that's allowed or not):

self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2,
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(64, 192, kernel_size=5, padding=2, bias=False),
            nn.BatchNorm2d(192),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(192, 384, kernel_size=3, padding=1, bias=False),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(384),
            nn.Conv2d(384, 256, kernel_size=3, padding=1, bias=False),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(256),
            nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.ReLU(inplace=True),
            nn.BatchNorm2d(256)
        )

I am specifically confused about how to change the features and the classifier. The description of the model I want is here:
https://arxiv.org/pdf/1609.04836.pdf on page 12, section B.3.

Thanks so much

Body:
Here's the code:

class AlexNet(nn.Module):

    def __init__(self, num_classes=10):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=5, padding=2,
                      bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, kernel_size=5, padding=2, bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
        )
        self.classifier = nn.Sequential(
            nn.Linear(64 * 7 * 7, 384, bias=False),
            nn.BatchNorm1d(384),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(384, 192, bias=False),
            nn.BatchNorm1d(192),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(192, num_classes)
        )
        self.regime = {
            0: {'optimizer': 'SGD', 'lr': 1e-3,
                'weight_decay': 5e-4, 'momentum': 0.9},
            60: {'lr': 1e-2},
            120: {'lr': 1e-3},
            180: {'lr': 1e-4}
        }

    def forward(self, x):
        x = self.features(x)
        x = x.view(-1, 64 * 7 * 7)
        x = self.classifier(x)
        return F.log_softmax(x)

def cifar10_shallow(**kwargs):
    num_classes = getattr(kwargs, 'num_classes', 10)
    return AlexNet(num_classes)

def cifar100_shallow(**kwargs):
    num_classes = getattr(kwargs, 'num_classes', 100)
    return AlexNet(num_classes)

Written by Wei Wen. smoothout repository


来源: stackexchange

问:
PHP imap_open(), OpenSSL, and no Cipher
I have moved a PHP script to another server, and now fail to login to an IMAP (TLS) postbox:

```<code>TLS/SSL failure for mail.servername.de: SSL negotiation failed
</code>```

It seems that the problem is caused by OpenSSL, because when I try to connect to the Mailserver from both servers, I get a connection in one case (the mailserver asking for input), but none in the other (the connection is closed, I am back to bash):

```<code> openssl s_client -crlf -connect mail.servername.de:993
</code>```

The most obvious difference is here:

```<code>verify return:1
---

<snip>

-----END CERTIFICATE-----
subject=/CN=mail.servername.de
issuer=/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: DH, 1024 bits
---
SSL handshake has read 3398 bytes and written 483 bytes
Verification: OK
---
New, TLSv1.2, Cipher is DHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
</code>```

And on th other server (where no connection is made)

```<code>verify return:1
depth=0 CN = mail.servername.de
verify return:1
140410888582464:error:141A318A:SSL routines:tls_process_ske_dhe:dh key too small:../ssl/statem/statem_clnt.c:2149:
---

<snip>

-----END CERTIFICATE-----
subject=CN = mail.servername.de

issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3

---
No client certificate CA names sent
---
SSL handshake has read 3167 bytes and written 318 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Server public key is 2048 bit
</code>```

On the mailserver dovecot is configured not to accept non-encrypted connections. But, I assume it already fails due to dh key too small, which seems to relate to cipher negotiation.

Now I simply fail to put the things together... Why does the SSL connection work from one server, but not from the other?

答:
TL;DR: your new host has a newer version of OpenSSL probably with higher security settings which prohibit connecting to the host for reasons explained below.

"dh key too small" comes from OpenSSL and because of too low security.

Things changed, and for example in newest Debian versions and with OpenSSL 1.1.1 (and I guess it is similar for newer versions), the security was enhanced.

The best and simplest explanation I have found is on Debian wiki at https://wiki.debian.org/ContinuousIntegration/TriagingTips/openssl-1.1.1
which says:

In Debian the defaults are set to more secure values by default. This
  is done in the /etc/ssl/openssl.cnf config file. At the end of the
  file there is:

```<code>[system_default_sect]
MinProtocol = TLSv1.2
CipherString = DEFAULT@SECLEVEL=2
</code>```

This can results in errors such as:

```<code>dh key too small
ee key too small
ca md too weak
</code>```

Now the possible solutions in descending order of preference:

ask the remote end to generate better "DH" values ("Server Temp Key: DH, 1024 bits"); the best explanations are at https://weakdh.org/sysadmin.html; note specifically the "Administrators should use 2048-bit or stronger Diffie-Hellman groups with "safe" primes."

configure your end specifically for this connnection to not use the OS default and lower your settings; it should be enough to set ciphers to "DEFAULT@SECLEVEL=1" in the code that does the connection

(really, really, really not recommended) change the value of SECLEVEL from 2 to 1 in the global configuration file on your end. But this impacts all connections from your host not just this one so you are lowering the global security of your system just because of one low level of security from one remote node.

ContentLicense: CC BY-SA 4.0

Title: PHP imap_open(), OpenSSL, and no Cipher

Body:
I have moved a PHP script to another server, and now fail to login to an IMAP (TLS) postbox:

TLS/SSL failure for mail.servername.de: SSL negotiation failed

It seems that the problem is caused by OpenSSL, because when I try to connect to the Mailserver from both servers, I get a connection in one case (the mailserver asking for input), but none in the other (the connection is closed, I am back to bash):

 openssl s_client -crlf -connect mail.servername.de:993

The most obvious difference is here:

verify return:1
---

<snip>

-----END CERTIFICATE-----
subject=/CN=mail.servername.de
issuer=/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: DH, 1024 bits
---
SSL handshake has read 3398 bytes and written 483 bytes
Verification: OK
---
New, TLSv1.2, Cipher is DHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit

And on th other server (where no connection is made)

verify return:1
depth=0 CN = mail.servername.de
verify return:1
140410888582464:error:141A318A:SSL routines:tls_process_ske_dhe:dh key too small:../ssl/statem/statem_clnt.c:2149:
---

<snip>

-----END CERTIFICATE-----
subject=CN = mail.servername.de

issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3

---
No client certificate CA names sent
---
SSL handshake has read 3167 bytes and written 318 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Server public key is 2048 bit

On the mailserver dovecot is configured not to accept non-encrypted connections. But, I assume it already fails due to dh key too small, which seems to relate to cipher negotiation.

Now I simply fail to put the things together... Why does the SSL connection work from one server, but not from the other?

Body:
TL;DR: your new host has a newer version of OpenSSL probably with higher security settings which prohibit connecting to the host for reasons explained below.

"dh key too small" comes from OpenSSL and because of too low security.

Things changed, and for example in newest Debian versions and with OpenSSL 1.1.1 (and I guess it is similar for newer versions), the security was enhanced.

The best and simplest explanation I have found is on Debian wiki at https://wiki.debian.org/ContinuousIntegration/TriagingTips/openssl-1.1.1
which says:

In Debian the defaults are set to more secure values by default. This
  is done in the /etc/ssl/openssl.cnf config file. At the end of the
  file there is:

[system_default_sect]
MinProtocol = TLSv1.2
CipherString = DEFAULT@SECLEVEL=2

This can results in errors such as:

dh key too small
ee key too small
ca md too weak

Now the possible solutions in descending order of preference:

ask the remote end to generate better "DH" values ("Server Temp Key: DH, 1024 bits"); the best explanations are at https://weakdh.org/sysadmin.html; note specifically the "Administrators should use 2048-bit or stronger Diffie-Hellman groups with "safe" primes."

configure your end specifically for this connnection to not use the OS default and lower your settings; it should be enough to set ciphers to "DEFAULT@SECLEVEL=1" in the code that does the connection

(really, really, really not recommended) change the value of SECLEVEL from 2 to 1 in the global configuration file on your end. But this impacts all connections from your host not just this one so you are lowering the global security of your system just because of one low level of security from one remote node.


问:
MySQL EF 6 v 8.2.0 - Couldn't connect to update model
I've a solution in C# VS2017 in which I use MySQL EF6. When I updated MySQL packages from Nuget and MySql Connector to last version I started facing this errors:

From Server Explorers when trying to connect to all dbs:

When clicking update I see this:

When trying to update model from designer I have this output:

And these are my nuget packages

My App.config:

```<code>  <configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
   </configSections>

    <entityFramework>
      <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" />
      <providers>
          <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.20.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
         </providers>
     </entityFramework>
</code>```

答: It was an error on MySQL for Visual Studio. Has to remove and re install. After that, reopen VS.</p>

Body:
I've a solution in C# VS2017 in which I use MySQL EF6. When I updated MySQL packages from Nuget and MySql Connector to last version I started facing this errors:

From Server Explorers when trying to connect to all dbs:

When clicking update I see this:

When trying to update model from designer I have this output:

And these are my nuget packages

My App.config:

  <configSections>

   </configSections>

    <entityFramework>
      <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" />
      <providers>
          <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.20.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
         </providers>
     </entityFramework>


问:
Flutter: ListView.builder ignores BoxContrainst of Container child. Always applies full parent width
Building chat bubbles in a chat app. I am unable to control the width of ListView.builder's Container children. The child Containers always take the full width of the ListView.builders parent:
Expanded -> Container width.

What I'm trying to achieve: message bubble width as small as possible while still containing message text, but not larger than 75% of the screen width.

Ignore wrapping of text for this simplified example.

Where and why is the chatBubble getting this full screen width?

Super Simplified widget layout example:

```<code>@override
Widget build(BuildContext context) {
  return Container(
    height: safeHeight,
    child: Column(
      children: <Widget>[
        Expanded(
          child: ListView.builder(
            itemCount: messages.length,
            itemBuilder: (ctx, i) => chatBubble(messages[i]),
          )
        ),
        Container(
          height: 50,
          child: TextField(/* stuff */),
        )
      ]
    )
  );
}

chatBubble(Message msg) {
  return Padding(
    padding: EdgeInsets.all(8.0),
    child: Container(
      color: Colors.lightBlue,
      child: Text(msg.text),
      constraints: BoxConstraints(
        maxWidth: screenWidth * 0.75,
      ),
    )
  )
}
</code>```

RESULT:

答:
By default all the widgets inside a ListView are expanded, but you can use other widget to keep your content wrapped. If you will have more data in your chatBubble you can use a Column or a Wrap widget as follows:

```<code>  chatBubble(Message msg) {
    return Wrap(
      children: [
       Padding(
        ...
        ),
       ],
    );
  }
</code>```

But if you want to provide only one child in that section you can use an Align Widget, which lets you use an alignment property to decide how to align the child. In this case, try the next:

```<code> chatBubble(Message msg) {
    return Align(
      alignment: Alignment.centerRight,
      child: Padding(
        padding: EdgeInsets.all(8.0),
        child: ...
      ),
    );
  }
</code>```

Body:
Building chat bubbles in a chat app. I am unable to control the width of ListView.builder's Container children. The child Containers always take the full width of the ListView.builders parent:
Expanded -> Container width.

What I'm trying to achieve: message bubble width as small as possible while still containing message text, but not larger than 75% of the screen width.

Ignore wrapping of text for this simplified example.

Where and why is the chatBubble getting this full screen width?

Super Simplified widget layout example:

@override
Widget build(BuildContext context) {
  return Container(
    height: safeHeight,
    child: Column(
      children: <Widget>[
        Expanded(
          child: ListView.builder(
            itemCount: messages.length,
            itemBuilder: (ctx, i) => chatBubble(messages[i]),
          )
        ),
        Container(
          height: 50,
          child: TextField(/* stuff */),
        )
      ]
    )
  );
}

chatBubble(Message msg) {
  return Padding(
    padding: EdgeInsets.all(8.0),
    child: Container(
      color: Colors.lightBlue,
      child: Text(msg.text),
      constraints: BoxConstraints(
        maxWidth: screenWidth * 0.75,
      ),
    )
  )
}

RESULT:

Body:
By default all the widgets inside a ListView are expanded, but you can use other widget to keep your content wrapped. If you will have more data in your chatBubble you can use a Column or a Wrap widget as follows:

  chatBubble(Message msg) {
    return Wrap(
      children: [
       Padding(
        ...
        ),
       ],
    );
  }

But if you want to provide only one child in that section you can use an Align Widget, which lets you use an alignment property to decide how to align the child. In this case, try the next:

 chatBubble(Message msg) {
    return Align(
      alignment: Alignment.centerRight,
      child: Padding(
        padding: EdgeInsets.all(8.0),
        child: ...
      ),
    );
  }


问:
Unexpected auto deref behavior
when tried impl a double linked list in rust, i found below unexpected error

if let Some(link) = self.tail.take() {
    let x = link.borrow_mut();
    link.borrow_mut().next = Some(node.clone());
} else { ... }
```

<p>here link is inferred to be <code>Rc<RefCell<Node<..>>></code> and compiler says: </p>

<blockquote>
  <p>Cannot borrow immutable local variable <code>link</code> as mutable.</p>
</blockquote>

<p>After tried, I guess when <code>use std::borrow::BorrowMut</code>, the error occurs.</p>

<pre class="lang-rust prettyprint-override"><code>// compiles
fn test1() {
    let a = Rc::new(RefCell::new(1));
    let b = RefCell::new(1);
    b.borrow_mut();
    a.borrow_mut();
}

// doesn't compile
fn test2() {
    use std::borrow::BorrowMut; // inserted this import!

    let a = Rc::new(RefCell::new(1));
    let b = RefCell::new(1);
    b.borrow_mut();
    a.borrow_mut();
}
</code>```

here test2() fails to be compiled. I wanna know why it works this way.

答:
What you want to call is the method RefCell::borrow_mut().

However, a is a Rc and not a RefCell, so it has no borrow_mut method. This is where auto-dereferencing enters the picture. Because Rc<RefCell<T>> implements the Deref trait, it can be automatically dereferenced to a &RefCell<T> at method calls, and that's exactly what happens in the first test.

Now, if we import the BorrowMut trait, the test stops working. This is because the BorrowMut trait also has a method called borrow_mut, which is implemented for all types:

impl<T: ?Sized> BorrowMut<T> for T { ... }
```

This means that there is now a borrow_mut method available for Rc, so no auto-dereferencing occurs, and our code calls the wrong method.

The most comprehensive explanation of how auto-dereferencing works is in this SO answer.

Title: Unexpected auto deref behavior

Body:
when tried impl a double linked list in rust, i found below unexpected error

if let Some(link) = self.tail.take() {
    let x = link.borrow_mut();
    link.borrow_mut().next = Some(node.clone());
} else { ... }

here link is inferred to be Rc<RefCell<Node<..>>> and compiler says:

Cannot borrow immutable local variable link as mutable.

After tried, I guess when use std::borrow::BorrowMut, the error occurs.

// compiles
fn test1() {
    let a = Rc::new(RefCell::new(1));
    let b = RefCell::new(1);
    b.borrow_mut();
    a.borrow_mut();
}

// doesn't compile
fn test2() {
    use std::borrow::BorrowMut; // inserted this import!

    let a = Rc::new(RefCell::new(1));
    let b = RefCell::new(1);
    b.borrow_mut();
    a.borrow_mut();
}

here test2() fails to be compiled. I wanna know why it works this way.

Body:
What you want to call is the method RefCell::borrow_mut().

However, a is a Rc and not a RefCell, so it has no borrow_mut method. This is where auto-dereferencing enters the picture. Because Rc<RefCell<T>> implements the Deref trait, it can be automatically dereferenced to a &RefCell<T> at method calls, and that's exactly what happens in the first test.

Now, if we import the BorrowMut trait, the test stops working. This is because the BorrowMut trait also has a method called borrow_mut, which is implemented for all types:

impl<T: ?Sized> BorrowMut<T> for T { ... }

This means that there is now a borrow_mut method available for Rc, so no auto-dereferencing occurs, and our code calls the wrong method.

The most comprehensive explanation of how auto-dereferencing works is in this SO answer.


问:
How to terminate process with loop function?
I write one module, which has one loop function, the function will send udp packet forever. i debug the program in erlang console, I want to know how to close the UDP socket ?
or else erlang will always print the debug message in console. thanks!</p>

```<code>start() ->
  {ok, Sock} = gen_udp:open(0, []),
  send(Sock).

send(Sock) ->
  gen_udp:send(Sock, "127.0.0.1", 3211, "hello world"),
  timer:sleep(5000),
  send(Sock).
</code>```

答:
There are two things to be considered here

If the process is the owner of
the socket.In that case you can
directly use gen_udp:close(Sock).

If the process is not the owner of the socket then use
gen_udp:controlling_process(Sock,Pid)
where Pid is the process id of the
new owner of the socket. Now you can
use gen_udp:close(Sock) from this
process. http://www.erlang.org/doc/man/gen_udp.html

ContentLicense: CC BY-SA 3.0

Body:
I write one module, which has one loop function, the function will send udp packet forever. i debug the program in erlang console, I want to know how to close the UDP socket ?
or else erlang will always print the debug message in console. thanks!

start() ->
  {ok, Sock} = gen_udp:open(0, []),
  send(Sock).

send(Sock) ->
  gen_udp:send(Sock, "127.0.0.1", 3211, "hello world"),
  timer:sleep(5000),
  send(Sock).


问:
How to protect a client side JavaScript variable?
Using the following function to check the existence of a given URL. The code is executed on the client side (browser), is there a way (if at all possible) to protect the url variable from being altered with the browser debugger while keeping the function on the client side?

Note that the url variable is generated by the server and set on the JS script (client side)

```<code>function UrlExists(url, callback)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url);
    http.onreadystatechange = function() {
        if (this.readyState == this.DONE) {
            callback(this.status != 404);
        }
    };
    http.send();
}
</code>```

Function source.

答:
No.

The code runs in the browser. The browser is completely under the control of the user. JavaScript is pretty easy to deobfuscate.

Body:
Using the following function to check the existence of a given URL. The code is executed on the client side (browser), is there a way (if at all possible) to protect the url variable from being altered with the browser debugger while keeping the function on the client side?

Note that the url variable is generated by the server and set on the JS script (client side)

function UrlExists(url, callback)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url);
    http.onreadystatechange = function() {
        if (this.readyState == this.DONE) {
            callback(this.status != 404);
        }
    };
    http.send();
}

Function source.


问:
How to Update data and Add new rows
I have the Invoice form so sometime I want to update the data of the same Invoice number and add now rows.

I want to update the data  and new rows on the same Invoice No, on my code below is update and add one row instead of add more than one rows which i have selected.

supposed the invoice has one row and i want to update by add 10 rows on that Invoice number, so the code below is works but it update one row and add 1 new row instead of 10(news rows).

My controller of update

```<code>public function update(Request $request, $inv_no)
{

$data = $request->all();

$date = date ("Y-m-d",  strtotime($request->Indate));

$stocks = Stock::where('inv_no', $inv_no)->get();
$i = 0;

foreach ($stocks as $stock) {
    Stock::where('inv_no', $inv_no)
        ->where('id', $stock->id)
        ->update([
            'pid' => $request->pid[$i],
            'qty' => $request->qty[$i],
            'user_id' => Auth::user()->id,
            'Indate'=>$date ,
            'supplierName' => $request->supplierName,
            'receiptNumber' => $request->receiptNumber,
            'truckNumber' => $request->truckNumber[$i],
            'driverName' => $request->driverName,
            'remark' => $request->remark,
        ]);

             $i++;
    }

    $totalPid = count($data['pid']);
    $totalQty = count($data['qty']);
    $totalTruckNumber = count($data['truckNumber']);
 // dd($stocks);

    if (count($stocks) < $totalPid) {
        Stock::create([
            'pid' => $request->pid[$totalPid-1],
            'qty' => $request->qty[$totalQty-1],
            'inv_no' => $request->inv_no,
            'user_id' => Auth::user()->id,
            'Indate'=>$date,
            'supplierName' => $request->supplierName,
            'receiptNumber' => $request->receiptNumber,
            'truckNumber' => $request->truckNumber[$totalTruckNumber-1],
            'driverName' => $request->driverName,
            'remark' => $request->remark,
        ]);
    }

return  $this->show($inv_no)->with('success', 'GRN  Edited Successfully ');
</code>```

}

below is the Invoice form which i want to Update and Add new rows.

So I need the help what can i Add there to update and able to add more rows.

答:
I am really sorry if i got wrong but why don't you put them in loop if you want more than one.</p>

```<code>    for($i=0;$i<$how_many_row_should_add;$i++){
if (count($stocks) < $totalPid) {
    Stock::create([
        'pid' => $request->pid[$totalPid-1],
        'qty' => $request->qty[$totalQty-1],
        'inv_no' => $request->inv_no,
        'user_id' => Auth::user()->id,
        'Indate'=>$date,
        'supplierName' => $request->supplierName,
        'receiptNumber' => $request->receiptNumber,
        'truckNumber' => $request->truckNumber[$totalTruckNumber-1],
        'driverName' => $request->driverName,
        'remark' => $request->remark,
    ]);
}
    }
</code>```

Title: How to Update data and Add new rows

Body:
I have the Invoice form so sometime I want to update the data of the same Invoice number and add now rows.

I want to update the data  and new rows on the same Invoice No, on my code below is update and add one row instead of add more than one rows which i have selected.

supposed the invoice has one row and i want to update by add 10 rows on that Invoice number, so the code below is works but it update one row and add 1 new row instead of 10(news rows).

My controller of update

public function update(Request $request, $inv_no)
{

$data = $request->all();

$date = date ("Y-m-d",  strtotime($request->Indate));

$stocks = Stock::where('inv_no', $inv_no)->get();
$i = 0;

foreach ($stocks as $stock) {
    Stock::where('inv_no', $inv_no)
        ->where('id', $stock->id)
        ->update([
            'pid' => $request->pid[$i],
            'qty' => $request->qty[$i],
            'user_id' => Auth::user()->id,
            'Indate'=>$date ,
            'supplierName' => $request->supplierName,
            'receiptNumber' => $request->receiptNumber,
            'truckNumber' => $request->truckNumber[$i],
            'driverName' => $request->driverName,
            'remark' => $request->remark,
        ]);

             $i++;
    }

    $totalPid = count($data['pid']);
    $totalQty = count($data['qty']);
    $totalTruckNumber = count($data['truckNumber']);
 // dd($stocks);

    if (count($stocks) < $totalPid) {
        Stock::create([
            'pid' => $request->pid[$totalPid-1],
            'qty' => $request->qty[$totalQty-1],
            'inv_no' => $request->inv_no,
            'user_id' => Auth::user()->id,
            'Indate'=>$date,
            'supplierName' => $request->supplierName,
            'receiptNumber' => $request->receiptNumber,
            'truckNumber' => $request->truckNumber[$totalTruckNumber-1],
            'driverName' => $request->driverName,
            'remark' => $request->remark,
        ]);
    }

return  $this->show($inv_no)->with('success', 'GRN  Edited Successfully ');

}

below is the Invoice form which i want to Update and Add new rows.

So I need the help what can i Add there to update and able to add more rows.

Body:
I am really sorry if i got wrong but why don't you put them in loop if you want more than one.

    for($i=0;$i<$how_many_row_should_add;$i++){
if (count($stocks) < $totalPid) {
    Stock::create([
        'pid' => $request->pid[$totalPid-1],
        'qty' => $request->qty[$totalQty-1],
        'inv_no' => $request->inv_no,
        'user_id' => Auth::user()->id,
        'Indate'=>$date,
        'supplierName' => $request->supplierName,
        'receiptNumber' => $request->receiptNumber,
        'truckNumber' => $request->truckNumber[$totalTruckNumber-1],
        'driverName' => $request->driverName,
        'remark' => $request->remark,
    ]);
}
    }


问:
Toolkit.getImage(URL url) works with Java 8 but fails with Java 11
I'm having a problem with a Java SE Swing application. It compiles fine on both Java 8 and 11, but it fails on the latter in these lines:

```<code>    URL url = Object.class.getResource("/org/mozillatranslator/resource/mt_icon_small.gif");
    Toolkit tk = Toolkit.getDefaultToolkit();

    Image img = tk.getImage(url); // Raises runtime exception
</code>```

with this exception:

```<code>Caused by: java.lang.NullPointerException
    at java.desktop/sun.awt.SunToolkit.getImageFromHash(SunToolkit.java:653)
    at java.desktop/sun.awt.SunToolkit.getImage(SunToolkit.java:689)
    at org.mozillatranslator.gui.MainWindow.loadIcon(MainWindow.java:232)
</code>```

As I've said, the line works on Java 8, but fails on Java 11 with the exact same JAR. I've searched for a change in Java behavior in versions beyond 8, but I haven't found anything. Has anyone suffered a similar situation, or can suggest any possible workarounds?

答:
Use

```<code>URL url = <YourClassName>.class.getResource("/org/mozillatranslator/resource/mt_icon_small.gif");
</code>```

or

```<code>URL url = Thread.currentThread()
    .getContextClassLoader()
    .getResource("org/mozillatranslator/resource/mt_icon_small.gif");
</code>```

Object is loaded by bootstrap class loader, so Object.class.getResource() uses system class loader.

Check return values with empty string parameter; Object.class.getResource(""), YourClass.class.getResource(""), and Thread.currentThread().getContextClassLoader().getResource("").

Body:
I'm having a problem with a Java SE Swing application. It compiles fine on both Java 8 and 11, but it fails on the latter in these lines:

    URL url = Object.class.getResource("/org/mozillatranslator/resource/mt_icon_small.gif");
    Toolkit tk = Toolkit.getDefaultToolkit();

    Image img = tk.getImage(url); // Raises runtime exception

with this exception:

Caused by: java.lang.NullPointerException
    at java.desktop/sun.awt.SunToolkit.getImageFromHash(SunToolkit.java:653)
    at java.desktop/sun.awt.SunToolkit.getImage(SunToolkit.java:689)
    at org.mozillatranslator.gui.MainWindow.loadIcon(MainWindow.java:232)

As I've said, the line works on Java 8, but fails on Java 11 with the exact same JAR. I've searched for a change in Java behavior in versions beyond 8, but I haven't found anything. Has anyone suffered a similar situation, or can suggest any possible workarounds?

Body:
Use

URL url = <YourClassName>.class.getResource("/org/mozillatranslator/resource/mt_icon_small.gif");

or

URL url = Thread.currentThread()
    .getContextClassLoader()
    .getResource("org/mozillatranslator/resource/mt_icon_small.gif");

Object is loaded by bootstrap class loader, so Object.class.getResource() uses system class loader.

Check return values with empty string parameter; Object.class.getResource(""), YourClass.class.getResource(""), and Thread.currentThread().getContextClassLoader().getResource("").


问:
Stop ajax loader on ajax success callback
I am using ajax loadmore pagination which works fine on localhost, but I am considering my method not applicable to live host.
This is what i am doing:

     $(".button").click(function(){
       setTimout(function(){
         $('#loader').show();
         $.ajax({
           //ajax stuffs
           success:function(data){
             $("loadmore").append(data).
           }
         });
       } ,2000);
     });
```

<p>Technically speaking to me this is just taking 2 seconds to do what is inside the setTimeout function which is not right for user experience on the live server as ajax would be calling after 2 seconds.</p>

<p>What I want:</p>

<p>Let ajax call be made while the loader icon is loading. once the call is made successfully then the loader icon should stop and loadmore data should be appended.</p>

<p>Something like this:</p>

<pre class="lang-js prettyprint-override"><code>$(".button").click(function(){
   $("#loader").show()
   $.ajax({
     //ajax stuffs
     success:function(data){
     }
   });
   if(success is finished){
     $("#loader").hide()
     $("#loadmore").append(data)
   }
 });
</code>```

Please how can I achieve that, thanks

答:
Would this work for you?</p>

```<code>$(".button").click(function(){
  $("#loader").show()
  $.ajax({
    //ajax stuffs
    success:function(data){
    }
  })
  .done(function (data) {
    $("#loader").hide();
    $("#loadmore").append(data);
  }).fail(function (jqXHR, textStatus) {
      // do something
  })
});
</code>```

Body:
I am using ajax loadmore pagination which works fine on localhost, but I am considering my method not applicable to live host.
This is what i am doing:

     $(".button").click(function(){
       setTimout(function(){
         $('#loader').show();
         $.ajax({
           //ajax stuffs
           success:function(data){
             $("loadmore").append(data).
           }
         });
       } ,2000);
     });

Technically speaking to me this is just taking 2 seconds to do what is inside the setTimeout function which is not right for user experience on the live server as ajax would be calling after 2 seconds.

What I want:

Let ajax call be made while the loader icon is loading. once the call is made successfully then the loader icon should stop and loadmore data should be appended.

Something like this:

$(".button").click(function(){
   $("#loader").show()
   $.ajax({
     //ajax stuffs
     success:function(data){
     }
   });
   if(success is finished){
     $("#loader").hide()
     $("#loadmore").append(data)
   }
 });

Please how can I achieve that, thanks

Body:
Would this work for you?

$(".button").click(function(){
  $("#loader").show()
  $.ajax({
    //ajax stuffs
    success:function(data){
    }
  })
  .done(function (data) {
    $("#loader").hide();
    $("#loadmore").append(data);
  }).fail(function (jqXHR, textStatus) {
      // do something
  })
});


问:
Enums in typescript d.ts file
I'm new to Typescript and I'm using it in a create-react-project. I have a folder called /typings which my tsconfig.json file points to and so far I've put all my type declarations in an index.d.ts file in that folder.

So far so good. "type" and "interface" declarations seem to be available in all parts of my project. I'm not explicitly exporting them from the index.d.ts file and not importing them into any other file.

The problem comes when I declare the following...

```<code>enum Gender {male, female}
</code>```

When I try to use the enum in a different file I get the error...

```<code>Ambient const enums are not allowed when the '--isolatedModules' flag is provided
</code>```

I have read other answers on SO which say you should declare the enum as a const but that doesn't help. I've also seen the suggestion that you should "export defualt undefined" at the bottom of the file but when I do that none of the other types are available in the rest of the project.

Lastly, I have tried changing my compiler options to set "isolatedModules": false but it automatically gets switched back to true when compiling. Apparently create-react-app will always do thi.

What should I do to allow enums declared in my index.d.ts file to be available to use in the rest of my project automatically?

答:
Enums can't go into a d.ts.

Reason for this is that enums have a compiled output, where as other .d.ts such as interfaces do not.

For example:

```<code>enum Hello{
    One = 'This is one',
    Two = ''
}
</code>```

compiles to:

```<code>"use strict";
var Hello;
(function (Hello) {
    Hello["One"] = "This is one";
    Hello["Two"] = "";
})(Hello || (Hello = {}));
</code>```

whereas an interface:

```<code>interface Hello {
    test: string;
}
</code>```

compiles to:

```<code>// an empty file, as interfaces are only used during pre-compile not in Javascript.
</code>```

.d.ts files are not explicitly imported into files and so as a result, Typescript does not know where to inject this file contents. As you are most likely aware, Javascript is compiled top to bottom, so where that enum is injected into the output Javascript is critical.

We historically put our enums into a common.ts file & class that we import when you require to use an enum.

Title: Enums in typescript d.ts file

Body:
I'm new to Typescript and I'm using it in a create-react-project. I have a folder called /typings which my tsconfig.json file points to and so far I've put all my type declarations in an index.d.ts file in that folder.

So far so good. "type" and "interface" declarations seem to be available in all parts of my project. I'm not explicitly exporting them from the index.d.ts file and not importing them into any other file.

The problem comes when I declare the following...

enum Gender {male, female}

When I try to use the enum in a different file I get the error...

Ambient const enums are not allowed when the '--isolatedModules' flag is provided

I have read other answers on SO which say you should declare the enum as a const but that doesn't help. I've also seen the suggestion that you should "export defualt undefined" at the bottom of the file but when I do that none of the other types are available in the rest of the project.

Lastly, I have tried changing my compiler options to set "isolatedModules": false but it automatically gets switched back to true when compiling. Apparently create-react-app will always do thi.

What should I do to allow enums declared in my index.d.ts file to be available to use in the rest of my project automatically?

Body:
Enums can't go into a d.ts.

Reason for this is that enums have a compiled output, where as other .d.ts such as interfaces do not.

For example:

enum Hello{
    One = 'This is one',
    Two = ''
}

compiles to:

"use strict";
var Hello;
(function (Hello) {
    Hello["One"] = "This is one";
    Hello["Two"] = "";
})(Hello || (Hello = {}));

whereas an interface:

interface Hello {
    test: string;
}

compiles to:

// an empty file, as interfaces are only used during pre-compile not in Javascript.

.d.ts files are not explicitly imported into files and so as a result, Typescript does not know where to inject this file contents. As you are most likely aware, Javascript is compiled top to bottom, so where that enum is injected into the output Javascript is critical.

We historically put our enums into a common.ts file & class that we import when you require to use an enum.


问:
How to properly document class' static variables?
What is the preferred way to document static variables in classes?

```<code>class Foo(object):
    """
    Foo doc.
    """

    bar = 'bar'
    """
    Bar doc.
    """

class Foo(object):
    """
    Foo doc.
    """

    # Bar doc.
    bar = 'bar'
</code>```

Something else...?

答:
I personally use the Google-style DocString format and my approach to static attributes is to include them in the class' DocString.

E.g.

```<code>class Bicycle:
    """
    A class defining a Bicycle

    Attributes:
        NUM_WHEELS (int): The number of wheels that a bicycle has: 2.
    """
    NUM_WHEELS = 2
</code>```

This is definitely an opinionated topic though. Depending on how visible you want your attributes to be, it might also make sense to just document them using a normal comment above the attribute's definition. E.g.

```<code>class Bicycle:
    """
    A class defining a Bicycle
    """
    # The number of wheels that a bicycle has
    NUM_WHEELS = 2
</code>```

Body:
What is the preferred way to document static variables in classes?

class Foo(object):
    """
    Foo doc.
    """

    bar = 'bar'
    """
    Bar doc.
    """

class Foo(object):
    """
    Foo doc.
    """

    # Bar doc.
    bar = 'bar'

Something else...?

Body:
I personally use the Google-style DocString format and my approach to static attributes is to include them in the class' DocString.

E.g.

class Bicycle:
    """
    A class defining a Bicycle

    Attributes:
        NUM_WHEELS (int): The number of wheels that a bicycle has: 2.
    """
    NUM_WHEELS = 2

This is definitely an opinionated topic though. Depending on how visible you want your attributes to be, it might also make sense to just document them using a normal comment above the attribute's definition. E.g.

class Bicycle:
    """
    A class defining a Bicycle
    """
    # The number of wheels that a bicycle has
    NUM_WHEELS = 2


问:
responsivevoice - I have to read the text inside the html element to the sound robot
responsivevoice .org
I couldn't do the text voice over service as I wanted.
There is no detailed explanation on the website.

I don't want to use < textarea > The example I want to use. I don't want to choose a robot. It should only speak Turkish Male. How should I do this?

```<code><div id = "text-read"> one two tree four five </div>

<button onclick="responsiveVoice.speak('text-read');" type="button" value="Play">Play</button>
</code>```

I want it to read the contents with the button.
Thank you for your interest

resources:

https://responsivevoice.org/api

https://responsivevoice.org/text-to-speech-sdk/text-to-speech-play-button

https://responsivevoice.org/text-to-speech-sdk/text-to-speech-widget

答:
```<code><script src="https://code.responsivevoice.org/responsivevoice.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
    <!-- Turkish  Man Or Women Voice -->
    var element = document.getElementById('#erkekoku');
    var text = element.innerText || element.textContent;
    element.innerHTML = erkekoku;

    var element = document.getElementById('#erkekoku');
    var text = element.innerText;

    function manspeak(obj) {
    responsiveVoice.speak($('#erkekoku').text(), 'Turkish Male');
    };
    </script>

    <div id="erkekoku">Bu metni seslendirdim.</div>
    <button class="btn btn-primary" onclick="manspeak('article')">Play</button>
</code>```

Body:
responsivevoice .org
I couldn't do the text voice over service as I wanted.
There is no detailed explanation on the website.

I don't want to use < textarea > The example I want to use. I don't want to choose a robot. It should only speak Turkish Male. How should I do this?

 one two tree four five

<button onclick="responsiveVoice.speak('text-read');" type="button" value="Play">Play</button>

I want it to read the contents with the button.
Thank you for your interest

resources:

https://responsivevoice.org/api

https://responsivevoice.org/text-to-speech-sdk/text-to-speech-play-button

https://responsivevoice.org/text-to-speech-sdk/text-to-speech-widget


问:
Doubly linked list - Update list->tail after a merge sort
In an implementation of a doubly linked list I am using the typical structure:

```<code>struct node
{
    void *data;
    struct node *prev;
    struct node *next;
};
</code>```

I will also insert at the end of the list in O(1) time, so I have another struct storing the head and the tail:

```<code>struct linklist
{
    struct node *head;
    struct node *tail;
    size_t size;
};
</code>```

The program works as expected for all insert and delete operations, but I have a problem with the sort function, I am using the merge-sort algorithm, as I understand it is the most effective or one of the most effective to sort lists, the algorithm works well:

```<code>static struct node *split(struct node *head)
{
    struct node *fast = head;
    struct node *slow = head;

    while ((fast->next != NULL) && (fast->next->next != NULL))
    {
        fast = fast->next->next;
        slow = slow->next;
    }

    struct node *temp = slow->next;

    slow->next = NULL;
    return temp;
}

static struct node *merge(struct node *first, struct node *second, int (*comp)(const void *, const void *))
{
    if (first == NULL)
    {
        return second;
    }
    if (second == NULL)
    {
        return first;
    }
    if (comp(first->data, second->data) < 0)
    {
        first->next = merge(first->next, second, comp);
        first->next->prev = first;
        first->prev = NULL;
        return first;
    }
    else
    {
        second->next = merge(first, second->next, comp);
        second->next->prev = second;
        second->prev = NULL;
        return second;
    }
}

static struct node *merge_sort(struct node *head, int (*comp)(const void *, const void *))
{
    if ((head == NULL) || (head->next == NULL))
    {
        return head;
    }

    struct node *second = split(head);

    head = merge_sort(head, comp);
    second = merge_sort(second, comp);
    return merge(head, second, comp);
}
</code>```

but I have no idea how to keep the address of list->tail updated:

```<code>void linklist_sort(struct linklist *list, int (*comp)(const void *, const void *))
{
    list->head = merge_sort(list->head, comp);
    // list->tail is no longer valid at this point
}
</code>```

Sure I can walk the whole list after ordering and update list->tail by brute force, but I'd like to know if there's a fancier way to do it.

I managed to solve the problem using a circular list, but I would like to avoid changing the structure of the program.

答:
One option is to merge sort the nodes as if they were single list nodes, then make a one time pass when done to set the previous pointers, and update the tail pointer.

Another option would use something similar to C++ std::list and std::list::sort. A circular doubly linked list is used. There is one dummy node that uses "next" as "head" and "prev" as "tail". The parameters to merge sort and merge are iterators or pointers, and only used to keep track of run boundaries, as nodes are merged by moving them within the original list. The merge function merges nodes from a second run into the first run, using std::list::splice. The logic is if first run element is less than or equal to second run element, just advance the iterator or pointer to the first run, else remove the node from the second run and insert it before the current node in the first run. This will automatically update the head and tail pointers in the dummy node if involved in a remove + insert step.

Changing struct node to :

```<code>struct node
{
    struct node *next;           // used as head for dummy node
    struct node *prev;           // used as tail for dummy node
    void *data;
};
</code>```

would be a bit more generic.

Since the dummy node is allocated when a list is created, then begin == dummy->next, last == dummy-> prev, and end == dummy.

Body:
In an implementation of a doubly linked list I am using the typical structure:

struct node
{
    void *data;
    struct node *prev;
    struct node *next;
};

I will also insert at the end of the list in O(1) time, so I have another struct storing the head and the tail:

struct linklist
{
    struct node *head;
    struct node *tail;
    size_t size;
};

The program works as expected for all insert and delete operations, but I have a problem with the sort function, I am using the merge-sort algorithm, as I understand it is the most effective or one of the most effective to sort lists, the algorithm works well:

static struct node *split(struct node *head)
{
    struct node *fast = head;
    struct node *slow = head;

    while ((fast->next != NULL) && (fast->next->next != NULL))
    {
        fast = fast->next->next;
        slow = slow->next;
    }

    struct node *temp = slow->next;

    slow->next = NULL;
    return temp;
}

static struct node *merge(struct node *first, struct node *second, int (*comp)(const void *, const void *))
{
    if (first == NULL)
    {
        return second;
    }
    if (second == NULL)
    {
        return first;
    }
    if (comp(first->data, second->data) < 0)
    {
        first->next = merge(first->next, second, comp);
        first->next->prev = first;
        first->prev = NULL;
        return first;
    }
    else
    {
        second->next = merge(first, second->next, comp);
        second->next->prev = second;
        second->prev = NULL;
        return second;
    }
}

static struct node *merge_sort(struct node *head, int (*comp)(const void *, const void *))
{
    if ((head == NULL) || (head->next == NULL))
    {
        return head;
    }

    struct node *second = split(head);

    head = merge_sort(head, comp);
    second = merge_sort(second, comp);
    return merge(head, second, comp);
}

but I have no idea how to keep the address of list->tail updated:

void linklist_sort(struct linklist *list, int (*comp)(const void *, const void *))
{
    list->head = merge_sort(list->head, comp);
    // list->tail is no longer valid at this point
}

Sure I can walk the whole list after ordering and update list->tail by brute force, but I'd like to know if there's a fancier way to do it.

I managed to solve the problem using a circular list, but I would like to avoid changing the structure of the program.

Body:
One option is to merge sort the nodes as if they were single list nodes, then make a one time pass when done to set the previous pointers, and update the tail pointer.

Another option would use something similar to C++ std::list and std::list::sort. A circular doubly linked list is used. There is one dummy node that uses "next" as "head" and "prev" as "tail". The parameters to merge sort and merge are iterators or pointers, and only used to keep track of run boundaries, as nodes are merged by moving them within the original list. The merge function merges nodes from a second run into the first run, using std::list::splice. The logic is if first run element is less than or equal to second run element, just advance the iterator or pointer to the first run, else remove the node from the second run and insert it before the current node in the first run. This will automatically update the head and tail pointers in the dummy node if involved in a remove + insert step.

Changing struct node to :

struct node
{
    struct node *next;           // used as head for dummy node
    struct node *prev;           // used as tail for dummy node
    void *data;
};

would be a bit more generic.

Since the dummy node is allocated when a list is created, then begin == dummy->next, last == dummy-> prev, and end == dummy.


问:
How to specify / select a particular property of an object
I am creating a react web app. My state in my parent component is an array of objects (one to many number of objects stored in this array...it could be any number of objects). I want to send object X of the array through to my child component through props. Here is my child component:

```<code>import React, { Component } from 'react'

export class Card extends Component {

    render() {
        console.log('in card');
        console.log(this.props.newCard);
        return (
            <div>
                <h2>Here is a card!</h2>

            </div>
        )
    }
}

export default Card
</code>```

For necessary context, here is my render method in the parent component that calls the child (named Card):

```<code>render() {
        return (
            <div>
                <Card newCard={this.state.cardList[this.state.eachCard]}></Card>
                <button>Next</button>
            </div>
        )
    }
</code>```

The this.state.eachCard is just referring to an accumulator I will later implement to go through each object of the array upon clicking the Next button. Right now it is just set to position 0 for testing purposes.

When I console.log the newCard prop in the child component, this is the structure of the object that is send from parent to child:

```<code>{CardID: 3, CardName: "test", CardDefinition: "testing", category_CategoryID: 2}
</code>```

However, I am wanting to specify a particular property of this object. For example, I want to retrieve the name of the card. However, when I tried to console.log this

```<code>console.log(this.props.newCard.CardName);
</code>```

I received the following error:

```<code>"Cannot read property 'CardName' of undefined"
</code>```

This does not make sense to me, as this.props.newCard was not undefined. Therefore it would make sense to me that specifying the newCard prop one more degree to newCard.CardName should logically work. I cannot figure out what I am missing. Is this some sort of syntax error? Or is my logic just totally off?
I seem to be very close, but am hung up on how to proceed...any ideas sure would be appreciated. Thanks!!

答:
A good first step would be to guard against undefined here. I'm not sure what the rest of your code looks like but if there's some async happening somewhere it's possible on first render that the prop is undefined. When you pass undefined in to console.log it doesn't log anything so if this component is indeed getting rendered twice then you'd get no log for the first render. A great way to test this theory is to do your console log like the following:

console.log('newCard', this.props.newCard);

You can also guard against undefined here so it won't throw an error by returning null if this.props.newCard is in fact undefined.

```<code>
export class Card extends Component {

    render() {
        if (this.props.newCard === undefined) {
          return null;
        }
        return (
            <div>
                <h2>Here is a card!</h2>

            </div>
        )
    }
}

export default Card
</code>```

Edit due to additional context.

The way you render items in an array as children in react is using the map method of the array object and passing in a component to the callback:

```<code>        return (
            <div>
                {
                  this.state.cardList.map(eachCard => (<Card newCard={eachCard} />))
                }
                <button>Next</button>
            </div>
        )
    }
</code>```

Body:
I am creating a react web app. My state in my parent component is an array of objects (one to many number of objects stored in this array...it could be any number of objects). I want to send object X of the array through to my child component through props. Here is my child component:

import React, { Component } from 'react'

export class Card extends Component {

    render() {
        console.log('in card');
        console.log(this.props.newCard);
        return (

Here is a card!

        )
    }
}

export default Card

For necessary context, here is my render method in the parent component that calls the child (named Card):

render() {
        return (

                <Card newCard={this.state.cardList[this.state.eachCard]}></Card>
                <button>Next</button>

        )
    }

The this.state.eachCard is just referring to an accumulator I will later implement to go through each object of the array upon clicking the Next button. Right now it is just set to position 0 for testing purposes.

When I console.log the newCard prop in the child component, this is the structure of the object that is send from parent to child:

{CardID: 3, CardName: "test", CardDefinition: "testing", category_CategoryID: 2}

However, I am wanting to specify a particular property of this object. For example, I want to retrieve the name of the card. However, when I tried to console.log this

console.log(this.props.newCard.CardName);

I received the following error:

"Cannot read property 'CardName' of undefined"

This does not make sense to me, as this.props.newCard was not undefined. Therefore it would make sense to me that specifying the newCard prop one more degree to newCard.CardName should logically work. I cannot figure out what I am missing. Is this some sort of syntax error? Or is my logic just totally off?
I seem to be very close, but am hung up on how to proceed...any ideas sure would be appreciated. Thanks!!

Body:
A good first step would be to guard against undefined here. I'm not sure what the rest of your code looks like but if there's some async happening somewhere it's possible on first render that the prop is undefined. When you pass undefined in to console.log it doesn't log anything so if this component is indeed getting rendered twice then you'd get no log for the first render. A great way to test this theory is to do your console log like the following:

console.log('newCard', this.props.newCard);

You can also guard against undefined here so it won't throw an error by returning null if this.props.newCard is in fact undefined.

export class Card extends Component {

    render() {
        if (this.props.newCard === undefined) {
          return null;
        }
        return (
            <div>
                <h2>Here is a card!</h2>

            </div>
        )
    }
}

export default Card

Edit due to additional context.

The way you render items in an array as children in react is using the map method of the array object and passing in a component to the callback:

        return (
            <div>
                {
                  this.state.cardList.map(eachCard => (<Card newCard={eachCard} />))
                }
                <button>Next</button>
            </div>
        )
    }


问:
How to add image to Facebook post without getting the image twice in the feed?
I am trying to make a post to a Facebook page using the Graph API that includes an image. I have successfully done it with a two step process:

Post to 'https://graph.facebook.com/PAGE_ID/photos?url=IMAGE_URL&access_token=ACCESS_TOKEN'

Taking the image id from the return data from the post and making another post to 'https://graph.facebook.com/PAGE_ID/feed?published=true&message=MESSAGE_TEXT&object_attachment=IMAGE_ID&fields=permalink_url&access_token=ACCESS_TOKEN'

However, when I do that, FB posts the image to the page first and then posts the message with the image in it. Not ideal; I only want a single post with message and image.

I then tried keeping the image unpublished (adding &published=false to my image post). That worked to keep the image from posting on the page and I got an OK message with the image id back from FB. However, I received an error code (1 - "An unknown error occurred") from the FB API when I went to post the message with image.

I also tried to keep the image unpublished and flag that as temporary (adding &published=false&temporary=true to my image post) with the same result.

Anyone know how to post a message with image to a page without first posting the image to the FB page?

答:
You can add a caption to your image post.

Or add the image as form data while creating the post.

Which Framework do you use?


问:
In Memory Database
I'm using SqlServer to drive a WPF application, I'm currently using NHibernate and pre-read all the data so it's cached for performance reasons. That works for a single client app, but I was wondering if there's an in memory database that I could use so I can share the information across multiple apps on the same machine. Ideally this would sit below my NHibernate stack, so my code wouldn't have to change. Effectively I'm looking to move my DB from it's traditional format on the server to be an in memory DB on the client.

Note I only need select functionality.

答:
I would be incredibly surprised if you even need to load all your information in memory.  I say this because, just as one example, I'm working on a Web app at the moment that (for various reasons) loads thousands of records on many pages.  This is PHP + MySQL.  And even so it can do it and render a page in well under 100ms.

Before you go down this route make sure that you have to.  First make your database as performant as possible.  Now obviously this includes things like having appropriate indexes and tuning your database but even though are putting the horse before the cart.

First and foremost you need to make sure you have a good relational data model: one that lends itself to performant queries.  This is as much art as it is science.

Also, you may like NHibernate but ORMs are not always the best choice.  There are some corner cases, for example, that hand-coded SQL will be vastly superior in.

Now assuming you have a good data model and assuming you've then optimized your indexes and database parameters and then you've properly configured NHibernate, then and only then should you consider storing data in memory if and only if performance is still an issue.

To put this in perspective, the only times I've needed to do this are on systems that need to perform millions of transactions per day.

One reason to avoid in-memory caching is because it adds a lot of complexity.  You have to deal with issues like cache expiry, independent updates to the underlying data store, whether you use synchronous or asynchronous updates, how you give the client a consistent (if not up-to-date) view of your data, how you deal with failover and replication and so on.  There is a huge complexity cost to be paid.

Assuming you've done all the above and you still need it, it sounds to me like what you need is a cache or grid solution.  Here is an overview of Java grid/cluster solutions but many of them (eg Coherence, memcached) apply to .Net as well.  Another choice for .Net is Velocity.

It needs to be pointed out and stressed that something like NHibernate is only consistent so long as nothing externally updates the database and that there is exactly one NHibernate-enabled process (barring clustered solutions).  If two desktop apps on two different PCs are both updating the same database with NHibernate the caching simply won't work because the persistence units simply won't be aware of the changes the other is making.

OwnerDisplayName: MrTelly

ContentLicense: CC BY-SA 2.5

Title: In Memory Database

LastEditorDisplayName: MrTelly

OwnerDisplayName: cletus


问:
How to get a specific date type in java
I am using the below method to get this string to_date('2011/06/02','yyyy/mm/dd')

```<code>private static String getOperationDate() {
  Date today= new Date();
  String output;
  SimpleDateFormat formatter;
  String pattern="yyyy/MM/dd";

  formatter = new SimpleDateFormat(pattern, Locale.US);
  output = formatter.format(today);
  String temp="to_date('"+output+"','yyyy/mm/dd')";

  return temp;
}
</code>```

How can i generate something like this to_date('2011-05-27 12:45:56.1',....) i.e., apart from just date how can i also include time with milliseconds, which would then be updated to the database

Added a oracle insert statement, after referring to an answer by trutheality, but this gives me 01810. 00000 -  "format code appears twice" error

```<code>INSERT INTO CONFIG_INFO(CFG_ID,CFG_NAME,CFG_DESC,CFG_TYPE,FILE_NAME,ABSOLUTE_PATH,EMAIL_ADDRESS,PROJECT_ID,HOSTNAME,CREATE_DATE,UPDATE_DATE,STATE,PRODUCT_ID)
    VALUES (config_seq.NEXTVAL,'Abhishek','as','Production','asdclient1.xml','E:tomcat 5.5bin/../webapps/asd/files/asdclient.xml','a@a.com','ABC','abhinix',to_date('2011/06/02 11:18:38.211','yyyy/MM/dd HH:mm:ss.SSS'),to_date('2011/06/02 11:18:38.211','yyyy/MM/dd HH:mm:ss.SSS'),2,123456)
</code>```

答:
Do this </p>

```<code> private static String getOperationDate() {
 Date today= new Date();
 String output;
 SimpleDateFormat formatter;
 String pattern="yyyy/MM/dd HH:mm:ss.SSS";

 formatter = new SimpleDateFormat(pattern, Locale.US);
 output = formatter.format(today);
 String temp="to_date('"+output+"','yyyy/mm/dd')";

 return temp;
}
</code>```

Title: How to get a specific date type in java

Body:
I am using the below method to get this string to_date('2011/06/02','yyyy/mm/dd')

private static String getOperationDate() {
  Date today= new Date();
  String output;
  SimpleDateFormat formatter;
  String pattern="yyyy/MM/dd";

  formatter = new SimpleDateFormat(pattern, Locale.US);
  output = formatter.format(today);
  String temp="to_date('"+output+"','yyyy/mm/dd')";

  return temp;
}

How can i generate something like this to_date('2011-05-27 12:45:56.1',....) i.e., apart from just date how can i also include time with milliseconds, which would then be updated to the database

Added a oracle insert statement, after referring to an answer by trutheality, but this gives me 01810. 00000 -  "format code appears twice" error

INSERT INTO CONFIG_INFO(CFG_ID,CFG_NAME,CFG_DESC,CFG_TYPE,FILE_NAME,ABSOLUTE_PATH,EMAIL_ADDRESS,PROJECT_ID,HOSTNAME,CREATE_DATE,UPDATE_DATE,STATE,PRODUCT_ID)
    VALUES (config_seq.NEXTVAL,'Abhishek','as','Production','asdclient1.xml','E:tomcat 5.5bin/../webapps/asd/files/asdclient.xml','a@a.com','ABC','abhinix',to_date('2011/06/02 11:18:38.211','yyyy/MM/dd HH:mm:ss.SSS'),to_date('2011/06/02 11:18:38.211','yyyy/MM/dd HH:mm:ss.SSS'),2,123456)

Body:
Do this

 private static String getOperationDate() {
 Date today= new Date();
 String output;
 SimpleDateFormat formatter;
 String pattern="yyyy/MM/dd HH:mm:ss.SSS";

 formatter = new SimpleDateFormat(pattern, Locale.US);
 output = formatter.format(today);
 String temp="to_date('"+output+"','yyyy/mm/dd')";

 return temp;
}


问:
Pandas.Series.mode eventually have multirow results. How to fix it?
I have this df:

```<code>nome_socio   cnpj_cpf_socio   municipio
Alexandre    AAA              Curitiba
Alexandre    AAA              Rio
Alexandre    AAA              Porto Alegre
Bruno        BBB              Porto Alegre
Bruno        BBB              Porto Alegre
</code>```

I want to get the mode for rows with the same nome_socio and cnpj_cpf_socio. For that I'm using the following code:

```<code>moda_municipio=df[['nome_socio','cnpj_cpf_socio','municipio']].groupby(['nome_socio','cnpj_cpf_socio'])['municipio'].apply(pd.Series.mode).to_frame().reset_index().rename(columns={'municipio':"cidade_pred"})
</code>```

It does find the mode, however since for Alexandre + AAA rows there is a draw between the three municipios it returns three different rows. I'm getting this result:

```<code>  nome_socio cnpj_cpf_socio  level_2   cidade_pred
0  Alexandre            AAA        0      Curitiba
1  Alexandre            AAA        1  Porto Alegre
2  Alexandre            AAA        2           Rio
3      Bruno            BBB        0  Porto Alegre
</code>```

I need to make it look like this:

```<code>  nome_socio cnpj_cpf_socio  level_2                      cidade_pred
   Alexandre            AAA        0      Curitiba, Porto Alegre, Rio
       Bruno            BBB        0                     Porto Alegre
</code>```

Is there a way to do it?

答:
We should do mode first then join the result

```<code>df.groupby(['nome_socio','cnpj_cpf_socio'])['cidade_pred'].agg(lambda x : ','.join(x.mode().tolist()))
</code>```

Body:
I have this df:

nome_socio   cnpj_cpf_socio   municipio
Alexandre    AAA              Curitiba
Alexandre    AAA              Rio
Alexandre    AAA              Porto Alegre
Bruno        BBB              Porto Alegre
Bruno        BBB              Porto Alegre

I want to get the mode for rows with the same nome_socio and cnpj_cpf_socio. For that I'm using the following code:

moda_municipio=df[['nome_socio','cnpj_cpf_socio','municipio']].groupby(['nome_socio','cnpj_cpf_socio'])['municipio'].apply(pd.Series.mode).to_frame().reset_index().rename(columns={'municipio':"cidade_pred"})

It does find the mode, however since for Alexandre + AAA rows there is a draw between the three municipios it returns three different rows. I'm getting this result:

  nome_socio cnpj_cpf_socio  level_2   cidade_pred
0  Alexandre            AAA        0      Curitiba
1  Alexandre            AAA        1  Porto Alegre
2  Alexandre            AAA        2           Rio
3      Bruno            BBB        0  Porto Alegre

I need to make it look like this:

  nome_socio cnpj_cpf_socio  level_2                      cidade_pred
   Alexandre            AAA        0      Curitiba, Porto Alegre, Rio
       Bruno            BBB        0                     Porto Alegre

Is there a way to do it?

Body:
We should do mode first then join the result

df.groupby(['nome_socio','cnpj_cpf_socio'])['cidade_pred'].agg(lambda x : ','.join(x.mode().tolist()))


问:
Can't knit in R markdown
Recently I was doing a course in Coursera and faced the problem while doing R markdown.  When I run the code in the console it works just fine however, when I knit it, the rmarkdown only show text in the code chunk as below.

I  run this in console and it work just fine:

But when i knit the code appear as text:

When I hit the green arrow it appears like there are some error going on:

答:
The bottom screenshot you provided is not an R code chunk. It does not have the proper header. R code chunks in an R markdown file must be formatted like this:</p>

```<code>```{r}
R code goes here
```
</code>```

Title: Can't knit in R markdown

Body:
The bottom screenshot you provided is not an R code chunk. It does not have the proper header. R code chunks in an R markdown file must be formatted like this:

```{r}
R code goes here
```


问:
Data set file not found in python
I am coding a python program to read a data set file writing this line:

```<code>df = pd.read_csv (r'C:\Users\user118\Desktop\StudentsPerformance.csv')
</code>```

This line works, but I have to upload this project as an assignment , so the computer path must be changed. I think about putting the csv file in the project folder and i did and wrote this line:

```<code>df = pd.read_csv ("StudentsPerformance.csv")
</code>```

but it gave me an error saying that the file isn't found. Where to correctly put the file in the project folder? Or what I should do?

答:
To read your csv file with a df = pd.read_csv ("StudentsPerformance.csv") line you should put it right next to executing .py file.
To do that you can just read your csv file using full path like this:

```<code>df = pd.read_csv (r'C:\Users\user118\Desktop\StudentsPerformance.csv')
</code>```

and than write df.to_csv('StudentsPerformance.csv')

After that you would be able to read your csv as you wanted using

```<code>df = pd.read_csv('StudentsPerformance.csv')
</code>```

Title: Data set file not found in python

Body:
I am coding a python program to read a data set file writing this line:

df = pd.read_csv (r'C:\Users\user118\Desktop\StudentsPerformance.csv')

This line works, but I have to upload this project as an assignment , so the computer path must be changed. I think about putting the csv file in the project folder and i did and wrote this line:

df = pd.read_csv ("StudentsPerformance.csv")

but it gave me an error saying that the file isn't found. Where to correctly put the file in the project folder? Or what I should do?

Body:
To read your csv file with a df = pd.read_csv ("StudentsPerformance.csv") line you should put it right next to executing .py file.
To do that you can just read your csv file using full path like this:

df = pd.read_csv (r'C:\Users\user118\Desktop\StudentsPerformance.csv')

and than write df.to_csv('StudentsPerformance.csv')

After that you would be able to read your csv as you wanted using

df = pd.read_csv('StudentsPerformance.csv')


答:
If you are looking to protect the values of variables from being edited or looked at by the console or such, you should look at scoping through IIFE (Immediately Invoked Function Expression).

Since the anonymous function within our IIFE is a function expression
  and is not being assigned to a global variable, no global property is
  being created, and all of the properties created inside of the
  function expression are scoped locally to the expression itself.

This way, any variable you declare and set within this function can not be accessed simply through the window object that your console works in.

If you are looking for some extra security and encrytion, search for JavaScript Obfuscator

Title: How to protect a client side JavaScript variable?

Body:
Using the following function to check the existence of a given URL. The code is executed on the client side (browser), is there a way (if at all possible) to protect the url variable from being altered with the browser debugger while keeping the function on the client side?

Note that the url variable is generated by the server and set on the JS script (client side)

function UrlExists(url, callback)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url);
    http.onreadystatechange = function() {
        if (this.readyState == this.DONE) {
            callback(this.status != 404);
        }
    };
    http.send();
}

Function source.


问:
How can I define the position of an audio source on a javascript canvas element in pixels (x,y) with Resonance Audio's setPosition?
I have a 2d canvas based web audio game which includes spatialised audio sources situated at specific pixel coordinates on the canvas using the web audio api.

Whilst I have successfully managed to locate each audio source precisely on the canvas element using the web audio pannerNode like so:

```<code>var canvas = document.getElementById("map");
var context = canvas.getContext("2d");
function audioFileLoader(fileDirectory) {
  var soundObj = {};
  var playSound = undefined;
  var panner = undefined;
  var gainNode = undefined;
  var getSound = new XMLHttpRequest();
  soundObj.fileDirectory = fileDirectory;
  getSound.open("GET", soundObj.fileDirectory, true);
  getSound.responseType = "arraybuffer";
  getSound.onload = function() {
audioContext.decodeAudioData(getSound.response, function(buffer) { soundObj.soundToPlay = buffer;
}); };
  getSound.send();
panner = audioContext.createPanner();
panner.panningModel = 'HRTF';

  soundObj.position = function(x,y,z) {
      panner.setPosition(x,y,z);
  };
</code>```

I am now attempting to upgrade the audio spatialisation using the Resonance Audio Web SDK so I can use its arguably more advanced audio spatialisation characteristics.

How can I define the position of the audio sources on the canvas element in pixels (x,y) with Resonance Audio's setPosition?

I can't seem to work out how to convert the native Resonance Audio scale (meters) into pixel coords on my canvas element. I'm assuming that if I can solve this I then define the size and locations of different audio rooms within the 2d game, which would be very cool.

Thanks.

答:
So, turns out if you get the coords on the canvas in pixels where you want to locate your sources, then use the same units (pixels) to locate and update the position of the listener then all is well. As long as you use the same units for your sources and your listener, then they remain relative to each other and the resonance audio spatialisation works:</p>

```<code>// Set some global variables
            var canvas = document.getElementById("map");
            var context = canvas.getContext("2d");
            var mouseX;
            var mouseY;

// Map event functions

// Get mouse coordinates on the map element

            function updateCoords() {
                mouseX = event.offsetX;
                mouseY = event.offsetY;
            }

// Create mouse event functions

            function moveAroundMap(event) {
                updateCoords();
                mapX.innerText = mouseX;
                mapY.innerText = mouseY;

// Update the listener position on the canvas in pixels (x,y)
                resonanceAudioScene.setListenerPosition(mouseX,mouseY,-20); // elevate the listener rather than lowering the sources
            }

            map.addEventListener("mousemove", moveAroundMap, false);

// Create an AudioContext
        let audioContext = new AudioContext();

        // Create a (third-order Ambisonic) Resonance Audio scene and pass it
        // the AudioContext.
        let resonanceAudioScene = new ResonanceAudio(audioContext);
        resonanceAudioScene.setAmbisonicOrder(3);

        // Connect the scene’s binaural output to stereo out.
        resonanceAudioScene.output.connect(audioContext.destination);

        // Create an AudioElement.
        let audioElement = document.createElement('audio');

        // Load an audio file into the AudioElement.
        audioElement.src = './samples/mono-seagulls.mp3';
        audioElement.loop = true;

        // Generate a MediaElementSource from the AudioElement.
        let audioElementSource = audioContext.createMediaElementSource(audioElement);

        // Add the MediaElementSource to the scene as an audio input source.
        let source = resonanceAudioScene.createSource();
        audioElementSource.connect(source.input);

        // Set the source position relative to the listener
        source.setPosition(140, 150, 0);
</code>```

Body:
I have a 2d canvas based web audio game which includes spatialised audio sources situated at specific pixel coordinates on the canvas using the web audio api.

Whilst I have successfully managed to locate each audio source precisely on the canvas element using the web audio pannerNode like so:

var canvas = document.getElementById("map");
var context = canvas.getContext("2d");
function audioFileLoader(fileDirectory) {
  var soundObj = {};
  var playSound = undefined;
  var panner = undefined;
  var gainNode = undefined;
  var getSound = new XMLHttpRequest();
  soundObj.fileDirectory = fileDirectory;
  getSound.open("GET", soundObj.fileDirectory, true);
  getSound.responseType = "arraybuffer";
  getSound.onload = function() {
audioContext.decodeAudioData(getSound.response, function(buffer) { soundObj.soundToPlay = buffer;
}); };
  getSound.send();
panner = audioContext.createPanner();
panner.panningModel = 'HRTF';

  soundObj.position = function(x,y,z) {
      panner.setPosition(x,y,z);
  };

I am now attempting to upgrade the audio spatialisation using the Resonance Audio Web SDK so I can use its arguably more advanced audio spatialisation characteristics.

How can I define the position of the audio sources on the canvas element in pixels (x,y) with Resonance Audio's setPosition?

I can't seem to work out how to convert the native Resonance Audio scale (meters) into pixel coords on my canvas element. I'm assuming that if I can solve this I then define the size and locations of different audio rooms within the 2d game, which would be very cool.

Thanks.

Body:
So, turns out if you get the coords on the canvas in pixels where you want to locate your sources, then use the same units (pixels) to locate and update the position of the listener then all is well. As long as you use the same units for your sources and your listener, then they remain relative to each other and the resonance audio spatialisation works:

// Set some global variables
            var canvas = document.getElementById("map");
            var context = canvas.getContext("2d");
            var mouseX;
            var mouseY;

// Map event functions

// Get mouse coordinates on the map element

            function updateCoords() {
                mouseX = event.offsetX;
                mouseY = event.offsetY;
            }

// Create mouse event functions

            function moveAroundMap(event) {
                updateCoords();
                mapX.innerText = mouseX;
                mapY.innerText = mouseY;

// Update the listener position on the canvas in pixels (x,y)
                resonanceAudioScene.setListenerPosition(mouseX,mouseY,-20); // elevate the listener rather than lowering the sources
            }

            map.addEventListener("mousemove", moveAroundMap, false);

// Create an AudioContext
        let audioContext = new AudioContext();

        // Create a (third-order Ambisonic) Resonance Audio scene and pass it
        // the AudioContext.
        let resonanceAudioScene = new ResonanceAudio(audioContext);
        resonanceAudioScene.setAmbisonicOrder(3);

        // Connect the scene’s binaural output to stereo out.
        resonanceAudioScene.output.connect(audioContext.destination);

        // Create an AudioElement.
        let audioElement = document.createElement('audio');

        // Load an audio file into the AudioElement.
        audioElement.src = './samples/mono-seagulls.mp3';
        audioElement.loop = true;

        // Generate a MediaElementSource from the AudioElement.
        let audioElementSource = audioContext.createMediaElementSource(audioElement);

        // Add the MediaElementSource to the scene as an audio input source.
        let source = resonanceAudioScene.createSource();
        audioElementSource.connect(source.input);

        // Set the source position relative to the listener
        source.setPosition(140, 150, 0);


问:
Is there any way to import a variable from a function in another file without using return in Python?
I have this pygame code which is divided into multiple files and in one of the files I want to import a variable from a function which is in another file.

```<code># gamescreen.py
highscore = 0
def game_screen(screen):
    ...

    hits = pygame.sprite.spritecollide(player, world_sprites, True, pygame.sprite.collide_mask)
    if len(hits) > 0:
        if score > highscore:
            global highscore
            highscore = score
            state = PLAYAGAIN
    ...

    return state
</code>```

```<code># playagain.py
def play_again(screen):
    ...

    highscore_texto = font.render('highscore: {0}'.format(highscore), True, (BLACK))
    background.blit(highscore_texto, (30, 25))
    ...
</code>```

Is there any way I can acess that highscore variable in the file playagain.py without having to return it in the game_screen function?

When I tried to return it in the game_screen function like this:

```<code>return state, highscore
</code>```

And access it in the playagain.py file like this:

```<code>game_screen(screen)[1]
</code>```

It just ran the game_screen function two times, which is not what I want because it messes up my game.

答:
```<code>import gamestream
print(gamestream.highscore)
</code>```

The variable is set in the module namespace (confusingly named "global" when its really "module global"). Import the module and you've got its namespace.

This doesn't work

```<code>from gamestream import highscore
</code>```

In that case you rebound the current thing in highscore to your module's namespace and it won't see changes to the original. It is the same as if you had done

```<code>import gamestream
highscore = gamestream.highscore
</code>```

A new variable called "highscore" is created in the local module and the current value in gamestream.highscore is bound to it. If gamestream.highscore is reassigned, that wouldn't affect this separate variable.

Body:
I have this pygame code which is divided into multiple files and in one of the files I want to import a variable from a function which is in another file.

# gamescreen.py
highscore = 0
def game_screen(screen):
    ...

    hits = pygame.sprite.spritecollide(player, world_sprites, True, pygame.sprite.collide_mask)
    if len(hits) > 0:
        if score > highscore:
            global highscore
            highscore = score
            state = PLAYAGAIN
    ...

    return state

# playagain.py
def play_again(screen):
    ...

    highscore_texto = font.render('highscore: {0}'.format(highscore), True, (BLACK))
    background.blit(highscore_texto, (30, 25))
    ...

Is there any way I can acess that highscore variable in the file playagain.py without having to return it in the game_screen function?

When I tried to return it in the game_screen function like this:

return state, highscore

And access it in the playagain.py file like this:

game_screen(screen)[1]

It just ran the game_screen function two times, which is not what I want because it messes up my game.

Body:
import gamestream
print(gamestream.highscore)

The variable is set in the module namespace (confusingly named "global" when its really "module global"). Import the module and you've got its namespace.

This doesn't work

from gamestream import highscore

In that case you rebound the current thing in highscore to your module's namespace and it won't see changes to the original. It is the same as if you had done

import gamestream
highscore = gamestream.highscore

A new variable called "highscore" is created in the local module and the current value in gamestream.highscore is bound to it. If gamestream.highscore is reassigned, that wouldn't affect this separate variable.


问:
TextView: How to prevent displaying the action menu when selecting text in TextView?
I have a selectable TextView.
I want to prevent showing the context menu when selecting text.

I implemented this code but action bar and context menu still is displayed.

```<code>   tv.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Return true to ensure the yourTextView is still selectable
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Remove all action items to provide an actionmode-less selection
            menu.clear();
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });
</code>```

How can it be remove forever?

答:
I thought and finally wrote the following code:</p>

```<code>    tv.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            removeActionBar(getWindow().getDecorView());
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });

    private void removeActionBar(View v) {
            ViewGroup viewgroup = (ViewGroup) v;

            for (int i = 0; i < viewgroup.getChildCount(); i++) {
                    View v1=viewgroup.getChildAt(i);
                    if ( v1 instanceof ViewGroup )
                            removeActionBar(v1);
                    if ( v1 instanceof ActionBarContextView ) {
                            viewgroup.removeView(v1);
                    }
            }
    }
</code>```

Body:
I have a selectable TextView.
I want to prevent showing the context menu when selecting text.

I implemented this code but action bar and context menu still is displayed.

   tv.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Return true to ensure the yourTextView is still selectable
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Remove all action items to provide an actionmode-less selection
            menu.clear();
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });

How can it be remove forever?

Body:
I thought and finally wrote the following code:

    tv.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            removeActionBar(getWindow().getDecorView());
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });

    private void removeActionBar(View v) {
            ViewGroup viewgroup = (ViewGroup) v;

            for (int i = 0; i < viewgroup.getChildCount(); i++) {
                    View v1=viewgroup.getChildAt(i);
                    if ( v1 instanceof ViewGroup )
                            removeActionBar(v1);
                    if ( v1 instanceof ActionBarContextView ) {
                            viewgroup.removeView(v1);
                    }
            }
    }