问:
OpenCV NoneType object has no attribute shape
Hello I'm working on Raspberry Pi with OpenCV. I want to try a tutorial which is ball tracking in link
http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/

But when I compile it, i get an error: 'NoneType' object has no attribute 'shape'.

What should I do?

答: I also face the same issue "OpenCV NoneType object has no attribute shape" and i solve this by changing the image location. I also use the PyCharm IDE. Currently my image location and class file in the same folder.


来源: stackexchange

问:
Why is any() only defined for a numeric and not logical data.frame?
This appears to be quite surprising:

```<code>df1 <- data.frame(A=TRUE, B=FALSE)
df2 <- data.frame(A=1, B=2)

> any(df1)
Error in FUN(X[[i]], ...) :
  only defined on a data frame with all numeric variables

> any(df2)
[1] TRUE
</code>```

This doesn't seem to be a bug because the error correctly states that any() will only work in the case where all variables within a data.frame are numeric.

But what is the reason for any() to work on all numeric variables and not when values are all logical?

答:
any can work if it is vector as the documentation says

Given a set of logical vectors, is at least one of the values true?

In the OP's post, both examples are not vectors.  The first is a data.frame with logical columns.  If we go by way to satisfy the documentation i.e create a logical vector, either convert to matrix (as a matrix is a vector anyway with some dim attributes)

```<code>any(as.matrix(df1))
#[1] TRUE
</code>```

Or change it to a vector by unlisting the list (a data.frame is a list of vectors aka columns of same length)

```<code>any(unlist(df1))
</code>```

In the second case, there is a warning and it is doing some coercing

```<code>any(df2)
#[1] TRUE
</code>```

Warning message: In any(c(1, 2), na.rm = FALSE) :   coercing argument
  of type 'double' to logical

ContentLicense: CC BY-SA 4.0

Body:
This appears to be quite surprising:

df1 <- data.frame(A=TRUE, B=FALSE)
df2 <- data.frame(A=1, B=2)

> any(df1)
Error in FUN(X[[i]], ...) :
  only defined on a data frame with all numeric variables

> any(df2)
[1] TRUE

This doesn't seem to be a bug because the error correctly states that any() will only work in the case where all variables within a data.frame are numeric.

But what is the reason for any() to work on all numeric variables and not when values are all logical?

Body:
any can work if it is vector as the documentation says

Given a set of logical vectors, is at least one of the values true?

In the OP's post, both examples are not vectors.  The first is a data.frame with logical columns.  If we go by way to satisfy the documentation i.e create a logical vector, either convert to matrix (as a matrix is a vector anyway with some dim attributes)

any(as.matrix(df1))
#[1] TRUE

Or change it to a vector by unlisting the list (a data.frame is a list of vectors aka columns of same length)

any(unlist(df1))

In the second case, there is a warning and it is doing some coercing

any(df2)
#[1] TRUE

Warning message: In any(c(1, 2), na.rm = FALSE) :   coercing argument
  of type 'double' to logical


问:
Is it possible to send an SMS over Wifi?
I'm working on an Android application in Android Studio and wanted to add a feature that allowed a text (SMS) message to be sent from the application to a mobile phone number.

I found one way to do this by using the SMS Manager API, but it seems like this only works if the application is run on a cell phone with a SIM Card/Data plan. I'd like the user to be able to send a text over WiFi in case they're running the application on a tablet with only WiFi or another device that only has access to a WiFi connection. The application would only send messages to a mobile number, and doesn't need to worry about receiving texts back from said mobile number.

My initial research proves that it is not possible to send SMS messages over WiFi. My question is, is this actually the case? Or does anyone know of a way to do this over a WiFi connection? Even if I don't use SMS, I'd like some other way to get a message from the device to a mobile phone number. I just figured that SMS would be the most straight forward.

答: If you're willing to pay for the service, you can use something like Twilio's Programmable SMS which does let you send text messages via calls to a REST API: https://www.twilio.com/docs/sms/api</p>


问:
Memory management with low memory: finding and tracking duplicates of random function return values
Lets assume i have a function that takes 32bit integer in, and returns random 32bit integer out.

Now, i want to see how many and which duplicate values this function will return on all possible input values from 0 to 2^32-1. I could make this easy if i had more than 4gigs free ram, but i dont have more than 1gig ram.

I tried to map the calculated values on disk, using 4gig file where one byte represented how many duplicates it had got, but i noticed the approximated finishing time will be 25 days in the future with my HDD speeds! (i had to use SSD in fear of breaking my HDD...)

So, now the next step is to calculate this all in RAM and not use disk at all, but i ran at wall when thinking how to solve this elegantly. The only method i could think of was to loop (2^32)*(2^32) times the function, but this is obviously even slower than my HDD method.

What i need now is some nasty ideas to speed this up!

Edit: The function isnt really a random function, but similar to a random function, but the fact is you dont need to know anything about the function, its not the problem here. I want to see all the duplicates by my bare eyes, not just some mathematical guessing how many there could be. Why im doing this? Out of curiosity :)

答:
To check for 2^32 possible duplicates you only need 4 gigabits which is 512MB, since you need only a single bit per value. The first hit of a zero bit sets it to 1 and on every hit of a 1 bit you know you have a duplicate and can print it out or do whatever you want to do with it.

I.e. you can do something like this:

```<code>int value = nextValue(...);
static int bits[] = new int[ 0x08000000 ]();

unsigned int idx = value >> 5, bit = 1 << ( value & 31 );
if( bits[ idx ] & bit )
   // duplicate
else
    bits[ idx ] |= bit;
</code>```

in response to your comments

Yes, putting the duplicates into a map is a good idea if there are not too many and not to many different duplicates. The worst case here is 2^31 entries if every 2nd value appears exactly twice. If the map becomes too large to be held in in memory at once you can partition it, i.e. by only allowing values in the certain range, i.e. a quarter of the entire number space. This would make the map have only 1/4th of the size of the entire map if the duplicates are distributed rather equally. You would of course need to run the program 4 times for each quarter to find all duplicates.

To find also the 1st duplicate you can run it in two passes: In the first pass you use the bitmap to find the duplicates and put them into the map. In the 2nd pass you skip the bitmap and add the values into the map if there is already a entry in the map and the value is not yet there.

No, there is no good reason for a int over a unsigned int array. you can as well use unsigned int which would actually be more appropriate here.

ContentLicense: CC BY-SA 3.0

Body:
To check for 2^32 possible duplicates you only need 4 gigabits which is 512MB, since you need only a single bit per value. The first hit of a zero bit sets it to 1 and on every hit of a 1 bit you know you have a duplicate and can print it out or do whatever you want to do with it.

I.e. you can do something like this:

int value = nextValue(...);
static int bits[] = new int[ 0x08000000 ]();

unsigned int idx = value >> 5, bit = 1 << ( value & 31 );
if( bits[ idx ] & bit )
   // duplicate
else
    bits[ idx ] |= bit;

in response to your comments

Yes, putting the duplicates into a map is a good idea if there are not too many and not to many different duplicates. The worst case here is 2^31 entries if every 2nd value appears exactly twice. If the map becomes too large to be held in in memory at once you can partition it, i.e. by only allowing values in the certain range, i.e. a quarter of the entire number space. This would make the map have only 1/4th of the size of the entire map if the duplicates are distributed rather equally. You would of course need to run the program 4 times for each quarter to find all duplicates.

To find also the 1st duplicate you can run it in two passes: In the first pass you use the bitmap to find the duplicates and put them into the map. In the 2nd pass you skip the bitmap and add the values into the map if there is already a entry in the map and the value is not yet there.

No, there is no good reason for a int over a unsigned int array. you can as well use unsigned int which would actually be more appropriate here.


问:
React datepicker set min and max date
I am using react-datepicker in my project.

I need to display only days for a specific month (lets say February 2020). I was under the impression that I could pass iso dates as minDate and maxDate but this does not seem to work.

My code:

```<code>   const DatePickerMod = () => {
    const [startDate, setStartDate] = useState(null);
  return (
    <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      minDate={'02-01-2020'}
      maxDate={'02-29-2020}
      placeholderText="Select a date in February 2020"
    />
  );
  };
</code>```

答:
minDate and maxDate are Date objects not String.

```<code><DatePicker
  selected={startDate}
  onChange={date => setStartDate(date)}
  minDate={new Date(2020, 1, 1)}
  maxDate={new Date(2020, 1, 29)}
  placeholderText="Select a date in February 2020"
/>
</code>```

MDN Date

React DatePicker Documentation

Title: React datepicker set min and max date

Body:
I am using react-datepicker in my project.

I need to display only days for a specific month (lets say February 2020). I was under the impression that I could pass iso dates as minDate and maxDate but this does not seem to work.

