问:
How to sort data in chart by 3rd variable?
I have a data.frame like this

```<code>head(df)
# Country Value1 Value2 Part
# Germany 2.5    3.5    West
# France  4.2    4.4    West
# Romania 10.3   5      East
# Latvia  12.2   13     East
</code>```

I have chart like this

```<code>ggplot(df) +
  geom_segment(aes(x=Country, xend=Country, y=Value1, yend=Value2), color="grey") +
  geom_point(aes(x=Country, y=Value1), color="red", size=3 ) +
  geom_point(aes(x=Country, y=Value2), color="blue", size=3 ) +
  theme_classic()
</code>```

I want to sort data on x-axis by variable "Part".

Cheers guys.

Data

```<code>df <- structure(list(Country = structure(c(3L, 4L, 1L, 2L), .Label = c("Romania",
"Latvia", "Germany", "France"), class = "factor"), Value1 = c(2.5,
4.2, 10.3, 12.2), Value2 = c(3.5, 4.4, 5, 13), Part = structure(c(2L,
2L, 1L, 1L), .Label = c("East", "West"), class = c("ordered",
"factor"))), row.names = c(NA, -4L), class = "data.frame")
</code>```

答:
The plot from your example data looks like this:

library(ggplot2)

ggplot(df) +
  geom_segment(aes(x=Country, xend=Country, y=Value1, yend=Value2), color="grey") +
  geom_point(aes(x=Country, y=Value1), color="red", size=3 ) +
  geom_point(aes(x=Country, y=Value2), color="blue", size=3 ) +
  theme_classic()
```

<p><img src="https://i.imgur.com/LmTqNj0.png" alt=""></p>

<p>If you want to reorder the countries according to their <code>Part</code> column, first ensure you define the "correct" order of the <code>Part</code> column (however you would like this to be):</p>

<pre class="lang-r prettyprint-override"><code>df$Part <- factor(df$Part, levels = c("East", "West"))
</code>```

Now order your countries' factors according to the order of the levels in Part:

```<code>df$Country <- factor(df$Country, levels = unique(df$Country[order(df$Part)]))
</code>```

Your plot now looks like this:

```<code>ggplot(df) +
  geom_segment(aes(x=Country, xend=Country, y=Value1, yend=Value2), color="grey") +
  geom_point(aes(x=Country, y=Value1), color="red", size=3 ) +
  geom_point(aes(x=Country, y=Value2), color="blue", size=3 ) +
  theme_classic()
</code>```

Created on 2020-05-31 by the reprex package (v0.3.0)

Body:
I have a data.frame like this

head(df)
# Country Value1 Value2 Part
# Germany 2.5    3.5    West
# France  4.2    4.4    West
# Romania 10.3   5      East
# Latvia  12.2   13     East

I have chart like this

ggplot(df) +
  geom_segment(aes(x=Country, xend=Country, y=Value1, yend=Value2), color="grey") +
  geom_point(aes(x=Country, y=Value1), color="red", size=3 ) +
  geom_point(aes(x=Country, y=Value2), color="blue", size=3 ) +
  theme_classic()

I want to sort data on x-axis by variable "Part".

Cheers guys.

Data

df <- structure(list(Country = structure(c(3L, 4L, 1L, 2L), .Label = c("Romania",
"Latvia", "Germany", "France"), class = "factor"), Value1 = c(2.5,
4.2, 10.3, 12.2), Value2 = c(3.5, 4.4, 5, 13), Part = structure(c(2L,
2L, 1L, 1L), .Label = c("East", "West"), class = c("ordered",
"factor"))), row.names = c(NA, -4L), class = "data.frame")

Body:
The plot from your example data looks like this:

library(ggplot2)

ggplot(df) +
  geom_segment(aes(x=Country, xend=Country, y=Value1, yend=Value2), color="grey") +
  geom_point(aes(x=Country, y=Value1), color="red", size=3 ) +
  geom_point(aes(x=Country, y=Value2), color="blue", size=3 ) +
  theme_classic()

If you want to reorder the countries according to their Part column, first ensure you define the "correct" order of the Part column (however you would like this to be):

df$Part <- factor(df$Part, levels = c("East", "West"))

Now order your countries' factors according to the order of the levels in Part:

df$Country <- factor(df$Country, levels = unique(df$Country[order(df$Part)]))

Your plot now looks like this:

ggplot(df) +
  geom_segment(aes(x=Country, xend=Country, y=Value1, yend=Value2), color="grey") +
  geom_point(aes(x=Country, y=Value1), color="red", size=3 ) +
  geom_point(aes(x=Country, y=Value2), color="blue", size=3 ) +
  theme_classic()

Created on 2020-05-31 by the reprex package (v0.3.0)


来源: stackexchange

问:
InterfaceError (0, '')
I have built a site using Django and I am receiving this annoying error when I am trying to execute a query.

If I restart the Apache server, the error will go away for a short time.

```<code>Traceback:
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
100.                     response = callback(request, *callback_args, **callback_kwargs)
File "/home/fran/cron/views/set_caches.py" in set_caches
24.         cursor.execute(query, [category['id']])
File "/usr/local/lib/python2.7/site-packages/django/db/backends/util.py" in execute
15.             return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
86.             return self.cursor.execute(query, args)
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py" in execute
155.         charset = db.character_set_name()

Exception Type: InterfaceError at /blablabla/
Exception Value: (0, '')
</code>```

答:
I had the same issue with Flask+pymysql, I was getting an empty tuple as a result in the except: block, something like this "(\"(0, '')\",)" to be specific.

It turned out that the connection was getting closed and later the code tried accessing it which resulted into this error.
So I solved it by referring to above solutions and used a function for connection which assured me a conn every time I had to access the db.

You can recreate this issue by inserting conn.close() just before accessing the cursor.

For reference I used this site which helped me solve this issue.

https://hackersandslackers.com/python-mysql-pymysql/

ContentLicense: CC BY-SA 3.0

Title: InterfaceError (0, '')

Body:
I have built a site using Django and I am receiving this annoying error when I am trying to execute a query.

If I restart the Apache server, the error will go away for a short time.

Traceback:
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
100.                     response = callback(request, *callback_args, **callback_kwargs)
File "/home/fran/cron/views/set_caches.py" in set_caches
24.         cursor.execute(query, [category['id']])
File "/usr/local/lib/python2.7/site-packages/django/db/backends/util.py" in execute
15.             return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
86.             return self.cursor.execute(query, args)
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py" in execute
155.         charset = db.character_set_name()

Exception Type: InterfaceError at /blablabla/
Exception Value: (0, '')

ContentLicense: CC BY-SA 4.0


问:
Issue with protection script for google sheets - Cannot read property 'getRange' of undefined
Script summery:

The script should loop over sheets protection and ranges protection and find a target sheet and target range.

Then, check if the current user has editor's permissions.

If not - the script checks if the number of users with editor's permission for the target sheet and target range is smaller than the number in the permitted user emails list.

If so - the script removes all permissions from target sheet and target range and re-set them to the permitted user emails list.

My problem: I get this error:

TypeError: Cannot read property 'getRange' of undefined
      at [the getRange properties of both while loops conditions]

The script:

```<code>function someFunction() {
  var ss = SpreadsheetApp.getActive();
  var sheetName = 'some sheet name';
  var rangeName = 'some range name';
  var targetSheet = ss.getSheetByName(sheetName);
  var targetRange = ss.getRangeByName(rangeName);
  // set permissions
  var permittedUserEmails = ['user1@gmail.com','user2@gmail.com','user3@gmail.com','user4@gmail.com','user5@gmail.com'];
  var sheetProtections = ss.getProtections(SpreadsheetApp.ProtectionType.SHEET);
  var rangeProtections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  var i = 0;
  while (sheetProtections[i].getRange().getSheet() != targetSheet {
    i++;
  }
  if (sheetProtections[i].canEdit() == false) {
    if (rangeProtections[i].getEditors().length < permittedUserEmails.length) {
      sheetProtections[i].remove();
      sheetProtections[i].addEditors(permittedUserEmails);
    }
  }
  var j = 0;
  while (rangeProtections[j].getRange() != targetRange {
    j++;
  }
  if (rangeProtections[j].canEdit() == false) {
    if (rangeProtections[j].getEditors().length < permittedUserEmails.length) {
      rangeProtections[j].remove();
      rangeProtections[j].addEditors(permittedUserEmails);
    }
  }
}
</code>```

Note:

If I use Browser.msgBox(sheetProtections[i].getRange()) and Browser.msgBox(rangeProtections[j].getRange()) just before the corresponding while loops I do not get an error at all.

user1@gmail.com is the ss owner.

Can someone please explain what is going on and how to fix this?

Update:
The error was caused due to i and j exceeded the sheetProtections and rangeProtections length, correspondingly without meeting the loops conditions.

A different approach to indicate the target sheet and range solved the problem.

答:
The error occurs because there were no sheet or range protections found of that name.
The getProtections method returns an empty array if there are no protections found.  It doesn't return undefined or null if there are no protections.  It returns a truthy value of an empty array if there are no protections found.  That means that the empty array will have a length of zero.  You are starting the count of the variable i at zero, which is a valid index, and doesn't return an error at the point of sheetProtections[i] even though the value at index zero is undefined.

There are multiple ways that you can deal with that situation, below is one possibility.

