问:
How to create timed Instagram story loading bar using Jetpack Compose animation?
I would like to create a composable component very similar to Instagram story loading bar with 10 seconds of duration.

I had an idea how to do it but I'm not how to executed. I was thinking about adding a static bar (grey color) using a BOX and then add another bar (white color) which animates from 0 to final of composable width in 10 seconds.

Do you have any idea how I can implement this component?

答:
This is can be a full sample solution you can see and try to extend as well as refactor. The code is self-explanatory and you will see how it goes.

A story composable:

```<code>@OptIn(ExperimentalAnimationApi::class)
@Composable
fun Story(story: Stories) {
    AnimatedContent(story) {
        when (story) {
            Stories.ONE -> {
                StoryContent("1")
            }
            Stories.TWO -> {
                StoryContent("2")
            }
            Stories.THREE -> {
                StoryContent("3")
            }
        }
    }
}

@Composable
private fun StoryContent(content: String) {
    Text("Story $content")
}
</code>```

Story progress indicator:

```<code>@Composable
fun StoryProgressIndicator(running: Boolean, modifier: Modifier = Modifier, onTenSecondsOnThisStory: () -> Unit) {
    val progress: Float by animateFloatAsState(
        if (running) 1f else 0f,
        animationSpec = tween(
            durationMillis = if (running) 10_000 else 0,
            easing = LinearEasing
        )
    )
    if (progress == 1f) {
        onTenSecondsOnThisStory()
    }
    LinearProgressIndicator(
        progress, modifier
    )
}
</code>```

And a screen that contains the navigation among stories and playing the animation.

```<code>@OptIn(ExperimentalAnimationApi::class)
@Composable
fun InstagramLikeStories() {
    var screenWidth by remember { mutableStateOf(1) }
    var currentStory by remember { mutableStateOf(Stories.ONE) }
    var currentStoryPointer by remember { mutableStateOf(0) }
    var runningStoryOne by remember { mutableStateOf(false) }
    var runningStoryTwo by remember { mutableStateOf(false) }
    var runningStoryThree by remember { mutableStateOf(false) }

    val runStoryOne = { runningStoryOne = true; runningStoryTwo = false; runningStoryThree = false }
    val runStoryTwo = { runningStoryOne = false; runningStoryTwo = true; runningStoryThree = false }
    val runStoryThree = { runningStoryOne = false; runningStoryTwo = false; runningStoryThree = true }

    val stories = Stories.values()

    LaunchedEffect(Unit) { runStoryOne() }

    Column(
        Modifier.fillMaxSize().onGloballyPositioned {
            screenWidth = it.size.width
        }.pointerInput(Unit) {
            detectTapGestures(onTap = {
                if ((it.x / screenWidth) * 100 > 50) {
                    if (currentStoryPointer == stories.size - 1) {
                        currentStoryPointer = 0
                    } else {
                        currentStoryPointer++
                    }
                    currentStory = stories[currentStoryPointer]
                } else {
                    if (currentStoryPointer != 0) {
                        currentStoryPointer--
                        currentStory = stories[currentStoryPointer]
                    }
                }
                runStoryIndicator(currentStory, runStoryOne, runStoryTwo, runStoryThree)
            })
        }
    ) {

        Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) {
            StoryProgressIndicator(runningStoryOne, Modifier.weight(1f), onTenSecondsOnThisStory = {
                runStoryIndicator(currentStory, runStoryOne, runStoryTwo, runStoryThree)
                currentStoryPointer = 1
                currentStory = stories[currentStoryPointer]
            })
            Spacer(Modifier.weight(0.1f))
            StoryProgressIndicator(runningStoryTwo, Modifier.weight(1f), onTenSecondsOnThisStory = {
                runStoryIndicator(currentStory, runStoryOne, runStoryTwo, runStoryThree)
                currentStoryPointer = 2
                currentStory = stories[currentStoryPointer]
            })
            Spacer(Modifier.weight(0.1f))
            StoryProgressIndicator(runningStoryThree, Modifier.weight(1f), onTenSecondsOnThisStory = {
                runStoryIndicator(currentStory, runStoryOne, runStoryTwo, runStoryThree)
                // go to first one
                currentStoryPointer = 0
                currentStory = stories[currentStoryPointer]
            })
        }
    }
    Story(currentStory)
    Row {
        Button(onClick = {
        }) {
           Text("button")
        }
    }
}

private fun runStoryIndicator(
    currentStory: Stories,
    runStoryOne: () -> Unit,
    runStoryTwo: () -> Unit,
    runStoryThree: () -> Unit
) {
    when (currentStory) {
        Stories.ONE -> runStoryOne()
        Stories.TWO -> runStoryTwo()
        Stories.THREE -> runStoryThree()
    }
}

enum class Stories {
    ONE, TWO, THREE
}
</code>```

Body:
This is can be a full sample solution you can see and try to extend as well as refactor. The code is self-explanatory and you will see how it goes.

A story composable:

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun Story(story: Stories) {
    AnimatedContent(story) {
        when (story) {
            Stories.ONE -> {
                StoryContent("1")
            }
            Stories.TWO -> {
                StoryContent("2")
            }
            Stories.THREE -> {
                StoryContent("3")
            }
        }
    }
}

@Composable
private fun StoryContent(content: String) {
    Text("Story $content")
}

Story progress indicator:

@Composable
fun StoryProgressIndicator(running: Boolean, modifier: Modifier = Modifier, onTenSecondsOnThisStory: () -> Unit) {
    val progress: Float by animateFloatAsState(
        if (running) 1f else 0f,
        animationSpec = tween(
            durationMillis = if (running) 10_000 else 0,
            easing = LinearEasing
        )
    )
    if (progress == 1f) {
        onTenSecondsOnThisStory()
    }
    LinearProgressIndicator(
        progress, modifier
    )
}

And a screen that contains the navigation among stories and playing the animation.

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun InstagramLikeStories() {
    var screenWidth by remember { mutableStateOf(1) }
    var currentStory by remember { mutableStateOf(Stories.ONE) }
    var currentStoryPointer by remember { mutableStateOf(0) }
    var runningStoryOne by remember { mutableStateOf(false) }
    var runningStoryTwo by remember { mutableStateOf(false) }
    var runningStoryThree by remember { mutableStateOf(false) }

    val runStoryOne = { runningStoryOne = true; runningStoryTwo = false; runningStoryThree = false }
    val runStoryTwo = { runningStoryOne = false; runningStoryTwo = true; runningStoryThree = false }
    val runStoryThree = { runningStoryOne = false; runningStoryTwo = false; runningStoryThree = true }

    val stories = Stories.values()

    LaunchedEffect(Unit) { runStoryOne() }

    Column(
        Modifier.fillMaxSize().onGloballyPositioned {
            screenWidth = it.size.width
        }.pointerInput(Unit) {
            detectTapGestures(onTap = {
                if ((it.x / screenWidth) * 100 > 50) {
                    if (currentStoryPointer == stories.size - 1) {
                        currentStoryPointer = 0
                    } else {
                        currentStoryPointer++
                    }
                    currentStory = stories[currentStoryPointer]
                } else {
                    if (currentStoryPointer != 0) {
                        currentStoryPointer--
                        currentStory = stories[currentStoryPointer]
                    }
                }
                runStoryIndicator(currentStory, runStoryOne, runStoryTwo, runStoryThree)
            })
        }
    ) {

        Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) {
            StoryProgressIndicator(runningStoryOne, Modifier.weight(1f), onTenSecondsOnThisStory = {
                runStoryIndicator(currentStory, runStoryOne, runStoryTwo, runStoryThree)
                currentStoryPointer = 1
                currentStory = stories[currentStoryPointer]
            })
            Spacer(Modifier.weight(0.1f))
            StoryProgressIndicator(runningStoryTwo, Modifier.weight(1f), onTenSecondsOnThisStory = {
                runStoryIndicator(currentStory, runStoryOne, runStoryTwo, runStoryThree)
                currentStoryPointer = 2
                currentStory = stories[currentStoryPointer]
            })
            Spacer(Modifier.weight(0.1f))
            StoryProgressIndicator(runningStoryThree, Modifier.weight(1f), onTenSecondsOnThisStory = {
                runStoryIndicator(currentStory, runStoryOne, runStoryTwo, runStoryThree)
                // go to first one
                currentStoryPointer = 0
                currentStory = stories[currentStoryPointer]
            })
        }
    }
    Story(currentStory)
    Row {
        Button(onClick = {
        }) {
           Text("button")
        }
    }
}

private fun runStoryIndicator(
    currentStory: Stories,
    runStoryOne: () -> Unit,
    runStoryTwo: () -> Unit,
    runStoryThree: () -> Unit
) {
    when (currentStory) {
        Stories.ONE -> runStoryOne()
        Stories.TWO -> runStoryTwo()
        Stories.THREE -> runStoryThree()
    }
}

enum class Stories {
    ONE, TWO, THREE
}


来源: stackexchange

问:
Wrapper for pointer to either constant or dynamic data (in C++11)
```<code>struct Item
{
    Item() = default;
    Item(int x, const char* s) : n{x}, text{s} {}

    int n{};
    const char* text;
};

static const size_t someSize = 2;
static const Item someItems[someSize] = {
    {0, "Some constant item"},
    {1, "Another constant item"}
};

class Foo
{
    void addArray(Item* a, size_t s) { itemArrays.emplace_back(a, s); }
    std::vector<std::pair<Item*, size_t>> itemArraysWithTheirSize{};
}

int main()
{
   size_t someCalculatedSize = 10; /* Not known compile-time */
   Item* someOtherItems = new Item[someCalculatedSize]{
      {0, "I'm only initializing"},
      {1, "The first two items"},
   }
   for (int i = 2; i < someCalculatedSize; i++)
   {
      someOtherItems[i] = {i, "Initialized later on"};
   }

   Foo foo;
   foo.addArray(someItems, someSize);
   foo.addArray(someOtherItems, someCalculatedSize);

   for (std::pair<const Item*, size_t>& a : foo.itemArraysWithTheirSize)
   {
      for (size_t i = 0; i < a.second; i++)
      {
         printf("%i %s\n", a.first[i].n, a.first[i].text);
      }
      printf("\n");
   }
}
</code>```

Link to code: https://godbolt.org/z/b4M5Kjhh9

I want to be able to rewrite Foo so that I don't need to explicitly know the size everywhere.

My guess is I'd need a wrapper for Item* that I can initialize in the two ways shown in the code: with constant data (on the stack) and with dynamic data (on the heap). The first being much more common. Therefore, simply using std::vector for everything doesn't seem like a good solution to me.

A few requirements for this wrapper:

It can contain either type of data

The pointer to the data doesn't change

It contains both the capacity and the current filling of the array

