问:
Different height for multiple prototype cells
Have 2 prototype cells. Each need to be a different size.So I have cell and cell1. Cell should be 40 and Cell needs to be 75.

I tried using heightForRowAt - Found out that that is called before cellForRowAt

I tired setting the height in the story board, for each cell

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "starshipCell", for: indexPath)
       let cell1 = tableView.dequeueReusableCell(withIdentifier: "starshipCell1", for: indexPath) as! SectionTableViewCell

       switch indexPath {
       case [4,0]:
           cell1.sectionLbl.text = "Armor".lowercased()
           cell1.detailTextLabel?.text = "Test"
           return cell1
       case [4,1]:
           cell.textLabel?.text = "Defensive Countermeasures"
           return cell
       case [4,2]:
           cell.textLabel?.text = "Shields"
           return cell
       case [11, 0]:
           cell.textLabel?.text = "Forward Arc"
           return cell
       case [11, 1]:
           cell.textLabel?.text = "Port Arc"
           return cell
       case [11, 2]:
           cell.textLabel?.text = "Starboard Arc"
           return cell
       case [11, 3]:
           cell.textLabel?.text = "Aft Arc"
           return cell
       case [11, 4]:
           cell.textLabel?.text = "Turret"
           return cell
       default:
           return cell
       }

      // return cell
   }

```

'Attempted to dequeue multiple cells for the same index path, which is not allowed. If you really need to dequeue more cells than the table view is requesting, use the -dequeueReusableCellWithIdentifier: method (without an index path). Cell identifier: starshipCell1, index path:  {length = 2, path = 0 - 0}'

So the above works perfectly. I just need to adjust the row height for those cells. Now the code isn't 100% complete. All the cases above will be changed and updated to cell1. The error is only when I use heightForRowAt

答:
Within the cellForRowAt method, you can only dequeue and return one cell. To return the right one given the index path, common practice is something more like the following:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell
    if indexPath.row == 0 { // starshipCell only appears if it's the first row
        cell = tableView.dequeueReusableCell(withIdentifier: "starshipCell", for: indexPath)
    } else { // Otherwise, we use starshipCell1
        cell = tableView.dequeueReusableCell(withIdentifier: "starshipCell1", for: indexPath) as! SectionTableViewCell
    }

    // Set up the cell here

    return cell
}
</code>```

This way, dequeueReusableCell is only called once per cell. (the error) heightForRowAt should be used similarly.

Body:
Have 2 prototype cells. Each need to be a different size.So I have cell and cell1. Cell should be 40 and Cell needs to be 75.

I tried using heightForRowAt - Found out that that is called before cellForRowAt

I tired setting the height in the story board, for each cell

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "starshipCell", for: indexPath)
       let cell1 = tableView.dequeueReusableCell(withIdentifier: "starshipCell1", for: indexPath) as! SectionTableViewCell

       switch indexPath {
       case [4,0]:
           cell1.sectionLbl.text = "Armor".lowercased()
           cell1.detailTextLabel?.text = "Test"
           return cell1
       case [4,1]:
           cell.textLabel?.text = "Defensive Countermeasures"
           return cell
       case [4,2]:
           cell.textLabel?.text = "Shields"
           return cell
       case [11, 0]:
           cell.textLabel?.text = "Forward Arc"
           return cell
       case [11, 1]:
           cell.textLabel?.text = "Port Arc"
           return cell
       case [11, 2]:
           cell.textLabel?.text = "Starboard Arc"
           return cell
       case [11, 3]:
           cell.textLabel?.text = "Aft Arc"
           return cell
       case [11, 4]:
           cell.textLabel?.text = "Turret"
           return cell
       default:
           return cell
       }

      // return cell
   }

'Attempted to dequeue multiple cells for the same index path, which is not allowed. If you really need to dequeue more cells than the table view is requesting, use the -dequeueReusableCellWithIdentifier: method (without an index path). Cell identifier: starshipCell1, index path:  {length = 2, path = 0 - 0}'

So the above works perfectly. I just need to adjust the row height for those cells. Now the code isn't 100% complete. All the cases above will be changed and updated to cell1. The error is only when I use heightForRowAt

Body:
Within the cellForRowAt method, you can only dequeue and return one cell. To return the right one given the index path, common practice is something more like the following:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell
    if indexPath.row == 0 { // starshipCell only appears if it's the first row
        cell = tableView.dequeueReusableCell(withIdentifier: "starshipCell", for: indexPath)
    } else { // Otherwise, we use starshipCell1
        cell = tableView.dequeueReusableCell(withIdentifier: "starshipCell1", for: indexPath) as! SectionTableViewCell
    }

    // Set up the cell here

    return cell
}

This way, dequeueReusableCell is only called once per cell. (the error) heightForRowAt should be used similarly.


来源: stackexchange

问:
Problem with interruptions in Arduino Uno
I work with interruptions in Arduino UNO. In this project, I want to when the Door is opened the LED blink 10 times, and when the door is closed again, stop blinking the LED and exit the function. But in this code the LED only turn on and off once and it does not flash again.
My other problem is that, when the door is opened or closed, sometimes the opened or closed word appears several times in the Series monitor.</p>

```<code>const byte LED_Red = 13;
const byte DOOR_SENSOR = 2; // magnetic door sensor pin

volatile int SensorState = LOW; // 0 close - 1 open wwitch

void setup()
{
Serial.begin(9600);
pinMode(LED_Red, OUTPUT);
pinMode(DOOR_SENSOR, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(DOOR_SENSOR), DoAction, CHANGE);
}

void DoAction()
{
    SensorState = digitalRead(DOOR_SENSOR);
    if (SensorState == HIGH) {
    Serial.println("Opened");
    blinkLED(10, 500);
}
    else {
    Serial.println("Closed");
        }
}

void blinkLED(int repeats, int time)
{
    for (int i = 0; i < repeats; i++) {
        if (SensorState == HIGH) {
        digitalWrite(LED_Red, HIGH);
        delay(time);
        digitalWrite(LED_Red, LOW);
        delay(time);
    }
    else
        return;
}
}

void loop()
{
}
</code>```

答:
You can't simply put a delay() on an interrupt's function. You need to just set a flag when the door is opened and based on that start blinkLED inside the main loop.

I also recommend you to use millis() function for an unblocking delay inside blinkLED function (e.g when you want to stop blinking while the door is closed).