```<code>function someFunction() {

  var ss = SpreadsheetApp.openById('1RwwWliVHscvvRLOZ4jTQNtQJOgoTSBAo43VRDMhKzoo');

  var sheetName = 'some';
  var rangeName = 'some';
  var targetSheet = ss.getSheetByName(sheetName);
  var targetRange = ss.getRangeByName(rangeName);
  // set permissions
  var permittedUserEmails = ['user1@gmail.com','user2@gmail.com','user3@gmail.com','user4@gmail.com','user5@gmail.com'];

  var sheetProtections = ss.getProtections(SpreadsheetApp.ProtectionType.SHEET);
  var rangeProtections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);

  Logger.log('sheetProtections: ' + sheetProtections)

  var L = sheetProtections.length;
  Logger.log("L: " + L)
  var i = 0;

  while (i < L) {//If i reaches the L number then it stops - If L is zero and i is zero then zero is not less than zero
    Logger.log('i ' + i)
    if (sheetProtections[i].getRange().getSheet() === targetSheet;) {
      break;
    }

    i++;//decrement
  }

  if (sheetProtections[i].canEdit() == false) {
    if (rangeProtections[i].getEditors().length < permittedUserEmails.length) {
      sheetProtections[i].remove();
      sheetProtections[i].addEditors(permittedUserEmails);
    }
  }

  L =  rangeProtections.length;

  var j = 0;

  while (j < L) {
    if (rangeProtections[j].getRange() === targetRange) {
      break;
    }
    j++;
  }

  if (rangeProtections[j].canEdit() == false) {
    if (rangeProtections[j].getEditors().length < permittedUserEmails.length) {
      rangeProtections[j].remove();
      rangeProtections[j].addEditors(permittedUserEmails);
    }
  }
}
</code>```

Body:
Script summery:

The script should loop over sheets protection and ranges protection and find a target sheet and target range.

Then, check if the current user has editor's permissions.

If not - the script checks if the number of users with editor's permission for the target sheet and target range is smaller than the number in the permitted user emails list.

If so - the script removes all permissions from target sheet and target range and re-set them to the permitted user emails list.

My problem: I get this error:

TypeError: Cannot read property 'getRange' of undefined
      at [the getRange properties of both while loops conditions]

The script:

function someFunction() {
  var ss = SpreadsheetApp.getActive();
  var sheetName = 'some sheet name';
  var rangeName = 'some range name';
  var targetSheet = ss.getSheetByName(sheetName);
  var targetRange = ss.getRangeByName(rangeName);
  // set permissions
  var permittedUserEmails = ['user1@gmail.com','user2@gmail.com','user3@gmail.com','user4@gmail.com','user5@gmail.com'];
  var sheetProtections = ss.getProtections(SpreadsheetApp.ProtectionType.SHEET);
  var rangeProtections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  var i = 0;
  while (sheetProtections[i].getRange().getSheet() != targetSheet {
    i++;
  }
  if (sheetProtections[i].canEdit() == false) {
    if (rangeProtections[i].getEditors().length < permittedUserEmails.length) {
      sheetProtections[i].remove();
      sheetProtections[i].addEditors(permittedUserEmails);
    }
  }
  var j = 0;
  while (rangeProtections[j].getRange() != targetRange {
    j++;
  }
  if (rangeProtections[j].canEdit() == false) {
    if (rangeProtections[j].getEditors().length < permittedUserEmails.length) {
      rangeProtections[j].remove();
      rangeProtections[j].addEditors(permittedUserEmails);
    }
  }
}

Note:

If I use Browser.msgBox(sheetProtections[i].getRange()) and Browser.msgBox(rangeProtections[j].getRange()) just before the corresponding while loops I do not get an error at all.

user1@gmail.com is the ss owner.

Can someone please explain what is going on and how to fix this?

Update:
The error was caused due to i and j exceeded the sheetProtections and rangeProtections length, correspondingly without meeting the loops conditions.

A different approach to indicate the target sheet and range solved the problem.

Body:
The error occurs because there were no sheet or range protections found of that name.
The getProtections method returns an empty array if there are no protections found.  It doesn't return undefined or null if there are no protections.  It returns a truthy value of an empty array if there are no protections found.  That means that the empty array will have a length of zero.  You are starting the count of the variable i at zero, which is a valid index, and doesn't return an error at the point of sheetProtections[i] even though the value at index zero is undefined.

There are multiple ways that you can deal with that situation, below is one possibility.

function someFunction() {

  var ss = SpreadsheetApp.openById('1RwwWliVHscvvRLOZ4jTQNtQJOgoTSBAo43VRDMhKzoo');

  var sheetName = 'some';
  var rangeName = 'some';
  var targetSheet = ss.getSheetByName(sheetName);
  var targetRange = ss.getRangeByName(rangeName);
  // set permissions
  var permittedUserEmails = ['user1@gmail.com','user2@gmail.com','user3@gmail.com','user4@gmail.com','user5@gmail.com'];

  var sheetProtections = ss.getProtections(SpreadsheetApp.ProtectionType.SHEET);
  var rangeProtections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);

  Logger.log('sheetProtections: ' + sheetProtections)

  var L = sheetProtections.length;
  Logger.log("L: " + L)
  var i = 0;

  while (i < L) {//If i reaches the L number then it stops - If L is zero and i is zero then zero is not less than zero
    Logger.log('i ' + i)
    if (sheetProtections[i].getRange().getSheet() === targetSheet;) {
      break;
    }

    i++;//decrement
  }

  if (sheetProtections[i].canEdit() == false) {
    if (rangeProtections[i].getEditors().length < permittedUserEmails.length) {
      sheetProtections[i].remove();
      sheetProtections[i].addEditors(permittedUserEmails);
    }
  }

  L =  rangeProtections.length;

  var j = 0;

  while (j < L) {
    if (rangeProtections[j].getRange() === targetRange) {
      break;
    }
    j++;
  }

  if (rangeProtections[j].canEdit() == false) {
    if (rangeProtections[j].getEditors().length < permittedUserEmails.length) {
      rangeProtections[j].remove();
      rangeProtections[j].addEditors(permittedUserEmails);
    }
  }
}


问:
Python selenium - modifying the source code of a webpage
I am using Python selenium to automate my attendance entry. It was working fine, now I wanted to try by modifying the source code. I have seen few posts stating that it can be modified using driver.execute_script() and it works for JavaScript, but in my case I need to modify a source code under the select tag. I was able to modify the source code using the inspect element. The following is select tags source code:

```<code><select name="date1">
    <option value="2016-09-17">2016-09-17</option>
    <option value="2016-09-16">2016-09-16</option>
    <option value="2016-09-14">2016-09-14</option>
</select>
</code>```

I tried to do it with driver.execute_script(). The following was my code:

```<code>sel = driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/form/table/tbody/tr[2]/td[3]/select')
input_list = sel.find_element_by_tag_name('option')
cmd = "input_list.value = '2016-09-07'"
driver.execute_script(cmd)
</code>```

But the above code is giving me the following error:

selenium.common.exceptions.WebDriverException: Message: input_list is not defined

I am able to modify the source code using the inspect element window. Is there any way to modify the source code using selenium?

答:
in python use this :

```<code>element = driver.find_element_by_id("some-random-number")
driver.execute_script("arguments[0].innerText = 'change text'", element)
</code>```

Body:
I am using Python selenium to automate my attendance entry. It was working fine, now I wanted to try by modifying the source code. I have seen few posts stating that it can be modified using driver.execute_script() and it works for JavaScript, but in my case I need to modify a source code under the select tag. I was able to modify the source code using the inspect element. The following is select tags source code:

<select name="date1">
    <option value="2016-09-17">2016-09-17</option>
    <option value="2016-09-16">2016-09-16</option>
    <option value="2016-09-14">2016-09-14</option>
</select>

I tried to do it with driver.execute_script(). The following was my code:

sel = driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/form/table/tbody/tr[2]/td[3]/select')
input_list = sel.find_element_by_tag_name('option')
cmd = "input_list.value = '2016-09-07'"
driver.execute_script(cmd)

But the above code is giving me the following error:

selenium.common.exceptions.WebDriverException: Message: input_list is not defined

I am able to modify the source code using the inspect element window. Is there any way to modify the source code using selenium?

Body:
in python use this :

element = driver.find_element_by_id("some-random-number")
driver.execute_script("arguments[0].innerText = 'change text'", element)


问:
Local Storage - React Native
As Async Storage is deprecated what other way is there to store a variable locally??

I have a React Native ios App with a Notification Centre.
Each time the user enters the Notification Centre a Cognito access Token was generated. To avoid excess of token generation the Tokens were saved through Async storage and their expiry was checked.

Now is there some other local storage in React Native that i can use??

答:
Async storage is not deprecated its moved to a separate package which you can install and use

https://github.com/react-native-community/async-storage/

Or for tokens you can use react-native-keychain which is a way secure package you can check it here.
https://github.com/oblador/react-native-keychain

Title: Local Storage - React Native


问:
Getting Rid of Lines in OpenCV-Python

Like I converted my original input to HSV color space image & applied the INRANGE function and found the green & blue lines & now i want to get rid of them and I want the image to look like in output....how shall i now get rid of the lines & replace them by the background color??

Code Snippet:

```<code>import cv2 as cv
import numpy as np
img= cv.imread('C:\input.png',1)

hsv=cv.cvtColor(img,cv.COLOR_BGR2HSV)
lower_green = np.array([30,70,20])
upper_green = np.array([70,255,255])
lower_blue = np.array([95, 110, 20])
upper_blue = np.array([135, 255, 255])
mask = cv.inRange(hsv, lower_green , upper_blue)
res = cv.bitwise_and(img,img, mask= mask)
cv.imwrite("out2.jpg", res)
</code>```

答:
```<code>import cv2 as cv
import numpy as np
img= cv.imread(r'input.png',1)

hsv=cv.cvtColor(img,cv.COLOR_BGR2HSV)
h,s,v = cv.split(hsv)
th, threshed = cv.threshold(s, 100, 255, cv.THRESH_OTSU|cv.THRESH_BINARY) #black background
mask_w = cv.bitwise_not(threshed)     #white background
fg_masked = cv.bitwise_and(v, v, mask=mask_w) #masking the image of shirt with mask_w
dst = cv.inpaint(fg_masked,threshed,3, cv.INPAINT_NS) #inpainting

#Dilation & Erosion.
kernel = np.ones((4, 4),np.uint8)
dilation = cv.dilate(dst,kernel,iterations = 2)
erosion = cv.erode(dilation, kernel, iterations=1)
dilation2= cv.dilate(erosion,kernel,iterations = 1)
dilation3= cv.dilate(dilation2,kernel,iterations = 1)
erosion_final = cv.erode(dilation3, kernel, iterations=3)
cv.imwrite("output_2 [improved].png", erosion_final)
</code>```

Title: Getting Rid of Lines in OpenCV-Python

Body:
Like I converted my original input to HSV color space image & applied the INRANGE function and found the green & blue lines & now i want to get rid of them and I want the image to look like in output....how shall i now get rid of the lines & replace them by the background color??

Code Snippet:

import cv2 as cv
import numpy as np
img= cv.imread('C:\input.png',1)

hsv=cv.cvtColor(img,cv.COLOR_BGR2HSV)
lower_green = np.array([30,70,20])
upper_green = np.array([70,255,255])
lower_blue = np.array([95, 110, 20])
upper_blue = np.array([135, 255, 255])
mask = cv.inRange(hsv, lower_green , upper_blue)
res = cv.bitwise_and(img,img, mask= mask)
cv.imwrite("out2.jpg", res)


问:
How to get the new Position of Filtered Data from RecycleView Android
I've Implemented a search Filter in RecycleView by Edittext. I've set onClickListener to the lists.  Everything is working fine when I search by editext, the data showing perfectly. But when I clicked the Filtered Data. it taking the position from the old list, like 0.

my Adapter class

```<code>package com.gujja.ajay.coronovirus;

public class WorldDataAdapter extends RecyclerView.Adapter<WorldDataAdapter.WorldDataViewHolder> {

   private final Context context;
   private ArrayList<CovidCountry> covidCountries;
   private OnItemClickListener covidListener;

public interface OnItemClickListener{
    void onItemClick(int position);
}

public void setOnItemClickListener(OnItemClickListener listener){
    covidListener = listener;
}

public WorldDataAdapter(Context context, ArrayList<CovidCountry> covidCountries) {
    this.covidCountries = covidCountries;
    this.context = context;
}

@NonNull
@Override
public WorldDataViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.activity_world_data_list, parent, false);

    return new WorldDataViewHolder(view,covidListener);
}

@Override
public void onBindViewHolder(@NonNull WorldDataViewHolder holder, int position) {

    CovidCountry covidCountry = covidCountries.get(position);
    String countryFlagUrl = covidCountry.getmCovidCountryImages();

    holder.worldDataTitle.setText(covidCountry.getmCovidCountry());
    holder.worldDataCasesCount.setText(covidCountry.getmCovidCases());
    holder.worldDataDeathCount.setText(covidCountry.getmCovidDeath());

    Picasso.get().load(countryFlagUrl).fit().centerInside().into(holder.countryFlags);

}

@Override
public int getItemCount() {
    return covidCountries.size();
}

public void filteredList(ArrayList<CovidCountry> filteredCountries) {
    covidCountries = new ArrayList<>();
    covidCountries.addAll(filteredCountries);
    notifyDataSetChanged();
}

public static class WorldDataViewHolder extends RecyclerView.ViewHolder {
    TextView worldDataTitle, worldDataDeathCount, worldDataCasesCount, worldNewCasesData;
    ImageView countryFlags;

    public WorldDataViewHolder(@NonNull View itemView, final OnItemClickListener listener) {
        super(itemView);

        worldDataTitle = itemView.findViewById(R.id.WorldDataName);
        worldDataDeathCount = itemView.findViewById(R.id.WorldDataDeathCount);
        worldDataCasesCount = itemView.findViewById(R.id.WorldDataCasesCount);
        countryFlags = itemView.findViewById(R.id.covCountryFlags);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener!= null ){
                    int position = getAdapterPosition();

                    if(position != RecyclerView.NO_POSITION){
                        listener.onItemClick(position);
                    }
                }
            }
        });
    }
}
</code>```

hers is my mainactivity class

```<code>public class MainActivity extends AppCompatActivity implements WorldDataAdapter.OnItemClickListener {

public static final String COUNTRY_NAME = "countryName";
private static final String TAG = MainActivity.class.getSimpleName();

TextView title, totalDeath, totalDeathNum, totalCases, totalCasesNum, totalRecovered, totalRecoveredData, activePatient, activePatientData;
ProgressBar progressBar;
EditText editText;

ArrayList<CovidCountry> covidCountries;
RecyclerView WorldRecycleView;
WorldDataAdapter worldDataAdapter;
RecyclerView.LayoutManager mlayoutManager;

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

    title = findViewById(R.id.Title);
    totalCases = findViewById(R.id.TotalCases);
    totalCasesNum = findViewById(R.id.TotalCasesData);
    totalDeath = findViewById(R.id.TotalDeath);
    totalDeathNum = findViewById(R.id.TotalDeathData);
    progressBar = findViewById(R.id.Progressloader);
    totalRecovered = findViewById(R.id.TotalRecovered);
    totalRecoveredData = findViewById(R.id.TotalRecoveredData);
    activePatient = findViewById(R.id.TotalActive);
    activePatientData = findViewById(R.id.TotalActiveData);
    editText = findViewById(R.id.search_country);

    getData();
    detDataFromServer();
    buildRecycleView();

    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            filter(editable.toString());
        }
    });
}

private void buildRecycleView() {
    WorldRecycleView = findViewById(R.id.RecycleView);
    WorldRecycleView.setHasFixedSize(true);
    mlayoutManager = new LinearLayoutManager(this);
    worldDataAdapter = new WorldDataAdapter(this,covidCountries);

    WorldRecycleView.setLayoutManager(mlayoutManager);
    WorldRecycleView.setAdapter(worldDataAdapter);
}

private void filter(String country) {
    ArrayList<CovidCountry> filteredCountries = new ArrayList<>();

    for(CovidCountry item: covidCountries){
        if (item.getmCovidCountry().toLowerCase().contains(country.toLowerCase())) {

            filteredCountries.add(item);
        }
    }

    worldDataAdapter.filteredList(filteredCountries);

}

@Override
public void onItemClick(int position) {
    Intent  detailIntent = new Intent(this, Deploy_Test.class);
    Log.e(TAG, "onclivk: " + ajay );

    CovidCountry covidCountry = filteredCountries.get(position);
    //CovidCountry detailCountry = covidCountries.get(position);

    //detailIntent.putExtra(COUNTRY_NAME,detailCountry.getmCovidCountry());

    detailIntent.putExtra(COUNTRY_NAME,covidCountry.getmCovidCountry());

    Log.e(TAG, "onItemClick: " + covidCountry );

    startActivity(detailIntent);
}
</code>```

How do I get the new Position of filtered List and set OnclickListener to it?

答:
Okay look I guess I know what you are doing wrong.

So you are sending the position and extracting the data in the activity, but you are extracting from the wrong list.

In the MainActivity:

```<code>//add this to the member fields
private ArrayList<CovidCountry> filteredCountries;

private final Context context;
private ArrayList<CovidCountry> covidCountries;
private OnItemClickListener covidListener;

.......

//the filter method becomes like this

private void filter(String country) {
    filteredCountries = new ArrayList<>();

    for(CovidCountry item: covidCountries){
        if (item.getmCovidCountry().toLowerCase().contains(country.toLowerCase())) {

            filteredCountries.add(item);
        }
    }

    worldDataAdapter.filteredList(filteredCountries);

}
</code>```

Here is where I think you are messing up, there is the interface method that you are not showing in your question which is called onItemClick(position):

```<code>@Override
public void onItemClick(int position){

//I am sure here is your mistake

//I guess you are using the old list to get the data at the position

//you must be getting data like this from the filteredCountries

CovidCountry covidCountry = filteredCountries.get(position);

........
........

}
</code>```

Body:
I've Implemented a search Filter in RecycleView by Edittext. I've set onClickListener to the lists.  Everything is working fine when I search by editext, the data showing perfectly. But when I clicked the Filtered Data. it taking the position from the old list, like 0.

my Adapter class

package com.gujja.ajay.coronovirus;

public class WorldDataAdapter extends RecyclerView.Adapter<WorldDataAdapter.WorldDataViewHolder> {

   private final Context context;
   private ArrayList<CovidCountry> covidCountries;
   private OnItemClickListener covidListener;

public interface OnItemClickListener{
    void onItemClick(int position);
}

public void setOnItemClickListener(OnItemClickListener listener){
    covidListener = listener;
}

public WorldDataAdapter(Context context, ArrayList<CovidCountry> covidCountries) {
    this.covidCountries = covidCountries;
    this.context = context;
}

@NonNull
@Override
public WorldDataViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.activity_world_data_list, parent, false);

    return new WorldDataViewHolder(view,covidListener);
}