In the case of static data, it infers its size from the constructor argument (an initializer list if possible)

So basically, how do I get this code to work (https://godbolt.org/z/fqEhYxTGz)

```<code>struct Item
{
    Item() = default;
    Item(int x, const char* s) : n{x}, text{s} {}

    int n{};
    const char* text;
};

struct ItemWrapper
{
    /* What do these constructors look like? */

    Item* array;
    size_t current_length;
    const size_t max_length;
};

static const ItemWrapper someItems = {
    {0, "Some constant item"},
    {1, "Another constant item"}
};

class Foo
{
public:
    void addWrapper(ItemWrapper* w) { itemwrappers.push_back(w); }
    std::vector<ItemWrapper*> itemwrappers{};
};

int main()
{
    /* Either one of these constructors would be fine */

    ItemWrapper someOtherItems = {
        {{0, "I'm only initializing"},
         {1, "The first two items"}},
        10}; // Infer the current length, which is 2

    ItemWrapper someOtherItems{10}; // Maximum length as argument
    someOtherItems.add({0, "I'm only initializing"});
    someOtherItems.add({1, "The first two items"});

    Foo foo;
    foo.addWrapper(someItems);
    foo.addWrapper(someOtherItems);

    for (ItemWrapper* w : foo.itemwrappers)
    {
        for (size_t i = 0; i < w->current_length; i++)
        {
            printf("%i %s\n", w->array[i].n, w->array[i].text);
        }
        printf("\n");
    }
}
</code>```

答:
As I understand, you want a function which takes a C-array and deduces its size, so you might do:

```<code>class Foo
{
public:
    void addArray(const Item* a, size_t s)
    {
        itemArraysWithTheirSize.emplace_back(a, s);
    }

    template <std::size_t N>
    void addArray(const Item (&a)[N]) { addArray(a, N); }

    std::vector<std::pair<const Item*, size_t>> itemArraysWithTheirSize{};
};
</code>```

Demo

ContentLicense: CC BY-SA 4.0

Body:
struct Item
{
    Item() = default;
    Item(int x, const char* s) : n{x}, text{s} {}

    int n{};
    const char* text;
};

static const size_t someSize = 2;
static const Item someItems[someSize] = {
    {0, "Some constant item"},
    {1, "Another constant item"}
};

class Foo
{
    void addArray(Item* a, size_t s) { itemArrays.emplace_back(a, s); }
    std::vector<std::pair<Item*, size_t>> itemArraysWithTheirSize{};
}

int main()
{
   size_t someCalculatedSize = 10; /* Not known compile-time */
   Item* someOtherItems = new Item[someCalculatedSize]{
      {0, "I'm only initializing"},
      {1, "The first two items"},
   }
   for (int i = 2; i < someCalculatedSize; i++)
   {
      someOtherItems[i] = {i, "Initialized later on"};
   }

   Foo foo;
   foo.addArray(someItems, someSize);
   foo.addArray(someOtherItems, someCalculatedSize);

   for (std::pair<const Item*, size_t>& a : foo.itemArraysWithTheirSize)
   {
      for (size_t i = 0; i < a.second; i++)
      {
         printf("%i %s\n", a.first[i].n, a.first[i].text);
      }
      printf("\n");
   }
}

Link to code: https://godbolt.org/z/b4M5Kjhh9

I want to be able to rewrite Foo so that I don't need to explicitly know the size everywhere.

My guess is I'd need a wrapper for Item* that I can initialize in the two ways shown in the code: with constant data (on the stack) and with dynamic data (on the heap). The first being much more common. Therefore, simply using std::vector for everything doesn't seem like a good solution to me.

A few requirements for this wrapper:

It can contain either type of data

The pointer to the data doesn't change

It contains both the capacity and the current filling of the array

In the case of static data, it infers its size from the constructor argument (an initializer list if possible)

So basically, how do I get this code to work (https://godbolt.org/z/fqEhYxTGz)

struct Item
{
    Item() = default;
    Item(int x, const char* s) : n{x}, text{s} {}

    int n{};
    const char* text;
};

struct ItemWrapper
{
    /* What do these constructors look like? */

    Item* array;
    size_t current_length;
    const size_t max_length;
};

static const ItemWrapper someItems = {
    {0, "Some constant item"},
    {1, "Another constant item"}
};

class Foo
{
public:
    void addWrapper(ItemWrapper* w) { itemwrappers.push_back(w); }
    std::vector<ItemWrapper*> itemwrappers{};
};

int main()
{
    /* Either one of these constructors would be fine */

    ItemWrapper someOtherItems = {
        {{0, "I'm only initializing"},
         {1, "The first two items"}},
        10}; // Infer the current length, which is 2

    ItemWrapper someOtherItems{10}; // Maximum length as argument
    someOtherItems.add({0, "I'm only initializing"});
    someOtherItems.add({1, "The first two items"});

    Foo foo;
    foo.addWrapper(someItems);
    foo.addWrapper(someOtherItems);

    for (ItemWrapper* w : foo.itemwrappers)
    {
        for (size_t i = 0; i < w->current_length; i++)
        {
            printf("%i %s\n", w->array[i].n, w->array[i].text);
        }
        printf("\n");
    }
}

Body:
As I understand, you want a function which takes a C-array and deduces its size, so you might do:

class Foo
{
public:
    void addArray(const Item* a, size_t s)
    {
        itemArraysWithTheirSize.emplace_back(a, s);
    }

    template <std::size_t N>
    void addArray(const Item (&a)[N]) { addArray(a, N); }

    std::vector<std::pair<const Item*, size_t>> itemArraysWithTheirSize{};
};

Demo


问:
not able to transfer all valuesof particular selected row in datagrid view to another form
I have done like this for sending gridview row values from one form to another

i have datagrid view with columns productdescription , productimage , productname

my main aim is if, i select the image cell in datagridview the selected image and the values of row which row has that image need to send to another form ...

in the below code only image will be transferred to another form i need to send another values also ...

i have searched a lot but i didnot find any solution.. and the code is given below....

```<code>      private void productGridview_Cellclick(object sender, DataGridViewCellEventArgs e)
      {
        byte[] bits = null;
        Image img = null;

            if (e.ColumnIndex != productgridview.Columns["productimage"].Index) return;

            if (productgridview.SelectedCells.Count == 0) return;

            bits = (byte[])productgridview.SelectedCells[0].Value;
            img = bytearraytoimage(bits);

            if (img is Image)
            {
                using (ProductDescriptionForm pf = new ProductDescriptionForm())
                {
                    pf.picture = img;

                    pf.ShowDialog(this);
                }
            }

    }
</code>```

and in productdescription form i have defined like this ...

```<code>   public partial class ProductDescriptionForm : Form
   {
     public ProductDescriptionForm()
    {
        InitializeComponent();
    }

    public Image picture
    {
        get { return pictureBox1.Image; }
        set { pictureBox1.Image = value; }
    }

}
</code>```

how do i transfer other values in the same row  that has the image to another form

I am using winforms....

many thanks in advance....

do i need to change the cell click event to row click event ?????

if so , how do i check the particular cell with image in datagridview

would any suggestions any bit of code would be helpful to me

答:
This doesn't sound from object orientated but hey;

@marshal thanq for ur help i got the answer ..see my answer int selectedrowindex= productgridview.SelectedCells[0].RowIndex; DataGridViewRow selectedRow = productgridview.Rows[selectedrowindex]; string desc = Convert.ToString(selectedRow.Cells["productdescr"].Value); by using above statements i got the values and I transferred to another form... – user852714

ContentLicense: CC BY-SA 3.0

Body:
I have done like this for sending gridview row values from one form to another

i have datagrid view with columns productdescription , productimage , productname

my main aim is if, i select the image cell in datagridview the selected image and the values of row which row has that image need to send to another form ...

in the below code only image will be transferred to another form i need to send another values also ...

i have searched a lot but i didnot find any solution.. and the code is given below....

      private void productGridview_Cellclick(object sender, DataGridViewCellEventArgs e)
      {
        byte[] bits = null;
        Image img = null;

            if (e.ColumnIndex != productgridview.Columns["productimage"].Index) return;

            if (productgridview.SelectedCells.Count == 0) return;

            bits = (byte[])productgridview.SelectedCells[0].Value;
            img = bytearraytoimage(bits);

            if (img is Image)
            {
                using (ProductDescriptionForm pf = new ProductDescriptionForm())
                {
                    pf.picture = img;

                    pf.ShowDialog(this);
                }
            }

    }

and in productdescription form i have defined like this ...

   public partial class ProductDescriptionForm : Form
   {
     public ProductDescriptionForm()
    {
        InitializeComponent();
    }

    public Image picture
    {
        get { return pictureBox1.Image; }
        set { pictureBox1.Image = value; }
    }

}

how do i transfer other values in the same row  that has the image to another form

I am using winforms....

many thanks in advance....

do i need to change the cell click event to row click event ?????

if so , how do i check the particular cell with image in datagridview

would any suggestions any bit of code would be helpful to me


问:
Does a condition variable really need another variable?
Note: I'll give examples in C++ but I believe my question is language-agnostic. Correct me if I'm wrong.

Just so you really understand me - what I'm trying to learn here is what the tool does and nothing else. Not what it's usually used for, not what the conventions says, just what the blunt tool does. In this case - what the condition variable does.

So far it seems to me like it's a simple mechanism that allows threads to wait (block) until some other thread signals them (unblocks them). Nothing more, no dealing with critical section access or data access (of course they can be used for that but it's only a matter of programmer's choice). Also the signaling is usually only done when something important happens (e.g. data was loaded) but theoretically it could be called at any time. Correct so far?

Now, every example that I have seen uses a condition variable object (e.g. std::condition_variable) but also some additional variable to mark if something happened (e.g. bool dataWasLoaded). Take a look at this example from https://thispointer.com//c11-multithreading-part-7-condition-variables-explained/:

```<code>#include <iostream>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
using namespace std::placeholders;
class Application
{
    std::mutex m_mutex;
    std::condition_variable m_condVar;
    bool m_bDataLoaded;
public:
    Application()
    {
        m_bDataLoaded = false;
    }
    void loadData()
    {
        // Make This Thread sleep for 1 Second
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout << "Loading Data from XML" << std::endl;
        // Lock The Data structure
        std::lock_guard<std::mutex> guard(m_mutex);
        // Set the flag to true, means data is loaded
        m_bDataLoaded = true;
        // Notify the condition variable
        m_condVar.notify_one();
    }
    bool isDataLoaded()
    {
        return m_bDataLoaded;
    }
    void mainTask()
    {
        std::cout << "Do Some Handshaking" << std::endl;
        // Acquire the lock
        std::unique_lock<std::mutex> mlock(m_mutex);
        // Start waiting for the Condition Variable to get signaled
        // Wait() will internally release the lock and make the thread to block
        // As soon as condition variable get signaled, resume the thread and
        // again acquire the lock. Then check if condition is met or not
        // If condition is met then continue else again go in wait.
        m_condVar.wait(mlock, std::bind(&Application::isDataLoaded, this));
        std::cout << "Do Processing On loaded Data" << std::endl;
    }
};
int main()
{
    Application app;
    std::thread thread_1(&Application::mainTask, &app);
    std::thread thread_2(&Application::loadData, &app);
    thread_2.join();
    thread_1.join();
    return 0;
}
</code>```

Now, other than the std::condition_variable m_condVar it also uses an additional variable bool m_bDataLoaded. But it seems to me that the thread performing mainTask is already notified that the data was loaded by means of std::condition_variable m_condVar. Why also check bool m_bDataLoaded for the same information? Compare (the same code without bool m_bDataLoaded):

```<code>#include <iostream>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
using namespace std::placeholders;
class Application
{
    std::mutex m_mutex;
    std::condition_variable m_condVar;
public:
    Application()
    {
    }
    void loadData()
    {
        // Make This Thread sleep for 1 Second
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout << "Loading Data from XML" << std::endl;
        // Lock The Data structure
        std::lock_guard<std::mutex> guard(m_mutex);
        // Notify the condition variable
        m_condVar.notify_one();
    }
    void mainTask()
    {
        std::cout << "Do Some Handshaking" << std::endl;
        // Acquire the lock
        std::unique_lock<std::mutex> mlock(m_mutex);
        // Start waiting for the Condition Variable to get signaled
        // Wait() will internally release the lock and make the thread to block
        // As soon as condition variable get signaled, resume the thread and
        // again acquire the lock. Then check if condition is met or not
        // If condition is met then continue else again go in wait.
        m_condVar.wait(mlock);
        std::cout << "Do Processing On loaded Data" << std::endl;
    }
};
int main()
{
    Application app;
    std::thread thread_1(&Application::mainTask, &app);
    std::thread thread_2(&Application::loadData, &app);
    thread_2.join();
    thread_1.join();
    return 0;
}
</code>```

Now I know about spurious wakeups and they alone necessitate the usage of an additional variable. My question is - are they they only reason for it? If they didn't occur could one just use condition variables without any additional variables (and btw wouldn't that make the name "condition variable" a misnomer then)?

Another thing is - isn't the usage of additional variables the only reason why condition variables also require a mutex? If not, what are the other reasons?

If additional variables are necessary (for spurious wakeups or other reasons) why doesn't the API require them (in the 2nd code I didn't have to use them for the code to compile)? (I don't know if it's the same in other languages, so this question might be C++-specific.)

