问:
jquery - change value, and re-read back into second function
How can I update a value using jquery, and then re-read that value back in another function.

Example:
I have two buttons:

```<code><span id="btn1" data-cust="1">BUTTON 1</span>
</br></br>
<span id="btn2">BUTTON2</span>
</code>```

I then have two jquery functions:

```<code>btn1=function()
{
    $('body').on('click','#btn1',function()
    {
        dc=$('#btn1').data('cust'); //get the value of btn1
        alert(dc);                  //Report the value of btn1
        $('#btn1').attr('data-cust',0);  //Change the value of btn1 to 0
    })
}

btn2=function()
{
    $('body').on('click','#btn2',function()
    {
        dc2=$('#btn1').data('cust'); //get the current value of btn1
        alert(dc2);                  //report the current value of btn1
    })
}
</code>```

As you can see, when I press BTN1 it changes the data attribute of #btn1 to 0.

Then I press BTN2, looking to pick up the new value of 0, but instead I get the old value of 1.

I tried using $('#btn1').data('cust',0) but that doesn't change the attribute, or get picked up by the second function.

Is there a way to do this?

答:
You need to be consistent with your use of .data() vs .attr('data', ...). This is because while .data() can read from both jQuery's internal data store AND the HTML5 data- attribute, the .attr('data', ...) method can only read from and write to HTML5 data- attribute.

You shouldn't worry about the HTML5 data- attribute not updating: because .data() does not update it. However, rest assured that it is being stored properly in the object reference. If you want to depend on jQuery's internal data store completely, then use .data() throughout your code:

$('body').on('click', '#btn1', function() {
  dc = $('#btn1').data('cust'); //get the value of btn1
  console.log(dc); //Report the value of btn1
  $('#btn1').data('cust', 0); //Change the value of btn1 to 0
})