```<code>const byte LED_Red = 13;
const byte DOOR_SENSOR = 2; // magnetic door sensor pin

// flag to check door is opened
volatile bool isOpened = false;

//flag to check already blinked
volatile bool isBlinked = false;

void setup()
{
    Serial.begin(9600);
    pinMode(LED_Red, OUTPUT);
    pinMode(DOOR_SENSOR, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(DOOR_SENSOR), DoAction, CHANGE);
}

void DoAction()
{
    if (digitalRead(DOOR_SENSOR) == HIGH)
    {
        //Serial.println("Opened");
        isOpened = true;
    }
    else
    {
        isOpened = false;
        isBlinked = false;
        //Serial.println("Closed");
    }
}

void blinkLED(int repeats, int time)
{
    byte LEDState = LOW;
    unsigned long delay_start = millis();
    for (int i = 0; i < 2 * repeats; i++)
    {
        //Toggle LED state
        if (LEDState == HIGH)
            LEDState = LOW;
        else
            LEDState = HIGH;
        // set value
        digitalWrite(LED_Red, LEDState);
        // some unblocking delay
        while (millis() - delay_start < time)
        {
            // return if door is closed
            if (!isOpened)
            {
                // turn off LED
                digitalWrite(LED_Red, LOW);
                return;
            }
        }
        delay_start = millis();
    }
    isBlinked = true;
}

void loop()
{
    // Check isBlinked beacue don't want to blink again until door is closed
    if (isOpened && !isBlinked)
    {
        blinkLED(10, 500);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I work with interruptions in Arduino UNO. In this project, I want to when the Door is opened the LED blink 10 times, and when the door is closed again, stop blinking the LED and exit the function. But in this code the LED only turn on and off once and it does not flash again.
My other problem is that, when the door is opened or closed, sometimes the opened or closed word appears several times in the Series monitor.

const byte LED_Red = 13;
const byte DOOR_SENSOR = 2; // magnetic door sensor pin

volatile int SensorState = LOW; // 0 close - 1 open wwitch

void setup()
{
Serial.begin(9600);
pinMode(LED_Red, OUTPUT);
pinMode(DOOR_SENSOR, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(DOOR_SENSOR), DoAction, CHANGE);
}

void DoAction()
{
    SensorState = digitalRead(DOOR_SENSOR);
    if (SensorState == HIGH) {
    Serial.println("Opened");
    blinkLED(10, 500);
}
    else {
    Serial.println("Closed");
        }
}

void blinkLED(int repeats, int time)
{
    for (int i = 0; i < repeats; i++) {
        if (SensorState == HIGH) {
        digitalWrite(LED_Red, HIGH);
        delay(time);
        digitalWrite(LED_Red, LOW);
        delay(time);
    }
    else
        return;
}
}

void loop()
{
}

Body:
You can't simply put a delay() on an interrupt's function. You need to just set a flag when the door is opened and based on that start blinkLED inside the main loop.

I also recommend you to use millis() function for an unblocking delay inside blinkLED function (e.g when you want to stop blinking while the door is closed).

const byte LED_Red = 13;
const byte DOOR_SENSOR = 2; // magnetic door sensor pin

// flag to check door is opened
volatile bool isOpened = false;

//flag to check already blinked
volatile bool isBlinked = false;

void setup()
{
    Serial.begin(9600);
    pinMode(LED_Red, OUTPUT);
    pinMode(DOOR_SENSOR, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(DOOR_SENSOR), DoAction, CHANGE);
}

void DoAction()
{
    if (digitalRead(DOOR_SENSOR) == HIGH)
    {
        //Serial.println("Opened");
        isOpened = true;
    }
    else
    {
        isOpened = false;
        isBlinked = false;
        //Serial.println("Closed");
    }
}

void blinkLED(int repeats, int time)
{
    byte LEDState = LOW;
    unsigned long delay_start = millis();
    for (int i = 0; i < 2 * repeats; i++)
    {
        //Toggle LED state
        if (LEDState == HIGH)
            LEDState = LOW;
        else
            LEDState = HIGH;
        // set value
        digitalWrite(LED_Red, LEDState);
        // some unblocking delay
        while (millis() - delay_start < time)
        {
            // return if door is closed
            if (!isOpened)
            {
                // turn off LED
                digitalWrite(LED_Red, LOW);
                return;
            }
        }
        delay_start = millis();
    }
    isBlinked = true;
}

void loop()
{
    // Check isBlinked beacue don't want to blink again until door is closed
    if (isOpened && !isBlinked)
    {
        blinkLED(10, 500);
    }
}


问:
cannot pass float array out of a function
I'm new to c++, and I want to pass a float array out of a function using a pointer. However, the returning array is always 0; I am running on an Arduino Uno.

This is my code. I want the readSensor() function to pass out a float array consisting of 3 floats. The float array should be pass to the pointer output*. But when I print out readings, it shows 0.00 instead of the values I passed out.

void setup() {
  Serial.begin(9600);
}

void loop() {
  float readings[3];
  readSensor(readings);
  for (int i = 0;i < 3;i++) {
    Serial.println(readings[i]);
  }
  delay(1000);
}

// pass out these 3 floats
float val1 = 3.14159;
float val2 = 2.741;
float val3 = 87;
void readSensor(float* output) {
  float container[3] = {val1, val2, val3};
  output = container;
}
```

答:
You can't "pass an array out of a function" in the way you seek.   C++ offers no such mechanism by simply using a pointer and a raw (C-style) array.

In your particular approach

```<code>void readSensor(float* output) {
 float container[3] = {val1, val2, val3};
 output = container;
}
</code>```

container ceases to exist when the function returns.  Also, output is passed by value, so the assignment output = container is not visible to the caller.

It is necessary to pass a pointer to (the first element of) an array into the function, and have the function copy data to it as needed.  For example,

```<code>void readSensor(float* output)
{
     float container[3] = {1, 2, 3};
     for (int i = 0; i < 3; ++i)
        output[i] = container[i];
}
</code>```

And the caller must supply the array and pass it.

```<code>int main()
{
     float result[3];
     readSensor(result);   // data will be copied into result
     // use result here
}
</code>```

Bear in mind that the caller is responsible for calling the function correctly.  For example if the caller of the function above passes an array with two elements, the behaviour is undefined.

A preferred way in C++ is to use a standard container, such as a std::vector.  For example;

```<code>#include <vector>

std::vector<float> readSensor()
{
     float container[3] = {1, 2, 3};
     std::vector<float> output;
     for (int i = 0; i < 3; ++i)
        output.push_back(container[i]);
     return output;
}

int main()
{
     std::vector<float> result;
     result = readSensor();
     // use result here
}
</code>```

If you don't know how to use standard containers, there is plenty of documentation around.

Body:
You can't "pass an array out of a function" in the way you seek.   C++ offers no such mechanism by simply using a pointer and a raw (C-style) array.

In your particular approach

void readSensor(float* output) {
 float container[3] = {val1, val2, val3};
 output = container;
}

container ceases to exist when the function returns.  Also, output is passed by value, so the assignment output = container is not visible to the caller.

It is necessary to pass a pointer to (the first element of) an array into the function, and have the function copy data to it as needed.  For example,

void readSensor(float* output)
{
     float container[3] = {1, 2, 3};
     for (int i = 0; i < 3; ++i)
        output[i] = container[i];
}

And the caller must supply the array and pass it.

int main()
{
     float result[3];
     readSensor(result);   // data will be copied into result
     // use result here
}

Bear in mind that the caller is responsible for calling the function correctly.  For example if the caller of the function above passes an array with two elements, the behaviour is undefined.

A preferred way in C++ is to use a standard container, such as a std::vector.  For example;

#include <vector>

std::vector<float> readSensor()
{
     float container[3] = {1, 2, 3};
     std::vector<float> output;
     for (int i = 0; i < 3; ++i)
        output.push_back(container[i]);
     return output;
}

int main()
{
     std::vector<float> result;
     result = readSensor();
     // use result here
}

If you don't know how to use standard containers, there is plenty of documentation around.


问:
Extension of STL container through composition or free functions?
Say I need a new type in my application, that consists of a std::vector<int> extended by a single function. The straightforward way would be composition (due to limitations in inheritance of STL containers):

```<code>class A {
    public:
        A(std::vector<int> & vec) : vec_(vec) {}
        int hash();
    private:
        std::vector<int> vec_
}
</code>```

This requires the user to first construct a vector<int> and a copy in the constructor, which is bad when we are going to handle a sizeable number of large vectors. One could, of course, write a pass-through to push_back(), but this introduces mutable state, which I would like to avoid.

So it seems to me, that we can either avoid copies or keep A immutable, is this correct?

If so, the simplest (and efficiency-wise equivalent) way would be to use a typedef and free functions at namespace scope:

```<code>namespace N {
typedef std::vector<int> A;
int a_hash(const A & a);
}
</code>```

This just feels wrong somehow, since extensions in the future will "pollute" the namespace. Also, calling a_hash(...) on any vector<int> is possible, which might lead to unexpected results (assuming that we impose constraints on A the user has to follow or that would otherwise be enforced in the first example)

My two questions are:

how can one not sacrifice both immutability and efficiency when using the above class code?

when does it make sense to use free functions as opposed to encapsulation in classes/structs?

Thank you!

答:
Hashing is an algorithm not a type, and probably shouldn't be restricted to data in any particular container type either. If you want to provide hashing, it probably makes the most sense to create a functor that computes a hash one element (int, as you've written things above) at a time, then use std::accumulate or std::for_each to apply that to a collection:

```<code>namespace whatever {
struct hasher {
    int current_hash;
public:
    hasher() : current_hash(0x1234) {}

    // incredibly simplistic hash: just XOR the values together.
    operator()(int new_val) { current_hash ^= new_val; }
    operator int() { return current_hash; }
};
}

int hash = std::for_each(coll.begin(), coll.end(), whatever::hasher());
</code>```

Note that this allows coll to be a vector, or a deque or you can use a pair of istream_iterators to hash data in a file...

ContentLicense: CC BY-SA 3.0

Body:
Say I need a new type in my application, that consists of a std::vector<int> extended by a single function. The straightforward way would be composition (due to limitations in inheritance of STL containers):

class A {
    public:
        A(std::vector<int> & vec) : vec_(vec) {}
        int hash();
    private:
        std::vector<int> vec_
}

This requires the user to first construct a vector<int> and a copy in the constructor, which is bad when we are going to handle a sizeable number of large vectors. One could, of course, write a pass-through to push_back(), but this introduces mutable state, which I would like to avoid.