答:
Yes, the condition variable is just useful to wait for an event. In my point of view you should not try to use it for controlling concurrent access of critical data structures.

I just can speak about C++. As you see in the example here https://en.cppreference.com/w/cpp/thread/condition_variable/wait, they used this expression cv.wait(lk, []{return i == 1;});. And []{...} is the expression of a nameless function. So you can also write your own function and give the name of the function:

bool condFn()
{
    std::cout << "condFn" << std::endl; // debug output ;)
    return i == 1;
}

void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cerr << "Waiting... \n";
    cv.wait(lk, condFn);
    std::cerr << "...finished waiting. i == 1\n";
}
```

And inside this function you can evaluate, whatever you want. The thread is always sleeping until it gets notified, then it processes always the function that evaluates the condition for continue working. In case of true, the thread continues, in case of false the programm goes sleeping again.

Body:
Note: I'll give examples in C++ but I believe my question is language-agnostic. Correct me if I'm wrong.

Just so you really understand me - what I'm trying to learn here is what the tool does and nothing else. Not what it's usually used for, not what the conventions says, just what the blunt tool does. In this case - what the condition variable does.

So far it seems to me like it's a simple mechanism that allows threads to wait (block) until some other thread signals them (unblocks them). Nothing more, no dealing with critical section access or data access (of course they can be used for that but it's only a matter of programmer's choice). Also the signaling is usually only done when something important happens (e.g. data was loaded) but theoretically it could be called at any time. Correct so far?

Now, every example that I have seen uses a condition variable object (e.g. std::condition_variable) but also some additional variable to mark if something happened (e.g. bool dataWasLoaded). Take a look at this example from https://thispointer.com//c11-multithreading-part-7-condition-variables-explained/:

#include <iostream>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
using namespace std::placeholders;
class Application
{
    std::mutex m_mutex;
    std::condition_variable m_condVar;
    bool m_bDataLoaded;
public:
    Application()
    {
        m_bDataLoaded = false;
    }
    void loadData()
    {
        // Make This Thread sleep for 1 Second
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout << "Loading Data from XML" << std::endl;
        // Lock The Data structure
        std::lock_guard<std::mutex> guard(m_mutex);
        // Set the flag to true, means data is loaded
        m_bDataLoaded = true;
        // Notify the condition variable
        m_condVar.notify_one();
    }
    bool isDataLoaded()
    {
        return m_bDataLoaded;
    }
    void mainTask()
    {
        std::cout << "Do Some Handshaking" << std::endl;
        // Acquire the lock
        std::unique_lock<std::mutex> mlock(m_mutex);
        // Start waiting for the Condition Variable to get signaled
        // Wait() will internally release the lock and make the thread to block
        // As soon as condition variable get signaled, resume the thread and
        // again acquire the lock. Then check if condition is met or not
        // If condition is met then continue else again go in wait.
        m_condVar.wait(mlock, std::bind(&Application::isDataLoaded, this));
        std::cout << "Do Processing On loaded Data" << std::endl;
    }
};
int main()
{
    Application app;
    std::thread thread_1(&Application::mainTask, &app);
    std::thread thread_2(&Application::loadData, &app);
    thread_2.join();
    thread_1.join();
    return 0;
}

Now, other than the std::condition_variable m_condVar it also uses an additional variable bool m_bDataLoaded. But it seems to me that the thread performing mainTask is already notified that the data was loaded by means of std::condition_variable m_condVar. Why also check bool m_bDataLoaded for the same information? Compare (the same code without bool m_bDataLoaded):

#include <iostream>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
using namespace std::placeholders;
class Application
{
    std::mutex m_mutex;
    std::condition_variable m_condVar;
public:
    Application()
    {
    }
    void loadData()
    {
        // Make This Thread sleep for 1 Second
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout << "Loading Data from XML" << std::endl;
        // Lock The Data structure
        std::lock_guard<std::mutex> guard(m_mutex);
        // Notify the condition variable
        m_condVar.notify_one();
    }
    void mainTask()
    {
        std::cout << "Do Some Handshaking" << std::endl;
        // Acquire the lock
        std::unique_lock<std::mutex> mlock(m_mutex);
        // Start waiting for the Condition Variable to get signaled
        // Wait() will internally release the lock and make the thread to block
        // As soon as condition variable get signaled, resume the thread and
        // again acquire the lock. Then check if condition is met or not
        // If condition is met then continue else again go in wait.
        m_condVar.wait(mlock);
        std::cout << "Do Processing On loaded Data" << std::endl;
    }
};
int main()
{
    Application app;
    std::thread thread_1(&Application::mainTask, &app);
    std::thread thread_2(&Application::loadData, &app);
    thread_2.join();
    thread_1.join();
    return 0;
}

Now I know about spurious wakeups and they alone necessitate the usage of an additional variable. My question is - are they they only reason for it? If they didn't occur could one just use condition variables without any additional variables (and btw wouldn't that make the name "condition variable" a misnomer then)?

Another thing is - isn't the usage of additional variables the only reason why condition variables also require a mutex? If not, what are the other reasons?

If additional variables are necessary (for spurious wakeups or other reasons) why doesn't the API require them (in the 2nd code I didn't have to use them for the code to compile)? (I don't know if it's the same in other languages, so this question might be C++-specific.)

Body:
Yes, the condition variable is just useful to wait for an event. In my point of view you should not try to use it for controlling concurrent access of critical data structures.

I just can speak about C++. As you see in the example here https://en.cppreference.com/w/cpp/thread/condition_variable/wait, they used this expression cv.wait(lk, []{return i == 1;});. And []{...} is the expression of a nameless function. So you can also write your own function and give the name of the function:

bool condFn()
{
    std::cout << "condFn" << std::endl; // debug output ;)
    return i == 1;
}

void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cerr << "Waiting... \n";
    cv.wait(lk, condFn);
    std::cerr << "...finished waiting. i == 1\n";
}

And inside this function you can evaluate, whatever you want. The thread is always sleeping until it gets notified, then it processes always the function that evaluates the condition for continue working. In case of true, the thread continues, in case of false the programm goes sleeping again.


问:
Filtering and array mapping issue in react
This is a translate of the original question, sorry for the english

I'm creating a filter for the notifications of an app I'm working on, the app is in react, the thing is this, I'm trying to use filter and map, but for some reason, I think it's probably some syntax error on my part, it does not do the filtering part, in the data I receive there is a value called status, if this is completed I want it to be removed from the new array.

status is located in notifications.data.status I put below the way I receive the data

notifications.data

It only does the mapping, I have to use Object.keys, because of the rest it gives me a compiled error, thank you very much

```<code>          <GlobalNotifications id="GlobalNotifications">
            {/* {console.log(Object.keys(notifications.data).filter(notification => notification.status !== 'completed'))} */}
            {console.log(Object.values(notifications.data))}
            {Object.keys(notifications.data)
              .filter(notification => notification.status !== 'completed')
              .map(key => (
                <NotificationItem
                  id={key}
                  key={key}
                  data={notifications.data[key]}
                  openHistory={openHistory === key}
                  callbackOpenHistory={onOpenHistory}
                />
              ))}
          </GlobalNotifications>
</code>```

答: I suggest to remove the rxjs tag as your question is related to JavaScript higher order functions on arrays but has nothing to do with rxjs</p>

Body:
This is a translate of the original question, sorry for the english

I'm creating a filter for the notifications of an app I'm working on, the app is in react, the thing is this, I'm trying to use filter and map, but for some reason, I think it's probably some syntax error on my part, it does not do the filtering part, in the data I receive there is a value called status, if this is completed I want it to be removed from the new array.

status is located in notifications.data.status I put below the way I receive the data

notifications.data

It only does the mapping, I have to use Object.keys, because of the rest it gives me a compiled error, thank you very much

          <GlobalNotifications id="GlobalNotifications">
            {/* {console.log(Object.keys(notifications.data).filter(notification => notification.status !== 'completed'))} */}
            {console.log(Object.values(notifications.data))}
            {Object.keys(notifications.data)
              .filter(notification => notification.status !== 'completed')
              .map(key => (
                <NotificationItem
                  id={key}
                  key={key}
                  data={notifications.data[key]}
                  openHistory={openHistory === key}
                  callbackOpenHistory={onOpenHistory}
                />
              ))}
          </GlobalNotifications>


问:
C++ : read a csv file and extract some parts
A .csv file is written like this:

```<code>    M9005U00-X30A0S00-1;BAS;X;-0.002;-0.095
    S707RY00-X30AOS00-1;HMV;X;+0.002;+0.081
    W3005U00-X30BOJ00-1;BAS;X;+0.026;-0.138
    H307QZ00-X30BOJ00-1;HMV;X;-0.025;+0.122
    ....
