问:
How to pass asynchronous function result into ajax function as parameter in js/jquery?
I'm trying to save the base64 image code of a video snapshot...

To do that, I have a first function I found which builds the snapshot I want, this function, videoSnap, is asynchronous, and I'd like to send it through an ajax function for further actions.

Problem is that the result of my videoSnap is completed way after the ajax call, thus, anytime I'm trying to send the result as a parameter of the ajax function, the result stay undefined...

How can I do this to work? I thought about promise function with then() but still the same result... I keep getting the base64 code after the ajax call making it uneffective...

I'm starting to be short of solution and idea... ^^'

Thanks much in advance for your great help! :)

```<code>    getTime = function (){
        var t = new Date();
        return t.getTime();
    }

    dump = function (r) {
        var pre = document.createElement('pre');
        pre.innerHTML = r;
        document.body.appendChild(pre)
    }

    videoSnap = function (file){
        var reader = new FileReader();
        if (file.type.match('video')) {
            reader.onload = function() {
              var blob = new Blob([reader.result], {type: file.type});
              var url = URL.createObjectURL(blob);
              var video = document.createElement('video');
              var timeupdate = function() {
                var snap = snapImage();
                if (snap.success) {
                  video.removeEventListener('timeupdate', timeupdate);
                  video.pause();
                  dump(getTime()+' : '+snap.image);
                  return snap.image;
                }else{
                  return false;
                }
              };
              video.addEventListener('loadeddata', function() {
                var snap = snapImage();
                if (snap.success) {
                  video.removeEventListener('timeupdate', timeupdate);
                  dump(getTime()+' : '+snap.image);
                  return snap.image;
                }else{
                  return false;
                }
              });
              var snapImage = function() {
                var canvas = document.createElement('canvas');
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
                var image = canvas.toDataURL();
                var success = image.length > 100000;
                var result = { success: success, image: image };
                return result;
              };
              video.addEventListener('timeupdate', timeupdate);
              video.preload = 'metadata';
              video.src = url;
              // Load video in Safari / IE11
              video.muted = true;
              video.playsInline = true;
              video.play();
            };
            reader.readAsArrayBuffer(file);
        }else{
            return false;
        }
    }

    dump(getTime());

    var base64Img = videoSnap(videoFile);

    formData.append("videoSnap",base64Img);

    /*
    function videoSnapPromise(vid) {
        return new Promise((resolve) => {
        resolve(videoSnap(vid));
      })
    }
    function appendResolve(resolve) {
        formData.append("videoSnap",resolve);
    }

    const promise = videoSnap(videoFile);
    promise.then(appendResolve);
    */

    dump(getTime());

    $.ajax({
        type: 'POST',
        url: 'uploadBase64Img.php',
        timeout: 10000,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        complete: function() {
            // complete function
        }
    });

    dump(getTime());
</code>```

答:
One way to do this would be to create a callback function and send it to the first function as a parameter, then refactor your first function to call that callback and pass it the result of the operation instead of returning it.

something like this should work:

```<code>getTime = function() {
  var t = new Date();
  return t.getTime();
}

dump = function(r) {
  var pre = document.createElement('pre');
  pre.innerHTML = r;
  document.body.appendChild(pre)
}

var videoSnap = function(file, callback) {
  var reader = new FileReader();
  if (file.type.match('video')) {
    reader.onload = function() {
      var blob = new Blob([reader.result], {
        type: file.type
      });
      var url = URL.createObjectURL(blob);
      var video = document.createElement('video');
      var timeupdate = function() {
        var snap = snapImage();
        if (snap.success) {
          video.removeEventListener('timeupdate', timeupdate);
          video.pause();
          dump(getTime() + ' : ' + snap.image);
          callback(snap.image);
        } else {
          callback(false);
        }
      };
      video.addEventListener('loadeddata', function() {
        var snap = snapImage();
        if (snap.success) {
          video.removeEventListener('timeupdate', timeupdate);
          dump(getTime() + ' : ' + snap.image);
          callback(snap.image);
        } else {
          callback(false);
        }
      });
      var snapImage = function() {
        var canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        var image = canvas.toDataURL();
        var success = image.length > 100000;
        var result = {
          success: success,
          image: image
        };
        callback(result);
      };
      video.addEventListener('timeupdate', timeupdate);
      video.preload = 'metadata';
      video.src = url;
      // Load video in Safari / IE11
      video.muted = true;
      video.playsInline = true;
      video.play();
    };
    reader.readAsArrayBuffer(file);
  } else {
    callback(false);
  }
}

var doAjax = function(base64Img) {
  var formData = FormData();
  formData.append("videoSnap", base64Img);
  $.ajax({
    type: 'POST',
    url: 'uploadBase64Img.php',
    timeout: 10000,
    data: formData,
    processData: false,
    contentType: false,
    dataType: "json",
    complete: function() {
      // complete function
    }
  });

}

videoSnap(videoFile, doAjax);
</code>```

Body:
I'm trying to save the base64 image code of a video snapshot...

To do that, I have a first function I found which builds the snapshot I want, this function, videoSnap, is asynchronous, and I'd like to send it through an ajax function for further actions.

Problem is that the result of my videoSnap is completed way after the ajax call, thus, anytime I'm trying to send the result as a parameter of the ajax function, the result stay undefined...

How can I do this to work? I thought about promise function with then() but still the same result... I keep getting the base64 code after the ajax call making it uneffective...

I'm starting to be short of solution and idea... ^^'

Thanks much in advance for your great help! :)

    getTime = function (){
        var t = new Date();
        return t.getTime();
    }

    dump = function (r) {
        var pre = document.createElement('pre');
        pre.innerHTML = r;
        document.body.appendChild(pre)
    }

    videoSnap = function (file){
        var reader = new FileReader();
        if (file.type.match('video')) {
            reader.onload = function() {
              var blob = new Blob([reader.result], {type: file.type});
              var url = URL.createObjectURL(blob);
              var video = document.createElement('video');
              var timeupdate = function() {
                var snap = snapImage();
                if (snap.success) {
                  video.removeEventListener('timeupdate', timeupdate);
                  video.pause();
                  dump(getTime()+' : '+snap.image);
                  return snap.image;
                }else{
                  return false;
                }
              };
              video.addEventListener('loadeddata', function() {
                var snap = snapImage();
                if (snap.success) {
                  video.removeEventListener('timeupdate', timeupdate);
                  dump(getTime()+' : '+snap.image);
                  return snap.image;
                }else{
                  return false;
                }
              });
              var snapImage = function() {
                var canvas = document.createElement('canvas');
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
                var image = canvas.toDataURL();
                var success = image.length > 100000;
                var result = { success: success, image: image };
                return result;
              };
              video.addEventListener('timeupdate', timeupdate);
              video.preload = 'metadata';
              video.src = url;
              // Load video in Safari / IE11
              video.muted = true;
              video.playsInline = true;
              video.play();
            };
            reader.readAsArrayBuffer(file);
        }else{
            return false;
        }
    }

    dump(getTime());

    var base64Img = videoSnap(videoFile);

    formData.append("videoSnap",base64Img);

    /*
    function videoSnapPromise(vid) {
        return new Promise((resolve) => {
        resolve(videoSnap(vid));
      })
    }
    function appendResolve(resolve) {
        formData.append("videoSnap",resolve);
    }

    const promise = videoSnap(videoFile);
    promise.then(appendResolve);
    */

    dump(getTime());

    $.ajax({
        type: 'POST',
        url: 'uploadBase64Img.php',
        timeout: 10000,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        complete: function() {
            // complete function
        }
    });

    dump(getTime());

Body:
One way to do this would be to create a callback function and send it to the first function as a parameter, then refactor your first function to call that callback and pass it the result of the operation instead of returning it.

something like this should work:

getTime = function() {
  var t = new Date();
  return t.getTime();
}

dump = function(r) {
  var pre = document.createElement('pre');
  pre.innerHTML = r;
  document.body.appendChild(pre)
}

var videoSnap = function(file, callback) {
  var reader = new FileReader();
  if (file.type.match('video')) {
    reader.onload = function() {
      var blob = new Blob([reader.result], {
        type: file.type
      });
      var url = URL.createObjectURL(blob);
      var video = document.createElement('video');
      var timeupdate = function() {
        var snap = snapImage();
        if (snap.success) {
          video.removeEventListener('timeupdate', timeupdate);
          video.pause();
          dump(getTime() + ' : ' + snap.image);
          callback(snap.image);
        } else {
          callback(false);
        }
      };
      video.addEventListener('loadeddata', function() {
        var snap = snapImage();
        if (snap.success) {
          video.removeEventListener('timeupdate', timeupdate);
          dump(getTime() + ' : ' + snap.image);
          callback(snap.image);
        } else {
          callback(false);
        }
      });
      var snapImage = function() {
        var canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        var image = canvas.toDataURL();
        var success = image.length > 100000;
        var result = {
          success: success,
          image: image
        };
        callback(result);
      };
      video.addEventListener('timeupdate', timeupdate);
      video.preload = 'metadata';
      video.src = url;
      // Load video in Safari / IE11
      video.muted = true;
      video.playsInline = true;
      video.play();
    };
    reader.readAsArrayBuffer(file);
  } else {
    callback(false);
  }
}

var doAjax = function(base64Img) {
  var formData = FormData();
  formData.append("videoSnap", base64Img);
  $.ajax({
    type: 'POST',
    url: 'uploadBase64Img.php',
    timeout: 10000,
    data: formData,
    processData: false,
    contentType: false,
    dataType: "json",
    complete: function() {
      // complete function
    }
  });

}

videoSnap(videoFile, doAjax);


来源: stackexchange

问:
hammer.js swipe right next page
I want to swipe right for next page and swipe right for previous page, I searched long time for ways to do, nothing seems to work