So it seems to me, that we can either avoid copies or keep A immutable, is this correct?

If so, the simplest (and efficiency-wise equivalent) way would be to use a typedef and free functions at namespace scope:

namespace N {
typedef std::vector<int> A;
int a_hash(const A & a);
}

This just feels wrong somehow, since extensions in the future will "pollute" the namespace. Also, calling a_hash(...) on any vector<int> is possible, which might lead to unexpected results (assuming that we impose constraints on A the user has to follow or that would otherwise be enforced in the first example)

My two questions are:

how can one not sacrifice both immutability and efficiency when using the above class code?

when does it make sense to use free functions as opposed to encapsulation in classes/structs?

Thank you!

Body:
Hashing is an algorithm not a type, and probably shouldn't be restricted to data in any particular container type either. If you want to provide hashing, it probably makes the most sense to create a functor that computes a hash one element (int, as you've written things above) at a time, then use std::accumulate or std::for_each to apply that to a collection:

namespace whatever {
struct hasher {
    int current_hash;
public:
    hasher() : current_hash(0x1234) {}

    // incredibly simplistic hash: just XOR the values together.
    operator()(int new_val) { current_hash ^= new_val; }
    operator int() { return current_hash; }
};
}

int hash = std::for_each(coll.begin(), coll.end(), whatever::hasher());

Note that this allows coll to be a vector, or a deque or you can use a pair of istream_iterators to hash data in a file...


问:
ViewPager animation fade in/out instead of slide
I got the FragmentBasics example from here. Is there a way make the ViewPager animation simply fade in and out when I swipe instead of sliding left and right? I've been trying some stuff with PageTransformer, but no success, I can still see it sliding. So I guess I need to somehow force its position to stay put, while sliding my finger only affects the alpha.</p>

```<code>public class SecondActivity extends Activity {

SectionsPagerAdapter mSectionsPagerAdapter;

ViewPager mViewPager;

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

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setPageTransformer(false, new FadePageTransformer());
    mViewPager.setAdapter(mSectionsPagerAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.second, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        case 2:
            return getString(R.string.title_section3).toUpperCase(l);
        }
        return null;
    }
}

public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_second, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

public class FadePageTransformer implements ViewPager.PageTransformer {
        public void transformPage(View view, float position) {

            if (position < -1 || position > 1) {
                view.setAlpha(0);
            }
            else if (position <= 0 || position <= 1) {
                // Calculate alpha. Position is decimal in [-1,0] or [0,1]
                float alpha = (position <= 0) ? position + 1 : 1 - position;
                view.setAlpha(alpha);
            }
            else if (position == 0) {
                view.setAlpha(1);
            }
        }
    }
</code>```

答:
Fade according to Google:
https://developer.android.com/training/animation/reveal-or-hide-view</p>
```<code>viewPager.setPageTransformer(false, new ViewPager.PageTransformer() {
    @Override
    public void transformPage(@NonNull View page, float position) {
        page.setAlpha(0f);
        page.setVisibility(View.VISIBLE);

        // Start Animation for a short period of time
        page.animate()
            .alpha(1f)
            .setDuration(page.getResources().getInteger(android.R.integer.config_shortAnimTime));
    }
});
</code>```

Body:
I got the FragmentBasics example from here. Is there a way make the ViewPager animation simply fade in and out when I swipe instead of sliding left and right? I've been trying some stuff with PageTransformer, but no success, I can still see it sliding. So I guess I need to somehow force its position to stay put, while sliding my finger only affects the alpha.

public class SecondActivity extends Activity {

SectionsPagerAdapter mSectionsPagerAdapter;

ViewPager mViewPager;

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

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setPageTransformer(false, new FadePageTransformer());
    mViewPager.setAdapter(mSectionsPagerAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.second, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        case 2:
            return getString(R.string.title_section3).toUpperCase(l);
        }
        return null;
    }
}

public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_second, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

public class FadePageTransformer implements ViewPager.PageTransformer {
        public void transformPage(View view, float position) {

            if (position < -1 || position > 1) {
                view.setAlpha(0);
            }
            else if (position <= 0 || position <= 1) {
                // Calculate alpha. Position is decimal in [-1,0] or [0,1]
                float alpha = (position <= 0) ? position + 1 : 1 - position;
                view.setAlpha(alpha);
            }
            else if (position == 0) {
                view.setAlpha(1);
            }
        }
    }

Body:
Fade according to Google:
https://developer.android.com/training/animation/reveal-or-hide-view

viewPager.setPageTransformer(false, new ViewPager.PageTransformer() {
    @Override
    public void transformPage(@NonNull View page, float position) {
        page.setAlpha(0f);
        page.setVisibility(View.VISIBLE);

        // Start Animation for a short period of time
        page.animate()
            .alpha(1f)
            .setDuration(page.getResources().getInteger(android.R.integer.config_shortAnimTime));
    }
});


问:
JedisMovedDataException (When using sadd with pipeline)
I have a 3 node EC2 redis cluster setup and I am trying to add records to redis (using sadd) with pipeline mode.

I get the following error after adding about 70/82 and 81 keys in 3 nodes:

```<code>    Exception in thread "main" redis.clients.jedis.exceptions.JedisMovedDataException: MOVED 1539 172.31.59.103:6379
at redis.clients.jedis.Protocol.processError(Protocol.java:93)
at redis.clients.jedis.Protocol.process(Protocol.java:122)
at redis.clients.jedis.Protocol.read(Protocol.java:191)
at redis.clients.jedis.Connection.getOne(Connection.java:258)
at redis.clients.jedis.ShardedJedisPipeline.sync(ShardedJedisPipeline.java:44)
at org.hu.e63.MovieLens21MPipeline.push(MovieLens21MPipeline.java:47)
at org.hu.e63.MovieLens21MPipeline.main(MovieLens21MPipeline.java:53
</code>```

I have looked at this thread, my code pretty much looks like that:

Input file is from here(ratings.csv): http://files.grouplens.org/datasets/movielens/ml-latest-small.zip

Here's the code:

```<code>import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPipeline;

public class MovieLens21MPipeline {
    ShardedJedis jedis;

    public MovieLens21MPipeline() {
        JedisShardInfo si = new JedisShardInfo("172.31.59.103", 6379, 5000);
        List<JedisShardInfo> list = new ArrayList<JedisShardInfo>();
        list.add(si);
        list.add(new JedisShardInfo("172.31.59.104", 6379, 5000));
        list.add(new JedisShardInfo("172.31.59.105", 6379, 5000));

        jedis = new ShardedJedis(list);
    }

    public void push() {
        ShardedJedisPipeline pipeline = jedis.pipelined();
        Scanner s;

        try {
            s = new Scanner(new File("input/ratings.csv"));

            StringBuilder key = new StringBuilder();
            String s1 = s.nextLine(); // Skip first line
            while (s.hasNextLine()) {
                s1 = s.nextLine();
                String[] spl = s1.split(",");
                // key="u:"+spl[0]+":m";
                key.append("u:").append(spl[0]).append(":m");
                pipeline.sadd(key.toString(), spl[1]);
                key.setLength(0);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("bye" + e.getMessage());
        }

        pipeline.sync();
    }

    public static void main(String[] args) {
        MovieLens21MPipeline obj = new MovieLens21MPipeline();
        long startTime = System.currentTimeMillis();
        obj.push();
        long endTime = System.currentTimeMillis();
        double d = 0.0;
        d = (double) (endTime - startTime);
        System.out.println("Throughput: " + d);
    }
}
</code>```

Any help appreciated.

答:
Just like Lim said, you are using Redis in cluster mode. Use JedisCluster can solve this problem. In addition, as a supplement, why JedisCluster works?

We can known that from JedisCluster source code.

```<code>private T runWithRetries(byte[] key, int attempts, boolean tryRandomNode, boolean asking) {
    if (attempts <= 0) {
        throw new JedisClusterMaxRedirectionsException("Too many Cluster redirections?");
    }

    Jedis connection = null;
    try {
        // omit ... get connection
        return execute(connection);

    } catch (JedisNoReachableClusterNodeException jnrcne) {
        throw jnrcne;
    } catch (JedisConnectionException jce) {
        // release current connection before recursion
        // omit

        return runWithRetries(key, attempts - 1, tryRandomNode, asking);
    } catch (JedisRedirectionException jre) {
        // if MOVED redirection occurred,
        if (jre instanceof JedisMovedDataException) {
            // here is the key point
            // it rebuilds cluster's slot cache
            // recommended by Redis cluster specification
            // Jedis or ShardedJedis won't run this code
            this.connectionHandler.renewSlotCache(connection);
        }

        // omit ...

        return runWithRetries(key, attempts - 1, false, asking);
    } finally {
        releaseConnection(connection);
    }
}
</code>```