</code>```

now I want to create a function, i.e.

```<code>      double find_and_extract (string sss)
</code>```

when this function is used with a keyword as its parameter, for example

```<code>      find_and_extract (W3005U00-X30BOJ00-1);
</code>```

it will search in the .csv file line by line, find corresponding line (in this case it should be the third line), and extract the certin part "+0.026" in this line, return as a double.

How should I write this function?

edit: Here is the code i've written so far:

```<code>    #include <iostream>
    #include <fstream>
    #include <string>
    #include <stdio.h>
    #include <vector>
    #include <iterator>
    #include <cstdlib>
    #include <cstdio>
    #include <sstream>
    #include <stdlib.h>

    using namespace std;

    void main()
        {
           find_and_extract (W3005U00-X30BOJ00-1);
        }

    double find_and_extract (string sss)
         {
             vector<string> vecarray;
             ifstream infile("C:\\Data\\testdata.csv");
             string temppo;
             string contnt;
             char csv_extract[40];
             stringstream ss;
             vector <string>::iterator ptr;
             while (!infile.eof())
               {
                 infile.getline(csv_extract,40);
                 ss << csv_extract;
                 ss >> contnt;
                 vecarray.push_back(contnt);
                }
             for (ptr=vecarray.begin();ptr!=vecarray.end();ptr++)
             {
                 if ((*ptr).find(sss)==0)
                     temppo = (*ptr).substr(27,6);
             }
             return (strtod(temppo.c_str(),NULL,0));
        }
</code>```

Could anyone help me out to point out the errors?

答:
You could use sed: This way, you could search for the key very efficiently, without having to implement an algorithm yourself. When you found the key, you can let sed output the parts of the line you need (use regular expressions to describe the pattern and groupings to print only part of it). After that, it's a simple string to float conversion that can be done in a programming language of your choice.

For starters:

```<code>sed -n 's/RegexToMatchYourKeyAndValues/MatchedValues/p'
</code>```

Body:
A .csv file is written like this:

    M9005U00-X30A0S00-1;BAS;X;-0.002;-0.095
    S707RY00-X30AOS00-1;HMV;X;+0.002;+0.081
    W3005U00-X30BOJ00-1;BAS;X;+0.026;-0.138
    H307QZ00-X30BOJ00-1;HMV;X;-0.025;+0.122
    ....

now I want to create a function, i.e.

      double find_and_extract (string sss)

when this function is used with a keyword as its parameter, for example

      find_and_extract (W3005U00-X30BOJ00-1);

it will search in the .csv file line by line, find corresponding line (in this case it should be the third line), and extract the certin part "+0.026" in this line, return as a double.

How should I write this function?

edit: Here is the code i've written so far:

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <stdio.h>
    #include <vector>
    #include <iterator>
    #include <cstdlib>
    #include <cstdio>
    #include <sstream>
    #include <stdlib.h>

    using namespace std;

    void main()
        {
           find_and_extract (W3005U00-X30BOJ00-1);
        }

    double find_and_extract (string sss)
         {
             vector<string> vecarray;
             ifstream infile("C:\\Data\\testdata.csv");
             string temppo;
             string contnt;
             char csv_extract[40];
             stringstream ss;
             vector <string>::iterator ptr;
             while (!infile.eof())
               {
                 infile.getline(csv_extract,40);
                 ss << csv_extract;
                 ss >> contnt;
                 vecarray.push_back(contnt);
                }
             for (ptr=vecarray.begin();ptr!=vecarray.end();ptr++)
             {
                 if ((*ptr).find(sss)==0)
                     temppo = (*ptr).substr(27,6);
             }
             return (strtod(temppo.c_str(),NULL,0));
        }

Could anyone help me out to point out the errors?

Body:
You could use sed: This way, you could search for the key very efficiently, without having to implement an algorithm yourself. When you found the key, you can let sed output the parts of the line you need (use regular expressions to describe the pattern and groupings to print only part of it). After that, it's a simple string to float conversion that can be done in a programming language of your choice.

For starters:

sed -n 's/RegexToMatchYourKeyAndValues/MatchedValues/p'


问:
Am I doing something wrong in my file-reader function?
I'm a beginner to C and wanted to code a simple function that reads the content of file and returns it as a string, as an exercise.

Here is my solution which I think works, but is there any obvious bad practices or unoptimal code here ? For example, I manually added a \0 at the end of the string, but I don't know if it is really necessary...

```<code>#include <stdio.h>
#include <stdlib.h>

char *readFile(char *path)
{
    //open file
    FILE *file = fopen(path, "r");
    //if broken
    if (file == NULL)
    {
        printf("Erreur");
        return NULL;
    }

    //return variable
    char *result;

    //length of the file
    int len;
    fseek(file, 0, SEEK_END);
    len = ftell(file);
    fseek(file, 0, SEEK_SET);

    //initialising return variable
    result = (char*) malloc(sizeof(char) * (len + 1));

    int c;
    int i = 0;
    while (feof(file) == 0)
    {
        c = fgetc(file);
        if (c != EOF)
        {
            printf("%04x -> %c\n", c, c);
            *(result + i) = c;
            i++;
        }
    }
    *(result + i) = '\0';
    printf("len : %i\n", len);
    fclose(file);

    return result;
}
</code>```

答:
Since you have already got the length of the file to be read, you could also read them at once instead char-by-char.

Another implmentation of your function, for example:

```<code>char *readFile(char *path)
{
    //open file
    FILE *file = fopen(path, "r");
    //if broken
    if (file == NULL)
    {
        printf("Erreur");
        return NULL;
    }

    //return variable
    char *result;

    //length of the file
    int len;
    fseek(file, 0, SEEK_END);
    len = ftell(file);
    fseek(file, 0, SEEK_SET);

    //initialising return variable
    result = (char*) malloc(sizeof(char) * (len + 1));

    size_t i = fread(result, sizeof(char), len, file);

    *(result + i) = '\0';
    printf("len : %i\n", len);
    fclose(file);

    return result;
}
</code>```

Body:
I'm a beginner to C and wanted to code a simple function that reads the content of file and returns it as a string, as an exercise.

Here is my solution which I think works, but is there any obvious bad practices or unoptimal code here ? For example, I manually added a \0 at the end of the string, but I don't know if it is really necessary...

#include <stdio.h>
#include <stdlib.h>

char *readFile(char *path)
{
    //open file
    FILE *file = fopen(path, "r");
    //if broken
    if (file == NULL)
    {
        printf("Erreur");
        return NULL;
    }

    //return variable
    char *result;

    //length of the file
    int len;
    fseek(file, 0, SEEK_END);
    len = ftell(file);
    fseek(file, 0, SEEK_SET);

    //initialising return variable
    result = (char*) malloc(sizeof(char) * (len + 1));

    int c;
    int i = 0;
    while (feof(file) == 0)
    {
        c = fgetc(file);
        if (c != EOF)
        {
            printf("%04x -> %c\n", c, c);
            *(result + i) = c;
            i++;
        }
    }
    *(result + i) = '\0';
    printf("len : %i\n", len);
    fclose(file);

    return result;
}

Body:
Since you have already got the length of the file to be read, you could also read them at once instead char-by-char.

Another implmentation of your function, for example:

char *readFile(char *path)
{
    //open file
    FILE *file = fopen(path, "r");
    //if broken
    if (file == NULL)
    {
        printf("Erreur");
        return NULL;
    }

    //return variable
    char *result;

    //length of the file
    int len;
    fseek(file, 0, SEEK_END);
    len = ftell(file);
    fseek(file, 0, SEEK_SET);

    //initialising return variable
    result = (char*) malloc(sizeof(char) * (len + 1));

    size_t i = fread(result, sizeof(char), len, file);

    *(result + i) = '\0';
    printf("len : %i\n", len);
    fclose(file);

    return result;
}


问:
Flutter animations error, The method '[]' can't be unconditionally invoked because the receiver can be 'null'
I am very new to flutter.
I am having trouble with fixing this error.

return ControlledAnimation(
delay: Duration(milliseconds: (500 * delay).round()),
duration: tween.duration,
tween: tween,
child: child,
builderWithChild: (context, child, animation) => Opacity(
opacity: animation["opacity"],

```<code>    child: Transform.translate(
      offset: Offset(0, animation["translateY"]),
      child: child
    ),
  ),
);
</code>```

and the error is
The method '[]' can't be unconditionally invoked because the receiver can be 'null'.
Try making the call conditional (using '?.') or adding a null check to the target ('!'). at the animation["opacity"] line.
Can somebody please help

Complete code

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

class FadeAnimation extends StatelessWidget {
  final double delay;
  final Widget child;

  FadeAnimation(this.delay, this.child);

  @override
  Widget build(BuildContext context) {
    final tween = MultiTrackTween([
      Track("opacity").add(Duration(milliseconds: 500), Tween(begin: 0.0, end: 1.0)),
      Track("translateY").add(
        Duration(milliseconds: 500), Tween(begin: -30.0, end: 0.0),
        curve: Curves.easeOut)
    ]);

    return ControlledAnimation(
      delay: Duration(milliseconds: (500 * delay).round()),
      duration: tween.duration,
      tween: tween,
      child: child,
      builderWithChild: (context, child, animation) => Opacity(
        //opacity: animation.["opacity"],
        opacity: animation!(["opacity"]),

        child: Transform.translate(
         // offset: Offset(0, animation.["translateY"]),
         offset: Offset(0, animation?["translateY"] ?? 0),
          child: child
        ),
      ),
    );
  }
}
</code>```

答:
Flutter supports what's called sound null safety. This helps you ensure values aren't null, and thereby prevents some runtime errors. You can read up on it here:
https://dart.dev/null-safety/understanding-null-safety

In this case, I think it's caused by your object named animation, likely a map of some sort. In this case, the compiler is not sure whether or not the animation object is null or not. There's two things you can do: If you're certain animation is never gonna be null, you can tell that by adding a !:

Offset(0, animation!["translateY"]),
```
<p>Or alternatively, if you think it might be null, you can tell that by adding a <code>?</code>:</p>
<pre class="lang-dart prettyprint-override"><code>Offset(0, animation?["translateY"]),
</code>```