hammer.js seems the most promising

hammertime.get('swipe').set({ direction: Hammer. });
```

the below suggested script doen't seem to work, any other suggestions?

答:
```<code>const hammerTime = new Hammer(someElement)
hammerTime.on('swipeleft swiperight', (event) => {
  switch(event.type) {
    case 'swipeleft':
      window.location.href = "https://someurl.com"
      break
    case 'swiperight':
      window.location.href = "https://someotherurl.com"
      break
  }
})
</code>```

or

```<code>hammerTime.on('swipeleft', (event) => {
  window.location.href = "https://someurl.com"
})
hammerTime.on('swiperight', (event) => {
  window.location.href = "https://someotherurl.com"
})
</code>```

ContentLicense: CC BY-SA 4.0

Title: hammer.js swipe right next page

Body:
I want to swipe right for next page and swipe right for previous page, I searched long time for ways to do, nothing seems to work

hammer.js seems the most promising

hammertime.get('swipe').set({ direction: Hammer. });

the below suggested script doen't seem to work, any other suggestions?

Body:
const hammerTime = new Hammer(someElement)
hammerTime.on('swipeleft swiperight', (event) => {
  switch(event.type) {
    case 'swipeleft':
      window.location.href = "https://someurl.com"
      break
    case 'swiperight':
      window.location.href = "https://someotherurl.com"
      break
  }
})

or

hammerTime.on('swipeleft', (event) => {
  window.location.href = "https://someurl.com"
})
hammerTime.on('swiperight', (event) => {
  window.location.href = "https://someotherurl.com"
})


问:
phpmyadmin error processing request 200
I changed my Wamp's phpmyadmin config.inc.php file few days ago for auto authentication. Phpmyadmin was working fine but now whenever I click anywhere in phpmyadmin it's giving me this error in popup:

Error in processing request

Error code: 200

Error text: OK

This is my config.inc.php file:

```<code><?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * phpMyAdmin sample configuration, you can use it as base for
 * manual configuration. For easier setup you can use setup/
 *
 * All directives are explained in documentation in the doc/ folder
 * or at <http://docs.phpmyadmin.net/>.
 *
 * @package PhpMyAdmin
 */

/*
 * This is needed for cookie based authentication to encrypt password in
 * cookie
 */
$cfg['blowfish_secret'] = 'a8b7c6d'; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */

/*
 * Servers configuration
 */
$i = 0;

/*
 * First server
 */
$i++;
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';

/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

/*
 * phpMyAdmin configuration storage settings.
 */

/* User used to manipulate with storage */
// $cfg['Servers'][$i]['controlhost'] = '';
// $cfg['Servers'][$i]['controluser'] = 'pma';
// $cfg['Servers'][$i]['controlpass'] = 'pmapass';

/* Storage database and tables */
// $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
// $cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
// $cfg['Servers'][$i]['relation'] = 'pma__relation';
// $cfg['Servers'][$i]['table_info'] = 'pma__table_info';
// $cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
// $cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
// $cfg['Servers'][$i]['column_info'] = 'pma__column_info';
// $cfg['Servers'][$i]['history'] = 'pma__history';
// $cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
// $cfg['Servers'][$i]['tracking'] = 'pma__tracking';
// $cfg['Servers'][$i]['designer_coords'] = 'pma__designer_coords';
// $cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
// $cfg['Servers'][$i]['recent'] = 'pma__recent';
/* Contrib / Swekey authentication */
// $cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf';

/*
 * End of servers configuration
 */

/*
 * Directories for saving/loading files from server
 */
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';

/**
 * Defines whether a user should be displayed a "show all (records)"
 * button in browse mode or not.
 * default = false
 */
//$cfg['ShowAll'] = true;

/**
 * Number of rows displayed when browsing a result set. If the result
 * set contains more rows, "Previous" and "Next".
 * default = 30
 */
//$cfg['MaxRows'] = 50;

/**
 * disallow editing of binary fields
 * valid values are:
 *   false    allow editing
 *   'blob'   allow editing except for BLOB fields
 *   'noblob' disallow editing except for BLOB fields
 *   'all'    disallow editing
 * default = blob
 */
//$cfg['ProtectBinary'] = 'false';

/**
 * Default language to use, if not browser-defined or user-defined
 * (you find all languages in the locale folder)
 * uncomment the desired line:
 * default = 'en'
 */
//$cfg['DefaultLang'] = 'en';
//$cfg['DefaultLang'] = 'de';

/**
 * default display direction (horizontal|vertical|horizontalflipped)
 */
//$cfg['DefaultDisplay'] = 'vertical';

/**
 * How many columns should be used for table display of a database?
 * (a value larger than 1 results in some information being hidden)
 * default = 1
 */
//$cfg['PropertiesNumColumns'] = 2;

/**
 * Set to true if you want DB-based query history.If false, this utilizes
 * JS-routines to display query history (lost by window close)
 *
 * This requires configuration storage enabled, see above.
 * default = false
 */
//$cfg['QueryHistoryDB'] = true;

/**
 * When using DB-based query history, how many entries should be kept?
 *
 * default = 25
 */
//$cfg['QueryHistoryMax'] = 100;

/*
 * You can find more configuration options in the documentation
 * in the doc/ folder or at <http://docs.phpmyadmin.net/>.
 */
?>
</code>```

Any help will be appreciated, thanks.

答: my problem was solved by :- ENABLING COOKIES FOR LOCALHOST

ContentLicense: CC BY-SA 3.0

Title: phpmyadmin error processing request 200

Body:
I changed my Wamp's phpmyadmin config.inc.php file few days ago for auto authentication. Phpmyadmin was working fine but now whenever I click anywhere in phpmyadmin it's giving me this error in popup:

Error in processing request

Error code: 200

Error text: OK

This is my config.inc.php file:

<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * phpMyAdmin sample configuration, you can use it as base for
 * manual configuration. For easier setup you can use setup/
 *
 * All directives are explained in documentation in the doc/ folder
 * or at <http://docs.phpmyadmin.net/>.
 *
 * @package PhpMyAdmin
 */

/*
 * This is needed for cookie based authentication to encrypt password in
 * cookie
 */
$cfg['blowfish_secret'] = 'a8b7c6d'; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */

/*
 * Servers configuration
 */
$i = 0;

/*
 * First server
 */
$i++;
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';

/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

/*
 * phpMyAdmin configuration storage settings.
 */

/* User used to manipulate with storage */
// $cfg['Servers'][$i]['controlhost'] = '';
// $cfg['Servers'][$i]['controluser'] = 'pma';
// $cfg['Servers'][$i]['controlpass'] = 'pmapass';

/* Storage database and tables */
// $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
// $cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
// $cfg['Servers'][$i]['relation'] = 'pma__relation';
// $cfg['Servers'][$i]['table_info'] = 'pma__table_info';
// $cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
// $cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
// $cfg['Servers'][$i]['column_info'] = 'pma__column_info';
// $cfg['Servers'][$i]['history'] = 'pma__history';
// $cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
// $cfg['Servers'][$i]['tracking'] = 'pma__tracking';
// $cfg['Servers'][$i]['designer_coords'] = 'pma__designer_coords';
// $cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
// $cfg['Servers'][$i]['recent'] = 'pma__recent';
/* Contrib / Swekey authentication */
// $cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf';

/*
 * End of servers configuration
 */

/*
 * Directories for saving/loading files from server
 */
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';

/**
 * Defines whether a user should be displayed a "show all (records)"
 * button in browse mode or not.
 * default = false
 */
//$cfg['ShowAll'] = true;

/**
 * Number of rows displayed when browsing a result set. If the result
 * set contains more rows, "Previous" and "Next".
 * default = 30
 */
//$cfg['MaxRows'] = 50;

/**
 * disallow editing of binary fields
 * valid values are:
 *   false    allow editing
 *   'blob'   allow editing except for BLOB fields
 *   'noblob' disallow editing except for BLOB fields
 *   'all'    disallow editing
 * default = blob
 */
//$cfg['ProtectBinary'] = 'false';

/**
 * Default language to use, if not browser-defined or user-defined
 * (you find all languages in the locale folder)
 * uncomment the desired line:
 * default = 'en'
 */
//$cfg['DefaultLang'] = 'en';
//$cfg['DefaultLang'] = 'de';

/**
 * default display direction (horizontal|vertical|horizontalflipped)
 */
//$cfg['DefaultDisplay'] = 'vertical';

/**
 * How many columns should be used for table display of a database?
 * (a value larger than 1 results in some information being hidden)
 * default = 1
 */
//$cfg['PropertiesNumColumns'] = 2;

/**
 * Set to true if you want DB-based query history.If false, this utilizes
 * JS-routines to display query history (lost by window close)
 *
 * This requires configuration storage enabled, see above.
 * default = false
 */
//$cfg['QueryHistoryDB'] = true;

/**
 * When using DB-based query history, how many entries should be kept?
 *
 * default = 25
 */
//$cfg['QueryHistoryMax'] = 100;

/*
 * You can find more configuration options in the documentation
 * in the doc/ folder or at <http://docs.phpmyadmin.net/>.
 */
?>

Any help will be appreciated, thanks.


问:
How can I convert array of bytes to a string in PHP?
I have an array of bytes that I'd like to map to their ASCII equivalents.

How can I do this?

答:
Mario has already provided the best fit, but here is a more exotic way to achieve this.

```<code>$str = call_user_func_array(
        'sprintf',
        array_merge((array) str_repeat('%c', count($bytes)), $bytes)
       );