Body:
I have a 3 node EC2 redis cluster setup and I am trying to add records to redis (using sadd) with pipeline mode.

I get the following error after adding about 70/82 and 81 keys in 3 nodes:

    Exception in thread "main" redis.clients.jedis.exceptions.JedisMovedDataException: MOVED 1539 172.31.59.103:6379
at redis.clients.jedis.Protocol.processError(Protocol.java:93)
at redis.clients.jedis.Protocol.process(Protocol.java:122)
at redis.clients.jedis.Protocol.read(Protocol.java:191)
at redis.clients.jedis.Connection.getOne(Connection.java:258)
at redis.clients.jedis.ShardedJedisPipeline.sync(ShardedJedisPipeline.java:44)
at org.hu.e63.MovieLens21MPipeline.push(MovieLens21MPipeline.java:47)
at org.hu.e63.MovieLens21MPipeline.main(MovieLens21MPipeline.java:53

I have looked at this thread, my code pretty much looks like that:

Input file is from here(ratings.csv): http://files.grouplens.org/datasets/movielens/ml-latest-small.zip

Here's the code:

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPipeline;

public class MovieLens21MPipeline {
    ShardedJedis jedis;

    public MovieLens21MPipeline() {
        JedisShardInfo si = new JedisShardInfo("172.31.59.103", 6379, 5000);
        List<JedisShardInfo> list = new ArrayList<JedisShardInfo>();
        list.add(si);
        list.add(new JedisShardInfo("172.31.59.104", 6379, 5000));
        list.add(new JedisShardInfo("172.31.59.105", 6379, 5000));

        jedis = new ShardedJedis(list);
    }

    public void push() {
        ShardedJedisPipeline pipeline = jedis.pipelined();
        Scanner s;

        try {
            s = new Scanner(new File("input/ratings.csv"));

            StringBuilder key = new StringBuilder();
            String s1 = s.nextLine(); // Skip first line
            while (s.hasNextLine()) {
                s1 = s.nextLine();
                String[] spl = s1.split(",");
                // key="u:"+spl[0]+":m";
                key.append("u:").append(spl[0]).append(":m");
                pipeline.sadd(key.toString(), spl[1]);
                key.setLength(0);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("bye" + e.getMessage());
        }

        pipeline.sync();
    }

    public static void main(String[] args) {
        MovieLens21MPipeline obj = new MovieLens21MPipeline();
        long startTime = System.currentTimeMillis();
        obj.push();
        long endTime = System.currentTimeMillis();
        double d = 0.0;
        d = (double) (endTime - startTime);
        System.out.println("Throughput: " + d);
    }
}

Any help appreciated.

Body:
Just like Lim said, you are using Redis in cluster mode. Use JedisCluster can solve this problem. In addition, as a supplement, why JedisCluster works?

We can known that from JedisCluster source code.

private T runWithRetries(byte[] key, int attempts, boolean tryRandomNode, boolean asking) {
    if (attempts <= 0) {
        throw new JedisClusterMaxRedirectionsException("Too many Cluster redirections?");
    }

    Jedis connection = null;
    try {
        // omit ... get connection
        return execute(connection);

    } catch (JedisNoReachableClusterNodeException jnrcne) {
        throw jnrcne;
    } catch (JedisConnectionException jce) {
        // release current connection before recursion
        // omit

        return runWithRetries(key, attempts - 1, tryRandomNode, asking);
    } catch (JedisRedirectionException jre) {
        // if MOVED redirection occurred,
        if (jre instanceof JedisMovedDataException) {
            // here is the key point
            // it rebuilds cluster's slot cache
            // recommended by Redis cluster specification
            // Jedis or ShardedJedis won't run this code
            this.connectionHandler.renewSlotCache(connection);
        }

        // omit ...

        return runWithRetries(key, attempts - 1, false, asking);
    } finally {
        releaseConnection(connection);
    }
}


问:
Mongo-go how to use arrayFilter to find elem in "array of objects inside array of objects"
Lets imagine a JSON like:

```<code>"user": {
  "id": "1234",
  ...some fields,
  "achievements": [
    {
      "scope": "life achievements",
      "list": [
        {"_id": 1, "title": "some text", "gotAt": "some date"},
        {"_id": 2, "title": "some other text", "gotAt": "some date"}
      ]
    },
    {
      "scope": "sport achievements",
      "list": [
        {"_id": 1, "title": "sport", "gotAt": "some date"},
        {"_id": 2, "title": "some other sport", "gotAt": "some date"}
      ]
    },
    {
      "scope": "academic achievements",
      "list": [
        {"_id": 1, "title": "some text", "gotAt": "some date"},
        {"_id": 2, "title": "some other text", "gotAt": "some date"}
      ]
    },
  ]
}
</code>```

I need to UPDATE for example the first life achievement (with id 1) using mongoDb and Golang driver Mongo-go for it

The problem is in the nesting level. I can get some array element by $ mongoDb operator, but here i need to identify every user achievement by the activity scope (life, sport, academic etc) and _id field of achievement. So I need to make a search inside an array of objects inside other array of objects.

Thats what ive done (it doesnt work anyway)

doc := coll.FindOneAndUpdate(
        context.Background(),
        bson.D{
            {"_id", "1234"},
            {"achievements.scope", "life achievements"},
            {"achievements.list._id", 1},
        },
        bson.D{
            {"$set", bson.D{
                {"achievements.$.list.$[elem].title", "some new test"},
            }},
        },
        options.FindOneAndUpdate().SetArrayFilters(options.ArrayFilters{
            Filters: append(make([]interface{}, 0), bson.D{
                {"elem", bson.D{
                    {"achievements.list._id", 1},
                }},
            }),
        }).SetReturnDocument(1),
    )
```

I expect this query to update only one element specified by "id" and "scope" fields. May be I use arrayFilters incorretly, or may be I set  param of FindOneAndUpdate function incorrectly. Now it doesnt throw any error nor updates the document. Please help me

答:
With the package go.mongodb.org/mongo-driver/mongo you can do it like this:

coll.FindOneAndUpdate(
    context.Background(),
    bson.D{
        {"id", "1234"},
        {"achievements.scope", "life achievements"},
        {"achievements.list._id", 1},
    },
    bson.M{"$set": bson.M{"achievements.$.list.$[elem].title": "some new test"}},
    options.FindOneAndUpdate().SetArrayFilters(options.ArrayFilters{
        Filters: []interface{}{bson.M{"elem._id": 1}},
    }),
)
```
<p>which "translates" to shell:</p>
<pre class="lang-golang prettyprint-override"><code>db.user.findOneAndUpdate(
  {"id": "1234","achievements.scope": "life achievements","achievements.list._id": 1},
  {$set: {"achievements.$.list.$[elem].title": "some new test"}},
  {arrayFilters: [{"elem._id": 1}]}
)
</code>```

Body:
Lets imagine a JSON like:

"user": {
  "id": "1234",
  ...some fields,
  "achievements": [
    {
      "scope": "life achievements",
      "list": [
        {"_id": 1, "title": "some text", "gotAt": "some date"},
        {"_id": 2, "title": "some other text", "gotAt": "some date"}
      ]
    },
    {
      "scope": "sport achievements",
      "list": [
        {"_id": 1, "title": "sport", "gotAt": "some date"},
        {"_id": 2, "title": "some other sport", "gotAt": "some date"}
      ]
    },
    {
      "scope": "academic achievements",
      "list": [
        {"_id": 1, "title": "some text", "gotAt": "some date"},
        {"_id": 2, "title": "some other text", "gotAt": "some date"}
      ]
    },
  ]
}

I need to UPDATE for example the first life achievement (with id 1) using mongoDb and Golang driver Mongo-go for it

The problem is in the nesting level. I can get some array element by $ mongoDb operator, but here i need to identify every user achievement by the activity scope (life, sport, academic etc) and _id field of achievement. So I need to make a search inside an array of objects inside other array of objects.

Thats what ive done (it doesnt work anyway)

doc := coll.FindOneAndUpdate(
        context.Background(),
        bson.D{
            {"_id", "1234"},
            {"achievements.scope", "life achievements"},
            {"achievements.list._id", 1},
        },
        bson.D{
            {"$set", bson.D{
                {"achievements.$.list.$[elem].title", "some new test"},
            }},
        },
        options.FindOneAndUpdate().SetArrayFilters(options.ArrayFilters{
            Filters: append(make([]interface{}, 0), bson.D{
                {"elem", bson.D{
                    {"achievements.list._id", 1},
                }},
            }),
        }).SetReturnDocument(1),
    )

I expect this query to update only one element specified by "id" and "scope" fields. May be I use arrayFilters incorretly, or may be I set  param of FindOneAndUpdate function incorrectly. Now it doesnt throw any error nor updates the document. Please help me

Body:
With the package go.mongodb.org/mongo-driver/mongo you can do it like this:

coll.FindOneAndUpdate(
    context.Background(),
    bson.D{
        {"id", "1234"},
        {"achievements.scope", "life achievements"},
        {"achievements.list._id", 1},
    },
    bson.M{"$set": bson.M{"achievements.$.list.$[elem].title": "some new test"}},
    options.FindOneAndUpdate().SetArrayFilters(options.ArrayFilters{
        Filters: []interface{}{bson.M{"elem._id": 1}},
    }),
)

which "translates" to shell:

db.user.findOneAndUpdate(
  {"id": "1234","achievements.scope": "life achievements","achievements.list._id": 1},
  {$set: {"achievements.$.list.$[elem].title": "some new test"}},
  {arrayFilters: [{"elem._id": 1}]}
)


问:
Selecting max and min dates in a group by with null values
I am trying to find the max and min dates of users in my app from two different tables, but some users exist in one table and some the other, and some both.

Here is an example of my tables

```<code>Table A:
Id  Action        Date
1   A           2019-01-19
1   B           2019-02-19
2   A           2019-02-19
2   B           2019-03-19
3   A           2019-05-19
3   B           2019-06-19

Table B:
Id  Action      Date
1   A           2019-01-19
1   B           2019-02-19
2   A           2019-03-19
2   B           2019-04-19
4   A           2019-05-19
4   B           2019-06-19
</code>```

Each table represents some action the user is performing and the date it occurs. They are distinct separate actions so there is no possibility of having them in 1 table. ID in this example is the user ID.

What is join both tables in user ids, and find the max and min dates for all actions. So in the example above, I would expect the result to be something like

```<code>Result:
Id   Min         Max
1    2019-01-19  2019-02-19
2    2019-02-19  2019-04-19
3    2019-05-19  2019-06-19
4    2019-05-19  2019-06-19
</code>```

What I tried doing is something like:

```<code>SELECT A.Id, LEAST(min(A.Date), min(B.Date)), GREATEST(max(A.Date, B.Date))
FROM A
JOIN A.Id = B.Id
GROUP BY A.Id
</code>```

but this is clearly not right because it groups by only users in table A, and will Users that only exist in table B. I started to play with full joins but was having issues with the group by statement because a user may not exist in either of the tables.

I am sure I am completely over complicating this, so please feel free to steer me in any direction that makes sense aside from restructuring the schema because the data has already been collected.

Here is SQL Fiddle: http://sqlfiddle.com/#!9/74ce9f/9

答:
We can try taking a union of both tables, followed by an aggregation by the id:

```<code>SELECT
    Id,
    MIN(Date) AS Min,
    MAX(Date) AS Max
FROM
(
    SELECT Id, Date FROM A
    UNION ALL
    SELECT Id, Date FROM B
) t
GROUP BY Id;
</code>```

Body:
I am trying to find the max and min dates of users in my app from two different tables, but some users exist in one table and some the other, and some both.

Here is an example of my tables

Table A:
Id  Action        Date
1   A           2019-01-19
1   B           2019-02-19
2   A           2019-02-19
2   B           2019-03-19
3   A           2019-05-19
3   B           2019-06-19

Table B:
Id  Action      Date
1   A           2019-01-19
1   B           2019-02-19
2   A           2019-03-19
2   B           2019-04-19
4   A           2019-05-19
4   B           2019-06-19

Each table represents some action the user is performing and the date it occurs. They are distinct separate actions so there is no possibility of having them in 1 table. ID in this example is the user ID.

What is join both tables in user ids, and find the max and min dates for all actions. So in the example above, I would expect the result to be something like

Result:
Id   Min         Max
1    2019-01-19  2019-02-19
2    2019-02-19  2019-04-19
3    2019-05-19  2019-06-19
4    2019-05-19  2019-06-19

What I tried doing is something like:

SELECT A.Id, LEAST(min(A.Date), min(B.Date)), GREATEST(max(A.Date, B.Date))
FROM A
JOIN A.Id = B.Id
GROUP BY A.Id

but this is clearly not right because it groups by only users in table A, and will Users that only exist in table B. I started to play with full joins but was having issues with the group by statement because a user may not exist in either of the tables.

I am sure I am completely over complicating this, so please feel free to steer me in any direction that makes sense aside from restructuring the schema because the data has already been collected.

Here is SQL Fiddle: http://sqlfiddle.com/#!9/74ce9f/9

Body:
We can try taking a union of both tables, followed by an aggregation by the id:

SELECT
    Id,
    MIN(Date) AS Min,
    MAX(Date) AS Max
FROM
(
    SELECT Id, Date FROM A
    UNION ALL
    SELECT Id, Date FROM B
) t
GROUP BY Id;


问:
How do I set the path to a DLL file in Visual Studio?
I developed an application that depends on a DLL file. When I debug my application, the applicationwould complain that:

"This application has failed to start because xxx.dll was not found."

So I have to copy the DLL file into the same directory as my .vcproj file.

Is there a way to set the project to look for the DLL file in (preferably) some relative path or (not preferred) some absolute path?

Similar concept to how we set include and library path in the project settings.

I mean when I debug my application (hitting F5) the above error would pop up.

答:
In your Project properties(Right click on project, click on property button) ▶ Configuration Properties ▶ Build Events ▶ Post Build Events ▶ Command Line.

Edit and add one instruction to command line.
for example copy botan.dll from source path to location where is being executed the program.

```<code>copy /Y "$(SolutionDir)ProjectDirs\x64\Botan\lib\botan.dll" "$(TargetDir)"
</code>```

Body:
In your Project properties(Right click on project, click on property button) ▶ Configuration Properties ▶ Build Events ▶ Post Build Events ▶ Command Line.

Edit and add one instruction to command line.
for example copy botan.dll from source path to location where is being executed the program.

copy /Y "$(SolutionDir)ProjectDirs\x64\Botan\lib\botan.dll" "$(TargetDir)"


问:
How to see python docs for opencv?
Cant find python documentation for opencv.

I am using python and try to do some denoising using opencv as in this tutorial:

https://docs.opencv.org/3.2.0/d5/d69/tutorial_py_non_local_means.html

However,  when I want to check the parameters to the function and click on for example "cv2.fastNlMeansDenoising" I come to the documentation for the C++-implementation. How can I find the python documentation?!

答:
Edit - November 10, 2021

The most recent version of the OpenCV docs (4.5.4 at the time of this writing) has the Python signatures directly below the C++ signatures.  For your specific case, the function you are interested in can be found here: https://docs.opencv.org/4.5.4/d1/d79/group__photo__denoise.html#ga4c6b0031f56ea3f98f768881279ffe93

Outdated (here for posterity)

OpenCV 3.0 beta docs are the last known stable docs for the Python functions. Unfortunately, anything after they don't show you the equivalent calls between C++ and Python.  I use these as a guide, but take them with a grain of salt.

For your specific case: https://docs.opencv.org/3.0-beta/modules/photo/doc/denoising.html?highlight=denoising#fastnlmeansdenoising

Title: How to see python docs for opencv?


问:
why irb plugins not loaded in rails console session?
I have installed both awsome print & hirb irb plugins to Ruby 1.9.2 through rvm. I can able to access it from irb session. But when i tried from rails console, i got the error

```<code>ruby-1.9.2-p180 :001 > require "hirb"
LoadError: no such file to load -- hirb
</code>```

What could be the reason?

答: You have to add hirb to Gemfile.

Body:
I have installed both awsome print & hirb irb plugins to Ruby 1.9.2 through rvm. I can able to access it from irb session. But when i tried from rails console, i got the error

ruby-1.9.2-p180 :001 > require "hirb"
LoadError: no such file to load -- hirb

What could be the reason?

Body: You have to add hirb to Gemfile.


问:
How to put each string into variables from a txt file in batch
I wondering if there is a way to put each string into variables from a txt file in Batch language, like :

Alim.txt  file :

```<code>381b4222-f694-41f0-9685-ff5bb260df2e   Utilisation_normale

8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c   Performances_élevées

a1841308-3541-4fab-bc81-f71556f20b4a   Économie_d'énergie
</code>```

result:

```<code>var1=381b4222-f694-41f0-9685-ff5bb260df2e

var2=Utilisation_normale

var3=8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c

var4=Performances_élevées

var5=a1841308-3541-4fab-bc81-f71556f20b4a

var6=Économie_d'énergie
</code>```

with a count number if possible

In a simple way, I’m not very good in Batchl. I will appreciate any kind of information

答:
You can accomplish this using the script below:

```<code>@echo off
setlocal enabledelayedexpansion
set _count=0
for /f "tokens=1* delims= " %%a in ('type Alim.txt') do (
    set /a _count=!_count!+1
    set var!_count!=%%a
    set /a _count=!_count!+1
    set var!_count!=%%b
)
</code>```

Explanation

setlocal enabledelayedexpansion enables delayed expansion to allow setting variables inside a for loop.

set _count=0 creates a counter variable for setting the variables.

type Alim.txt prints the contents of the Alim.txt file.

for /f "tokens=1* delims= " %%a in ('...') do loops through each line in Alim.txt, splitting them by spaces and saving those parts to %%a and %%b.

set /a _count=!_count!+1 increments the _count variable.

set var!_count!=%%a and set var!_count!=%%b set a variable based on the current _count variable (ex: var1=381b4222-f694-41f0-9685-ff5bb260df2e).

For reference

Setlocal - SS64.com

Delayed Expansion - SS64.com

For /F command - SS64.com

Set - SS64.com

Body:
I wondering if there is a way to put each string into variables from a txt file in Batch language, like :

Alim.txt  file :

381b4222-f694-41f0-9685-ff5bb260df2e   Utilisation_normale

8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c   Performances_élevées

a1841308-3541-4fab-bc81-f71556f20b4a   Économie_d'énergie

result:

var1=381b4222-f694-41f0-9685-ff5bb260df2e

var2=Utilisation_normale

var3=8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c

var4=Performances_élevées

var5=a1841308-3541-4fab-bc81-f71556f20b4a

var6=Économie_d'énergie

with a count number if possible

In a simple way, I’m not very good in Batchl. I will appreciate any kind of information

Body:
You can accomplish this using the script below:

@echo off
setlocal enabledelayedexpansion
set _count=0
for /f "tokens=1* delims= " %%a in ('type Alim.txt') do (
    set /a _count=!_count!+1
    set var!_count!=%%a
    set /a _count=!_count!+1
    set var!_count!=%%b
)

Explanation

setlocal enabledelayedexpansion enables delayed expansion to allow setting variables inside a for loop.

set _count=0 creates a counter variable for setting the variables.

type Alim.txt prints the contents of the Alim.txt file.

for /f "tokens=1* delims= " %%a in ('...') do loops through each line in Alim.txt, splitting them by spaces and saving those parts to %%a and %%b.

set /a _count=!_count!+1 increments the _count variable.

set var!_count!=%%a and set var!_count!=%%b set a variable based on the current _count variable (ex: var1=381b4222-f694-41f0-9685-ff5bb260df2e).

For reference

Setlocal - SS64.com

Delayed Expansion - SS64.com

For /F command - SS64.com

Set - SS64.com


问:
DataTables Uncaught TypeError: Cannot set property 'pdfMake' of undefined
I'm attempting to set up Datatables for a table.  There is nothing particularly unusual about the table (content has been left blank in this example), and I believe I have included all the correct files for Datatables to function, however, there is an javascript error:

buttons.html5.min.js:11 Uncaught TypeError: Cannot set property 'pdfMake' of undefined

```<code>   <head>
    <link rel="stylesheet" href="../js/jquery-ui-1.12.1/jquery-ui.css">

    <script type="text/javascript" src="../js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="../js/jquery.cookie.js"></script>
    <script type="text/javascript" src="../js/jquery-ui-1.12.1/jquery-ui.js"></script>
    <script type="text/javascript" src="../js/DataTables-1.10.18/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="../js/Buttons-1.5.4/js/buttons.html5.min.js"></script>
    <script type="text/javascript" src="../js/Buttons-1.5.4/js/dataTables.buttons.min.js"></script>

    <script type="text/javascript" src="../js/pdfmake-0.1.36/pdfmake.min.js"></script>
    <script type="text/javascript" src="../js/JSZip-2.5.0/jszip.min.js"></script>
    <script type="text/javascript" src="../js/pdfmake-0.1.36/vfs_fonts.js"></script>
    <script type="text/javascript" src="../js/Buttons-1.5.4/js/buttons.colVis.min.js"></script>
    <script type="text/javascript" src="../js/Responsive-2.2.2/js/dataTables.responsive.min.js"></script>
    <link rel="stylesheet" type="text/css" href="../js/Buttons-1.5.4/css/buttons.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="../js/DataTables-1.10.18/css/jquery.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="../js/Responsive-2.2.2/css/responsive.dataTables.min.css">
</head>
<body><table id="termtable7"></table></body>
<script>
$(document).ready(function(){
    var datatable=$('#termtable'+question_id).DataTable({
       dom:'Bfrtip',
       buttons:['columnsToggle', 'copy', 'excel', 'pdf'],
      responsive:true
    });
});
</script>
</code>```

The only buttons that are displayed are the columnsToggle and the search option.  The other buttons are missing due to the error.

Would anyone have an understanding of Datatables that could clue me in on what is really going on here?

答:
Probably it is late to answer this question but might help someone else..

I had to change my loading order to following and error went away. Pay attention to what loading order of javascript files. Order has to be exactly same order otherwise components are not going to be found.

```<code><script src="js/jquery-3.4.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/jquery.dataTables.min.js"></script>
<script src="js/dataTables.buttons.min.js"></script>
<script src="js/pdfmake.min.js"></script>
<script src="js/buttons.html5.min.js"></script>
<script src="js/buttons.print.min.js"></script>
</code>```

Body:
I'm attempting to set up Datatables for a table.  There is nothing particularly unusual about the table (content has been left blank in this example), and I believe I have included all the correct files for Datatables to function, however, there is an javascript error:

buttons.html5.min.js:11 Uncaught TypeError: Cannot set property 'pdfMake' of undefined

    <link rel="stylesheet" href="../js/jquery-ui-1.12.1/jquery-ui.css">

    <link rel="stylesheet" type="text/css" href="../js/Buttons-1.5.4/css/buttons.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="../js/DataTables-1.10.18/css/jquery.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="../js/Responsive-2.2.2/css/responsive.dataTables.min.css">

The only buttons that are displayed are the columnsToggle and the search option.  The other buttons are missing due to the error.

Would anyone have an understanding of Datatables that could clue me in on what is really going on here?

Body:
Probably it is late to answer this question but might help someone else..

I had to change my loading order to following and error went away. Pay attention to what loading order of javascript files. Order has to be exactly same order otherwise components are not going to be found.

<script src="js/jquery-3.4.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/jquery.dataTables.min.js"></script>
<script src="js/dataTables.buttons.min.js"></script>
<script src="js/pdfmake.min.js"></script>
<script src="js/buttons.html5.min.js"></script>
<script src="js/buttons.print.min.js"></script>


问:
How do I generate random numbers without rand() function?
I want to generate (pseudo) random numbers between 0 and some integer. I don't mind if they aren't too random. I have access to the current time of the day but not the rand function. Can anyone think of a sufficiently robust way to generate these? Perhaps, discarding some bits from time of day and taking modulo my integer or something?

I am using c.

答:
```<code>import java.io.*;
public class random{
public static class p{

}
static long reg=0;
static long lfsr()
{
    if(reg==0)
    {
        reg=145896027340307l;
    }
    long bit=(reg>>0^reg>>2^reg>>3^reg>>5)&1;
    reg=reg>>1|bit<<62;
    return reg;
}
static long getRand()
{
    String s=String.valueOf(new p());
    //System.out.println(s);
    long n=0;
    lfsr();
    for(int i=0;i<s.length();i++)
    {
        n=n<<8|+s.charAt(i);
    }
    System.out.print(n+" "+System.currentTimeMillis()+" "+reg+" ");
    n=n^System.currentTimeMillis()^reg;
    return n;
}
public static void main(String args[])throws IOException
{
    for(int i=0;i<400;i++)
    {
        System.out.println(getRand());
    }
}
</code>```

}

This is a random number generator where it is guaranteed that the sequence never repeats itself. I have paired time with object value (randomly put by java) with LFSR.

Advantages:

The sequence doesn't repeat itself

The sequence is new on every run

Disadvantages:

Only compatible with java. In C++, new object that is created is same on every run.

But there too time and LFSR parameters would put in enough randomness

It is slower than most PRNGs as an object needs to be created everytime a number is needed

Body:
import java.io.*;
public class random{
public static class p{

}
static long reg=0;
static long lfsr()
{
    if(reg==0)
    {
        reg=145896027340307l;
    }
    long bit=(reg>>0^reg>>2^reg>>3^reg>>5)&1;
    reg=reg>>1|bit<<62;
    return reg;
}
static long getRand()
{
    String s=String.valueOf(new p());
    //System.out.println(s);
    long n=0;
    lfsr();
    for(int i=0;i<s.length();i++)
    {
        n=n<<8|+s.charAt(i);
    }
    System.out.print(n+" "+System.currentTimeMillis()+" "+reg+" ");
    n=n^System.currentTimeMillis()^reg;
    return n;
}
public static void main(String args[])throws IOException
{
    for(int i=0;i<400;i++)
    {
        System.out.println(getRand());
    }
}

}

This is a random number generator where it is guaranteed that the sequence never repeats itself. I have paired time with object value (randomly put by java) with LFSR.

Advantages:

The sequence doesn't repeat itself

The sequence is new on every run

Disadvantages:

Only compatible with java. In C++, new object that is created is same on every run.

But there too time and LFSR parameters would put in enough randomness

It is slower than most PRNGs as an object needs to be created everytime a number is needed


问:
How do I check that composer package installed in bash script
I'm trying to install composer package if it not installed in bash script. But now it doesn't work, and no_package function always pass

```<code>#!/bin/bash -e

no_package() {
    composer show | grep matchish/laravel-scout-elasticsearch | test
}

if [ no_package ]; then
  composer require "matchish/laravel-scout-elasticsearch"
else
  echo 'Package installed'
fi
</code>```

UPD: Here is solution

```<code>package_installed() {
    composer show | grep matchish/laravel-scout-elasticsearch --quiet
}
if package_installed; then
  echo 'Package installed'
else
  composer require "matchish/laravel-scout-elasticsearch"
fi
</code>```

答:
There are two misunderstandings here:

You can't pipe stuff to test.

if some_command is the way to do something if a command succeeds. [ no_package ] doesn't actually run the command, it simply checks that the string "no_package" is not empty and therefore always succeeds.

In addition to this you may want to use the --quiet flag to grep to avoid printing the package name.

Body:
I'm trying to install composer package if it not installed in bash script. But now it doesn't work, and no_package function always pass

#!/bin/bash -e

no_package() {
    composer show | grep matchish/laravel-scout-elasticsearch | test
}

if [ no_package ]; then
  composer require "matchish/laravel-scout-elasticsearch"
else
  echo 'Package installed'
fi

UPD: Here is solution

package_installed() {
    composer show | grep matchish/laravel-scout-elasticsearch --quiet
}
if package_installed; then
  echo 'Package installed'
else
  composer require "matchish/laravel-scout-elasticsearch"
fi


问:
Can't find the exe for anaconda installer

I use a 64-bit Windows 10 machine. I was trying to install Anaconda by following the steps mentioned on this DataCamp page. I was expecting a .exe file, instead, I got a .pkg file. I don't know how to open the .pkg file. I could see .exe files in Anaconda's archive. Not sure which one to download. Any help?

答: By default the anaconda website will set the option to MAC OS(.pkg is MAC extension) change and download by windows it works!</p>


问:
How to detect if a date is within this or next week in java?
If I have a date of an event, such as 2011-01-03, how to detect if it is within this or next week in java ? Any sample code ?

Edit :

I thought it was a simple question, it turned out more complex than I thought, what I meat this week is : from this past Sun to this Sat, next week is from next Sun to the Sat after that.

答:
Most answers here do not satisfy me. They either use the outdated Calendar-API (excusable in old answers given in times before Java 8, and it is hence not fair to criticize such answers), or they are even partially wrong or unnecessarily complex. For example, the most upvoted answer by Jon Skeet suggests to determine the first day of week by the Joda-expression new LocalDate().withDayOfWeek(DateTimeConstants.SUNDAY). But such code uses the ISO-definition of a week starting on Monday with the consequence that if the current date is not on Sunday the code would produce next Sunday and not previous Sunday as desired by the OP. Joda-Time is incapable of handling non-ISO weeks.

Another minor flaw of other answers is not to care about if the current AND NEXT week contains a given date - as requested by the OP. So here my improved suggestion in modern Java:

```<code>LocalDate today = LocalDate.now(); // involves the system time zone and clock of system
LocalDate startOfCurrentWeek =
  today.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
LocalDate endOfNextWeek =
  startOfCurrentWeek.plusDays(13);

LocalDate event = LocalDate.of(2011, 1, 3); // input of example given by OP

boolean matchingResult =
  !(event.isBefore(startOfCurrentWeek) || event.isAfter(endOfNextWeek));
</code>```

Side note: The question has inspired me to add a small enhancement to the class DateInterval in my library Time4J how to determine the current calendar week in a very generic way.

ContentLicense: CC BY-SA 2.5

Body:
Most answers here do not satisfy me. They either use the outdated Calendar-API (excusable in old answers given in times before Java 8, and it is hence not fair to criticize such answers), or they are even partially wrong or unnecessarily complex. For example, the most upvoted answer by Jon Skeet suggests to determine the first day of week by the Joda-expression new LocalDate().withDayOfWeek(DateTimeConstants.SUNDAY). But such code uses the ISO-definition of a week starting on Monday with the consequence that if the current date is not on Sunday the code would produce next Sunday and not previous Sunday as desired by the OP. Joda-Time is incapable of handling non-ISO weeks.

Another minor flaw of other answers is not to care about if the current AND NEXT week contains a given date - as requested by the OP. So here my improved suggestion in modern Java:

LocalDate today = LocalDate.now(); // involves the system time zone and clock of system
LocalDate startOfCurrentWeek =
  today.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
LocalDate endOfNextWeek =
  startOfCurrentWeek.plusDays(13);

LocalDate event = LocalDate.of(2011, 1, 3); // input of example given by OP

boolean matchingResult =
  !(event.isBefore(startOfCurrentWeek) || event.isAfter(endOfNextWeek));

Side note: The question has inspired me to add a small enhancement to the class DateInterval in my library Time4J how to determine the current calendar week in a very generic way.


问:
How to generate random functions using a for loop?
I want to create a random set of functions using a for loop, but my functions end up being the same.

I guess this is related to the environment, but I could not fix it:

```<code>a <- runif(100)

for(i in 1:100){
  assign(paste0("r",i), function(x){a[i]*x})
  }

</code>```

All the one hundred (r1 until r100) functions created end up being the same.

I would like them to have random a parameters.

答:
Try this:

for(i in 1:100){
  a <- runif(1)
  assign(paste0("r",i), function(x){a*x})
}
```

Body:
I want to create a random set of functions using a for loop, but my functions end up being the same.

I guess this is related to the environment, but I could not fix it:

a <- runif(100)

for(i in 1:100){
  assign(paste0("r",i), function(x){a[i]*x})
  }

All the one hundred (r1 until r100) functions created end up being the same.

I would like them to have random a parameters.


问:
Why is this login program can login when i correct putting the username and password just at the first time?
So, I tried to make a simple login program with python. And get stuck with the else condition thing, when the username and password don't match, I want to make it start all over again which is the Username input and Password input. Then I just wrote login() in else block. I can login when I put the correct username and password at the first try. But when I am wrong once, then input the correct username and password, it just goes back to the login() function.
 I'm new with python, so I think making a simple login is a good exercise for "if else condition". Sorry for my bad english, thank you.

```<code>admin = "admin"
key = "admin"

def login():
    access = False
    while access == False:
        username = input("Username : ")
        password = input("Password : ")
        if username == admin and password == key:
            access = True
            print("Welcome admin")
        else:
            login()
</code>```

答:
This code will work as you wanted it to:</p>

```<code>admin = "admin"
key = "admin"

def login():
    access = False
    if access is False:
        username = input("Username : ")
        password = input("Password : ")
        if username == admin and password == key:
            access = True
            print("welcome admin")
        else:
            login()

login()
</code>```

Body:
So, I tried to make a simple login program with python. And get stuck with the else condition thing, when the username and password don't match, I want to make it start all over again which is the Username input and Password input. Then I just wrote login() in else block. I can login when I put the correct username and password at the first try. But when I am wrong once, then input the correct username and password, it just goes back to the login() function.
 I'm new with python, so I think making a simple login is a good exercise for "if else condition". Sorry for my bad english, thank you.

admin = "admin"
key = "admin"

def login():
    access = False
    while access == False:
        username = input("Username : ")
        password = input("Password : ")
        if username == admin and password == key:
            access = True
            print("Welcome admin")
        else:
            login()

Body:
This code will work as you wanted it to:

admin = "admin"
key = "admin"

def login():
    access = False
    if access is False:
        username = input("Username : ")
        password = input("Password : ")
        if username == admin and password == key:
            access = True
            print("welcome admin")
        else:
            login()

login()


问:
How would I use javascript to make an image "jiggle" or "shiver"?
So my question is simple, I'm building a webpage in HTML and I want to incorporate a little JavaScript into it so as to make an image "vibrate" or "jiggle" Basically move back and forth in a relatively tight space/pattern.

I did some research and I found this:

```<code>Copy the below code and paste it into the <HEAD> section of your page
Example:<head>Code Here</head>
<style>
.jc{
position:relative;
}
</style>

<script language="JavaScript1.2">

var ns6=document.getElementById&&!document.all
var ie=document.all

var customcollect=new Array()
var i=0

function jiggleit(num){
if ((!document.all&&!document.getElementById)) return;
customcollect[num].style.left=(parseInt(customcollect[num].style.left)==-1)? customcollect[num].style.left=1 : customcollect[num].style.left=-1
}

function init(){
if (ie){
while (eval("document.all.jiggle"+i)!=null){
customcollect[i]= eval("document.all.jiggle"+i)
i++
}
}
else if (ns6){
while (document.getElementById("jiggle"+i)!=null){
customcollect[i]= document.getElementById("jiggle"+i)
i++
}
}

if (customcollect.length==1)
setInterval("jiggleit(0)",80)
else if (customcollect.length>1)
for (y=0;y<customcollect.length;y++){
var tempvariable='setInterval("jiggleit('+y+')",'+'100 )'
eval(tempvariable)
}
}

window.onload=init

</script>

NOW PASTE THIS ANYWHERE YOU WISH YOUR IMAGE TO APPEAR

<span id="jiggle0" class="jc"><b>YOUR IMAGE URL HERE</b></span>
</code>```

They called it a "shivering pic" and gave an example... its exactly what I want. I did it exactly as they described it. I added the code where they said it was needed, I copied all the right parts (none of the directions), and I made sure everything is in the right place.

I tested it out an there was no image! There was nothing! I realized that this was because I was using a black background, and if there was any text, it would also be black, so what actually was happening was that it was merely showing the URL of the image I want to add in (I could see it once I highlighted it). Regardless, still no image (just the text), and still no vibrating/jittering/shivering/jiggling. I did note that there were bold tags right where it suggests to add the image URL... so to me that would make it seem like I would be putting in text.

PLEASE HELP! How do I make this code work, or how do I make an image "shiver"?

答: Use Mootools, Fx.Shake. Check this out!</p>

Body:
So my question is simple, I'm building a webpage in HTML and I want to incorporate a little JavaScript into it so as to make an image "vibrate" or "jiggle" Basically move back and forth in a relatively tight space/pattern.

I did some research and I found this:

Copy the below code and paste it into the  section of your page
Example:Code Here

NOW PASTE THIS ANYWHERE YOU WISH YOUR IMAGE TO APPEAR

YOUR IMAGE URL HERE

They called it a "shivering pic" and gave an example... its exactly what I want. I did it exactly as they described it. I added the code where they said it was needed, I copied all the right parts (none of the directions), and I made sure everything is in the right place.

I tested it out an there was no image! There was nothing! I realized that this was because I was using a black background, and if there was any text, it would also be black, so what actually was happening was that it was merely showing the URL of the image I want to add in (I could see it once I highlighted it). Regardless, still no image (just the text), and still no vibrating/jittering/shivering/jiggling. I did note that there were bold tags right where it suggests to add the image URL... so to me that would make it seem like I would be putting in text.

PLEASE HELP! How do I make this code work, or how do I make an image "shiver"?

Body: Use Mootools, Fx.Shake. Check this out!


问:
Why does this regex code have different results in Python 2.7 and Python 3.7?
It's to validate username, my codes:

```<code>import re
regex = r'^[\w.@+-]+\Z'
result = re.match(regex,'名字')
</code>```

In python2.7, it returns None.

In python3.7, it returns '名字'.

答:
It's because of the different definitions for \w in Python 2.7 versus Python 3.7.

In Python 2.7, we have:

When the LOCALE and UNICODE flags are not specified, matches any
  alphanumeric character and the underscore; this is equivalent to the
  set [a-zA-Z0-9_].

(emphasis and hyperlink and formatting added)

However, in Python 3.7, we have:

For Unicode (str) patterns: Matches Unicode word characters; this
  includes most characters that can be part of a word in any language,
  as well as numbers and the underscore. If the ASCII flag is used, only
  [a-zA-Z0-9_] is matched.

(emphasis and formatting added)

So, if you want it to work in both versions, you can do something like this:

```<code># -*- coding: utf-8 -*-
import re
regex = re.compile(r'^[\w.@+-]+\Z', re.UNICODE)
match = regex.match(u'名字')

if match:
    print(match.group(0))
else:
    print("not matched!")

output:
名字
</code>```

Here's proof that it works in both versions:

Note the differences:

I added # -*- coding: utf-8 -*- at the top of the script, because without it, in Python 2.7, we'll get an error saying

Non-ASCII character '\xe5' on line 3, but no encoding declared;  see
  http://www.python.org/peps/pep-0263.html for details

Instead of using result = re.match(pattern, string), I used regex = re.compile(pattern, flags) and match = regex.match(string) so that I can specify flags.

I used re.UNICODE flag, because without it, in Python 2.7, it will only match [a-zA-Z0-9_] when using \w.

I used u'名字' instead of '名字', because in Python 2.7 you need to use Unicode Literals for unicode characters.

Also, while answering your question, I found out that print("not matched!") works in Python 2.7 as well, which makes sense, because in this case the parentheses are ignored, which I didn't know, so that was fun.

Body:
It's to validate username, my codes:

import re
regex = r'^[\w.@+-]+\Z'
result = re.match(regex,'名字')

In python2.7, it returns None.

In python3.7, it returns '名字'.

Body:
It's because of the different definitions for \w in Python 2.7 versus Python 3.7.

In Python 2.7, we have:

When the LOCALE and UNICODE flags are not specified, matches any
  alphanumeric character and the underscore; this is equivalent to the
  set [a-zA-Z0-9_].

(emphasis and hyperlink and formatting added)

However, in Python 3.7, we have:

For Unicode (str) patterns: Matches Unicode word characters; this
  includes most characters that can be part of a word in any language,
  as well as numbers and the underscore. If the ASCII flag is used, only
  [a-zA-Z0-9_] is matched.

(emphasis and formatting added)

So, if you want it to work in both versions, you can do something like this:

# -*- coding: utf-8 -*-
import re
regex = re.compile(r'^[\w.@+-]+\Z', re.UNICODE)
match = regex.match(u'名字')

if match:
    print(match.group(0))
else:
    print("not matched!")

output:
名字

Here's proof that it works in both versions:

Note the differences:

I added # -*- coding: utf-8 -*- at the top of the script, because without it, in Python 2.7, we'll get an error saying

Non-ASCII character '\xe5' on line 3, but no encoding declared;  see
  http://www.python.org/peps/pep-0263.html for details

Instead of using result = re.match(pattern, string), I used regex = re.compile(pattern, flags) and match = regex.match(string) so that I can specify flags.

I used re.UNICODE flag, because without it, in Python 2.7, it will only match [a-zA-Z0-9_] when using \w.

I used u'名字' instead of '名字', because in Python 2.7 you need to use Unicode Literals for unicode characters.

Also, while answering your question, I found out that print("not matched!") works in Python 2.7 as well, which makes sense, because in this case the parentheses are ignored, which I didn't know, so that was fun.