@Override
public void onBindViewHolder(@NonNull WorldDataViewHolder holder, int position) {

    CovidCountry covidCountry = covidCountries.get(position);
    String countryFlagUrl = covidCountry.getmCovidCountryImages();

    holder.worldDataTitle.setText(covidCountry.getmCovidCountry());
    holder.worldDataCasesCount.setText(covidCountry.getmCovidCases());
    holder.worldDataDeathCount.setText(covidCountry.getmCovidDeath());

    Picasso.get().load(countryFlagUrl).fit().centerInside().into(holder.countryFlags);

}

@Override
public int getItemCount() {
    return covidCountries.size();
}

public void filteredList(ArrayList<CovidCountry> filteredCountries) {
    covidCountries = new ArrayList<>();
    covidCountries.addAll(filteredCountries);
    notifyDataSetChanged();
}

public static class WorldDataViewHolder extends RecyclerView.ViewHolder {
    TextView worldDataTitle, worldDataDeathCount, worldDataCasesCount, worldNewCasesData;
    ImageView countryFlags;

    public WorldDataViewHolder(@NonNull View itemView, final OnItemClickListener listener) {
        super(itemView);

        worldDataTitle = itemView.findViewById(R.id.WorldDataName);
        worldDataDeathCount = itemView.findViewById(R.id.WorldDataDeathCount);
        worldDataCasesCount = itemView.findViewById(R.id.WorldDataCasesCount);
        countryFlags = itemView.findViewById(R.id.covCountryFlags);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener!= null ){
                    int position = getAdapterPosition();

                    if(position != RecyclerView.NO_POSITION){
                        listener.onItemClick(position);
                    }
                }
            }
        });
    }
}

hers is my mainactivity class