My code:

   const DatePickerMod = () => {
    const [startDate, setStartDate] = useState(null);
  return (
    <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      minDate={'02-01-2020'}
      maxDate={'02-29-2020}
      placeholderText="Select a date in February 2020"
    />
  );
  };

Body:
minDate and maxDate are Date objects not String.

<DatePicker
  selected={startDate}
  onChange={date => setStartDate(date)}
  minDate={new Date(2020, 1, 1)}
  maxDate={new Date(2020, 1, 29)}
  placeholderText="Select a date in February 2020"
/>

MDN Date

React DatePicker Documentation


问:
Combine awkward-array JaggedArray contents and offsets into nested JaggedArray
I'm trying to use the excellent uproot and awkward-array to read some analysis data stored in a TTree. I understand that ROOT doesn't write nested vectors (ie. std::vector<std::vector<int>>) in a columnar format, but following this discussion, I modified my tree output to contain two separate branches: one std::vector<int> with the content, and one std::vector<int> with the offsets. The contents vector has values pushed into it multiple times between filling the tree. Each time it has values pushed in, the size of the contents vector is stored in the offsets.

My idea was that I would recreate the structure that I need via a nested JaggedArray when I read the tree. However, reading through the awkward-array documentation, I can't seem to figure out the right way to construct this nested JaggedArray without looping in python. fromoffsets requires a 1D index, which means that the jagged indices must be flattened, which then loses their structure. None of the other classmethods seem to fit. The example below uses a generator, which I think will be rather slow due to looping in python. Is there a better way to construct the JaggedArray? Or a better way to store the data in the tree?

import awkward as ak
all_jagged_indices = ak.fromiter([[0, 1, 4], [0, 1, 2, 3]])
all_constituents = ak.fromiter([[12, 14, 3, 4], [2, 8, 3]])
output = ak.fromiter(
    (ak.JaggedArray.fromoffsets(jagged_indices, constituents)
     for jagged_indices, constituents in
     zip(all_jagged_indices, all_constituents))
)
expected = ak.fromiter([[[12], [14, 3, 4]], [[2], [8], [3]]])
assert (output == expected).all().all().all()
```

Thanks!

答:
You've got the right idea, but ultimately, there isn't a way to convert a jagged ObjectArray into a doubly jagged array without a "for" loop. The structure of the data requires it.

This is a key issue, though, and it's a reason why some of these algorithms are being ported into C++. The last plot in this talk directly addresses this kind of data (jagged^N of numbers) with a "for" loop moved into C++. This is in development for Awkward 1.0 and Uproot 4.0, which is scheduled to be ready for users at the end of April. (At which point, the conversion of std::vector<std::vector<numbers>> will be automatic, because there's no performance penality anymore.)

At the moment, however, a Python "for" loop, implicitly within fromiter, is the best you can do.

Body:
I'm trying to use the excellent uproot and awkward-array to read some analysis data stored in a TTree. I understand that ROOT doesn't write nested vectors (ie. std::vector<std::vector<int>>) in a columnar format, but following this discussion, I modified my tree output to contain two separate branches: one std::vector<int> with the content, and one std::vector<int> with the offsets. The contents vector has values pushed into it multiple times between filling the tree. Each time it has values pushed in, the size of the contents vector is stored in the offsets.

My idea was that I would recreate the structure that I need via a nested JaggedArray when I read the tree. However, reading through the awkward-array documentation, I can't seem to figure out the right way to construct this nested JaggedArray without looping in python. fromoffsets requires a 1D index, which means that the jagged indices must be flattened, which then loses their structure. None of the other classmethods seem to fit. The example below uses a generator, which I think will be rather slow due to looping in python. Is there a better way to construct the JaggedArray? Or a better way to store the data in the tree?

import awkward as ak
all_jagged_indices = ak.fromiter([[0, 1, 4], [0, 1, 2, 3]])
all_constituents = ak.fromiter([[12, 14, 3, 4], [2, 8, 3]])
output = ak.fromiter(
    (ak.JaggedArray.fromoffsets(jagged_indices, constituents)
     for jagged_indices, constituents in
     zip(all_jagged_indices, all_constituents))
)
expected = ak.fromiter([[[12], [14, 3, 4]], [[2], [8], [3]]])
assert (output == expected).all().all().all()

Thanks!


问:
GCC modified/custom target with a custom calling convention on x86-64
I was wondering if it's possible (in a reasonable amount of time) to modify an existing or to define a new build target for gcc. The goal is to do minor modifications like changing the register in which the result of a function is returned or passing arguments using different registers than by the standard SystemV ABI for x86-64.

For example if I want to change the register for the return value of a function from RAX to R8 or returning a 64-byte struct using YMM0 and YMM1 without writing it myself using x86 asm code.

(Background) I'm working on a small self-written OS so I was wondering if it's possible to not stick to System-V ABI or the one used by Microsoft for Windows. Compatibility with existing libs and stuff is not neccessary as every line of OS code is written by myself. I'm only using gcc, ld and objdump. No gdb, etc...

If this is possible, where do I have to make such modifications in the gcc source or config files? I've cloned the gcc git repo, but couldn't find a starting point for such a modification.

答:
This is all a bit theoretical, since I've never actually attempted a complete customisation. But I think it would be a reasonable project.

GCC internals are documented in the GCC internals manual. You probably don't need to read all of it in detail but you should at least try to get an overview of the basic structure. It is all highly configurable.

The calling convention is configured in the "machine description", which in part of the back end. The most important part for the type of changes you are looking at is the description of the stack layout and calling conventions. For example, you can change the way functions return scalar values using the TARGET_FUNCTION_VALUE hook, although you probably will also need to modify other parts of the machine description to correctly handle the register assignment.

I'd suggest starting with a very small modification and thoroughly testing it (at least by verifying that the assembler output is as expected). Then you can implement other modifications, as required. As you develop the changes, keep a collection of test cases; these  will be extremely useful to help ensure that changes don't have unexpected interactions with each other.


问:
Is it bad practice to store VkSemaphores in an std::unordered_map in a synchronisation manager class?
Vulkan API requires you to synchronise your rendering using VkSemaphores. When rendering a frame for example, we have to wait until the next image can be acquired from the swapchain. We also have to signal that presentation of the rendered image can begin. This is discussed by every Vulkan tutorial.

The semaphores are create during initialisation and destroyed during shutdown. In any example code I could find (Sascha Willems, official Khronos examples..), VkSemaphore are stored as a class member in the renderer class. I was wondering if I could abstract the problem by creating a VulkanSemaphoreManager class, which would be inherited by the renderer class. In short, this class stores the semaphores in an unordered_map with std::string (the name I gave to the semaphore) as key:

```<code>/// @class VulkanSynchronisationManager
/// @brief Creates and destroys Vulkan fences and semaphores.
/// Those are essential for the synchronisation of multithreaded rendering and asynchronous code in general!
/// @note Fences are mainly designed to synchronize your application itself with rendering operation,
/// whereas semaphores are used to synchronize operations within or across command queues.
class VulkanSynchronisationManager
{
    private:

        // The semaphores that our application needs.
        std::unordered_map<std::string, VkSemaphore> semaphores;

    public:

        VulkanSynchronisationManager()
        {}

        ~VulkanSynchronisationManager()
        {}

    protected:

        /// @brief Checks if a semaphore with this name already exists.
        /// @param semaphore_name The name of the semaphore.
        /// @return True if a Vulkan semaphore with this name already exists, false otherwise.
        bool does_semaphore_exist(const std::string&semaphore_name) const
        {
            std::unordered_map<std::string, VkSemaphore>::const_iterator semaphore_lookup = semaphores.find(semaphore_name);

            if(semaphore_lookup == semaphores.end())
            {
                return true;
            }

            return false;
        }

        /// @brief Creates a new Vulkan semaphore.
        /// @param semaphore_name The unique name of the semaphore.
        const std::optional<VkSemaphore> VulkanSynchronisationManager::create_semaphore(const VkDevice& vulkan_device, const std::string& semaphore_name) const
        {
            // First check if a Vulkan semaphore with this name already exists!
            if(does_semaphore_exist(semaphore_name))
            {
                // Error handling...
                return std::nullopt;
            }

            VkSemaphoreCreateInfo semaphore_create_info = {};

            // So far, there is nothing to fill into this structure.
            // This may change in the future!
            // https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkSemaphoreCreateInfo.html
            semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
            semaphore_create_info.pNext = nullptr;
            semaphore_create_info.flags = 0;

            // The new Vulkan semaphore which will be created.
            VkSemaphore new_semaphore;

            VkResult result = vkCreateSemaphore(vulkan_device, &semaphore_create_info, nullptr, &new_semaphore);
            if(VK_SUCCESS != result)
            {
                vulkan_error_check(result);
                return std::nullopt;
            }

            // THIS does not work, see following text.
            semaphores.insert({semaphore_name, new_semaphore});

            return new_semaphore;
        }

        /// @brief Gets a certain semaphore by name.
        /// @param semaphore_name The name of the semaphore.
        /// @return The acquired semaphore (if existent), std::nullopt otherwise.
        const std::optional<VkSemaphore> get_semaphore(const std::string& semaphore_name) const
        {
            if(!does_semaphore_exist(semaphore_name))
            {
                // Error handling...
                return std::nullopt;
            }

            // Return the requested semaphore.
            return semaphores.at(semaphore_name);
        }

        /// @brief Destroys all existing semaphores.
        void shutdown_semaphores(const VkDevice& vulkan_device)
        {
            // Create an iterator for the unordered map.
            std::unordered_map<std::string, VkSemaphore>::const_iterator sepahore_iterator = semaphores.begin();

            // Iterate over the unordered map.
            while(sepahore_iterator != semaphores.end())
            {
                // Destroy the semaphore.
                vkDestroySemaphore(vulkan_device, sepahore_iterator->second, nullptr);

                // Move on to the next Semaphore.
                sepahore_iterator++;
            }

            // Clear the unordered map!
            semaphores.clear();
        }

};
</code>```

This class bundles all existing semaphores and offers create and get methods. It is also responsible for destroying all semaphores during application shutdown.

But there is a problem: We can't insert the new VkSemaphore into the unordered_map, because Vulkan defines semaphores are nondispatchable handles.

Is this a good idea after all?

Thanks for you feedback, John.

答:
I found the problem: By declaring create_semaphore as a "const" member function, I was unable to modify the unordered_map.

Thanks for the advice though! Since this class is way bigger than the old approach, I will rethink it.

Body:
Vulkan API requires you to synchronise your rendering using VkSemaphores. When rendering a frame for example, we have to wait until the next image can be acquired from the swapchain. We also have to signal that presentation of the rendered image can begin. This is discussed by every Vulkan tutorial.

The semaphores are create during initialisation and destroyed during shutdown. In any example code I could find (Sascha Willems, official Khronos examples..), VkSemaphore are stored as a class member in the renderer class. I was wondering if I could abstract the problem by creating a VulkanSemaphoreManager class, which would be inherited by the renderer class. In short, this class stores the semaphores in an unordered_map with std::string (the name I gave to the semaphore) as key:

/// @class VulkanSynchronisationManager
/// @brief Creates and destroys Vulkan fences and semaphores.
/// Those are essential for the synchronisation of multithreaded rendering and asynchronous code in general!
/// @note Fences are mainly designed to synchronize your application itself with rendering operation,
/// whereas semaphores are used to synchronize operations within or across command queues.
class VulkanSynchronisationManager
{
    private:

        // The semaphores that our application needs.
        std::unordered_map<std::string, VkSemaphore> semaphores;

    public:

        VulkanSynchronisationManager()
        {}

        ~VulkanSynchronisationManager()
        {}

    protected:

        /// @brief Checks if a semaphore with this name already exists.
        /// @param semaphore_name The name of the semaphore.
        /// @return True if a Vulkan semaphore with this name already exists, false otherwise.
        bool does_semaphore_exist(const std::string&semaphore_name) const
        {
            std::unordered_map<std::string, VkSemaphore>::const_iterator semaphore_lookup = semaphores.find(semaphore_name);

            if(semaphore_lookup == semaphores.end())
            {
                return true;
            }

            return false;
        }

        /// @brief Creates a new Vulkan semaphore.
        /// @param semaphore_name The unique name of the semaphore.
        const std::optional<VkSemaphore> VulkanSynchronisationManager::create_semaphore(const VkDevice& vulkan_device, const std::string& semaphore_name) const
        {
            // First check if a Vulkan semaphore with this name already exists!
            if(does_semaphore_exist(semaphore_name))
            {
                // Error handling...
                return std::nullopt;
            }

            VkSemaphoreCreateInfo semaphore_create_info = {};

            // So far, there is nothing to fill into this structure.
            // This may change in the future!
            // https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkSemaphoreCreateInfo.html
            semaphore_create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
            semaphore_create_info.pNext = nullptr;
            semaphore_create_info.flags = 0;

            // The new Vulkan semaphore which will be created.
            VkSemaphore new_semaphore;

            VkResult result = vkCreateSemaphore(vulkan_device, &semaphore_create_info, nullptr, &new_semaphore);
            if(VK_SUCCESS != result)
            {
                vulkan_error_check(result);
                return std::nullopt;
            }

            // THIS does not work, see following text.
            semaphores.insert({semaphore_name, new_semaphore});

            return new_semaphore;
        }

        /// @brief Gets a certain semaphore by name.
        /// @param semaphore_name The name of the semaphore.
        /// @return The acquired semaphore (if existent), std::nullopt otherwise.
        const std::optional<VkSemaphore> get_semaphore(const std::string& semaphore_name) const
        {
            if(!does_semaphore_exist(semaphore_name))
            {
                // Error handling...
                return std::nullopt;
            }

            // Return the requested semaphore.
            return semaphores.at(semaphore_name);
        }

        /// @brief Destroys all existing semaphores.
        void shutdown_semaphores(const VkDevice& vulkan_device)
        {
            // Create an iterator for the unordered map.
            std::unordered_map<std::string, VkSemaphore>::const_iterator sepahore_iterator = semaphores.begin();

            // Iterate over the unordered map.
            while(sepahore_iterator != semaphores.end())
            {
                // Destroy the semaphore.
                vkDestroySemaphore(vulkan_device, sepahore_iterator->second, nullptr);

                // Move on to the next Semaphore.
                sepahore_iterator++;
            }

            // Clear the unordered map!
            semaphores.clear();
        }

};

This class bundles all existing semaphores and offers create and get methods. It is also responsible for destroying all semaphores during application shutdown.

But there is a problem: We can't insert the new VkSemaphore into the unordered_map, because Vulkan defines semaphores are nondispatchable handles.

Is this a good idea after all?

Thanks for you feedback, John.


问:
Remove near-identical strings (noun plural forms) from list
I'm trying to identify and remove plural forms of a noun in a list. Essentially, I want the below test to pass:

```<code>@Test
public void testRemoveNounPlurals(){
    List<String> listWithDups = List.of("friend", "friends", "dog", "dogs", "serious");

    List<String> filteredList = removeDuplicates(listWithDups); // testing this method

    org.assertj.core.api.Assertions.assertThat(filteredList)
            .hasSize(3)
            .containsOnly("friend", "dog", "serious");
}
</code>```

The no-quite-there implementation:

```<code>public static List<String> removeDuplicates(List<String> list) {

    List<String> maybePlurals = list.stream()
            .filter(s -> s.endsWith("s"))
            .collect(toList()); // friends, dogs, serious

    return list.stream()
             // correctly removes friends and dogs, should keep 'serious'
            .filter( word -> maybePlurals.contains(word.concat("s")))
            .collect(toList());
}
</code>```

答:
This solution adds an "s" to each word and checks if it exists and if so removes it

```<code>public static List<String> removeDuplicates(List<String> list) {
    List<String> result = new ArrayList<>();
    result.addAll(list);

    for (String word : list) {
        String words = word + "s";
        result.remove(words);
    }
    return result;
}
</code>```

I guess some optimisation could be done by adding

```<code>if (word.endsWith("s")) {
     continue;
}
</code>```

first in the for loop

Body:
I'm trying to identify and remove plural forms of a noun in a list. Essentially, I want the below test to pass:

@Test
public void testRemoveNounPlurals(){
    List<String> listWithDups = List.of("friend", "friends", "dog", "dogs", "serious");

    List<String> filteredList = removeDuplicates(listWithDups); // testing this method

    org.assertj.core.api.Assertions.assertThat(filteredList)
            .hasSize(3)
            .containsOnly("friend", "dog", "serious");
}

The no-quite-there implementation:

public static List<String> removeDuplicates(List<String> list) {

    List<String> maybePlurals = list.stream()
            .filter(s -> s.endsWith("s"))
            .collect(toList()); // friends, dogs, serious

    return list.stream()
             // correctly removes friends and dogs, should keep 'serious'
            .filter( word -> maybePlurals.contains(word.concat("s")))
            .collect(toList());
}

Body:
This solution adds an "s" to each word and checks if it exists and if so removes it

public static List<String> removeDuplicates(List<String> list) {
    List<String> result = new ArrayList<>();
    result.addAll(list);

    for (String word : list) {
        String words = word + "s";
        result.remove(words);
    }
    return result;
}

I guess some optimisation could be done by adding

if (word.endsWith("s")) {
     continue;
}

first in the for loop


问:
Javascript - Create a currying function returning the list of parameters
I'm trying to create a currying function returning the list of parameters but I don't how to make it.
This is my code :

const getParameters = arg => {
  const parameters = [];

  const innerFunction = arg => {
    parameters.push(arg);
    return innerFunction;
  };
  return innerFunction(arg);
};

getParameters(1)(2)(5); // => expected value [1,2,5]
getParameters(1)(2)(5)(20); // => expected value [1,2,5,20]
```

答:
If you can use a final parameter(like "x") to signify end, you can use .bind

const getParameters = function(...arg) {
  if (arg[arg.length - 1] !== 'x') {
    return getParameters.bind(null, ...arg);
  }
  arg.pop();
  return arg;
};
console.info(getParameters(1)(2)(5)('x'));
console.info(getParameters(1)(2)(5)(20)("x"))```


问:
Handle NULL Parameter in SQL Server Table Valued Function
```<code>CREATE FUNCTION fn_roles(@userid varchar(36))
RETURNS TABLE
AS
    RETURN
        SELECT *
        FROM user_roles
        WHERE userid = @userid
</code>```

My function accepts a parameter @userid and returns roles that the user is assigned to from the user_roles table.

What if I want to return all records from the user_roles table if a NULL value for the parameter is passed? What would be the most elegant way to handle that?

答:
Not the least but just another option you can try this way also.

```<code>CREATE FUNCTION fn_roles (@userid VARCHAR(36))
RETURNS TABLE
AS
RETURN

SELECT *
FROM user_roles
WHERE @userid IS NULL
    OR (
        @userid IS NOT NULL
        AND userid = @userid
        )
</code>```

How do I create a conditional WHERE clause?

Body:
CREATE FUNCTION fn_roles(@userid varchar(36))
RETURNS TABLE
AS
    RETURN
        SELECT *
        FROM user_roles
        WHERE userid = @userid

My function accepts a parameter @userid and returns roles that the user is assigned to from the user_roles table.

What if I want to return all records from the user_roles table if a NULL value for the parameter is passed? What would be the most elegant way to handle that?

Body:
Not the least but just another option you can try this way also.

CREATE FUNCTION fn_roles (@userid VARCHAR(36))
RETURNS TABLE
AS
RETURN

SELECT *
FROM user_roles
WHERE @userid IS NULL
    OR (
        @userid IS NOT NULL
        AND userid = @userid
        )

How do I create a conditional WHERE clause?


问:
React setState for API doesn't update even thought it gets new parameter
I'm having issues with this web app im working on.

https://food-search-octavian.netlify.com/

Now, on the recipe page https://food-search-octavian.netlify.com/recipes my search doesn't actually work. It's binded to Enter key which works, the request itself works, but when I try to set the state to the new search, it doesn't update.

This is the code in the component:

```<code>this.state = {
      recipes: [],
      search: "chicken",
      loading: false,
      height: 0
    };
    this.getRecipes = this.getRecipes.bind(this);
    this.changeActive = this.changeActive.bind(this);
  }

  componentDidMount() {
    this.getRecipes(this.state.search);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.search !== this.state.search) {
      this.getRecipes(this.state.search);
    }
  }

  changeActive(newSearch) {
    this.setState({
      search: newSearch
    });
  }

  getRecipes = async e => {
    this.setState({
      loading: true
    });

    await recipesRequest(e).then(response => {
      this.setState({
        recipes: response,
        loading: false
      });
    });
  };