</code>```

CodePad.

Body:
Mario has already provided the best fit, but here is a more exotic way to achieve this.

$str = call_user_func_array(
        'sprintf',
        array_merge((array) str_repeat('%c', count($bytes)), $bytes)
       );

CodePad.


问:
Using a generic type of any nested subclass within its abstract superclass
Suppose you have the following abstract java class:

```<code>public abstract class AbstractRequestHandler<I,O> {
    I input;
    O output;
}
</code>```

and the following child classes hierarchy:

```<code>public abstract class AbstractUserRequestHandler<I extends User,O> extends AbstractRequestHandler<I,O>{...}
public abstract class AbstractUniversityRequestHandler<I extends UniversityUser> extends AbstractUserRequestHandler<I,String>{...}
public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{...}
public class TeacherRequestHandler extends AbstractUniversityRequestHandler<Teacher>{...}
</code>```

Suppose you need to use at a given point on the super class the generic type, for example in order to deserialize on the constructor the request json to the specific request object using gson library as follow:

```<code>public AbstractRequestHandler(final String inputJson) {
        input = new Gson().fromJson(inputJson,typeOfI);
}
</code>```

You need the type of generic I within variable "typeOfI"

Is there a global solution that allows to get the generic type specified by a concrete child class that respects the following constraints?

The type is gotten at runtime regardless the child classes hierarchy ( that can be also more complex the one given as example on this question )

The developer just needs to define the generic extending the super class without manually specify the generic type somewhere on concrete child class ( for example on overrided method or constructor )

So that if you want to define a new concrete child that assign a new value to a generic you can just write the following concrete class for example:

```<code>public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

}
</code>```

I found the following solutions but they don't respect both the asked solution constraints.

Solution that breaks constraint n°2

A solution could be to define an abstract method on the superclass as follow

```<code>protected abstract Type getRequestType();
</code>```

and then implement it on every concrete child class that defines the generic:

```<code>public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

    @Override
    protected Type getRequestType() {
        return Student.class;
    }
}
</code>```

Then the getRequestType() method can be used on constructor on the target superclass:

```<code>public AbstractRequestHandler(final String inputJson) {
        request = new Gson().fromJson(inputJson,getRequestType());
}
</code>```

But even if it works regardless the child classes hierarchy ( respect constraint n°1 ) the developer should manually implement an abstract method on each concrete child class.

Solution that breaks constraint n°1

If the hierarchy is simple having only a direct child that extend from the target superclass, as for example:

```<code>public class TeacherRequestHandler extends AbstractRequestHandler<Teacher,String>{...}
</code>```

a working solution has been proposed by @naikus ( https://stackoverflow.com/users/306602/naikus ) on the following stackoverflow thread:
Using a generic type of a subclass within it's abstract superclass?

However this doesn't work if the concrete class is not a direct child of the superclass that defines the generics ( as the one proposed as example on this question ).

答:
The answer is: Java does not support reified generics, see this feature request from 2004 with lots of duplicates. See also:

C# has reified generics, Java does not

Kotlin reified generics example

Java generics, type erasure and again Kotlin's reified generics

So unless you want to switch to Kotlin, there is simply nothing you can do because generic type information in Java is available to the compiler only, not during runtime (reified generics).

I am sorry if you do not like the answer, but still it is correct as of Java 13 in early 2020.

Body:
Suppose you have the following abstract java class:

public abstract class AbstractRequestHandler {
    I input;
    O output;
}

and the following child classes hierarchy:

public abstract class AbstractUserRequestHandler extends AbstractRequestHandler{...}
public abstract class AbstractUniversityRequestHandler extends AbstractUserRequestHandler{...}
public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{...}
public class TeacherRequestHandler extends AbstractUniversityRequestHandler<Teacher>{...}

Suppose you need to use at a given point on the super class the generic type, for example in order to deserialize on the constructor the request json to the specific request object using gson library as follow:

public AbstractRequestHandler(final String inputJson) {
        input = new Gson().fromJson(inputJson,typeOfI);
}

You need the type of generic I within variable "typeOfI"

Is there a global solution that allows to get the generic type specified by a concrete child class that respects the following constraints?

The type is gotten at runtime regardless the child classes hierarchy ( that can be also more complex the one given as example on this question )

The developer just needs to define the generic extending the super class without manually specify the generic type somewhere on concrete child class ( for example on overrided method or constructor )

So that if you want to define a new concrete child that assign a new value to a generic you can just write the following concrete class for example:

public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

}

I found the following solutions but they don't respect both the asked solution constraints.

Solution that breaks constraint n°2

A solution could be to define an abstract method on the superclass as follow

protected abstract Type getRequestType();

and then implement it on every concrete child class that defines the generic:

public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

    @Override
    protected Type getRequestType() {
        return Student.class;
    }
}

Then the getRequestType() method can be used on constructor on the target superclass:

public AbstractRequestHandler(final String inputJson) {
        request = new Gson().fromJson(inputJson,getRequestType());
}

But even if it works regardless the child classes hierarchy ( respect constraint n°1 ) the developer should manually implement an abstract method on each concrete child class.

Solution that breaks constraint n°1

If the hierarchy is simple having only a direct child that extend from the target superclass, as for example:

public class TeacherRequestHandler extends AbstractRequestHandler<Teacher,String>{...}

a working solution has been proposed by @naikus ( https://stackoverflow.com/users/306602/naikus ) on the following stackoverflow thread:
Using a generic type of a subclass within it's abstract superclass?

However this doesn't work if the concrete class is not a direct child of the superclass that defines the generics ( as the one proposed as example on this question ).


问:
Webtrc broadcast have multiple bandwidth usage
I want to create a webrtc broadcasting demo

https://webrtc-experiment.appspot.com/socket.io/

here i have a one problem broadcaster have huge bandwidth when connect 10+ user because it use peer to peer connection so it use upload bandwidth like this

Total upload bandwith = number of user * ( 30 kb approximate to upload 1 video)

so i want to develop like this

http://bloggeek.me/webrtc-multipoint-small-groups

how to i develop multipoint webrtc using minimum bandwidth ?

答: While your thought of using WebRTC in a small group multipoint manner, this comes with a lot of complexity and reliability issues. Most WebRTC apps that relay through peers tend to be not so reliable in my experience.  In concept it's a great idea, but I haven't seen any solid practical applications.  The most reliable implementations of scalable WebRTC broadcasts tends to use a server in the middle.  You can use something like Janus, but I prefer Kurento which is open source.  There is also a platform called OpenVidu that sits on top of Kurento if you don't want to have to get into the nuts and bolts of how things works, but is less customize-able.  You can even record, transcode and process the video in real time.</p>


问:
MySQL LIKE on Subquery
I am writing a query where I am trying to pull out values based on a portion of a subquery and can't seem to work out how to get the needed values.

The table has only a half-dozen entries containing author names but in some instances, there is more than one author in the field and I need to get their separate individual biographies. Right now this gives no errors but it is pulling up only the single entry that contains both author names rather than the two that contain the actual biographies. I need only the two single-name entries, not the one containing both but it's giving the opposite.

AuthorName has something like this:

```<code>Joe Blow
Jane Doe
Jow Blow and Jane Doe
</code>```

and here is the query

```<code>SELECT a.`ID` AS AuthorID, `AuthorName`, `AuthorPhoto`, `AuthorBio`, `Email`,
FROM authorbiographies a
WHERE `AuthorName` LIKE CONCAT('%',(
SELECT `AuthorName` )
FROM authorbiographies WHERE `AuthorName` LIKE '% and %),'%'
)
AND `ID` <> 3
</code>```

答:
Doesn't this do what you want?

```<code>SELECT ab.*
FROM authorbiographies ab
WHERE ab.authorname NOT LIKE '% and %';
</code>```

You seem to just want to pick out the rows that do not have ' and ' in them.

Title: MySQL LIKE on Subquery

Body:
I am writing a query where I am trying to pull out values based on a portion of a subquery and can't seem to work out how to get the needed values.

The table has only a half-dozen entries containing author names but in some instances, there is more than one author in the field and I need to get their separate individual biographies. Right now this gives no errors but it is pulling up only the single entry that contains both author names rather than the two that contain the actual biographies. I need only the two single-name entries, not the one containing both but it's giving the opposite.

AuthorName has something like this:

Joe Blow
Jane Doe
Jow Blow and Jane Doe

and here is the query

SELECT a.`ID` AS AuthorID, `AuthorName`, `AuthorPhoto`, `AuthorBio`, `Email`,
FROM authorbiographies a
WHERE `AuthorName` LIKE CONCAT('%',(
SELECT `AuthorName` )
FROM authorbiographies WHERE `AuthorName` LIKE '% and %),'%'
)
AND `ID` <> 3

Body:
Doesn't this do what you want?

SELECT ab.*
FROM authorbiographies ab
WHERE ab.authorname NOT LIKE '% and %';

You seem to just want to pick out the rows that do not have ' and ' in them.


问:
How to check in Ruby rails, if a word is present in value of a string which is part of jsonb column in postgres?
I have a User table in postgres. In rails console I search for User.where(<myWhereClause>).count

I have jsonb column called as "criteria".

Within criteria for key eligibility, I want to see if the value contains my search term 'directMBA'

eligibility is a comma separated string - 'directMBA, correspondanceMBA, onlineMBA'

This doesn't work

```<code>User.where("criteria->>'eligibility'.include?('directMBA')").count
</code>```

I don't want the sql query.
I need the Ruby Rails code to run in console

PS:
Also, what if my keyword is 'directMBA' or 'onlineMBA'

答:
You are looking for SQL LIKE operator</p>

```<code>User.where("criteria->>'eligibility' LIKE '%directMBA%'").count

