问:
How to fill an input correctly with a value = ""?
When I put value="" inside the input, it does not allow me to fill the username and the password.

Without the value="" it allows me to fill, with the value="" nothing happens

```<code>{/* User */}
<div class="input-group form-group">
   <div class="input-group-prepend">
      <span class="input-group-text"><i class="fas fa-user"></i></span>
   </div>
   <input type="text" class="form-control" placeholder="username" value={this.state.name} onChange={this.handleChange}></input>
</div>
{/* Senha */}
<div class="input-group form-group">
   <div class="input-group-prepend">
      <span class="input-group-text"><i class="fas fa-key"></i></span>
   </div>
   <input type="password" class="form-control" placeholder="password" value={this.state.password} onChange={this.handleChange}></input>
</div>
</code>```

The input field has to allow me to fill username and password.

答:
Try with "defaultValue" instead of "value" similar to:
React Input Type not editable</p>

```<code>{/* User */}
<div class="input-group form-group">
   <div class="input-group-prepend">
      <span class="input-group-text"><i class="fas fa-user"></i></span>
   </div>
   <input type="text" class="form-control" placeholder="username" defaultValue={this.state.name} onChange={this.handleChange}></input>
</div>
{/* Senha */}
<div class="input-group form-group">
   <div class="input-group-prepend">
      <span class="input-group-text"><i class="fas fa-key"></i></span>
   </div>
   <input type="password" class="form-control" placeholder="password" defaultValue={this.state.password} onChange={this.handleChange}></input>
</div>
</code>```

Body:
When I put value="" inside the input, it does not allow me to fill the username and the password.

Without the value="" it allows me to fill, with the value="" nothing happens

{/* User */}

   <input type="text" class="form-control" placeholder="username" value={this.state.name} onChange={this.handleChange}></input>

{/* Senha */}

   <input type="password" class="form-control" placeholder="password" value={this.state.password} onChange={this.handleChange}></input>

The input field has to allow me to fill username and password.

Body:
Try with "defaultValue" instead of "value" similar to:
React Input Type not editable

{/* User */}
<div class="input-group form-group">
   <div class="input-group-prepend">
      <span class="input-group-text"><i class="fas fa-user"></i></span>
   </div>
   <input type="text" class="form-control" placeholder="username" defaultValue={this.state.name} onChange={this.handleChange}></input>
</div>
{/* Senha */}
<div class="input-group form-group">
   <div class="input-group-prepend">
      <span class="input-group-text"><i class="fas fa-key"></i></span>
   </div>
   <input type="password" class="form-control" placeholder="password" defaultValue={this.state.password} onChange={this.handleChange}></input>
</div>


来源: stackexchange

问:
How to use onSaveInstance method with Recyclerview
I have an App which should keep all the data displayed into Recycler when the screen is rotated. the recycler receives data from a Custom Array List. there is also a second variable used to set the Uri of the VideoView inside the adapter.

already tried onSave and onRestoreIntance. maybe I have used them wrong.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Variables-----------------------------------------

     recyclerView = findViewById(R.id.recyclerView);
    Button video = findViewById(R.id.video);
    Button camera = findViewById(R.id.camera);
    Button send = findViewById(R.id.send);
    final EditText editText = findViewById(R.id.editText);

    // Layout Manager------------------------------------------------

    linearLayoutManager = new LinearLayoutManager(MainActivity.this);
    linearLayoutManager.setStackFromEnd(true);
    RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setItemAnimator(itemAnimator);

    // Adapter-----------------------------------------

        //adapter.notifyDataSetChanged();
        adapter =  new myAdapter(dati, this);
        recyclerView.setAdapter(adapter);

    // Click Listener Video button----------------------------------------
    video.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            startActivityForResult(intent,0);
        }
    });

    // Click Listener Camera button--------------------------------------
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,1);
        }
    });

    // Click Listener Send button-----------------------------------------
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String string = editText.getText().toString();
            dati.add(new ModelloDati(0,string));
            adapter.notifyItemInserted(dati.size());
            editText.getText().clear();
            recyclerView.smoothScrollToPosition(dati.size());
            closeKeyboard();
        }
    });

    if(savedInstanceState != null)

linearLayoutManager.onRestoreInstanceState(
savedInstanceState.getParcelable("STATO_LISTA"));

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable
Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode){
        case 0:
            try {
                Uri contentURI = data.getData();
                passUri = contentURI;
                String recordedVideoPath = getPath(contentURI);
                saveVideoToInternalStorage(recordedVideoPath);
                dati.add(new ModelloDati(2, contentURI));
                adapter.notifyItemInserted(dati.size());
                recyclerView.smoothScrollToPosition(dati.size());

            }catch (Throwable o){Log.i("CAM","User aborted action");}
        case 1:
            try {
                Bitmap bitmap = (Bitmap)data.getExtras().get("data");
                dati.add(new ModelloDati(1,bitmap));
                adapter.notifyItemInserted(dati.size());
                recyclerView.smoothScrollToPosition(dati.size());

            }catch(Throwable o){
                Log.i("CAM","User aborted action");
            }

    }

}

@Override
protected void onResume() {
    super.onResume();

    if (saveList != null) {
        linearLayoutManager.onRestoreInstanceState(saveList);
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveList = linearLayoutManager.onSaveInstanceState();
    outState.putParcelable("STATO_LISTA",saveList);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if(savedInstanceState != null)
       savedInstanceState.getParcelable("STATO_LISTA");
}

}
</code>```

答:
Android offers Architecture components which helps you deal with those kind of situations.
For example ViewModel

The Android framework manages the lifecycles of UI controllers, such as activities and fragments. The framework may decide to destroy or re-create a UI controller in response to certain user actions or device events that are completely out of your control.

If the system destroys or re-creates a UI controller, any transient UI-related data you store in them is lost. For example, your app may include a list of users in one of its activities. When the activity is re-created for a configuration change, the new activity has to re-fetch the list of users. For simple data, the activity can use the onSaveInstanceState() method and restore its data from the bundle in onCreate(), but this approach is only suitable for small amounts of data that can be serialized then deserialized, not for potentially large amounts of data like a list of users or bitmaps.

So basically you can hold your dataset for your adapter in your ViewModel and inside onCreate get the data and set it into your adapter.

```<code>MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
new adapter(model.getData(),this); // just for the example.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an App which should keep all the data displayed into Recycler when the screen is rotated. the recycler receives data from a Custom Array List. there is also a second variable used to set the Uri of the VideoView inside the adapter.

already tried onSave and onRestoreIntance. maybe I have used them wrong.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Variables-----------------------------------------

     recyclerView = findViewById(R.id.recyclerView);
    Button video = findViewById(R.id.video);
    Button camera = findViewById(R.id.camera);
    Button send = findViewById(R.id.send);
    final EditText editText = findViewById(R.id.editText);

    // Layout Manager------------------------------------------------

    linearLayoutManager = new LinearLayoutManager(MainActivity.this);
    linearLayoutManager.setStackFromEnd(true);
    RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setItemAnimator(itemAnimator);

    // Adapter-----------------------------------------

        //adapter.notifyDataSetChanged();
        adapter =  new myAdapter(dati, this);
        recyclerView.setAdapter(adapter);

    // Click Listener Video button----------------------------------------
    video.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            startActivityForResult(intent,0);
        }
    });

    // Click Listener Camera button--------------------------------------
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,1);
        }
    });

    // Click Listener Send button-----------------------------------------
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String string = editText.getText().toString();
            dati.add(new ModelloDati(0,string));
            adapter.notifyItemInserted(dati.size());
            editText.getText().clear();
            recyclerView.smoothScrollToPosition(dati.size());
            closeKeyboard();
        }
    });

    if(savedInstanceState != null)

linearLayoutManager.onRestoreInstanceState(
savedInstanceState.getParcelable("STATO_LISTA"));

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable
Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode){
        case 0:
            try {
                Uri contentURI = data.getData();
                passUri = contentURI;
                String recordedVideoPath = getPath(contentURI);
                saveVideoToInternalStorage(recordedVideoPath);
                dati.add(new ModelloDati(2, contentURI));
                adapter.notifyItemInserted(dati.size());
                recyclerView.smoothScrollToPosition(dati.size());

            }catch (Throwable o){Log.i("CAM","User aborted action");}
        case 1:
            try {
                Bitmap bitmap = (Bitmap)data.getExtras().get("data");
                dati.add(new ModelloDati(1,bitmap));
                adapter.notifyItemInserted(dati.size());
                recyclerView.smoothScrollToPosition(dati.size());

            }catch(Throwable o){
                Log.i("CAM","User aborted action");
            }

    }

}

@Override
protected void onResume() {
    super.onResume();

    if (saveList != null) {
        linearLayoutManager.onRestoreInstanceState(saveList);
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveList = linearLayoutManager.onSaveInstanceState();
    outState.putParcelable("STATO_LISTA",saveList);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if(savedInstanceState != null)
       savedInstanceState.getParcelable("STATO_LISTA");
}

}

Body:
Android offers Architecture components which helps you deal with those kind of situations.
For example ViewModel

The Android framework manages the lifecycles of UI controllers, such as activities and fragments. The framework may decide to destroy or re-create a UI controller in response to certain user actions or device events that are completely out of your control.