</code>```

This is the code for the request:

```<code>const axios = require("axios");

const recipesRequest = param => {
  let api_key = "*";
  let api_id = "*";

  return axios
    .get(
      `https://api.edamam.com/search?q=chicken&app_id=${api_id}&app_key=${api_key}`,
      {
        headers: {
          "Content-Type": "application/json"
        }
      }
    )
    .then(function(response) {
      return response.data.hits;
    });
};

export default recipesRequest;
</code>```

This is the component with the search that updates the active state in the first compomnent:

```<code> this.state = {
      input: ""
    };

    this.checkInput = this.checkInput.bind(this);
    this.newSearch = this.newSearch.bind(this);
    this.handleKeyDown = this.handleKeyDown.bind(this);
  }

  checkInput(e) {
    var value = e.target.value;
    this.setState({
      input: value
    });
  }

  handleKeyDown = e => {
    if (e.key === "Enter") {
      console.log(e.key);
      let choice = this.state.input;
      this.newSearch(choice);
    }
  };

  newSearch(choice) {
    this.props.changeActive(choice);
    this.setState({
      input: ""
    });
  }
</code>```

From what I read, setState is async but I kinda have the exact logic in the other page of my web app and it works.

答:
I'm guessing it is your getRecipes function. React's setState is "asynchronous, but not in the javascript async/await sense. It is more like state updates during the current render cycle are queued up to be processed for the next render cycle.

```<code>getRecipes = async e => {
  this.setState({
    loading: true
  });

  await recipesRequest(e).then(response => {
    this.setState({
      recipes: response,
      loading: false
    });
  });
};
</code>```

Here you are awaiting the execution of the state updates you've queued up, which normally are processed after the function returns. Try not awaiting it.

```<code>getRecipes = e => {
  this.setState({
    loading: true
  });

  recipesRequest(e).then(response => {
    this.setState({
      recipes: response,
      loading: false
    });
  });
};
</code>```

This allows the fetch to occur, which is asynchronous, but it correctly allows the state updates to be queued. The state will update loading to be true, and returns the (likely) unresolved Promise, and when the request resolves (any number of render cycles later) it updates state again loading false and with the recipes.

codesandbox

EDIT
In the codesandbox both ways work, so perhaps you are not receiving/processing response data correctly, or you have a malformed request.

Body:
I'm having issues with this web app im working on.

https://food-search-octavian.netlify.com/

Now, on the recipe page https://food-search-octavian.netlify.com/recipes my search doesn't actually work. It's binded to Enter key which works, the request itself works, but when I try to set the state to the new search, it doesn't update.

This is the code in the component:

this.state = {
      recipes: [],
      search: "chicken",
      loading: false,
      height: 0
    };
    this.getRecipes = this.getRecipes.bind(this);
    this.changeActive = this.changeActive.bind(this);
  }

  componentDidMount() {
    this.getRecipes(this.state.search);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.search !== this.state.search) {
      this.getRecipes(this.state.search);
    }
  }

  changeActive(newSearch) {
    this.setState({
      search: newSearch
    });
  }

  getRecipes = async e => {
    this.setState({
      loading: true
    });

    await recipesRequest(e).then(response => {
      this.setState({
        recipes: response,
        loading: false
      });
    });
  };

This is the code for the request:

const axios = require("axios");

const recipesRequest = param => {
  let api_key = "*";
  let api_id = "*";

  return axios
    .get(
      `https://api.edamam.com/search?q=chicken&app_id=${api_id}&app_key=${api_key}`,
      {
        headers: {
          "Content-Type": "application/json"
        }
      }
    )
    .then(function(response) {
      return response.data.hits;
    });
};