# Also, what if my keyword is 'directMBA' or 'onlineMBA'
User.where("criteria->>'eligibility' LIKE '%directMBA%' OR LIKE '%onlineMBA%'").count
</code>```

Body:
I have a User table in postgres. In rails console I search for User.where(<myWhereClause>).count

I have jsonb column called as "criteria".

Within criteria for key eligibility, I want to see if the value contains my search term 'directMBA'

eligibility is a comma separated string - 'directMBA, correspondanceMBA, onlineMBA'

This doesn't work

User.where("criteria->>'eligibility'.include?('directMBA')").count

I don't want the sql query.
I need the Ruby Rails code to run in console

PS:
Also, what if my keyword is 'directMBA' or 'onlineMBA'

Body:
You are looking for SQL LIKE operator

User.where("criteria->>'eligibility' LIKE '%directMBA%'").count

# Also, what if my keyword is 'directMBA' or 'onlineMBA'
User.where("criteria->>'eligibility' LIKE '%directMBA%' OR LIKE '%onlineMBA%'").count


问:
How do I pull data from an SQL database into local double var using c#?
I'm trying to pull data through an ODBC connection into two local double variables but I keep getting a syntax error and I'm not sure what I'm missing.

I'm using this to plot coordinates on a map.

The code:

```<code>using (ODBC.connect = new OdbcConnection(ODBC.connectionString))
{
    double Latitude = 0.0;
    double Longitude = 0.0;

    OdbcCommand command = new OdbcCommand("SELECT Latitude, Longitude INTO ?, ? FROM TrackVehicles WHERE Registration = ?", ODBC.connect);

    command.Parameters.AddWithValue("?1", Latitude);
    command.Parameters.AddWithValue("?2", Longitude);
    command.Parameters.AddWithValue("?3", textBox1.Text);

    try
    {
        ODBC.connect.Open();
        command.ExecuteNonQuery();

        gMap.Position = new GMap.NET.PointLatLng(Latitude, Longitude);
    }
    catch (OdbcException exception)
    {
        MessageBox.Show(exception.Message);
    }
}
</code>```

The SQL error I get is:

ERROR [42000] [Sybase][ODBC Driver][SQL Anywhere]Syntax error near '?' on line 1

I've looked into using Parameters.Add() instead but had no luck as I'm a complete noob.

答:
With reference to:
https://learn.microsoft.com/en-us/dotnet/api/system.data.odbc.odbcdatareader?view=netframework-4.8

It looks like you're trying to return two values from the database into your C# code.

```<code>using (ODBC.connect = new OdbcConnection(ODBC.connectionString))
{
    double Latitude = 0.0;
    double Longitude = 0.0;

    OdbcCommand command = new OdbcCommand("SELECT Latitude, Longitude FROM TrackVehicles WHERE Registration = ?", ODBC.connect);

    command.Parameters.AddWithValue("?1", textBox1.Text);

    try
    {
        ODBC.connect.Open();
        OdbcDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            Latitude = reader[0];
            Longitude = reader[1];
        }
        reader.Close()

        gMap.Position = new GMap.NET.PointLatLng(Latitude, Longitude);
    }
    catch (OdbcException exception)
    {
        MessageBox.Show(exception.Message);
    }
}
</code>```

Body:
I'm trying to pull data through an ODBC connection into two local double variables but I keep getting a syntax error and I'm not sure what I'm missing.

I'm using this to plot coordinates on a map.

The code:

using (ODBC.connect = new OdbcConnection(ODBC.connectionString))
{
    double Latitude = 0.0;
    double Longitude = 0.0;

    OdbcCommand command = new OdbcCommand("SELECT Latitude, Longitude INTO ?, ? FROM TrackVehicles WHERE Registration = ?", ODBC.connect);

    command.Parameters.AddWithValue("?1", Latitude);
    command.Parameters.AddWithValue("?2", Longitude);
    command.Parameters.AddWithValue("?3", textBox1.Text);

    try
    {
        ODBC.connect.Open();
        command.ExecuteNonQuery();

        gMap.Position = new GMap.NET.PointLatLng(Latitude, Longitude);
    }
    catch (OdbcException exception)
    {
        MessageBox.Show(exception.Message);
    }
}

The SQL error I get is:

ERROR [42000] [Sybase][ODBC Driver][SQL Anywhere]Syntax error near '?' on line 1

I've looked into using Parameters.Add() instead but had no luck as I'm a complete noob.

Body:
With reference to:
https://learn.microsoft.com/en-us/dotnet/api/system.data.odbc.odbcdatareader?view=netframework-4.8

It looks like you're trying to return two values from the database into your C# code.

using (ODBC.connect = new OdbcConnection(ODBC.connectionString))
{
    double Latitude = 0.0;
    double Longitude = 0.0;

    OdbcCommand command = new OdbcCommand("SELECT Latitude, Longitude FROM TrackVehicles WHERE Registration = ?", ODBC.connect);

    command.Parameters.AddWithValue("?1", textBox1.Text);

    try
    {
        ODBC.connect.Open();
        OdbcDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            Latitude = reader[0];
            Longitude = reader[1];
        }
        reader.Close()

        gMap.Position = new GMap.NET.PointLatLng(Latitude, Longitude);
    }
    catch (OdbcException exception)
    {
        MessageBox.Show(exception.Message);
    }
}


问:
.NET Core 3.0 : getting a type cast error when trying to retrieve option values using .Value
I have the following piece of code where I get the JWT options set in StartUp.cs.

First here is where I set the TokenOptions in StartUp.cs in the ConfigureServices method:

```<code>// Get jwt options from app settings
var tokenOptions = _configuration.GetSection("Authentication").Get<JwtTokenOptions>();

services.AddAuthentication(x => {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options => {
            options.TokenValidationParameters = new TokenValidationParameters {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                RequireExpirationTime = true,
                ValidIssuer = tokenOptions.Issuer,
                ValidAudience = tokenOptions.Audience,
                IssuerSigningKey = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(tokenOptions.SigningKey)),
                ClockSkew = TimeSpan.Zero
            };
});
</code>```

This works I think and I set the options there.

Now I want to use those options in a class using dependency injection:

```<code>using JobsLedger.AUTHORISATION.Interfaces;
using JobsLedger.CATALOG.ENTITIES;
using JobsLedger.CATALOG.Repositories.Interfaces;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Identity;

namespace JobsLedger.AUTHORISATION
{
    public class UserAuthorisationServices : IUserAuthorisationServices
    {
        #region Variables
        private readonly IUserCATALOGRepository _userCATALOGRepository;
        private readonly IRoleCATALOGRepository _roleCATALOGRepository;
        private readonly ICryptoService _cryptoService;
        IOptions<TokenOptions> _tokenOptions;
        #endregion

        public UserAuthorisationServices(IUserCATALOGRepository userCATALOGRepository,
                            IRoleCATALOGRepository roleCATALOGRepository,
                            ICryptoService cryptoService,
                            IOptions<TokenOptions> tokenOptions)
        {
            _userCATALOGRepository = userCATALOGRepository;
            _roleCATALOGRepository = roleCATALOGRepository;
            _cryptoService = cryptoService;
            _tokenOptions = tokenOptions.Value;
        }
</code>```

Problem is.. I am getting a type error on this line:

```<code>_tokenOptions = tokenOptions.Value;
</code>```

and the error is:

Error CS0266  Cannot implicitly convert type 'Microsoft.AspNetCore.Identity.TokenOptions' to 'Microsoft.Extensions.Options.IOptions'.
  An explicit conversion exists (are you missing a cast?)

So this is failing despite the fact I am using IOptions<TokenOptions> in both cases.

What am I doing wrong and what do I need to do to fix it?

答:
You are trying to use the .Value property inside the IOptions<T> which is type T to set a member in your class of type IOptions<T>. Since IOptions<T> is not T, you are getting an error.

You can either change the member

```<code>IOptions<TokenOptions> _tokenOptions;
</code>```

to

```<code>TokenOptions _tokenOptions;
</code>```

or change within your constructor

```<code>_tokenOptions = tokenOptions.Value;
</code>```

to

```<code>_tokenOptions = tokenOptions;
</code>```

Body:
I have the following piece of code where I get the JWT options set in StartUp.cs.

First here is where I set the TokenOptions in StartUp.cs in the ConfigureServices method:

// Get jwt options from app settings
var tokenOptions = _configuration.GetSection("Authentication").Get<JwtTokenOptions>();

services.AddAuthentication(x => {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options => {
            options.TokenValidationParameters = new TokenValidationParameters {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                RequireExpirationTime = true,
                ValidIssuer = tokenOptions.Issuer,
                ValidAudience = tokenOptions.Audience,
                IssuerSigningKey = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(tokenOptions.SigningKey)),
                ClockSkew = TimeSpan.Zero
            };
});

This works I think and I set the options there.

Now I want to use those options in a class using dependency injection:

using JobsLedger.AUTHORISATION.Interfaces;
using JobsLedger.CATALOG.ENTITIES;
using JobsLedger.CATALOG.Repositories.Interfaces;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Identity;

namespace JobsLedger.AUTHORISATION
{
    public class UserAuthorisationServices : IUserAuthorisationServices
    {
        #region Variables
        private readonly IUserCATALOGRepository _userCATALOGRepository;
        private readonly IRoleCATALOGRepository _roleCATALOGRepository;
        private readonly ICryptoService _cryptoService;
        IOptions<TokenOptions> _tokenOptions;
        #endregion

        public UserAuthorisationServices(IUserCATALOGRepository userCATALOGRepository,
                            IRoleCATALOGRepository roleCATALOGRepository,
                            ICryptoService cryptoService,
                            IOptions<TokenOptions> tokenOptions)
        {
            _userCATALOGRepository = userCATALOGRepository;
            _roleCATALOGRepository = roleCATALOGRepository;
            _cryptoService = cryptoService;
            _tokenOptions = tokenOptions.Value;
        }

Problem is.. I am getting a type error on this line:

_tokenOptions = tokenOptions.Value;

and the error is:

Error CS0266  Cannot implicitly convert type 'Microsoft.AspNetCore.Identity.TokenOptions' to 'Microsoft.Extensions.Options.IOptions'.
  An explicit conversion exists (are you missing a cast?)

So this is failing despite the fact I am using IOptions<TokenOptions> in both cases.

What am I doing wrong and what do I need to do to fix it?

Body:
You are trying to use the .Value property inside the IOptions<T> which is type T to set a member in your class of type IOptions<T>. Since IOptions<T> is not T, you are getting an error.

You can either change the member

IOptions<TokenOptions> _tokenOptions;

to

TokenOptions _tokenOptions;

or change within your constructor

_tokenOptions = tokenOptions.Value;

to

_tokenOptions = tokenOptions;


问:
creating xml document with c# and parsing it with perl
I am currently creating an xml document from database content. The output of my creation is saved to another database field. When I validate the xml that I have created it is invalid as the data within the xml tags is not valid eg. & symbols, < symbols within the xml tag content.

Should I be encoding the xml content as I create the xml document?

After the data is saved in to the database it is read via batch job written in perl. After the xml content is encoded, can perl decode this content? And if so, how is this achieve?

答:
If you're creating an XML document in C#, you should be using one of the built-in types, like XmlWriter or XDocument. That way, the details of escaping characters that need to be escaped is taken care of and you don't have to think about it.

You should do the same on the other side and use some XML parser in Perl.

If you still want to know how is it achieved (you shouldn't need to), then all the characters that can't appear inside a text node are escaped using character entities. For example, < is escaped as <.

Body:
If you're creating an XML document in C#, you should be using one of the built-in types, like XmlWriter or XDocument. That way, the details of escaping characters that need to be escaped is taken care of and you don't have to think about it.

You should do the same on the other side and use some XML parser in Perl.

If you still want to know how is it achieved (you shouldn't need to), then all the characters that can't appear inside a text node are escaped using character entities. For example, < is escaped as &lt;.


问:
Why can't I save data in plist file with Swift
** the readData.plist is:**

```<code>
  <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>currentChapter</key>
    <string>2</string>
    <key>currentLine</key>
    <string>2</string>
    <key>bookname</key>
    <string>ExcelBible</string>
</dict>
</plist>

</code>```

** The following is code:**

```<code>
        let Chapter = currentChapter
        let Line = currentLine
        let name = bookname