If the system destroys or re-creates a UI controller, any transient UI-related data you store in them is lost. For example, your app may include a list of users in one of its activities. When the activity is re-created for a configuration change, the new activity has to re-fetch the list of users. For simple data, the activity can use the onSaveInstanceState() method and restore its data from the bundle in onCreate(), but this approach is only suitable for small amounts of data that can be serialized then deserialized, not for potentially large amounts of data like a list of users or bitmaps.

So basically you can hold your dataset for your adapter in your ViewModel and inside onCreate get the data and set it into your adapter.

MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
new adapter(model.getData(),this); // just for the example.


问:
why output is null at select translate(' @',' ','') from dual; and why resulit is @ at select replace(' @',' ','') from dual;
Basically  translate will change character to character and Replace string to string , and  here i have tried to remove spaces using translate to count the number words . </p>

```<code>select translate('  @',' ','') from dual;

select replace('  @',' ','') from dual;

select ename , nvl(length(replace(TRANSLATE(upper(trim(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ','                           @ '),' ',''))+1,1) NOOFWORDs
from emp;
</code>```

答:
Unfortunately Oracle has made many bizarre choices around null vs. empty string.

One of those has to do with TRANSLATE. TRANSLATE will return NULL if any of its arguments (including the last one) is NULL, no matter what the logical behavior should be.

So, to remove spaces (say) with TRANSLATE, you must add a character you do NOT want to be removed to both the second and the third argument. I added the lower-case letter z, but you could add anything (a dot, the digit 0, whatever - just make sure you add the same character at the beginning of both arguments)

```<code>... translate (input_string, 'z ', 'z')    ....
</code>```

For example:

```<code>select translate('  @','z ','z') from dual;

TRANSLATE('@','Z','Z')
------------------------
@
</code>```

Body:
Basically  translate will change character to character and Replace string to string , and  here i have tried to remove spaces using translate to count the number words .

select translate('  @',' ','') from dual;

select replace('  @',' ','') from dual;