public class MainActivity extends AppCompatActivity implements WorldDataAdapter.OnItemClickListener {

public static final String COUNTRY_NAME = "countryName";
private static final String TAG = MainActivity.class.getSimpleName();

TextView title, totalDeath, totalDeathNum, totalCases, totalCasesNum, totalRecovered, totalRecoveredData, activePatient, activePatientData;
ProgressBar progressBar;
EditText editText;

ArrayList<CovidCountry> covidCountries;
RecyclerView WorldRecycleView;
WorldDataAdapter worldDataAdapter;
RecyclerView.LayoutManager mlayoutManager;

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

    title = findViewById(R.id.Title);
    totalCases = findViewById(R.id.TotalCases);
    totalCasesNum = findViewById(R.id.TotalCasesData);
    totalDeath = findViewById(R.id.TotalDeath);
    totalDeathNum = findViewById(R.id.TotalDeathData);
    progressBar = findViewById(R.id.Progressloader);
    totalRecovered = findViewById(R.id.TotalRecovered);
    totalRecoveredData = findViewById(R.id.TotalRecoveredData);
    activePatient = findViewById(R.id.TotalActive);
    activePatientData = findViewById(R.id.TotalActiveData);
    editText = findViewById(R.id.search_country);

    getData();
    detDataFromServer();
    buildRecycleView();

    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            filter(editable.toString());
        }
    });
}

private void buildRecycleView() {
    WorldRecycleView = findViewById(R.id.RecycleView);
    WorldRecycleView.setHasFixedSize(true);
    mlayoutManager = new LinearLayoutManager(this);
    worldDataAdapter = new WorldDataAdapter(this,covidCountries);

    WorldRecycleView.setLayoutManager(mlayoutManager);
    WorldRecycleView.setAdapter(worldDataAdapter);
}

private void filter(String country) {
    ArrayList<CovidCountry> filteredCountries = new ArrayList<>();

    for(CovidCountry item: covidCountries){
        if (item.getmCovidCountry().toLowerCase().contains(country.toLowerCase())) {

            filteredCountries.add(item);
        }
    }

    worldDataAdapter.filteredList(filteredCountries);

}

@Override
public void onItemClick(int position) {
    Intent  detailIntent = new Intent(this, Deploy_Test.class);
    Log.e(TAG, "onclivk: " + ajay );

    CovidCountry covidCountry = filteredCountries.get(position);
    //CovidCountry detailCountry = covidCountries.get(position);

    //detailIntent.putExtra(COUNTRY_NAME,detailCountry.getmCovidCountry());

    detailIntent.putExtra(COUNTRY_NAME,covidCountry.getmCovidCountry());

    Log.e(TAG, "onItemClick: " + covidCountry );

    startActivity(detailIntent);
}

How do I get the new Position of filtered List and set OnclickListener to it?

Body:
Okay look I guess I know what you are doing wrong.

So you are sending the position and extracting the data in the activity, but you are extracting from the wrong list.

In the MainActivity:

//add this to the member fields
private ArrayList<CovidCountry> filteredCountries;

private final Context context;
private ArrayList<CovidCountry> covidCountries;
private OnItemClickListener covidListener;

.......

//the filter method becomes like this

private void filter(String country) {
    filteredCountries = new ArrayList<>();

    for(CovidCountry item: covidCountries){
        if (item.getmCovidCountry().toLowerCase().contains(country.toLowerCase())) {

            filteredCountries.add(item);
        }
    }

    worldDataAdapter.filteredList(filteredCountries);

}

Here is where I think you are messing up, there is the interface method that you are not showing in your question which is called onItemClick(position):

@Override
public void onItemClick(int position){

//I am sure here is your mistake

//I guess you are using the old list to get the data at the position

//you must be getting data like this from the filteredCountries

CovidCountry covidCountry = filteredCountries.get(position);

........
........

}


问:
mysqli_num_rows() returning incorrect number of rows

Context:

I've created a page where users can vote on debates. The debates all have two potential options. When the user clicks on the option on the left side, it returns a value of "0". When the user clicks on the option on the right side, it returns a value of "1". After the user clicks the side they want to vote on, an AJAX call is executed, which checks the database to see if the user has already voted by checking the user ID and poll ID. The AJAX works fine. This is the jQuery/AJAX code:

```<code>$(".display-polls-container").on("click", "input:radio", function(e) { //when user votes on debate

    var thisElement = $(this);
    var vote_value = $(this).val();
    var pollId = $(this).parent().parent().parent().siblings().children(".poll-id").val();

    <?php if (isset($_SESSION['id'])) { ?>

        setVote(vote_value, pollId, thisElement); //insert vote into database

    <?php } else { ?>

        alert("You must sign in to vote on a debate");

    <?php } ?>

});

function setVote(vote_value, pollId, thisElement) { //insert vote into database

    $.ajax({
        url: 'includes/poll_votes.php',
        type: 'POST',
        data: {vote_value: vote_value, pollId: pollId, idUsers: idUsers},
        success: function(data) {

            getVote(pollId, thisElement); //if vote inserts correctly, get the vote count and apply it to the debate (this function is not relevant enough to include its code)

        },
        error: function(requestObject, error, errorThrown) {
            //console.log(error);
            //console.log(errorThrown);
        }
    });

}
</code>```

Problem:

The problem is that the PHP code isn't working at the moment. Everything seems to be working about it except the mysqli_num_rows() function. Here's the PHP code:

```<code><?php

include 'dbh.inc.php'; //include database connection

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

$query = "SELECT idUsers FROM poll_votes WHERE idUsers = ? AND poll_id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'ii', $idUsers, $poll_id);

$idUsers = $_POST['idUsers'];
$pollId = $_POST['pollId'];
$vote_value = $_POST['vote_value'];
$seen = "false";

if ($vote_value == 0) { //change value inserted into database based on which side you voted for

    $yes = "true";
    $no = "false";

} elseif ($vote_value == 1) {

    $yes = "false";
    $no = "true";

}

mysqli_stmt_execute($stmt);

$r = mysqli_stmt_get_result($stmt);

if ($r) {

    if (mysqli_num_rows($r) == 0) { //check if user has already voted on debate; this seems to be where the problem lies - it always returns 0

        $q = "INSERT INTO poll_votes (yes, no, poll_id, idUsers, seen) VALUES (?, ?, ?, ?, ?)"; //insert vote into database
        $stmt2 = mysqli_prepare($conn, $q);
        mysqli_stmt_bind_param($stmt2, 'ssiis', $yes, $no, $pollId, $idUsers, $seen);

        $execute = mysqli_stmt_execute($stmt2);

        if ($execute) {

            echo "Vote submitted successfully!";

        }

    } else {

        echo "You can't vote twice!";

    }

}

mysqli_stmt_close($stmt);

mysqli_close($conn);

}
</code>```

What happens is, even when the user has already voted on a specific debate, the query doesn't disallow them from continuing to vote on the same debate. Once the user votes once, they shouldn't be able to do it again. I try checking if they have already voted using the mysqli_num_rows() function, but it ALWAYS returns 0, regardless of how many rows there actually are.

Things I have tried:

I checked the original query by submitting my own values into the "SQL" part of the mysqli database, and it worked just fine, so I don't think that the problem is with the query. I have also formed the query using non-prepared statements, which worked fine and returned the correct number of results from the database. This means that the fact that I'm using prepared statements might mean that I left something out. Any ideas? Thanks.

答: I don't know why this worked, but I just re-wrote the code to go through the motions again and see if I could notice any prior mistakes. Ultimately, I don't THINK anything was changed, but it works now.</p>

Body:
Context:

I've created a page where users can vote on debates. The debates all have two potential options. When the user clicks on the option on the left side, it returns a value of "0". When the user clicks on the option on the right side, it returns a value of "1". After the user clicks the side they want to vote on, an AJAX call is executed, which checks the database to see if the user has already voted by checking the user ID and poll ID. The AJAX works fine. This is the jQuery/AJAX code:

$(".display-polls-container").on("click", "input:radio", function(e) { //when user votes on debate

    var thisElement = $(this);
    var vote_value = $(this).val();
    var pollId = $(this).parent().parent().parent().siblings().children(".poll-id").val();

    <?php if (isset($_SESSION['id'])) { ?>

        setVote(vote_value, pollId, thisElement); //insert vote into database

    <?php } else { ?>

        alert("You must sign in to vote on a debate");

    <?php } ?>

});

function setVote(vote_value, pollId, thisElement) { //insert vote into database

    $.ajax({
        url: 'includes/poll_votes.php',
        type: 'POST',
        data: {vote_value: vote_value, pollId: pollId, idUsers: idUsers},
        success: function(data) {

            getVote(pollId, thisElement); //if vote inserts correctly, get the vote count and apply it to the debate (this function is not relevant enough to include its code)

        },
        error: function(requestObject, error, errorThrown) {
            //console.log(error);
            //console.log(errorThrown);
        }
    });

}

Problem:

The problem is that the PHP code isn't working at the moment. Everything seems to be working about it except the mysqli_num_rows() function. Here's the PHP code:

<?php

include 'dbh.inc.php'; //include database connection

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

$query = "SELECT idUsers FROM poll_votes WHERE idUsers = ? AND poll_id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'ii', $idUsers, $poll_id);

$idUsers = $_POST['idUsers'];
$pollId = $_POST['pollId'];
$vote_value = $_POST['vote_value'];
$seen = "false";

if ($vote_value == 0) { //change value inserted into database based on which side you voted for

    $yes = "true";
    $no = "false";

} elseif ($vote_value == 1) {

    $yes = "false";
    $no = "true";

}

mysqli_stmt_execute($stmt);

$r = mysqli_stmt_get_result($stmt);

if ($r) {

    if (mysqli_num_rows($r) == 0) { //check if user has already voted on debate; this seems to be where the problem lies - it always returns 0

        $q = "INSERT INTO poll_votes (yes, no, poll_id, idUsers, seen) VALUES (?, ?, ?, ?, ?)"; //insert vote into database
        $stmt2 = mysqli_prepare($conn, $q);
        mysqli_stmt_bind_param($stmt2, 'ssiis', $yes, $no, $pollId, $idUsers, $seen);

        $execute = mysqli_stmt_execute($stmt2);

        if ($execute) {

            echo "Vote submitted successfully!";

        }

    } else {

        echo "You can't vote twice!";

    }

}