        let dict:NSMutableDictionary = NSMutableDictionary()

        dict.setObject("1", forKey: "currentChapter" as NSCopying)
        dict.setObject("1", forKey: "currentLine" as NSCopying)
        dict.setObject("WordBible", forKey: "bookname" as NSCopying)

        //I also use dict[0] = "1", and setValue() method both of them are not work

        let plistPath = Bundle.main.path(forResource: "readData", ofType: "plist")

        dict.write(toFile: plistPath!, atomically: true)

</code>```

Blockquote
     I also use FileManager and several examples here to save data, some display "Successfully write", but the file does't change.

Blockquote

I am an iOS developer since Feb 12, 2020

答: I think the file is not in a writable location, so you should create it in the documents directory. Then, it has to be read from the documents directory. </p>

Body:
** the readData.plist is:**

  <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>currentChapter</key>
    <string>2</string>
    <key>currentLine</key>
    <string>2</string>
    <key>bookname</key>
    <string>ExcelBible</string>
</dict>
</plist>

** The following is code:**

        let Chapter = currentChapter
        let Line = currentLine
        let name = bookname

        let dict:NSMutableDictionary = NSMutableDictionary()

        dict.setObject("1", forKey: "currentChapter" as NSCopying)
        dict.setObject("1", forKey: "currentLine" as NSCopying)
        dict.setObject("WordBible", forKey: "bookname" as NSCopying)

        //I also use dict[0] = "1", and setValue() method both of them are not work

        let plistPath = Bundle.main.path(forResource: "readData", ofType: "plist")

        dict.write(toFile: plistPath!, atomically: true)

Blockquote
     I also use FileManager and several examples here to save data, some display "Successfully write", but the file does't change.

Blockquote

I am an iOS developer since Feb 12, 2020


问:
How would I get the base address of a process and edit that pointer with it?
I thought base addresses where meant to be like 0x00 but when i use a button to give me the base address i get this 1966604288. I'm using the Vam Memory DLL. The problem might also be i dont know how to use ida to get memory addresses..
Note: I've tried kernel32.dll and user32.dll

```<code>

        public IntPtr GetModuleBaseAddress(string processName, string moduleName)
        {

            Process process;

            try
            {
                process = Process.GetProcessesByName(processName)[0];
            }

            catch (IndexOutOfRangeException)
            {

                throw new ArgumentException($"No process with name {processName} is currently running");
            }

            var module = process.Modules.Cast<ProcessModule>().SingleOrDefault(m => string.Equals(m.ModuleName, moduleName, StringComparison.OrdinalIgnoreCase));

            return module?.BaseAddress ?? IntPtr.Zero;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            vam.processName = "the process im using";
            IntPtr baseaddy = GetModuleBaseAddress("the process im using", "user32.dll");
            int addy = 0xFD1117;
            vam.WriteInt32((IntPtr)baseaddy + addy, 1000);
            richTextBox1.Text = baseaddy.ToString();
        }
    }
}

</code>```

That's not all my code but it should be enough.

答:
The address that begins with 0x is the Hex value you are referring to which you can obtain by with a suffix like BaseAddress.ToString("x8")

Output: The process's main module's base address is: 0x00a80000

Snippet: Retrieves Base Address of every module associated with the Notepad Process and prints Main Modules Base address in Hex representation

```<code>using (Process myProcess = new Process())
{
   ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("notepad.exe");
   myProcess.StartInfo = myProcessStartInfo;
   myProcess.Start();
   System.Threading.Thread.Sleep(1000);
   ProcessModule myProcessModule;

   Console.WriteLine("Base addresses of the modules associated "+"with 'notepad' are:");
   for (int i = 0; i < myProcess.Modules.Count; i++)
   {
      myProcessModule = myProcess.Modules[i];
      Console.WriteLine(myProcessModule.ModuleName + " : " + (IntPtr)myProcessModule.BaseAddress);
   }

   Console.WriteLine("The process's main module's base address is: 0x"+myProcess.MainModule.BaseAddress.ToString("x8"));
   myProcess.CloseMainWindow();
}

