问:
Calculating average of list from certain point in list?
I have a question, I know that it is possible to calculate the average of a list but is it possible to calculate average but from a certain point?

For example:

```<code>def Average(lst):
    return sum(lst) / len(lst)

list = [2, 8, 6, 7, 3, 2, 1]
average = Average(lst)
</code>```

Printing average of the list:

```<code>print("Average of the list =", round(average, 2))
</code>```

Output:
    Average of the list = 4.14

Say we want to keep the first 3 values and average the rest to have only 4 values in the list

So my new list is:

```<code>list = [2, 8, 6, 7, 3, 2, 1]
new_list = [2, 8, 6, 12.25]
</code>```

Edit 1

Thank you all for your answers. I have another question, say, I don't know the length of my list and I just want 4 elements in my new list. How could I tackle this?

答:
Your function Average will work just as well on a slice of the original list.

So, for your example:

```<code>new_list = list[:3] + [Average(list[3:])]
print(new_list)
</code>```

Will output:

[2, 8, 6, 3.25]

The slice syntax used here is useful fro selecting only sub sequences of a list. In summary, the syntax is list[start:stop:step] with each of start, stop and step being optional. You can read more here. The examples given will be particularly helpful.

Body:
I have a question, I know that it is possible to calculate the average of a list but is it possible to calculate average but from a certain point?

For example:

def Average(lst):
    return sum(lst) / len(lst)

list = [2, 8, 6, 7, 3, 2, 1]
average = Average(lst)

Printing average of the list:

print("Average of the list =", round(average, 2))

Output:
    Average of the list = 4.14

Say we want to keep the first 3 values and average the rest to have only 4 values in the list

So my new list is:

list = [2, 8, 6, 7, 3, 2, 1]
new_list = [2, 8, 6, 12.25]

Edit 1

Thank you all for your answers. I have another question, say, I don't know the length of my list and I just want 4 elements in my new list. How could I tackle this?

Body:
Your function Average will work just as well on a slice of the original list.

So, for your example:

new_list = list[:3] + [Average(list[3:])]
print(new_list)

Will output:

[2, 8, 6, 3.25]

The slice syntax used here is useful fro selecting only sub sequences of a list. In summary, the syntax is list[start:stop:step] with each of start, stop and step being optional. You can read more here. The examples given will be particularly helpful.


来源: stackexchange

问:
how to convert this string to an array?
I'm trying to convert this array I create in JS to then used in my controller to used in a foreach and used the data of the array. I'm using the framework codeigniter.

Here where I create the array in my JS file.