But this will replace the translateY value with null if animation is null.
In this case, it might be wise to define a default value to use when it resolves to null, using the ?? operator:

Offset(0, animation?["translateY"] ?? 0),
```

If you want to know more I advise you to read up on the dart.dev website or look up a helpful video or Medium post.

Body:
I am very new to flutter.
I am having trouble with fixing this error.

return ControlledAnimation(
delay: Duration(milliseconds: (500 * delay).round()),
duration: tween.duration,
tween: tween,
child: child,
builderWithChild: (context, child, animation) => Opacity(
opacity: animation["opacity"],

    child: Transform.translate(
      offset: Offset(0, animation["translateY"]),
      child: child
    ),
  ),
);

and the error is
The method '[]' can't be unconditionally invoked because the receiver can be 'null'.
Try making the call conditional (using '?.') or adding a null check to the target ('!'). at the animation["opacity"] line.
Can somebody please help

Complete code

import 'package:flutter/material.dart';
import 'package:simple_animations/simple_animations.dart';

class FadeAnimation extends StatelessWidget {
  final double delay;
  final Widget child;

  FadeAnimation(this.delay, this.child);

  @override
  Widget build(BuildContext context) {
    final tween = MultiTrackTween([
      Track("opacity").add(Duration(milliseconds: 500), Tween(begin: 0.0, end: 1.0)),
      Track("translateY").add(
        Duration(milliseconds: 500), Tween(begin: -30.0, end: 0.0),
        curve: Curves.easeOut)
    ]);

    return ControlledAnimation(
      delay: Duration(milliseconds: (500 * delay).round()),
      duration: tween.duration,
      tween: tween,
      child: child,
      builderWithChild: (context, child, animation) => Opacity(
        //opacity: animation.["opacity"],
        opacity: animation!(["opacity"]),

        child: Transform.translate(
         // offset: Offset(0, animation.["translateY"]),
         offset: Offset(0, animation?["translateY"] ?? 0),
          child: child
        ),
      ),
    );
  }
}

Body:
Flutter supports what's called sound null safety. This helps you ensure values aren't null, and thereby prevents some runtime errors. You can read up on it here:
https://dart.dev/null-safety/understanding-null-safety

In this case, I think it's caused by your object named animation, likely a map of some sort. In this case, the compiler is not sure whether or not the animation object is null or not. There's two things you can do: If you're certain animation is never gonna be null, you can tell that by adding a !:

Offset(0, animation!["translateY"]),

Or alternatively, if you think it might be null, you can tell that by adding a ?:

Offset(0, animation?["translateY"]),

But this will replace the translateY value with null if animation is null.
In this case, it might be wise to define a default value to use when it resolves to null, using the ?? operator:

Offset(0, animation?["translateY"] ?? 0),

If you want to know more I advise you to read up on the dart.dev website or look up a helpful video or Medium post.


问:
Can't install node-sass@6 for node v16
This is my package.json after uninstalling sass  node-sass and sass-loader because I changed my node version from 14 to 16,

```<code>{
  "name": "our-awesome-project",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "static": "NUXTJS_DEPLOY_TARGET=static NUXTJS_SSR=true nuxt generate",
    "build-and-start": "NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt build && NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt start"
  },
  "husky": {
    "hooks": {
      "pre-commit": "cross-env PRE_COMMIT=true lint-staged -r"
    }
  },
  "dependencies": {
    "core-js": "^3.19.3",
    "nuxt": "^2.15.8",
    "nuxt-i18n": "^6.28.1",
    "nuxt-purgecss": "^1.0.0",
    "vue": "^2.6.14",
    "vue-server-renderer": "^2.6.14",
    "vue-template-compiler": "^2.6.14",
    "webpack": "^4.46"
  },
  "devDependencies": {
    "@nuxtjs/eslint-config": "^8.0.0",
    "@nuxtjs/google-fonts": "^1.3.0",
    "@nuxtjs/storybook": "^4.2.0",
    "@nuxtjs/style-resources": "^1.2.1",
    "@vue/cli-plugin-babel": "^4.5.15",
    "babel-eslint": "^10.1.0",
    "eslint": "^8.7.0",
    "husky": "^7.0.4",
    "nuxt-svg-loader": "^1.2.0",
    "postcss": "^8.4.5"
  }
}
</code>```

According to this I should install node-sass version 6.0

But I'm trying:
npm install --save-dev sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1

Also, read here to add --unsafe-perm so I tried:
npm install --save-dev --unsafe-perm sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1

But it keeps failing, being the first error always this one:

```<code>npm ERR! code 1
npm ERR! path /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-sass
npm ERR! command failed
npm ERR! command sh -c node scripts/build.js
npm ERR! Building: /Users/user/.nvm/versions/node/v16.13.1/bin/node /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
</code>```

I tried removing node_modules package-lock.json and the same result

Of course, this is driving me nuts.. please tell me that anyone has an idea to try out

答:
The error message hints to node-gyp as the culprit. To work on a MacOS, node-gyp requires the XCode Command Line Tools to be installed (see here). So basically, in case you haven't done that yet, run

```<code>xcode-select --install
</code>```

Or try any of the other methods described here. Then retry to install node-sass.

Title: Can't install node-sass@6 for node v16

Body:
This is my package.json after uninstalling sass  node-sass and sass-loader because I changed my node version from 14 to 16,

{
  "name": "our-awesome-project",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "static": "NUXTJS_DEPLOY_TARGET=static NUXTJS_SSR=true nuxt generate",
    "build-and-start": "NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt build && NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt start"
  },
  "husky": {
    "hooks": {
      "pre-commit": "cross-env PRE_COMMIT=true lint-staged -r"
    }
  },
  "dependencies": {
    "core-js": "^3.19.3",
    "nuxt": "^2.15.8",
    "nuxt-i18n": "^6.28.1",
    "nuxt-purgecss": "^1.0.0",
    "vue": "^2.6.14",
    "vue-server-renderer": "^2.6.14",
    "vue-template-compiler": "^2.6.14",
    "webpack": "^4.46"
  },
  "devDependencies": {
    "@nuxtjs/eslint-config": "^8.0.0",
    "@nuxtjs/google-fonts": "^1.3.0",
    "@nuxtjs/storybook": "^4.2.0",
    "@nuxtjs/style-resources": "^1.2.1",
    "@vue/cli-plugin-babel": "^4.5.15",
    "babel-eslint": "^10.1.0",
    "eslint": "^8.7.0",
    "husky": "^7.0.4",
    "nuxt-svg-loader": "^1.2.0",
    "postcss": "^8.4.5"
  }
}

According to this I should install node-sass version 6.0

But I'm trying:
npm install --save-dev sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1

Also, read here to add --unsafe-perm so I tried:
npm install --save-dev --unsafe-perm sass@1.49.0 node-sass@6.0.1 sass-loader@10.2.1

But it keeps failing, being the first error always this one:

npm ERR! code 1
npm ERR! path /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-sass
npm ERR! command failed
npm ERR! command sh -c node scripts/build.js
npm ERR! Building: /Users/user/.nvm/versions/node/v16.13.1/bin/node /Users/toniweb/Proyectos/our-awesome-project/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=

I tried removing node_modules package-lock.json and the same result

Of course, this is driving me nuts.. please tell me that anyone has an idea to try out

Body:
The error message hints to node-gyp as the culprit. To work on a MacOS, node-gyp requires the XCode Command Line Tools to be installed (see here). So basically, in case you haven't done that yet, run

xcode-select --install

Or try any of the other methods described here. Then retry to install node-sass.


答:
I'd replace this:

```<code>    int c;
    int i = 0;
    while (feof(file) == 0)
    {
        c = fgetc(file);
        if (c != EOF)
        {
            printf("%04x -> %c\n", c, c);
            *(result + i) = c;
            i++;
        }
    }
</code>```

with this:

```<code>    fread(file, 1, len, result);
</code>```

It's much shorter

It's correct

It's certainly faster

There is still room for improvement though, for example you could add error handling, fread can fail.

Title: Am I doing something wrong in my file-reader function?

Body:
I'd replace this:

    int c;
    int i = 0;
    while (feof(file) == 0)
    {
        c = fgetc(file);
        if (c != EOF)
        {
            printf("%04x -> %c\n", c, c);
            *(result + i) = c;
            i++;
        }
    }

with this:

    fread(file, 1, len, result);

It's much shorter

It's correct

It's certainly faster

There is still room for improvement though, for example you could add error handling, fread can fail.


问:
How to add CSS to change colour on hover
I am trying to create a button with text inside. I want it so that when you hover over the box, the color of the box changes to white, and the colour of the text changes to blue.

How can I add css to make my text and box change colors on hover?

Edited: I got the html snippet for that from another part of the website template I am editing. It is basically a box that does exactly what I have outline above. I then placed it inside the list tag of the menu html, hoping that it will just transfer the functionality but it didn't work. So I tried to add the [hover:] but it still isn't working.

I know I am doing something wrong but I don't know enough to know what it is.

Code snippet is for html:

                                Upload resources

答:
Use the :hover pseudo selector

e.g.

```<code>button {
    color: white;
    background: blue;
}

button:hover {
    color: blue;
    background: white;
}
</code>```

Of course, replace with the actual hex codes you need rather than the colour names above, and any valid property can be used, e.g. border, text-decoration etc.

Body:
Use the :hover pseudo selector

e.g.

button {
    color: white;
    background: blue;
}

button:hover {
    color: blue;
    background: white;
}

Of course, replace with the actual hex codes you need rather than the colour names above, and any valid property can be used, e.g. border, text-decoration etc.


问:
React - changing an uncontrolled input
I have a simple react component with the form which I believe to have one controlled input:

```<code>import React from 'react';

export default class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    render() {
        return (
            <form className="add-support-staff-form">
                <input name="name" type="text" value={this.state.name} onChange={this.onFieldChange('name').bind(this)}/>
            </form>
        )
    }

    onFieldChange(fieldName) {
        return function (event) {
            this.setState({[fieldName]: event.target.value});
        }
    }
}