</code>```

Body:
I thought base addresses where meant to be like 0x00 but when i use a button to give me the base address i get this 1966604288. I'm using the Vam Memory DLL. The problem might also be i dont know how to use ida to get memory addresses..
Note: I've tried kernel32.dll and user32.dll

        public IntPtr GetModuleBaseAddress(string processName, string moduleName)
        {

            Process process;

            try
            {
                process = Process.GetProcessesByName(processName)[0];
            }

            catch (IndexOutOfRangeException)
            {

                throw new ArgumentException($"No process with name {processName} is currently running");
            }

            var module = process.Modules.Cast<ProcessModule>().SingleOrDefault(m => string.Equals(m.ModuleName, moduleName, StringComparison.OrdinalIgnoreCase));

            return module?.BaseAddress ?? IntPtr.Zero;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            vam.processName = "the process im using";
            IntPtr baseaddy = GetModuleBaseAddress("the process im using", "user32.dll");
            int addy = 0xFD1117;
            vam.WriteInt32((IntPtr)baseaddy + addy, 1000);
            richTextBox1.Text = baseaddy.ToString();
        }
    }
}

That's not all my code but it should be enough.

Body:
The address that begins with 0x is the Hex value you are referring to which you can obtain by with a suffix like BaseAddress.ToString("x8")

Output: The process's main module's base address is: 0x00a80000

Snippet: Retrieves Base Address of every module associated with the Notepad Process and prints Main Modules Base address in Hex representation

using (Process myProcess = new Process())
{
   ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("notepad.exe");
   myProcess.StartInfo = myProcessStartInfo;
   myProcess.Start();
   System.Threading.Thread.Sleep(1000);
   ProcessModule myProcessModule;

   Console.WriteLine("Base addresses of the modules associated "+"with 'notepad' are:");
   for (int i = 0; i < myProcess.Modules.Count; i++)
   {
      myProcessModule = myProcess.Modules[i];
      Console.WriteLine(myProcessModule.ModuleName + " : " + (IntPtr)myProcessModule.BaseAddress);
   }

   Console.WriteLine("The process's main module's base address is: 0x"+myProcess.MainModule.BaseAddress.ToString("x8"));
   myProcess.CloseMainWindow();
}


问:
Freeradius: Request without User-Password attribute for rest module
I'm trying to set up a radius server using a rest backend for authentication. I used the following project as example: https://github.com/fgsants/REST-API-FreeRADIUS

Everything is setup already, and everything works if I use the following command to simulated a login on radius:

radtest bar passwd 127.0.0.1 10 testing123

The rest backend receives /user/:username/mac?action=authorize and then /user/:username/mac?action=authenticate&password=passwd.

When I configure the AP to use this radius server, the request seems to be different than expected and the auth fails. This is the output of the radius server when trying to login through the AP:

```<code>(0) Received Access-Request Id 105 from 172.21.0.1:46358 to 172.21.0.3:1812 length 126
(0)   User-Name = "bar"
(0)   NAS-IP-Address = 192.168.0.21
(0)   NAS-Identifier = "RalinkAP1"
(0)   NAS-Port = 0
(0)   Called-Station-Id = "1A-0D-2C-1B-49-11"
(0)   Calling-Station-Id = "D4-9A-20-70-F4-0E"
(0)   Framed-MTU = 1400
(0)   NAS-Port-Type = Wireless-802.11
(0)   EAP-Message = 0x0201000801626172
(0)   Message-Authenticator = 0xbffda6639904c9026259be2a45b378c4
(0) # Executing section authorize from file /etc/freeradius/3.0/sites-enabled/default
(0)   authorize {
rlm_rest (rest): Reserved connection (0)
(0) rest: Expanding URI components
(0) rest: EXPAND http://rest:3000
(0) rest:    --> http://rest:3000
(0) rest: EXPAND /user/%{User-Name}/mac?action=authorize
(0) rest:    --> /user/bar/mac?action=authorize
(0) rest: Sending HTTP GET to "http://rest:3000/user/bar/mac?action=authorize"
(0) rest: Processing response header
(0) rest:   Status : 204 (No Content)
rlm_rest (rest): Released connection (0)
Need 5 more connections to reach 10 spares
rlm_rest (rest): Opening additional connection (5), 1 of 27 pending slots used
rlm_rest (rest): Connecting to "http://rest:3000"
(0)     [rest] = ok
(0)     if (ok) {
(0)     if (ok)  -> TRUE
(0)     if (ok)  {
(0)       update control {
(0)         Auth-Type := rest
(0)       } # update control = noop
(0)     } # if (ok)  = noop
(0)   } # authorize = ok
(0) Found Auth-Type = rest
(0) # Executing group from file /etc/freeradius/3.0/sites-enabled/default
(0)   Auth-Type rest {
(0) rest: ERROR: You set 'Auth-Type = REST' for a request that does not contain a User-Password attribute!
(0)     [rest] = invalid
(0)   } # Auth-Type rest = invalid
(0) Failed to authenticate the user
(0) Using Post-Auth-Type Reject
(0) Post-Auth-Type sub-section not found.  Ignoring.
(0) # Executing group from file /etc/freeradius/3.0/sites-enabled/default
(0) Delaying response for 1.000000 seconds
Waking up in 0.2 seconds.
Waking up in 0.7 seconds.
(0) (0) Discarding duplicate request from client ipv4 port 46358 - ID: 105 due to delayed response
(0) Sending delayed response
(0) Sent Access-Reject Id 105 from 172.21.0.3:1812 to 172.21.0.1:46358 length 20
Waking up in 3.9 seconds.
(0) Cleaning up request packet ID 105 with timestamp +15
Ready to process requests

</code>```

The radius server don't seem to be receiving a password from the AP:

```<code>(0)   User-Name = "bar"
(0)   NAS-IP-Address = 192.168.0.21
(0)   NAS-Identifier = "RalinkAP1"
(0)   NAS-Port = 0
(0)   Called-Station-Id = "1A-0D-2C-1B-49-11"
(0)   Calling-Station-Id = "D4-9A-20-70-F4-0E"
(0)   Framed-MTU = 1400
(0)   NAS-Port-Type = Wireless-802.11
(0)   EAP-Message = 0x0201000801626172
(0)   Message-Authenticator = 0xbffda6639904c9026259be2a45b378c4
</code>```

So later the authorization fails:

```<code>(0) rest: ERROR: You set 'Auth-Type = REST' for a request that does not contain a User-Password attribute!
</code>```

This is my configuration file:

```<code>server default {

listen {
    type = auth
    ipaddr = *
    port = 0
    limit {
          max_connections = 16
          lifetime = 0
          idle_timeout = 30
    }
}

listen {
    ipaddr = *
    port = 0
    type = acct
    limit {
    }
}

authorize {
    rest
        if (ok) {
            update control {
                Auth-Type := rest
            }
        }
}

authenticate {
    Auth-Type rest {
        rest {
            updated = 1
        }
        if (updated) {
            ok
        }
    }
}

preacct {
    preprocess
    acct_unique
    suffix
}

accounting {
    detail
    rest
}

post-auth {
    update {
        &reply: += &session-state:
    }
}
}

</code>```

What's missing? What needs to be done so I can receive the password from the access point?

Thanks

答:
I have spent an enormous amount of time, trying to figure out, how is this thing suppose to work, as I am a newbie, regarding freeradius. I am also using the nodejs rest api and was able to succeed with the second approach, but in order to do it, I had to add some more bits, inside the inner-tunnel file as follows:</p>

```<code>authorize {
    update control {
        MS-CHAP-Use-NTLM-Auth := No
    }
    rest
    inner-eap
}

authenticate {
    inner-eap
    Auth-Type PAP {
        pap
    }
    Auth-Type MS-CHAP {
        mschap
    }
}
</code>```

Body:
I'm trying to set up a radius server using a rest backend for authentication. I used the following project as example: https://github.com/fgsants/REST-API-FreeRADIUS

Everything is setup already, and everything works if I use the following command to simulated a login on radius:

radtest bar passwd 127.0.0.1 10 testing123

The rest backend receives /user/:username/mac?action=authorize and then /user/:username/mac?action=authenticate&password=passwd.

When I configure the AP to use this radius server, the request seems to be different than expected and the auth fails. This is the output of the radius server when trying to login through the AP:

(0) Received Access-Request Id 105 from 172.21.0.1:46358 to 172.21.0.3:1812 length 126
(0)   User-Name = "bar"
(0)   NAS-IP-Address = 192.168.0.21
(0)   NAS-Identifier = "RalinkAP1"
(0)   NAS-Port = 0
(0)   Called-Station-Id = "1A-0D-2C-1B-49-11"
(0)   Calling-Station-Id = "D4-9A-20-70-F4-0E"
(0)   Framed-MTU = 1400
(0)   NAS-Port-Type = Wireless-802.11
(0)   EAP-Message = 0x0201000801626172
(0)   Message-Authenticator = 0xbffda6639904c9026259be2a45b378c4
(0) # Executing section authorize from file /etc/freeradius/3.0/sites-enabled/default
(0)   authorize {
rlm_rest (rest): Reserved connection (0)
(0) rest: Expanding URI components
(0) rest: EXPAND http://rest:3000
(0) rest:    --> http://rest:3000
(0) rest: EXPAND /user/%{User-Name}/mac?action=authorize
(0) rest:    --> /user/bar/mac?action=authorize
(0) rest: Sending HTTP GET to "http://rest:3000/user/bar/mac?action=authorize"
(0) rest: Processing response header
(0) rest:   Status : 204 (No Content)
rlm_rest (rest): Released connection (0)
Need 5 more connections to reach 10 spares
rlm_rest (rest): Opening additional connection (5), 1 of 27 pending slots used
rlm_rest (rest): Connecting to "http://rest:3000"
(0)     [rest] = ok
(0)     if (ok) {
(0)     if (ok)  -> TRUE
(0)     if (ok)  {
(0)       update control {
(0)         Auth-Type := rest
(0)       } # update control = noop
(0)     } # if (ok)  = noop
(0)   } # authorize = ok
(0) Found Auth-Type = rest
(0) # Executing group from file /etc/freeradius/3.0/sites-enabled/default
(0)   Auth-Type rest {
(0) rest: ERROR: You set 'Auth-Type = REST' for a request that does not contain a User-Password attribute!
(0)     [rest] = invalid
(0)   } # Auth-Type rest = invalid
(0) Failed to authenticate the user
(0) Using Post-Auth-Type Reject
(0) Post-Auth-Type sub-section not found.  Ignoring.
(0) # Executing group from file /etc/freeradius/3.0/sites-enabled/default
(0) Delaying response for 1.000000 seconds
Waking up in 0.2 seconds.
Waking up in 0.7 seconds.
(0) (0) Discarding duplicate request from client ipv4 port 46358 - ID: 105 due to delayed response
(0) Sending delayed response
(0) Sent Access-Reject Id 105 from 172.21.0.3:1812 to 172.21.0.1:46358 length 20
Waking up in 3.9 seconds.
(0) Cleaning up request packet ID 105 with timestamp +15
Ready to process requests

The radius server don't seem to be receiving a password from the AP:

(0)   User-Name = "bar"
(0)   NAS-IP-Address = 192.168.0.21
(0)   NAS-Identifier = "RalinkAP1"
(0)   NAS-Port = 0
(0)   Called-Station-Id = "1A-0D-2C-1B-49-11"
(0)   Calling-Station-Id = "D4-9A-20-70-F4-0E"
(0)   Framed-MTU = 1400
(0)   NAS-Port-Type = Wireless-802.11
(0)   EAP-Message = 0x0201000801626172
(0)   Message-Authenticator = 0xbffda6639904c9026259be2a45b378c4

So later the authorization fails:

(0) rest: ERROR: You set 'Auth-Type = REST' for a request that does not contain a User-Password attribute!

This is my configuration file:

server default {

listen {
    type = auth
    ipaddr = *
    port = 0
    limit {
          max_connections = 16
          lifetime = 0
          idle_timeout = 30
    }
}

listen {
    ipaddr = *
    port = 0
    type = acct
    limit {
    }
}

authorize {
    rest
        if (ok) {
            update control {
                Auth-Type := rest
            }
        }
}

authenticate {
    Auth-Type rest {
        rest {
            updated = 1
        }
        if (updated) {
            ok
        }
    }
}

preacct {
    preprocess
    acct_unique
    suffix
}

accounting {
    detail
    rest
}

post-auth {
    update {
        &reply: += &session-state:
    }
}
}

What's missing? What needs to be done so I can receive the password from the access point?

Thanks

Body:
I have spent an enormous amount of time, trying to figure out, how is this thing suppose to work, as I am a newbie, regarding freeradius. I am also using the nodejs rest api and was able to succeed with the second approach, but in order to do it, I had to add some more bits, inside the inner-tunnel file as follows:

authorize {
    update control {
        MS-CHAP-Use-NTLM-Auth := No
    }
    rest
    inner-eap
}

authenticate {
    inner-eap
    Auth-Type PAP {
        pap
    }
    Auth-Type MS-CHAP {
        mschap
    }
}


问:
xarray.DataArray.diff vs. pandas.DataFrame.diff output is different
I have been trying to migrate some of my higher dimensional data from pandas to xarray with the deprecation of pandas panels.  I would like to use the diff function in xarray but it's parameters and output are not the same as pandas.

The pandas version: "DataFrame.diff(self, periods=1, axis=0)" allows me to set the number of periods to shift for calculating difference. ie periods=2

The xarray version "DataArray.diff(self, dim: Hashable, n: int = 1, label: Hashable = 'upper')" only has the parameter n.  Which is the number of times the values are differenced.

Imports and example DataFrame:

```<code>import numpy as np
import pandas as pd
import xarray as xr

data = np.random.randint(0, 9,(5,3))
date = pd.date_range('2000-01-01', periods=5)
cols = ['A','B','C']

df = pd.DataFrame(data, index=date, columns=cols)

print(df)
            A  B  C
2000-01-01  6  4  4
2000-01-02  1  1  5
2000-01-03  5  6  5
2000-01-04  5  8  4
2000-01-05  6  8  0

</code>```

And corresponding DataArray:

```<code>da = xr.DataArray(df, dims = ['date', 'col'])

print(da)
<xarray.DataArray (date: 5, col: 3)>
array([[6, 4, 4],
       [1, 1, 5],
       [5, 6, 5],
       [5, 8, 4],
       [6, 8, 0]])
Coordinates:
  * date     (date) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-05
  * col      (col) object 'A' 'B' 'C'
</code>```

DataFrame difference as expected and desired output with periods=1:

```<code>print(df.diff(periods=1))

              A    B    C
2000-01-01  NaN  NaN  NaN
2000-01-02 -5.0 -3.0  1.0
2000-01-03  4.0  5.0  0.0
2000-01-04  0.0  2.0 -1.0
2000-01-05  1.0  0.0 -4.0
</code>```

Is the same as the DataArray output for n=1:

```<code>print(da.diff('date', n=1))

<xarray.DataArray (date: 4, col: 3)>
array([[-5, -3,  1],
       [ 4,  5,  0],
       [ 0,  2, -1],
       [ 1,  0, -4]])
Coordinates:
  * date     (date) datetime64[ns] 2000-01-02 2000-01-03 2000-01-04 2000-01-05
  * col      (col) object 'A' 'B' 'C'
</code>```

But differs if the periods or n>1:

```<code>print(df.diff(periods=2))

              A    B    C
2000-01-01  NaN  NaN  NaN
2000-01-02  NaN  NaN  NaN
2000-01-03 -1.0  2.0  1.0
2000-01-04  4.0  7.0 -1.0
2000-01-05  1.0  2.0 -5.0
</code>```

vs.

```<code>print(da.diff('date',n=2))

<xarray.DataArray (date: 3, col: 3)>
array([[ 9,  8, -1],
       [-4, -3, -1],
       [ 1, -2, -3]])
Coordinates:
  * date     (date) datetime64[ns] 2000-01-03 2000-01-04 2000-01-05
  * col      (col) object 'A' 'B' 'C'
</code>```

I can do a shift workaround to get the desired output and same answer as the DataFrame.diff:

```<code>print (da - da.shift(date=2))

<xarray.DataArray (date: 5, col: 3)>
array([[nan, nan, nan],
       [nan, nan, nan],
       [-1.,  2.,  1.],
       [ 4.,  7., -1.],
       [ 1.,  2., -5.]])
Coordinates:
  * date     (date) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-05
  * col      (col) object 'A' 'B' 'C'
</code>```

But I want to use the xarray.diff() instead if possible.  Any advice or explanation would be welcome please.

答:
n in da.diff is 'The number of times values are differenced'.

So if n = 2, it's second-order difference in xarray. while df.diff is always first order.

Body:
I have been trying to migrate some of my higher dimensional data from pandas to xarray with the deprecation of pandas panels.  I would like to use the diff function in xarray but it's parameters and output are not the same as pandas.

The pandas version: "DataFrame.diff(self, periods=1, axis=0)" allows me to set the number of periods to shift for calculating difference. ie periods=2

The xarray version "DataArray.diff(self, dim: Hashable, n: int = 1, label: Hashable = 'upper')" only has the parameter n.  Which is the number of times the values are differenced.

Imports and example DataFrame:

import numpy as np
import pandas as pd
import xarray as xr

data = np.random.randint(0, 9,(5,3))
date = pd.date_range('2000-01-01', periods=5)
cols = ['A','B','C']

df = pd.DataFrame(data, index=date, columns=cols)

print(df)
            A  B  C
2000-01-01  6  4  4
2000-01-02  1  1  5
2000-01-03  5  6  5
2000-01-04  5  8  4
2000-01-05  6  8  0

And corresponding DataArray:

da = xr.DataArray(df, dims = ['date', 'col'])

print(da)
<xarray.DataArray (date: 5, col: 3)>
array([[6, 4, 4],
       [1, 1, 5],
       [5, 6, 5],
       [5, 8, 4],
       [6, 8, 0]])
Coordinates:
  * date     (date) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-05
  * col      (col) object 'A' 'B' 'C'

DataFrame difference as expected and desired output with periods=1:

print(df.diff(periods=1))

              A    B    C
2000-01-01  NaN  NaN  NaN
2000-01-02 -5.0 -3.0  1.0
2000-01-03  4.0  5.0  0.0
2000-01-04  0.0  2.0 -1.0
2000-01-05  1.0  0.0 -4.0

Is the same as the DataArray output for n=1:

print(da.diff('date', n=1))

<xarray.DataArray (date: 4, col: 3)>
array([[-5, -3,  1],
       [ 4,  5,  0],
       [ 0,  2, -1],
       [ 1,  0, -4]])
Coordinates:
  * date     (date) datetime64[ns] 2000-01-02 2000-01-03 2000-01-04 2000-01-05
  * col      (col) object 'A' 'B' 'C'

But differs if the periods or n>1:

print(df.diff(periods=2))

              A    B    C
2000-01-01  NaN  NaN  NaN
2000-01-02  NaN  NaN  NaN
2000-01-03 -1.0  2.0  1.0
2000-01-04  4.0  7.0 -1.0
2000-01-05  1.0  2.0 -5.0

vs.

print(da.diff('date',n=2))

<xarray.DataArray (date: 3, col: 3)>
array([[ 9,  8, -1],
       [-4, -3, -1],
       [ 1, -2, -3]])
Coordinates:
  * date     (date) datetime64[ns] 2000-01-03 2000-01-04 2000-01-05
  * col      (col) object 'A' 'B' 'C'

I can do a shift workaround to get the desired output and same answer as the DataFrame.diff:

print (da - da.shift(date=2))

<xarray.DataArray (date: 5, col: 3)>
array([[nan, nan, nan],
       [nan, nan, nan],
       [-1.,  2.,  1.],
       [ 4.,  7., -1.],
       [ 1.,  2., -5.]])
Coordinates:
  * date     (date) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-05
  * col      (col) object 'A' 'B' 'C'

But I want to use the xarray.diff() instead if possible.  Any advice or explanation would be welcome please.


问:
React-Native: Module AppRegistry is not a registered callable module
I'm currently trying to get the ES6 react-native-webpack-server running
on an Android emulator. The difference is I've upgraded my package.json and build.grade to use react 0.18.0, and am getting this error on boot. As far as I'm aware AppRegistry is imported correctly. Even if I were to comment out the code this error still comes up. This does work on iOS without issue.

What am I doing wrong?

EDIT: After trying other boilerplates that do support 0.18.0, I'm still coming across the same issue.

答: If you are using windows machine you need to do cd android then ./gradlew clean then run react-native run-android


问:
DatePickerDialog issue with fragments
I have a fragment with editText that is meant to open a date picker. I have done everything seemingly correctly, however I can't figure out why I get the following error.

It has something to do with the fact that I'm working with a fragment.

Could you please help with this error?

EditProfileFragment.java

```<code>import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;

import com.archive.pod.R;
import com.google.android.material.textfield.TextInputEditText;

import java.util.Calendar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

public class EditProfileFragment extends Fragment {

  //Initializing
  private TextInputEditText mDisplayDate;
  private DatePickerDialog.OnDateSetListener mDateSetListener;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_editprofile, container, false);

    //EditText
    mDisplayDate = view.findViewById(R.id.etDateOfBirth);

    //Date picker dialog box
    mDisplayDate.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dialog = new DatePickerDialog(
          requireContext(),
          android.R.style.Theme_DeviceDefault_Dialog_MinWidth,
          mDateSetListener,
          year, month, day);

        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
      }
    });

    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
      @Override
      public void onDateSet(DatePicker datePicker, int year, int month, int day) {
        month = month + 1;
        String date = month + "/" + day + "/" + year;
        mDisplayDate.setText(date);
      }
    };
    return view;
  }
}
</code>```

Error Log

```<code>/AndroidRuntime: FATAL EXCEPTION: main
Process: com.archive.pod, PID: 20399
java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to com.google.android.material.textfield.TextInputEditText
at com.archive.pod.Profile.EditProfileFragment.onCreateView(EditProfileFragment.java: 33)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java: 2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java: 881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java: 1238)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java: 434)
</code>```

Fragment Layout

```<code><merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="20dp">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/userProfilePicture"
                android:src="@drawable/ic_profile_picture_default"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginTop="20dp"
                android:layout_centerHorizontal="true" />

            <ImageButton
                android:id="@+id/changeUserPhoto"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginTop="90dp"
                android:layout_marginLeft="200dp"
                android:layout_marginStart="200dp"
                android:elevation="10dp"
                android:background="@drawable/ic_add_circle"/>

            <RelativeLayout
                android:id="@+id/sectionTitle1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/changeUserPhoto"
                android:layout_marginTop="50dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="true"
                    android:textSize="12sp"
                    android:textColor="@color/label"
                    android:text="Primary Information"/>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/relLayout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:layout_below="@+id/sectionTitle1">

                <!-- Full name input -->
                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etFullname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textNoSuggestions"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/full_name" />

                </com.google.android.material.textfield.TextInputLayout>

                <!-- Email input -->
                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etEmail"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/etFullname"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/emailAddress"
                        android:inputType="textEmailAddress"/>

                </com.google.android.material.textfield.TextInputLayout>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/sectionTitle2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/relLayout1"
                android:layout_marginTop="20dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="true"
                    android:textSize="12sp"
                    android:textColor="@color/label"
                    android:text="Private Information"/>

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/sectionTitle2">

                <!-- Phone number input -->
                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etPhoneNumber"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:focusable="false"
                    android:longClickable="false"
                    android:focusableInTouchMode="false"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/phone_number"
                        android:inputType="date"/>

                </com.google.android.material.textfield.TextInputLayout>

                <!-- Date of birth input -->
                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etDateOfBirth"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/etPhoneNumber"
                    android:focusable="false"
                    android:longClickable="false"
                    android:focusableInTouchMode="false"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/dob"
                        android:inputType="date"/>

                </com.google.android.material.textfield.TextInputLayout>

            </RelativeLayout>

        </RelativeLayout>

    </ScrollView>