mysqli_stmt_close($stmt);

mysqli_close($conn);

}

What happens is, even when the user has already voted on a specific debate, the query doesn't disallow them from continuing to vote on the same debate. Once the user votes once, they shouldn't be able to do it again. I try checking if they have already voted using the mysqli_num_rows() function, but it ALWAYS returns 0, regardless of how many rows there actually are.

Things I have tried:

I checked the original query by submitting my own values into the "SQL" part of the mysqli database, and it worked just fine, so I don't think that the problem is with the query. I have also formed the query using non-prepared statements, which worked fine and returned the correct number of results from the database. This means that the fact that I'm using prepared statements might mean that I left something out. Any ideas? Thanks.


问:
I'm trying to retrieve data from qSQL database
But it does not get the data from the database. I'm do not want to retrieve the data to the table and want to display data in particular line edit. What is the error? Is there any modification?

This is the Code that I'm using:

```<code>void Userdetails::on_pushButton_4_clicked()
{
    delete ui;

    // database connection
    database = QSqlDatabase::addDatabase("QMYSQL");
    database.setHostName("localhost");
    database.setUserName("root");
    database.setPassword("");
    database.setDatabaseName("electricity");

    if(database.open()) {
         QSqlQuery qry;

         QSqlQuery query(QSqlDatabase::database("MyConnect"));

         query.prepare(QString("SELECT accno, fullname, address, telephone FROM user_reg_elec WHERE username = :username AND password = :password"));

         if(query.exec()) {
             query.exec();

             while(query.next()) {
                 ui ->dislayaccountnumber ->setText(query.value(0).toString());
                 ui ->displayname ->setText(query.value(3).toString());
                 ui ->displayaddress ->setText(query.value(4).toString());
                 ui ->displattelephoneno ->setText(query.value(5).toString());
                 // ui ->displayamountoebill ->setText(query.value(6).toString());
             }
         } else {
               QMessageBox::information(this, "Query did not execute", "Not successful executing the query");
         }
    } else {
         QMessageBox::information(this, "Database not open", "Not opened successfully");
    }

    database.close();
}
</code>```

答:
This code has four main issues:

You have deleted the ui at the beginning of your code. Hence, the first line that calls ui-> will crash the program.

You have defined your query improperly. Also, your way to select a name for your connection is not right.

You have executed your query twice (one is enough).

You've not bind values for username and password.

Please use the following:

```<code>void Userdetails::on_pushButton_4_clicked() {

    {
        // database connection
        QSqlDatabase database;
        database = QSqlDatabase::addDatabase("QMYSQL","MyConnect");
        database.setHostName("localhost");
        database.setUserName("root");
        database.setPassword("");
        database.setDatabaseName("electricity");

        if(database.open()) {

            QSqlQuery query(database);

            if (query.prepare(QString("SELECT accno, fullname, address, telephone FROM user_reg_elec WHERE username = :username AND password = :password"))) {

                //Add bindings
                query.bindValue(":username","your user name");
                query.bindValue(":password","your password");
                if(query.exec()) {

                    while(query.next()) {
                        ui ->dislayaccountnumber ->setText(query.value(0).toString());
                        ui ->displayname ->setText(query.value(1).toString());
                        ui ->displayaddress ->setText(query.value(2).toString());
                        ui ->displattelephoneno ->setText(query.value(3).toString());
                        // ui ->displayamountoebill ->setText(query.value(4).toString());
                    }
                } else {
                    qDebug() << "Query did not execute due to: " << query.lastError().text();
                    QMessageBox::information(this, "Query did not execute", "Not successful executing the query");
                }
            } else {
                qDebug() << "Query not prepared due to the following error: " << query.lastError().text();
            }
        } else {
            qDebug() << "Database not opened due to: " << database.lastError().text();
            QMessageBox::information(this, "Database not open", "Not opened successfully");
        }

        database.close();
    }

    QSqlDatabase::removeDatabase("MyConnect");
}
</code>```

Please add #include <QSqlError> to the top, if you have not already included this library.

Only to the questionary:

To show details in a new window, after you got the target user's information from your database, you can create a new dialog (window) and show the results in it as follows:

```<code>    //Create a new dialog
    QDialog *dialog = new QDialog;

    //Add some elements to the dialog
    QLabel *accountNumber = new QLabel("Account number: " + query.value(0).toString());
    QLabel *name = new QLabel("Name: " + query.value(1).toString());
    QLabel *address = new QLabel("Address: " + query.value(2).toString());
    QLabel *phoneNumber = new QLabel("Phone number: " + query.value(3).toString());
    QVBoxLayout *lay = new QVBoxLayout;
    lay->addWidget(accountNumber);
    lay->addWidget(name);
    lay->addWidget(address);
    lay->addWidget(phoneNumber);
    dialog->setLayout(lay);

    //Show the dialog
    dialog->open();
</code>```

Body:
But it does not get the data from the database. I'm do not want to retrieve the data to the table and want to display data in particular line edit. What is the error? Is there any modification?

This is the Code that I'm using:

void Userdetails::on_pushButton_4_clicked()
{
    delete ui;

    // database connection
    database = QSqlDatabase::addDatabase("QMYSQL");
    database.setHostName("localhost");
    database.setUserName("root");
    database.setPassword("");
    database.setDatabaseName("electricity");

    if(database.open()) {
         QSqlQuery qry;

         QSqlQuery query(QSqlDatabase::database("MyConnect"));

         query.prepare(QString("SELECT accno, fullname, address, telephone FROM user_reg_elec WHERE username = :username AND password = :password"));

         if(query.exec()) {
             query.exec();

             while(query.next()) {
                 ui ->dislayaccountnumber ->setText(query.value(0).toString());
                 ui ->displayname ->setText(query.value(3).toString());
                 ui ->displayaddress ->setText(query.value(4).toString());
                 ui ->displattelephoneno ->setText(query.value(5).toString());
                 // ui ->displayamountoebill ->setText(query.value(6).toString());
             }
         } else {
               QMessageBox::information(this, "Query did not execute", "Not successful executing the query");
         }
    } else {
         QMessageBox::information(this, "Database not open", "Not opened successfully");
    }

    database.close();
}

Body:
This code has four main issues:

You have deleted the ui at the beginning of your code. Hence, the first line that calls ui-> will crash the program.

You have defined your query improperly. Also, your way to select a name for your connection is not right.

You have executed your query twice (one is enough).

You've not bind values for username and password.

Please use the following:

void Userdetails::on_pushButton_4_clicked() {

    {
        // database connection
        QSqlDatabase database;
        database = QSqlDatabase::addDatabase("QMYSQL","MyConnect");
        database.setHostName("localhost");
        database.setUserName("root");
        database.setPassword("");
        database.setDatabaseName("electricity");

        if(database.open()) {

            QSqlQuery query(database);

            if (query.prepare(QString("SELECT accno, fullname, address, telephone FROM user_reg_elec WHERE username = :username AND password = :password"))) {

                //Add bindings
                query.bindValue(":username","your user name");
                query.bindValue(":password","your password");
                if(query.exec()) {

                    while(query.next()) {
                        ui ->dislayaccountnumber ->setText(query.value(0).toString());
                        ui ->displayname ->setText(query.value(1).toString());
                        ui ->displayaddress ->setText(query.value(2).toString());
                        ui ->displattelephoneno ->setText(query.value(3).toString());
                        // ui ->displayamountoebill ->setText(query.value(4).toString());
                    }
                } else {
                    qDebug() << "Query did not execute due to: " << query.lastError().text();
                    QMessageBox::information(this, "Query did not execute", "Not successful executing the query");
                }
            } else {
                qDebug() << "Query not prepared due to the following error: " << query.lastError().text();
            }
        } else {
            qDebug() << "Database not opened due to: " << database.lastError().text();
            QMessageBox::information(this, "Database not open", "Not opened successfully");
        }

        database.close();
    }

    QSqlDatabase::removeDatabase("MyConnect");
}

Please add #include <QSqlError> to the top, if you have not already included this library.

Only to the questionary:

To show details in a new window, after you got the target user's information from your database, you can create a new dialog (window) and show the results in it as follows:

    //Create a new dialog
    QDialog *dialog = new QDialog;

    //Add some elements to the dialog
    QLabel *accountNumber = new QLabel("Account number: " + query.value(0).toString());
    QLabel *name = new QLabel("Name: " + query.value(1).toString());
    QLabel *address = new QLabel("Address: " + query.value(2).toString());
    QLabel *phoneNumber = new QLabel("Phone number: " + query.value(3).toString());
    QVBoxLayout *lay = new QVBoxLayout;
    lay->addWidget(accountNumber);
    lay->addWidget(name);
    lay->addWidget(address);
    lay->addWidget(phoneNumber);
    dialog->setLayout(lay);

    //Show the dialog
    dialog->open();


问:
How to deal with dates in global system
Let's say that I need to create 'chat-like' system. Of course I need to deal with dates somehow.
I read about it a lot and I have some knowledge but I really don't know how to use it.

I would like to store message date in UTC (postgres 12)

Each user should be able to select his time zone and this time zone should be saved into database (standard approach)

When message is retrieved from database I need to convert message date into valid local date based on user selected timezone.

This is really all I need to do and here problem starts:

In postgres date is stored with offset f.e 2020-05-01 00:00:00+02, but I want to store timezone in another table, not here

How can I store user timezone? I should use names like "EST5EDT" or use time offsets as integer?

Where can I find list of all timezones to present user? (Each global website f.e. facebook has list of timezones with offsets, where can I find list of all valid timezones?)

How can I select date with user appropriate timezone? f.e.

```<code>SELECT convert_to_user_date("Date", "timezonename??")
FROM "Messages"
</code>```

Is this correct way to achieve my goal?

答:
You are very close to a workable setup.

First, use timestamp or timestamp without timezone column data type to store those UTC date/time stamps.

Second, store your users' preferred time zones in varchar(63) columns in the form Asia/Kolkata or America/Halifax.