export default recipesRequest;

This is the component with the search that updates the active state in the first compomnent:

 this.state = {
      input: ""
    };

    this.checkInput = this.checkInput.bind(this);
    this.newSearch = this.newSearch.bind(this);
    this.handleKeyDown = this.handleKeyDown.bind(this);
  }

  checkInput(e) {
    var value = e.target.value;
    this.setState({
      input: value
    });
  }

  handleKeyDown = e => {
    if (e.key === "Enter") {
      console.log(e.key);
      let choice = this.state.input;
      this.newSearch(choice);
    }
  };

  newSearch(choice) {
    this.props.changeActive(choice);
    this.setState({
      input: ""
    });
  }

From what I read, setState is async but I kinda have the exact logic in the other page of my web app and it works.

Body:
I'm guessing it is your getRecipes function. React's setState is "asynchronous, but not in the javascript async/await sense. It is more like state updates during the current render cycle are queued up to be processed for the next render cycle.

getRecipes = async e => {
  this.setState({
    loading: true
  });

  await recipesRequest(e).then(response => {
    this.setState({
      recipes: response,
      loading: false
    });
  });
};

Here you are awaiting the execution of the state updates you've queued up, which normally are processed after the function returns. Try not awaiting it.

getRecipes = e => {
  this.setState({
    loading: true
  });

  recipesRequest(e).then(response => {
    this.setState({
      recipes: response,
      loading: false
    });
  });
};

This allows the fetch to occur, which is asynchronous, but it correctly allows the state updates to be queued. The state will update loading to be true, and returns the (likely) unresolved Promise, and when the request resolves (any number of render cycles later) it updates state again loading false and with the recipes.

codesandbox

EDIT
In the codesandbox both ways work, so perhaps you are not receiving/processing response data correctly, or you have a malformed request.


问:
RIA Services exposing nested objects
I am having an issue exposing my nested object VIA WCF RIA Service.

Example of business objects (not tied to DB)

```<code>public class User
{
    public string Name { get; set; }
    public Product Product { get; set; }

}
</code>```

The user object will come to my client object, however the product does not. How can I resolve this?

答:
You can also do it in the query like this:</p>

```<code>var MyUsers = DataContext.Users.Include("Product").ToList();
</code>```

Title: RIA Services exposing nested objects

Body:
I am having an issue exposing my nested object VIA WCF RIA Service.

Example of business objects (not tied to DB)

public class User
{
    public string Name { get; set; }
    public Product Product { get; set; }

}

The user object will come to my client object, however the product does not. How can I resolve this?

Body:
You can also do it in the query like this:

var MyUsers = DataContext.Users.Include("Product").ToList();


问:
Remove empty fields in json file
I have this json file and I have to remove some null fields. I have posted my json file and also the json file that I am expecting. Can you help me what codes should I write for this to happen?

Here is my json file:

```<code>{
 "selection1": [
  {
   "name": "Radisson Blu Azuri Resort & Spa",
   "url": "https://www.marideal.mu/hotel-deals/radisson-blu-azuri-resort-hotel-deals.html",
   "reviews": [
{
     "name": "4",
     "date": "October 09, 2015",
     "review": "The personal was friendly , helpful n professional and put you at ease."
    },
    {
     "name": "3",
     "date": "July 20, 2015",
     "review": "Everyone really enjoy each moment we had there. The staffs are all very friendly and professionals."
    }
   ]
  },
  {
   "name": "Manta Cove by Horizon Holidays",
   "url": "https://www.marideal.mu/hotel-deals/manta-cove-by-horizon-holidays.html"
  },
  {
   "name": "Sous Le Badamier",
   "url": "https://www.marideal.mu/hotel-deals/sous-le-badamier.html"
  },
  {
   "name": "Honeymoon Special at Lagoon Attitude",
   "url": "https://www.marideal.mu/hotel-deals/honeymoon-special-at-lagoon-attitude.html",
   "reviews": [
    {
     "name": "3",
     "date": "January 20, 2020",
     "review": "Lagoon Attitude has been my best hotel stay ever in Mauritius. The eco friendly concept is one of a kind, esp. with the water fountains. My friends and I were warmly welcomed upon arrival. The staff were amazingly friendly, very professional and hospitable."
    },
{
     "name": "134",
     "date": "June 12, 2019",
     "review": "Had an amazing stay for 2 nights.\nThe cleanliness of the room is faultless"
    },
    {
     "name": "132",
     "date": "April 11, 2019",
     "review": "A highly recommendable hotel. Value for money and thanks to Marideal.\nThe room provided to us was very clean, and well maintained, we got a room in the 1800`s range, personal swimming pool along being cleaned everyday."
    },
    {
     "name": "131",
     "date": "January 24, 2019",
     "review": "Super week-end en famille. Merci à toute l'équipe du Radisson pour votre accueil, votre gentilesse et votre écoute."
    },
    {
     "name": "2",
     "date": "January 06, 2020",
     "review": "Our second visit to the hotel. Fantastic experience with the new Otentik concept. The personnel is the most welcoming and kind to us, namely Mr Kevin and Mr Jevissen, as well as Ms Veronique, to name a few."
    }
   ]
  }
 ]
}
</code>```

What should I do to remove the empty fields and make my json file looks like:

```<code>{
 "selection1": [
  {
   "name": "Radisson Blu Azuri Resort & Spa",
   "url": "https://www.marideal.mu/hotel-deals/radisson-blu-azuri-resort-hotel-deals.html",
   "reviews": [
{
     "name": "4",
     "date": "October 09, 2015",
     "review": "The personal was friendly , helpful n professional and put you at ease."
    },
    {
     "name": "3",
     "date": "July 20, 2015",
     "review": "Everyone really enjoy each moment we had there. The staffs are all very friendly and professionals."
    }
   ]
  },
  {
   "name": "Honeymoon Special at Lagoon Attitude",
   "url": "https://www.marideal.mu/hotel-deals/honeymoon-special-at-lagoon-attitude.html",
   "reviews": [
    {
     "name": "3",
     "date": "January 20, 2020",
     "review": "Lagoon Attitude has been my best hotel stay ever in Mauritius. The eco friendly concept is one of a kind, esp. with the water fountains. My friends and I were warmly welcomed upon arrival. The staff were amazingly friendly, very professional and hospitable."
    },
{
     "name": "134",
     "date": "June 12, 2019",
     "review": "Had an amazing stay for 2 nights.\nThe cleanliness of the room is faultless"
    },
    {
     "name": "132",
     "date": "April 11, 2019",
     "review": "A highly recommendable hotel. Value for money and thanks to Marideal.\nThe room provided to us was very clean, and well maintained, we got a room in the 1800`s range, personal swimming pool along being cleaned everyday."
    },
    {
     "name": "131",
     "date": "January 24, 2019",
     "review": "Super week-end en famille. Merci à toute l'équipe du Radisson pour votre accueil, votre gentilesse et votre écoute."
    },
    {
     "name": "2",
     "date": "January 06, 2020",
     "review": "Our second visit to the hotel. Fantastic experience with the new Otentik concept. The personnel is the most welcoming and kind to us, namely Mr Kevin and Mr Jevissen, as well as Ms Veronique, to name a few."
    }
   ]
  }
 ]
}
</code>```

Can someone explain to me on how to remove the empty fields so that my json file is ready to do preprocessing of 'review' for each loop?

答:
You can use for-loop to iterate data["selection1"] and copy to new dictionary only elements which have reviews

```<code>import json

# read from file
#with open('input.json') as f:
#    data = json.load(f)

data = {
 "selection1": [
  {
   "name": "Radisson Blu Azuri Resort & Spa",
   "url": "https://www.marideal.mu/hotel-deals/radisson-blu-azuri-resort-hotel-deals.html",
   "reviews": [
{
     "name": "4",
     "date": "October 09, 2015",
     "review": "The personal was friendly , helpful n professional and put you at ease."
    },
    {
     "name": "3",
     "date": "July 20, 2015",
     "review": "Everyone really enjoy each moment we had there. The staffs are all very friendly and professionals."
    }
   ]
  },
  {
   "name": "Manta Cove by Horizon Holidays",
   "url": "https://www.marideal.mu/hotel-deals/manta-cove-by-horizon-holidays.html"
  },
  {
   "name": "Sous Le Badamier",
   "url": "https://www.marideal.mu/hotel-deals/sous-le-badamier.html"
  },
  {
   "name": "Honeymoon Special at Lagoon Attitude",
   "url": "https://www.marideal.mu/hotel-deals/honeymoon-special-at-lagoon-attitude.html",
   "reviews": [
    {
     "name": "3",
     "date": "January 20, 2020",
     "review": "Lagoon Attitude has been my best hotel stay ever in Mauritius. The eco friendly concept is one of a kind, esp. with the water fountains. My friends and I were warmly welcomed upon arrival. The staff were amazingly friendly, very professional and hospitable."
    },
    {
     "name": "134",
     "date": "June 12, 2019",
     "review": "Had an amazing stay for 2 nights.\nThe cleanliness of the room is faultless"
    },
    {
     "name": "132",
     "date": "April 11, 2019",
     "review": "A highly recommendable hotel. Value for money and thanks to Marideal.\nThe room provided to us was very clean, and well maintained, we got a room in the 1800`s range, personal swimming pool along being cleaned everyday."
    },
    {
     "name": "131",
     "date": "January 24, 2019",
     "review": "Super week-end en famille. Merci à toute l'équipe du Radisson pour votre accueil, votre gentilesse et votre écoute."
    },
    {
     "name": "2",
     "date": "January 06, 2020",
     "review": "Our second visit to the hotel. Fantastic experience with the new Otentik concept. The personnel is the most welcoming and kind to us, namely Mr Kevin and Mr Jevissen, as well as Ms Veronique, to name a few."
    }
   ]
  }
 ]
}

# dictionary for element which you want to keep
new_data = {'selection1': []}

# copy item from old data to new data if it has 'reviews'
for item in data['selection1']:
    if 'reviews' in item:
        new_data['selection1'].append(item)
        #print(item['reviews'])
        #print('--')

# save in file
with open('output.json', 'w') as f:
    json.dump(new_data, f)
</code>```

Title: Remove empty fields in json file

Body:
I have this json file and I have to remove some null fields. I have posted my json file and also the json file that I am expecting. Can you help me what codes should I write for this to happen?

Here is my json file:

{
 "selection1": [
  {
   "name": "Radisson Blu Azuri Resort & Spa",
   "url": "https://www.marideal.mu/hotel-deals/radisson-blu-azuri-resort-hotel-deals.html",
   "reviews": [
{
     "name": "4",
     "date": "October 09, 2015",
     "review": "The personal was friendly , helpful n professional and put you at ease."
    },
    {
     "name": "3",
     "date": "July 20, 2015",
     "review": "Everyone really enjoy each moment we had there. The staffs are all very friendly and professionals."
    }
   ]
  },
  {
   "name": "Manta Cove by Horizon Holidays",
   "url": "https://www.marideal.mu/hotel-deals/manta-cove-by-horizon-holidays.html"
  },
  {
   "name": "Sous Le Badamier",
   "url": "https://www.marideal.mu/hotel-deals/sous-le-badamier.html"
  },
  {
   "name": "Honeymoon Special at Lagoon Attitude",
   "url": "https://www.marideal.mu/hotel-deals/honeymoon-special-at-lagoon-attitude.html",
   "reviews": [
    {
     "name": "3",
     "date": "January 20, 2020",
     "review": "Lagoon Attitude has been my best hotel stay ever in Mauritius. The eco friendly concept is one of a kind, esp. with the water fountains. My friends and I were warmly welcomed upon arrival. The staff were amazingly friendly, very professional and hospitable."
    },
{
     "name": "134",
     "date": "June 12, 2019",
     "review": "Had an amazing stay for 2 nights.\nThe cleanliness of the room is faultless"
    },
    {
     "name": "132",
     "date": "April 11, 2019",
     "review": "A highly recommendable hotel. Value for money and thanks to Marideal.\nThe room provided to us was very clean, and well maintained, we got a room in the 1800`s range, personal swimming pool along being cleaned everyday."
    },
    {
     "name": "131",
     "date": "January 24, 2019",
     "review": "Super week-end en famille. Merci à toute l'équipe du Radisson pour votre accueil, votre gentilesse et votre écoute."
    },
    {
     "name": "2",
     "date": "January 06, 2020",
     "review": "Our second visit to the hotel. Fantastic experience with the new Otentik concept. The personnel is the most welcoming and kind to us, namely Mr Kevin and Mr Jevissen, as well as Ms Veronique, to name a few."
    }
   ]
  }
 ]
}

What should I do to remove the empty fields and make my json file looks like:

{
 "selection1": [
  {
   "name": "Radisson Blu Azuri Resort & Spa",
   "url": "https://www.marideal.mu/hotel-deals/radisson-blu-azuri-resort-hotel-deals.html",
   "reviews": [
{
     "name": "4",
     "date": "October 09, 2015",
     "review": "The personal was friendly , helpful n professional and put you at ease."
    },
    {
     "name": "3",
     "date": "July 20, 2015",
     "review": "Everyone really enjoy each moment we had there. The staffs are all very friendly and professionals."
    }
   ]
  },
  {
   "name": "Honeymoon Special at Lagoon Attitude",
   "url": "https://www.marideal.mu/hotel-deals/honeymoon-special-at-lagoon-attitude.html",
   "reviews": [
    {
     "name": "3",
     "date": "January 20, 2020",
     "review": "Lagoon Attitude has been my best hotel stay ever in Mauritius. The eco friendly concept is one of a kind, esp. with the water fountains. My friends and I were warmly welcomed upon arrival. The staff were amazingly friendly, very professional and hospitable."
    },
{
     "name": "134",
     "date": "June 12, 2019",
     "review": "Had an amazing stay for 2 nights.\nThe cleanliness of the room is faultless"
    },
    {
     "name": "132",
     "date": "April 11, 2019",
     "review": "A highly recommendable hotel. Value for money and thanks to Marideal.\nThe room provided to us was very clean, and well maintained, we got a room in the 1800`s range, personal swimming pool along being cleaned everyday."
    },
    {
     "name": "131",
     "date": "January 24, 2019",
     "review": "Super week-end en famille. Merci à toute l'équipe du Radisson pour votre accueil, votre gentilesse et votre écoute."
    },
    {
     "name": "2",
     "date": "January 06, 2020",
     "review": "Our second visit to the hotel. Fantastic experience with the new Otentik concept. The personnel is the most welcoming and kind to us, namely Mr Kevin and Mr Jevissen, as well as Ms Veronique, to name a few."
    }
   ]
  }
 ]
}