</merge>
</code>```

答:
It just tells you that the first parameter of the DatePickerDialog constructor is not as supposed to be; where you put a Fragment, while it expects a context, so replace below line

```<code>    DatePickerDialog dialog = new DatePickerDialog(
      EditProfileFragment.this,
      android.R.style.Theme_DeviceDefault_Dialog_MinWidth,
      mDateSetListener,
      year, month, day);
</code>```

with

```<code>    DatePickerDialog dialog = new DatePickerDialog(
      requireContext(),
      android.R.style.Theme_DeviceDefault_Dialog_MinWidth,
      mDateSetListener,
      year, month, day);
</code>```

Title: DatePickerDialog issue with fragments

Body:
I have a fragment with editText that is meant to open a date picker. I have done everything seemingly correctly, however I can't figure out why I get the following error.

It has something to do with the fact that I'm working with a fragment.

Could you please help with this error?

EditProfileFragment.java

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;

import com.archive.pod.R;
import com.google.android.material.textfield.TextInputEditText;

import java.util.Calendar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

public class EditProfileFragment extends Fragment {

  //Initializing
  private TextInputEditText mDisplayDate;
  private DatePickerDialog.OnDateSetListener mDateSetListener;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_editprofile, container, false);

    //EditText
    mDisplayDate = view.findViewById(R.id.etDateOfBirth);

    //Date picker dialog box
    mDisplayDate.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dialog = new DatePickerDialog(
          requireContext(),
          android.R.style.Theme_DeviceDefault_Dialog_MinWidth,
          mDateSetListener,
          year, month, day);

        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
      }
    });

    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
      @Override
      public void onDateSet(DatePicker datePicker, int year, int month, int day) {
        month = month + 1;
        String date = month + "/" + day + "/" + year;
        mDisplayDate.setText(date);
      }
    };
    return view;
  }
}

Error Log

/AndroidRuntime: FATAL EXCEPTION: main
Process: com.archive.pod, PID: 20399
java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to com.google.android.material.textfield.TextInputEditText
at com.archive.pod.Profile.EditProfileFragment.onCreateView(EditProfileFragment.java: 33)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java: 2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java: 881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java: 1238)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java: 434)

Fragment Layout

<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="20dp">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/userProfilePicture"
                android:src="@drawable/ic_profile_picture_default"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginTop="20dp"
                android:layout_centerHorizontal="true" />

            <ImageButton
                android:id="@+id/changeUserPhoto"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginTop="90dp"
                android:layout_marginLeft="200dp"
                android:layout_marginStart="200dp"
                android:elevation="10dp"
                android:background="@drawable/ic_add_circle"/>

            <RelativeLayout
                android:id="@+id/sectionTitle1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/changeUserPhoto"
                android:layout_marginTop="50dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="true"
                    android:textSize="12sp"
                    android:textColor="@color/label"
                    android:text="Primary Information"/>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/relLayout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:layout_below="@+id/sectionTitle1">

                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etFullname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textNoSuggestions"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/full_name" />

                </com.google.android.material.textfield.TextInputLayout>

                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etEmail"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/etFullname"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/emailAddress"
                        android:inputType="textEmailAddress"/>

                </com.google.android.material.textfield.TextInputLayout>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/sectionTitle2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/relLayout1"
                android:layout_marginTop="20dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAllCaps="true"
                    android:textSize="12sp"
                    android:textColor="@color/label"
                    android:text="Private Information"/>

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/sectionTitle2">

                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etPhoneNumber"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:focusable="false"
                    android:longClickable="false"
                    android:focusableInTouchMode="false"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/phone_number"
                        android:inputType="date"/>

                </com.google.android.material.textfield.TextInputLayout>

                <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/etDateOfBirth"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/etPhoneNumber"
                    android:focusable="false"
                    android:longClickable="false"
                    android:focusableInTouchMode="false"
                    app:errorEnabled="true">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/dob"
                        android:inputType="date"/>

                </com.google.android.material.textfield.TextInputLayout>

            </RelativeLayout>

        </RelativeLayout>

    </ScrollView>

</merge>

Body:
It just tells you that the first parameter of the DatePickerDialog constructor is not as supposed to be; where you put a Fragment, while it expects a context, so replace below line

    DatePickerDialog dialog = new DatePickerDialog(
      EditProfileFragment.this,
      android.R.style.Theme_DeviceDefault_Dialog_MinWidth,
      mDateSetListener,
      year, month, day);

with

    DatePickerDialog dialog = new DatePickerDialog(
      requireContext(),
      android.R.style.Theme_DeviceDefault_Dialog_MinWidth,
      mDateSetListener,
      year, month, day);


问:
Show 3 random colors at once every 4 seconds with jQuery
I have this code and I'm trying to show 3 random colors from an array, at once, every 4 seconds, but instead I get 1 color every 4 seconds, even if they are properly randomized...

What am I missing?

```<code>//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
    return colors.reduce((memo, val, index) => {
        var p = (n-memo.length); // How many remaining to choose.
        var q = colors.length-index; // How many remaining to choose from.
        if (Math.random() < p/q){
            memo.push(val);
        }
        return memo;
    }, []);
};