```<code>function get_array(){
  var datos = []; // Array
  $("#tbl_esctructura tbody > tr").each(function() {

    var item = $(this).find('td:eq(1)').text();
    var cantidad = $(this).find('td:eq(4)').text();

    datos.push({
       "item": item,
       "cantidad": cantidad
    });
  });

  datos =  JSON.stringify(datos);
  $.ajax({
        data: {
            'datos': datos
        },
        url: "<?php echo base_url() ?>Controller/data_from_array",
        type: 'POST',
        dataType : "json",
        success: function(response) {

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

the data I send to the controller look like this.
[{"item":"1","cantidad":"2"},{"item":"2","cantidad":"4"}]

Now my controller PHP

```<code>public function data_from_array(){
   $data   =  $this->input->post('datos', TRUE);
   $items = explode(',', $data);
   var_dump($items);
   foreach ($items as $row) {
       echo  $row->item.'<br>';
   }
}
</code>```

and the var_dump($items) this is the result

array(2) { [0]=> string(12) "[{"item":"1"" [1]=> string(16) ""cantidad":"1"}]" }
        }

And in this echo I get this error Message: Trying to get property 'item' of non-object

And I don't know what I'm doing wrong

答:
You can use this code as the explode return array, not an object.</p>

```<code>public function data_from_array(){
  $data   =  $this->input->post('datos', TRUE);
  $items = explode(',', $data);
  var_dump($items);
   foreach ($items as $row) {
      echo  $row["item"].'<br>';
   }
</code>```

ContentLicense: CC BY-SA 4.0

Title: how to convert this string to an array?

Body:
I'm trying to convert this array I create in JS to then used in my controller to used in a foreach and used the data of the array. I'm using the framework codeigniter.

Here where I create the array in my JS file.

function get_array(){
  var datos = []; // Array
  $("#tbl_esctructura tbody > tr").each(function() {

    var item = $(this).find('td:eq(1)').text();
    var cantidad = $(this).find('td:eq(4)').text();

    datos.push({
       "item": item,
       "cantidad": cantidad
    });
  });

  datos =  JSON.stringify(datos);
  $.ajax({
        data: {
            'datos': datos
        },
        url: "<?php echo base_url() ?>Controller/data_from_array",
        type: 'POST',
        dataType : "json",
        success: function(response) {

        }
    });
}

the data I send to the controller look like this.
[{"item":"1","cantidad":"2"},{"item":"2","cantidad":"4"}]

Now my controller PHP

public function data_from_array(){
   $data   =  $this->input->post('datos', TRUE);
   $items = explode(',', $data);
   var_dump($items);
   foreach ($items as $row) {
       echo  $row->item.'
';
   }
}

and the var_dump($items) this is the result

array(2) { [0]=> string(12) "[{"item":"1"" [1]=> string(16) ""cantidad":"1"}]" }
        }

And in this echo I get this error Message: Trying to get property 'item' of non-object

And I don't know what I'm doing wrong

Body:
You can use this code as the explode return array, not an object.

public function data_from_array(){
  $data   =  $this->input->post('datos', TRUE);
  $items = explode(',', $data);
  var_dump($items);
   foreach ($items as $row) {
      echo  $row["item"].'<br>';
   }


问:
Tasks in parallel using C#. Am I doing this right?
I've already search and read about, I just want to make sure if I am right. I have three methods that I want to run in parallel, and I want to make sure that all of them are done before continue. They are all async, and this code are inside an async method. I've done this:

```<code>public async ProcessBegin() {
   //... some code

   await SomeProcess();
   await AnotherMethod().
}

public async SomeProcess() {
   //.. some code

   var tasks = new Task[3];
   tasks[0] = method1();
   tasks[1] = method2();
   tasks[2] = method3();

   Task.WaitAll(tasks);
}

public async Method1(){...}
public async Method2(){...}
public async Method3(){...}
</code>```

Is this right?

答:
```<code>public async Task SomeProcess()
{
    //.. some code

    await Task.WhenAll(method1(), method2(), method3());
}
</code>```

Use Task.WhenAll which returns a new Task that completes once all the provided tasks have also completed.

You don't need to create the array manually because Task.WhenAll accepts params Task[].

Using Task.WaitAll, as you have tried, will block the current thread until the tasks complete, hence rendering the method synchronous.

Furthermore, it could cause deadlocks depending on the synchronisation context of your app, as method1 / method2 / method3 may attempt to resume on the thread blocked by WaitAll.

Body:
I've already search and read about, I just want to make sure if I am right. I have three methods that I want to run in parallel, and I want to make sure that all of them are done before continue. They are all async, and this code are inside an async method. I've done this:

public async ProcessBegin() {
   //... some code

   await SomeProcess();
   await AnotherMethod().
}

public async SomeProcess() {
   //.. some code

   var tasks = new Task[3];
   tasks[0] = method1();
   tasks[1] = method2();
   tasks[2] = method3();

   Task.WaitAll(tasks);
}

public async Method1(){...}
public async Method2(){...}
public async Method3(){...}

Is this right?

Body:
public async Task SomeProcess()
{
    //.. some code

    await Task.WhenAll(method1(), method2(), method3());
}

Use Task.WhenAll which returns a new Task that completes once all the provided tasks have also completed.

You don't need to create the array manually because Task.WhenAll accepts params Task[].

Using Task.WaitAll, as you have tried, will block the current thread until the tasks complete, hence rendering the method synchronous.

Furthermore, it could cause deadlocks depending on the synchronisation context of your app, as method1 / method2 / method3 may attempt to resume on the thread blocked by WaitAll.


问:
How to change chars between 2 strings?
I want to change a char in a String with another in second String, the distance is 3.

For example:

String s1:abc,
String s2:abcdef->s2 will be abadef then -> abadeb.

If it is possible all chars from first String should goes to second s2. I have to mention that upperCase letters from the first should be lowerCase, and only letters will be taken from the first String. I know Strings are immutable

```<code>public static void Encrypt(String s1, String s2) {
        s1 = s1.toLowerCase();
        StringBuilder finalS2 = new StringBuilder();
        finalS2.append(s2);

        for (int i = 0; i < finalS2.length(); i++) {

            if (s1.charAt(i) >= 'a' && s1.charAt(i) <= 'z') {

                finalS2.setCharAt(i + 2, s1.charAt(0));

                break;
            }
        }

        System.out.println(finalS2);
    }
</code>```

I think in my method, which I don't think is a good idea, I should place another for loop for s1 and a break somewhere. I tried many methods, with charArray, etc. but didn't managed.

答:
If I've understood correctly this should work. everyX in your example would be 3</p>

```<code>public static String encrypt(String s1, String s2, int everyX) {
    //Start with S2
    StringBuilder finalS2 = new StringBuilder(s2);
    s1 = s1.toLowerCase();

    int indexInS1 = 0;
    //Whilst there are characters in S2 and S1 left to iterate over
    for (int placeInS2 = 0; placeInS2 < finalS2.length() && indexInS1 < s1.length(); placeInS2++) {
         //Has there been everyX places encountered and the character in S1 is alphanumeric
        if ((placeInS2 + 1) % everyX == 0) {
            if (Character.isAlphabetic(s1.charAt(indexInS1)) {
                finalS2.setCharAt(placeInS2, s1.charAt(indexInS1));
            }
            indexInS1++;
        }
    }

    return finalS2.toString();
}
</code>```

Title: How to change chars between 2 strings?

Body:
I want to change a char in a String with another in second String, the distance is 3.

For example:

String s1:abc,
String s2:abcdef->s2 will be abadef then -> abadeb.

If it is possible all chars from first String should goes to second s2. I have to mention that upperCase letters from the first should be lowerCase, and only letters will be taken from the first String. I know Strings are immutable

public static void Encrypt(String s1, String s2) {
        s1 = s1.toLowerCase();
        StringBuilder finalS2 = new StringBuilder();
        finalS2.append(s2);

        for (int i = 0; i < finalS2.length(); i++) {

            if (s1.charAt(i) >= 'a' && s1.charAt(i) <= 'z') {

                finalS2.setCharAt(i + 2, s1.charAt(0));

                break;
            }
        }

        System.out.println(finalS2);
    }

I think in my method, which I don't think is a good idea, I should place another for loop for s1 and a break somewhere. I tried many methods, with charArray, etc. but didn't managed.

Body:
If I've understood correctly this should work. everyX in your example would be 3

public static String encrypt(String s1, String s2, int everyX) {
    //Start with S2
    StringBuilder finalS2 = new StringBuilder(s2);
    s1 = s1.toLowerCase();

    int indexInS1 = 0;
    //Whilst there are characters in S2 and S1 left to iterate over
    for (int placeInS2 = 0; placeInS2 < finalS2.length() && indexInS1 < s1.length(); placeInS2++) {
         //Has there been everyX places encountered and the character in S1 is alphanumeric
        if ((placeInS2 + 1) % everyX == 0) {
            if (Character.isAlphabetic(s1.charAt(indexInS1)) {
                finalS2.setCharAt(placeInS2, s1.charAt(indexInS1));
            }
            indexInS1++;
        }
    }

    return finalS2.toString();
}


问:
Angular routerLinkActive for multiple paths
In my Angular 5 project I've got a bootstrap nav-bar menu. routerLinkActive does work nicely when the start of the path matches the routerlink of the menu, like:

```<code><li [routerLinkActive]="['active']">
  <a [routerLink]="['/entity/teacher']">Teacher</a>
</li>
</code>```

the Code above activates the menu item nicely for `/entity/teacher/add' and more

Problem is, I've got a Kind of 'catch-all' navigation item which contains things which do not line up:

```<code><li [routerLinkActive]="['active']">
  <a [routerLink]="['/config']">Configuration</a>
</li>
</code>```

I want this item to highlight for the paths /tasks and /entity/settings, too, not only for /config.

Problem is, I can't change the routing of the app. How do I get the menu item to line up for other routing paths as well as the one in the routerLink?

答:
as specified there are multiple routerLinks but only one routerLinkActive show highlight or enabled.for that this works fine
for me.

```<code><a class="nav-link" href="javascript:void(0)" routerLink='/rulesConfiguration' routerLinkActive='active' [ngClass]="{'active': createRules.isActive}"><i class="nav-icon fa fa-list-alt "></i>Rules Configuration</a>
<a class="nav-link" href="javascript:void(0)" routerLink="/createRules" routerLinkActive #createRules="routerLinkActive" style="display: none"><i class="nav-icon fa fa-list-alt "></i>Rules </a>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my Angular 5 project I've got a bootstrap nav-bar menu. routerLinkActive does work nicely when the start of the path matches the routerlink of the menu, like:

  Teacher

the Code above activates the menu item nicely for `/entity/teacher/add' and more

Problem is, I've got a Kind of 'catch-all' navigation item which contains things which do not line up:

  Configuration

I want this item to highlight for the paths /tasks and /entity/settings, too, not only for /config.

Problem is, I can't change the routing of the app. How do I get the menu item to line up for other routing paths as well as the one in the routerLink?

Body:
as specified there are multiple routerLinks but only one routerLinkActive show highlight or enabled.for that this works fine
for me.

<a class="nav-link" href="javascript:void(0)" routerLink='/rulesConfiguration' routerLinkActive='active' [ngClass]="{'active': createRules.isActive}"><i class="nav-icon fa fa-list-alt "></i>Rules Configuration</a>
<a class="nav-link" href="javascript:void(0)" routerLink="/createRules" routerLinkActive #createRules="routerLinkActive" style="display: none"><i class="nav-icon fa fa-list-alt "></i>Rules </a>


问:
Does pip take into account the actual Python version when installing compatible package versions?
I have a library that has to support several Python versions starting from 2.6. E.g., one of my requirements is requests. I know that the last version supporting Python 2.6 is 2.19.1 (the latest version 2.20.0 supports any Python >= 2.7).

So my question is whether pip understands that the line requests~=2.19 in requirements should install 2.19.1 for Python 2.6 and 2.20.0 for any higher version of Python?

Update. The question is not about the syntax, I'm curious whether pip is smart enough and in a Python 2.6 environment will be able not to go beyond 0.19.1.

答:
I believe yes, pip does take into account the version of the currently running Python interpreter, to choose an appropriate version (or distribution of a version) of a project to install. So since pip install 'requests~=2.19' is the equivalent of pip install 'requests>=2.19,requests==2.*', it should give as of today (2020-02-18):

requests 2.19.1 on Python 2.6; and

requests 2.22.0 on Python 2.7.


问:
Fetch value from Azure Key Vault reference (Managed identity)
I am trying to fetch secret values from azure key vault in Azure App Service.
My App Service has a managed identity
In the Azure Key vault, this managed identity is added under 'Role assignments' as 'Key vault contributor'
Also access policies has been added in azure key vault to give 'Get' permission to the AppServices's managed identity
Now in my c# code, I am trying to get the value of the AppSetting element using the code
ConfigurationManager.AppSettings['something'];

In my azure app service, under app settings, I have added the a key with name 'something' and it has the value pointing to the reference of the Key Vault as below:

```<code>@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)
</code>```

Now I am able to retrieve the value from the appsettings, but instead of the actual value, it is pulling the output as @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/c96f02080254f109c51a1f1cdb1931)

I am expecting the output to be value that I have set, not the keyvault reference string itself.

I am using .Net MVC 4.7 web app

答:
As junnas said, you just add webapp's MSI in key vault Access policy.

1.Turn on webapp System-assign managed identity.

2.Add the identity into keyvault Access policy with secret Get permission.

3.Add the reference of the Key Vault into webapp Application settings.

4.Use Environment.GetEnvironmentVariable("AppsettingName"); to get the secret vaule.

Here is the output:

Body:
I am trying to fetch secret values from azure key vault in Azure App Service.
My App Service has a managed identity
In the Azure Key vault, this managed identity is added under 'Role assignments' as 'Key vault contributor'
Also access policies has been added in azure key vault to give 'Get' permission to the AppServices's managed identity
Now in my c# code, I am trying to get the value of the AppSetting element using the code
ConfigurationManager.AppSettings['something'];

In my azure app service, under app settings, I have added the a key with name 'something' and it has the value pointing to the reference of the Key Vault as below:

@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)