export default MyForm;
</code>```

When I run my application I get the following warning:

Warning: MyForm is changing an uncontrolled input of type text to be
  controlled. Input elements should not switch from uncontrolled to
  controlled (or vice versa). Decide between using a controlled or
  uncontrolled input element for the lifetime of the component

I believe my input is controlled since it has a value.  I am wondering what am I doing wrong?

I am using React 15.1.0

答:
I had the same problem.
the problem was when i kept the state info blank

```<code>  const [name, setName] = useState()
</code>```

I fixed it by adding empty string like this

```<code>  const [name, setName] = useState('')
</code>```

Title: React - changing an uncontrolled input

Body:
I have a simple react component with the form which I believe to have one controlled input:

import React from 'react';

export default class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    render() {
        return (
            <form className="add-support-staff-form">
                <input name="name" type="text" value={this.state.name} onChange={this.onFieldChange('name').bind(this)}/>
            </form>
        )
    }

    onFieldChange(fieldName) {
        return function (event) {
            this.setState({[fieldName]: event.target.value});
        }
    }
}

export default MyForm;

When I run my application I get the following warning:

Warning: MyForm is changing an uncontrolled input of type text to be
  controlled. Input elements should not switch from uncontrolled to
  controlled (or vice versa). Decide between using a controlled or
  uncontrolled input element for the lifetime of the component

I believe my input is controlled since it has a value.  I am wondering what am I doing wrong?

I am using React 15.1.0

Body:
I had the same problem.
the problem was when i kept the state info blank

  const [name, setName] = useState()

I fixed it by adding empty string like this

  const [name, setName] = useState('')


问:
Logical with count in Pyspark
I'm new to Pyspark and I have a problem to solve.

I have a dataframe with 4 columns, being customers, person, is_online_store and count:

customer
PersonId
is_online_store
count

afabd2d2
4
true
1

afabd2d2
8
true
2

afabd2d2
3
true
1

afabd2d2
2
false
1

afabd2d2
4
false
1

I need to create according to the following rules:

If PersonId count(column) has 1 or + Trues and None False then Online

If PersonId count(column) has 1 or + False and None True then offline

If the PersonId count(column) has at least 1 False AND 1 True then Hybrid

How it should look:

customer
PersonId
New_Column

afabd2d2
4
Hybrid

afabd2d2
8
Online

afabd2d2
3
Online

afabd2d2
2
Offline

答:
Group by customer + personId and use when expression to check if all values in is_online_store column are true / false or a mix of the 2, using for example bool_and function:

from pyspark.sql import functions as F

df1 = df.groupBy("customer", "PersonId").agg(
    F.when(F.expr("bool_and(is_online_store)"), "Online")
     .when(F.expr("bool_and(!is_online_store)"), "Offline")
     .otherwise("Hybrid").alias("New_Column")
)

df1.show()
#+--------+--------+----------+
#|customer|PersonId|New_Column|
#+--------+--------+----------+
#|afabd2d2|       2|   Offline|
#|afabd2d2|       8|    Online|
#|afabd2d2|       4|    Hybrid|
#|afabd2d2|       3|    Online|
#+--------+--------+----------+
```

Title: Logical with count in Pyspark


问:
Angular error: No value accessor for form control with name: 'text'
I´m trying to write a unit test for editing a text inside a comment, but I am getting an error Error: No value accessor for form control with name: 'text'  I want to expand on my unit test but I am already getting an error - can you suggest what am I doing wrong?

```<code><div class="modal" id="edit-comment-modal">
  <form [formGroup]="editForm" (ngSubmit)="editComment()">
    <textarea
      id="edit-text"
      formControlName="text"
    ></textarea>
   <button type="submit"">Edit</button>
  </form>
</div>
</code>```
```<code>export class EditCommentComponent implements OnInit {
 @Input() comment;
 editForm: FormGroup;

 constructor(
    private editService: editService,
  ) {}

 ngOnInit(): void {
    this.editForm = new FormGroup({
      text: new FormControl(''),
    });
  }

 public editComment(): void {
    this.editService.editComment(this.editForm.value, this.comment.id)
      .subscribe(
        () => {
          this.comment.text = this.editForm.value.text;
        }
      );
  }
}
</code>```
```<code> it('should edit comment', () => {
    component.editForm.value.text = 'Text comment';
    component.comment.text = component.editForm.value.text;
    expect(component.comment.text).toEqual(component.editForm.value.text);
 });
</code>```

答:
it seems you are missing either ReactiveFormsModule or FormsModule imported in your test module

```<code>TestBed.configureTestingModule({
      ...,
      imports: [ReactiveFormsModule]
    });
</code>```

Body:
I´m trying to write a unit test for editing a text inside a comment, but I am getting an error Error: No value accessor for form control with name: 'text'  I want to expand on my unit test but I am already getting an error - can you suggest what am I doing wrong?

  <form [formGroup]="editForm" (ngSubmit)="editComment()">
    <textarea
      id="edit-text"
      formControlName="text"
    ></textarea>
   <button type="submit"">Edit</button>
  </form>

export class EditCommentComponent implements OnInit {
 @Input() comment;
 editForm: FormGroup;

 constructor(
    private editService: editService,
  ) {}

 ngOnInit(): void {
    this.editForm = new FormGroup({
      text: new FormControl(''),
    });
  }

 public editComment(): void {
    this.editService.editComment(this.editForm.value, this.comment.id)
      .subscribe(
        () => {
          this.comment.text = this.editForm.value.text;
        }
      );
  }
}

 it('should edit comment', () => {
    component.editForm.value.text = 'Text comment';
    component.comment.text = component.editForm.value.text;
    expect(component.comment.text).toEqual(component.editForm.value.text);
 });

Body:
it seems you are missing either ReactiveFormsModule or FormsModule imported in your test module

TestBed.configureTestingModule({
      ...,
      imports: [ReactiveFormsModule]
    });


问:
Target of URI doesn't exist: 'package:image_picker/image_picker.dart'
i tried everything i could to import image_picker and i find on various sites but couldn't get rid of this error :

```<code>import 'package:image_picker/image_picker.dart';
</code>```

Target of URI doesn't exist: 'package:image_picker/image_picker.dart'.
Try creating the file referenced by the URI, or Try using a URI for a file that does exis

already added the dependencies such as :

```<code>     dependencies:

       image_picker: ^0.8.4+8

</code>```

Running "flutter pub get" it turns out to

OUTPUT:

The plugin flutter_plugin_android_lifecycle doesn't have a main
class defined in C:\Users\Iradukunda
Didier\Documents\flutter_windows_2.8.1-stable\flutter.pub-cache\hosted\pub.dartlang.org\flutter_plugin_android_lifecycle-2.0.5\android\src\main\java\io\flutter\plugins\flutter_plugin_android_lifecycle\FlutterAndroidLifecyclePlugin.java
or C:\Users\Iradukunda
Didier\Documents\flutter_windows_2.8.1-stable\flutter.pub-cache\hosted\pub.dartlang.org\flutter_plugin_android_lifecycle-2.0.5\android\src\main\kotlin\io\flutter\plugins\flutter_plugin_android_lifecycle\FlutterAndroidLifecyclePlugin.kt.
This is likely to due to an incorrect androidPackage: io.flutter.plugins.flutter_plugin_android_lifecycle or mainClass
entry in the plugin's pubspec.yaml. If you are the author of this
plugin, fix the androidPackage entry or move the main class to any
of locations used above. Otherwise, please contact the author of this
plugin and consider using a different plugin in the meanwhile.  exit
code 1

答:
Run flutter packages get instead of flutter pub get. If it does not work, Re-start the Visual Studio Code after flutter packages get

Source:

Body:
i tried everything i could to import image_picker and i find on various sites but couldn't get rid of this error :

import 'package:image_picker/image_picker.dart';

Target of URI doesn't exist: 'package:image_picker/image_picker.dart'.
Try creating the file referenced by the URI, or Try using a URI for a file that does exis

already added the dependencies such as :

     dependencies:

       image_picker: ^0.8.4+8

Running "flutter pub get" it turns out to

OUTPUT:

The plugin flutter_plugin_android_lifecycle doesn't have a main
class defined in C:\Users\Iradukunda
Didier\Documents\flutter_windows_2.8.1-stable\flutter.pub-cache\hosted\pub.dartlang.org\flutter_plugin_android_lifecycle-2.0.5\android\src\main\java\io\flutter\plugins\flutter_plugin_android_lifecycle\FlutterAndroidLifecyclePlugin.java
or C:\Users\Iradukunda
Didier\Documents\flutter_windows_2.8.1-stable\flutter.pub-cache\hosted\pub.dartlang.org\flutter_plugin_android_lifecycle-2.0.5\android\src\main\kotlin\io\flutter\plugins\flutter_plugin_android_lifecycle\FlutterAndroidLifecyclePlugin.kt.
This is likely to due to an incorrect androidPackage: io.flutter.plugins.flutter_plugin_android_lifecycle or mainClass
entry in the plugin's pubspec.yaml. If you are the author of this
plugin, fix the androidPackage entry or move the main class to any
of locations used above. Otherwise, please contact the author of this
plugin and consider using a different plugin in the meanwhile.  exit
code 1


问:
Find a specific value/characters in a string field (If statement)
I have these string statments:

10 - Holiday Booking

20 - Summer term

34 - Nighttime

Autumn time

I wanted to create a IF statement which says:

If the start of the string contains 'X - ' (a number and a hyphen with spaces, although I think it will recognise the number as a string type), then keep it as it is, otherwise add a random number and hyphen to the start

10 - Holiday Booking

20 - Summer term

34 - Nighttime

55 - Autumn time

I am using Google App Scripts/Java.

答:
The function can be made like this</p>
```<code>const str1 = '10 - Holiday Booking';
const str2 = 'Autumn time';

function MyFun(str) {
  const firstAscii = str.charCodeAt(0);
  if( (firstAscii>=65 && firstAscii<=90 ) || (firstAscii>=65 && firstAscii<=90) ){
    str = Math.floor((Math.random() * 100) + 1) + " - " + str;
  }
  console.log(str);
}

MyFun(str1);
MyFun(str2);
</code>```

Body:
The function can be made like this

const str1 = '10 - Holiday Booking';
const str2 = 'Autumn time';

function MyFun(str) {
  const firstAscii = str.charCodeAt(0);
  if( (firstAscii>=65 && firstAscii<=90 ) || (firstAscii>=65 && firstAscii<=90) ){
    str = Math.floor((Math.random() * 100) + 1) + " - " + str;
  }
  console.log(str);
}

MyFun(str1);
MyFun(str2);


问:
Saving Excel file as CSV while excluding header in VBA?
I have written  the following code:

```<code>Sub create_talpo_kiint_csv()
    Dim FileName As String
    Dim PathName As String
    Dim ws As Worksheet

    Set ws = ActiveWorkbook.Sheets("SheetName").range("B2", range("B2").End(xlToRight).End(xlDown)).Select
    FileName = "test.csv"
    PathName = Application.ActiveWorkbook.Path
    ws.Copy
    ActiveWorkbook.SaveAs FileName:=PathName & "\" & FileName, _
        FileFormat:=xlCSV, CreateBackup:=False
End Sub
</code>```

The goal is to save the excel file as csv while excluding the header. However, the code above is not working. What should I do to fix it?

答:
Note that ws.Copy copies the entire worksheet regardles your selection. So I recommend to delete the header after the copy.

```<code>ws.Copy
ActiveWorkbook.Worksheets(1).Rows(1).Delete Shift:=xlUp  ' delete first row
</code>```

Make sure you set ws just to the worksheet then

```<code>Set ws = ActiveWorkbook.Worksheets("SheetName")
</code>```

Body:
I have written  the following code:

Sub create_talpo_kiint_csv()
    Dim FileName As String
    Dim PathName As String
    Dim ws As Worksheet

    Set ws = ActiveWorkbook.Sheets("SheetName").range("B2", range("B2").End(xlToRight).End(xlDown)).Select
    FileName = "test.csv"
    PathName = Application.ActiveWorkbook.Path
    ws.Copy
    ActiveWorkbook.SaveAs FileName:=PathName & "\" & FileName, _
        FileFormat:=xlCSV, CreateBackup:=False
End Sub

The goal is to save the excel file as csv while excluding the header. However, the code above is not working. What should I do to fix it?

Body:
Note that ws.Copy copies the entire worksheet regardles your selection. So I recommend to delete the header after the copy.

ws.Copy
ActiveWorkbook.Worksheets(1).Rows(1).Delete Shift:=xlUp  ' delete first row

Make sure you set ws just to the worksheet then

Set ws = ActiveWorkbook.Worksheets("SheetName")


问:
When doing pre-training of a transformer model, how can I add words to the vocabulary?
Given a DistilBERT trained language model for a given language, taken from the Huggingface hub, I want to pre-train the model on a specific domain, and I want to add new words that are:

definitely non existing in the original training set

and impossible to handle via word piece toeknization - basically you can think of these words as "codes" that are a normalized form of a named entity

Consider that:

I would like to avoid to learn a new tokenizer: I am fine to add the new words, and then let the model learn their embeddings via pre-training

the number of the "words" is way larger that the "unused" tokens in the "stock" vocabulary

The only advice that I have found is the one reported here:

Append it to the end of the vocab, and write a script which generates a new checkpoint that is identical to the pre-trained checkpoint, but but with a bigger vocab where the new embeddings are randomly initialized (for initialized we used tf.truncated_normal_initializer(stddev=0.02)). This will likely require mucking around with some tf.concat() and tf.assign() calls.

Do you think this is the only way of achieve my goal?

If yes, I do not have any idea of how to write this "script": does someone has some hints at how to proceeed (sample code, documentation etc)?

答:
As per my comment, I'm assuming that you go with a pre-trained checkpoint, if only to "avoid [learning] a new tokenizer."
Also, the solution works with PyTorch, which might be more suitable for such changes. I haven't checked Tensorflow (which is mentioned in one of your quotes), so no guarantees that this works across platforms.

To solve your problem, let us divide this into two sub-problems:

Adding the new tokens to the tokenizer, and

Re-sizing the token embedding matrix of the model accordingly.

The first can actually be achieved quite simply by using .add_tokens(). I'm referencing the slow tokenizer's implementation of it (because it's in Python), but from what I can see, this also exists for the faster Rust-based tokenizers.

from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
# Will return an integer corresponding to the number of added tokens
# The input could also be a list of strings instead of a single string
num_new_tokens = tokenizer.add_tokens("dennlinger")
```
<p>You can quickly verify that this worked by looking at the encoded input ids:</p>
<pre class="lang-py prettyprint-override"><code>print(tokenizer("This is dennlinger."))
# 'input_ids': [101, 2023, 2003, 30522, 1012, 102]
</code>```

The index 30522 now corresponds to the new token with my username, so we can check the first part. However, if we look at the function docstring of .add_tokens(), it also says:

Note, hen adding new tokens to the vocabulary, you should make sure to also resize the token embedding matrix of the model so that its embedding matrix matches the tokenizer.

In order to do that, please use the PreTrainedModel.resize_token_embeddings method.

Looking at this particular function, the description is a bit confusing, but we can get a correctly resized matrix (with randomly initialized weights for new tokens), by simply passing the previous model size, plus the number of new tokens:

from transformers import AutoModel

model = AutoModel.from_pretrained("distilbert-base-uncased")
model.resize_token_embeddings(model.config.vocab_size + num_new_tokens)

# Test that everything worked correctly
model(**tokenizer("This is dennlinger", return_tensors="pt"))
```

EDIT: Notably, .resize_token_embeddings() also takes care of any associated weights; this means, if you are pre-training, it will also adjust the size of the language modeling head (which should have the same number of tokens), or fix tied weights that would be affected by an increased number of tokens.

Body:
As per my comment, I'm assuming that you go with a pre-trained checkpoint, if only to "avoid [learning] a new tokenizer."
Also, the solution works with PyTorch, which might be more suitable for such changes. I haven't checked Tensorflow (which is mentioned in one of your quotes), so no guarantees that this works across platforms.

To solve your problem, let us divide this into two sub-problems:

Adding the new tokens to the tokenizer, and

Re-sizing the token embedding matrix of the model accordingly.

The first can actually be achieved quite simply by using .add_tokens(). I'm referencing the slow tokenizer's implementation of it (because it's in Python), but from what I can see, this also exists for the faster Rust-based tokenizers.

from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
# Will return an integer corresponding to the number of added tokens
# The input could also be a list of strings instead of a single string
num_new_tokens = tokenizer.add_tokens("dennlinger")

You can quickly verify that this worked by looking at the encoded input ids:

print(tokenizer("This is dennlinger."))
# 'input_ids': [101, 2023, 2003, 30522, 1012, 102]

The index 30522 now corresponds to the new token with my username, so we can check the first part. However, if we look at the function docstring of .add_tokens(), it also says:

Note, hen adding new tokens to the vocabulary, you should make sure to also resize the token embedding matrix of the model so that its embedding matrix matches the tokenizer.

In order to do that, please use the PreTrainedModel.resize_token_embeddings method.

Looking at this particular function, the description is a bit confusing, but we can get a correctly resized matrix (with randomly initialized weights for new tokens), by simply passing the previous model size, plus the number of new tokens:

from transformers import AutoModel

model = AutoModel.from_pretrained("distilbert-base-uncased")
model.resize_token_embeddings(model.config.vocab_size + num_new_tokens)

# Test that everything worked correctly
model(**tokenizer("This is dennlinger", return_tensors="pt"))

EDIT: Notably, .resize_token_embeddings() also takes care of any associated weights; this means, if you are pre-training, it will also adjust the size of the language modeling head (which should have the same number of tokens), or fix tied weights that would be affected by an increased number of tokens.


问:
How do I make a non-editable field editable in Django?
I have a field creation with auto_now_add=True in my model. I want to be able to edit this from the admin website, but when I try to display the field, I get the following error:

```<code>'creation' cannot be specified for model form as it is a non-editable field
</code>```

I tried adding editable=True to the model field as per the docs, but that did not work.

答:
The fields with auto_now_add=True are not editable. You need remove the auto_now_add, and set a default value or overwrite the model save method to set the creation date.

created = models.DateTimeField(default=timezone.now)
```
<p>... or ...</p>
<pre class="lang-py prettyprint-override"><code>
class MyModel(models.Model):
    # ...

    def save(self, *args, **kw)
        if not self.created:
            self.created = timezone.now()
        super(MyModel, self).save(*args, **kw)

</code>```

Body:
I have a field creation with auto_now_add=True in my model. I want to be able to edit this from the admin website, but when I try to display the field, I get the following error:

'creation' cannot be specified for model form as it is a non-editable field

I tried adding editable=True to the model field as per the docs, but that did not work.

Body:
The fields with auto_now_add=True are not editable. You need remove the auto_now_add, and set a default value or overwrite the model save method to set the creation date.

created = models.DateTimeField(default=timezone.now)

... or ...

class MyModel(models.Model):
    # ...

    def save(self, *args, **kw)
        if not self.created:
            self.created = timezone.now()
        super(MyModel, self).save(*args, **kw)


问:
Java - Iterating over a Map which contains a List
First time here so I hope this makes sense!

I have a Map which contains a String as it's Key, and a List of Strings as it's Value. I need to iterate over all vlaues contained within each List within the Map.

So, first I want to get the Keys, which works:

```<code>Set<String> keys = theMap.keySet();
</code>```

This returns me a Set containing all my Keys. Great :)

This is where I've got stuck - most of the info on the web seems to assume that the values I'd want returned from the Key would be a simple String or Integer, not another Set, or in this case a List. I tried theMap.values() but that didn't work, and I tried a forloop / for:eachloop, and neither of those did the trick.

Thanks y'all!

答:
Another example with the Java 8 API (lambda function).

When you want to iterate over:

```<code>Map<String, List<String>> theMap = new HashMap<>();

theMap.forEach((key, value) -> {
       System.out.println("KEY: " + key);
       System.out.print("VALUES: ");
       value.forEach(System.out::println);
});
</code>```

Body:
First time here so I hope this makes sense!

I have a Map which contains a String as it's Key, and a List of Strings as it's Value. I need to iterate over all vlaues contained within each List within the Map.

So, first I want to get the Keys, which works:

Set<String> keys = theMap.keySet();

This returns me a Set containing all my Keys. Great :)

This is where I've got stuck - most of the info on the web seems to assume that the values I'd want returned from the Key would be a simple String or Integer, not another Set, or in this case a List. I tried theMap.values() but that didn't work, and I tried a forloop / for:eachloop, and neither of those did the trick.

Thanks y'all!

Body:
Another example with the Java 8 API (lambda function).

When you want to iterate over:

Map<String, List<String>> theMap = new HashMap<>();

theMap.forEach((key, value) -> {
       System.out.println("KEY: " + key);
       System.out.print("VALUES: ");
       value.forEach(System.out::println);
});


问:
Unit testing using library 'unittest' in Python 3
I need to write test cases using unit test in Python for testing circle creation.

Define a class Circle with method init which initializes a circle with
attribute radius, having following restrictions.

radius must be numeric value, if not raise type error with error message "radius must be number".

radius must be between 0 to 1000 inclusive on both sides, if not raise the value error with error message "radius must be between 0 and
1000 inclusive"

Define a class method area and circumference which must return values rounded off to 2 decimals.

Complete the definition of class TestingCircleCircumference which
tests the behaviour of circumference  method as specification below.

Define the test method test_circlecircum_with_random_numerical_radius
which creates circle c1 with radius 2.5 and check if its computed
circumference match the value 15.71

Define the test method test_circlecircum_with__min_radius which
creates circle c2 with radius 0 and check if its computed
circumference match the value 0

Define the test method test_circlecircum_with_max_radius  which
creates circle c3 with radius 1000 and check if its computed
circumference match the value 6283.19

My code is:

```<code>import inspect
import re
import unittest
import math

class Circle:

    def __init__(self, radius):

        try:
            if not isinstance(radius, (int, float)):
                raise TypeError
            elif 1000 >= radius >= 0:
                self.radius=radius
            else:
                raise ValueError
        except ValueError:
            raise ValueError("radius must be between 0 and 1000 inclusive")
        except TypeError:
            raise TypeError("radius must be a number")

def area(self):

    y = math.pi*(self.radius**2)
    return round(y, 2)

def circumference(self):

    x = math.pi*2*self.radius
    return round(x, 2)

class TestCircleArea(unittest.TestCase):

    def test_circlearea_with_random_numeric_radius(self):

        c1 = Circle(2.5)
        self.assertEqual(c1.area(), 19.63)

    def test_circlearea_with_min_radius(self):

        c2 = Circle(0)
        self.assertEqual(c2.area(), 0)

    def test_circlearea_with_max_radius(self):

        c3 = Circle(1000.1)
        self.assertEqual(c3.area(), 3141592.65)
</code>```

The below code is generated by the system and I can't edit it. This code is from HackerRank.

```<code>if __name__ == '__main__':

    fptr = open('output.txt', 'w')

    runner = unittest.TextTestRunner(fptr)

    unittest.main(testRunner=runner, exit=False)

    fptr.close()

    with open('output.txt') as fp:
        output_lines = fp.readlines()

    pass_count = [len(re.findall(r'\.', line)) for line in output_lines if line.startswith('.')
                     and line.endswith('.\n')]

    pass_count = pass_count[0]

    print(str(pass_count))

    doc1 = inspect.getsource(TestCircleArea.test_circlearea_with_random_numeric_radius)
    doc2 = inspect.getsource(TestCircleArea.test_circlearea_with_min_radius)
    doc3 = inspect.getsource(TestCircleArea.test_circlearea_with_max_radius)

    assert1_count = len(re.findall(r'assertEqual', doc1))

    print(str(assert1_count))

    assert1_count = len(re.findall(r'assertEqual', doc2))

    print(str(assert1_count))

    assert1_count = len(re.findall(r'assertEqual', doc3))

    print(str(assert1_count))
</code>```

The error I am getting is:

Traceback (most recent call last):
  File "main.py", line 75, in <module>
    pass_count = pass_count[0]
IndexError: list index out of range
```

答:
You can refer to this GitHub file

or

# Define below the class 'Circle' and it's methods.
class Circle:

    def __init__(self, radius):
        # Define the initialization method below
        pattern = re.compile("^\\-?[0-9]")
        if(pattern.match(str(radius))):
            if(radius >= 0 and radius <= 1000):
                self.radius = radius
            else:
                raise ValueError("radius must be between 0 and 1000 inclusive")
        else:
            raise TypeError("radius must be a number")

    def area(self):
        # Define the area functionality below
        return round(((self.radius ** 2) * math.pi),2)

    def circumference(self):
        # Define the circumference functionality below
        return round((self.radius * 2 * math.pi),2)

class TestCircleCircumference(unittest.TestCase):

    def test_circlecircum_with_random_numeric_radius(self):
        # Define a circle 'c1' with radius 2.5 and check if
        # it's circumference is 15.71
        c1= Circle(2.5)
        self.assertEqual(c1.circumference(), 15.71)

    def test_circlecircum_with_min_radius(self):
        # Define a circle 'c2' with radius 0 and check if
        # it's circumference is 0.
        c2= Circle(0)
        self.assertEqual(c2.circumference(), 0)

    def test_circlecircum_with_max_radius(self):
        # Define a circle 'c3' with radius 1000 and check if
        # it's circumference is 6283.19.
        c3= Circle(1000)
        self.assertEqual(c3.circumference(), 6283.19)
```

Body:
I need to write test cases using unit test in Python for testing circle creation.

Define a class Circle with method init which initializes a circle with
attribute radius, having following restrictions.

radius must be numeric value, if not raise type error with error message "radius must be number".

radius must be between 0 to 1000 inclusive on both sides, if not raise the value error with error message "radius must be between 0 and
1000 inclusive"

Define a class method area and circumference which must return values rounded off to 2 decimals.

Complete the definition of class TestingCircleCircumference which
tests the behaviour of circumference  method as specification below.

Define the test method test_circlecircum_with_random_numerical_radius
which creates circle c1 with radius 2.5 and check if its computed
circumference match the value 15.71

Define the test method test_circlecircum_with__min_radius which
creates circle c2 with radius 0 and check if its computed
circumference match the value 0

Define the test method test_circlecircum_with_max_radius  which
creates circle c3 with radius 1000 and check if its computed
circumference match the value 6283.19

My code is:

import inspect
import re
import unittest
import math

class Circle:

    def __init__(self, radius):

        try:
            if not isinstance(radius, (int, float)):
                raise TypeError
            elif 1000 >= radius >= 0:
                self.radius=radius
            else:
                raise ValueError
        except ValueError:
            raise ValueError("radius must be between 0 and 1000 inclusive")
        except TypeError:
            raise TypeError("radius must be a number")

def area(self):

    y = math.pi*(self.radius**2)
    return round(y, 2)

def circumference(self):

    x = math.pi*2*self.radius
    return round(x, 2)

class TestCircleArea(unittest.TestCase):

    def test_circlearea_with_random_numeric_radius(self):

        c1 = Circle(2.5)
        self.assertEqual(c1.area(), 19.63)

    def test_circlearea_with_min_radius(self):

        c2 = Circle(0)
        self.assertEqual(c2.area(), 0)

    def test_circlearea_with_max_radius(self):

        c3 = Circle(1000.1)
        self.assertEqual(c3.area(), 3141592.65)

The below code is generated by the system and I can't edit it. This code is from HackerRank.

if __name__ == '__main__':

    fptr = open('output.txt', 'w')

    runner = unittest.TextTestRunner(fptr)

    unittest.main(testRunner=runner, exit=False)

    fptr.close()

    with open('output.txt') as fp:
        output_lines = fp.readlines()

    pass_count = [len(re.findall(r'\.', line)) for line in output_lines if line.startswith('.')
                     and line.endswith('.\n')]

    pass_count = pass_count[0]

    print(str(pass_count))

    doc1 = inspect.getsource(TestCircleArea.test_circlearea_with_random_numeric_radius)
    doc2 = inspect.getsource(TestCircleArea.test_circlearea_with_min_radius)
    doc3 = inspect.getsource(TestCircleArea.test_circlearea_with_max_radius)

    assert1_count = len(re.findall(r'assertEqual', doc1))

    print(str(assert1_count))

    assert1_count = len(re.findall(r'assertEqual', doc2))

    print(str(assert1_count))

    assert1_count = len(re.findall(r'assertEqual', doc3))

    print(str(assert1_count))

The error I am getting is:

Traceback (most recent call last):
  File "main.py", line 75, in <module>
    pass_count = pass_count[0]
IndexError: list index out of range


问:
vscode prettier doesn't format .tsx file
I've used the Prettier extension in the visual studio code editor for a long time, but recently I have been writing to React with Typescript. So I need to configure for Prettier to format .tsx files.

答:
Update 2023

Create a .vscode folder at the root of your project. In the .vscode folder, create the settings.json file, and in it, write this section:

```<code>{
    "[typescript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },
    "[typescriptreact]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    }
}
</code>```

Don't forget to add .vscode in the .gitignore file.

Body:
Update 2023

Create a .vscode folder at the root of your project. In the .vscode folder, create the settings.json file, and in it, write this section:

{
    "[typescript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },
    "[typescriptreact]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    }
}

Don't forget to add .vscode in the .gitignore file.


问:
Tools to compare two sites structures
Does anyone knows about any tools allowing to compare two almost exactly same websites?

Simply, I have a sandbox site and production site, and would like to find out the difference between them, to know what content to move to production site.

Thanks!

Edit:

Ok, I see I missed a critical piece of information (sorry!). The both sites are online and based on CMS (Drupal), hence I need some crawling tool which would run over the two sites, and show what pages present in sandbox, but not on production.

Thanks for everyone who answered regardless!

答:
Use wget to crawl the sites, the compare the content with some diff tool.

Or, use a diff tool on the script files, and then dump the DBs in a text (csv) files, and compare.

OwnerDisplayName: SyRenity

ContentLicense: CC BY-SA 2.5

Title: Tools to compare two sites structures

LastEditorDisplayName: SyRenity

OwnerDisplayName: Sunny


问:
Can I store data on an Android device to persist between installs?
I want to store a small amount of data in a way where it persists between application installs. I obviously can't use SharedPreferences as they are removes upon uninstallation. Is there any way to store data so it survives a reinstall of the app?

The data I want to store is a unique ID, to allow blocking of users of the app if they misbehave. If I cannot store an ID, can I access the Google account(s) email addresses to use them as an indicator?

This blog post makes it clear none of the IDs the OS produces are any good, especially when considering tablets
Android: Identifying app installations

答:
You can store the data in shared preferences and use a backup manager to have them backed up automatically. They should be restored once the app is reinstalled.

There is no real way of blocking the app for certain persons. You could fore all your users to create an account to use the app and block the accounts but they always can recreate an account. You could store something on the SD-Card and check for it but malicious users can find that and delete it. You could try to get the user to authenticate themselves with their google account against your app (andlytics is using an authentication method like that) but the user can factory reset his phone and create a new google account.

You have to choose how important the blocking of the users is and how much you want to annoy your other users because of some users that are not using your app as intended.


答:
With QUALIFY you can keep the newest per name

```<code>SELECT *
FROM table
QUALIFY row_number() OVER (PARTITION BY name ORDER BY date desc) = 1;
</code>```

As you will see in the doc's it's the same as Tim's answer without the need for the nested select.

Title: Group by name and return row with most recent date

Body:
Suppose you have the following data:

+-------+--------+------------+
| Name  | Rating |    Date    |
+-------+--------+------------+
| Alice |    4.5 | 01/01/2022 |
| Alice |      4 | 14/12/2021 |
| Alice |      4 | 16/05/2021 |
| Mary  |      5 | 05/01/2022 |
| Mary  |      4 | 31/01/2022 |
| Bob   |    3.5 | 03/02/2022 |
+-------+--------+------------+

What would be the best way to group by name and return the row with the most recent date in Snowflake (ANSI SQL)? Expected output:

+-------+--------+------------+
| Name  | Rating |    Date    |
+-------+--------+------------+
| Alice |    4.5 | 01/01/2022 |
| Mary  |      4 | 31/01/2022 |
| Bob   |    3.5 | 03/02/2022 |
+-------+--------+------------+

Body:
With QUALIFY you can keep the newest per name

SELECT *
FROM table
QUALIFY row_number() OVER (PARTITION BY name ORDER BY date desc) = 1;

As you will see in the doc's it's the same as Tim's answer without the need for the nested select.