Can someone explain to me on how to remove the empty fields so that my json file is ready to do preprocessing of 'review' for each loop?

Body:
You can use for-loop to iterate data["selection1"] and copy to new dictionary only elements which have reviews

import json

# read from file
#with open('input.json') as f:
#    data = json.load(f)

data = {
 "selection1": [
  {
   "name": "Radisson Blu Azuri Resort & Spa",
   "url": "https://www.marideal.mu/hotel-deals/radisson-blu-azuri-resort-hotel-deals.html",
   "reviews": [
{
     "name": "4",
     "date": "October 09, 2015",
     "review": "The personal was friendly , helpful n professional and put you at ease."
    },
    {
     "name": "3",
     "date": "July 20, 2015",
     "review": "Everyone really enjoy each moment we had there. The staffs are all very friendly and professionals."
    }
   ]
  },
  {
   "name": "Manta Cove by Horizon Holidays",
   "url": "https://www.marideal.mu/hotel-deals/manta-cove-by-horizon-holidays.html"
  },
  {
   "name": "Sous Le Badamier",
   "url": "https://www.marideal.mu/hotel-deals/sous-le-badamier.html"
  },
  {
   "name": "Honeymoon Special at Lagoon Attitude",
   "url": "https://www.marideal.mu/hotel-deals/honeymoon-special-at-lagoon-attitude.html",
   "reviews": [
    {
     "name": "3",
     "date": "January 20, 2020",
     "review": "Lagoon Attitude has been my best hotel stay ever in Mauritius. The eco friendly concept is one of a kind, esp. with the water fountains. My friends and I were warmly welcomed upon arrival. The staff were amazingly friendly, very professional and hospitable."
    },
    {
     "name": "134",
     "date": "June 12, 2019",
     "review": "Had an amazing stay for 2 nights.\nThe cleanliness of the room is faultless"
    },
    {
     "name": "132",
     "date": "April 11, 2019",
     "review": "A highly recommendable hotel. Value for money and thanks to Marideal.\nThe room provided to us was very clean, and well maintained, we got a room in the 1800`s range, personal swimming pool along being cleaned everyday."
    },
    {
     "name": "131",
     "date": "January 24, 2019",
     "review": "Super week-end en famille. Merci à toute l'équipe du Radisson pour votre accueil, votre gentilesse et votre écoute."
    },
    {
     "name": "2",
     "date": "January 06, 2020",
     "review": "Our second visit to the hotel. Fantastic experience with the new Otentik concept. The personnel is the most welcoming and kind to us, namely Mr Kevin and Mr Jevissen, as well as Ms Veronique, to name a few."
    }
   ]
  }
 ]
}

# dictionary for element which you want to keep
new_data = {'selection1': []}

# copy item from old data to new data if it has 'reviews'
for item in data['selection1']:
    if 'reviews' in item:
        new_data['selection1'].append(item)
        #print(item['reviews'])
        #print('--')

# save in file
with open('output.json', 'w') as f:
    json.dump(new_data, f)


问:
Xcode error: "_main", referenced from: implicit entry/start for main executable
I am getting the following error, which seems to be coming from something in the bottom to do with "_main". </p>

```<code>Ld /Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Products/Debug-iphonesimulator/TownHall\ iPhone.app/TownHall\ iPhone normal i386
    cd "/Users/jianglin/Desktop/TownHall iPhone"
    export IPHONEOS_DEPLOYMENT_TARGET=8.1
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk -L/Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Products/Debug-iphonesimulator -F/Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Products/Debug-iphonesimulator -filelist /Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Intermediates/TownHall\ iPhone.build/Debug-iphonesimulator/TownHall\ iPhone.build/Objects-normal/i386/TownHall\ iPhone.LinkFileList -Xlinker -rpath -Xlinker @executable_path/Frameworks -Xlinker -objc_abi_version -Xlinker 2 -ObjC -lPods-AFNetworking -lPods-Masonry -lPods-SDWebImage -framework CoreGraphics -framework Foundation -framework ImageIO -framework MobileCoreServices -framework Security -framework SystemConfiguration -framework UIKit -fobjc-arc -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=8.1 -lPods -Xlinker -dependency_info -Xlinker /Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Intermediates/TownHall\ iPhone.build/Debug-iphonesimulator/TownHall\ iPhone.build/Objects-normal/i386/TownHall\ iPhone_dependency_info.dat -o /Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Products/Debug-iphonesimulator/TownHall\ iPhone.app/TownHall\ iPhone

Undefined symbols for architecture i386:
  "_main", referenced from:
     implicit entry/start for main executable
     (maybe you meant: _OBJC_IVAR_$_PostTableViewCell._mainTextView, _OBJC_IVAR_$_ConfirmationViewController._mainLabel , _OBJC_IVAR_$_SignInViewController._mainLabel , _OBJC_IVAR_$_SignUpViewController._mainLabel )
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

<p>Any help would be much appreciated. </p>

答:
I ran into this after a large upgrade, and was quite annoying to see so many answers across Github advising RN users to start a new project to remedy this issue.

To start, here are the build settings I was mindful of when running into this error and the settings that should be set:

Build Phases for the App Target

Link Binary With Libraries

JavaScriptCore.framework

libPods-app_name.a

Compile Sources

AppDelegate.m

main.m

Build Settings for App Target

Linking OTHER_LDFLAGS

ObjC

lc++

lz

If the settings look fine, but you still receive the error on build, the next step is to check the main file itself.

The Main.m file lives in the ios/app_name folder, and in the file itself, you will find the referenced main method. If there is an issue with this file (missing, broken), you can use the code below to recreate it:

main.m 0.23.1 - 0.62.0 from Upgrade Helper

```<code>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#import <UIKit/UIKit.h>

#import "AppDelegate.h"

int main(int argc, char * argv[]) {
  @autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
  }
}
</code>```

I really hope this helps someone out in the future.

Body:
I am getting the following error, which seems to be coming from something in the bottom to do with "_main".

Ld /Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Products/Debug-iphonesimulator/TownHall\ iPhone.app/TownHall\ iPhone normal i386
    cd "/Users/jianglin/Desktop/TownHall iPhone"
    export IPHONEOS_DEPLOYMENT_TARGET=8.1
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk -L/Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Products/Debug-iphonesimulator -F/Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Products/Debug-iphonesimulator -filelist /Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Intermediates/TownHall\ iPhone.build/Debug-iphonesimulator/TownHall\ iPhone.build/Objects-normal/i386/TownHall\ iPhone.LinkFileList -Xlinker -rpath -Xlinker @executable_path/Frameworks -Xlinker -objc_abi_version -Xlinker 2 -ObjC -lPods-AFNetworking -lPods-Masonry -lPods-SDWebImage -framework CoreGraphics -framework Foundation -framework ImageIO -framework MobileCoreServices -framework Security -framework SystemConfiguration -framework UIKit -fobjc-arc -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=8.1 -lPods -Xlinker -dependency_info -Xlinker /Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Intermediates/TownHall\ iPhone.build/Debug-iphonesimulator/TownHall\ iPhone.build/Objects-normal/i386/TownHall\ iPhone_dependency_info.dat -o /Users/jianglin/Library/Developer/Xcode/DerivedData/TownHall_iPhone-bdlgipvgaapgjhglhromfvcubbxz/Build/Products/Debug-iphonesimulator/TownHall\ iPhone.app/TownHall\ iPhone

Undefined symbols for architecture i386:
  "_main", referenced from:
     implicit entry/start for main executable
     (maybe you meant: _OBJC_IVAR_$_PostTableViewCell._mainTextView, _OBJC_IVAR_$_ConfirmationViewController._mainLabel , _OBJC_IVAR_$_SignInViewController._mainLabel , _OBJC_IVAR_$_SignUpViewController._mainLabel )
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any help would be much appreciated.

Body:
I ran into this after a large upgrade, and was quite annoying to see so many answers across Github advising RN users to start a new project to remedy this issue.

To start, here are the build settings I was mindful of when running into this error and the settings that should be set:

Build Phases for the App Target

Link Binary With Libraries

JavaScriptCore.framework

libPods-app_name.a

Compile Sources

AppDelegate.m

main.m

Build Settings for App Target

Linking OTHER_LDFLAGS

ObjC

lc++

lz

If the settings look fine, but you still receive the error on build, the next step is to check the main file itself.

The Main.m file lives in the ios/app_name folder, and in the file itself, you will find the referenced main method. If there is an issue with this file (missing, broken), you can use the code below to recreate it:

main.m 0.23.1 - 0.62.0 from Upgrade Helper

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#import <UIKit/UIKit.h>

#import "AppDelegate.h"

int main(int argc, char * argv[]) {
  @autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
  }
}

I really hope this helps someone out in the future.


问:
Button not working on mobile website - wordpress
I can't figure out why this button will not work on mobile. I've tried a few different things but can't seem to get it tow work. Everything is fine on desktop but not on mobile (google inspect or actual iPhone). Using Wordpress.

// Starts the sequence from the GO button
function onSubmit() {
  inputHandler();
  findItem(input)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="barItem" style="width: 40px" id="submit" onclick={onSubmit()}>GO</button></code>```