Third, use postgresql's built in view pg_timezone_names to get a list of valid time zones. You can use it to populate a pulldown list of choices in your user-settings screen.

If you have time for some real excellence in your user-settings screen, you can suggest time zone settings you guess from the users' ip adresses and allow them to change them if your guess was wrong. Read this. How to get Time Zone through IP Address in PHP

Then, when your application starts using postgresql on behalf of any user, look up that user's chosen time zone in your users table, and use it in this SQL command. SET TIME ZONE 'America/Halifax'; (whatever the user's choice is).

Then when you retrieve your time stamps, they will be rendered in the user's local time, and when you store the they'll be in UTC.

The 'toobz are full of advice about this. Here's something that might be useful. How to get Time Zone through IP Address in PHP

Title: How to deal with dates in global system

Body:
Let's say that I need to create 'chat-like' system. Of course I need to deal with dates somehow.
I read about it a lot and I have some knowledge but I really don't know how to use it.

I would like to store message date in UTC (postgres 12)

Each user should be able to select his time zone and this time zone should be saved into database (standard approach)

When message is retrieved from database I need to convert message date into valid local date based on user selected timezone.

This is really all I need to do and here problem starts:

In postgres date is stored with offset f.e 2020-05-01 00:00:00+02, but I want to store timezone in another table, not here

How can I store user timezone? I should use names like "EST5EDT" or use time offsets as integer?

Where can I find list of all timezones to present user? (Each global website f.e. facebook has list of timezones with offsets, where can I find list of all valid timezones?)

How can I select date with user appropriate timezone? f.e.

SELECT convert_to_user_date("Date", "timezonename??")
FROM "Messages"

Is this correct way to achieve my goal?


问:
Download SFTP files that starts with prefix name using SSH.NET in C#
I am using SSH.NET library to download a file from SFTP server. When I gave it full file name it works. But I want to download a file with prefix name and in that folder, the prefix name is POS_ETH_SE7*. There will be always one file. After I download it, I move it to another folder. Here is my  method:

```<code>var auth = new PasswordAuthenticationMethod(username, password);
var connectionInfo = new ConnectionInfo(ipAddress, port, auth);

// Upload File
using (var sftp = new SftpClient(connectionInfo))
{
    string pathLocalFile =
        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
            "POS_ETH_SE7.ics");

    sftp.Connect();

    Console.WriteLine("Downloading {0}", remoteFilePath);

    using (Stream fileStream = File.OpenWrite(pathLocalFile))
    using (StreamWriter writer = new StreamWriter(fileStream))

    {
        try
        {
            sftp.DownloadFile(remoteFilePath, fileStream);
        }
        catch (SftpPathNotFoundException ex)
        {

        }
    }
    try
    {
        var inFile = sftp.Get(remoteFilePath);
        inFile.MoveTo(remoteMoveFileToPath + "/POS_ETH_SE7.xml");
    }
    catch (SftpPathNotFoundException ex)
    {
        Console.WriteLine("\nnothing to update...\n");
    }

    sftp.Disconnect();
}
</code>```

答:
Start with the code from the following question and add the additional constraint on the file name prefix.

Downloading a directory using SSH.NET SFTP in C#

```<code>const string prefix = "POS_ETH_SE7";
IEnumerable<SftpFile> files = client.ListDirectory(remotePath);
files = files.Where(file => file.Name.StartsWith(prefix));
foreach (SftpFile file in files)
{
    string pathLocalFile = Path.Combine(localPath, file.Name);

    using (var stream = File.Create(pathLocalFile))
    {
        client.DownloadFile(file.FullName, stream);
    }

    // If you want to archive the downloaded files:
    string archivePath = remoteMoveFileToPath + "/" + file.Name;
    client.RenameFile(file.FullName, archivePath);
}
</code>```

Or use a more powerful SFTP library. For example with my WinSCP .NET assembly, you can do the same with a single call to Session.GetFilesToDirectory:

```<code>session.GetFilesToDirectory(remotePath, localPath, prefix + "*").Check();
</code>```

Body:
I am using SSH.NET library to download a file from SFTP server. When I gave it full file name it works. But I want to download a file with prefix name and in that folder, the prefix name is POS_ETH_SE7*. There will be always one file. After I download it, I move it to another folder. Here is my  method:

var auth = new PasswordAuthenticationMethod(username, password);
var connectionInfo = new ConnectionInfo(ipAddress, port, auth);

// Upload File
using (var sftp = new SftpClient(connectionInfo))
{
    string pathLocalFile =
        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
            "POS_ETH_SE7.ics");

    sftp.Connect();

    Console.WriteLine("Downloading {0}", remoteFilePath);

    using (Stream fileStream = File.OpenWrite(pathLocalFile))
    using (StreamWriter writer = new StreamWriter(fileStream))

    {
        try
        {
            sftp.DownloadFile(remoteFilePath, fileStream);
        }
        catch (SftpPathNotFoundException ex)
        {

        }
    }
    try
    {
        var inFile = sftp.Get(remoteFilePath);
        inFile.MoveTo(remoteMoveFileToPath + "/POS_ETH_SE7.xml");
    }
    catch (SftpPathNotFoundException ex)
    {
        Console.WriteLine("\nnothing to update...\n");
    }

    sftp.Disconnect();
}

Body:
Start with the code from the following question and add the additional constraint on the file name prefix.

Downloading a directory using SSH.NET SFTP in C#

const string prefix = "POS_ETH_SE7";
IEnumerable<SftpFile> files = client.ListDirectory(remotePath);
files = files.Where(file => file.Name.StartsWith(prefix));
foreach (SftpFile file in files)
{
    string pathLocalFile = Path.Combine(localPath, file.Name);

    using (var stream = File.Create(pathLocalFile))
    {
        client.DownloadFile(file.FullName, stream);
    }

    // If you want to archive the downloaded files:
    string archivePath = remoteMoveFileToPath + "/" + file.Name;
    client.RenameFile(file.FullName, archivePath);
}

Or use a more powerful SFTP library. For example with my WinSCP .NET assembly, you can do the same with a single call to Session.GetFilesToDirectory:

session.GetFilesToDirectory(remotePath, localPath, prefix + "*").Check();


问:
Using auto layout to orientate stack views vertically in portrait and horizontally in landscape
What is the best way to get a vertical stackview in portrait to align horizontally in landscape. I have tried code and auto layout solutions and they have not worked. Is there any simple way to do this in storyboard?</p>

答:
Swift 5

the trick is to set the StackView axis to be Horizontal when the Height is Compact.

Check this post: Magical View Rotation with StackView

I tried and it worked wonderfully in iOS 13, swift 5


问:
There is a nested object in my Elastic mapping. I am trying to create a filter query for that nested object
As I know when I declared the object as nested it created an array like structure to store the multiple object of that object type.
This is example of mapping json file.

```<code>{
    "employee": {
        "dynamic": "strict",
        "properties": {
            "id": {
                "type": "keyword"
            },
            "name": {
             "type": "keyword"
            },
            "previous_job_documents": {
                "type": "nested",
                "properties": {
                    "id": {
                        "type": "keyword"
                    },
                    "status": {
                        "type": "keyword"
                    },
                    "type": {
                        "type": "integer"
                    }
                   }
                  }
                }}}
</code>```

Sample data fetched from elastic.

```<code>  "data": {
    "nodes": {
      "totalCount": 465,
      "edges": [
        {
          "id": "b6ecb8aa-4d12-44d6-8ed7-9ee1003d0d54",
          "name": "test",
          "previous_job_documents": [
            {
              "type": "RELIEVING_LETTER",
              "status": "NOT_SUBMITTED"
            },
            {
              "type": "OFFER_LETTER",
              "status": "SUBMITTED"
            },
            {
              "type": "PAYSLIP_FIRST_MONTH",
              "status": "VERIFIED"
            },
            {
              "type": "PAYSLIP_SECOND_MONTH",
              "status": "NOT_SUBMITTED"
            },
            {
              "type": "PAYSLIP_THIRD_MONTH",
              "status": "NOT_SUBMITTED"
            }
          ]
        }
        ]
        }}}
</code>```

Problem: I want to write a filter which will find all the employees whose name is test and  RELIEVING_LETTER is NOT_SUBMITTED and OFFER_LETTER is SUBMITTED.

This is what I tried in filter:

```<code>{
  "filters": {
    "Employee":
    {"AND": [{"name": "test"},
      {
        "path": "previous_job_documents"
        "AND": [
            {
              "term": {
                "previous_job_documents.type": {
                  "value": "RELIEVING_LETTER"
                }
              }
            },
            {
              "term": {
                "previous_job_documents.status": {
                  "value": "NOT_SUBMITTED"
                }
              }
            },

          {
              "term": {
                "previous_job_documents.type": {
                  "value": "OFFER_LETTER"
                }
              }
            },
            {
              "term": {
                "previous_job_documents.status": {
                  "value": "SUBMITTED"
                }
              }
            }
        ]
      }
        ]
    }
  }
}
</code>```

答:
You need to use a nested query for nested fields inside match query(as nested fields will be stored separately).</p>

```<code> {
"query":{
"bool":{
"must":[
{
    "match":{"name":"user2"}
},
{
        "nested":{
            "path": "previous_job_documents",
            "query":{
            "bool":{
                "must":[
                    {"match": {"previous_job_documents.type": "RELIEVING_LETTER"}},
                    {"match":{"previous_job_documents.status":"NOT_SUBMITTED"}}
                ]
            }
        }
    }
    },
    {
        "nested":{
            "path": "previous_job_documents",
            "query":{
            "bool":{
                "must":[
                    {"match": {"previous_job_documents.type": "OFFER_LETTER"}},
                    {"match":{"previous_job_documents.status":"SUBMITTED"}}
                ]
            }
        }
    }
}
]
}
}
}
</code>```

Body:
As I know when I declared the object as nested it created an array like structure to store the multiple object of that object type.
This is example of mapping json file.

{
    "employee": {
        "dynamic": "strict",
        "properties": {
            "id": {
                "type": "keyword"
            },
            "name": {
             "type": "keyword"
            },
            "previous_job_documents": {
                "type": "nested",
                "properties": {
                    "id": {
                        "type": "keyword"
                    },
                    "status": {
                        "type": "keyword"
                    },
                    "type": {
                        "type": "integer"
                    }
                   }
                  }
                }}}

Sample data fetched from elastic.

  "data": {
    "nodes": {
      "totalCount": 465,
      "edges": [
        {
          "id": "b6ecb8aa-4d12-44d6-8ed7-9ee1003d0d54",
          "name": "test",
          "previous_job_documents": [
            {
              "type": "RELIEVING_LETTER",
              "status": "NOT_SUBMITTED"
            },
            {
              "type": "OFFER_LETTER",
              "status": "SUBMITTED"
            },
            {
              "type": "PAYSLIP_FIRST_MONTH",
              "status": "VERIFIED"
            },
            {
              "type": "PAYSLIP_SECOND_MONTH",
              "status": "NOT_SUBMITTED"
            },
            {
              "type": "PAYSLIP_THIRD_MONTH",
              "status": "NOT_SUBMITTED"
            }
          ]
        }
        ]
        }}}

Problem: I want to write a filter which will find all the employees whose name is test and  RELIEVING_LETTER is NOT_SUBMITTED and OFFER_LETTER is SUBMITTED.

This is what I tried in filter:

{
  "filters": {
    "Employee":
    {"AND": [{"name": "test"},
      {
        "path": "previous_job_documents"
        "AND": [
            {
              "term": {
                "previous_job_documents.type": {
                  "value": "RELIEVING_LETTER"
                }
              }
            },
            {
              "term": {
                "previous_job_documents.status": {
                  "value": "NOT_SUBMITTED"
                }
              }
            },

          {
              "term": {
                "previous_job_documents.type": {
                  "value": "OFFER_LETTER"
                }
              }
            },
            {
              "term": {
                "previous_job_documents.status": {
                  "value": "SUBMITTED"
                }
              }
            }
        ]
      }
        ]
    }
  }
}

Body:
You need to use a nested query for nested fields inside match query(as nested fields will be stored separately).

 {
"query":{
"bool":{
"must":[
{
    "match":{"name":"user2"}
},
{
        "nested":{
            "path": "previous_job_documents",
            "query":{
            "bool":{
                "must":[
                    {"match": {"previous_job_documents.type": "RELIEVING_LETTER"}},
                    {"match":{"previous_job_documents.status":"NOT_SUBMITTED"}}
                ]
            }
        }
    }
    },
    {
        "nested":{
            "path": "previous_job_documents",
            "query":{
            "bool":{
                "must":[
                    {"match": {"previous_job_documents.type": "OFFER_LETTER"}},
                    {"match":{"previous_job_documents.status":"SUBMITTED"}}
                ]
            }
        }
    }
}
]
}
}
}


问:
How to read parameters from GET request in CherryPy?
How to read parameters from GET request in CherryPy ? I generate request from JQuery like

```<code>$.get(
    "http://localhost:8080/temp",
    "{a:10}",
    function(data) { alert(data); },
    "html"
);
</code>```

and I have class temp with @cherrypy.expose function index(self). How to extract data from GET request ?

答:
```<code>@cherrypy.expose
def index(self, param)
</code>```

where param is your GET param

Body:
How to read parameters from GET request in CherryPy ? I generate request from JQuery like

$.get(
    "http://localhost:8080/temp",
    "{a:10}",
    function(data) { alert(data); },
    "html"
);

and I have class temp with @cherrypy.expose function index(self). How to extract data from GET request ?

Body:
@cherrypy.expose
def index(self, param)

where param is your GET param


问:
Laravel - A Model for a 3rd Party API?
I'm working on an iphone app which uses a Laravel backend for the API.  At some point, there will be Google Places integration (or a similar service).

In my application, I'll need to store relationships between Users and Places, which is many-to-many.  However because 'Places' are not represented by an Eloquent model (but by Google's API), how do I create this relationship?  Do I need to create a wrapper for the Google Places API?

答:
To provider complexe implementation between an API and a Eloquent Model transparency. I recommand that you use https://github.com/CristalTeam/php-api-wrapper.

cristal/php-api-wrapper, you can create Models for your APIs and you have a query builder specifically adapted to API requests. You can use advanced Laravel features like Route Binding and relationships between an Eloquent model and a model of this package.

Title: Laravel - A Model for a 3rd Party API?


问:
Menu pops up at center rather than touched place
When trying to create a menu on map, menu pops up at center of the map rather than touched place on map when using onPressAndHold on Android. However the same code works correctly on desktop (Ubuntu). When press and hold with mouse on map, the menu pops up from mouse position on Ubuntu. I also tried Map Viewer example in Qt 5.13, it is the same. Is it possible to fix the menu position for Android? Thanks.</p>

```<code>import QtQuick.Window 2.2
import QtQuick 2.11
import QtQuick.Controls 2.4
import QtLocation 5.11
import QtPositioning 5.11

Window {
    id: root
    visible: true
    width: 640
    height: 480
    Plugin {
        id: mapPlugin
        name: "osm"
    }
    Menu {
        id:mapPopupMenu
        Action {
            text: qsTr("Get coordinate")
        }
    }

    Map {
        id: map
        anchors.fill: parent
        plugin: mapPlugin
        zoomLevel: 14
        center:  QtPositioning.coordinate(40,40)
        activeMapType: supportedMapTypes[1]
    }

    MouseArea {
        anchors.fill: parent
        onPressAndHold:mapPopupMenu.popup()
    }
}
</code>```

答:
Thanks to  Ramkumar R's answer. Now it works when using mouse.x and mouse.y in popup:</p>

```<code>MouseArea {
        anchors.fill: parent
        onPressAndHold:mapPopupMenu.popup(mouse.x, mouse.y)
    }
</code>```

Body:
When trying to create a menu on map, menu pops up at center of the map rather than touched place on map when using onPressAndHold on Android. However the same code works correctly on desktop (Ubuntu). When press and hold with mouse on map, the menu pops up from mouse position on Ubuntu. I also tried Map Viewer example in Qt 5.13, it is the same. Is it possible to fix the menu position for Android? Thanks.

import QtQuick.Window 2.2
import QtQuick 2.11
import QtQuick.Controls 2.4
import QtLocation 5.11
import QtPositioning 5.11

Window {
    id: root
    visible: true
    width: 640
    height: 480
    Plugin {
        id: mapPlugin
        name: "osm"
    }
    Menu {
        id:mapPopupMenu
        Action {
            text: qsTr("Get coordinate")
        }
    }

    Map {
        id: map
        anchors.fill: parent
        plugin: mapPlugin
        zoomLevel: 14
        center:  QtPositioning.coordinate(40,40)
        activeMapType: supportedMapTypes[1]
    }

    MouseArea {
        anchors.fill: parent
        onPressAndHold:mapPopupMenu.popup()
    }
}

Body:
Thanks to  Ramkumar R's answer. Now it works when using mouse.x and mouse.y in popup:

MouseArea {
        anchors.fill: parent
        onPressAndHold:mapPopupMenu.popup(mouse.x, mouse.y)
    }


问:
Getting null object reference when passing data from 1st tab to 3rd tab activity in android
I am passing data from the first tab fragment to the 3rd tab fragment using an interface in the pager adapter.

My Main Activity

```<code>public class MainActivity extends AppCompatActivity implements FragmentOne.SendMessage {
    TabLayout tabLayout;
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
        tabLayout.addTab(tabLayout.newTab().setText("Fragment1"));
        tabLayout.addTab(tabLayout.newTab().setText("Fragment2"));
        tabLayout.addTab(tabLayout.newTab().setText("Fragment3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        final MyAdapter adapter = new MyAdapter(this, getSupportFragmentManager(),
                tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    @Override
    public void sendData(String message) {
        System.out.println("message1"+message);
        String tag = "android:switcher:" + R.id.viewPager + ":" + 2; // here i am getting the value of tag but in the line below it is throwing null object reference.
        FragmentThree lah = (FragmentThree)getSupportFragmentManager().findFragmentByTag(tag);
if(message != null){
    assert lah != null;
    lah.displayReceivedData(message); // here i am getting null
}
</code>```

My First Fragment

```<code>public class FragmentOne extends Fragment {
    private SendMessage sendMessage;
    public FragmentOne() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment1, container, false);
    }
    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button btnPassData = view.findViewById(R.id.btnPassData);
        final EditText inData = view.findViewById(R.id.passMessage);
        btnPassData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage.sendData("hlahari");
            }
        });
    }
    interface SendMessage {
        void sendData(String message);
    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        try {
            sendMessage = (SendMessage) getActivity();
        }
        catch (ClassCastException e) {
            throw new ClassCastException("Error in retrieving data. Please try again");
        }
    }
}
</code>```

And in third fragment I am getting data

```<code>public class FragmentThree extends Fragment {
    private TextView textView;
    public FragmentThree() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment3, container, false);
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        textView = view.findViewById(R.id.txtData);
    }
    public void displayReceivedData(String message)
    {
        System.out.println("message3"+message);
        textView.setText("Data received: "+message);
    }
</code>```

}

My view Pager adapter class

```<code>class MyAdapter extends FragmentPagerAdapter {
   Context context;
   int totalTabs;
   public MyAdapter(Context c, FragmentManager fm, int totalTabs) {
      super(fm);
      context = c;
      this.totalTabs = totalTabs;
   }
   @Override
   public Fragment getItem(int position) {
      switch (position) {
         case 0:
            FragmentOne frag1 = new FragmentOne();

         return frag1;
         case 1:
            FragmentTwo frag2 = new FragmentTwo();
         return frag2;
         case 2:
             FragmentThree frag3 = new FragmentThree();
         return frag3;
         default:
         return null;
      }
   }
   @Override
   public int getCount() {
      return totalTabs;
   }
}
</code>```

Please help me how to solve the problem. Is there any method to pass data from tab 1 fragment to 3rd tab fragment.

答:
Is there any method to pass data from tab 1 fragment to 3rd tab fragment.

you should use SharedViewModel approach which is recommended by Google now and it is very easy and best approach

https://developer.android.com/topic/libraries/architecture/viewmodel