Now I am able to retrieve the value from the appsettings, but instead of the actual value, it is pulling the output as @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/c96f02080254f109c51a1f1cdb1931)

I am expecting the output to be value that I have set, not the keyvault reference string itself.

I am using .Net MVC 4.7 web app


问:
Create calendar event using ruby outlook
I am trying create a event in calendar,

Iam able get all the data like calendar,contacts and emails by following below documentaion,

https://learn.microsoft.com/en-us/outlook/rest/ruby-tutorial,

But when try to create a event using ruby_outlook getting below error

```<code>  {"ruby_outlook_error"=>401,
   "ruby_outlook_response"=>{"error"=>{"code"=>"InvalidAudience", "message"=>"The audience claim value is invalid 'aud'.",
   "innerError"=>{"requestId"=>"75984820-5241-11ea-b6fc-fc4dd44c1550", "date"=>"2020-02-18T11:26:08"}}}}
</code>```

Below code is for creating event

```<code>def def index
   token = get_access_token   //getting access token
   if token
      outlook_client = RubyOutlook::Client.new
      event_payload =
      {
         "Subject": "Discuss the Calendar REST API",
        "Body": {
        "ContentType": "HTML",
        "Content": "I think it will meet our requirements!"
        },
        "Start": {
        "DateTime": "2020-03-03T18:00:00",
        "TimeZone": "Pacific Standard Time"
        },
        "End": {
        "DateTime": "2020-03-03T19:00:00",
        "TimeZone": "Pacific Standard Time"
        },
        "Attendees": [
        {
        "EmailAddress": {
        "Address": "john@example.com",
        "Name": "John Doe"
        },
        "Type": "Required"
        }
        ]
      }
      outlook_client.create_event(token, event_payload, nil, 'user@domain.com')
   end
end
</code>```

答:
Your issue is that the token that you fetched was using the Microsoft graph API but now you are trying to create an even through the Outlook API. You cannot use a token issued for Graph ("aud": "graph.microsoft.com") against the Outlook endpoint. You need a token with "aud": "outlook.office.com".Better is use the graph API itself using the graph gem to create an event since you already have the token fetched from it.

To do that first create the MicrosoftGraph object

```<code>def create_service_auth
  access_token = get_access_token
  callback =  Proc.new do |r|
    r.headers['Authorization'] = "Bearer #{access_token}"
    r.headers['Content-Type']  = 'application/json'
    r.headers['X-AnchorMailbox'] = "#{ email_of_calendar_for_which_to_create_the_event }"
  end
  @graph = ::MicrosoftGraph.new(base_url: 'https://graph.microsoft.com/v1.0',
                            cached_metadata_file: File.join(MicrosoftGraph::CACHED_METADATA_DIRECTORY, 'metadata_v1.0.xml'),
                              &callback)
end
</code>```

Then create the event -

```<code>def create_event
  event = {
    subject: summary,
    body: {
      content_type: "HTML",
      content: description
    },
    start: {
      date_time: start_time,
      time_zone: timezone
    },
    end: {
      date_time: end_time,
      time_zone: timezone
    },
    response_requested: true,
    organizer: {emailAddress: { name: "#{organizer.full_name}", address: email_of_calendar_for_which_to_create_the_event }},
    attendees: [
      {
        email_address: {
          address: attendee_email,
          name: "#{attendee.full_name}"
        },
        type: "required"
      }
    ]
  }

  result = @graph.me.events.create(event)
end
</code>```

Body:
I am trying create a event in calendar,

Iam able get all the data like calendar,contacts and emails by following below documentaion,

https://learn.microsoft.com/en-us/outlook/rest/ruby-tutorial,

But when try to create a event using ruby_outlook getting below error

  {"ruby_outlook_error"=>401,
   "ruby_outlook_response"=>{"error"=>{"code"=>"InvalidAudience", "message"=>"The audience claim value is invalid 'aud'.",
   "innerError"=>{"requestId"=>"75984820-5241-11ea-b6fc-fc4dd44c1550", "date"=>"2020-02-18T11:26:08"}}}}

Below code is for creating event

def def index
   token = get_access_token   //getting access token
   if token
      outlook_client = RubyOutlook::Client.new
      event_payload =
      {
         "Subject": "Discuss the Calendar REST API",
        "Body": {
        "ContentType": "HTML",
        "Content": "I think it will meet our requirements!"
        },
        "Start": {
        "DateTime": "2020-03-03T18:00:00",
        "TimeZone": "Pacific Standard Time"
        },
        "End": {
        "DateTime": "2020-03-03T19:00:00",
        "TimeZone": "Pacific Standard Time"
        },
        "Attendees": [
        {
        "EmailAddress": {
        "Address": "john@example.com",
        "Name": "John Doe"
        },
        "Type": "Required"
        }
        ]
      }
      outlook_client.create_event(token, event_payload, nil, 'user@domain.com')
   end
end

Body:
Your issue is that the token that you fetched was using the Microsoft graph API but now you are trying to create an even through the Outlook API. You cannot use a token issued for Graph ("aud": "graph.microsoft.com") against the Outlook endpoint. You need a token with "aud": "outlook.office.com".Better is use the graph API itself using the graph gem to create an event since you already have the token fetched from it.

To do that first create the MicrosoftGraph object

def create_service_auth
  access_token = get_access_token
  callback =  Proc.new do |r|
    r.headers['Authorization'] = "Bearer #{access_token}"
    r.headers['Content-Type']  = 'application/json'
    r.headers['X-AnchorMailbox'] = "#{ email_of_calendar_for_which_to_create_the_event }"
  end
  @graph = ::MicrosoftGraph.new(base_url: 'https://graph.microsoft.com/v1.0',
                            cached_metadata_file: File.join(MicrosoftGraph::CACHED_METADATA_DIRECTORY, 'metadata_v1.0.xml'),
                              &callback)
end

Then create the event -

def create_event
  event = {
    subject: summary,
    body: {
      content_type: "HTML",
      content: description
    },
    start: {
      date_time: start_time,
      time_zone: timezone
    },
    end: {
      date_time: end_time,
      time_zone: timezone
    },
    response_requested: true,
    organizer: {emailAddress: { name: "#{organizer.full_name}", address: email_of_calendar_for_which_to_create_the_event }},
    attendees: [
      {
        email_address: {
          address: attendee_email,
          name: "#{attendee.full_name}"
        },
        type: "required"
      }
    ]
  }

  result = @graph.me.events.create(event)
end


问:
Automation Testing approach - Which is best?
Which is the best suited automation approach? is it Data driven testing or Keyword driven testing? Now even we have Business process testing, what according to you is best approach?</p>

答: It depends what you are trying to accomplish in your particular situation.  One thing that is universal, however, is that test automation is software development, and needs to be treated as such.  Use sound design and coding practices.  It sounds like you are new to automation.  Often a good place to start is building a smoke test that will quickly run for each new build.</p>

OwnerDisplayName: Pavan

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Tom E


问:
How to getRange() of a group of cells while doing iteration in a Google Apps Script?
I want to check if there is any blank cells in a given range and trying to use below code for that. Problem is Range is not certain and subject to change with every iteration.
I tried something like getRange('A'+ row : 'H'+ row) but its in wrong syntax. Can someone help me with this issue ? Thanks!

var sheet1 = spreadsheet.getSheetByName('Red'); // Get worksheet
var endRow = sheet1.getLastRow();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Get current active spreadsheet.
var sheet2 = spreadsheet.getSheetByName('Template');
var runloop = true;
var startRow = 3;

for (var row = startRow; row <= endRow; row++) {

    var sheet_name = sheet1.getRange("A" + row).getValue(); // Get the JD number for the file name.
    var range = sheet1.getRange('A' + row: 'H' + row);

    if (range.isBlank()) {
        # Dome Something here
    }
}
```

答:
You can try Utilities.formatString

```<code>var range = sheet1.getRange(Utilities.formatString('A%s:H%s', row, row));
</code>```

For V8 runtime

```<code>const range = sheet1.getRange(`A${row}:H${row}`);
</code>```

Body:
You can try Utilities.formatString

var range = sheet1.getRange(Utilities.formatString('A%s:H%s', row, row));

For V8 runtime

const range = sheet1.getRange(`A${row}:H${row}`);


问:
Using multiple viewholders for several laytous
I'm an average programmer, and I'm trying to finalize a project, but I crashed again on an issue that is making me sleepy.
The point is that i am trying to use several layouts in a recycleview, taking the data from firebase, in this case i will use several viewholders, but i did several tests with content that i searched, but some errors occur and i couldn't solve it. Can someone help me?
I'll put all the code here, point out the errors, and if there is a simpler way to do this, you can talk.
In the future I will reuse the code for another part of the application with more than 10 views.

Firebase.

Main.class

```<code>package com.example.visualizarautomoveis;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import com.example.visualizarautomoveis.Adapatadores.AdaptadorGeral;
import com.example.visualizarautomoveis.Models.ModelBicicleta;
import com.example.visualizarautomoveis.Models.ModelCompleto;
import com.example.visualizarautomoveis.Models.ModelMoto;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {

    private final String ested = "GE";
    private final String city = "Geoneion";

    DatabaseReference automoveis_banco;

    FirebaseDatabase database;

    ArrayList<ModelCompleto> list;

    private Context context;

    private RecyclerView recyclerView;

    RecyclerView.LayoutManager manager;
    AdaptadorGeral adaptadorGeral;

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

        recyclerView = findViewById(R.id.recyclerview);

        list = new ArrayList<ModelCompleto>();

        manager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(manager);

        automoveis_banco = FirebaseDatabase.getInstance().getReference().child(estet).child(cidy).child("Automoveis");

        automoveis_banco.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot eventSnapshot: dataSnapshot.getChildren())
                {
                    ModelCompleto mod =eventSnapshot.getValue(ModelCompleto.class);
                    list.add(mod);

                    Collections.reverse(list);
                }
                adaptadorGeral = new AdaptadorGeral(MainActivity.this,list);
                recyclerView.setAdapter(adaptadorGeral);
                adaptadorGeral.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

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

AdaptadorGeral.class

```<code>package com.example.visualizarautomoveis.Adapatadores;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.visualizarautomoveis.Models.ModelCompleto;
import com.example.visualizarautomoveis.R;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos;

import java.util.ArrayList;

public class AdaptadorGeral extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context context;
    private final ArrayList<ModelCompleto> completos;

    private final String BICICLETA = "0";
    private final String MOTO = "1";

    public AdaptadorGeral(Context context, ArrayList<ModelCompleto> completos)
    {
        this.context = context;
        this.completos = completos;

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        switch (completos.get(viewType).getTipo()){
            case "0":
                return new ViewHolderBicicletas(LayoutInflater.from(context).inflate(R.layout.popup_automoveis_bicicletas,parent,false));

            case "1":
                return new ViewHolderMotos(LayoutInflater.from(context).inflate(R.layout.popup_automoveis_motocicletas, parent, false));

            default:
                break;
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        switch (completos.get(position).getTipo()){

            case "0":
                RequestOptions requestOptions1 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                ViewHolderBicicletas viewHolderBicicletas = (ViewHolderBicicletas) holder;

                ((ViewHolderBicicletas) holder).textViewMarca.setText(completos.get(position).getMarca());
                ((ViewHolderBicicletas) holder).textViewAno.setText(completos.get(position).getAno());
                ((ViewHolderBicicletas) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                ((ViewHolderBicicletas) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                ((ViewHolderBicicletas) holder).textViewValor.setText("R$ "+completos.get(position).getValor());
                Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions1).into(((ViewHolderBicicletas) holder).imageViewFoto);
            case "1":
                RequestOptions requestOptions2 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                ViewHolderMotos viewHolderMotos = (ViewHolderMotos)holder;

                ((ViewHolderMotos) holder).textViewMarca.setText(completos.get(position).getMarca());
                ((ViewHolderMotos) holder).textViewModelo.setText(completos.get(position).getModelo());
                ((ViewHolderMotos) holder).textViewAno.setText(completos.get(position).getAno());
                ((ViewHolderMotos) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                ((ViewHolderMotos) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                ((ViewHolderMotos) holder).textViewValor.setText("R$ "+completos.get(position).getValor());

                Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions2).into(((ViewHolderMotos) holder).imageViewFoto);

        }
    }

    @Override
    public int getItemCount() {

        if (completos != null){
            return this.completos.size();
        }else {
            return 0;
        }
    }

    @Override
    public int getItemViewType(int position) {

        if (completos.get(position).getTipo().equals("0"))
            return 0;
        if (completos.get(position).getTipo().equals("1")) {
            return 1;
        }
        return position;
    }
}
</code>```

ViewHolderBicicletas.class

```<code>package com.example.visualizarautomoveis.ViewHolderes;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.visualizarautomoveis.R;

public class ViewHolderBicicletas extends RecyclerView.ViewHolder{

    public  TextView textViewMarca;
    public  TextView textViewAno;
    public  TextView textViewDescrip;
    public  TextView textViewDataPublicacao;
    public  TextView textViewValor;
    public  ImageView imageViewFoto;

    public ViewHolderBicicletas(@NonNull View itemView) {
        super(itemView);

        textViewAno = itemView.findViewById(R.id.popup_ano_bicicleta);
        textViewMarca = itemView.findViewById(R.id.popup_marca_bicicleta);
        textViewDescrip = itemView.findViewById(R.id.popup_descricao_bicicleta);
        textViewDataPublicacao = itemView.findViewById(R.id.popup_data_pubicacao_bicicleta);
        imageViewFoto = itemView.findViewById(R.id.popup_imagem_central_bicicletas);
        textViewValor = itemView.findViewById(R.id.popup_valor_bicicleta);
    }
}
</code>```

ViewHolderMotos.class

```<code>package com.example.visualizarautomoveis.ViewHolderes;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.visualizarautomoveis.R;

public class ViewHolderMotos extends RecyclerView.ViewHolder{

    public  TextView textViewMarca;
    public  TextView textViewModelo;
    public  TextView textViewAno;
    public  TextView textViewDescrip;
    public  TextView textViewDataPublicacao;
    public  TextView textViewValor;
    public  ImageView imageViewFoto;

    public ViewHolderMotos(@NonNull View itemView) {
        super(itemView);
        textViewAno = itemView.findViewById(R.id.popup_ano_motocicleta);
        textViewMarca = itemView.findViewById(R.id.popup_marca_motocicleta);
        textViewModelo = itemView.findViewById(R.id.popup_modelo_motocicleta);
        textViewDescrip = itemView.findViewById(R.id.popup_descricao_motocicleta);
        textViewDataPublicacao = itemView.findViewById(R.id.popup_data_public_moto);
        textViewValor = itemView.findViewById(R.id.popup_valor_motocicleta);

        imageViewFoto = itemView.findViewById(R.id.popup_imagem_central_motocicletas);

    }
}
</code>```

ModelCompleto.class

```<code>package com.example.visualizarautomoveis.Models;

public class ModelCompleto {
    private String valor,descricao,datapubicacao,foto1,marca,ano,modelo,tipo;

    public ModelCompleto() {
    }

    public ModelCompleto(String valor, String descricao, String datapubicacao, String foto1, String marca, String ano, String modelo, String tipo) {
        this.valor = valor;
        this.descricao = descricao;
        this.datapubicacao = datapubicacao;
        this.foto1 = foto1;
        this.marca = marca;
        this.ano = ano;
        this.modelo = modelo;
        this.tipo = tipo;
    }

    public String getValor() {
        return valor;
    }

    public void setValor(String valor) {
        this.valor = valor;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public String getDatapubicacao() {
        return datapubicacao;
    }

    public void setDatapubicacao(String datapubicacao) {
        this.datapubicacao = datapubicacao;
    }

    public String getFoto1() {
        return foto1;
    }

    public void setFoto1(String foto1) {
        this.foto1 = foto1;
    }

    public String getMarca() {
        return marca;
    }

    public void setMarca(String marca) {
        this.marca = marca;
    }

    public String getAno() {
        return ano;
    }

    public void setAno(String ano) {
        this.ano = ano;
    }

    public String getModelo() {
        return modelo;
    }

    public void setModelo(String modelo) {
        this.modelo = modelo;
    }

    public String getTipo() {
        return tipo;
    }

    public void setTipo(String tipo) {
        this.tipo = tipo;
    }
}
</code>```

Error that appears when running the program:

```<code>D/TextView: setTypeface with style : 0
W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.visualizarautomoveis, PID: 27653
    java.lang.ClassCastException: com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas cannot be cast to com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos
        at com.example.visualizarautomoveis.Adapatadores.AdaptadorGeral.onBindViewHolder(AdaptadorGeral.java:84)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1080)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1742)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1742)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:3175)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2776)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2477)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1544)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7602)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
        at android.view.Choreographer.doCallbacks(Choreographer.java:686)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7331)
Process 27653 terminated.
</code>```

答: I think you forgot to add break statements in switch block inside onBindViewHolder method.</p>

Body:
I'm an average programmer, and I'm trying to finalize a project, but I crashed again on an issue that is making me sleepy.
The point is that i am trying to use several layouts in a recycleview, taking the data from firebase, in this case i will use several viewholders, but i did several tests with content that i searched, but some errors occur and i couldn't solve it. Can someone help me?
I'll put all the code here, point out the errors, and if there is a simpler way to do this, you can talk.
In the future I will reuse the code for another part of the application with more than 10 views.

Firebase.

Main.class

package com.example.visualizarautomoveis;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import com.example.visualizarautomoveis.Adapatadores.AdaptadorGeral;
import com.example.visualizarautomoveis.Models.ModelBicicleta;
import com.example.visualizarautomoveis.Models.ModelCompleto;
import com.example.visualizarautomoveis.Models.ModelMoto;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {

    private final String ested = "GE";
    private final String city = "Geoneion";

    DatabaseReference automoveis_banco;

    FirebaseDatabase database;

    ArrayList<ModelCompleto> list;

    private Context context;

    private RecyclerView recyclerView;

    RecyclerView.LayoutManager manager;
    AdaptadorGeral adaptadorGeral;

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

        recyclerView = findViewById(R.id.recyclerview);

        list = new ArrayList<ModelCompleto>();

        manager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(manager);

        automoveis_banco = FirebaseDatabase.getInstance().getReference().child(estet).child(cidy).child("Automoveis");

        automoveis_banco.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot eventSnapshot: dataSnapshot.getChildren())
                {
                    ModelCompleto mod =eventSnapshot.getValue(ModelCompleto.class);
                    list.add(mod);

                    Collections.reverse(list);
                }
                adaptadorGeral = new AdaptadorGeral(MainActivity.this,list);
                recyclerView.setAdapter(adaptadorGeral);
                adaptadorGeral.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

AdaptadorGeral.class

package com.example.visualizarautomoveis.Adapatadores;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.visualizarautomoveis.Models.ModelCompleto;
import com.example.visualizarautomoveis.R;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos;

import java.util.ArrayList;

public class AdaptadorGeral extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context context;
    private final ArrayList<ModelCompleto> completos;

    private final String BICICLETA = "0";
    private final String MOTO = "1";

    public AdaptadorGeral(Context context, ArrayList<ModelCompleto> completos)
    {
        this.context = context;
        this.completos = completos;

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        switch (completos.get(viewType).getTipo()){
            case "0":
                return new ViewHolderBicicletas(LayoutInflater.from(context).inflate(R.layout.popup_automoveis_bicicletas,parent,false));

            case "1":
                return new ViewHolderMotos(LayoutInflater.from(context).inflate(R.layout.popup_automoveis_motocicletas, parent, false));

            default:
                break;
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        switch (completos.get(position).getTipo()){

            case "0":
                RequestOptions requestOptions1 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                ViewHolderBicicletas viewHolderBicicletas = (ViewHolderBicicletas) holder;

                ((ViewHolderBicicletas) holder).textViewMarca.setText(completos.get(position).getMarca());
                ((ViewHolderBicicletas) holder).textViewAno.setText(completos.get(position).getAno());
                ((ViewHolderBicicletas) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                ((ViewHolderBicicletas) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                ((ViewHolderBicicletas) holder).textViewValor.setText("R$ "+completos.get(position).getValor());
                Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions1).into(((ViewHolderBicicletas) holder).imageViewFoto);
            case "1":
                RequestOptions requestOptions2 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                ViewHolderMotos viewHolderMotos = (ViewHolderMotos)holder;

                ((ViewHolderMotos) holder).textViewMarca.setText(completos.get(position).getMarca());
                ((ViewHolderMotos) holder).textViewModelo.setText(completos.get(position).getModelo());
                ((ViewHolderMotos) holder).textViewAno.setText(completos.get(position).getAno());
                ((ViewHolderMotos) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                ((ViewHolderMotos) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                ((ViewHolderMotos) holder).textViewValor.setText("R$ "+completos.get(position).getValor());

                Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions2).into(((ViewHolderMotos) holder).imageViewFoto);

        }
    }

    @Override
    public int getItemCount() {

        if (completos != null){
            return this.completos.size();
        }else {
            return 0;
        }
    }

    @Override
    public int getItemViewType(int position) {

        if (completos.get(position).getTipo().equals("0"))
            return 0;
        if (completos.get(position).getTipo().equals("1")) {
            return 1;
        }
        return position;
    }
}

ViewHolderBicicletas.class

package com.example.visualizarautomoveis.ViewHolderes;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.visualizarautomoveis.R;

public class ViewHolderBicicletas extends RecyclerView.ViewHolder{

    public  TextView textViewMarca;
    public  TextView textViewAno;
    public  TextView textViewDescrip;
    public  TextView textViewDataPublicacao;
    public  TextView textViewValor;
    public  ImageView imageViewFoto;

    public ViewHolderBicicletas(@NonNull View itemView) {
        super(itemView);

        textViewAno = itemView.findViewById(R.id.popup_ano_bicicleta);
        textViewMarca = itemView.findViewById(R.id.popup_marca_bicicleta);
        textViewDescrip = itemView.findViewById(R.id.popup_descricao_bicicleta);
        textViewDataPublicacao = itemView.findViewById(R.id.popup_data_pubicacao_bicicleta);
        imageViewFoto = itemView.findViewById(R.id.popup_imagem_central_bicicletas);
        textViewValor = itemView.findViewById(R.id.popup_valor_bicicleta);
    }
}

ViewHolderMotos.class

package com.example.visualizarautomoveis.ViewHolderes;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.visualizarautomoveis.R;

public class ViewHolderMotos extends RecyclerView.ViewHolder{

    public  TextView textViewMarca;
    public  TextView textViewModelo;
    public  TextView textViewAno;
    public  TextView textViewDescrip;
    public  TextView textViewDataPublicacao;
    public  TextView textViewValor;
    public  ImageView imageViewFoto;

    public ViewHolderMotos(@NonNull View itemView) {
        super(itemView);
        textViewAno = itemView.findViewById(R.id.popup_ano_motocicleta);
        textViewMarca = itemView.findViewById(R.id.popup_marca_motocicleta);
        textViewModelo = itemView.findViewById(R.id.popup_modelo_motocicleta);
        textViewDescrip = itemView.findViewById(R.id.popup_descricao_motocicleta);
        textViewDataPublicacao = itemView.findViewById(R.id.popup_data_public_moto);
        textViewValor = itemView.findViewById(R.id.popup_valor_motocicleta);

        imageViewFoto = itemView.findViewById(R.id.popup_imagem_central_motocicletas);

    }
}

ModelCompleto.class

package com.example.visualizarautomoveis.Models;

public class ModelCompleto {
    private String valor,descricao,datapubicacao,foto1,marca,ano,modelo,tipo;

    public ModelCompleto() {
    }

    public ModelCompleto(String valor, String descricao, String datapubicacao, String foto1, String marca, String ano, String modelo, String tipo) {
        this.valor = valor;
        this.descricao = descricao;
        this.datapubicacao = datapubicacao;
        this.foto1 = foto1;
        this.marca = marca;
        this.ano = ano;
        this.modelo = modelo;
        this.tipo = tipo;
    }

    public String getValor() {
        return valor;
    }

    public void setValor(String valor) {
        this.valor = valor;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public String getDatapubicacao() {
        return datapubicacao;
    }

    public void setDatapubicacao(String datapubicacao) {
        this.datapubicacao = datapubicacao;
    }

    public String getFoto1() {
        return foto1;
    }

    public void setFoto1(String foto1) {
        this.foto1 = foto1;
    }

    public String getMarca() {
        return marca;
    }

    public void setMarca(String marca) {
        this.marca = marca;
    }

    public String getAno() {
        return ano;
    }

    public void setAno(String ano) {
        this.ano = ano;
    }

    public String getModelo() {
        return modelo;
    }

    public void setModelo(String modelo) {
        this.modelo = modelo;
    }

    public String getTipo() {
        return tipo;
    }

    public void setTipo(String tipo) {
        this.tipo = tipo;
    }
}

Error that appears when running the program:

D/TextView: setTypeface with style : 0
W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.visualizarautomoveis, PID: 27653
    java.lang.ClassCastException: com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas cannot be cast to com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos
        at com.example.visualizarautomoveis.Adapatadores.AdaptadorGeral.onBindViewHolder(AdaptadorGeral.java:84)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1080)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1742)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1742)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:3175)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2776)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2477)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1544)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7602)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
        at android.view.Choreographer.doCallbacks(Choreographer.java:686)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7331)