Also Tried this

// Starts the sequence from the GO button
function onSubmit() {
  inputHandler();
  findItem(input);
}

// Starts the sequence when you press enter
document.getElementById('pNum').onkeydown = function(e) {
  if (e.keyCode == 13) {
    onSubmit();
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="barItem" type="submit" onclick={onSubmit()} onsubmit={onSubmit()} value="GO" /></code>```

答: The correct syntax would be onclick="onsubmit()" I believe unless you're using some kind of framework</p>

Body:
I can't figure out why this button will not work on mobile. I've tried a few different things but can't seem to get it tow work. Everything is fine on desktop but not on mobile (google inspect or actual iPhone). Using Wordpress.

// Starts the sequence from the GO button
function onSubmit() {
  inputHandler();
  findItem(input)
}

<button class="barItem" style="width: 40px" id="submit" onclick={onSubmit()}>GO</button>

Also Tried this

// Starts the sequence from the GO button
function onSubmit() {
  inputHandler();
  findItem(input);
}

// Starts the sequence when you press enter
document.getElementById('pNum').onkeydown = function(e) {
  if (e.keyCode == 13) {
    onSubmit();
  }
};

<input class="barItem" type="submit" onclick={onSubmit()} onsubmit={onSubmit()} value="GO" />


问:
Rails Database Query .order GREATEST ignore if NULL or empty
I am trying to filter by a specific user's last activity in a discussion, so if a user made a post or a comment this discussion gets to be the first in their personal list.

Relations:

a Discussion has_many posts.

a Post has_many comments.

a User has_many posts.

a User has_many comments.

a discussion has_many comments through posts.

My query pretty much works but only when both a post and comment from a user exist in a discussion.

How could I adjust my query to look either for the last_created post or last_created comment, meaning in my .order how can I ignore the MAX(comments.created_at) if this is empty and just
use MAX(posts.created_at)

```<code>@discussions = Discussion.
  joins(:posts,:comments).
  where(posts: {user: current_user}).
  where(comments: {user: current_user}).
  group('discussions.id').
  order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')

</code>```

答:
I would start with something like this:

```<code>@discussions = Discussion
  .left_outer_joins(:posts)
  .left_outer_joins(:comments)
  .where("posts.user_id = :id OR comments.user_id = :id", id: current_user.id)
  .group('discussions.id')
  .order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')
</code>```

You will need to use

left_outer_joins otherwise the join would only find Discussion with both a matching post and a matching comment

a where condition with OR because there might be only a post or comment from the current user in the row in after the join

Body:
I am trying to filter by a specific user's last activity in a discussion, so if a user made a post or a comment this discussion gets to be the first in their personal list.

Relations:

a Discussion has_many posts.

a Post has_many comments.

a User has_many posts.

a User has_many comments.

a discussion has_many comments through posts.

My query pretty much works but only when both a post and comment from a user exist in a discussion.

How could I adjust my query to look either for the last_created post or last_created comment, meaning in my .order how can I ignore the MAX(comments.created_at) if this is empty and just
use MAX(posts.created_at)

@discussions = Discussion.
  joins(:posts,:comments).
  where(posts: {user: current_user}).
  where(comments: {user: current_user}).
  group('discussions.id').
  order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')

Body:
I would start with something like this:

@discussions = Discussion
  .left_outer_joins(:posts)
  .left_outer_joins(:comments)
  .where("posts.user_id = :id OR comments.user_id = :id", id: current_user.id)
  .group('discussions.id')
  .order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')

You will need to use

left_outer_joins otherwise the join would only find Discussion with both a matching post and a matching comment

a where condition with OR because there might be only a post or comment from the current user in the row in after the join


问:
Apache PDFBox cannot find class 'Loader'. Why?
I'm using either pdfbox-app-2.0.18.jar or pdfbox-app-2.0.17.jar.

From the example here, I have this code below :

```<code>try (FileOutputStream fos = new FileOutputStream(signedFile);
     PDDocument doc = Loader.loadPDF(inputFile)) {

     // code

}
</code>```

After executing this code, I'm getting this error given below :

```<code>org.apache.pdfbox.Loader is not found
</code>```

How to resolve this issue ?

答:
The Loader class has been added January 25, 2020. SVN log

It's not part of version 2.0.18, as it is not in this file:
pdfbox-2.0.18-src.zip

So this class is simply too new and that's why you cannot use it!

Body:
I'm using either pdfbox-app-2.0.18.jar or pdfbox-app-2.0.17.jar.

From the example here, I have this code below :

try (FileOutputStream fos = new FileOutputStream(signedFile);
     PDDocument doc = Loader.loadPDF(inputFile)) {

     // code

}

After executing this code, I'm getting this error given below :

org.apache.pdfbox.Loader is not found

How to resolve this issue ?


问:
How to stop the ringing of a triggered alarm?
This is MainActivity.java

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

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

import static android.app.PendingIntent.getBroadcast;

public class MainActivity extends AppCompatActivity{

    int nHour1, nHour2, nHour3, nHour4, nMinute1, nMinute2, nMinute3, nMinute4;
    Calendar cal;
    AlarmManager alarmMgr;
    PendingIntent alarmIntent;
    Intent intent;
    Button editButton, infoButton, stopButton, editAlarm1, editAlarm2, editAlarm3, editAlarm4;
    Switch alarmSwitch1, alarmSwitch2, alarmSwitch3, alarmSwitch4;
    TextView alarmText1, alarmText2, alarmText3, alarmText4;

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

        editButton = findViewById(R.id.editButton);
        infoButton = findViewById(R.id.infoButton);
        stopButton = findViewById(R.id.stopButton);
        alarmSwitch1 = findViewById(R.id.alarmSwitch1);
        alarmSwitch2 = findViewById(R.id.alarmSwitch2);
        alarmSwitch3 = findViewById(R.id.alarmSwitch3);
        alarmSwitch4 = findViewById(R.id.alarmSwitch4);
        alarmText1 = findViewById(R.id.alarmText1);
        alarmText2 = findViewById(R.id.alarmText2);
        alarmText3 = findViewById(R.id.alarmText3);
        alarmText4 = findViewById(R.id.alarmText4);
        editAlarm1 = findViewById(R.id.editAlarm1);
        editAlarm2 = findViewById(R.id.editAlarm2);
        editAlarm3 = findViewById(R.id.editAlarm3);
        editAlarm4 = findViewById(R.id.editAlarm4);

        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopRinging(1);
            }
        });
        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editAlarm1.getVisibility() == View.VISIBLE) {
                    editAlarm1.setVisibility(View.INVISIBLE);
                    editAlarm2.setVisibility(View.INVISIBLE);
                    editAlarm3.setVisibility(View.INVISIBLE);
                    editAlarm4.setVisibility(View.INVISIBLE);
                    editButton.setText("EDIT");
                } else {
                    editAlarm1.setVisibility(View.VISIBLE);
                    editAlarm2.setVisibility(View.VISIBLE);
                    editAlarm3.setVisibility(View.VISIBLE);
                    editAlarm4.setVisibility(View.VISIBLE);
                    editButton.setText("DONE");
                }
            }
        });

        infoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openDialog();
            }
        });

        alarmSwitch1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch1.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 1 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(1, nHour1, nMinute1);
                    editAlarm1.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 1 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(1);
                    editAlarm1.setClickable(true);
                }
            }
        });

        alarmSwitch2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch2.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 2 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(2, nHour2, nMinute2);
                    editAlarm2.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 2 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(2);
                    editAlarm2.setClickable(true);
                }
            }
        });

        alarmSwitch3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch3.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 3 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(3, nHour3, nMinute3);
                    editAlarm3.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 3 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(3);
                    editAlarm3.setClickable(true);
                }
            }
        });

        alarmSwitch4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch4.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 4 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(4, nHour4, nMinute4);
                    editAlarm4.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 4 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(4);
                    editAlarm4.setClickable(true);
                }
            }
        });
    }

    public void setTime1(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour1 = hourOfDay;
                nMinute1 = minute;
                updateAlarmText(nHour1, nMinute1, alarmText1);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();
    }

    public void setTime2(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour2 = hourOfDay;
                nMinute2 = minute;
                updateAlarmText(nHour2, nMinute2, alarmText2);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();
    }

    public void setTime3(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour3 = hourOfDay;
                nMinute3 = minute;
                updateAlarmText(nHour3, nMinute3, alarmText3);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();
    }

    public void setTime4(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour4 = hourOfDay;
                nMinute4 = minute;
                updateAlarmText(nHour4, nMinute4, alarmText4);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();

    }

    public void startAlarm(int requestCode, int nHour, int nMinute) {
        intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = getBroadcast(this.getApplicationContext(), requestCode, intent, 0);
        alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
        cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, nHour);
        cal.set(Calendar.MINUTE, nMinute);
        cal.set(Calendar.SECOND, 0);

        if (cal.before(Calendar.getInstance())){
            cal.add(Calendar.DATE, 1);
        }

        assert alarmMgr != null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            alarmMgr.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), alarmIntent);
        } else {
            alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), alarmIntent);
        }
    }

    public void cancelAlarm(int requestCode) {
        intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(this.getApplicationContext(), requestCode, intent, 0);
        alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);

        assert alarmMgr != null;
        alarmMgr.cancel(alarmIntent);
    }
    public void stopRinging(int requestCode){
        intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(this.getApplicationContext(), requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    public void openDialog(){
        Dialog dialog = new Dialog();
        dialog.show(getSupportFragmentManager(), "dialog");
    }

    public void updateAlarmText (int nHour, int nMinute, TextView alarmText) {
        String timeTextHour = "";
        String timeTextMinute = "";
        if (nHour == 0){
            timeTextHour = "12";
        }
        if (nHour <= 12 && nHour != 0) {
            timeTextHour = String.valueOf(nHour);
        }
        if (nHour > 12) {
            timeTextHour = String.valueOf(nHour - 12);
        }
        if (nMinute < 10) {
            timeTextMinute += "0" + nMinute;
        } else {
            timeTextMinute = String.valueOf(nMinute);
        }
        if (nHour < 12){
            alarmText.setText(timeTextHour + ":" + timeTextMinute + " AM");
        } else {
            alarmText.setText(timeTextHour + ":" + timeTextMinute + " PM");
        }
    }
}
</code>```

This is AlarmReceiver.java

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

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        Ringtone r = RingtoneManager.getRingtone(context, alarmUri);
        if (r.isPlaying()) {
            r.stop();
        } else {
            r.play();
        }
    }
}
</code>```

This is AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.quizalarm">

    <application
        android:fullBackupContent="@xml/backup_descriptor"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".QuizActivity"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".AlarmReceiver" />
    </application>

</manifest>
</code>```