$('body').on('click', '#btn2', function() {
  dc2 = $('#btn1').data('cust'); //get the current value of btn1
  console.log(dc2); //report the current value of btn1
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="btn1" data-cust="1">BUTTON 1</span>
<br /><br />
<span id="btn2">BUTTON2</span></code>```

However, if it is important that the data-cust attribute is updated in the DOM (maybe because other plugins or part of your code relies on reading the HTML5 data attribute, then use .attr('data', ...) instead:

$('body').on('click', '#btn1', function() {
  dc = $('#btn1').attr('data-cust'); //get the value of btn1
  console.log(dc); //Report the value of btn1
  $('#btn1').attr('data-cust', 0); //Change the value of btn1 to 0
})

$('body').on('click', '#btn2', function() {
  dc2 = $('#btn1').attr('data-cust'); //get the current value of btn1
  console.log(dc2); //report the current value of btn1
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="btn1" data-cust="1">BUTTON 1</span>
<br /><br />
<span id="btn2">BUTTON2</span></code>```

Body:
How can I update a value using jquery, and then re-read that value back in another function.

Example:
I have two buttons:

BUTTON 1

BUTTON2

I then have two jquery functions:

btn1=function()
{
    $('body').on('click','#btn1',function()
    {
        dc=$('#btn1').data('cust'); //get the value of btn1
        alert(dc);                  //Report the value of btn1
        $('#btn1').attr('data-cust',0);  //Change the value of btn1 to 0
    })
}

btn2=function()
{
    $('body').on('click','#btn2',function()
    {
        dc2=$('#btn1').data('cust'); //get the current value of btn1
        alert(dc2);                  //report the current value of btn1
    })
}

As you can see, when I press BTN1 it changes the data attribute of #btn1 to 0.

Then I press BTN2, looking to pick up the new value of 0, but instead I get the old value of 1.

I tried using $('#btn1').data('cust',0) but that doesn't change the attribute, or get picked up by the second function.

Is there a way to do this?

Body:
You need to be consistent with your use of .data() vs .attr('data', ...). This is because while .data() can read from both jQuery's internal data store AND the HTML5 data- attribute, the .attr('data', ...) method can only read from and write to HTML5 data- attribute.

You shouldn't worry about the HTML5 data- attribute not updating: because .data() does not update it. However, rest assured that it is being stored properly in the object reference. If you want to depend on jQuery's internal data store completely, then use .data() throughout your code:

$('body').on('click', '#btn1', function() {
  dc = $('#btn1').data('cust'); //get the value of btn1
  console.log(dc); //Report the value of btn1
  $('#btn1').data('cust', 0); //Change the value of btn1 to 0
})

$('body').on('click', '#btn2', function() {
  dc2 = $('#btn1').data('cust'); //get the current value of btn1
  console.log(dc2); //report the current value of btn1
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="btn1" data-cust="1">BUTTON 1</span>
<br /><br />
<span id="btn2">BUTTON2</span>

However, if it is important that the data-cust attribute is updated in the DOM (maybe because other plugins or part of your code relies on reading the HTML5 data attribute, then use .attr('data', ...) instead:

$('body').on('click', '#btn1', function() {
  dc = $('#btn1').attr('data-cust'); //get the value of btn1
  console.log(dc); //Report the value of btn1
  $('#btn1').attr('data-cust', 0); //Change the value of btn1 to 0
})

$('body').on('click', '#btn2', function() {
  dc2 = $('#btn1').attr('data-cust'); //get the current value of btn1
  console.log(dc2); //report the current value of btn1
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="btn1" data-cust="1">BUTTON 1</span>
<br /><br />
<span id="btn2">BUTTON2</span>


来源: stackexchange

问:
Clang analyzer potential memory leak - false positive
I have an implementation of static function in my codebase, and while running clang-tidy on it, I noticed that the static analyzer points towards a possible memory leak when I am pretty sure the code is correct. (I have verified it with sanitizers). I think this is most likely due to static analyzers missing some branch statement, but I am not 100% sure.

Here is a slim down version of the code:

#include <array>
#include <functional>
#include <utility>

struct SmallFunction {
  struct Base {
    virtual ~Base() = default;
    virtual void destroy() = 0;
  };

  template <typename T>
  struct Inner : Base {
    Inner(T&& f) : f_(std::move(f)) {}
    void destroy() override { f_.~T(); }
    T f_;
  };

  template <typename T>
  SmallFunction(T&& f) : empty(false) {
    static_assert(sizeof(T) <= 32);
    new (storage) Inner<T>(std::forward<T>(f));
  }

  ~SmallFunction() {
    if (!empty) {
      reinterpret_cast<Base*>(storage)->destroy();
    }
  }

  bool empty = true;
  alignas(8) char storage[40];  // 32 + 8
};

int main() {
  std::array<char, 64> large;
  auto lambda = [large] {};
  std::function<void()> f = lambda;
  SmallFunction sf = std::move(f);
}
```

<p>Here is the clang-tidy analysis:</p>

```/home/ce/example.cpp:39:1: warning: Potential memory leak [clang-analyzer-cplusplus.NewDeleteLeaks]
}
^
/home/ce/example.cpp:37:29: note: Calling constructor for 'function<void ()>'
  std::function<void()> f = lambda;
                            ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:675:2: note: Taking true branch
        if (_My_handler::_M_not_empty_function(__f))
        ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:677:6: note: Calling '_Base_manager::_M_init_functor'
            _My_handler::_M_init_functor(_M_functor, std::move(__f));
            ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:223:4: note: Calling '_Base_manager::_M_init_functor'
        { _M_init_functor(__functor, std::move(__f), _Local_storage()); }
          ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:252:39: note: Memory is allocated
        { __functor._M_access<_Functor*>() = new _Functor(std::move(__f)); }
                                             ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:223:4: note: Returned allocated memory
        { _M_init_functor(__functor, std::move(__f), _Local_storage()); }
          ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:677:6: note: Returned allocated memory
            _My_handler::_M_init_functor(_M_functor, std::move(__f));
            ^
/home/ce/example.cpp:37:29: note: Returning from constructor for 'function<void ()>'
  std::function<void()> f = lambda;
                            ^
/home/ce/example.cpp:39:1: note: Potential memory leak
}
^
1 warning generated.
```

Here is godbolt link with clang-tidy enabled.

答:
The reporting from clang-tidy is definitely a bit weird and could use some clarification.

It's upset about the placement-new of Inner<T> without seeing a matching explicit destructor call.  You have this strange destroy() method that isn't even necessary since the Base destructor is virtual and the implicit Inner destructor will clean up Inner::f_.

This is trivially fixed in the following ways:

Replace bool SmallFunction::empty with Base *SmallFunction::value and store the result of the placement-new in it. (This is not strictly necessary, but I find the code flows better without requiring the reinterpret_cast, and it's easier to get right since the compiler can type-check.)

In SmallFunction::~SmallFunction, replace the destroy call with value->~Base().

Remove the destroy() method; it's not needed.

This satisfies clang-tidy (see here).

I don't think there was a memory leak, but there was an object (the Inner<T>) that was constructed and never destructed. There is no consequence that I can see, but it doesn't hurt to do things the right way -- and it makes the job of static analyzers easier, anyway.

ContentLicense: CC BY-SA 4.0

Body:
I have an implementation of static function in my codebase, and while running clang-tidy on it, I noticed that the static analyzer points towards a possible memory leak when I am pretty sure the code is correct. (I have verified it with sanitizers). I think this is most likely due to static analyzers missing some branch statement, but I am not 100% sure.

Here is a slim down version of the code:

#include <array>
#include <functional>
#include <utility>

struct SmallFunction {
  struct Base {
    virtual ~Base() = default;
    virtual void destroy() = 0;
  };

  template <typename T>
  struct Inner : Base {
    Inner(T&& f) : f_(std::move(f)) {}
    void destroy() override { f_.~T(); }
    T f_;
  };

  template <typename T>
  SmallFunction(T&& f) : empty(false) {
    static_assert(sizeof(T) <= 32);
    new (storage) Inner<T>(std::forward<T>(f));
  }

  ~SmallFunction() {
    if (!empty) {
      reinterpret_cast<Base*>(storage)->destroy();
    }
  }

  bool empty = true;
  alignas(8) char storage[40];  // 32 + 8
};

int main() {
  std::array<char, 64> large;
  auto lambda = [large] {};
  std::function<void()> f = lambda;
  SmallFunction sf = std::move(f);
}

Here is the clang-tidy analysis:

/home/ce/example.cpp:39:1: warning: Potential memory leak [clang-analyzer-cplusplus.NewDeleteLeaks]
}
^
/home/ce/example.cpp:37:29: note: Calling constructor for 'function<void ()>'
  std::function<void()> f = lambda;
                            ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:675:2: note: Taking true branch
        if (_My_handler::_M_not_empty_function(__f))
        ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:677:6: note: Calling '_Base_manager::_M_init_functor'
            _My_handler::_M_init_functor(_M_functor, std::move(__f));
            ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:223:4: note: Calling '_Base_manager::_M_init_functor'
        { _M_init_functor(__functor, std::move(__f), _Local_storage()); }
          ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:252:39: note: Memory is allocated
        { __functor._M_access<_Functor*>() = new _Functor(std::move(__f)); }
                                             ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:223:4: note: Returned allocated memory
        { _M_init_functor(__functor, std::move(__f), _Local_storage()); }
          ^
/opt/compiler-explorer/gcc-9.2.0/lib/gcc/x86_64-linux-gnu/9.2.0/../../../../include/c++/9.2.0/bits/std_function.h:677:6: note: Returned allocated memory
            _My_handler::_M_init_functor(_M_functor, std::move(__f));
            ^
/home/ce/example.cpp:37:29: note: Returning from constructor for 'function<void ()>'
  std::function<void()> f = lambda;
                            ^
/home/ce/example.cpp:39:1: note: Potential memory leak
}
^
1 warning generated.

Here is godbolt link with clang-tidy enabled.


问:
Given a function object, how do I find its name and module?
Given a function object f, how do I find:

Function's name.

Module(s) of its method(s)?

In Julia 0.4 I was able to find name using f.env.name, but no tips for module. For Julia 0.5 I wasn't able to find any of two.

答:
In Julia 1.x the commands are:

Base.nameof

Base.parentmodule

Since this two methods are exported, also nameof and parentmodule works.

ContentLicense: CC BY-SA 3.0


问:
Keras: Generator runs out of data when starting second epoch
I have the following generator:

```<code>def customGenerator(generator, indexes):

    for i in indexes:
        x,y = generator[i]
        yield (np.squeeze(x),
                {'outputsA': y[:,4:6], 'outputsB': y[:,11:],
                'outputsC': y[:,10]} )
</code>```

and then lines to train the model (I am omitting some lines that are unrelated to the problem):

```<code>randomize = np.arange( len(generator) )
np.random.shuffle(randomize)
trainLimit = int( 0.9*len(generator) )

model.fit(x = customGenerator(generator, randomize[:trainLimit]), y = None,
    validation_data = customGenerator(generator, randomize[trainLimit:]),
    epochs=1000, steps_per_epoch = trainLimit)
</code>```

Setting steps_per_epoch to None (or just removing this argument) produces the same error.

This code works well during the first epoch, but then when starting the second epoch it says it ran out of data:

```<code>Epoch 1/1000
2534/2534 [==============================] - 1124s 443ms/step - loss: 20.3274 - outputsA_loss: 8.2611 - outputsB_loss: 11.8572 - outputsC_loss: 0.2091 - val_loss: 11.4947 - val_outputsA_loss
: 3.3958 - val_outputsB_loss: 7.9044 - val_outputsC_loss: 0.1945
Epoch 2/1000
WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 2534000
 batches). You may need to use the repeat() function when building your dataset.
</code>```

This warning is not just a warning, it stops the execution completely.

it seems that it only runs through the generator once, while I thought it would re-start the generator each epoch.

I don't really know how to do this.

I could create an input array which is the original data repeated 1000 times, but this would use a lot of memory, and there has to be a way to tell it to re-start the generator in every iteration, but I don't know how.

答:
The generator stops at the end of the for loop. To simply repeat the data, wrap the for loop in a while loop:</p>

```<code>def customGenerator(generator, indexes):

    while True:

        indexes = np.random.shuffle(indexes) # reshuffle every new epoch

        for i in indexes:
            x,y = generator[i]
            yield (np.squeeze(x),
                    {'outputsA': y[:,4:6], 'outputsB': y[:,11:],
                    'outputsC': y[:,10]} )
</code>```

Body:
I have the following generator:

def customGenerator(generator, indexes):

    for i in indexes:
        x,y = generator[i]
        yield (np.squeeze(x),
                {'outputsA': y[:,4:6], 'outputsB': y[:,11:],
                'outputsC': y[:,10]} )

and then lines to train the model (I am omitting some lines that are unrelated to the problem):

randomize = np.arange( len(generator) )
np.random.shuffle(randomize)
trainLimit = int( 0.9*len(generator) )

model.fit(x = customGenerator(generator, randomize[:trainLimit]), y = None,
    validation_data = customGenerator(generator, randomize[trainLimit:]),
    epochs=1000, steps_per_epoch = trainLimit)

Setting steps_per_epoch to None (or just removing this argument) produces the same error.

This code works well during the first epoch, but then when starting the second epoch it says it ran out of data:

Epoch 1/1000
2534/2534 [==============================] - 1124s 443ms/step - loss: 20.3274 - outputsA_loss: 8.2611 - outputsB_loss: 11.8572 - outputsC_loss: 0.2091 - val_loss: 11.4947 - val_outputsA_loss
: 3.3958 - val_outputsB_loss: 7.9044 - val_outputsC_loss: 0.1945
Epoch 2/1000
WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 2534000
 batches). You may need to use the repeat() function when building your dataset.

This warning is not just a warning, it stops the execution completely.

it seems that it only runs through the generator once, while I thought it would re-start the generator each epoch.

I don't really know how to do this.

I could create an input array which is the original data repeated 1000 times, but this would use a lot of memory, and there has to be a way to tell it to re-start the generator in every iteration, but I don't know how.

Body:
The generator stops at the end of the for loop. To simply repeat the data, wrap the for loop in a while loop:

def customGenerator(generator, indexes):

    while True:

        indexes = np.random.shuffle(indexes) # reshuffle every new epoch

        for i in indexes:
            x,y = generator[i]
            yield (np.squeeze(x),
                    {'outputsA': y[:,4:6], 'outputsB': y[:,11:],
                    'outputsC': y[:,10]} )


问:
How to render components that rely on firebase async functions?
I'm unable to have my component render the value from events[0].  I've tried putting the data array in the .then block but the scoping gets screwed up. Since firebase requests are async, how can I make the whole component render only when I receive my data from firebase?

Finalized.js

```<code>const Finalized = () => {
  let events = [];
  firebase
    .database()
    .ref("events/arts/" + 2 + "/name")
    .once("value")
    .then((snapshot) => {
      events.push(snapshot.val());
    });
  let data = [{
      time: "09:00",
      title: "Event 1",
      description: <Text>{events[0]}</Text>,  // {events[0]} has no value returned
    }];
  return (
    <View style={styles.container}>
      <Timeline style={styles.list} data={data} />
    </View>
  );
};
</code>```

答:
You can use a state called events instead of the variable.

Here is how to do it...

```<code>const [events, setEvents] = useState([]);

const Finalized = () => {
  firebase
    .database()
    .ref("events/arts/" + 2 + "/name")
    .once("value")
    .then((snapshot) => {
      setEvents(snapshot.val());
    });
  let data = [{
      time: "09:00",
      title: "Event 1",
      description: <Text>{events[0]}</Text>,
    }];
  return (
    <View style={styles.container}>
      <Timeline style={styles.list} data={data} />
    </View>
  );
};
</code>```

Body:
I'm unable to have my component render the value from events[0].  I've tried putting the data array in the .then block but the scoping gets screwed up. Since firebase requests are async, how can I make the whole component render only when I receive my data from firebase?

Finalized.js

const Finalized = () => {
  let events = [];
  firebase
    .database()
    .ref("events/arts/" + 2 + "/name")
    .once("value")
    .then((snapshot) => {
      events.push(snapshot.val());
    });
  let data = [{
      time: "09:00",
      title: "Event 1",
      description: <Text>{events[0]}</Text>,  // {events[0]} has no value returned
    }];
  return (
    <View style={styles.container}>
      <Timeline style={styles.list} data={data} />
    </View>
  );
};

Body:
You can use a state called events instead of the variable.

Here is how to do it...

const [events, setEvents] = useState([]);

const Finalized = () => {
  firebase
    .database()
    .ref("events/arts/" + 2 + "/name")
    .once("value")
    .then((snapshot) => {
      setEvents(snapshot.val());
    });
  let data = [{
      time: "09:00",
      title: "Event 1",
      description: <Text>{events[0]}</Text>,
    }];
  return (
    <View style={styles.container}>
      <Timeline style={styles.list} data={data} />
    </View>
  );
};


问:
How to cut 25% of image from each side
I'm trying to find a way to cut 25% from each side of the image.
I was trying with this cutted_data = data[1:645,1:645] but it's not what I'm looking for.

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img

image_name = 'image.jpg'

data = plt.imread('image.jpg')
cutted_data = data[...?]

print(data)
print(np.shape(data))

plt.subplot(231)
plt.imshow(data)
plt.axis('off')
plt.title('Obraz w naturalnych kolorach')

plt.subplot(234)
plt.imshow(cutted_data)
plt.axis('off')
plt.title('Przycięty obraz')

plt.show()
</code>```

答:
You can try:</p>

```<code>data = plt.imread('image.jpg')
rows, cols = data.shape[:2]
cut_data = data[rows//4:-rows//4, cols//4:-cols//4]
</code>```

Title: How to cut 25% of image from each side

Body:
I'm trying to find a way to cut 25% from each side of the image.
I was trying with this cutted_data = data[1:645,1:645] but it's not what I'm looking for.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img

image_name = 'image.jpg'

data = plt.imread('image.jpg')
cutted_data = data[...?]

print(data)
print(np.shape(data))

plt.subplot(231)
plt.imshow(data)
plt.axis('off')
plt.title('Obraz w naturalnych kolorach')

plt.subplot(234)
plt.imshow(cutted_data)
plt.axis('off')
plt.title('Przycięty obraz')

plt.show()

Body:
You can try:

data = plt.imread('image.jpg')
rows, cols = data.shape[:2]
cut_data = data[rows//4:-rows//4, cols//4:-cols//4]


问:
Why do I get unexpected behavior in Python isinstance after pickling?
Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:

```<code>from __future__ import with_statement
import pickle

# Simple class definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Create an instance of the class
x = myclass(100)

# Pickle the instance to a file
with open("c:\\pickletest.dat", "wb") as f:
    pickle.dump(x, f)

# Replace class with exact same definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Read an object from the pickled file
with open("c:\\pickletest.dat", "rb") as f:
    x2 = pickle.load(f)

# The class names appear to match
print x.__class__
print x2.__class__

# Uh oh, this fails...(why?)
assert isinstance(x2, x.__class__)
</code>```

Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine.

答:
This is how the unpickler works (site-packages/pickle.py):

```<code>def find_class(self, module, name):
    # Subclasses may override this
    __import__(module)
    mod = sys.modules[module]
    klass = getattr(mod, name)
    return klass
</code>```

To find and instantiate a class.

So of course if you replace a class with an identically named class, the klass = getattr(mod, name) will return the new class, and the instance will be of the new class, and so isinstance will fail.

OwnerDisplayName: Ben Hoffstein

ContentLicense: CC BY-SA 2.5

Body:
Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:

from __future__ import with_statement
import pickle

# Simple class definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Create an instance of the class
x = myclass(100)

# Pickle the instance to a file
with open("c:\\pickletest.dat", "wb") as f:
    pickle.dump(x, f)

# Replace class with exact same definition
class myclass(object):
    def __init__(self, data):
        self.data = data

# Read an object from the pickled file
with open("c:\\pickletest.dat", "rb") as f:
    x2 = pickle.load(f)

# The class names appear to match
print x.__class__
print x2.__class__

# Uh oh, this fails...(why?)
assert isinstance(x2, x.__class__)

Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine.

LastEditorDisplayName: Rich B

Body:
This is how the unpickler works (site-packages/pickle.py):

def find_class(self, module, name):
    # Subclasses may override this
    __import__(module)
    mod = sys.modules[module]
    klass = getattr(mod, name)
    return klass

To find and instantiate a class.

So of course if you replace a class with an identically named class, the klass = getattr(mod, name) will return the new class, and the instance will be of the new class, and so isinstance will fail.

OwnerDisplayName: Ali A


问:
Testing "HTML fixtures" with RSpec and rails
I have a web scraper built to parse html from a website and I'm trying to write tests for it.

The class I'm trying to test receives a Nokogiri HTML object and extracts the required data from it. Now as usual the html can vary, sometimes elements will be missing or whatnot. I need to test these different situations.

So what I'd like to do is make a bunch of html files, each one representing a case with a particular element missing etc. For each html file, I wish to also construct an associated hash of the data I would expect the scraper to extract, assuming it is working correctly.

So I would like to write a test which will iterate over these html files and compare the data extracted by the class being tested against the expected data and report whether or not it is correct.

Any suggestions as to how to do this?

答: Have a look at the Artifice, fakeweb or webmock gems, which override net/http in order to supply testable results.</p>


问:
Loading Bar For Pdf.js
I want to create a loading bar for pdf.js so the user can monitor how far along pdf.js is with downloading a pdf document to be rendered. My app is run in through gwt, with the pdf.js pdf reader, although I don't think this question has much to do with gwt. In the pdf.js code, there is an bject called progressCallback, which should give me the total amount of data in the pdf to be rendered, and the amount that has been loaded. It's used in methods such as getDocument i.e.

```<code>PDFJS.getDocument = function getDocument(source,
                                     pdfDataRangeTransport,
                                     passwordCallback,
                                     progressCallback) {
</code>```

here is another method that utilizes it, and shows how it is used

```<code>messageHandler.on('DocProgress', function transportDocProgress(data) {
    if (this.progressCallback) {
      this.progressCallback({
        loaded: data.loaded,
        total: data.total
      });
</code>```

I was wondering how I would use progressCallback. I can't find a way to access the loaded variable sucesfully. So far, amongst other things, I have tried setting alert windows with the value of progressCallback.loaded and it hasn't worked. Any suggestions for how to make a progressBar using this progressCallback variable? Thanks in advance!

答:
Try this way

```<code>//load document
var loadingTask = pdf.getDocument(src);

//get progress data
loadingTask.onProgress = function(data){
   console.log( "loaded : " + data.loaded" )
   console.log( "total : " + data.total ")
}

//use document
loadingTask.promise.then( function (pdf){
   //do anything with pdf
}
</code>```

hope it gonna work

Title: Loading Bar For Pdf.js

Body:
I want to create a loading bar for pdf.js so the user can monitor how far along pdf.js is with downloading a pdf document to be rendered. My app is run in through gwt, with the pdf.js pdf reader, although I don't think this question has much to do with gwt. In the pdf.js code, there is an bject called progressCallback, which should give me the total amount of data in the pdf to be rendered, and the amount that has been loaded. It's used in methods such as getDocument i.e.

PDFJS.getDocument = function getDocument(source,
                                     pdfDataRangeTransport,
                                     passwordCallback,
                                     progressCallback) {

here is another method that utilizes it, and shows how it is used

messageHandler.on('DocProgress', function transportDocProgress(data) {
    if (this.progressCallback) {
      this.progressCallback({
        loaded: data.loaded,
        total: data.total
      });

I was wondering how I would use progressCallback. I can't find a way to access the loaded variable sucesfully. So far, amongst other things, I have tried setting alert windows with the value of progressCallback.loaded and it hasn't worked. Any suggestions for how to make a progressBar using this progressCallback variable? Thanks in advance!

Body:
Try this way

//load document
var loadingTask = pdf.getDocument(src);

//get progress data
loadingTask.onProgress = function(data){
   console.log( "loaded : " + data.loaded" )
   console.log( "total : " + data.total ")
}

//use document
loadingTask.promise.then( function (pdf){
   //do anything with pdf
}

hope it gonna work


问:
how to download base64 string as pdf in IE version 11 & same for mozilla firefox
I want to download base64 string as pdf in internet explorer browser version 11

  var data = "Base 64 string";
                var fileName = "MyFile.pdf";
                //For IE using atob convert base64 encoded data to byte array
                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    debugger; // shows something wrong in downloading the file(error in downloading pdf)
                    var byteCharacters = atob(data);
                    var byteNumbers = new Array(byteCharacters.length);
                    for (var i = 0; i < byteCharacters.length; i++) {
                        byteNumbers[i] = byteCharacters.charCodeAt(i);
                    }
                    var byteArray = new Uint8Array(byteNumbers);
                    var blob = new Blob([byteArray], { type: 'application/pdf' });
                    window.navigator.msSaveOrOpenBlob(blob, fileName);
                } else {
                    debugger; // this code works for chrome(pdf downloaded successfully)
                       let a = document.createElement("a");
                       a.href = "data:application/octet-stream;base64," + result.data.data;
                    a.download = "MyFile.pdf";
                       a.click();
                }```

else part works fine for chrome browser,but not working for internet explorer browser(v11) i got the pop up to save file in IE but then i got error message file couldn't  be downloaded any help is appreciated

答:
You can check following code it's working for IE 11 and other browsers.</p>

```<code> function downloadFile(pdfBase64, fileName) {
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    var byteCharacters = atob(pdfBase64);
    var byteNumbers = new Array(byteCharacters.length);
    for (var i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    var byteArray = new Uint8Array(byteNumbers);
    var blob = new Blob([byteArray], { type: 'application/pdf' });
    window.navigator.msSaveOrOpenBlob(blob, fileName);
    return;
}

// For Other Browsers
const linkSource = 'data:application/pdf;base64,' + pdfBase64;
const link = document.createElement('a');
link.href = linkSource;
link.download = fileName;
document.body.appendChild(link);
link.click();
link.remove();

window.addEventListener("focus", function () {
    URL.revokeObjectURL(link.href);
}, { once: true });}
</code>```

Body:
I want to download base64 string as pdf in internet explorer browser version 11

  var data = "Base 64 string";
                var fileName = "MyFile.pdf";
                //For IE using atob convert base64 encoded data to byte array
                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    debugger; // shows something wrong in downloading the file(error in downloading pdf)
                    var byteCharacters = atob(data);
                    var byteNumbers = new Array(byteCharacters.length);
                    for (var i = 0; i < byteCharacters.length; i++) {
                        byteNumbers[i] = byteCharacters.charCodeAt(i);
                    }
                    var byteArray = new Uint8Array(byteNumbers);
                    var blob = new Blob([byteArray], { type: 'application/pdf' });
                    window.navigator.msSaveOrOpenBlob(blob, fileName);
                } else {
                    debugger; // this code works for chrome(pdf downloaded successfully)
                       let a = document.createElement("a");
                       a.href = "data:application/octet-stream;base64," + result.data.data;
                    a.download = "MyFile.pdf";
                       a.click();
                }

else part works fine for chrome browser,but not working for internet explorer browser(v11) i got the pop up to save file in IE but then i got error message file couldn't  be downloaded any help is appreciated

Body:
You can check following code it's working for IE 11 and other browsers.

 function downloadFile(pdfBase64, fileName) {
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    var byteCharacters = atob(pdfBase64);
    var byteNumbers = new Array(byteCharacters.length);
    for (var i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    var byteArray = new Uint8Array(byteNumbers);
    var blob = new Blob([byteArray], { type: 'application/pdf' });
    window.navigator.msSaveOrOpenBlob(blob, fileName);
    return;
}

// For Other Browsers
const linkSource = 'data:application/pdf;base64,' + pdfBase64;
const link = document.createElement('a');
link.href = linkSource;
link.download = fileName;
document.body.appendChild(link);
link.click();
link.remove();

window.addEventListener("focus", function () {
    URL.revokeObjectURL(link.href);
}, { once: true });}


问:
Google Cloud Run fails to listen even after changing port to 8080
I am having some issues deploying to Cloud Run lately. When I am trying to deploy the below Dockerfile to Cloud Run, it ends up with the error Failed to start and then listen on the port defined by the PORT environment variable.:

```<code>FROM phpmyadmin/phpmyadmin:latest

EXPOSE 8080

RUN sed -i 's/80/${PORT}/g' /etc/apache2/sites-available/000-default.conf /etc/apache2/ports.conf

ENTRYPOINT [ "/docker-entrypoint.sh" ]

CMD [ "apache2-foreground" ]
</code>```

The ENTRYPOINT and CMD were added separately even though the phpmyadmin/phpmyadmin:latest uses this same ENTRYPOINT and CMD to see if that would solve it, though it is not required. The same Docker image when deployed using docker run runs properly and listens on port 8080. Is there something I am doing wrong?

This is the command I use to deploy:

```<code>gcloud run deploy phpmyadmin --memory=1Gi --platform=managed \
--allow-unauthenticated --add-cloudsql-instances project_id:us-central1:db-name \
--region=us-central1 --image gcr.io/project_id/phpmyadmin:1.3 \
--update-env-vars PMA_HOST=localhost,PMA_SOCKET="/cloudsql/project_id:us-central1:db-name",PMA_ABSOLUTE_URI=phpmyadmin.domain.com
</code>```

This is all I can find in the logs. (Have redacted some data):

https://gist.github.com/shanukk27/9dd4b3076c55307bd6e853a76e7a34e0

答:
Cloud Run runtime environment seems to be slightly different than Docker run command. You can't use ENTRYPOINT and CMD in the same time

```<code>ENTRYPOINT [ "/docker-entrypoint.sh" ]

CMD [ "apache2-foreground" ]
</code>```

It works with Docker Run (Why? Docker issue? Docker feature?) and not on Cloud Run (missing feature? bug?).

Use only one of them, for example:

```<code>ENTRYPOINT /docker-entrypoint.sh && apache2-foreground
</code>```

EDIT

A strange remark shared by Shanu is the 2 command works with Wordpress deployment, and doesn't work here.

```<code>FROM wordpress:5.3.2-php7.3-apache

EXPOSE 8080

# Copy custom entrypoint from repo
COPY cloud-run-entrypoint.sh /usr/local/bin/

# Change apache listening port and set permission for docker entrypoint
RUN sed -i 's/80/${PORT}/g' /etc/apache2/sites-available/000-default.conf /etc/apache2/ports.conf && \
chmod +x /usr/local/bin/cloud-run-entrypoint.sh

# Wordpress conf
COPY wordpress/. /var/www/html/

# Custom entrypoint
ENTRYPOINT ["cloud-run-entrypoint.sh","docker-entrypoint.sh"]

# Start apache when docker container starts
CMD ["apache2-foreground"]
</code>```

The problem is solved here, but the reason is not clear

Note to Googler (Steren? Ahmet?): Can you share more details on this behavior?

Body:
I am having some issues deploying to Cloud Run lately. When I am trying to deploy the below Dockerfile to Cloud Run, it ends up with the error Failed to start and then listen on the port defined by the PORT environment variable.:

FROM phpmyadmin/phpmyadmin:latest

EXPOSE 8080

RUN sed -i 's/80/${PORT}/g' /etc/apache2/sites-available/000-default.conf /etc/apache2/ports.conf

ENTRYPOINT [ "/docker-entrypoint.sh" ]

CMD [ "apache2-foreground" ]

The ENTRYPOINT and CMD were added separately even though the phpmyadmin/phpmyadmin:latest uses this same ENTRYPOINT and CMD to see if that would solve it, though it is not required. The same Docker image when deployed using docker run runs properly and listens on port 8080. Is there something I am doing wrong?

This is the command I use to deploy:

gcloud run deploy phpmyadmin --memory=1Gi --platform=managed \
--allow-unauthenticated --add-cloudsql-instances project_id:us-central1:db-name \
--region=us-central1 --image gcr.io/project_id/phpmyadmin:1.3 \
--update-env-vars PMA_HOST=localhost,PMA_SOCKET="/cloudsql/project_id:us-central1:db-name",PMA_ABSOLUTE_URI=phpmyadmin.domain.com

This is all I can find in the logs. (Have redacted some data):

https://gist.github.com/shanukk27/9dd4b3076c55307bd6e853a76e7a34e0

Body:
Cloud Run runtime environment seems to be slightly different than Docker run command. You can't use ENTRYPOINT and CMD in the same time

ENTRYPOINT [ "/docker-entrypoint.sh" ]

CMD [ "apache2-foreground" ]

It works with Docker Run (Why? Docker issue? Docker feature?) and not on Cloud Run (missing feature? bug?).

Use only one of them, for example:

ENTRYPOINT /docker-entrypoint.sh && apache2-foreground

EDIT

A strange remark shared by Shanu is the 2 command works with Wordpress deployment, and doesn't work here.

FROM wordpress:5.3.2-php7.3-apache

EXPOSE 8080

# Copy custom entrypoint from repo
COPY cloud-run-entrypoint.sh /usr/local/bin/

# Change apache listening port and set permission for docker entrypoint
RUN sed -i 's/80/${PORT}/g' /etc/apache2/sites-available/000-default.conf /etc/apache2/ports.conf && \
chmod +x /usr/local/bin/cloud-run-entrypoint.sh

# Wordpress conf
COPY wordpress/. /var/www/html/

# Custom entrypoint
ENTRYPOINT ["cloud-run-entrypoint.sh","docker-entrypoint.sh"]

# Start apache when docker container starts
CMD ["apache2-foreground"]

The problem is solved here, but the reason is not clear

Note to Googler (Steren? Ahmet?): Can you share more details on this behavior?


问:
Connection url not visible while creating xa datasource mysql using Teiid
I am trying to create a mysql xa datasource, but am unable to mention connection url properties in it. I have used property names such as "URL" and "connection-url", but the property is not visible in datasource.

Also when I explicitly make a property tag in datasource for the url, it is working, but not when I am creating it through Admin Api,

I need the connection url to be set for the datasource, for using mysql connection arguments such as "rewriteBatchedStatements=true"

答: I got to find a way to set connection url in xa-datasource. It is by setting a property called "connection-properties", and the value will be "URL=". It works for mysql and sqlserver xa datasources as far as I have checked.</p>


问:
How do I rerun a static integer array?
here's the array I want to rerun:

```<code>public static int[] rollDice(int dice[]) {
    // generate 5 random numbers / update dice array
    for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }

    return dice;
}
</code>```

If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.

答:
You would have to have a class member like this:

public static final int[] dice = new int[5];
```

<p>Then to roll/reroll the dice use your method, else just access <code>dice</code>.</p>

<pre class="lang-java prettyprint-override"><code>public static void rollDice() {
    // generate 5 random numbers / update dice array
    for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }
}
</code>```

Interesting fact: Java has no static function variables as C and C++ does. In those languages it could look like this:
(I wrote it like a java Function for you Java guys)

```<code>public static int[5] rollDice(boolean reroll) {
    static final int[] dice = new int[5];
    if (reroll) for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }
    return dice;
}
</code>```

As you can see, static variables can be embedded into those functions. If you ask me, it's a huge minus, Java doesn't support this as I use it all the time to hide those from the class namespace.

Title: How do I rerun a static integer array?

Body:
here's the array I want to rerun:

public static int[] rollDice(int dice[]) {
    // generate 5 random numbers / update dice array
    for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }

    return dice;
}

If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.

Body:
You would have to have a class member like this:

public static final int[] dice = new int[5];

Then to roll/reroll the dice use your method, else just access dice.

public static void rollDice() {
    // generate 5 random numbers / update dice array
    for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }
}

Interesting fact: Java has no static function variables as C and C++ does. In those languages it could look like this:
(I wrote it like a java Function for you Java guys)

public static int[5] rollDice(boolean reroll) {
    static final int[] dice = new int[5];
    if (reroll) for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }
    return dice;
}

As you can see, static variables can be embedded into those functions. If you ask me, it's a huge minus, Java doesn't support this as I use it all the time to hide those from the class namespace.


问:
How to delete a row in cassandra materialiezed view?
I have a cassadra namespace with a table and a materialized view from it.
A row got deleted in the base table but the change was not propagated to the materialized view. I don't know the exact reason why this happend.

So now I am stuck with that row in the MV and I am not able to delete it.
Any ideas?

答:
Yeah, materialized views are still very much broken.  The two main problems are:

There isn't a way to know when a MV is out of sync.

Once it's out of sync, there really isn't a way to get it back in sync.

So it sounds like you're past point #1.

There is a nodetool rebuild_view command, but it does not clear-out existing data, which is what you would need.

Unfortunately, I think the only path forward is to DROP the view and re-create it.


问:
How can I make sure TCL doesn't mess up the order of array elements?
The problem is that the order in which I "insert" elements in an array changes throughout the execution of the script.

Here is a quick reproduction of the problem:

```<code>#!/bin/bash
# : \
exec /home/binops/afse/eer/eer_SPI-7.3.1/tclsh "$0" "$@"

proc myProc { theArray } {
  upvar $theArray theArrayInside
  parray theArrayInside
  puts "------"
  foreach { key value } [array get theArrayInside] {
    puts "$key => $value"
  }
}

# MAIN
set myArray(AQHI) AQHI
set myArray(O3) 1
set myArray(NO2) 2
set myArray(PM2.5) 3

parray myArray
puts "------"
myProc myArray
</code>```

Output is:

```<code>myArray(AQHI)  = AQHI
myArray(NO2)   = 2
myArray(O3)    = 1
myArray(PM2.5) = 3
------
theArrayInside(AQHI)  = AQHI
theArrayInside(NO2)   = 2
theArrayInside(O3)    = 1
theArrayInside(PM2.5) = 3
------
PM2.5 => 3
O3 => 1
NO2 => 2
AQHI => AQHI
</code>```

Notice I didn't use generic keys like A, B, C and generic values like 1, 2, 3, as you may have expected. This is because the order isn't messed up with these generic keys/values. Maybe this can help identify the problem.

Also notice that the initial order (AQHI, O3, NO2, PM2.5) is lost even at the first call to parray (order is now AQHI, NO2, O3, PM2.5; alphabetically sorted?). It is then changed again upon calling array get ... (inversed?)

So anyways, the question is: How can I make sure the initial order is kept?

答:
You're making the mistake of equating Tcl arrays to those in a language like C, where it's a list of elements. Instead, Tcl arrays are maps (from a key to a value) like a HashMap in Java, and the order of elements is not preserved.

You may be better off using a list (if you just have a number of items you need to store in order).

If you're using 8.5 or higher, a dict if you actually have a mapping of keys to values, since dictionaries are order preserving maps. There are dict backports to Tcl versions before 8.5, but I'm not sure whether they preserve order (and they're slower).

If you can't use 8.5 dicts and need key/value pairs, one option is to use a list of key value pairs and then use lsearch to pull out the values you need

```<code>> set mylist {{key1 value1} {key2 value2} {key3 value3}}
> lsearch -index 0 $mylist key2
0
> lindex $mylist [list [lsearch -index 0 $mylist key2] 1]
> value2
> proc kv_lookup {dictList key} {
      set index [lsearch -index 0 $dictList $key]
      if {$index < 0} {
          error "Key '$key' not found in list $dictList"
      }
      return [lindex $dictList [list $index 1]]
  }
> kv_lookup $mylist key2
value2
</code>```

Man pages for 8.4 are here

You may also want to look at this page on keyed lists for Tcl. It implements what I mentioned above, plus some other useful commands.

For an example of the different between an ordered "map" and an unordered one, you can take a look at the two java classes HashMap (unordered) and LinkedHashMap (ordered).

Body:
The problem is that the order in which I "insert" elements in an array changes throughout the execution of the script.

Here is a quick reproduction of the problem:

#!/bin/bash
# : \
exec /home/binops/afse/eer/eer_SPI-7.3.1/tclsh "$0" "$@"

proc myProc { theArray } {
  upvar $theArray theArrayInside
  parray theArrayInside
  puts "------"
  foreach { key value } [array get theArrayInside] {
    puts "$key => $value"
  }
}

# MAIN
set myArray(AQHI) AQHI
set myArray(O3) 1
set myArray(NO2) 2
set myArray(PM2.5) 3

parray myArray
puts "------"
myProc myArray

Output is:

myArray(AQHI)  = AQHI
myArray(NO2)   = 2
myArray(O3)    = 1
myArray(PM2.5) = 3
------
theArrayInside(AQHI)  = AQHI
theArrayInside(NO2)   = 2
theArrayInside(O3)    = 1
theArrayInside(PM2.5) = 3
------
PM2.5 => 3
O3 => 1
NO2 => 2
AQHI => AQHI

Notice I didn't use generic keys like A, B, C and generic values like 1, 2, 3, as you may have expected. This is because the order isn't messed up with these generic keys/values. Maybe this can help identify the problem.

Also notice that the initial order (AQHI, O3, NO2, PM2.5) is lost even at the first call to parray (order is now AQHI, NO2, O3, PM2.5; alphabetically sorted?). It is then changed again upon calling array get ... (inversed?)

So anyways, the question is: How can I make sure the initial order is kept?

Body:
You're making the mistake of equating Tcl arrays to those in a language like C, where it's a list of elements. Instead, Tcl arrays are maps (from a key to a value) like a HashMap in Java, and the order of elements is not preserved.

You may be better off using a list (if you just have a number of items you need to store in order).

If you're using 8.5 or higher, a dict if you actually have a mapping of keys to values, since dictionaries are order preserving maps. There are dict backports to Tcl versions before 8.5, but I'm not sure whether they preserve order (and they're slower).

If you can't use 8.5 dicts and need key/value pairs, one option is to use a list of key value pairs and then use lsearch to pull out the values you need

> set mylist {{key1 value1} {key2 value2} {key3 value3}}
> lsearch -index 0 $mylist key2
0
> lindex $mylist [list [lsearch -index 0 $mylist key2] 1]
> value2
> proc kv_lookup {dictList key} {
      set index [lsearch -index 0 $dictList $key]
      if {$index < 0} {
          error "Key '$key' not found in list $dictList"
      }
      return [lindex $dictList [list $index 1]]
  }
> kv_lookup $mylist key2
value2

Man pages for 8.4 are here

You may also want to look at this page on keyed lists for Tcl. It implements what I mentioned above, plus some other useful commands.

For an example of the different between an ordered "map" and an unordered one, you can take a look at the two java classes HashMap (unordered) and LinkedHashMap (ordered).


问:
Pysaprk multi groupby with different column
I have data like below

```<code>year    name    percent     sex
1880    John    0.081541    boy
1881    William 0.080511    boy
1881    John    0.050057    boy
</code>```

I need to groupby and count using different columns

```<code>df_year = df.groupby('year').count()
df_name = df.groupby('name').count()
df_sex = df.groupby('sex').count()
</code>```

then I have to create a Window to get the top-3 data by each column

```<code>window = Window.partitionBy('year').orderBy(col("count").desc())
top4_res = df_year.withColumn('topn', func.row_number().over(window)).\
                                              filter(col('topn') <= 4).repartition(1)
</code>```

suppose I have hundreds of columns to groupby and count and topk_3 operation.

can I do it all in once?

or is there any better ways to do it?

答:
I am not sure if this will meet your requirement but if you are okay with a single dataframe, i think it can give you a start, let me know if otherwise. You can stack these 3 columns (or more) and then groupby and take count :

```<code>cols = ['year','name','sex']
e = f"""stack({len(cols)},{','.join(map(','.join,
             (zip([f'"{i}"' for i in cols],cols))))}) as (col,val)"""

(df.select(*[F.col(i).cast('string') for i in cols]).selectExpr(e)
 .groupBy(*['col','val']).agg(F.count("col").alias("Counts")).orderBy('col')).show()

+----+-------+------+
| col|    val|Counts|
+----+-------+------+
|name|   John|     2|
|name|William|     1|
| sex|    boy|     3|
|year|   1881|     2|
|year|   1880|     1|
+----+-------+------+
</code>```

If you want a wide form you can also pivot but i think long form would be helpful:

```<code>(df.select(*[F.col(i).cast('string') for i in cols]).selectExpr(e)
 .groupBy('col').pivot('val').agg(F.count('val')).show())

+----+----+----+----+-------+----+
| col|1880|1881|John|William| boy|
+----+----+----+----+-------+----+
|name|null|null|   2|      1|null|
|year|   1|   2|null|   null|null|
| sex|null|null|null|   null|   3|
+----+----+----+----+-------+----+
</code>```

Body:
I have data like below

year    name    percent     sex
1880    John    0.081541    boy
1881    William 0.080511    boy
1881    John    0.050057    boy

I need to groupby and count using different columns

df_year = df.groupby('year').count()
df_name = df.groupby('name').count()
df_sex = df.groupby('sex').count()

then I have to create a Window to get the top-3 data by each column

window = Window.partitionBy('year').orderBy(col("count").desc())
top4_res = df_year.withColumn('topn', func.row_number().over(window)).\
                                              filter(col('topn') <= 4).repartition(1)

suppose I have hundreds of columns to groupby and count and topk_3 operation.

can I do it all in once?

or is there any better ways to do it?

Body:
I am not sure if this will meet your requirement but if you are okay with a single dataframe, i think it can give you a start, let me know if otherwise. You can stack these 3 columns (or more) and then groupby and take count :

cols = ['year','name','sex']
e = f"""stack({len(cols)},{','.join(map(','.join,
             (zip([f'"{i}"' for i in cols],cols))))}) as (col,val)"""

(df.select(*[F.col(i).cast('string') for i in cols]).selectExpr(e)
 .groupBy(*['col','val']).agg(F.count("col").alias("Counts")).orderBy('col')).show()

+----+-------+------+
| col|    val|Counts|
+----+-------+------+
|name|   John|     2|
|name|William|     1|
| sex|    boy|     3|
|year|   1881|     2|
|year|   1880|     1|
+----+-------+------+

If you want a wide form you can also pivot but i think long form would be helpful:

(df.select(*[F.col(i).cast('string') for i in cols]).selectExpr(e)
 .groupBy('col').pivot('val').agg(F.count('val')).show())

+----+----+----+----+-------+----+
| col|1880|1881|John|William| boy|
+----+----+----+----+-------+----+
|name|null|null|   2|      1|null|
|year|   1|   2|null|   null|null|
| sex|null|null|null|   null|   3|
+----+----+----+----+-------+----+


问:
How to find derivative in Python using SymPy
I want to find derivative of a certain function inputted by the user.

```<code>x = np.linspace(-5,5)

print('Options are:')
print('1. y = x')
print('2. y = ax^2')
print('3. y = k(x-a)(x-b)')
print('4. y = k(x-a)(x-b)(x-c)')

n = int(input('Your option is: '))

if n == 1:
    func = x
    plt.plot(x,func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        print('Derivative is 1')
    else:
        print('Done')

elif n == 2:
    a = int(input('Enter a value for a: '))
    func = a*x**2
    plt.plot(x,func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        x = sp.Symbol('x')
        print(sp.diff(func,x))
    else:
        print('Done')
</code>```

When n == 2,
i will need the user to input the 'a' value for the ax^2 function.
The code will then plot the graph ax^2.
Then proceeds to ask whether the user wants the derivative of the function.
In this part I'm confused because with the syntax i used above, it doesnt show the derivative, but it instead shows a list of 0s like below.

```<code>1. y = x
2. y = ax^2
3. y = k(x-a)(x-b)
4. y = k(x-a)(x-b)(x-c)
Your option is: 2
Enter a value for a: 3
Do you wanna find its derivative? (Y/N)Y
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code>```

How do i fix this problem?

答:
You will need to define the Symbol x before defining the function func. For plotting you can use SymPy's plotting modules. Below is a possible solution.

```<code>import sympy as sp
import numpy as np
from sympy.plotting import plot

x = sp.Symbol('x')

print('Options are:')
print('1. y = x')
print('2. y = ax^2')
print('3. y = k(x-a)(x-b)')
print('4. y = k(x-a)(x-b)(x-c)')

n = int(input('Your option is: '))

if n == 1:
    func = x
    plot(func)

    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        print('Derivative is 1')
    else:
        print('Done')

elif n == 2:
    a = int(input('Enter a value for a: '))
    func = a*x**2
    plot(func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        print(sp.diff(func,x))
    else:
        print('Done')
</code>```

Body:
I want to find derivative of a certain function inputted by the user.

x = np.linspace(-5,5)

print('Options are:')
print('1. y = x')
print('2. y = ax^2')
print('3. y = k(x-a)(x-b)')
print('4. y = k(x-a)(x-b)(x-c)')

n = int(input('Your option is: '))

if n == 1:
    func = x
    plt.plot(x,func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        print('Derivative is 1')
    else:
        print('Done')

elif n == 2:
    a = int(input('Enter a value for a: '))
    func = a*x**2
    plt.plot(x,func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        x = sp.Symbol('x')
        print(sp.diff(func,x))
    else:
        print('Done')

When n == 2,
i will need the user to input the 'a' value for the ax^2 function.
The code will then plot the graph ax^2.
Then proceeds to ask whether the user wants the derivative of the function.
In this part I'm confused because with the syntax i used above, it doesnt show the derivative, but it instead shows a list of 0s like below.

1. y = x
2. y = ax^2
3. y = k(x-a)(x-b)
4. y = k(x-a)(x-b)(x-c)
Your option is: 2
Enter a value for a: 3
Do you wanna find its derivative? (Y/N)Y
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

How do i fix this problem?

Body:
You will need to define the Symbol x before defining the function func. For plotting you can use SymPy's plotting modules. Below is a possible solution.

import sympy as sp
import numpy as np
from sympy.plotting import plot

x = sp.Symbol('x')

print('Options are:')
print('1. y = x')
print('2. y = ax^2')
print('3. y = k(x-a)(x-b)')
print('4. y = k(x-a)(x-b)(x-c)')

n = int(input('Your option is: '))

if n == 1:
    func = x
    plot(func)

    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        print('Derivative is 1')
    else:
        print('Done')

elif n == 2:
    a = int(input('Enter a value for a: '))
    func = a*x**2
    plot(func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        print(sp.diff(func,x))
    else:
        print('Done')


问:
Segmentation fault error while working with command-line argument, C program
I am working on a program that decodes a message provided as a morse code as a command line argument. If the provided string contains 7 spaces it means that I need to print a space to the decoded string. Currently, my program shows all correct letters, but I cannot overcome the issue with locating 7 spaces in a string and printing one space instead.

Here is the issue and how I pass the encoded string:

```<code>e3r2p2% ./morse "..- -.. .-. .. .-- --.    ..- ....."
udriwg zsh: segmentation fault ./morse "..- -.. .-. .. .-- --.    ..- ....."
</code>```

Program works fine and prints all the decrypted letters (udriwg) till it meets the first (or maybe second) space out of 7;

Here is the code of my program:

```<code>int find_morse(const char *s);
bool count_spaces(char *s);
bool is_valid_char(char *s);
bool is_valid_params(int argc, char *argv[]);
void mx_printchar(char c);
void mx_printerr(const char *s);
int mx_strcmp(const char *first, const char *second);
char* mx_strcpy(char* dest, const char* source);
int mx_strlen(const char *s)

  int main(int argc, char *argv[]){

  if (!is_valid_params(argc, argv)){
        mx_printerr("usage: ./morse \"str\"\n");
        exit(1);
      }
      char *output[27]= {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o",
                        "p","q","r","s","t","u","v","w","x","y","z","."};
      char *copy;
      copy = malloc(mx_strlen(argv[1]) + 1);
  if (copy != NULL) {
   mx_strcpy(copy, argv[1]);
  } else {
    mx_printerr("usage: ./morse \"str\"\n");
    exit(1);
  }
  int buff = 0;
  char temp[5];
  int index;
  int space = 0;
  int j;

  for (int i = 0, n = mx_strlen(copy); i < n; i++) {
    if (copy[i] == '.' && copy[i + 1] == '.' && copy[i + 2] == '.'
        && copy[i + 3] == '.' &&  copy[i + 4] == '.') {
      mx_printchar(*output[26]);
    }
    if (copy[i] != ' ') {
      temp[buff] = copy[i];
      buff++;
    }
    if (copy[i] == ' ') {
      index = find_morse(temp);
      //print letter converted from morse to ENG
      mx_printchar(*output[index]);

      j = i;
      while (copy[j] == ' ') {
          space++;
          j++;
          if (space == 7) {
            mx_printchar(' ');
            space = 0;
            break;
          }
       }
       temp[buff] = '\0';
       buff = 0;
       for(int j = 0; j <4; j++) {
        temp[j] ='\0';
       }
     }
   }
   mx_printchar('\n');

   free(copy);
   return 0;
 }

   int find_morse(const char *s) {
   char *input[27]={".-","-...","-.-.","-..",".","..-.","--.", "....", "..",
          ".---","-.-",".-..","--","-.", "---",".--.","--.-",".-.",
          "...","-","..-", "...-",".--","-..-","-.--","--..","....."};
     for (int i = 0; i < 27; i++) {
       if (mx_strcmp(s, input[i]) == 0) {
         return i;
       }
     }
   return -1;

   }

  bool count_spaces(char *s) {
   int space = 0;
   for (int i = 0; s[i] != '\0'; i++) {
     if (s[i] == ' ') {
       space++;
       if (s[i + 1] != ' ') {
         if (space != 1 && space != 7) {
          return false;
        } else {
          space = 0;
        }
      }
    }
  }
  return true;
}

bool is_valid_char(char *s){
  int i = 0;
  while (s[i] != '\0'){
    if (s[i] != ' ' && s[i] != '-' && s[i] != '.') {
      return false;
    }
    i++;
  }
  return true;
}

bool is_valid_params(int argc, char *argv[]){
  if (argc != 2) {
    return false;
  }
  if (!is_valid_char(argv[1])){
    return false;
  }
  if (!count_spaces(argv[1])){
    return false;
  }
  return true;
}

void mx_printchar(char c){
  write(1, &c, 1);
}

void mx_printerr(const char *s){
  write(2, s, mx_strlen(s));
}

int mx_strcmp(const char *first, const char *second) {
  while (*first) {
    if (*first != *second) break;
    first++;
    second++;
  }
  return *(const unsigned char*)first - *(const unsigned char*)second;
}

char* mx_strcpy(char* dest, const char* source){
  if (dest == NULL) {
    return NULL;
  }
  char *ptr = dest;
  while (*source != '\0') {
    *dest = *source;
    dest++;
    source++;
  }
  *dest = '\0';
  return ptr;
}

int mx_strlen(const char *s){
  int length = 0;
  while (s[length] != '\0'){
    length++;
  }
  return length;
}
</code>```

I believe the issue starts here:

```<code>      j = i;
      while (copy[j] == ' ') {
          space++;
          j++;
          if (space == 7) {
            mx_printchar(' ');
            space = 0;
            break;
          }
       }
</code>```

Program prints the decripted letter, then tries to check those spaces but somethis go wrong.
I'd appreciate any suggestions as how to resolve it

答:
When using a program from command line you always put a space as a delimiter between your program name and the parameters and other parameters. So, in your case if there are 7 spaces then a extra space will be added as delimiter between your program name and 7 spaces making it to 8 spaces like this  ./morse. So, I'd rather suggest to use any other symbol like ! or any other symbol.
Now for the Segmentation fault error I think that's not happening because of that space counter section that's happening because of this line copy = malloc(mx_strlen(argv[1]) + 1); as you must know that malloc() returns a void * to the allocated space.Now here I don't know what those mx_ functions are. Also some questions popped out in my mind while I was debugging your code those answers are included in the modified code(at somewhat satisfying level) i'm putting below. Please answer them in comments.

Code:

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

/* Questions
** 1. What are these mx_ functions?
** 2. What is is_valid_params?
** 3. Can't we define *output[27] as *output = "abcdef...z." ?
** 4. In " for(j = 0; j < 4; j++) temp[j] ='\0'; " why j < 4 instead of j < 5?
*/

// Function Prototype
int find_morse(const char *s);

//main()
int main(int argc, char *argv[])
{
    char *output[27]= {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","."};
    char *copy, temp[5];
    int buff = 0, index, space = 0, i, j, n;
    // Checking for valid parameters.
    if (argc != 2)
    {
        printf("usage: ./morse \"Invalid Parameters.\"\n");//mx_printerr("usage: ./morse \"str\"\n");
        exit(1);
    }

    copy = (char *)malloc(strlen(argv[1]) + 1);

    if (copy != NULL)
        strcpy(copy, argv[1]);
    else
    {
        printf("usage: ./morse \"Memory Unavailable.\"\n");
        exit(2);
    }

    for (i = 0, n = strlen(copy); i < n; i++)
    {
        if (copy[i] == '.' && copy[i + 1] == '.' && copy[i + 2] == '.' && copy[i + 3] == '.' &&  copy[i + 4] == '.')
            putchar(*output[26]);

        if (copy[i] != ' ')
            temp[buff++] = copy[i];
        else
        {
            j = i;
            while (copy[j] == ' ')
            {
                space++;
                j++;
                if (space == 7)
                {
                    putchar(' ');
                    space = 0;
                    break;
                }
            }
            temp[buff] = '\0';
            buff = 0;
            // Emptying temp[5]
            //for(j = 0; j < 5; j++)
            temp[0] = '\0'; // Rest elements will automatically be assigned to \0 by compiler.
        }
        if(index = find_morse(temp) != -1)
                putchar(*output[index]); //print letter converted from morse to ENG

    }
    putchar('\n');
    free(copy);
    return 0;
}

int find_morse(const char *s)
{
    char *input[27] = {".-","-...","-.-.","-..",".","..-.","--.", "....", "..",".---","-.-",".-..","--","-.", "---",".--.","--.-",".-.","...","-","..-", "...-",".--","-..-","-.--","--..","....."};
    for (int i = 0; i < 27; i++)
    {
        if (strcmp(s, input[i]) == 0)
            return i;
    }
    return -1;
}
</code>```

Here in this program I didn't understand that how the user will enter morse code one by one or as a string. Because, when matching those morse code entries, I'm sure a logical error would occur.

Body:
I am working on a program that decodes a message provided as a morse code as a command line argument. If the provided string contains 7 spaces it means that I need to print a space to the decoded string. Currently, my program shows all correct letters, but I cannot overcome the issue with locating 7 spaces in a string and printing one space instead.

Here is the issue and how I pass the encoded string:

e3r2p2% ./morse "..- -.. .-. .. .-- --.    ..- ....."
udriwg zsh: segmentation fault ./morse "..- -.. .-. .. .-- --.    ..- ....."

Program works fine and prints all the decrypted letters (udriwg) till it meets the first (or maybe second) space out of 7;

Here is the code of my program:

int find_morse(const char *s);
bool count_spaces(char *s);
bool is_valid_char(char *s);
bool is_valid_params(int argc, char *argv[]);
void mx_printchar(char c);
void mx_printerr(const char *s);
int mx_strcmp(const char *first, const char *second);
char* mx_strcpy(char* dest, const char* source);
int mx_strlen(const char *s)

  int main(int argc, char *argv[]){

  if (!is_valid_params(argc, argv)){
        mx_printerr("usage: ./morse \"str\"\n");
        exit(1);
      }
      char *output[27]= {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o",
                        "p","q","r","s","t","u","v","w","x","y","z","."};
      char *copy;
      copy = malloc(mx_strlen(argv[1]) + 1);
  if (copy != NULL) {
   mx_strcpy(copy, argv[1]);
  } else {
    mx_printerr("usage: ./morse \"str\"\n");
    exit(1);
  }
  int buff = 0;
  char temp[5];
  int index;
  int space = 0;
  int j;

  for (int i = 0, n = mx_strlen(copy); i < n; i++) {
    if (copy[i] == '.' && copy[i + 1] == '.' && copy[i + 2] == '.'
        && copy[i + 3] == '.' &&  copy[i + 4] == '.') {
      mx_printchar(*output[26]);
    }
    if (copy[i] != ' ') {
      temp[buff] = copy[i];
      buff++;
    }
    if (copy[i] == ' ') {
      index = find_morse(temp);
      //print letter converted from morse to ENG
      mx_printchar(*output[index]);

      j = i;
      while (copy[j] == ' ') {
          space++;
          j++;
          if (space == 7) {
            mx_printchar(' ');
            space = 0;
            break;
          }
       }
       temp[buff] = '\0';
       buff = 0;
       for(int j = 0; j <4; j++) {
        temp[j] ='\0';
       }
     }
   }
   mx_printchar('\n');

   free(copy);
   return 0;
 }

   int find_morse(const char *s) {
   char *input[27]={".-","-...","-.-.","-..",".","..-.","--.", "....", "..",
          ".---","-.-",".-..","--","-.", "---",".--.","--.-",".-.",
          "...","-","..-", "...-",".--","-..-","-.--","--..","....."};
     for (int i = 0; i < 27; i++) {
       if (mx_strcmp(s, input[i]) == 0) {
         return i;
       }
     }
   return -1;

   }

  bool count_spaces(char *s) {
   int space = 0;
   for (int i = 0; s[i] != '\0'; i++) {
     if (s[i] == ' ') {
       space++;
       if (s[i + 1] != ' ') {
         if (space != 1 && space != 7) {
          return false;
        } else {
          space = 0;
        }
      }
    }
  }
  return true;
}

bool is_valid_char(char *s){
  int i = 0;
  while (s[i] != '\0'){
    if (s[i] != ' ' && s[i] != '-' && s[i] != '.') {
      return false;
    }
    i++;
  }
  return true;
}

bool is_valid_params(int argc, char *argv[]){
  if (argc != 2) {
    return false;
  }
  if (!is_valid_char(argv[1])){
    return false;
  }
  if (!count_spaces(argv[1])){
    return false;
  }
  return true;
}

void mx_printchar(char c){
  write(1, &c, 1);
}

void mx_printerr(const char *s){
  write(2, s, mx_strlen(s));
}

int mx_strcmp(const char *first, const char *second) {
  while (*first) {
    if (*first != *second) break;
    first++;
    second++;
  }
  return *(const unsigned char*)first - *(const unsigned char*)second;
}

char* mx_strcpy(char* dest, const char* source){
  if (dest == NULL) {
    return NULL;
  }
  char *ptr = dest;
  while (*source != '\0') {
    *dest = *source;
    dest++;
    source++;
  }
  *dest = '\0';
  return ptr;
}

int mx_strlen(const char *s){
  int length = 0;
  while (s[length] != '\0'){
    length++;
  }
  return length;
}

I believe the issue starts here:

      j = i;
      while (copy[j] == ' ') {
          space++;
          j++;
          if (space == 7) {
            mx_printchar(' ');
            space = 0;
            break;
          }
       }

Program prints the decripted letter, then tries to check those spaces but somethis go wrong.
I'd appreciate any suggestions as how to resolve it

Body:
When using a program from command line you always put a space as a delimiter between your program name and the parameters and other parameters. So, in your case if there are 7 spaces then a extra space will be added as delimiter between your program name and 7 spaces making it to 8 spaces like this  ./morse. So, I'd rather suggest to use any other symbol like ! or any other symbol.
Now for the Segmentation fault error I think that's not happening because of that space counter section that's happening because of this line copy = malloc(mx_strlen(argv[1]) + 1); as you must know that malloc() returns a void * to the allocated space.Now here I don't know what those mx_ functions are. Also some questions popped out in my mind while I was debugging your code those answers are included in the modified code(at somewhat satisfying level) i'm putting below. Please answer them in comments.

Code:

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

/* Questions
** 1. What are these mx_ functions?
** 2. What is is_valid_params?
** 3. Can't we define *output[27] as *output = "abcdef...z." ?
** 4. In " for(j = 0; j < 4; j++) temp[j] ='\0'; " why j < 4 instead of j < 5?
*/

// Function Prototype
int find_morse(const char *s);

//main()
int main(int argc, char *argv[])
{
    char *output[27]= {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","."};
    char *copy, temp[5];
    int buff = 0, index, space = 0, i, j, n;
    // Checking for valid parameters.
    if (argc != 2)
    {
        printf("usage: ./morse \"Invalid Parameters.\"\n");//mx_printerr("usage: ./morse \"str\"\n");
        exit(1);
    }

    copy = (char *)malloc(strlen(argv[1]) + 1);

    if (copy != NULL)
        strcpy(copy, argv[1]);
    else
    {
        printf("usage: ./morse \"Memory Unavailable.\"\n");
        exit(2);
    }

    for (i = 0, n = strlen(copy); i < n; i++)
    {
        if (copy[i] == '.' && copy[i + 1] == '.' && copy[i + 2] == '.' && copy[i + 3] == '.' &&  copy[i + 4] == '.')
            putchar(*output[26]);

        if (copy[i] != ' ')
            temp[buff++] = copy[i];
        else
        {
            j = i;
            while (copy[j] == ' ')
            {
                space++;
                j++;
                if (space == 7)
                {
                    putchar(' ');
                    space = 0;
                    break;
                }
            }
            temp[buff] = '\0';
            buff = 0;
            // Emptying temp[5]
            //for(j = 0; j < 5; j++)
            temp[0] = '\0'; // Rest elements will automatically be assigned to \0 by compiler.
        }
        if(index = find_morse(temp) != -1)
                putchar(*output[index]); //print letter converted from morse to ENG

    }
    putchar('\n');
    free(copy);
    return 0;
}

int find_morse(const char *s)
{
    char *input[27] = {".-","-...","-.-.","-..",".","..-.","--.", "....", "..",".---","-.-",".-..","--","-.", "---",".--.","--.-",".-.","...","-","..-", "...-",".--","-..-","-.--","--..","....."};
    for (int i = 0; i < 27; i++)
    {
        if (strcmp(s, input[i]) == 0)
            return i;
    }
    return -1;
}

Here in this program I didn't understand that how the user will enter morse code one by one or as a string. Because, when matching those morse code entries, I'm sure a logical error would occur.


问:
Fast method to access random image pixels and at most once
I'm learning OpenCV (C++) and as a simple practice, I designed a simple effect which makes some of image pixels black or white. I want each pixel to be edited at most once; so I added address of all pixels to a vector. But it made my code very slow; specially for large images or high amounts of effect. Here is my code:

void effect1(Mat& img, float amount)    // 100 ≥ amount ≥ 0
{
    vector<uchar*> addresses;
    int channels = img.channels();
    uchar* lastAddress = img.ptr<uchar>(0) + img.total() * channels;
    for (uchar* i = img.ptr<uchar>(0); i < lastAddress; i += channels) addresses.push_back(i);   //Fast Enough
    size_t count = img.total() * amount / 100 / 2;
    for (size_t i = 0; i < count; i++)
    {
        size_t addressIndex = xor128() % addresses.size();   //Fast Enough, xor128() is a fast random number generator
        for (size_t j = 0; j < channels; j++)
        {
            *(addresses[addressIndex] + j) = 255;
        }   //Fast Enough
        addresses.erase(addresses.begin() + addressIndex);    // MAKES CODE EXTREMELY SLOW
    }
    for (size_t i = 0; i < count; i++)
    {
        size_t addressIndex = xor128() % addresses.size();   //Fast Enough, xor128() is a fast random number generator
        for (size_t j = 0; j < channels; j++)
        {
            *(addresses[addressIndex] + j) = 0;
        }   //Fast Enough
        addresses.erase(addresses.begin() + addressIndex);    // MAKES CODE EXTREMELY SLOW
    }
}
```

I think rearranging vector items after erasing an item is what makes my code slow (if I remove addresses.erase, code will run fast).

Is there any fast method to select each random item from a collection (or a number range) at most once?

Also: I'm pretty sure such effect already exists. Does anyone know the name of it?

答:
I also post a simpler code:

void saltAndPepper(Mat& img, float amount)
{
    vector<size_t> pixels(img.total());    // size_t = unsigned long long
    uchar channels = img.channels();
    iota(pixels.begin(), pixels.end(), 0);    // Fill vector with 0, 1, 2, ...
    shuffle(pixels.begin(), pixels.end(), mt19937(time(nullptr)));    // Shuffle the vector
    size_t count = img.total() * amount / 100 / 2;
    for (size_t i = 0; i < count; i++)
    {
        for (size_t j = 0; j < channels; j++)    // Set all pixel channels (e.g. Grayscale with 1 channel or BGR with 3 channels) to 255
        {
            *(img.ptr<uchar>(0) + (pixels[i] * channels) + j) = 255;
        }
    }
    for (size_t i = count; i < count*2; i++)
    {
        for (size_t j = 0; j < channels; j++)    // Set all pixel channels (e.g. Grayscale with 1 channel or BGR with 3 channels) to 0
        {
            *(img.ptr<uchar>(0) + (pixels[i] * channels) + j) = 0;
        }
    }
}
```

Body:
I'm learning OpenCV (C++) and as a simple practice, I designed a simple effect which makes some of image pixels black or white. I want each pixel to be edited at most once; so I added address of all pixels to a vector. But it made my code very slow; specially for large images or high amounts of effect. Here is my code:

void effect1(Mat& img, float amount)    // 100 ≥ amount ≥ 0
{
    vector<uchar*> addresses;
    int channels = img.channels();
    uchar* lastAddress = img.ptr<uchar>(0) + img.total() * channels;
    for (uchar* i = img.ptr<uchar>(0); i < lastAddress; i += channels) addresses.push_back(i);   //Fast Enough
    size_t count = img.total() * amount / 100 / 2;
    for (size_t i = 0; i < count; i++)
    {
        size_t addressIndex = xor128() % addresses.size();   //Fast Enough, xor128() is a fast random number generator
        for (size_t j = 0; j < channels; j++)
        {
            *(addresses[addressIndex] + j) = 255;
        }   //Fast Enough
        addresses.erase(addresses.begin() + addressIndex);    // MAKES CODE EXTREMELY SLOW
    }
    for (size_t i = 0; i < count; i++)
    {
        size_t addressIndex = xor128() % addresses.size();   //Fast Enough, xor128() is a fast random number generator
        for (size_t j = 0; j < channels; j++)
        {
            *(addresses[addressIndex] + j) = 0;
        }   //Fast Enough
        addresses.erase(addresses.begin() + addressIndex);    // MAKES CODE EXTREMELY SLOW
    }
}

I think rearranging vector items after erasing an item is what makes my code slow (if I remove addresses.erase, code will run fast).

Is there any fast method to select each random item from a collection (or a number range) at most once?

Also: I'm pretty sure such effect already exists. Does anyone know the name of it?


问:
How do i copy a Json file from the Assets/Resources/ to the Internal storage of an Android device ( persistent data)? [Unity Android]
I want to copy a single json file from Unity's Assets/Resources/ directory to the internal persistent memory of Android device (INTERNAL STORAGE/Android/data/<packagename>/files/) only once at the start of the game. I looked up all over the internet, with solutions saying to use Streaming assets and UnityWebRequests or WWW class which is obsolete now. I tried everything for hours now. And did not find a exact solutions, but only got null references and directory not found.

I added my json file to the <UnityProject>/Assets/Resources/StreamingAssets/, but it doesn't seem to detect any streaming assets. I understand an apk is a zip file and so I can only read the contents of streaming assets, but my I can't find a solution to this.

Once I get my json from streaming asset, I can finally add it to Application.persistentDataPath.

UPDATE
I had actually figured it out,

```<code>     public void LoadFromResources() {
 {mobilePath = "StreamingAssets/"; mobilePath = mobilePath + "stickerJson" + ".json";
 string newPath = mobilePath.Replace(".json", "");
 TextAsset ta = Resources.Load<TextAsset>(newPath);
 string json = ta.text; Debug.Log(json); System.IO.File.WriteAllText(Application.persistentDataPath + "/stickers.json", json);
 }
}
</code>```

答:
To copy a file you only need to have the information of the file and then create a new one in another place.

So if you got your json file into your Resources directory you can retreive like the documentation say:

```<code>//Load text from a JSON file (Assets/Resources/Text/jsonFile01.json)
var jsonTextFile = Resources.Load<TextAsset>("Text/jsonFile01");
//Then use JsonUtility.FromJson<T>() to deserialize jsonTextFile into an object
</code>```

Then you only have to create your android file in your persistentDataPath as @Iggy says in the comments doing:

```<code>System.IO.File.WriteAllText(Path.Combine(Application.persistentDataPath, "file.txt"), jsonTextFile);
</code>```

Note: Not really sure, but for other cases I think that StreamingAssets folder should be inside Assets, no inside Resources.

Body:
I want to copy a single json file from Unity's Assets/Resources/ directory to the internal persistent memory of Android device (INTERNAL STORAGE/Android/data/<packagename>/files/) only once at the start of the game. I looked up all over the internet, with solutions saying to use Streaming assets and UnityWebRequests or WWW class which is obsolete now. I tried everything for hours now. And did not find a exact solutions, but only got null references and directory not found.

I added my json file to the <UnityProject>/Assets/Resources/StreamingAssets/, but it doesn't seem to detect any streaming assets. I understand an apk is a zip file and so I can only read the contents of streaming assets, but my I can't find a solution to this.

Once I get my json from streaming asset, I can finally add it to Application.persistentDataPath.

UPDATE
I had actually figured it out,

     public void LoadFromResources() {
 {mobilePath = "StreamingAssets/"; mobilePath = mobilePath + "stickerJson" + ".json";
 string newPath = mobilePath.Replace(".json", "");
 TextAsset ta = Resources.Load<TextAsset>(newPath);
 string json = ta.text; Debug.Log(json); System.IO.File.WriteAllText(Application.persistentDataPath + "/stickers.json", json);
 }
}

Body:
To copy a file you only need to have the information of the file and then create a new one in another place.

So if you got your json file into your Resources directory you can retreive like the documentation say:

//Load text from a JSON file (Assets/Resources/Text/jsonFile01.json)
var jsonTextFile = Resources.Load<TextAsset>("Text/jsonFile01");
//Then use JsonUtility.FromJson<T>() to deserialize jsonTextFile into an object

Then you only have to create your android file in your persistentDataPath as @Iggy says in the comments doing:

System.IO.File.WriteAllText(Path.Combine(Application.persistentDataPath, "file.txt"), jsonTextFile);

Note: Not really sure, but for other cases I think that StreamingAssets folder should be inside Assets, no inside Resources.


问:
Remove current view from superview
Let's say I have a viewcontroller "ViewBViewController". In that viewcontroller I create an instance of the "ViewAViewController" and use the addSubView: method to display this ViewAViewController. It then processes a bunch of information, and is now done. I want it to automatically get removed as a subview when it's done.

I was looking at the removeFromSuperview method, but can't seem to call that from within the viewcontroller whose view I'm trying to remove (my first instinct was [self.view removeFromSuperview], but that gets rid of the entire view, not just the subview I'm after).

The only way I can think of is setting up a delegate protocol, and have View B take care of the unloading of View A on behalf of View A as its delegate. However this approach seems a bit overkill. Am I missing an easier solution?

Thanks in advance!

答:
There are two basically correct solutions here:

Use a navigation controller.  You can hide the navigation bar if you don't want it to be part of your interface.  Then you can dispose of the top view controller and its view from either view controller by calling

```<code>// argument can be YES or NO, as you like
[self.navigationController popViewControllerAnimated:YES];
</code>```

Use a delegate call that tells the parent view controller to do something like

```<code>-(void)removeViewA {
    // remove the view from the view hierarchy
    [self.viewAController.view removeFromSuperview];
    // dispose of the view controller so it doesn't leak.
    self.viewAController = nil;
}
</code>```

It's important to make sure that you don't leak the child view controller and its view.

Either of these approaches works, but using a navigation controller seems more idiomatic to me.

Title: Remove current view from superview

Body:
There are two basically correct solutions here:

Use a navigation controller.  You can hide the navigation bar if you don't want it to be part of your interface.  Then you can dispose of the top view controller and its view from either view controller by calling

// argument can be YES or NO, as you like
[self.navigationController popViewControllerAnimated:YES];

Use a delegate call that tells the parent view controller to do something like

-(void)removeViewA {
    // remove the view from the view hierarchy
    [self.viewAController.view removeFromSuperview];
    // dispose of the view controller so it doesn't leak.
    self.viewAController = nil;
}

It's important to make sure that you don't leak the child view controller and its view.

Either of these approaches works, but using a navigation controller seems more idiomatic to me.


问:
Using openapi.yaml in springdoc
I can customize OpenAPI from code.

Can I do same over openapi.yaml like swagger-petstore

I create simple springboot project with one @RestController.

I create openapi.yaml and copy it to /src/main/resources/.

But I see default values on open swagger-ui page.

答:
If you need configuration file, you can have a look at the FAQ, documentation:

https://springdoc.org/faq.html#can-i-use-spring-property-with-swagger-annotations

And here is the link for code samples:

https://raw.githubusercontent.com/springdoc/springdoc-openapi/master/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app15/SpringDocApp15Test.java

Title: Using openapi.yaml in springdoc


问:
How to convert nested array of object into arraylist in javascript?
i have a nested array of object and i want to convert in arraylist like this :
this is my data array of object :

```<code>{
    "status": true,
    "message": "",
    "data": [{
            "pasien_docs": [{
                    "ecg": null,
                    "date": "2020-01-21T05:22:01.901Z"
                }, {
                    "ecg": 1.03,
                    "date": "2020-01-21T05:22:02.979Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:04.053Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:05.126Z"
                },
            ]
        }
    ]
}
</code>```

and i want change convert to array like this :

```<code>{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ],
        [
            "2020-01-21T05:22:01.901Z",
            1, 03
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
    ]
 }
</code>```

i try using map to convert on result like this :

```<code>result = result.map((u, i) => [
            u.pasien_docs[i].date,
            u.pasien_docs[i].ecg,
        ]);
</code>```

but why i only get result data of one array not four data ? help me please, thankyou..

```<code>{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ]
    ]
}
</code>```

答:
let obj = {
  status: true,
  message: "",
  data: [
    {
      pasien_docs: [
        {
          ecg: null,
          date: "2020-01-21T05:22:01.901Z",
        },
        {
          ecg: 1.03,
          date: "2020-01-21T05:22:02.979Z",
        },
        {
          ecg: 1.04,
          date: "2020-01-21T05:22:04.053Z",
        },
        {
          ecg: 1.04,
          date: "2020-01-21T05:22:05.126Z",
        },
      ],
    },
  ],
};

var finalobj = JSON.parse(JSON.stringify(obj));
var innerobj = obj.data;
var intermd = innerobj.map((data) => {
  return data.pasien_docs;
});
finalarray = intermd[0].map((val) => {
  return [val.ecg, val.date];
});
console.log(obj);
finalobj.data[0].pasien_docs=finalarray;
console.log(finalobj);```

Body:
i have a nested array of object and i want to convert in arraylist like this :
this is my data array of object :

{
    "status": true,
    "message": "",
    "data": [{
            "pasien_docs": [{
                    "ecg": null,
                    "date": "2020-01-21T05:22:01.901Z"
                }, {
                    "ecg": 1.03,
                    "date": "2020-01-21T05:22:02.979Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:04.053Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:05.126Z"
                },
            ]
        }
    ]
}

and i want change convert to array like this :

{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ],
        [
            "2020-01-21T05:22:01.901Z",
            1, 03
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
    ]
 }

i try using map to convert on result like this :

result = result.map((u, i) => [
            u.pasien_docs[i].date,
            u.pasien_docs[i].ecg,
        ]);

but why i only get result data of one array not four data ? help me please, thankyou..

{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ]
    ]
}


问:
Android Studio Flutter Project Error: Out of Memory
I run any flutter project on Android Studio and it throws an Out Of Memory Error.
The message shown in the console looks something like this:

e:\b\build\slave\windows_engine\build\src\third_party\dart\runtime\vm\scavenger.cc: 411: error: Out of memory.
Dumping native stack trace for thread 2750
  [0x00007ff676324b63] Dart_IsPrecompiledRuntime
  [0x00007ff676324b63] Dart_IsPrecompiledRuntime
-- End of DumpStackTrace
```

答:
shutdown computer completely, don't to hibernate.
That works for me.
You can shutdown computer completely using this command</p>

```<code>shutdown /s /f /t 0
</code>```

Body:
shutdown computer completely, don't to hibernate.
That works for me.
You can shutdown computer completely using this command

shutdown /s /f /t 0


问:
Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]
I have been googling for about 90 minutes now and still don't have an answer to this.  Where do I set default_url_options?  I've already set it for config.action_mailer.default_url_options to solve this same bug elsewhere, but now I'm getting this error when trying to use a URL helper inside an RSpec spec.  I have no idea where it's expecting default_url_options to be set.

```<code> Failure/Error: listing_url(listing).should match(/\/\d+-\w+$/)
 RuntimeError:
   Missing host to link to! Please provide :host parameter or set default_url_options[:host]
 # ./spec/routing/listing_routing_spec.rb:9:in `block (3 levels) in <top (required)>'
</code>```

This code has nothing to do with emails/ActionMailer, it just happens to need a URL instead of a path.

Any ideas?

答:
The above answer did not work for me, at least not as I wanted.
I realised
config.action_mailer.default_url_options = { host: "localhost", port: 3000 }
after installing devise.
Hope it will help someone with the same problem.

Body:
I have been googling for about 90 minutes now and still don't have an answer to this.  Where do I set default_url_options?  I've already set it for config.action_mailer.default_url_options to solve this same bug elsewhere, but now I'm getting this error when trying to use a URL helper inside an RSpec spec.  I have no idea where it's expecting default_url_options to be set.

 Failure/Error: listing_url(listing).should match(/\/\d+-\w+$/)
 RuntimeError:
   Missing host to link to! Please provide :host parameter or set default_url_options[:host]
 # ./spec/routing/listing_routing_spec.rb:9:in `block (3 levels) in <top (required)>'

This code has nothing to do with emails/ActionMailer, it just happens to need a URL instead of a path.

Any ideas?


问:
Android, reload or refresh current fragment after click "ok" in DIALOG
This is my dialog inside fragment it works fine, now I want that when i click "ok" button it reload the current fragment. the dialog is show when the method showDialog is called:
mi fragment is  android.support.v4.app.Fragment

```<code>void showDialog() {
    LayoutInflater layoutInflater = LayoutInflater.from(getContext());
    View promptView = layoutInflater.inflate(R.layout.dialog_fragment_agenda, null);
    TextView txtNombre = (TextView)promptView.findViewById(R.id.txtdialog1);
    txtNombre.setText("ADD THIS STUFF?");
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
    alertDialogBuilder.setView(promptView);

    alertDialogBuilder.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            sendSomeStuff();
            //HERE TODO RELOAD OR REFRESH THE FRAGMENT

        }
    });
    alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

        } });
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}
</code>```

update
this is the fragment. Iwant to recall the onCreateView methos of the fragment

```<code>public class FragmentOne extends Fragment {
//...some variables
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fragment_one, container, false);
    showDialog()//HERE I CALL MY CUSTOM DIALOG

    return rootView;
}
}
</code>```

The Simple Solution

Tested using viewpager, and FragmentPagerAdapter

```<code>FragmentTransaction ft = getFragmentManager().beginTransaction();

ft.detach(FragmentOne.this).attach(FragmentOne.this).commit();
</code>```

答:
refresh fragment when fragment is visible to user</p>

```<code>    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
    super.setUserVisibleHint(isVisibleToUser)
    if(isVisibleToUser){
        if (getFragmentManager() != null) {
            getFragmentManager()
                ?.beginTransaction()
                ?.detach(this)
                ?.attach(this)
                ?.commit();
        }
    }
}
</code>```

Body:
This is my dialog inside fragment it works fine, now I want that when i click "ok" button it reload the current fragment. the dialog is show when the method showDialog is called:
mi fragment is  android.support.v4.app.Fragment

void showDialog() {
    LayoutInflater layoutInflater = LayoutInflater.from(getContext());
    View promptView = layoutInflater.inflate(R.layout.dialog_fragment_agenda, null);
    TextView txtNombre = (TextView)promptView.findViewById(R.id.txtdialog1);
    txtNombre.setText("ADD THIS STUFF?");
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
    alertDialogBuilder.setView(promptView);

    alertDialogBuilder.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            sendSomeStuff();
            //HERE TODO RELOAD OR REFRESH THE FRAGMENT

        }
    });
    alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

        } });
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

update
this is the fragment. Iwant to recall the onCreateView methos of the fragment

public class FragmentOne extends Fragment {
//...some variables
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fragment_one, container, false);
    showDialog()//HERE I CALL MY CUSTOM DIALOG

    return rootView;
}
}

The Simple Solution

Tested using viewpager, and FragmentPagerAdapter

FragmentTransaction ft = getFragmentManager().beginTransaction();

ft.detach(FragmentOne.this).attach(FragmentOne.this).commit();

Body:
refresh fragment when fragment is visible to user

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
    super.setUserVisibleHint(isVisibleToUser)
    if(isVisibleToUser){
        if (getFragmentManager() != null) {
            getFragmentManager()
                ?.beginTransaction()
                ?.detach(this)
                ?.attach(this)
                ?.commit();
        }
    }
}