Please refer to the above link.

Body:
I am passing data from the first tab fragment to the 3rd tab fragment using an interface in the pager adapter.

My Main Activity

public class MainActivity extends AppCompatActivity implements FragmentOne.SendMessage {
    TabLayout tabLayout;
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
        tabLayout.addTab(tabLayout.newTab().setText("Fragment1"));
        tabLayout.addTab(tabLayout.newTab().setText("Fragment2"));
        tabLayout.addTab(tabLayout.newTab().setText("Fragment3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        final MyAdapter adapter = new MyAdapter(this, getSupportFragmentManager(),
                tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    @Override
    public void sendData(String message) {
        System.out.println("message1"+message);
        String tag = "android:switcher:" + R.id.viewPager + ":" + 2; // here i am getting the value of tag but in the line below it is throwing null object reference.
        FragmentThree lah = (FragmentThree)getSupportFragmentManager().findFragmentByTag(tag);
if(message != null){
    assert lah != null;
    lah.displayReceivedData(message); // here i am getting null
}

My First Fragment

public class FragmentOne extends Fragment {
    private SendMessage sendMessage;
    public FragmentOne() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment1, container, false);
    }
    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button btnPassData = view.findViewById(R.id.btnPassData);
        final EditText inData = view.findViewById(R.id.passMessage);
        btnPassData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage.sendData("hlahari");
            }
        });
    }
    interface SendMessage {
        void sendData(String message);
    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        try {
            sendMessage = (SendMessage) getActivity();
        }
        catch (ClassCastException e) {
            throw new ClassCastException("Error in retrieving data. Please try again");
        }
    }
}

And in third fragment I am getting data

public class FragmentThree extends Fragment {
    private TextView textView;
    public FragmentThree() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment3, container, false);
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        textView = view.findViewById(R.id.txtData);
    }
    public void displayReceivedData(String message)
    {
        System.out.println("message3"+message);
        textView.setText("Data received: "+message);
    }

}

My view Pager adapter class

class MyAdapter extends FragmentPagerAdapter {
   Context context;
   int totalTabs;
   public MyAdapter(Context c, FragmentManager fm, int totalTabs) {
      super(fm);
      context = c;
      this.totalTabs = totalTabs;
   }
   @Override
   public Fragment getItem(int position) {
      switch (position) {
         case 0:
            FragmentOne frag1 = new FragmentOne();

         return frag1;
         case 1:
            FragmentTwo frag2 = new FragmentTwo();
         return frag2;
         case 2:
             FragmentThree frag3 = new FragmentThree();
         return frag3;
         default:
         return null;
      }
   }
   @Override
   public int getCount() {
      return totalTabs;
   }
}

Please help me how to solve the problem. Is there any method to pass data from tab 1 fragment to 3rd tab fragment.


问:
How to refresh styles and layout of radio buttons in jQuery Mobile?
I'm using

```<code>$("input[type='radio']").checkboxradio("refresh");
</code>```

to refresh a container of radio buttons.  Except when I remove/add a radio button from/to the top or bottom, I do not get rounded corners on the new (top or bottom) radio button.

Here is the jquery ajax function that contains the code for removing a radio button:

```<code>$.ajax({
 type: "POST",
 url: url,
 data: data,
 dataType: "json",
 success: function(resp) {
    $("'label[for="+key+"]'").parent().remove();
}
</code>```

Here is the form:

```<code><form id="test-form">
  <div data-role="fieldcontain" id="test">
    <fieldset data-role="controlgroup">
        <input type="radio" name="key" id="{{a.key}}" value="{{a.key}}"
    <label for="{{a.key}}">{{a.name}}</label>
        <input type="radio" name="key" id="{{b.key}}" value="{{b.key}}"
    <label for="{{b.key}}">{{b.name}}</label>
        <input type="radio" name="key" id="{{c.key}}" value="{{c.key}}"
    <label for="{{c.key}}">{{c.name}}</label>
    </fieldset>
  </div>
</form>
</code>```

答:
Call .page() on an element that is a parent of the element that doesn't render correctly.

We'll have to find a way to do it with refresh

Body:
I'm using

$("input[type='radio']").checkboxradio("refresh");

to refresh a container of radio buttons.  Except when I remove/add a radio button from/to the top or bottom, I do not get rounded corners on the new (top or bottom) radio button.

Here is the jquery ajax function that contains the code for removing a radio button:

$.ajax({
 type: "POST",
 url: url,
 data: data,
 dataType: "json",
 success: function(resp) {
    $("'label[for="+key+"]'").parent().remove();
}

Here is the form:

<form id="test-form">

    <fieldset data-role="controlgroup">
        <input type="radio" name="key" id="{{a.key}}" value="{{a.key}}"
    {{a.name}}
        <input type="radio" name="key" id="{{b.key}}" value="{{b.key}}"
    {{b.name}}
        <input type="radio" name="key" id="{{c.key}}" value="{{c.key}}"
    {{c.name}}
    </fieldset>

</form>


问:
How to add new tabs to a TabControl and be able to update controls in them?
I need to be able to programmatically create new tabs on a TabControl, add controls to them, and be able to update the controls in each tab from another function. I already have a function to add tabs to the control, and to add controls to those tabs when they are created, but I'm stuck as to update the controls after they have been created.

EDIT: This is what I have to make the tabs and add the controls:

```<code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim tabpage As New TabPage
    tabpage.Text = "(empty)"

    Dim textbox1 As New TextBox
    Dim textbox2 As New TextBox

    textbox1.Parent = tabpage
    textbox2.Parent = tabpage

    textbox1.Location = New Point(10, 10)
    textbox2.Location = New Point(10, 30)

    TabControl1.TabPages.Add(tabpage)

End Sub
</code>```

Urgh. I can't seem to get back into the account I used to post this question, so I have to post my follow-up to Tim's question in the comments for the previous answer as a new answer.
Debug.WriteLine(TabControl1.TabPages.Item(2).Controls.Find("textbox1", True).Count) returns 0. The tab and the controls have been created prior.

答:
can i add tabcontroll elements after programm started?

```<code>  For i = 0 To frmMain.cmbZielSpache.Items.Count - 1

        Dim cBox = New CheckBox()
        cBox.Name = "GEN_" & i
        cBox.Location = New Point(offsetX, offsetY)
        cBox.Text = frmMain.cmbZielSpache.Items(i)

        If frmMain.cmbZielSpache.Items(i) = frmMain.cmbZielSpache.Text Or My.Settings.chkTranslate_normal_alleSprachen = True Then
            cBox.Checked = True
        End If

        offsetX = offsetX + 120

        Me.Controls.Add(cBox)
        AddHandler cBox.CheckedChanged, AddressOf checkChangedHandler

    Next i
</code>```

Instead of using Me.Controls i wanna add the checkboxes after programm started dynamically.

Body:
I need to be able to programmatically create new tabs on a TabControl, add controls to them, and be able to update the controls in each tab from another function. I already have a function to add tabs to the control, and to add controls to those tabs when they are created, but I'm stuck as to update the controls after they have been created.

EDIT: This is what I have to make the tabs and add the controls:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim tabpage As New TabPage
    tabpage.Text = "(empty)"

    Dim textbox1 As New TextBox
    Dim textbox2 As New TextBox

    textbox1.Parent = tabpage
    textbox2.Parent = tabpage

    textbox1.Location = New Point(10, 10)
    textbox2.Location = New Point(10, 30)

    TabControl1.TabPages.Add(tabpage)

End Sub

Urgh. I can't seem to get back into the account I used to post this question, so I have to post my follow-up to Tim's question in the comments for the previous answer as a new answer.
Debug.WriteLine(TabControl1.TabPages.Item(2).Controls.Find("textbox1", True).Count) returns 0. The tab and the controls have been created prior.

Body:
can i add tabcontroll elements after programm started?

  For i = 0 To frmMain.cmbZielSpache.Items.Count - 1

        Dim cBox = New CheckBox()
        cBox.Name = "GEN_" & i
        cBox.Location = New Point(offsetX, offsetY)
        cBox.Text = frmMain.cmbZielSpache.Items(i)

        If frmMain.cmbZielSpache.Items(i) = frmMain.cmbZielSpache.Text Or My.Settings.chkTranslate_normal_alleSprachen = True Then
            cBox.Checked = True
        End If

        offsetX = offsetX + 120

        Me.Controls.Add(cBox)
        AddHandler cBox.CheckedChanged, AddressOf checkChangedHandler

    Next i

Instead of using Me.Controls i wanna add the checkboxes after programm started dynamically.


问:
PHP: how can I change variable content of a txt file?
I currently try to find a solution to edit a column of a txt file, the problem is there a no column "endings?". I need to multiple the price by 1.1 & replace it with the new value (fields I need to edit 280,24 and 378,07)

this txt updates every 12h so the prices change every 12h...

a row looks like this:

```<code>961983  5031713050124   44661802    3335    OKI 19  Lasertoner  schwarz OKI 44661802    1       ST  280,24  378,07                                  29.05.2020  Lager   Beschaffungsartikel nein
</code>```

anyone has a sugesstion how i could do it?

答:
Are the columns of fixed width? Then you could use preg_split as

$data = preg_split("/[\s,]+/", $input);

and search for the term ST in the array and increment the next four fields as
$num = (int)$data[index] * 1.1;
$data[index] = $num;

Then build the string again using implode() as
 $input = implode("\number of spaces\",$data);

Note that this maybe treated as a pseudo code of PHP, the functions exist but since I dont know whether the spaces are fixed or not or the way to write back to CSV I cant write the exact code.

Please forgive me if I couldnt solve the question exactly.

Body:
I currently try to find a solution to edit a column of a txt file, the problem is there a no column "endings?". I need to multiple the price by 1.1 & replace it with the new value (fields I need to edit 280,24 and 378,07)

this txt updates every 12h so the prices change every 12h...

a row looks like this:

961983  5031713050124   44661802    3335    OKI 19  Lasertoner  schwarz OKI 44661802    1       ST  280,24  378,07                                  29.05.2020  Lager   Beschaffungsartikel nein

anyone has a sugesstion how i could do it?