select ename , nvl(length(replace(TRANSLATE(upper(trim(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ','                           @ '),' ',''))+1,1) NOOFWORDs
from emp;

Body:
Unfortunately Oracle has made many bizarre choices around null vs. empty string.

One of those has to do with TRANSLATE. TRANSLATE will return NULL if any of its arguments (including the last one) is NULL, no matter what the logical behavior should be.

So, to remove spaces (say) with TRANSLATE, you must add a character you do NOT want to be removed to both the second and the third argument. I added the lower-case letter z, but you could add anything (a dot, the digit 0, whatever - just make sure you add the same character at the beginning of both arguments)

... translate (input_string, 'z ', 'z')    ....

For example:

select translate('  @','z ','z') from dual;

TRANSLATE('@','Z','Z')
------------------------
@


问:
Create profile at the same time that the user is created
I'm trying to create a profile in the DRF create function in serializer, but when save User model the next exception is triggered

ValueError: "<Usuario: Some Name>" needs to have a value for field "id" before this many-to-many relationship can be used.

This is my configuration background over python 3
Django == 1.11
DRF == Django rest framework

```<code>class CustomUserManager(BaseUserManager):
    def _create_user(self, firstname, lastname, password, **extra_fields):
        now = timezone.now()
        if not firstname:
            raise ValueError(u'The firstname is required.')

        user = self.model(
            firstname=firstname,
            lastname=lastname,
            last_login=now,
            **extra_fields
        )
        user.set_password(password)
        user.save()

        return user

class Usuario(
    AbstractBaseUser, PermissionsMixin,
    TimeStampedModel, SoftDeletableModel
):

    objects = CustomUserManager()

class Profile(models.Model):
    user = models.OneToOneField(Usuario, related_name='profile', on_delete=models.CASCADE)

class UserSerializer(serializers.ModelSerializer):
    profile = PerfilSerializer(read_only=True)

    def create(self, validate_data):
        user_data = validate_data
        profile_data = validate_data.pop('profile')

        usr = Usuario(**user_data)
        usr.save()

        profl = Profile(**profile_data)
        profl.save()
        profl.user.set(usr)

        return usr
</code>```

I want to get the model with the user instance and the profile created

答:
Simply use Django Signals on User save.

```<code>from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()
</code>```

Check out this concrete tutorial, as it solves your problem.

https://simpleisbetterthancomplex.com/tutorial/2016/07/28/how-to-create-django-signals.html

Glad to help you!

Body:
I'm trying to create a profile in the DRF create function in serializer, but when save User model the next exception is triggered

ValueError: "<Usuario: Some Name>" needs to have a value for field "id" before this many-to-many relationship can be used.

This is my configuration background over python 3
Django == 1.11
DRF == Django rest framework

class CustomUserManager(BaseUserManager):
    def _create_user(self, firstname, lastname, password, **extra_fields):
        now = timezone.now()
        if not firstname:
            raise ValueError(u'The firstname is required.')

        user = self.model(
            firstname=firstname,
            lastname=lastname,
            last_login=now,
            **extra_fields
        )
        user.set_password(password)
        user.save()

        return user

class Usuario(
    AbstractBaseUser, PermissionsMixin,
    TimeStampedModel, SoftDeletableModel
):

    objects = CustomUserManager()

class Profile(models.Model):
    user = models.OneToOneField(Usuario, related_name='profile', on_delete=models.CASCADE)

class UserSerializer(serializers.ModelSerializer):
    profile = PerfilSerializer(read_only=True)

    def create(self, validate_data):
        user_data = validate_data
        profile_data = validate_data.pop('profile')

        usr = Usuario(**user_data)
        usr.save()

        profl = Profile(**profile_data)
        profl.save()
        profl.user.set(usr)

        return usr

I want to get the model with the user instance and the profile created

Body:
Simply use Django Signals on User save.

from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()

Check out this concrete tutorial, as it solves your problem.

https://simpleisbetterthancomplex.com/tutorial/2016/07/28/how-to-create-django-signals.html

Glad to help you!


问:
'google-cloud-firestore' distribution doesn't get added to PyInstaller build
When I am trying to build an executable for my python script it gives me:

```<code>pkg_resources.DistributionNotFound: The 'google-cloud-firestore' distribution was not found and is required by the application
</code>```

I've created the following hooks: 'hook-google-cloud-firestore.py' and 'hook-google.cloud.py', but it doesn't seem to help either. Any ideas how to fix that?

答:
for two days, i have found the solution with three steps

FIRST

in hook-google.cloud add this code.

```<code>datas += copy_metadata('google-cloud-firestore')
</code>```

root of hook-google.cloud.py
..

```<code>C:\Users\ASPIREone\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\PyInstaller\hooks
</code>```

SECOND

make

```<code>hook-google-cloud-firestore.py
</code>```

in root of:

```<code>C:\Users\ASPIREone\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\PyInstaller\hooks
</code>```

and add this code

```<code>from PyInstaller.utils.hooks import copy_metadata, get_package_dir
datas += copy_metadata('google-cloud-firestore')
datas += copy_metadata('google_cloud_firestore')  #altlll

hiddenimports += ['google-cloud-firestore_v1']
#pythonhosted.org/pyinstaller/hooks.html#understanding-pyinstaller-hooks
#get_package_dir returns tuple (where pkg stored, abs path to pkg)
pkg_dir = 'C:/Users/ASPIREone/AppData/Local/Programs/Python/Python37-32/Lib/site-packages/google/cloud/firestore_v1'

datas += (pkg_dir, 'google-cloud-firestore')
</code>```

don't forget to delete folder __pycache__ in your main project my main project is root of  C:\Users\ASPIREone\PycharmProjects\amazon\parking-go

third

delete your app (example: main.exe) in root of:

```<code>C:\Users\ASPIREone\AppData\Local\Programs\Python\Python37-32\Scripts\dist
</code>```

go to command line

don't use pyinstaller.exe --onefile main.py but use

pyinstaller.exe --onefile --clean main.py

because m main proect in root folder so i write in command line:

pyinstaller.exe --onefile --clean C:\Users\ASPIREone\PycharmProjects\amazon\parking-go\main.py

you have to clean it and rebuild from first

it should work !

.........

if you have an error when your app running when retrieve data or write to firestore like this:

```<code>Exception ignored in: 'grpc._cython.cygrpc.ssl_roots_override_callback'
E0527 07:10:01.571000000  3672 src/core/lib/security/security_connector/ssl_util
s.cc:449] assertion failed: pem_root_certs != nullptr
</code>```

it solved with this step:

copy file roots.pm into your main project or where you run your app

dir of roots.pm is

```<code>C:\Users\ASPIREone\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\grpc\_cython\_credentials\roots.pm
</code>```

make hook-grpc.py and put this code

```<code>from PyInstaller.utils.hooks import collect_data_files
datas = collect_data_files('grpc')
</code>```

go to commandline

```<code>pyinstaller.exe --onefile --clean yourmainfile.py
</code>```

it should work !

Body:
When I am trying to build an executable for my python script it gives me:

pkg_resources.DistributionNotFound: The 'google-cloud-firestore' distribution was not found and is required by the application

I've created the following hooks: 'hook-google-cloud-firestore.py' and 'hook-google.cloud.py', but it doesn't seem to help either. Any ideas how to fix that?

Body:
for two days, i have found the solution with three steps

FIRST

in hook-google.cloud add this code.

datas += copy_metadata('google-cloud-firestore')

root of hook-google.cloud.py
..

C:\Users\ASPIREone\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\PyInstaller\hooks

SECOND

make

hook-google-cloud-firestore.py

in root of:

C:\Users\ASPIREone\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\PyInstaller\hooks

and add this code

from PyInstaller.utils.hooks import copy_metadata, get_package_dir
datas += copy_metadata('google-cloud-firestore')
datas += copy_metadata('google_cloud_firestore')  #altlll

hiddenimports += ['google-cloud-firestore_v1']
#pythonhosted.org/pyinstaller/hooks.html#understanding-pyinstaller-hooks
#get_package_dir returns tuple (where pkg stored, abs path to pkg)
pkg_dir = 'C:/Users/ASPIREone/AppData/Local/Programs/Python/Python37-32/Lib/site-packages/google/cloud/firestore_v1'

datas += (pkg_dir, 'google-cloud-firestore')

don't forget to delete folder __pycache__ in your main project my main project is root of  C:\Users\ASPIREone\PycharmProjects\amazon\parking-go

third

delete your app (example: main.exe) in root of:

C:\Users\ASPIREone\AppData\Local\Programs\Python\Python37-32\Scripts\dist

go to command line

don't use pyinstaller.exe --onefile main.py but use

pyinstaller.exe --onefile --clean main.py

because m main proect in root folder so i write in command line:

pyinstaller.exe --onefile --clean C:\Users\ASPIREone\PycharmProjects\amazon\parking-go\main.py

you have to clean it and rebuild from first

it should work !

.........

if you have an error when your app running when retrieve data or write to firestore like this:

Exception ignored in: 'grpc._cython.cygrpc.ssl_roots_override_callback'
E0527 07:10:01.571000000  3672 src/core/lib/security/security_connector/ssl_util
s.cc:449] assertion failed: pem_root_certs != nullptr

it solved with this step:

copy file roots.pm into your main project or where you run your app

dir of roots.pm is

C:\Users\ASPIREone\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\grpc\_cython\_credentials\roots.pm

make hook-grpc.py and put this code

from PyInstaller.utils.hooks import collect_data_files
datas = collect_data_files('grpc')

go to commandline

pyinstaller.exe --onefile --clean yourmainfile.py

it should work !


问:
How do i make onClick and href work together?
I have an a element which has his own href and it works perfectly. The problem is that besides an href element i want to make an onClick function, but when i do so, the href is ignored:

```<code><li><a href="#someSectionOfThePage" onClick={someFunction}>GO TO SECTION</a></li>
</code>```

Using this syntax, the someFunction runs, but i'm not being redirected to #someSectionOfThePage.

答:
This should do the trick:

```<code><li onClick={someFunction}>
   <a href="#someSectionOfThePage">GO TO SECTION</a>
</li>
</code>```

When you click the
 it will execute the function... and when you click the  it will process the href. Since you'll be clicking this element, both will work the same time.

Body:
I have an a element which has his own href and it works perfectly. The problem is that besides an href element i want to make an onClick function, but when i do so, the href is ignored:

GO TO SECTION

Using this syntax, the someFunction runs, but i'm not being redirected to #someSectionOfThePage.

Body:
This should do the trick:

<li onClick={someFunction}>
   <a href="#someSectionOfThePage">GO TO SECTION</a>
</li>

When you click the <li> it will execute the function... and when you click the <a> it will process the href. Since you'll be clicking this element, both will work the same time.


问:
Display multiple lines within a Jlist cell
How can I display multiple lines within a single cell of a JList. In jtable, it is achieved by adding a JTextarea to the table cell renderer. Similiarly, Is there any code to add a custom cell renderer for a JList that holds a textarea? If yes, can you please give me a code snippet for the same?

Or do you think there is any other better method to display multiple lines within the cell of Jlist instead of using a textarea? please help me!!

答: Beside usage of HTML code in Swing component (like Jigar says), you can also specify a ListCellRenderer that uses a TextArea, exactly like you do in your JTable.

ContentLicense: CC BY-SA 3.0


问:
backward count in a numpy array
Let's suppose I have a series of integer values arranged in a numpy array like this.

```<code>nan = np.nan
arr = np.array([3, nan, nan, nan, 5, nan, nan, nan, nan, nan])
</code>```

nan values should be filled with backward count from the first not null value to zero.

```<code>[3, 2, 1, 0, 5, 4, 3, 2, 1, 0]
</code>```

答:
Here's a vectorized one with NumPy -

```<code>def backward_count(a):
    m = ~np.isnan(a)
    idx = np.flatnonzero(m)

    p = np.full(len(a), -1, dtype=a.dtype)
    p[idx[0]] = a[idx[0]]+idx[0]

    d = np.diff(idx)
    p[idx[1:]] = np.diff(a[m]) + d - 1
    out = p.cumsum()
    out[:idx[0]] = np.nan
    return out
</code>```

Sample run with a more generic case -

```<code>In [238]: a
Out[238]: array([nan,  3., nan,  5., nan, 10., nan, nan,  4., nan, nan])

In [239]: backward_count(a)
Out[239]: array([nan,  3.,  2.,  5.,  4., 10.,  9.,  8.,  4.,  3.,  2.])
</code>```

Benchmarking

Setup with scaling up the given sample by 10,000x -

```<code>In [240]: arr = np.array([3, nan, nan, nan, 5, nan, nan, nan, nan, nan])

In [241]: arr = np.tile(arr,10000)

# Pandas based one by @cs95
In [243]: %%timeit
     ...: s = pd.Series(np.cumsum(~np.isnan(arr)))
     ...: s.groupby(s).cumcount(ascending=False)
35.9 ms ± 258 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [245]: %timeit backward_count(arr)
3.04 ms ± 4.35 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

Title: backward count in a numpy array

Body:
Let's suppose I have a series of integer values arranged in a numpy array like this.

nan = np.nan
arr = np.array([3, nan, nan, nan, 5, nan, nan, nan, nan, nan])

nan values should be filled with backward count from the first not null value to zero.

[3, 2, 1, 0, 5, 4, 3, 2, 1, 0]

Body:
Here's a vectorized one with NumPy -

def backward_count(a):
    m = ~np.isnan(a)
    idx = np.flatnonzero(m)

    p = np.full(len(a), -1, dtype=a.dtype)
    p[idx[0]] = a[idx[0]]+idx[0]

    d = np.diff(idx)
    p[idx[1:]] = np.diff(a[m]) + d - 1
    out = p.cumsum()
    out[:idx[0]] = np.nan
    return out

Sample run with a more generic case -

In [238]: a
Out[238]: array([nan,  3., nan,  5., nan, 10., nan, nan,  4., nan, nan])

In [239]: backward_count(a)
Out[239]: array([nan,  3.,  2.,  5.,  4., 10.,  9.,  8.,  4.,  3.,  2.])

Benchmarking

Setup with scaling up the given sample by 10,000x -

In [240]: arr = np.array([3, nan, nan, nan, 5, nan, nan, nan, nan, nan])

In [241]: arr = np.tile(arr,10000)

# Pandas based one by @cs95
In [243]: %%timeit
     ...: s = pd.Series(np.cumsum(~np.isnan(arr)))
     ...: s.groupby(s).cumcount(ascending=False)
35.9 ms ± 258 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [245]: %timeit backward_count(arr)
3.04 ms ± 4.35 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


问:
Android Studio does not find color style resource
I'm trying to use a custom with Theme.AppCompat.NoActionBar but the IDE throws the error that the named resources cannot be found. Kindly assist.Any help would be greatly appreciated.

The styles.xml is as follows:

```<code><?xml version="1.0" encoding="utf-8"?>

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:windowActionBar">false</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorPrimaryLight">@color/primary_light</item>
        <item name="colorAccent">@color/accent</item>
        <item name="textColorPrimary">@color/primary_text</item>
        <item name="textColorSecondary">@color/secondary_text</item>
        <item name="iconColor">@color/icons</item>
        <item name="dividerColor">@color/divider</item>
    </style>
</resources>
</code>```

The colors.xml is as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primary">#FF9800</color>
    <color name="primary_dark">#F57C00</color>
    <color name="primary_light">#FFE0B2</color>
    <color name="accent">#03A9F4</color>
    <color name="primary_text">#212121</color>
    <color name="secondary_text">#727272</color>
    <color name="icons">#212121</color>
    <color name="divider">#B6B6B6</color>
</resources>
</code>```

答:
Make sure you don't have any imports like mine below

import android.R

This imports the wrong resource.

Body:
I'm trying to use a custom with Theme.AppCompat.NoActionBar but the IDE throws the error that the named resources cannot be found. Kindly assist.Any help would be greatly appreciated.

The styles.xml is as follows:

<?xml version="1.0" encoding="utf-8"?>

<resources>

</resources>

The colors.xml is as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primary">#FF9800</color>
    <color name="primary_dark">#F57C00</color>
    <color name="primary_light">#FFE0B2</color>
    <color name="accent">#03A9F4</color>
    <color name="primary_text">#212121</color>
    <color name="secondary_text">#727272</color>
    <color name="icons">#212121</color>
    <color name="divider">#B6B6B6</color>
</resources>


问:
Ruby - free up memory used by required gems?
Is there a way to free up memory used by required gems? My Rails app grows in memory usage and I would like to use gems only when I need them and after that free them up, IF this is possible.

Thanks!

答:
The whole purpose of a memory managed programming language (Ruby) is to avoid developers having to concern themselves with such issues.
If memory does become a sticking point, you'll need to profile the memory by using the following tools

ruby/ruby on rails memory leak detection

Although your control over memory is limited to ensuring memory leaks are avoided and the overall architecture is inline with best practices. An example is ImageMagick takes excessive memory, so rather than having images being converted by all rails mongrels/passengers, restricting the conversion to dedicated ruby services, so as to avoid a large memory footprint.


问:
Optimizing SQL query with cte and variable inputs
I am trying to run the following SQL script using Java and am getting issues with no resultset from JDBCTemplate. I thought about reducing it using functions/stored procedures and would like some help with it:

SQL - first part:

```<code>SET NOCOUNT ON

IF OBJECT_ID('tempdb.dbo.#tempSearch', 'U') IS NOT NULL
    DROP TABLE #tempSearch;

CREATE TABLE #tempSearch
(
    ID INT,
    Value VARCHAR(255)
)

INSERT INTO #tempSearch
VALUES (1, 'Variable1'), (2, 'Variabl2');
</code>```

Second part:

```<code>WITH cte AS
(
    SELECT
        RoleID,
        ',' + REPLACE(REPLACE(GroupNames, ',', ',,'), ' ', '') + ',' GroupNames
    FROM
        UserGroup_Role_Mapping
), cte2 AS
(
    SELECT
        cte.RoleID,
        REPLACE(cte.GroupNames, ',' + Value + ',', '') AS GroupNames,
        s.ID, s.Value
    FROM
        cte
    JOIN
        #tempSearch s ON ID = 1
    UNION ALL
    SELECT
        cte2.RoleID,
        REPLACE(cte2.GroupNames, ',' + s.Value + ',', '') AS l,
        s.ID, s.Value
    FROM
        cte2
    JOIN
        #tempSearch s ON s.ID = cte2.ID + 1
)
SELECT
    a.Role, a.Sort_Order,
    a.Parent, a.Parent_ID, a.Parent_URL,
    a.Child, a.Child_ID,a.Child_URL
FROM
    Config_View a
WHERE
    a.Role IN (SELECT Name
               FROM
                   (SELECT DISTINCT RoleID FROM cte2 WHERE LEN(GroupNames) = 0) tempRoles
               JOIN
                   User_Role ON tempRoles.RoleID = User_Role.ID
              )

DROP TABLE #tempSearch
</code>```

I was thinking first part can be done in a stored procedure. I did read here (stored procedure with variable number of parameters) about making a table from a list of variables but am not sure how to do set those variables in a loop like i am doing from above (1,Variable1 etc.).

I think the second part can be by itself?

So my updated query might be:

Call stored procedure (variable1, ..., variablex);

SQL part 2?

If anyone can help that would be great!

答:
It's possible to do this in two seperate batches, but only if you can ensure that the first batch runs in session scope, and not in a nested batch ( eg via sp_executesql ).  Temp tables created in nested batches, like stored procedures or prepared statements are automatically destroyed at the end of the nested batch.  So it depends on how you call it.  My guess is that a PreparedStatement won't work.

The right way to do this is probably to use a stored procedure with a table-valued parameter, or a JSON (for SQL 2016+), or XML parameter and parses it in the stored procedure body.  See https://learn.microsoft.com/en-us/sql/connect/jdbc/using-table-valued-parameters?view=sql-server-2017

You can also use a TSQL batch instead of a stored procedure and bind a Table-Valued Parameter, or a NVarchar(max) parameter containing JSON.

With a TVP you could simply use a batch like:

```<code>with s as (
     select * from ? --bind a table-valued parameter here
     ), cte as (
    select RoleID,','+replace(replace(GroupNames,',',',,'),' ','')+',' GroupNames from UserGroup_Role_Mapping
    )
    ,cte2 as(
    select cte.RoleID, replace(cte.GroupNames,','+Value+',','') as GroupNames, s.ID, s.Value
    from cte
    join s on ID=1
    union all
    select cte2.RoleID, replace(cte2.GroupNames,','+s.Value+',','') as l, s.ID ,s.Value
    from cte2
    join s on s.ID=cte2.ID+1
)
SELECT a.Role, a.Sort_Order, a.Parent, a.Parent_ID, a.Parent_URL, a.Child, a.Child_ID,a.Child_URL
FROM Config_View a
WHERE a.Role IN (
    Select Name from (
        Select distinct RoleID from cte2 where len(GroupNames)=0
    ) tempRoles
    join User_Role
    on tempRoles.RoleID = User_Role.ID
    )
</code>```

That would be the value of the string variable sql, and then call it something like:

```<code>SQLServerPreparedStatement pStmt = (SQLServerPreparedStatement) connection.prepareStatement(sql);
pStmt.setStructured(1, "dbo.CategoryTableType", sourceTVPObject);
ResultSet rs = stmt.executeQuery();
</code>```

Body:
I am trying to run the following SQL script using Java and am getting issues with no resultset from JDBCTemplate. I thought about reducing it using functions/stored procedures and would like some help with it:

SQL - first part:

SET NOCOUNT ON

IF OBJECT_ID('tempdb.dbo.#tempSearch', 'U') IS NOT NULL
    DROP TABLE #tempSearch;

CREATE TABLE #tempSearch
(
    ID INT,
    Value VARCHAR(255)
)

INSERT INTO #tempSearch
VALUES (1, 'Variable1'), (2, 'Variabl2');

Second part:

WITH cte AS
(
    SELECT
        RoleID,
        ',' + REPLACE(REPLACE(GroupNames, ',', ',,'), ' ', '') + ',' GroupNames
    FROM
        UserGroup_Role_Mapping
), cte2 AS
(
    SELECT
        cte.RoleID,
        REPLACE(cte.GroupNames, ',' + Value + ',', '') AS GroupNames,
        s.ID, s.Value
    FROM
        cte
    JOIN
        #tempSearch s ON ID = 1
    UNION ALL
    SELECT
        cte2.RoleID,
        REPLACE(cte2.GroupNames, ',' + s.Value + ',', '') AS l,
        s.ID, s.Value
    FROM
        cte2
    JOIN
        #tempSearch s ON s.ID = cte2.ID + 1
)
SELECT
    a.Role, a.Sort_Order,
    a.Parent, a.Parent_ID, a.Parent_URL,
    a.Child, a.Child_ID,a.Child_URL
FROM
    Config_View a
WHERE
    a.Role IN (SELECT Name
               FROM
                   (SELECT DISTINCT RoleID FROM cte2 WHERE LEN(GroupNames) = 0) tempRoles
               JOIN
                   User_Role ON tempRoles.RoleID = User_Role.ID
              )

DROP TABLE #tempSearch

I was thinking first part can be done in a stored procedure. I did read here (stored procedure with variable number of parameters) about making a table from a list of variables but am not sure how to do set those variables in a loop like i am doing from above (1,Variable1 etc.).

I think the second part can be by itself?

So my updated query might be:

Call stored procedure (variable1, ..., variablex);

SQL part 2?

If anyone can help that would be great!

Body:
It's possible to do this in two seperate batches, but only if you can ensure that the first batch runs in session scope, and not in a nested batch ( eg via sp_executesql ).  Temp tables created in nested batches, like stored procedures or prepared statements are automatically destroyed at the end of the nested batch.  So it depends on how you call it.  My guess is that a PreparedStatement won't work.

The right way to do this is probably to use a stored procedure with a table-valued parameter, or a JSON (for SQL 2016+), or XML parameter and parses it in the stored procedure body.  See https://learn.microsoft.com/en-us/sql/connect/jdbc/using-table-valued-parameters?view=sql-server-2017

You can also use a TSQL batch instead of a stored procedure and bind a Table-Valued Parameter, or a NVarchar(max) parameter containing JSON.

With a TVP you could simply use a batch like:

with s as (
     select * from ? --bind a table-valued parameter here
     ), cte as (
    select RoleID,','+replace(replace(GroupNames,',',',,'),' ','')+',' GroupNames from UserGroup_Role_Mapping
    )
    ,cte2 as(
    select cte.RoleID, replace(cte.GroupNames,','+Value+',','') as GroupNames, s.ID, s.Value
    from cte
    join s on ID=1
    union all
    select cte2.RoleID, replace(cte2.GroupNames,','+s.Value+',','') as l, s.ID ,s.Value
    from cte2
    join s on s.ID=cte2.ID+1
)
SELECT a.Role, a.Sort_Order, a.Parent, a.Parent_ID, a.Parent_URL, a.Child, a.Child_ID,a.Child_URL
FROM Config_View a
WHERE a.Role IN (
    Select Name from (
        Select distinct RoleID from cte2 where len(GroupNames)=0
    ) tempRoles
    join User_Role
    on tempRoles.RoleID = User_Role.ID
    )

That would be the value of the string variable sql, and then call it something like:

SQLServerPreparedStatement pStmt = (SQLServerPreparedStatement) connection.prepareStatement(sql);
pStmt.setStructured(1, "dbo.CategoryTableType", sourceTVPObject);
ResultSet rs = stmt.executeQuery();


问:
Call a function defined inside script tags, from curly braces
I tried importing a javascript library with a script tag, and then called a function from it inside React curly braces. I got an error telling me that the function wasn't defined.

```<code><script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<p>{marked(string)}</p>
</code>```

I know that I could import the library inside the react App file, or that I could use another script tag to call the function, but my question is: is there a way to call functions defined inside a script tag from React curly braces?? And viceversa?

答:
You cannot include script tag inside your React component, instead you should include it in your HTML.

Once included, you should be able to use the functions as global functions (if the library is designed to be use as such)

class Example extends React.Component {
  render() {
    return (

        {marked("Function marked() is accessible as global function")}

    )
  }
}

ReactDOM.render(<Example />, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<!--
Here you include your script in the HTML, then
you can access the functions defined in the script
as global variable inside your React components
-->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

<div id="app"></div></code>```

Body:
I tried importing a javascript library with a script tag, and then called a function from it inside React curly braces. I got an error telling me that the function wasn't defined.

{marked(string)}

I know that I could import the library inside the react App file, or that I could use another script tag to call the function, but my question is: is there a way to call functions defined inside a script tag from React curly braces?? And viceversa?

Body:
You cannot include script tag inside your React component, instead you should include it in your HTML.

Once included, you should be able to use the functions as global functions (if the library is designed to be use as such)

class Example extends React.Component {
  render() {
    return (
      <div>
        {marked("Function marked() is accessible as global function")}
      </div>
    )
  }
}

ReactDOM.render(<Example />, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<!--
Here you include your script in the HTML, then
you can access the functions defined in the script
as global variable inside your React components
-->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

<div id="app"></div>


问:
Get new autoincremented value to selected cells
Accidentally imported values to an id column which is set to be auto increment. Having lots of duplicated, tried to reset those ids to table's autoincrement value:

```<code>update tableccc set id=(SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "mydb"
AND TABLE_NAME = "tableccc") where id<1700
</code>```

but now I have the same value for each id

how can I add the auto incremented value to those id cells?

答:
At first save in a var the max id in this way you will avoid duplicated records

```<code>SET @id=(SELECT MAX(id) FROM tableccc );
</code>```

Then update all records with id 146293 (duplicated id)

```<code>UPDATE tableccc SET id=(@id:=@id+1) WHERE id =146293 ;
</code>```

finally update auto incremt for 'tableccc'

```<code>UPDATE information_schema.TABLES
 SET AUTO_INCREMENT = (SELECT MAX(id) FROM tableccc )
 WHERE
          TABLE_SCHEMA = "mydb"
      AND TABLE_NAME = 'tableccc';
</code>```

Body:
Accidentally imported values to an id column which is set to be auto increment. Having lots of duplicated, tried to reset those ids to table's autoincrement value:

update tableccc set id=(SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "mydb"
AND TABLE_NAME = "tableccc") where id<1700

but now I have the same value for each id

how can I add the auto incremented value to those id cells?

Body:
At first save in a var the max id in this way you will avoid duplicated records

SET @id=(SELECT MAX(id) FROM tableccc );

Then update all records with id 146293 (duplicated id)

UPDATE tableccc SET id=(@id:=@id+1) WHERE id =146293 ;

finally update auto incremt for 'tableccc'

UPDATE information_schema.TABLES
 SET AUTO_INCREMENT = (SELECT MAX(id) FROM tableccc )
 WHERE
          TABLE_SCHEMA = "mydb"
      AND TABLE_NAME = 'tableccc';


问:
Why do I get Error: Could not find or load main class .jar when I run docker image
I have written my docker file as below:

```<code>  From java:8
  EXPOSE 8081
  ADD /target/Demo-0.0.1-SNAPSHOT.jar Demo.jar
  ENTRYPOINT ["java",".jar","Demo.jar"]
</code>```

("Demo" is my project name. It creates a Spring boot application.)

I am using a Linux machine.

答:
Make sure you have mentioned "-jar" in the ENTRYPOINT ["java","-jar","Demo.jar"]. you can try to execute the jar using normal java command( java -jar target/Demo-0.0.1-SNAPSHOT.jar ) to make sure the jar builds properly.

```<code>FROM java:8
ADD target/Demo-0.0.1-SNAPSHOT.jar Demo.jar
EXPOSE 8081
ENTRYPOINT ["java","-jar","Demo.jar"]
</code>```

Body:
I have written my docker file as below:

  From java:8
  EXPOSE 8081
  ADD /target/Demo-0.0.1-SNAPSHOT.jar Demo.jar
  ENTRYPOINT ["java",".jar","Demo.jar"]

("Demo" is my project name. It creates a Spring boot application.)

I am using a Linux machine.

Body:
Make sure you have mentioned "-jar" in the ENTRYPOINT ["java","-jar","Demo.jar"]. you can try to execute the jar using normal java command( java -jar target/Demo-0.0.1-SNAPSHOT.jar ) to make sure the jar builds properly.

FROM java:8
ADD target/Demo-0.0.1-SNAPSHOT.jar Demo.jar
EXPOSE 8081
ENTRYPOINT ["java","-jar","Demo.jar"]


问:
How to make a page in flutter that contain multiple sliverlist and a slivergid?
"How to create a gridview within a listview by flutter with json API"

I went through the above link and its good explanation, but when i add one more sliver list with this code and if try to scroll very fast, something happens to slivergrid, only one item will be ther in slivergrid, pls help i am new to flutter.

答:
For main.dart

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

void main() {
  runApp(new MaterialApp(
      home: new fetchPost(),

  ));

}
</code>```

For the fetch.dart

```<code>class fetch extends StatefulWidget{
  fetchPost createState()=> fetchPost();
}

class fetchPost extends State<fetch>{

    //Add your own Json fetch function

       @override
          Widget build(BuildContext context) {
            return CustomScrollView(
                slivers: <Widget>[
                  SliverPadding(
                    padding: EdgeInsets.all(0.0),
                    sliver :SliverList(
                    delegate: SliverChildListDelegate([
                      Column(
                        children: <Widget>[
                          //your widgets
                          firstWidget(),
                          yourNextWidget(),
                        ],
                      )
                    ]),
                  )
                  )
                ],
            );
          }
    Widget firstWidget(){
        return Column( GridView.builder(
                  gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2,crossAxisSpacing: 0.0, childAspectRatio: 1/1),
                  itemCount: recent == null ? 0 : list.length,
                  itemBuilder: (BuildContext context, int index, ) {
                  return Column(
                   children: <Widget>[
                      Card(
                        child: Column(
                          children: <Widget>[
                            new Image.network('asset/image']),
                            new ListTile(
                                title: new Text(''),
                                    subtitle: Text("",),
                                    onTap: () {Navigator.push(
                                      context, new MaterialPageRoute(
                                      builder: (context) => new nextclass(),
                                      ),
                                    );
                                    },
                                dense: true,
                              ),
                            ],
                         ),
                       )
                     ],
                   );
                 },shrinkWrap: true,
                physics: ClampingScrollPhysics(),
              ) );
           }

     Widget nextWidget(){
           return Column(
         //your custom widget
          );
        }
    }
</code>```

Body:
For main.dart

import 'package:flutter/material.dart';
import './pages/fetch.dart';

void main() {
  runApp(new MaterialApp(
      home: new fetchPost(),

  ));

}

For the fetch.dart

class fetch extends StatefulWidget{
  fetchPost createState()=> fetchPost();
}

class fetchPost extends State<fetch>{

    //Add your own Json fetch function

       @override
          Widget build(BuildContext context) {
            return CustomScrollView(
                slivers: <Widget>[
                  SliverPadding(
                    padding: EdgeInsets.all(0.0),
                    sliver :SliverList(
                    delegate: SliverChildListDelegate([
                      Column(
                        children: <Widget>[
                          //your widgets
                          firstWidget(),
                          yourNextWidget(),
                        ],
                      )
                    ]),
                  )
                  )
                ],
            );
          }
    Widget firstWidget(){
        return Column( GridView.builder(
                  gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2,crossAxisSpacing: 0.0, childAspectRatio: 1/1),
                  itemCount: recent == null ? 0 : list.length,
                  itemBuilder: (BuildContext context, int index, ) {
                  return Column(
                   children: <Widget>[
                      Card(
                        child: Column(
                          children: <Widget>[
                            new Image.network('asset/image']),
                            new ListTile(
                                title: new Text(''),
                                    subtitle: Text("",),
                                    onTap: () {Navigator.push(
                                      context, new MaterialPageRoute(
                                      builder: (context) => new nextclass(),
                                      ),
                                    );
                                    },
                                dense: true,
                              ),
                            ],
                         ),
                       )
                     ],
                   );
                 },shrinkWrap: true,
                physics: ClampingScrollPhysics(),
              ) );
           }

     Widget nextWidget(){
           return Column(
         //your custom widget
          );
        }
    }


问:
How to verify that function with Hoare Triple?
As the title says, how can I verify the function below with the Hoare Triple? I read various lectures about it but I can't figure out how to do it.</p>

```<code>int uguaglianza_insiemi(elem_lista_t *insieme_A,
                        elem_lista_t *insieme_B)
{
    int esito;

    if ((insieme_A == NULL) &&
        (insieme_B == NULL))
        esito = 1;

    else if (insieme_A == NULL ||
            insieme_B == NULL)
            esito = 0;

    else if (insieme_A->valore != insieme_B->valore)
            esito = 0;

    else esito = uguaglianza_insiemi(insieme_A->succ_p,
                                     insieme_B->succ_p);

    return (esito);
}
</code>```

答:
To prevent a long discussion in comments, I'll try to write some pre- and post conditions.

As it is not possible to test inside the function whether it is called with pointers to valid list objects, that falls to the parent/the caller:

```<code>// The following function must be called with pointers that are either null
// or point to valid list elements. The lists must be correct (no malloc bugs etc).
// The compiler must have checked that it is called with pointers to the proper types,
// as C has no typeof operator.
//
int uguaglianza_insiemi(elem_lista_t *insieme_A,
                        elem_lista_t *insieme_B)
{
    int esito;

    if ((insieme_A == NULL) &&
        (insieme_B == NULL))
        esito = 1;    // both pointers are null: equal

    // not both pointes are null
    else if (insieme_A == NULL ||
            insieme_B == NULL)
            esito = 0;    // not both pointers are null, but one is: not equal

    // neither pointer is null and so they may be dereferenced
    else if (insieme_A->valore != insieme_B->valore)
            esito = 0;    // neither pointer is null, but their element values aer not equal: not equal

    // the function can be called recursively now because its precondition has been met,
    // that both successor pointers are null or point to valid list elements (induction).
    else esito = uguaglianza_insiemi(insieme_A->succ_p,
                                     insieme_B->succ_p);
    // the post condition is that esito reflects equality of both (partial) lists
    return (esito);
}
</code>```

I hope this is something that you and you professor can work with.

{P}: The function must be called with pointers that are either null or point to valid list elements.

C: uguaglianza_insiemi( *A, *B)

{Q}: function result reflects equality of the lists

Inside the function, this continues with the if statement using the rule of composition.

Body:
As the title says, how can I verify the function below with the Hoare Triple? I read various lectures about it but I can't figure out how to do it.

int uguaglianza_insiemi(elem_lista_t *insieme_A,
                        elem_lista_t *insieme_B)
{
    int esito;

    if ((insieme_A == NULL) &&
        (insieme_B == NULL))
        esito = 1;

    else if (insieme_A == NULL ||
            insieme_B == NULL)
            esito = 0;

    else if (insieme_A->valore != insieme_B->valore)
            esito = 0;

    else esito = uguaglianza_insiemi(insieme_A->succ_p,
                                     insieme_B->succ_p);

    return (esito);
}

Body:
To prevent a long discussion in comments, I'll try to write some pre- and post conditions.

As it is not possible to test inside the function whether it is called with pointers to valid list objects, that falls to the parent/the caller:

// The following function must be called with pointers that are either null
// or point to valid list elements. The lists must be correct (no malloc bugs etc).
// The compiler must have checked that it is called with pointers to the proper types,
// as C has no typeof operator.
//
int uguaglianza_insiemi(elem_lista_t *insieme_A,
                        elem_lista_t *insieme_B)
{
    int esito;

    if ((insieme_A == NULL) &&
        (insieme_B == NULL))
        esito = 1;    // both pointers are null: equal

    // not both pointes are null
    else if (insieme_A == NULL ||
            insieme_B == NULL)
            esito = 0;    // not both pointers are null, but one is: not equal

    // neither pointer is null and so they may be dereferenced
    else if (insieme_A->valore != insieme_B->valore)
            esito = 0;    // neither pointer is null, but their element values aer not equal: not equal

    // the function can be called recursively now because its precondition has been met,
    // that both successor pointers are null or point to valid list elements (induction).
    else esito = uguaglianza_insiemi(insieme_A->succ_p,
                                     insieme_B->succ_p);
    // the post condition is that esito reflects equality of both (partial) lists
    return (esito);
}

I hope this is something that you and you professor can work with.

{P}: The function must be called with pointers that are either null or point to valid list elements.

C: uguaglianza_insiemi( *A, *B)

{Q}: function result reflects equality of the lists

Inside the function, this continues with the if statement using the rule of composition.


问:
How can i execute one by one statement after delaying some time in iphone?
I have a problem in iPhone programing.

In my app i want to execute one by one statement after delaying some time.

Example:

```<code>Label1.text =@"2";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"3";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"8";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"6";
</code>```

答:
You are going to use something called an NSTimer like this:

```<code>[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(update:) userinfo:nil repeats:YES];
</code>```

What this does call the update: method on the current object and send the timer object as a parameter. In this method you can update your label.

Body:
I have a problem in iPhone programing.

In my app i want to execute one by one statement after delaying some time.

Example:

Label1.text =@"2";

Then after delaying some time i want execute:

Label2.text =@"3";

Then after delaying some time i want execute:

Label2.text =@"8";

Then after delaying some time i want execute:

Label2.text =@"6";

Body:
You are going to use something called an NSTimer like this:

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(update:) userinfo:nil repeats:YES];

What this does call the update: method on the current object and send the timer object as a parameter. In this method you can update your label.


问:
Firebase UI login with Google is failing due to 12500(SIGN_IN_FAILED) error code
I am using Firebase UI to provide login for my app. When i try to login with Google it is giving error message com.firebase.ui.auth.FirebaseUiException: Code: 12500, message: 12500. But i when try to integrate google login directly it is working fine. I Couldn't find the way to resolve this issue. Error code description in google document

The sign in attempt didn't succeed with the current account.

Unlike SIGN_IN_REQUIRED. when seeing this error code, there is nothing user can do to recover from the sign in failure. Switching to another account may or may not help. Check adb log to see details if any.

答: Check to see if you have added a "Support email" in your firebase project settings. This was able to solve the problem for me after a lot of trying different things that didn't work.</p>


问:
didn't return an HttpResponse object. It returned None instead
When incorrectly registering a user to my site I get this following error:

ValueError at /accounts/register/ The view accounts.views.register
  didn't return an HttpResponse   object. It returned None instead.

views.py:

```<code>def register(request):
   if request.method == 'POST':
      form = RegistrationForm(request.POST)
      if form.is_valid():
          form.save()
          return redirect('/accounts')

   else:
      form = RegistrationForm()

      args = {'form': form}
      return render(request, 'accounts/reg_form.html', args)
</code>```

urls.py:

```<code>urlpatterns = [
  path('', views.home, name="home"),
  path('explore/', views.explore, name='explore'),
  path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'),
  path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
  path('register/', views.register, name='register'),
  path('profile/', views.view_profile, name='profile'),
  path('profile/edit/', views.edit_profile, name='profile-edit'),
  path('change-password/', views.change_password, name='change_password'),
  path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'),
     name='reset-password'),
  path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
  path('reset-password/confirm/<uidb64>/<token>/',
     PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
  path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]
</code>```

main/urls.py:

```<code>urlpatterns = [
   path('', views.login_redirect, name='login_redirect'),
   path('admin/', admin.site.urls),
   path('accounts/', include('accounts.urls')),

  ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

答:
you are not returning anything for the case form is invalid..

def register(request):
   if request.method == 'POST':
      form = RegistrationForm(request.POST)
      if form.is_valid():
          form.save()
          return redirect('/accounts')
      else: #new
          return render(request, 'accounts/reg_form.html',  {'errors':form.errors})#new

   else:
      form = RegistrationForm()

      args = {'form': form}
      return render(request, 'accounts/reg_form.html', args)
```

it will redirect to account/reg_form.html with errors generated through forms

Body:
When incorrectly registering a user to my site I get this following error:

ValueError at /accounts/register/ The view accounts.views.register
  didn't return an HttpResponse   object. It returned None instead.

views.py:

def register(request):
   if request.method == 'POST':
      form = RegistrationForm(request.POST)
      if form.is_valid():
          form.save()
          return redirect('/accounts')

   else:
      form = RegistrationForm()

      args = {'form': form}
      return render(request, 'accounts/reg_form.html', args)

urls.py:

urlpatterns = [
  path('', views.home, name="home"),
  path('explore/', views.explore, name='explore'),
  path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'),
  path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
  path('register/', views.register, name='register'),
  path('profile/', views.view_profile, name='profile'),
  path('profile/edit/', views.edit_profile, name='profile-edit'),
  path('change-password/', views.change_password, name='change_password'),
  path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'),
     name='reset-password'),
  path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
  path('reset-password/confirm/<uidb64>/<token>/',
     PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
  path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]

main/urls.py:

urlpatterns = [
   path('', views.login_redirect, name='login_redirect'),
   path('admin/', admin.site.urls),
   path('accounts/', include('accounts.urls')),

  ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Body:
you are not returning anything for the case form is invalid..

def register(request):
   if request.method == 'POST':
      form = RegistrationForm(request.POST)
      if form.is_valid():
          form.save()
          return redirect('/accounts')
      else: #new
          return render(request, 'accounts/reg_form.html',  {'errors':form.errors})#new

   else:
      form = RegistrationForm()

      args = {'form': form}
      return render(request, 'accounts/reg_form.html', args)

it will redirect to account/reg_form.html with errors generated through forms


答: You can also try to add a click event handler for li and make sure li and anchor tag a takes the same width.

Title: How do i make onClick and href work together?

Body:
I have an a element which has his own href and it works perfectly. The problem is that besides an href element i want to make an onClick function, but when i do so, the href is ignored:

GO TO SECTION

Using this syntax, the someFunction runs, but i'm not being redirected to #someSectionOfThePage.


问:
Trying to do getElementById on a
 which I created within a function, returns null
I am creating a Google Maps info window, in which I want to place a clickable text to set a start and end point.

So, I want to add listeners to the text, which I have created within the initialisation of the window.

In the below code, the showInfoWindow(marker) successfully shows appears and the start/end text is there.

However, if that is the only info window present, I get an error Uncaught TypeError: Cannot read property 'addEventListener' of null.

If I debug, I can't get the element after the infoWindow.open(map, marker); (at which point the window isn't actually visible),
but I can once the window has appeared (it goes through a lot of google's own native code before this happens)

I even tried adding the listeners after the line which calls showInfoWindow(marker) but it still doesn't work.

```<code>function showInfoWindow(marker) {

     var infoWindow = new google.maps.InfoWindow({
    content: (marker.title
      + '<br><img id="thumbnail" src = "img/'
      + marker.title.toLowerCase()
      + '.jpg"><br>'
      + '<ul>'
      + '<li id="infoWindowStart">Start from here</li>'
      + '<li id="infoWindowEnd">End here</li>'
      + '</ul>'
      )

  });

      infoWindow.open(map, marker);

   // then try to add a listener to the newly-created "infoWindowStart"
       document.getElementById("infoWindowStart").addEventListener("click",function(){
  console.log("We're going from here")
 });

}
</code>```

答:
domready event is fired when the info window is attached to DOM.
So you can use the following code.

```<code>infoWindow.addListener("domready", function() {
  var infoWindowDom = document.getElementById("infoWindowStart");
  console.log(infoWindowDom); // check if it's loaded correctly
  infoWindowDom.addEventListener("click", function(){
    console.log("We're going from here")
  });
});
</code>```

Title: Trying to do getElementById on a <li> which I created within a function, returns null

Body:
I am creating a Google Maps info window, in which I want to place a clickable text to set a start and end point.

So, I want to add listeners to the text, which I have created within the initialisation of the window.

In the below code, the showInfoWindow(marker) successfully shows appears and the start/end text is there.

However, if that is the only info window present, I get an error Uncaught TypeError: Cannot read property 'addEventListener' of null.

If I debug, I can't get the element after the infoWindow.open(map, marker); (at which point the window isn't actually visible),
but I can once the window has appeared (it goes through a lot of google's own native code before this happens)

I even tried adding the listeners after the line which calls showInfoWindow(marker) but it still doesn't work.

function showInfoWindow(marker) {

     var infoWindow = new google.maps.InfoWindow({
    content: (marker.title
      + '

'
      + '
'
      + '
Start from here
'
      + '
End here
'
      + '
'
      )

  });

      infoWindow.open(map, marker);

   // then try to add a listener to the newly-created "infoWindowStart"
       document.getElementById("infoWindowStart").addEventListener("click",function(){
  console.log("We're going from here")
 });

}

Body:
domready event is fired when the info window is attached to DOM.
So you can use the following code.

infoWindow.addListener("domready", function() {
  var infoWindowDom = document.getElementById("infoWindowStart");
  console.log(infoWindowDom); // check if it's loaded correctly
  infoWindowDom.addEventListener("click", function(){
    console.log("We're going from here")
  });
});


问:
Adding a public key to ~/.ssh/authorized_keys does not log me in automatically
I added the public SSH key to the authorized_keys file.  ssh localhost should log me in without asking for the password.

I did that and tried typing ssh localhost, but it still asks me to type in the password. Is there another setting that I have to go through to make it work?

I have followed the instructions for changing permissions:

Below is the result if I do ssh -v localhost.

```<code>debug1: Reading configuration data /home/john/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /home/john/.ssh/identity type 1
debug1: identity file /home/john/.ssh/id_rsa type -1
debug1: identity file /home/john/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_4.7p1 Debian-8ubuntu3
debug1: match: OpenSSH_4.7p1 Debian-8ubuntu3 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.7p1 Debian-8ubuntu3
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'localhost' is known and matches the RSA host key.
debug1: Found key in /home/john/.ssh/known_hosts:12
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering public key: /home/john/.ssh/identity
debug1: Server accepts key: pkalg ssh-rsa blen 149
debug1: PEM_read_PrivateKey failed
debug1: read PEM private key done: type <unknown>
</code>```

Then it asks for a passphase after the above log. Why isn't it logging me in without a password?

答:
I had this problem when I added the group of the login user to another user.

Let's say there is an SSH-login user called userA and a non-SSH-login user userB. userA has the group userA as well. I modified userB to have the group userA as well. The lead to the the described behaviour, so that userA was not able to login without a prompt.

After I removed the group userA from userB, the login without a prompt worked again.

Body:
I added the public SSH key to the authorized_keys file.  ssh localhost should log me in without asking for the password.

I did that and tried typing ssh localhost, but it still asks me to type in the password. Is there another setting that I have to go through to make it work?

I have followed the instructions for changing permissions:

Below is the result if I do ssh -v localhost.

debug1: Reading configuration data /home/john/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /home/john/.ssh/identity type 1
debug1: identity file /home/john/.ssh/id_rsa type -1
debug1: identity file /home/john/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_4.7p1 Debian-8ubuntu3
debug1: match: OpenSSH_4.7p1 Debian-8ubuntu3 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.7p1 Debian-8ubuntu3
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'localhost' is known and matches the RSA host key.
debug1: Found key in /home/john/.ssh/known_hosts:12
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering public key: /home/john/.ssh/identity
debug1: Server accepts key: pkalg ssh-rsa blen 149
debug1: PEM_read_PrivateKey failed
debug1: read PEM private key done: type <unknown>

Then it asks for a passphase after the above log. Why isn't it logging me in without a password?


问:
How to create a FOR where every 10 correct questions raise a level
I have to find the method where every 10 correct questions raise 1 level and so on.

void updateScoreAndLevel(int answerGiven){

```<code>    if(isCorrect(answerGiven)) {
        for (int i = 1; i <= currentLevel; i = i + 100) {
            currentScore = currentScore + 100;
        }
        for (int i = 10; i <= currentScore; i++) {
            currentLevel = currentLevel + i;
        }

    }else{
        currentScore = currentScore - 50;
        currentLevel = currentLevel ;
    }
</code>```

I hope that every 10 correct questions go up one level but it does not give me

答:
```<code>        if(isCorrect) {
        for (int i = 1; i <= currentLevel; i = i + 100) {
            currentScore = currentScore + 100;
            amountCorrect + 1;
        }
        for (int i = 10; i <= currentScore; i++) {
            currentLevel = currentLevel + i;
        }

    }else{
        currentScore = currentScore - 50;
        currentLevel = currentLevel ;
    }

    if(amountCorrect % 10 == 1){
        currentLevel + 1;
    }
</code>```

Something like this i think. You can add a amountCorrect interger. Which goes up every time the player get's it right. If he get's it wrong you can lower it (if you want to)

the % ,aka the modulo (not good with names), will check if the player has 10 or more answers correct and adds a level. Is this what you wanted?

Body:
I have to find the method where every 10 correct questions raise 1 level and so on.

void updateScoreAndLevel(int answerGiven){

    if(isCorrect(answerGiven)) {
        for (int i = 1; i <= currentLevel; i = i + 100) {
            currentScore = currentScore + 100;
        }
        for (int i = 10; i <= currentScore; i++) {
            currentLevel = currentLevel + i;
        }

    }else{
        currentScore = currentScore - 50;
        currentLevel = currentLevel ;
    }

I hope that every 10 correct questions go up one level but it does not give me

Body:
        if(isCorrect) {
        for (int i = 1; i <= currentLevel; i = i + 100) {
            currentScore = currentScore + 100;
            amountCorrect + 1;
        }
        for (int i = 10; i <= currentScore; i++) {
            currentLevel = currentLevel + i;
        }

    }else{
        currentScore = currentScore - 50;
        currentLevel = currentLevel ;
    }

    if(amountCorrect % 10 == 1){
        currentLevel + 1;
    }

Something like this i think. You can add a amountCorrect interger. Which goes up every time the player get's it right. If he get's it wrong you can lower it (if you want to)

the % ,aka the modulo (not good with names), will check if the player has 10 or more answers correct and adds a level. Is this what you wanted?


问:
Compare two html files
Hi
I want to compare code of two HTML files. How do I achieve this?</p>

答: I use winmerge when I'm on Windows.</p>

Title: Compare two html files

Body: I use winmerge when I'm on Windows.


问:
How can I change the text of a label in a button event?
Just doing my very first test app with Xamarin.

How can I change (within a button event) the text in the label from "Welcome to Xamarin.Forms!" to "Hello World" ?

I tried to do so with the following XAML script and C# code:

XAMLscript within the Stacklayout and my C# code in mainpage.xaml.cs:

```<code>    <Label Text="Welcome to Xamarin.Forms!"
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" />
    <Button Text="click here" Clicked="Button_Clicked" />

private void Button_Clicked(object sender, EventArgs e)
    {
        Label.Text = "Hello World";
    }
</code>```

Somehow the system does not accept .Text as a property of the label.

答:
I already found the error myself. Here is the correct code after having added x:Name:</p>

```<code><Label Text="Welcome to Xamarin.Forms!"
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" x:Name="myLabel"/>
    <Button Text="click here" Clicked="Button_Clicked" />

private void Button_Clicked(object sender, EventArgs e)
    {
        myLabel.Text = "Hello World";
    }
</code>```

Body:
Just doing my very first test app with Xamarin.

How can I change (within a button event) the text in the label from "Welcome to Xamarin.Forms!" to "Hello World" ?

I tried to do so with the following XAML script and C# code:

XAMLscript within the Stacklayout and my C# code in mainpage.xaml.cs:

    <Button Text="click here" Clicked="Button_Clicked" />

private void Button_Clicked(object sender, EventArgs e)
    {
        Label.Text = "Hello World";
    }

Somehow the system does not accept .Text as a property of the label.

Body:
I already found the error myself. Here is the correct code after having added x:Name:

<Label Text="Welcome to Xamarin.Forms!"
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" x:Name="myLabel"/>
    <Button Text="click here" Clicked="Button_Clicked" />

private void Button_Clicked(object sender, EventArgs e)
    {
        myLabel.Text = "Hello World";
    }


问:
Need help on how to use onActivityResult() on Adapter Class?
I tried to return a phone number from a contact list on my adapter class, when i use  super.onActivityResult(requestCode, resultCode, data); I got error.

```<code>btnContactGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
                // Show only contacts with phone numbers

intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                // Start the Contacts activity
                context.startActivityForResult(intent, PICK_CONTACT);

            }
        });

public void onActivityResult(int requestCode, int resultCode, Intent data) {

 super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case PICK_CONTACT :
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI};
Cursor c = conR.query(contactData, projection, null, null, null);
                c.moveToFirst();
int nameIdx =c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx =c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI);
                String name = c.getString(nameIdx);
                String phoneNumber = c.getString(phoneNumberIdx);
                String photo = c.getString(photoIdx);
                if (name == null) {
                    name = "No Name";
                }
                String nwPhone = phoneNumber.replace("+251", "0");

                edtPhoneGift.setText(nwPhone);
                c.close();

                // Now you have the phone number

            }
            break;
    }
 }
</code>```

Can not resolve method onActivityResult(int, int, Intent)

答: onActivityResult() needs to be implemented on the activity or fragment on which you call startActivityForResult(). In your case, that would be whatever activity or fragment is identified by context (from context.startActivityForResult(intent, PICK_CONTACT)).

Body:
I tried to return a phone number from a contact list on my adapter class, when i use  super.onActivityResult(requestCode, resultCode, data); I got error.

btnContactGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
                // Show only contacts with phone numbers

intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                // Start the Contacts activity
                context.startActivityForResult(intent, PICK_CONTACT);

            }
        });

public void onActivityResult(int requestCode, int resultCode, Intent data) {

 super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case PICK_CONTACT :
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI};
Cursor c = conR.query(contactData, projection, null, null, null);
                c.moveToFirst();
int nameIdx =c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx =c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI);
                String name = c.getString(nameIdx);
                String phoneNumber = c.getString(phoneNumberIdx);
                String photo = c.getString(photoIdx);
                if (name == null) {
                    name = "No Name";
                }
                String nwPhone = phoneNumber.replace("+251", "0");

                edtPhoneGift.setText(nwPhone);
                c.close();

                // Now you have the phone number

            }
            break;
    }
 }

Can not resolve method onActivityResult(int, int, Intent)


问:
Image in the card appears very poorly because of styles (Bootstrap 4)
If you upload an image which has higher height and less width then it shows very poorly in the card (user cards). Here are the HTML and css parts. We are using Angular with it:

HTML

```<code><div class="container-fluid" >
  <div class="row people-row">
    <div class="col-12 row">
      <div class="m1-* col-md-3 text-center" *ngFor="let user of filteredUsers | filter: searchByKeyword: 'name' | paginate: { itemsPerPage: 12, currentPage: p }">
        <div class="card card-person">
          <a  (click)="ViewUser(user)">
            <img class="card-img-top" src="http://res.cloudinary.com/dfg5p1pww/image/upload/v{{user.picVersion}}/{{user.picId}}"
            alt="Card image" style="width:100%">
            <div class="card-body">
              <h4 class="card-title"> {{user.firstName}} {{user.lastName}}</h4>
              <p class="card-text">{{user.age}}</p>
              <p class="card-text">{{user.country}},{{user.city}}</p>
              <p class="material-icons" *ngIf="CheckIfOnline(user.username)">online</p>
              <a class="btn button-image closeButton btn-message" [routerLink]="['/chat', user.username]">Message</a>
            </div>
          </a>
        </div>
      </div>
    </div>
</code>```

CSS

```<code>.card-img-top {
    position: relative;
    overflow: hidden;
    height: 200px;
    width: auto
}

.card-person {
  margin: 50px auto;
  background-color: #ffffff;
  border-radius: 0;
  border: 0;
  box-shadow: 1em 1em 2em rgba(0,0,0,.2);
}

.card-text {
 margin-bottom:0.2rem
}

.btn-match,
.btn-message {
  color:#ffffff;
  background: #FF512F;  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #FF512F, #DD2476);  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #FF512F, #DD2476); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
transition: all .4s;
margin:5px;
border-radius:40px
}

.button-image:before {
  content: "";
  width: 23px;
  height: 23px;
  display: inline-block;
  background-size: 100%;
  vertical-align: text-top;
  background-color: transparent;
  background-position : center center;
  background-repeat:no-repeat;
}

.btn-match.closeButton:before{
   background-image : url('../../../assets/images/heart-white.png');
}

.btn-message.closeButton:before{
  background-image : url('../../../assets/images/chat-white.png');

}

a.fill {
  width: 100%;
  height: 50px;
  }
</code>```

What can cause such an issue and how can this problem be fixed in Bootstrap 4 so all type of images can be look normal?

答:
The issue is caused by the background-size CSS property. When set to 100% the browser is trying to stretch the background image to fill the container in both directions.