//output the colors on the HTML
var counter = 0; //start counter
var elem = document.getElementById("changeText");//the place where we change things
setInterval(change, 4000);//every 4 seconds run the following stuff:
function change() {
 var text = three_random_colors(3);//get what's inside "three_random_colors"
 elem.innerHTML = text[counter];//on div, add content <--- (I want 3 at once here! but I get only 1)
    counter++;
    if(counter >= text.length) { counter = 0; var text = three_random_colors(3); }//reset
}
</code>```

答:
You can do this pretty simply with randojs.com, and this code will execute immediately for the first run- then every four seconds thereafter, and it will never repeat the same color more than once within the same three-color set. All I do is make a shuffled color array using randojs's randoSequence function, slice the first three values from that array, map them to their raw values with .value (because randojs actually returns an array of objects in case you need to access the value's original index with .index), join those values together into a string, and stick them into #color's innerHTML.

function showRandomColors() {
  var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];
  document.querySelector("#colors").innerHTML = randoSequence(colors).slice(0, 3).map(i => i.value).join(" ");
}

showRandomColors();
setInterval(showRandomColors, 4000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://randojs.com/1.0.0.js"></script>
<div id="colors"></div></code>```

Like I said, this code uses randojs.com, so if you want to use this code, make sure you have this in the head tag of your html document:

```<code><script src="https://randojs.com/1.0.0.js"></script>
</code>```

Body:
I have this code and I'm trying to show 3 random colors from an array, at once, every 4 seconds, but instead I get 1 color every 4 seconds, even if they are properly randomized...

What am I missing?

//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
    return colors.reduce((memo, val, index) => {
        var p = (n-memo.length); // How many remaining to choose.
        var q = colors.length-index; // How many remaining to choose from.
        if (Math.random() < p/q){
            memo.push(val);
        }
        return memo;
    }, []);
};

//output the colors on the HTML
var counter = 0; //start counter
var elem = document.getElementById("changeText");//the place where we change things
setInterval(change, 4000);//every 4 seconds run the following stuff:
function change() {
 var text = three_random_colors(3);//get what's inside "three_random_colors"
 elem.innerHTML = text[counter];//on div, add content <--- (I want 3 at once here! but I get only 1)
    counter++;
    if(counter >= text.length) { counter = 0; var text = three_random_colors(3); }//reset
}

Body:
You can do this pretty simply with randojs.com, and this code will execute immediately for the first run- then every four seconds thereafter, and it will never repeat the same color more than once within the same three-color set. All I do is make a shuffled color array using randojs's randoSequence function, slice the first three values from that array, map them to their raw values with .value (because randojs actually returns an array of objects in case you need to access the value's original index with .index), join those values together into a string, and stick them into #color's innerHTML.

function showRandomColors() {
  var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];
  document.querySelector("#colors").innerHTML = randoSequence(colors).slice(0, 3).map(i => i.value).join(" ");
}

showRandomColors();
setInterval(showRandomColors, 4000);

<script src="https://randojs.com/1.0.0.js"></script>
<div id="colors"></div>

Like I said, this code uses randojs.com, so if you want to use this code, make sure you have this in the head tag of your html document:

<script src="https://randojs.com/1.0.0.js"></script>