Process 27653 terminated.


答:
there are two scenarios:

if you want to parse JSON object, then

```<code>$items = json_decode($data); // instead of $items = explode(',', $data);
</code>```

if you want to treat data as a strings then

```<code>echo  $row[0].'<br>'; // instead of echo  $row->item.'<br>';
</code>```

Title: how to convert this string to an array?

Body:
there are two scenarios:

if you want to parse JSON object, then

$items = json_decode($data); // instead of $items = explode(',', $data);

if you want to treat data as a strings then

echo  $row[0].'<br>'; // instead of echo  $row->item.'<br>';


问:
How to store values from a function in python?
I have a function:

```<code>def get_val():
    for a in b:
        c = b['values']
        print (c)
</code>```

When I call the function get_val(), I get the result which is a long list of values with numbering up to 1000.  type(c) is float.

Now I want to store this result from the function into a variable e. I tried using return c instead of print(c)

Return function is not convenient because it will only return a line instead of the whole 1000.

答:
One-liner in Python using list comprehension:

```<code>def get_val(b):
    # Do something else
    return [i["values"] for i in b]
</code>```

Note: I am assuming you mistyped a['values'] and you meant i[values]

Body:
I have a function:

def get_val():
    for a in b:
        c = b['values']
        print (c)

When I call the function get_val(), I get the result which is a long list of values with numbering up to 1000.  type(c) is float.

Now I want to store this result from the function into a variable e. I tried using return c instead of print(c)

Return function is not convenient because it will only return a line instead of the whole 1000.

Body:
One-liner in Python using list comprehension:

def get_val(b):
    # Do something else
    return [i["values"] for i in b]

Note: I am assuming you mistyped a['values'] and you meant i[values]


问:
How to get id number of file system watcher is deleted?
Main Code:

```<code>    static void Main(string[] args)
    {

        MySqlConnection mcon = new MySqlConnection("connection credentials...");
        MySqlDataReader myreader = null;
        MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
        mcon.Open();

        myreader = cmd.ExecuteReader();

        //List of path's from MySQL table
        List<String> list = new List<String>();

        while (myreader.Read())
        {
            //Appending the list of all path names from MySQL table
            list.Add(myreader[1].ToString());
            //Retrieving id number of path from MySQL table (see list before 'private static void directoryChange')
            list2.Add(myreader.GetInt32(0));

        }
        mcon.Close();

        //This watches all path's listed in MySQL table
        foreach (string i in list)
        {

            Console.WriteLine(i);
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = Path.GetDirectoryName($@"{i}"); //get specific files listed in MySQL table
            watcher.Filter = Path.GetFileName($@"{i}");
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = true;

            watcher.Created += directoryChange;
            watcher.Deleted += directoryChange;
            watcher.Renamed += onRename;
        }

        Console.Read();
    }

    //List of Id numbers from MySQL table
    static List<int> list2 = new List<int>();

    private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
    {
                if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted){
                Console.WriteLine($"Deleted {e.FullPath}"); //Here I need to get the id number of file that has been deleted
                 }
    }
</code>```

Goal:

My goal is to get the id number from MySQL of the file that has been deleted.

The file system watches only files listed from MySQL table.

But how can I print the id number of the record that has just deleted? within the directoryChange?

Update:

This is where I got to now:

```<code>static void Main(string[] args)
{

    MySqlConnection mcon = new MySqlConnection("connection credentials...");
    MySqlDataReader myreader = null;
    MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
    mcon.Open();

    myreader = cmd.ExecuteReader();

    //List of path's from MySQL table
    List<String> list = new List<String>();
   //List of Id numbers from MySQL table
   static List<int> list2 = new List<int>();

    while (myreader.Read())
    {
        //Appending the list of all path names from MySQL table
        list.Add(myreader[1].ToString());
        //Retrieving id number of path from MySQL table (see list before 'private static void directoryChange')
        list2.Add(myreader.GetInt32(0));

    }
    mcon.Close();

    //This watches all path's listed in MySQL table
        var data = list.Zip(list2, (n, w) => new {Path= n, ID = w});

        foreach(var nw in data)
        {
            int result = nw.ID;
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = Path.GetDirectoryName($@"{nw.Path}");
            watcher.Filter = Path.GetFileName($@"{nw.Path}");
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = true;

            watcher.Created += directoryChange;
            watcher.Deleted += directoryChange;
            watcher.Renamed += onRename;
        }

    Console.Read();
}
//Tried passing over the id from for loop
static int result;

private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
{
            if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted){
            Console.WriteLine($"Deleted {e.FullPath}");
            Console.WriteLine(result);
             }
}
</code>```

This does not work, because result shows as 0. Will see if I can fix this.

答:
So to recap what I parsed from your code:

You read a list of files from a SQL table

You initialize a FileSystemWatcher on the directory of each file, with a filter on the name of each file

You bind all event listeners of all watchers to the same handlers

In the handler, where you only get the full path to the file you're being alerted about, you want to know the "id" (i.e. primary key of the table) for the given path

So, simply keep a dictionary with the data around instead of two lists or a single static variable?

```<code>// Class-level field
private static Dictionary<string, int> fileList = new Dictionary<string, int>();

// Then while reading the data:
while (myreader.Read())
{
    // Use path as a key to the id, so you can use the path later to look up the key
    fileList[myreader[1].ToString()] = myreader.GetInt32(0);
}

foreach(var nw in fileList)
{
    // ...
}
</code>```

And then in your event handler:

```<code>private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
{
    if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted)
    {
        if (fileList.TryGetValue(e.FullPath, out var id))
        {
            Console.WriteLine(id);
        }
        else
        {
            Console.WriteLine($"Path '{e.FullPath}' not present in dictionary?");
        }
    }
}
</code>```

Body:
Main Code:

    static void Main(string[] args)
    {

        MySqlConnection mcon = new MySqlConnection("connection credentials...");
        MySqlDataReader myreader = null;
        MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
        mcon.Open();

        myreader = cmd.ExecuteReader();

        //List of path's from MySQL table
        List<String> list = new List<String>();

        while (myreader.Read())
        {
            //Appending the list of all path names from MySQL table
            list.Add(myreader[1].ToString());
            //Retrieving id number of path from MySQL table (see list before 'private static void directoryChange')
            list2.Add(myreader.GetInt32(0));

        }
        mcon.Close();

        //This watches all path's listed in MySQL table
        foreach (string i in list)
        {

            Console.WriteLine(i);
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = Path.GetDirectoryName($@"{i}"); //get specific files listed in MySQL table
            watcher.Filter = Path.GetFileName($@"{i}");
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = true;

            watcher.Created += directoryChange;
            watcher.Deleted += directoryChange;
            watcher.Renamed += onRename;
        }

        Console.Read();
    }

    //List of Id numbers from MySQL table
    static List<int> list2 = new List<int>();

    private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
    {
                if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted){
                Console.WriteLine($"Deleted {e.FullPath}"); //Here I need to get the id number of file that has been deleted
                 }
    }

Goal:

My goal is to get the id number from MySQL of the file that has been deleted.

The file system watches only files listed from MySQL table.

But how can I print the id number of the record that has just deleted? within the directoryChange?

Update:

This is where I got to now:

static void Main(string[] args)
{

    MySqlConnection mcon = new MySqlConnection("connection credentials...");
    MySqlDataReader myreader = null;
    MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
    mcon.Open();

    myreader = cmd.ExecuteReader();

    //List of path's from MySQL table
    List<String> list = new List<String>();
   //List of Id numbers from MySQL table
   static List<int> list2 = new List<int>();

    while (myreader.Read())
    {
        //Appending the list of all path names from MySQL table
        list.Add(myreader[1].ToString());
        //Retrieving id number of path from MySQL table (see list before 'private static void directoryChange')
        list2.Add(myreader.GetInt32(0));

    }
    mcon.Close();

    //This watches all path's listed in MySQL table
        var data = list.Zip(list2, (n, w) => new {Path= n, ID = w});

        foreach(var nw in data)
        {
            int result = nw.ID;
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = Path.GetDirectoryName($@"{nw.Path}");
            watcher.Filter = Path.GetFileName($@"{nw.Path}");
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = true;

            watcher.Created += directoryChange;
            watcher.Deleted += directoryChange;
            watcher.Renamed += onRename;
        }

    Console.Read();
}
//Tried passing over the id from for loop
static int result;

private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
{
            if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted){
            Console.WriteLine($"Deleted {e.FullPath}");
            Console.WriteLine(result);
             }
}

This does not work, because result shows as 0. Will see if I can fix this.

Body:
So to recap what I parsed from your code:

You read a list of files from a SQL table

You initialize a FileSystemWatcher on the directory of each file, with a filter on the name of each file

You bind all event listeners of all watchers to the same handlers

In the handler, where you only get the full path to the file you're being alerted about, you want to know the "id" (i.e. primary key of the table) for the given path

So, simply keep a dictionary with the data around instead of two lists or a single static variable?

// Class-level field
private static Dictionary<string, int> fileList = new Dictionary<string, int>();

// Then while reading the data:
while (myreader.Read())
{
    // Use path as a key to the id, so you can use the path later to look up the key
    fileList[myreader[1].ToString()] = myreader.GetInt32(0);
}

foreach(var nw in fileList)
{
    // ...
}

And then in your event handler:

private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
{
    if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted)
    {
        if (fileList.TryGetValue(e.FullPath, out var id))
        {
            Console.WriteLine(id);
        }
        else
        {
            Console.WriteLine($"Path '{e.FullPath}' not present in dictionary?");
        }
    }
}


问:
Using case when clause in insert values
So I have this insert statement, and I need to check another table before setting the number1 & number2 columns. I've used the case when statement in the values part of the insert statement. Is there a better way of doing this without duplicating code when setting both of these columns.

```<code>INSERT INTO history (
    user_id
    ,number1
    ,number2
    )
VALUES (
    'user1'
    ,CASE
        WHEN (
                SELECT user_id
                FROM old_history
                WHERE user_id = 'user1'
                ) IS NOT NULL
            THEN 12.3
        ELSE NULL
        END
    ,CASE
        WHEN (
                SELECT user_id
                FROM old_history
                WHERE user_id = 'user1'
                ) IS NOT NULL
            THEN 15
        ELSE NULL
        END
    );
</code>```

Thanks.

答:
Try this:</p>

```<code>INSERT INTO history (user_id, number1, number2)
SELECT
 'user1'
, case when count(1)=1 then 12.3 end
, case when count(1)=1 then 15   end
FROM old_history
WHERE user_id = 'user1';
</code>```

Title: Using case when clause in insert values

Body:
So I have this insert statement, and I need to check another table before setting the number1 & number2 columns. I've used the case when statement in the values part of the insert statement. Is there a better way of doing this without duplicating code when setting both of these columns.

INSERT INTO history (
    user_id
    ,number1
    ,number2
    )
VALUES (
    'user1'
    ,CASE
        WHEN (
                SELECT user_id
                FROM old_history
                WHERE user_id = 'user1'
                ) IS NOT NULL
            THEN 12.3
        ELSE NULL
        END
    ,CASE
        WHEN (
                SELECT user_id
                FROM old_history
                WHERE user_id = 'user1'
                ) IS NOT NULL
            THEN 15
        ELSE NULL
        END
    );

Thanks.

Body:
Try this:

INSERT INTO history (user_id, number1, number2)
SELECT
 'user1'
, case when count(1)=1 then 12.3 end
, case when count(1)=1 then 15   end
FROM old_history
WHERE user_id = 'user1';


问:
Send Object as string, not JSON, via Node Express
Ok, I want the response to be a plain string, not JSON.

Ex. this object

let obj = {
  foo: 'bar',
  baz: 1
}
```

<p>Should be returned as </p>

```"{foo: 'bar', baz: 1}"
```

<p>Instead of</p>

```{"foo": "bar", "baz": 1}
```

<p>Why? I need to use the string as a link in quickchart</p>

<pre class="lang-html prettyprint-override"><code><img src="https://quickchart.io/chart?c={type:'line',data:{labels:['January','February', 'March','April', 'May'], datasets:[{label:'Dogs', data: [50,60,70,180,190], fill:false,borderColor:'blue'},{label:'Cats', data:[100,200,300,400,500], fill:false,borderColor:'green'}]}}">
</code>```

The double quotes in JSON break the image link.

Or, maybe suggest a better way.

答:
You can use JSON.stringify for this.

```<code>let obj = {
  foo: 'bar',
  baz: 1
}

console.log(JSON.stringify(obj));
</code>```

This will convert the object into string.

Body:
Ok, I want the response to be a plain string, not JSON.

Ex. this object

let obj = {
  foo: 'bar',
  baz: 1
}

Should be returned as

"{foo: 'bar', baz: 1}"

Instead of

{"foo": "bar", "baz": 1}

Why? I need to use the string as a link in quickchart

The double quotes in JSON break the image link.

Or, maybe suggest a better way.

Body:
You can use JSON.stringify for this.

let obj = {
  foo: 'bar',
  baz: 1
}

console.log(JSON.stringify(obj));

This will convert the object into string.


问:
Spring ReactiveCrudRepository ExistsQuery method returns null
Any idea why the following code would return a mono of null? I realize why the contract would allow it but I would expect the Spring code to return either a true or a false.</p>

```<code>public interface SampleRepository extends ReactiveCrudRepository<Sample, String> {
    @ExistsQuery("{ userId: ?0 }")
    Mono<Boolean> existsWithUserId(String userId);

    @Query("{ userId: ?0 }")
    Mono<Sample> findWithUserId(String userId);
}
</code>```

答: If the repository can't find the entry, it will return a Mono</p>

Body:
Any idea why the following code would return a mono of null? I realize why the contract would allow it but I would expect the Spring code to return either a true or a false.

public interface SampleRepository extends ReactiveCrudRepository<Sample, String> {
    @ExistsQuery("{ userId: ?0 }")
    Mono<Boolean> existsWithUserId(String userId);

    @Query("{ userId: ?0 }")
    Mono<Sample> findWithUserId(String userId);
}


问:
jQuery .click() and .change() conflict?
I have problem with .click() and .change() functions. I don't know why, but I put them into the html code separately they works, but when I put them together like below they stop working. What is the problem?
The .change() function populates the fields of form in specific table row. The .click() functions add a row to and remove a row from the table within the form.</p>

```<code>$(document).ready(function() {
    $('select[name="produkt[]"]').change(function() {
        var id = $('select[name="produkt[]"] option:selected').val();
        var par = $(this).parent().parent().attr('id');
        $.getJSON(
            '<?php echo $head['site_link'];?>index.php/faktura/pobierzProdukt/'+id,
            function(data){
                alert(par);
                $('#'+par+' input[name="pkwiu[]"]').val(data.product_pkwiu);
                $('#'+par+' input[name="netto[]"]').val(data.product_netto);
                $('#'+par+' input[name="vat[]"]').val(data.product_vat);
                $('#'+par+' input[name="brutto[]"]').val(data.product_brutto);
                $('#'+par+' input[name="jedn[]"]').val(data.product_jedn);
            },
            'json'
        );
    });

    $('#dodajWiersz').click(function() {
        var liczba = $('#produkty tr').length;
        var f1  = '<?php echo form_dropdown('produkt[]',$lista,'');?></td>';
        var f2  = '<?php echo form_input(array('name'=>'pkwiu[]','class'=>'short','readonly'=>'readonly'));?>';
        var f3  = '<?php echo form_input(array('name'=>'netto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f4  = '<?php echo form_input(array('name'=>'vat[]','class'=>'mini','readonly'=>'readonly'));?>';
        var f5  = '<?php echo form_input(array('name'=>'brutto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f6  = '<?php echo form_input(array('name'=>'jedn[]','class'=>'mini','readonly'=>'readonly'));?>';
        var f7  = '<?php echo form_input(array('name'=>'ilosc[]','class'=>'short'));?>';
        var f8  = '<?php echo form_input(array('name'=>'knetto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f9  = '<?php echo form_input(array('name'=>'kvat[]','class'=>'short','readonly'=>'readonly'));?>';
        var f10 = '<?php echo form_input(array('name'=>'kbrutto[]','class'=>'short','readonly'=>'readonly'));?>';

        var row = '<tr id="wiersz-'+liczba+'"><td>'+liczba+'</td><td>'+f1+'</td><td>'+f2+'</td><td>'+f3+'</td><td>'+f4+'</td><td>'+f5+'</td><td>'+f6+'</td><td>'+f7+'</td><td>'+f8+'</td><td>'+f9+'</td><td>'+f10+'</td>';
        $('#produkty').find('tbody').append(row);
    });

    $('#usunWiersz').click(function() {
       $('#produkty').find('tbody tr:last').remove();
    });
});
</code>```

答:
Tips to improve your code;

Don't mix PHP and Javascript code. Your asking for trouble and it just doesn't need to be done. If you need information from PHP available in your Javascript, then use json_encode -- don't write literally to the Javascript file like so:

```<code>var userId = "<?php echo $_GET['user_id']; ?>"
var postId = "<?php echo $_GET['post_id']; ?>"
</code>```

Instead have a PHP file that generates JSON object and have that loaded by a script tag:

```<code><script type="text/javascript" src="/get_json.php"></script>
</code>```

Inside get_json.php will be this magic:

```<code><?php
   $json['user_id'] = $_GET['user_id'];
   $json['post_id'] = $_GET['post_id'];
   echo json_encode($json);
?>
</code>```

Don't repeat code. All your f1 f2 are all unneeded. Why not just put this into a Javascript array, and .join('	') and add  and 	 onto the end.

```<code>var inputsArray = ['<input name="email"/>','<input name="fullname"/>'];

var tdString = '<td>' + inputsArray.join('</td><td>') + '</td>';
</code>```

Although I really don't see why you need PHP to help you create a form and HTML, especially as it's not even using any information specific within your PHP application. It's completely pointless.

Use selectors appropriately and cache.

```<code>$('#'+par+' input[name="pkwiu[]"]').val(data.product_pkwiu);
$('#'+par+' input[name="netto[]"]').val(data.product_netto);
</code>```

Doing this over doing $('#'+par+' over and over is inefficient. Use the context parameter to help you

```<code>var $id = $('#' + par);
$('input[name="pkwiu[]"]', $id).val(data.product_pkwiu);
</code>```

Notice the second parameter of $ is used, which is telling jQuery to select inputs within that context (id of an element in this case). This allows us cache that id so jQuery isn't constantly trying to find it through each iteration.

Don't tie yourself to your own HTML structure.

Avoid using parent parent parent parent parent parent, you get the idea. It'll cause headaches when you make even simple changes in your HTML structure

```<code>var par = $(this).parent().parent().attr('id')`
</code>```

Instead it's far better to utilise the .closest(selector) (which travels up the DOM and stops when it reaches a match) .parents(selector) (which travels up the DOM and matches ALL elements for the selector up until the root, which is usually the body tag)

Without seeing your HTML structure, it's hard to tell what .parent().parent() could be replaced with, but lets guess it's the form element:

```<code>var par = $(this).closest('form').attr('id')`
</code>```

Ok it's getting a little long now. There's plenty of other things I can pick apart, but for now, that's all folks!

Title: jQuery .click() and .change() conflict?

Body:
I have problem with .click() and .change() functions. I don't know why, but I put them into the html code separately they works, but when I put them together like below they stop working. What is the problem?
The .change() function populates the fields of form in specific table row. The .click() functions add a row to and remove a row from the table within the form.

$(document).ready(function() {
    $('select[name="produkt[]"]').change(function() {
        var id = $('select[name="produkt[]"] option:selected').val();
        var par = $(this).parent().parent().attr('id');
        $.getJSON(
            '<?php echo $head['site_link'];?>index.php/faktura/pobierzProdukt/'+id,
            function(data){
                alert(par);
                $('#'+par+' input[name="pkwiu[]"]').val(data.product_pkwiu);
                $('#'+par+' input[name="netto[]"]').val(data.product_netto);
                $('#'+par+' input[name="vat[]"]').val(data.product_vat);
                $('#'+par+' input[name="brutto[]"]').val(data.product_brutto);
                $('#'+par+' input[name="jedn[]"]').val(data.product_jedn);
            },
            'json'
        );
    });

    $('#dodajWiersz').click(function() {
        var liczba = $('#produkty tr').length;
        var f1  = '<?php echo form_dropdown('produkt[]',$lista,'');?>	';
        var f2  = '<?php echo form_input(array('name'=>'pkwiu[]','class'=>'short','readonly'=>'readonly'));?>';
        var f3  = '<?php echo form_input(array('name'=>'netto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f4  = '<?php echo form_input(array('name'=>'vat[]','class'=>'mini','readonly'=>'readonly'));?>';
        var f5  = '<?php echo form_input(array('name'=>'brutto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f6  = '<?php echo form_input(array('name'=>'jedn[]','class'=>'mini','readonly'=>'readonly'));?>';
        var f7  = '<?php echo form_input(array('name'=>'ilosc[]','class'=>'short'));?>';
        var f8  = '<?php echo form_input(array('name'=>'knetto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f9  = '<?php echo form_input(array('name'=>'kvat[]','class'=>'short','readonly'=>'readonly'));?>';
        var f10 = '<?php echo form_input(array('name'=>'kbrutto[]','class'=>'short','readonly'=>'readonly'));?>';

        var row = '
'+liczba+'	'+f1+'	'+f2+'	'+f3+'	'+f4+'	'+f5+'	'+f6+'	'+f7+'	'+f8+'	'+f9+'	'+f10+'	';
        $('#produkty').find('tbody').append(row);
    });

    $('#usunWiersz').click(function() {
       $('#produkty').find('tbody tr:last').remove();
    });
});

Body:
Tips to improve your code;

Don't mix PHP and Javascript code. Your asking for trouble and it just doesn't need to be done. If you need information from PHP available in your Javascript, then use json_encode -- don't write literally to the Javascript file like so:

var userId = "<?php echo $_GET['user_id']; ?>"
var postId = "<?php echo $_GET['post_id']; ?>"

Instead have a PHP file that generates JSON object and have that loaded by a script tag:

<script type="text/javascript" src="/get_json.php"></script>

Inside get_json.php will be this magic:

<?php
   $json['user_id'] = $_GET['user_id'];
   $json['post_id'] = $_GET['post_id'];
   echo json_encode($json);
?>

Don't repeat code. All your f1 f2 are all unneeded. Why not just put this into a Javascript array, and .join('</td><td>') and add <td> and </td> onto the end.

var inputsArray = ['<input name="email"/>','<input name="fullname"/>'];

var tdString = '<td>' + inputsArray.join('</td><td>') + '</td>';

Although I really don't see why you need PHP to help you create a form and HTML, especially as it's not even using any information specific within your PHP application. It's completely pointless.

Use selectors appropriately and cache.

$('#'+par+' input[name="pkwiu[]"]').val(data.product_pkwiu);
$('#'+par+' input[name="netto[]"]').val(data.product_netto);

Doing this over doing $('#'+par+' over and over is inefficient. Use the context parameter to help you

var $id = $('#' + par);
$('input[name="pkwiu[]"]', $id).val(data.product_pkwiu);

Notice the second parameter of $ is used, which is telling jQuery to select inputs within that context (id of an element in this case). This allows us cache that id so jQuery isn't constantly trying to find it through each iteration.

Don't tie yourself to your own HTML structure.

Avoid using parent parent parent parent parent parent, you get the idea. It'll cause headaches when you make even simple changes in your HTML structure

var par = $(this).parent().parent().attr('id')`

Instead it's far better to utilise the .closest(selector) (which travels up the DOM and stops when it reaches a match) .parents(selector) (which travels up the DOM and matches ALL elements for the selector up until the root, which is usually the body tag)

Without seeing your HTML structure, it's hard to tell what .parent().parent() could be replaced with, but lets guess it's the form element:

var par = $(this).closest('form').attr('id')`

Ok it's getting a little long now. There's plenty of other things I can pick apart, but for now, that's all folks!