The background-size property takes several "keyword" inputs as well as percentage or pixel sizes.

background-size:cover will make the smallest size fill the container with the remaining image "overflow" hidden.

background-size:contain will make the largest part of the image fill the container with a "letterbox" effect for any excess.

Then you can use background-position to define where that excess content get's cut or what part of the container is exposed.

body {
  font-family: Arial, Helvetica, Sans-Serif;
}
img {
  width: 250px;
}

hr {
  margin: 20px 0;
}

div {
  position: relative;
  width: 300px;
  height: 300px;
  margin-bottom: 20px;
  border: 1px solid #dadada;
  background-image: url(https://images.unsplash.com/photo-1556229040-2a7bc8a00a3e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9);
  background-color: blue;
  background-position: center center;
  background-repeat: no-repeat;
}

span {
  position: absolute;
  bottom: 20px;
  right: 20px;
  color: white;
  text-shadow: 0 0 3px rgba(0,0,0,0.2);
}

.cover {
  background-size: cover;
}

.contain {
  background-size: contain;
}

.pos {
  background-position: top left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://images.unsplash.com/photo-1556229040-2a7bc8a00a3e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9" />
<p>Image from Unsplash</p>

<hr />

<div class="cover">
  <span>background-size:cover</span>
</div>

<div class="contain">
  <span>background-size:contain</span>
</div>

<div class="cover pos">
  <span>Cover + background-position: left top</span>
</div>

<div class="contain pos">
  <span>Contain + background-position: left top</span>
</div></code>```

Body:
If you upload an image which has higher height and less width then it shows very poorly in the card (user cards). Here are the HTML and css parts. We are using Angular with it:

HTML

 {{user.firstName}} {{user.lastName}}

{{user.age}}

{{user.country}},{{user.city}}

online

              Message

CSS

.card-img-top {
    position: relative;
    overflow: hidden;
    height: 200px;
    width: auto
}

.card-person {
  margin: 50px auto;
  background-color: #ffffff;
  border-radius: 0;
  border: 0;
  box-shadow: 1em 1em 2em rgba(0,0,0,.2);
}

.card-text {
 margin-bottom:0.2rem
}

.btn-match,
.btn-message {
  color:#ffffff;
  background: #FF512F;  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #FF512F, #DD2476);  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #FF512F, #DD2476); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
transition: all .4s;
margin:5px;
border-radius:40px
}

.button-image:before {
  content: "";
  width: 23px;
  height: 23px;
  display: inline-block;
  background-size: 100%;
  vertical-align: text-top;
  background-color: transparent;
  background-position : center center;
  background-repeat:no-repeat;
}

.btn-match.closeButton:before{
   background-image : url('../../../assets/images/heart-white.png');
}

.btn-message.closeButton:before{
  background-image : url('../../../assets/images/chat-white.png');

}

a.fill {
  width: 100%;
  height: 50px;
  }

What can cause such an issue and how can this problem be fixed in Bootstrap 4 so all type of images can be look normal?

Body:
The issue is caused by the background-size CSS property. When set to 100% the browser is trying to stretch the background image to fill the container in both directions.

The background-size property takes several "keyword" inputs as well as percentage or pixel sizes.

background-size:cover will make the smallest size fill the container with the remaining image "overflow" hidden.

background-size:contain will make the largest part of the image fill the container with a "letterbox" effect for any excess.

Then you can use background-position to define where that excess content get's cut or what part of the container is exposed.

body {
  font-family: Arial, Helvetica, Sans-Serif;
}
img {
  width: 250px;
}

hr {
  margin: 20px 0;
}

div {
  position: relative;
  width: 300px;
  height: 300px;
  margin-bottom: 20px;
  border: 1px solid #dadada;
  background-image: url(https://images.unsplash.com/photo-1556229040-2a7bc8a00a3e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9);
  background-color: blue;
  background-position: center center;
  background-repeat: no-repeat;
}

span {
  position: absolute;
  bottom: 20px;
  right: 20px;
  color: white;
  text-shadow: 0 0 3px rgba(0,0,0,0.2);
}

.cover {
  background-size: cover;
}

.contain {
  background-size: contain;
}

.pos {
  background-position: top left;
}

<img src="https://images.unsplash.com/photo-1556229040-2a7bc8a00a3e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9" />
<p>Image from Unsplash</p>

<hr />

<div class="cover">
  <span>background-size:cover</span>
</div>

<div class="contain">
  <span>background-size:contain</span>
</div>

<div class="cover pos">
  <span>Cover + background-position: left top</span>
</div>

<div class="contain pos">
  <span>Contain + background-position: left top</span>
</div>