My problem is in the stopRinging() method. I don't know how to stop the ringing of the triggered alarm. I tried recalling the AlarmReceiver in the stopRinging() method so that it will do r.stop() but it doesn't work, it's still ringing. What is the right way to stop the ringing?

答:
Did you see this reply</p>

```<code> public void setAlarm(Context context)
    {
        AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, Alarm.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
    }

    public void cancelAlarm(Context context)
    {
        Intent intent = new Intent(context, Alarm.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }
</code>```

Body:
This is MainActivity.java

package com.example.quizalarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

import static android.app.PendingIntent.getBroadcast;

public class MainActivity extends AppCompatActivity{

    int nHour1, nHour2, nHour3, nHour4, nMinute1, nMinute2, nMinute3, nMinute4;
    Calendar cal;
    AlarmManager alarmMgr;
    PendingIntent alarmIntent;
    Intent intent;
    Button editButton, infoButton, stopButton, editAlarm1, editAlarm2, editAlarm3, editAlarm4;
    Switch alarmSwitch1, alarmSwitch2, alarmSwitch3, alarmSwitch4;
    TextView alarmText1, alarmText2, alarmText3, alarmText4;

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

        editButton = findViewById(R.id.editButton);
        infoButton = findViewById(R.id.infoButton);
        stopButton = findViewById(R.id.stopButton);
        alarmSwitch1 = findViewById(R.id.alarmSwitch1);
        alarmSwitch2 = findViewById(R.id.alarmSwitch2);
        alarmSwitch3 = findViewById(R.id.alarmSwitch3);
        alarmSwitch4 = findViewById(R.id.alarmSwitch4);
        alarmText1 = findViewById(R.id.alarmText1);
        alarmText2 = findViewById(R.id.alarmText2);
        alarmText3 = findViewById(R.id.alarmText3);
        alarmText4 = findViewById(R.id.alarmText4);
        editAlarm1 = findViewById(R.id.editAlarm1);
        editAlarm2 = findViewById(R.id.editAlarm2);
        editAlarm3 = findViewById(R.id.editAlarm3);
        editAlarm4 = findViewById(R.id.editAlarm4);

        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopRinging(1);
            }
        });
        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editAlarm1.getVisibility() == View.VISIBLE) {
                    editAlarm1.setVisibility(View.INVISIBLE);
                    editAlarm2.setVisibility(View.INVISIBLE);
                    editAlarm3.setVisibility(View.INVISIBLE);
                    editAlarm4.setVisibility(View.INVISIBLE);
                    editButton.setText("EDIT");
                } else {
                    editAlarm1.setVisibility(View.VISIBLE);
                    editAlarm2.setVisibility(View.VISIBLE);
                    editAlarm3.setVisibility(View.VISIBLE);
                    editAlarm4.setVisibility(View.VISIBLE);
                    editButton.setText("DONE");
                }
            }
        });

        infoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openDialog();
            }
        });

        alarmSwitch1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch1.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 1 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(1, nHour1, nMinute1);
                    editAlarm1.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 1 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(1);
                    editAlarm1.setClickable(true);
                }
            }
        });

        alarmSwitch2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch2.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 2 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(2, nHour2, nMinute2);
                    editAlarm2.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 2 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(2);
                    editAlarm2.setClickable(true);
                }
            }
        });

        alarmSwitch3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch3.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 3 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(3, nHour3, nMinute3);
                    editAlarm3.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 3 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(3);
                    editAlarm3.setClickable(true);
                }
            }
        });

        alarmSwitch4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmSwitch4.isChecked()) {
                    Toast.makeText(MainActivity.this, "Alarm 4 Activated", Toast.LENGTH_SHORT).show();
                    startAlarm(4, nHour4, nMinute4);
                    editAlarm4.setClickable(false);
                } else {
                    Toast.makeText(MainActivity.this, "Alarm 4 Deactivated", Toast.LENGTH_SHORT).show();
                    cancelAlarm(4);
                    editAlarm4.setClickable(true);
                }
            }
        });
    }

    public void setTime1(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour1 = hourOfDay;
                nMinute1 = minute;
                updateAlarmText(nHour1, nMinute1, alarmText1);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();
    }

    public void setTime2(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour2 = hourOfDay;
                nMinute2 = minute;
                updateAlarmText(nHour2, nMinute2, alarmText2);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();
    }

    public void setTime3(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour3 = hourOfDay;
                nMinute3 = minute;
                updateAlarmText(nHour3, nMinute3, alarmText3);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();
    }

    public void setTime4(View v) {
        cal = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                nHour4 = hourOfDay;
                nMinute4 = minute;
                updateAlarmText(nHour4, nMinute4, alarmText4);
            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), DateFormat.is24HourFormat(getApplication()));
        timePickerDialog.show();

    }

    public void startAlarm(int requestCode, int nHour, int nMinute) {
        intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = getBroadcast(this.getApplicationContext(), requestCode, intent, 0);
        alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
        cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, nHour);
        cal.set(Calendar.MINUTE, nMinute);
        cal.set(Calendar.SECOND, 0);

        if (cal.before(Calendar.getInstance())){
            cal.add(Calendar.DATE, 1);
        }

        assert alarmMgr != null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            alarmMgr.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), alarmIntent);
        } else {
            alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), alarmIntent);
        }
    }

    public void cancelAlarm(int requestCode) {
        intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(this.getApplicationContext(), requestCode, intent, 0);
        alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);

        assert alarmMgr != null;
        alarmMgr.cancel(alarmIntent);
    }
    public void stopRinging(int requestCode){
        intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(this.getApplicationContext(), requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    public void openDialog(){
        Dialog dialog = new Dialog();
        dialog.show(getSupportFragmentManager(), "dialog");
    }

    public void updateAlarmText (int nHour, int nMinute, TextView alarmText) {
        String timeTextHour = "";
        String timeTextMinute = "";
        if (nHour == 0){
            timeTextHour = "12";
        }
        if (nHour <= 12 && nHour != 0) {
            timeTextHour = String.valueOf(nHour);
        }
        if (nHour > 12) {
            timeTextHour = String.valueOf(nHour - 12);
        }
        if (nMinute < 10) {
            timeTextMinute += "0" + nMinute;
        } else {
            timeTextMinute = String.valueOf(nMinute);
        }
        if (nHour < 12){
            alarmText.setText(timeTextHour + ":" + timeTextMinute + " AM");
        } else {
            alarmText.setText(timeTextHour + ":" + timeTextMinute + " PM");
        }
    }
}

This is AlarmReceiver.java

package com.example.quizalarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        Ringtone r = RingtoneManager.getRingtone(context, alarmUri);
        if (r.isPlaying()) {
            r.stop();
        } else {
            r.play();
        }
    }
}

This is AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.quizalarm">

    <application
        android:fullBackupContent="@xml/backup_descriptor"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".QuizActivity"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".AlarmReceiver" />
    </application>

</manifest>

My problem is in the stopRinging() method. I don't know how to stop the ringing of the triggered alarm. I tried recalling the AlarmReceiver in the stopRinging() method so that it will do r.stop() but it doesn't work, it's still ringing. What is the right way to stop the ringing?

Body:
Did you see this reply

 public void setAlarm(Context context)
    {
        AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, Alarm.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
    }

    public void cancelAlarm(Context context)
    {
        Intent intent = new Intent(context, Alarm.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }