text:
Q: Is this a Python version conflict? I'm taking over an old Python project, that was developed by 5 engineers over several years. All of them are gone now, and I have to revive this project. I'm getting errors on the install scripts, and I cannot figure out if these error messages are because of a classic Python2/Python3 or if this is something else, like virtual env oddity.
One thing I want to clarify, if I do this:
ls -al /home/centos/blueflow/blueflow/bin/blueflow-pipenv

I get:
-rwxrwxr-x. 1 centos centos 1135 Feb 22 11:32 /home/centos/blueflow/blueflow/bin/blueflow-pipenv

So the file is there.
But I see in the code below this error message:
Failed to load paths: /bin/sh: /home/centos/blueflow/blueflow/bin/blueflow-pipenv --venv/bin/python: No such file or directory

Not sure why.
Ignoring numpy: markers u"python_version >= '3.6'" don't match your environment
Ignoring pillow: markers u"python_version >= '3.6'" don't match your environment
Ignoring platformdirs: markers u"python_version >= '3.6'" don't match your environment
Ignoring pluggy: markers u"python_version >= '3.6'" don't match your environment
Ignoring prompt-toolkit: markers u"python_full_version >= '3.6.2'" don't match your environment
Ignoring pygments: markers u"python_version >= '3.5'" don't match your environment
Ignoring pyparsing: markers u"python_version >= '3.6'" don't match your environment
Ignoring pytest: markers u"python_version >= '3.6'" don't match your environment
Ignoring tomli: markers u"python_version >= '3.6'" don't match your environment

But Python 3.6 is installed. I've got a fairly default Centos 7 setup:
ls -al /usr/bin/python

lrwxrwxrwx. 1 root root 18 Feb 22 12:31 /usr/bin/python -> /usr/bin/python2.7
ls -al /usr/bin/python3

lrwxrwxrwx. 1 root root 9 Dec 20  2020 /usr/bin/python3 -> python3.6
Am I dealing with some kind of virtual env problem? Should I set some Python version inside of a virtual environment? I cannot figure out what these error messages are asking for.
./bin/blueflow-install-dev
./bin/blueflow-install-dev
BLUEFLOW_HOME=/home/centos/blueflow/blueflow
DJANGO_SETTINGS_MODULE=app.settings.development
+ PIPENV_VENV_IN_PROJECT=true
+ /home/centos/blueflow/blueflow/bin/blueflow-pipenv install --dev
Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.
Pipfile.lock not found, creating...
Locking [dev-packages] dependencies...
Building requirements...
Resolving dependencies...
✔ Success!
Locking [packages] dependencies...
Building requirements...
Resolving dependencies...
✔ Success!
Updated Pipfile.lock (25d5ee)!
Installing dependencies from Pipfile.lock (25d5ee)...
Failed to load paths: /bin/sh: /home/centos/blueflow/blueflow/bin/blueflow-pipenv --venv/bin/python: No such file or directory

Output:
Failed to load paths: /bin/sh: /home/centos/blueflow/blueflow/bin/blueflow-pipenv --venv/bin/python: No such file or directory

Output:
Failed to load paths: /bin/sh: /home/centos/blueflow/blueflow/bin/blueflow-pipenv --venv/bin/python: No such file or directory

Output:
Ignoring astroid: markers u"python_full_version >= '3.6.2'" don't match your environment
Ignoring cycler: markers u"python_version >= '3.6'" don't match your environment
Ignoring decorator: markers u"python_version >= '3.5'" don't match your environment
An error occurred while installing fancycompleter==0.9.1 --hash=sha256:09e0feb8ae242abdfd7ef2ba55069a46f011814a80fe5476be48f51b00247272 --hash=sha256:dd076bca7d9d524cc7f25ec8f35ef95388ffef9ef46def4d3d25e9b044ad7080! Will try again.
An error occurred while installing ipython==7.16.3 --hash=sha256:5ac47dc9af66fc2f5530c12069390877ae372ac905edca75a92a6e363b5d7caa --hash=sha256:c0427ed8bc33ac481faf9d3acf7e84e0010cdaada945e0badd1e2e74cc075833! Will try again.
Ignoring isort: markers u"python_full_version >= '3.6.1' and python_version < '4.0'" don't match your environment
Ignoring kiwisolver: markers u"python_version >= '3.6'" don't match your environment
Ignoring lazy-object-proxy: markers u"python_version >= '3.6'" don't match your environment
An error occurred while installing matplotlib==3.3.4 --hash=sha256:672960dd114e342b7c610bf32fb99d14227f29919894388b41553217457ba7ef --hash=sha256:9a79e5dd7bb797aa611048f5b70588b23c5be05b63eefd8a0d152ac77c4243db --hash=sha256:46b1a60a04e6d884f0250d5cc8dc7bd21a9a96c584a7acdaab44698a44710bab --hash=sha256:c24c05f645aef776e8b8931cb81e0f1632d229b42b6d216e30836e2e145a2b40 --hash=sha256:ed4a9e6dcacba56b17a0a9ac22ae2c72a35b7f0ef0693aa68574f0b2df607a89 --hash=sha256:a1acb72f095f1d58ecc2538ed1b8bca0b57df313b13db36ed34b8cdf1868e674 --hash=sha256:aa49571d8030ad0b9ac39708ee77bd2a22f87815e12bdee52ecaffece9313ed8 --hash=sha256:7310e353a4a35477c7f032409966920197d7df3e757c7624fd842f3eeb307d3d --hash=sha256:f44149a0ef5b4991aaef12a93b8e8d66d6412e762745fea1faa61d98524e0ba9 --hash=sha256:7c155437ae4fd366e2700e2716564d1787700687443de46bcb895fe0f84b761d --hash=sha256:e15fa23d844d54e7b3b7243afd53b7567ee71c721f592deb0727ee85e668f96a --hash=sha256:3d2eb9c1cc254d0ffa90bc96fde4b6005d09c2228f99dfd493a4219c1af99644 --hash=sha256:cf3a7e54eff792f0815dbbe9b85df2f13d739289c93d346925554f71d484be78 --hash=sha256:746a1df55749629e26af7f977ea426817ca9370ad1569436608dc48d1069b87c --hash=sha256:451cc89cb33d6652c509fc6b588dc51c41d7246afdcc29b8624e256b7663ed1f --hash=sha256:215e2a30a2090221a9481db58b770ce56b8ef46f13224ae33afe221b14b24dc1 --hash=sha256:348e6032f666ffd151b323342f9278b16b95d4a75dfacae84a11d2829a7816ae --hash=sha256:5f571b92a536206f7958f7cb2d367ff6c9a1fa8229dc35020006e4cdd1ca0acd --hash=sha256:94bdd1d55c20e764d8aea9d471d2ae7a7b2c84445e0fa463f02e20f9730783e1 --hash=sha256:a17f0a10604fac7627ec82820439e7db611722e80c408a726cd00d8c974c2fb3 --hash=sha256:1e850163579a8936eede29fad41e202b25923a0a8d5ffd08ce50fc0a97dcdc93 --hash=sha256:3e477db76c22929e4c6876c44f88d790aacdf3c3f8f3a90cb1975c0bf37825b0 --hash=sha256:9265ae0fb35e29f9b8cc86c2ab0a2e3dcddc4dd9de4b85bf26c0f63fe5c1c2ca --hash=sha256:1de0bb6cbfe460725f0e97b88daa8643bcf9571c18ba90bb8e41432aaeca91d6 --hash=sha256:d738acfdfb65da34c91acbdb56abed46803db39af259b7f194dc96920360dbe4! Will try again.
Ignoring numpy: markers u"python_version >= '3.6'" don't match your environment
Ignoring pillow: markers u"python_version >= '3.6'" don't match your environment
Ignoring platformdirs: markers u"python_version >= '3.6'" don't match your environment
Ignoring pluggy: markers u"python_version >= '3.6'" don't match your environment
Ignoring prompt-toolkit: markers u"python_full_version >= '3.6.2'" don't match your environment
Ignoring pygments: markers u"python_version >= '3.5'" don't match your environment
Ignoring pyparsing: markers u"python_version >= '3.6'" don't match your environment
Ignoring pytest: markers u"python_version >= '3.6'" don't match your environment
Ignoring tomli: markers u"python_version >= '3.6'" don't match your environment
Ignoring typed-ast: markers u"implementation_name == 'cpython' and python_version < '3.8'" don't match your environment
An error occurred while installing typing-extensions==4.1.1; python_version < '3.8' and python_version < '3.8' --hash=sha256:21c85e0fe4b9a155d0799430b0ad741cdce7e359660ccbd8b530613e8df88ce2 --hash=sha256:1a9462dcc3347a79b1f1c0271fbe79e844580bb598bafa1ed208b94da3cdcd42! Will try again.
Ignoring asgiref: markers u"python_version >= '3.6'" don't match your environment
Ignoring charset-normalizer: markers u"python_version >= '3'" don't match your environment
An error occurred while installing click==8.0.4 --hash=sha256:6a7a62563bbfabfda3a38f3023a1db4a35978c0abd76f6c9605ecd6554d6d9b1 --hash=sha256:8458d7b1287c5fb128c90e23381cf99dcde74beaf6c7ff6384ce84d6fe090adb! Will try again.
An error occurred while installing django==3.2.12 --hash=sha256:9772e6935703e59e993960832d66a614cf0233a1c5123bc6224ecc6ad69e41e2 --hash=sha256:9b06c289f9ba3a8abea16c9c9505f25107809fb933676f6c891ded270039d965! Will try again.
Ignoring django-timezone-field: markers u"python_version >= '3.5'" don't match your environment
Ignoring idna: markers u"python_version >= '3'" don't match your environment
An error occurred while installing markdown==3.3.6 --hash=sha256:9923332318f843411e9932237530df53162e29dc7a4e2b91e35764583c46c9a3 --hash=sha256:76df8ae32294ec39dcf89340382882dfa12975f87f45c3ed1ecdb1e8cefc7006! Will try again.
Ignoring markupsafe: markers u"python_version >= '3.6'" don't match your environment
An error occurred while installing pyodbc==4.0.32 --hash=sha256:736acad1b264ddb7313058dfe37265b0c5160c1c2a9d1ffd391347c025eb5dd1 --hash=sha256:cda790bdc25bfad12d4fb9ba93368275802f7f9ecfa4c9c65e982d3a7fc35f2e --hash=sha256:0d4e14adb149cae45da37fa87aa297055156dae6e89ca3c75493d3d62d78e543 --hash=sha256:2152ce6d5131d769ff5839aa762e12d844c95e9ec4bb2f666e8cd9dfa1ae2240 --hash=sha256:c066f032e69fd71e9fadb3a380dfe8ecd1728b40a2bf38f76054d284f8523b29 --hash=sha256:0e4178e9b93329bbba17555882008e36a114179d06033b813a13b254dcd755d0 --hash=sha256:6c1e1c1fe747b0f6419e8df0b5c43161e7437dbf72f93f9fcfb9b7358fad3e12 --hash=sha256:699c080b1c1f7b4afc368b3521fd1161f46a10223443692a249cb01d90949b31 --hash=sha256:bbc07517f339e019ee9f1fe679c4241251d11ca2124567616f67d62e73c29fc0 --hash=sha256:56ec4974096d40d6c62a228799122dbc2ade6c4045cc5d31860212a32cae95b1 --hash=sha256:339d8aa633b0c65be5149c3378c7e3b5bead94dc8bb023a715b416bd047a008e --hash=sha256:9be5f0c3590655e1968488410fe3528bb8023d527e7ccec1f663d64245071a6b --hash=sha256:e81ebf9cab80a6eaba7922dea02036e9f8a507a7b818856b8008a02d6fc0d2ab! Will try again.
An error occurred while installing python-nmap==0.7.1 --hash=sha256:f75af6b91dd8e3b0c31f869db32163f62ada686945e5b7c25f84bc0f7fad3b64! Will try again.
An error occurred while installing pyyaml==6.0 --hash=sha256:231710d57adfd809ef5d34183b8ed1eeae3f76459c18fb4a0b373ad56bedcdd9 --hash=sha256:d4eccecf9adf6fbcc6861a38015c2a64f38b9d94838ac1810a9023a0609e1b78 --hash=sha256:b5b9eccad747aabaaffbc6064800670f0c297e52c12754eb1d976c57e4f74dcb --hash=sha256:819b3830a1543db06c4d4b865e70ded25be52a2e0631ccd2f6a47a2822f2fd7c --hash=sha256:213c60cd50106436cc818accf5baa1aba61c0189ff610f64f4a3e8c6726218ba --hash=sha256:d4db7c7aef085872ef65a8fd7d6d09a14ae91f691dec3e87ee5ee0539d516f53 --hash=sha256:2cd5df3de48857ed0544b34e2d40e9fac445930039f3cfe4bcc592a1f836d513 --hash=sha256:c5687b8d43cf58545ade1fe3e055f70eac7a5a1a0bf42824308d868289a95737 --hash=sha256:9df7ed3b3d2e0ecfe09e14741b857df43adb5a3ddadc919a2d94fbdf78fea53c --hash=sha256:cba8c411ef271aa037d7357a2bc8f9ee8b58b9965831d9e51baf703280dc73d3 --hash=sha256:e61ceaab6f49fb8bdfaa0f92c4b57bcfbea54c09277b1b4f7ac376bfb7a7c174 --hash=sha256:07751360502caac1c067a8132d150cf3d61339af5691fe9e87803040dbc5db57 --hash=sha256:77f396e6ef4c73fdc33a9157446466f1cff553d979bd00ecb64385760c6babdc --hash=sha256:473f9edb243cb1935ab5a084eb238d842fb8f404ed2193a915d1784b5a6b5fc0 --hash=sha256:0283c35a6a9fbf047493e3a0ce8d79ef5030852c51e9d911a27badfde0605293 --hash=sha256:277a0ef2981ca40581a47093e9e2d13b3f1fbbeffae064c1d21bfceba2030287 --hash=sha256:0ce82d761c532fe4ec3f87fc45688bdd3a4c1dc5e0b4a19814b9009a29baefd4 --hash=sha256:9fa600030013c4de8165339db93d182b9431076eb98eb40ee068700c9c813e34 --hash=sha256:daf496c58a8c52083df09b80c860005194014c3698698d1a57cbcfa182142a3a --hash=sha256:055d937d65826939cb044fc8c9b08889e8c743fdc6a32b33e2390f66013e449b --hash=sha256:48c346915c114f5fdb3ead70312bd042a953a8ce5c7106d5bfb1a5254e47da92 --hash=sha256:a80a78046a72361de73f8f395f1f1e49f956c6be882eed58505a15f3e430962b --hash=sha256:897b80890765f037df3403d22bab41627ca8811ae55e9a722fd0392850ec4d86 --hash=sha256:0b4624f379dab24d3725ffde76559cff63d9ec94e1736b556dacdfebe5ab6d4b --hash=sha256:d67d839ede4ed1b28a4e8909735fc992a923cdb84e618544973d7dfc71540803 --hash=sha256:68fb519c14306fec9720a2a5b45bc9f0c8d1b9c72adf45c37baedfcd949c35a2 --hash=sha256:1e4747bc279b4f613a09eb64bba2ba602d8a6664c6ce6396a4d0cd413a50ce07 --hash=sha256:50602afada6d6cbfad699b0c7bb50d5ccffa7e46a3d738092afddc1f9758427f --hash=sha256:40527857252b61eacd1d9af500c3337ba8deb8fc298940291486c465c8b46ec0 --hash=sha256:d15a181d1ecd0d4270dc32edb46f7cb7733c7c508857278d3d378d14d606db2d --hash=sha256:98c4d36e99714e55cfbaaee6dd5badbc9a1ec339ebfc3b1f52e293aee6bb71a4 --hash=sha256:b3d267842bf12586ba6c734f89d1f5b871df0273157918b0ccefa29deb05c21c --hash=sha256:f84fbc98b019fef2ee9a1cb3ce93e3187a6df0b2538a651bfb890254ba9f90b5! Will try again.
Ignoring sqlparse: markers u"python_version >= '3.5'" don't match your environment
Ignoring uritemplate: markers u"python_version >= '3.6'" don't match your environment
     ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 92/92 — 00:00:41
Installing initially failed dependencies...
[InstallError]:   File "/usr/local/lib/python3.6/site-packages/pipenv/cli/command.py", line 253, in install
[InstallError]:       site_packages=state.site_packages
[InstallError]:   File "/usr/local/lib/python3.6/site-packages/pipenv/core.py", line 2063, in do_install
[InstallError]:       keep_outdated=keep_outdated
[InstallError]:   File "/usr/local/lib/python3.6/site-packages/pipenv/core.py", line 1312, in do_init
[InstallError]:       pypi_mirror=pypi_mirror,
[InstallError]:   File "/usr/local/lib/python3.6/site-packages/pipenv/core.py", line 900, in do_install_dependencies
[InstallError]:       retry_list, procs, failed_deps_queue, requirements_dir, **install_kwargs
[InstallError]:   File "/usr/local/lib/python3.6/site-packages/pipenv/core.py", line 796, in batch_install
[InstallError]:       _cleanup_procs(procs, failed_deps_queue, retry=retry)
[InstallError]:   File "/usr/local/lib/python3.6/site-packages/pipenv/core.py", line 703, in _cleanup_procs
[InstallError]:       raise exceptions.InstallError(c.dep.name, extra=err_lines)
[pipenv.exceptions.InstallError]: Usage:
[pipenv.exceptions.InstallError]:   pip install [options] <requirement specifier> [package-index-options] ...
[pipenv.exceptions.InstallError]:   pip install [options] -r <requirements file> [package-index-options] ...
[pipenv.exceptions.InstallError]:   pip install [options] [-e] <vcs project url> ...
[pipenv.exceptions.InstallError]:   pip install [options] [-e] <local project path> ...
[pipenv.exceptions.InstallError]:   pip install [options] <archive url/path> ...
[pipenv.exceptions.InstallError]:
[pipenv.exceptions.InstallError]: no such option: --no-use-pep517
ERROR: Couldn't install package: fancycompleter
 Package installation failed...
  ☤  ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 7/11 — 00:00:01


text:
Q: UIDatePicker return wrong NSDate I am using UIDatePicker in my app and when i take the date that was chosen with:
NSDate *date = picker.date;

picker.date returned the day before the date that I chose.
any idea why it happens?

A: UIDatePicker will be displaying dates and times in your local timezone. However, NSDate does not have any concept of a timezone as it stores an absolute number of seconds since a reference date. When NSLogging a date, it shows the date and time in GMT. I expect if you work out your local timezone difference from GMT, you will see that it is the correct date.
Try creating an NSDateFormatter or NSCalendar with the appropriate locale and pass the date through that.
For further reading on this common topic, see this site written by another SO contributor.

A: give this a try worked for me
        NSDate* sourceDate = [NSDate date];

        NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
        NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

        NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
        NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
        NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

        NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];

//i'm outputting mine in a label you can use anything you like
        NSString *dateOutput = [[[NSString alloc] initWithFormat:@"%@", destinationDate]autorelease];
        self.dateLabel.text = dateOutput;

A: Remember to create the NSDate and then output it with a valid timezone and calendar!
NSDate only represents an absolute point in time. It has no concept of timezone (NY, Barcelona, ...) or calendar (Gregorian, Hebrew, ...).
UIDatePicker returns by default a NSDate with the system NSCalendar and NSTimeZone, but when you try to print it later, you do not format the output. You may have there the mismatch.
So 1st you need to setup the UIDatePicker correctly and 2nd transform the output with the NSDateFormatter so it knows the Calendar and the TimeZone being used.
An example code with the init of the UIDatePicker and then printing the result:
- (void)viewDidLoad
{
   [super viewDidLoad];

   // init the UIDatePicker with your values
   // by default UIDatePicker inits with today, system calendar and timezone
   // Only for teaching purposes I will init with default values
   NSDate * now = [[NSDate alloc] init];
   [_datePicker setDate: now]
               animated: YES];

   _datePicker.timeZone = [NSTimeZone localTimeZone];
   _datePicker.calendar = [NSCalendar currentCalendar];

   [_datePicker addTarget: self
                   action: @selector(getDatePickerSelection:)
         forControlEvents:UIControlEventValueChanged];

}

-(void)getDatePickerSelection:(id) sender
{

   // NSDateFormatter automatically inits with system calendar and timezone
   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
   // Setup an output style
   [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
   [dateFormatter setTimeStyle:NSDateFormatterShortStyle];

   // Medium style date, short style time => "Nov 23, 1937 3:30pm"
   NSString *dateString = [dateFormatter stringFromDate:date];

}

Check the answer I did for another very similar question:

NSDate output using NSDateFormatter

A: Did you check the timezone?
When you print an NSDate it will use GMT as it timezone.
If you set the system timezone to the NSDateFormatter you might get an other date, because it will take the timezone and calculate the time accordingly.
Add this code and see if the output is correct:
NSDate *date = picker.date;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:NSDateFormatterNoStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSLog(@"Date: %@", [dateFormmater stringFromDate:date]);
[dateFormatter release], dateFormatter = nil;

A: Just add one line of code
self.datePicker.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

0 is for GMT 00 . Add according to your time zone.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I override the properties and functions of a generically typed interface extending a non generic interface to consider generic type(s) in C# What I have is a non generic interface for the purpose of having a common contact that I can call functions. The interface returns objects which implement other interfaces. For example:
public interface ISearchAdvancedInputController
{
    ISearchAdvancedInput GetAdvancedInput();
    void LoadFromModel(ISearchAdvancedInput advancedInput);
}

I then currently have an abstract generic class which implements the interface but imposes requirements of the type. The types of the abstract class must implement the same interfaces as the interface's properties and functions demand. I cast the generic type to the implemented type when necessary so that I can satisfy the requirements of the implemented non abstract interface. This way, I can extend this abstract class and it will enforce type requirements across a larger class w/ many different types used across it. For example:
public abstract class ISearchAdvancedInputControllerBase<standardInput, advancedInputType> : ISearchAdvancedInputController
    where advancedInputType : ISearchAdvancedInput
{
    protected abstract advancedInputType GetAdvancedInput();

    ISearchAdvancedInput ISearchAdvancedInputController.GetAdvancedInput()
    {
        return GetAdvancedInput();
    }

    void ISearchAdvancedInputController.LoadFromModel(ISearchAdvancedInput advancedInput)
    {
        LoadFromModel((advancedInputType)advancedInput);
    }

    public abstract void LoadFromModel(advancedInputType advancedInput);
}

This works really well in general however it falls short because I'm having to use an abstract CLASS in order to perform this overriding. As such when I want to actually make use of it for more concrete examples, I encounter the error that I can only extend a single class.
So to get around this I extend the "other" class in the previous base abstract class. However this is not ideal because if I wind up creating another concrete implementation I need to redefine all of the type translations that I'm doing which is NOT related to the concrete classes implementation.
What I'd like is to not have an abstract class but instead some sort of abstract interface. If I had this I'd be able to implement concrete classes more succinctly. I've looked at other instances of this question and have tried what seems to be the main suggestion which is to make the initial interface generic and have the type extend the resulting interface type and then extend that interface with the more abstract interface as such:
interface TestGenericInterface<a> where a:TestClassInterfaceA
{
    TestClassInterfaceA testGeneric { get; }
}

interface TestGenericComplexInterface<a> : TestGenericInterface<a>
    where a:TestClassInterfaceA
{
    new a testGeneric { get; }
}

However the concrete class seems to suffer from the same issue that's shown when you start from a non generic interface where each function / property of the base interface needs overwritten.
public class TestClass : TestGenericComplexInterface<TestGC>
{
    public TestGC testGeneric => I want to complete this because its return is the type that I'm wanting to use for this concrete implementation

    TestClassInterfaceA TestGenericInterface<TestGC>.testGeneric => I don't want to have to complete this because this function is already handled by the previous function in a round about sense.
}

public class TestGC : TestClassInterfaceA { }

I do see a note that I could provide default implementation of functions if I use c# v8.0 or greater, so I must be on a version prior to that but I figure this should be possible w/o that, but maybe in a different way. Hope ya'll can assist.


text:
Q: Error in adding firebase messaging to flutter? I want to add firebase messaging to my flutter app and I want to register the plugin in application.java
but my app gets stuck at
 Installing build\app\outputs\apk\app.apk...
and when I try to launch it gives me an error that it keeps stopping.
the file contains errors in importing the package
My Code:
package com.example.flutter_fcm_java_test;

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
//Error in this import
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;

public class Application extends FlutterApplication implements PluginRegistrantCallback {
    @Override
    public void onCreate() {
        super.onCreate();
        //can't read firebase messaging service
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    @Override
    public void registerWith(PluginRegistry registry) {
        GeneratedPluginRegistrant.registerWith(registry);
    }
}

I've added the firebase messaging plugin dependency in my pubspec.yaml file and changed my name tag in the manifest to .Application and it can read it.
please help me.
My directory to Application.java
C:\Users...\AndroidStudioProjects\flutter_fcm_java_test\android\app\src\main\java\com\example\flutter_fcm_java_test
the file extension is java source file

A: Any error message with the building? If faced message as
[firebase_messaging] class file for com.google.firebase.messaging.FirebaseMessagingService not found

Try following resolution (tested with firebase_messaging: ^6.0.3) by adding firebase messaging dependency in your app/build.gradle
dependencies {
  // ...

  implementation 'com.google.firebase:firebase-messaging:20.1.0'
}


text:
Q: Show content after the first and second paragraph The function below is used to show certain content after the first paragraph. I would like to show 'content X' after the 1st paragraph and 'content Y' after 2nd paragraph.
<?php
$paragraphAfter= 1; //display after the first paragraph
$content = apply_filters('the_content', get_the_content());
$content = explode("
", $content);
for ($i = 0; $i <count($content); $i++ ) {
if ($i == $paragraphAfter) { ?>

Insert content here

<?php }
echo $content[$i] . "
";
} ?>

I appreciate any help.

A: My way to do this (see update below):
function addParagraphs($content) {
    // you can add as many as you want:
    $additions = array(
        '
After 1st paragraph
',
        '
After 2nd paragraph
'
    );

    $content = get_the_content();

    $output = ''; // define variable to avoid PHP warnings

    $parts = explode("
", $content);

    $count = count($parts); // call count() only once, it's faster

    for($i=0; $i<$count; $i++) {
        $output .= $parts[$i] . '
' . $additions[$i]; // non-existent additions does not concatenate
    }
    return $output;

}
add_filter('the_content','addParagraphs');

Answer is updated according to subsequent comments:
$paragraphAfter[1] = '
AFTER FIRST
'; //display after the first paragraph
$paragraphAfter[3] = '
AFTER THIRD
'; //display after the third paragraph
$paragraphAfter[5] = '
AFTER FIFtH
'; //display after the fifth paragraph

$content = apply_filters( 'the_content', get_the_content() );
$content = explode("
", $content);
$count = count($content);
for ($i = 0; $i < $count; $i++ ) {
    if ( array_key_exists($i, $paragraphAfter) ) {
        echo $paragraphAfter[$i];
    }
    echo $content[$i] . "
";
}

A: add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = '
Ads code goes here
';

    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 2, $content );
    }

    return $content;
}

// Parent Function that makes the magic happen

function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '
';
    $paragraphs = explode( $closing_p, $content );
    foreach ($paragraphs as $index => $paragraph) {

        if ( trim( $paragraph ) ) {
            $paragraphs[$index] .= $closing_p;
        }

        if ( $paragraph_id == $index + 1 ) {
            $paragraphs[$index] .= $insertion;
        }
    }

    return implode( '', $paragraphs );
}

A: I knew it's old question but this answer should help the people still looking for it.
This plugin works perfectly in any theme.
https://wordpress.org/plugins/insert-post-ads
You can choose first / second or whatever you like to display your ads.

A: I was looking for a way to make calls get_template and here I share it in case it is useful
<?php
            $paragraphAfter[1] = "get_template_part( 'part-related', 'ad-first' );";
            $paragraphAfter[3] = "get_template_part( 'part-related', 'ad-third' );"; //display after the fifth paragraph
            $paragraphAfter[5] = "get_template_part( 'part-related', 'ad-fifth' );";

            $content = apply_filters( 'the_content', get_the_content() );
            $content = explode("
", $content);
            $count = count($content);
            for ($i = 0; $i < $count; $i++ ) {
                if ( array_key_exists($i, $paragraphAfter) ) {
                $string = eval($paragraphAfter[$i]); // Eval string
                    echo $string;
                }
                echo $content[$i] . "
";
            }
     ?>


text:
Q: JS pass default parameter as a variable that is defined inside that function? For example:
function mf(z, x c, lol = b) { // I need lol = azazaz
  let b = azazaz
  ...
}

Instead of lol = azazaz I obviously get b is not defined.
What I can do:
function mf(z, x, c, lol = "b") { //parameter lol is a string
  let b = azazaz
  lol = eval(lol) //now lol = azazaz
  ...
}

Also I can do this:
function mf(z, x, c, lol) { //parameter lol doesn't have default value
  b = azazaz
  if (lol == 0) {
    lol = b             //default value of lol = azazaz
  }
  ...
}

But the first one looks so non-professional, the second one has extra if statement which I also don't want. Is there any better way to do this?

A: If defining the variable inside of the function isn't a hard requirement, you can probably leverage closures to do something like:
const b = 'azazaz';
function mf(z, x, c, lol = b) {
 ...
}

Or, perhaps use 'OR' to avoid if
function mf(z, x, c, lol) { //parameter lol doesn't have default value
  let b = 'azazaz';
  lol = lol || b;
  ...
}

A: If you need to change paramater and re-use it you must re-call the function like:

//every time function change lol and recall function
function mf(z, x, c, lol) {
  console.log('lol now is: ' + lol);
  lol++;
  if (lol <= 10) {
    mf(1, 2, 3, lol);
  }
}

mf(1, 2, 3, 0);


text:
Q: PHP - How to add the letter 'a' after each consonant from a string in an array? I need to put an a after each consonant in an array so that for example:
hello result will be : haelalao

A: <?php
$str = "hello";
$vowel = ['a','e','i','o','u'];
$arr1 = str_split($str);//convert your string to array
$arr_new = array();

foreach ($arr1 as $value) {
    array_push($arr_new, $value);
    if (!in_array($value, $vowel)) {
        array_push($arr_new, 'a');
    }
}

print_r($arr_new);//print your array here
?>

A: Probably the  easiest way to do it:
preg_replace('/[b-df-hj-np-tv-z]/i', '${0}a', 'hello'); // => haelalao

Demo

A: Without a foreach , However, internal loopings apply..

$str="hello";
$srch=array_diff(str_split($str),array('a','e','i','o','u'));
echo str_replace('aa','a',str_replace($srch,array_map(function ($v){ return $v.'a';},$srch),$str));

OUTPUT:
haelalao

Working Demo

A: <?php
$str = 'hello';
$vowels = array('a', 'e', 'i', 'o', 'u');
$new = str_split($str);
$converted = '';
foreach ($new as $each) {
  if(in_array($each, $vowels)) {
    $converted .= $each;
  } else {
    $converted .= $each.'a';
  }
}
?>

A: function ConvertString($convert) {
    return preg_replace('/[b-df-hj-np-tv-z]/i', '${0}a', '$convert');
}

echo ConvertString("Hello");


text:
Q: List of software for finding closed form of floating point number (a numeric approximation). The number 10.3500574150076 is a numeric approximation of $\log(2)^2+\pi^2$. If we do not know its closed form and want to find it using computer, then there are a few things we may tre:

*

*Inverse Symbolic Calculator (ISC)

*WolframAlpha

*Maple's identify function.

*The On-Line Encyclopedia of Integer Sequences (oeis).

By asking my previous question, I also learned a new one.

*

*RIES by Robert Munafo.

Is there any other software that may be helpful for this kind of task?

A: This is not an answer to the question, but a comment too long to be put in the comments section.
I don't know if they are other public softwares than those in the large list already given.
For the record, it will be noted that one of the first software of this kind was developed by Simon Plouffe , Laboratoire de combinatoire et d'informatique mathématique de l'UQAM, Québec University, Montréal(Canada) and in the IUT Informatique de Nantes (France). Unfortunately, the public access to the so called "Plouffe Inverter" is no longer available.
I would like to give another viewpoint about these kind of softwares. This concerns the computer students and more precisely mathematical software development.
Developing a basic form of software of this kind is not so complicated that one think at first sight. This could be an excellent training for students learning data processing and computational science : That is why I pick that point up here.
Even with a small computer rather slow and of low capacity, already remarkable results can be observed. For example, with a personal computer of old generation, the example proposed by ablmf (10.3500574150076 ) is solved in an acceptable time. The solution $(\ln(2))^2+\pi^2$ appears in top place on the list of approximate formulas found :

The symbols are : p=$\pi$ , c=Catalan constant, g=Euler-Mascheroni constant, sh=$\sinh$, ch=$\cosh$, ...
The general principle to write such a software is roughly described in the paper (in French) :  https://fr.scribd.com/doc/14161596/Mathematiques-experimentales


text:
Q: How can TypeScript support This type of Generic Type?
seems there are already a github issue for this ts#1213.

This type usage is more like high-order function.
I'm not sure whether TS support it.
The interface is same, but want to implement sync & async version.

interface IO<T> {
  get: () => T<number>;
  set: (v: number) => T<boolean>;
}

type Raw<T> = T;

class SyncO implements IO<Raw> {
  get() {
    return 1;
  }

  set(v) {
    v;
    return true;
  }
}

class AsyncO implements IO<Promise> {
  get() {
    return Promise.resolve(1);
  }

  set(v) {
    v;
    return Promise.resolve(true);
  }
}

A: Not fully sure why you have a T that is not generic but then used in your interface as it is. That is a syntax error.
But if you want a merged interface for both you can use the union types with |
type syncOrAsync<T> = T | Promise<T>;

interface IO<T> {
  get: () => syncOrAsync<T>;
  set: (v: number) => syncOrAsync<boolean>;
}

class SyncO implements IO<syncOrAsync<number>> {
  get() {
    return 1;
  }

  set(v: number) {
    return true;
  }
}

class AsyncO implements IO<syncOrAsync<number>> {
  get() {
    return Promise.resolve(1);
  }

  set(v: number) {
    return Promise.resolve(true);
  }
}

A: just find an answer when I read RESTyped's code:
type MaybePromise<T, P extends boolean> =
  P extends true ? Promise<T> : T;

interface IO<P extends boolean> {
  get: () => MaybePromise<number, P>;
  set: (v: number) => MaybePromise<boolean, P>;

  invalidSet: (v: number) => MaybePromise<boolean, P>;
}

class SyncO implements IO<false> {
  get() { return 1; }
  set(v) { return true; }

/* ts error:
(method) SyncO.invalidSet(v: any): Promise<boolean>
Property 'invalidSet' in type 'SyncO' is not assignable to the same property in base type 'IO<false>'.
  Type '(v: any) => Promise<boolean>' is not assignable to type '(v: number) => boolean'.
    Type 'Promise<boolean>' is not assignable to type 'boolean'.ts(2416)
*/
  invalidSet(v) { return Promise.resolve(true); }
}

class AsyncO implements IO<true> {
  get() { return Promise.resolve(1); }
  set(v) { return Promise.resolve(true); }

/* ts error:
(method) AsyncO.invalidSet(v: any): boolean
Property 'invalidSet' in type 'AsyncO' is not assignable to the same property in base type 'IO<true>'.
  Type '(v: any) => boolean' is not assignable to type '(v: number) => Promise<boolean>'.
    Type 'boolean' is not assignable to type 'Promise<boolean>'.ts(2416)
*/
  invalidSet(v) { return true; }
}


text:
Q: Date formatting not working in Apex I am trying to convert the date in a date field to different time zones using format method. But it is not getting converted. Below is the sample code.
Account acc = [select id, custom_date__c from Account where custom_date__c != null limit 1];

datetime dateee = acc.custom_date__c ;

system.debug('date1 -- '+dateee);
dateee.format('MM/dd/yyyy HH:mm:ss','America/New_York');
system.debug('date2 -- '+dateee);
dateee.format('MM/dd/yyyy HH:mm:ss','GMT');
system.debug('date3 -- '+dateee);
dateee.format('MM/dd/yyyy HH:mm:ss','Australia/Sydney');
system.debug('date4 -- '+dateee);

custom_date__c  is a Date field. I am not concerned with the timestamp. I tried by declaring 'dateee' variable as Date and DateTime both. But nothing is working and the dateee variable is not getting converted. I am trying this piece of code in anon window. Does it make any difference ?
Below is the debug log.

A: Format returns a new string. You need to assign the value to a new variable.
Account acc = [select id, custom_date__c from Account where custom_date__c != null limit 1];

datetime dateee = acc.custom_date__c ;
String formattedString = dateee.format('MM/dd/yyyy');
System.debug(formattedString);


text:
Q: Unrecognized VM option 'AggressiveOpts' I'm trying to run my gatling project in intelliJ using Java 8.
I know that the VM option 'AggressiveOpts' is deprecated in Java 11 and removed in Java 12, but I was wondering why I am getting this error in Java 8?
I have updated my project SDK to be java 8 as well as updating my intelliJ boot runtime to also be Java 8 but this doesn't seem to work.
I have uninstalled Java and IntelliJ and clean installed them both again but that did not resolve the issue.
I have also tried using a different IDE which is VSC (Visual Studio Code) but I get the same errors as I did in intelliJ.
Unrecognized VM option 'AggressiveOpts'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

My current version of Java is 1.8.0_181
My current version of Gatling is 3.3.1
If it helps I am using gradle and the version is 4.8.1
Can anyone help resolve this issue?
Edit: Added build.gradle code
please see the build.gradle here:
https://pastebin.com/MigH0Gxz

A: The only possible explanation is that you have multiple JDK version installed on your machine and that gradle doesn't pick 1.8.0_181 but 12+ when creating the forked Gatling process. Do you have JAVA_HOME env var defined and where does it point to?

A: If what you have shown us is accurate, you don't mention AggressiveOpts at all in the Gradle file.
I found an issue in the Gatling issue tracker that mentions this is a problem when you try to run Gatling on newer JVMs.  The implication of the issue is that Gatling is supplying the JVM option itself.
However:

*

*The issue was apparently fixed in Gatling 3.3.0 (see issue 3807)

*It should only affect you if Gatling is run using a Java 12+ JVM.

The latter suggests that (despite what you say that you are running your Gradle build using Java 8) Gatling is actually using a later version of Java.
For what it is worth, the changeset that fixes this problem simply removes the unknown flag from the gatling.bat and gatling.sh files.  You could find and check whichever of those files is relevant to your platform and remove the unsupported option by hand.  Or you could try to figure out how Gatling is deciding which JVM to use.


text:
Q: Sending Arabic text from Android phone to online MySQl database I made an application that sends few text inputs from android to my online database. My application ran good, but some users reported that they can't use Arabic text. So I tried, and When I send Arabic text in the database it appears as ????? ????? ??????
My php script:
<?php
$connect = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);

if(mysql_errno($connect))
{
die("Failed to connect to MySQL: " . mysql_error());
}
else
{
    echo "success";
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
}

$name = isset($_POST['name']) ? $_POST['name'] : '';
$sex = isset($_POST['sex']) ? $_POST['sex'] : '';
$nationality = isset($_POST['nationality']) ? $_POST['nationality'] : '';

$query = mysql_query( "insert into people (name, sex, nationality) values (N'$name' ,N'$sex', N'$nationality') ", $connect);

print_r($_POST);
if(!$query) echo mysql_error();
mysql_close($connect);
?>

my Android code:
                DefaultHttpClient httpclient= new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.xxxxxxxx.com/thescript.php");
                Log.e("done 1st","its here");

                try
                {
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("name", Name.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("sex",  Sex.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("nationality",  Nationality.getText().toString()));

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    Log.e("done", String.valueOf(response));
                }

I tried few stuff as you can see but none worked.
and when using insert into using online pc .php I get like this : لببي
---------
My Database settings are:
The table collation is utf8_general_ci
 and its type is MyISAM
and the collumns (name,sex,nationality) inside it:
type is varchar and collation is utf8_general_ci
ex.
the output should be علي but it's ???

A: Do this way
DefaultHttpClient httpclient= new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.xxxxxxxx.com/thescript.php");
                Log.e("done 1st","its here");

                try
                {
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("name", Name.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("sex",  Sex.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("nationality",  Nationality.getText().toString()));

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); //UPDATE HERE
                    HttpResponse response = httpclient.execute(httppost);
                    Log.e("done", String.valueOf(response));
                }

A: Type shouldn't be varchar, since it does not accept Unicode characters. Update it to nvarchar!
Like Andries said, collation should be set to utf8_general_ci or other Unicode collation as well.
EDIT:
So, since you are on MySQL v5.x you should have a config file (like my.cnf). You should ensure you are not using your super user to access the database. Add this to you config file.
[mysqld]
init_connect='SET collation_connection = utf8_general_ci; SET NAMES utf8;'
default-character-set=utf8
character-set-server=utf8
collation-server=utf8_general_ci

This will trigger any connection to use utf8_general_ci for any connection.
Restart MySQL and if mysqld.log does not return any error you should rally!

A: I believe your java code is right.
On the backend, Try to use this code: (and if you can switch to PDO)
$conn= mysql_connect($db_host,$db_uid,$db_pass, true) or die('could not connect');
mysql_select_db($db_name);
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);
mysql_set_charset('utf8', $conn);

Debug to know the encoding using:
<?php
$charset = mysql_client_encoding($conn);
echo "The current character set is: $charset\n";
?>

Then
Execute the following commands as root:
ALTER DATABASE YOUR_DATABASE_ NAME CHARACTER SET utf8 COLLATE utf8_general_ci;
update mysql.proc set character_set_client = "utf8", collation_connection = "utf8_general_ci", db_collation = "utf8";

Then execute the code in the following SO answer

A: You should change your table collation to utf8_general_ci or any other unicode collation. Latin1 cannot represent Arabic script.

A: I had this problem for a week long time and searched and searched, the solution that @biraj Suggested in THE ONLY way to solve this problem! No need to change database or set UTF-8 in php or ....
Using this
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));

and this problem is gone for ever.

A: You need to pass the correct (UTF-8) Charset to your UrlEncodedFormEntity constructor.


text:
Q: Vertical Carousel jQuery I'm trying to create a Carousel, my first attempt at first ever. http://jsfiddle.net/PmNM5/
HTML holds UL LI, each LI has 2 images both accumulate width of 242px and height = 81px
Out of several LI, only 3 should be visible (i.e. 6 images will be visble, as One LI holds 2 images, float:left each.)
UL : is set to display BLOCK, with WIDTH of 242px. HTML is displaying perfectly. but carousel doesnt work, as I know I need to calculate TOP smartly which Im lacking.

JAVASCRIPT:
var myCarousel = {

    setHeight: function() {

        var $img = $('li', '#home_carousel');
        var total = 81 * $img.length;

        $('#home_carousel ul').height(total);

    },

    slide: function() {
        var outPart = $('#home_carousel ul').outerHeight();
        $('#home_carousel_up').on('click', function() {

            var $a = $(this);

            $('#home_carousel ul').animate({
                top: -81 + outPart + 'px'
            }, 500, 'easeOutBounce');

        });

        $('#home_carousel_down').on('click', function() {

            var $a = $(this);

            $('#home_carousel ul').animate({
                top: 81 + 'px'
            }, 500, 'easeOutBounce');

        });

    },

    init: function() {
        this.setHeight();
        this.slide();
    }

};

myCarousel.init();

A: try this
I have written all logic for top offset and stopping animation at ends points.
When scrolling top the condition would be:
($('#home_carousel ul').position().top - 81) >  (242 - outPart)

And when scrolling down condition would be:
$('#home_carousel ul').position().top + 81 <= 0

I have harcoded all values. Please store numbers like 81 and 242 (wrapper height) in variables. It would be great if you calculate heights via jquery .outerHeight method. In that case if height gets changed due to change in your markup or CSS then your code will not break.


text:
Q: VBA Excel - Update one column in different sheet simultaneously May I ask if how can I update a column in different sheets simultaneously? So the thing is I have multiple sheets with the same structure and I need to update the column P with 1 or 0.
Another thing is that I have a delete function that deletes rows simultaneously. It works fine and deletes rows at the same time. Can I use this for my concern? But rather than delete, codes should be modified with the process of updating.
Sub del_stud()

    LRN = ThisWorkbook.Sheets("HOME").Range("K11").value

    For Each ws In Sheets(Array("STUDENTS_INFO", "N-Q1", "N-Q2", "N-Q3", "N-Q4", "N-D", _
    "JK-Q1", "JK-Q2", "JK-Q3", "JK-Q4", "JK-D", "SK-Q1", "SK-Q2", "SK-Q3", "SK-Q4", "SK-D", _
    "CERTIFICATION"))

        With ws.Cells(8, 3).CurrentRegion
            .AutoFilter 2, LRN
            .Offset(1).EntireRow.Delete
            ws.AutoFilterMode = False
        End With
    Next ws

    ThisWorkbook.Sheets("HOME").Range("K11").value = ""

End Sub

A: Sub UpdateAllSheets(rngAddress as String, valueToSet)

    For Each ws In Sheets(Array("STUDENTS_INFO", "N-Q1", "N-Q2", "N-Q3", "N-Q4", "N-D", _
                                "JK-Q1", "JK-Q2", "JK-Q3", "JK-Q4", "JK-D", "SK-Q1", _
                                "SK-Q2", "SK-Q3", "SK-Q4", "SK-D", "CERTIFICATION"))
        ws.range(rngAddress).value = valueToSet
    Next ws
End Sub

Example call to set P5 to 1 on each sheet:
UpdateAllSheets "P5", 1


text:
Q: How to prevent nested promise from hanging? The following code works (the user object is written to the console), however the process doesn't exit. I believe one of the promises must not be resolved?
var Promise = require("bluebird");
var mongodb = require('mongodb');

Promise.promisifyAll(mongodb);

mongodb.MongoClient.connectAsync("mongodb://localhost/test")
.then(function(db){
    var users = db.collection('users');
    return users.findOneAsync({userName: "someuser"});
})
.then(function (result) {
    console.log(result);
})
.catch(function(e){
    //handle error
});

What is wrong with this code?

A: MongoDB creates a persistent connection which you're supposed to use for the whole lifecycle of your application.
When you're done with it - close it. That is - call db.close()
If you want to write saner code, use Promise.using and a disposer for making a saner connectAsync which does resource management for you.


text:
Q: Derivation of formula for heading to another point (lat/long) I know the formula for calculating the heading between to given points (latitude, longitude) is
$$ \tag{1}
\theta = \arctan2(\sin(\Delta\lambda)*\cos(\varphi_2), \cos(\varphi_1)*\sin(\varphi_2) − \sin(\varphi_1)*\cos(\varphi_2)*\cos(\Delta\lambda))
$$
where $\theta$ is the heading from the starting point $P_1(\varphi_1, \lambda_1)$ (latitude, longitude) to the target point $P_2(\varphi_2, \lambda_2)$ and the difference in longitude is $\Delta\lambda = \lambda_2 - \lambda_1$ unless the great circle between the points crosses longitude $\pi$ or $-\pi$, in which case you have to correct.
Equation 1 comes from the formula
$$\tag{2}
\tan(\theta) = \frac{\sin(\Delta\lambda)\cos(\varphi_2)}{\cos(\varphi_1)\sin(\varphi_2)-\sin(\varphi_1)\cos(\varphi_2)\cos(\Delta\lambda)}
$$
but I don't know where this one comes from. Can anyone provide a derivation as I want to understand how this formula came to be.

A: Have a look at this sketch of a triangle on a sphere. B denotes point 1, i.e., $(\phi_1, \lambda_1)$ as well as the angle in the depicted triangle at that point. C denotes point 2, i.e., $(\phi_2, \lambda_2)$ as well as the depicted angle in the triangle at that point. A denotes the north pole as well as the angle in the triangle at that point. We want to find the angle B, which you denoted by $\theta$ in your question.
We can read off these sides and angles from the sketch:
\begin{align}
c&=(\pi/2 - \phi_1)  \\
b&=(\pi/2-\phi_2) \\
A &= (\lambda_2 - \lambda_1) =: \Delta \lambda
\end{align}
To start off, let's use one of the cosine rules of spherical trigonometry
\begin{align}
\cos a&= \cos b \cos c + \sin b \sin c \cos A \\
 &=\sin \phi_2 \sin \phi_1 + \cos \phi_2 \cos \phi_1 \cos (\Delta \lambda)
\end{align}
Note that I used $\sin(\pi/2-x)=\cos(x)$ and $\cos(\pi/2-x)=\sin(x)$ for the last step.
Now that we have $\cos a$, let's solve the following cosine rule of spherical trigonometry for $\cos B$:
\begin{align}
\cos b&= \cos c \cos a + \sin c \sin a \cos B \\
\cos B &= \frac{\cos b -\cos c \cos a }{\sin c \sin a}
\end{align}
The formula you are looking for is given in terms of $\tan B$. So we want to divide $\sin B$ by $\cos B$. For $\sin B$ we will use the sine rule of spherical trigonometry, which states that
\begin{align}
\frac{\sin A}{\sin a}=\frac{\sin B}{\sin b}=\frac{\sin C}{\sin c}
\end{align}
Hence
\begin{align}
\sin B = \sin b \frac{\sin A }{\sin a}
\end{align}
Now we have a formula for $\cos B$ and a formula for $\sin B$. We can use that to find
\begin{align}
\frac{\sin B}{\cos B} &= \sin b \frac{\sin A }{\sin a} \frac{1}{\cos B} \\
\tan (B) &= \cos \phi_2 \frac{\sin(\Delta \lambda)}{\sin a}  \frac{\sin c \sin a} {\cos b -\cos c \cos a }\\
&= \cos \phi_2 \sin(\Delta \lambda)  \frac{\sin c} {\cos b -\cos c \cos a }\\
&= \cos \phi_2 \sin(\Delta \lambda)  \frac{\cos \phi_1} {\sin \phi_2 -\sin \phi_1  \cos a } \\
&= \cos \phi_2 \sin(\Delta \lambda)  \frac{\cos \phi_1} {\sin \phi_2 -\sin \phi_1(  \sin \phi_2 \sin \phi_1 + \cos \phi_2 \cos \phi_1 \cos (\Delta \lambda) ) } \\
&=   \frac{ \sin(\Delta \lambda)  \cos \phi_2 \cos \phi_1} {\sin \phi_2(1-\sin^2\phi_1) -\sin \phi_1 \cos \phi_2 \cos \phi_1 \cos (\Delta \lambda) ) }  \\
&=   \frac{\sin(\Delta \lambda)  \cos \phi_2 } {\sin \phi_2 \cos \phi_1 -\sin \phi_1 \cos \phi_2  \cos (\Delta \lambda) ) }
\end{align}


text:
Q: Pandas isnull.().sum() list all all columns without summary Hello I have a database that has 115 column headers and I need to summarize which columns have null values.  When I use df.isnull().sum() it just gives me the top 30 and the bottom 30 I need to list all columns how would I go about this?
df.isnull().sum()

A: obj = file.isnull().sum()
for key,value in obj.iteritems():
    print(key,",",value)

this line of code worked for me was able to copy to comma-separated CSV

A: I am a beginner pandas user. However, this is a bigenner code that solves your issue, where you store the sum of NaNs in another variable. Then, prints it with .to_string()
var = df.isnull().sum()
print(var.to_string())

I hope it helps you.

A: You can also increase the number of rows that will display:
pd.options.display.min_rows = 115
df.isnull().sum()

A: pd.set_option("display.max_columns" , None)

dataframe.isnull().sum

Use these two commands one by one then you will get your answer
cell 1 run this : pd.set_option("display.max_columns" , None)
cell 2 run this : dataframe.isnull().sum


text:
Q: Print the numbers and pick the right for loop The question is: write a method that is passed an int n and returns a String that counts down from n to 1. Ex countDown(3) prints 321
My code is:
public class CountDown {
    public static void main(String[] args) {
        for(int n = n; n> 0; n--;) {
            System.out.println("i=" + i);
        }
    }
}

I'm a beginner at coding but I'm not sure how to fix this. I believe my for loop is wrong.

A: In your current attempt you haven't declared n variable and then re-declared it inside the for loop which is not allowed.
You should declare a new countDown(int) method and then use either while or for loop. It could look like:
public static void main(String[] args) {
  System.out.println(countDown(3));
}

private static String countDown(int n) {
  StringBuilder builder = new StringBuilder();
  while (n > 0) {
    builder.append(n);
    n--;
  }
  return builder.toString();
}

A: The variable you declared in your for loop (n) is different than the one you printed (i), and you are assigning n to n when it is declared. You need to do this in order to make it work:

*

*Either change the value of the variable in your for loop from n to i or print out n instead of i

*Change the declaration of the variable to not assign it to itself
Here is one way:
public class CountDown {
    public static void main(String[] args) {
        for(int i = 5; i > 0; i--;) {
            System.out.println("i=" + i);
        }
    }
}

This will be the output:
i=5
i=4
i=3
i=2
i=1


text:
Q: Bootstrap nav-tabs with progress bar I am building a registration system and I have a progress bar and a bootstrap nav-tabs in that page.
I am trying to setup the JQuery so that the progress bar advances with the nav-tabs. Here is a visual.

I tried to come up with a simple if else conditional jquery using hasClass and addCLass functions but never got to make a dent.
Something like this:
$(document).ready(function () {
   $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
     if (".nav-tabs") hasClass(".active"); {
       $(".checkout-bar li").addClass("active");
     }
   });
});

I am attaching a CODEPEN
Any idea on how to do this client side? I'd rather keep C# out of this one

A: http://jsfiddle.net/o3637uwh/2/ (update)
in html remove class form all checkout-bar li, except first
HTML

Get Started

About You

Looking For

Review

JQ (update)
$(document).ready(function () {
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

        var href = $(e.target).attr('href');
        var $curr = $(".checkout-bar  a[href='" + href + "']").parent();

        $('.checkout-bar li').removeClass();

        $curr.addClass("active");
        $curr.prevAll().addClass("visited");

    });
});

A: You are not specifying which .checkout-bar li to select. You have to get the index of the .active tab and with this index select the checkount li, I think you shoud do something like this:

$(document).ready(function () {
  $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    activeTabIndex = $('.nav.nav-tabs > li.active ').index();
    (".checkout-bar li.active").removeClass('active');
    $(".checkout-bar li:eq("+activeTabIndex+")").addClass('active')
  });
});


text:
Q: using sequelize login authorization failed in node js I'm trying to make some authorization api using sequelize, nodejs, jwt, mysql but it has some problem
router.post('/login', async(req, res, next) => {
    const {email, password} = req.body;

    findSalt(email)
        .then((doc) => createHash(password, doc.salt)) // password hash
        .then((hashedPassword) => findUser(email, hashedPassword))
        .then((user) => {
            if (user == null) {
                res.json({msg: "failed"});
                return;
            }
            let accessToken = jwt.sign({email, type: user.userType, verified: user.verified},
                process.env.JWT_SECRET_ACCESS, {expiresIn: '36000m'});
            /*
            let refreshToken = jwt.sign({email, type: user.userType, verified: user.verified}, // jwt 생성 후 토큰 반환
                process.env.JWT_SECRET_REFRESH, {expiresIn: '60m'});

            req.cache.set(email, refreshToken);
            req.expire(email, 60 * 10);
            */
            return accessToken
        })
        .then(token => { // save access_token in redis
            const parsedKey = 'access_' + email;
            console.log("parsedKey: ", parsedKey);
            return saveRedis(req, parsedKey, token, 60 * 5);
        })
        .then((token) => { // save token in cookie
            console.log("result token: ",token);
            res.cookie('accessToken', token, {secure: false, httpOnly: true,readOnly : true});
            res.json({msg: 'success'}); // 성공
        })
        .catch(err => {
            res.json({msg: "failed", err});
        });
});

this is login part
function findUser(email, password) {
    return new Promise(function (resolve, reject) {
        User.findOne({
            where: {
                "email": email,
           "password": password
            }
        })
        .then(result => {
            resolve(result);
        })
        .catch((err) => {
            reject(err);
        });

    })
}

this is find user function
function findSalt (email) {
    return new Promise((resolve, reject) => {
        User.findOne({where: {email}})
            .then(result => {
                resolve(result);
            })
            .catch(err => {
                resolve(err);
            });
    })
}

this is findSalt function
function createHash(password, salt) {
    return new Promise((resolve, reject) => {
        crypto.pbkdf2(password, salt, 100000, 64, 'sha512', (err, key) => {
            if (err) reject(err);
            const hashedKey = key.toString('base64');
            resolve(hashedKey);
        });
    });
}

this is create hash function part
I tried login through mysql, database password and console log are same but it failed login
is there any problem?
As you saw in my picture, database content and console log content are same

A: I think your findSalt-function does not work as expected, since it is missing the field to search in:

function findSalt (email) {
 ...
 User.findOne({where: {<name of field>: email}})
 ...
}


text:
Q: How to align images in a row in bootstrap Hey i am aligning 5 images in a row having col-md-2 spacing. But i want to align the row in the middle of the page. Can anyone help how can i acheve this row?
I have just tried the offset col. But it is not working properly.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

A: This is what you are looking for?

A: You can use Bootstrap's alignment classes. Just add the .text-center class to the row.
Please check the result:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">


text:
Q: Disabling SplitScreen mode in Nougat How to disable the SplitScreen mode in Android 7.1.1 without disabling the MultiWindow mode?
I am using Freeform Window Mode to open multiple activities. In landscape orientation of device when an activitiy is dragged to the left or right edge of the screen the activity gets docked and the StackDivider splits the screen. Disabling MultiWindow mode eventually disables Freeform Window mode. So is there any way to disable the SplitScreen mode only (without disabling MultiWindow mode) by editing the Android source code?

A: https://developer.android.com/guide/topics/ui/multi-window.html
As per documentation, do this in you manifest activity or application
android:resizeableActivity=["true" | "false"]

A: In freeform mode, when an application or window is moved left or right corner of the screen by dragging its DecorCaptionView a dim layer is generated either at left or right depending on the position of window and it get docked to the current dim side on  MOtionEvent.ACTION_UP event.
The MotionEvent actions on DecorCaptionView is handled by frameworks/base/services/core/java/com/android/server/wm/TaskPositioner.java and moveTaskToDockedStack() method in ActivityManagerService is invoked whenever a window gets docked. The updateDimLayerVisibility() method in TaskPositioner.java is responsible for the creation of dim layer. So the SplitScreen mode can be disabled by commenting out above mentioned two method calling lines in TaskPositioner.java.


text:
Q: Pass a dynamic Date Date Range to dateRangeInput in R Shiny I am just starting out with Shiny and using it to show wind frequency outputs (speed and direction) for a selected site.
The Issue
Each data set has a different date range and I cant seem to return these variable date ranges back to the dateRangeInput in the UI when the user selects a different site.
If a date is selected that is outside of the selected data set range, Shiny errors and displays red text everywhere. To solve this I am using the min/max ranges to feed into the dataRangeInput.
My Code Sample So Far
The user selects a site from a drop down menu in the UI 'selectInput' which creates the variable input/ID "df".
The only way I can get anything to work is by passing the date range as a global variable using the date range of a particular data set however this is effectively a manual process:
Create some sample data (In the actual data the dates are date/time formatted):
library(shiny)
library(openair)
library(ggplot2)

date<- c("2017-01-01","2017-01-02","2017-01-03","2017-01-04")
ws<-c(rep(0:3,1))
SiteA <- data.frame(date,ws,stringsAsFactors = FALSE)

date<- c("2017-01-01","2017-01-02","2017-01-03","2017-01-04","2017-01-05", "2017-01-06")
ws<-c(rep(0:5,1))
SiteB <- data.frame(date,ws,stringsAsFactors = FALSE)

Extract min and max from the data (this is where I need assistance):
# Date ranges currently fixed to SiteA (need this to be dynamic based on selection)
mystartdate <- as.character(format(as.Date(min(SiteA$date))),"yyyy-mm-dd")
myenddate <- as.character(format(as.Date(max(SiteA$date))),"yyyy-mm-dd")

These dates are then passed to the date range in the UI:
ui <- fluidPage(
    titlePanel("title"),

    sidebarLayout(
            sidebarPanel(
                    selectInput("df","Choose a Site:",
                                choices = c(
                                        "Site A" = 'SiteA',
                                        "Site B" = 'SiteB')
                    ),

                    dateRangeInput("date", "Select the date range:",
                                   start = mystartdate, # Start date of the selected df
                                   end = myenddate, # End date of the selected df
                                   min = mystartdate,
                                   max = myenddate,
                                   format = "yyyy-mm-dd")
            ),
            mainPanel(
                    strong(paste("Frequency Distribution:")),
                    plotOutput("hist")
            )
    )
)

The date ranges are then passed as inputs to filter the plots input$date[1] and input$date[2].
server <- function(input, output) {

    df <- reactive({
            x <- get(input$df)
    })

    output$hist <- renderPlot({
            df <- df() # df is the user selected dataset
            dfhist<- selectByDate(df, start = input$date[1], end = input$date[2])
            ggplot(df, aes(df$ws)) +
                    geom_histogram(fill = "blue", bins = 50) +
                    labs(x="Wind Speed (m/s)", y="Count")

    })
}

shinyApp(ui = ui, server = server)

My Question:
How do I extract the min/max dates from the selected data sets (SiteA or SiteB) and return these to the dateRangeInput cells?
Any ideas/pointers would be much appreciated. Thanks

A: I extract the min / max data from the selected data sets (SiteA or SiteB) and return these to the dateRangeInput cells. And I made the subset in the dataframe according to the date chosen on the dataRangeInput to display the plot.I believe this satisfies all your app.
library(shiny)
library(openair)
library(ggplot2)
library(readr)

ui <- fluidPage(
  titlePanel("title"),

  sidebarLayout(
    sidebarPanel(
      selectInput("df","Choose a Site:",
                  choices = c(
                    "Site A" = 'SiteA',
                    "Site B" = 'SiteB')
      ),
       uiOutput("dateRange")

    ),
    mainPanel(
      strong(paste("Frequency Distribution:")),
      plotOutput("hist")
    )
  )
)

server <- function(input, output, session) {
  df <- reactive({
    if(input$df == "SiteA"){
      date<- c("2017-01-01","2017-01-02","2017-01-03","2017-01-04")
      ws<-c(rep(0:3,1))
      SiteA <- data.frame(date,ws,stringsAsFactors = FALSE)
      x <- SiteA
    }
    if(input$df == "SiteB"){
      date<- c("2017-01-01","2017-01-02","2017-01-03",
                "2017-01-04","2017-01-05", "2017-01-06")
      ws<-c(rep(0:5,1))
      SiteB <- data.frame(date,ws,stringsAsFactors = FALSE)
      x <- SiteB
   }
      return(x)
  })

  output$dateRange <- renderUI({
    dateRangeInput("date", "Select the date range:",
                   start =
    as.character(format(as.Date(min(df()$date))),"yyyy-mm-dd"), # Start
                        end =
    as.character(format(as.Date(max(df()$date))),"yyyy-mm-dd"), # End
               min =
    as.character(format(as.Date(min(df()$date))),"yyyy-mm-dd"),
               max =
    as.character(format(as.Date(max(df()$date))),"yyyy-mm-dd"),
               format = "yyyy-mm-dd")

  })

  output$hist <- renderPlot({
    df <- df() # df is the user selected dataset
    dfhist<- subset(df, date >= as.Date(input$date[1]) & date <=
                     as.Date(input$date[2]) )
    ggplot(dfhist, aes(dfhist$ws)) +
      geom_histogram(fill = "blue", bins = 50) +
      labs(x="Wind Speed (m/s)", y="Count")

  })

}

shinyApp(ui=ui, server = server)


text:
Q: add two sum with join and group by in sql SELECT t1.id, t1.name,SUM(t3.points), SUM(t2.points)
FROM app_users t1
LEFT JOIN loyalty_points_redeem t3 ON t3.app_user_id = t1.id
LEFT JOIN loyalty_points_gain t2 ON t2.app_user_id = t1.id
GROUP BY t1.id

i want to calculate the sum of a particilar i from  table first sum is ok but another is incorrect i am new in sql how to solve that if any idea please help

A: You can try below  by adding t1.name in group by clause
SELECT t1.id, t1.name,SUM(t3.points), SUM(t2.points)
FROM app_users t1
LEFT JOIN loyalty_points_redeem t3 ON t3.app_user_id = t1.id
LEFT JOIN loyalty_points_gain t2 ON t2.app_user_id = t1.id
GROUP BY t1.id,t1.name

A: Couldnt see a problem othertah the GROUP BY
SELECT t1.id, t1.name,SUM(t3.points), SUM(t2.points)
FROM app_users t1
LEFT JOIN loyalty_points_redeem t3 ON t3.app_user_id = t1.id
LEFT JOIN loyalty_points_gain t2 ON t2.app_user_id = t1.id
GROUP BY t1.id, t1.name


text:
Q: Prestashop, building the sub categories tree I'm trying to build a module for Prestashop 1.4, I need to retrieve and show the full category and subcategories list but I'm finding some difficulties:
This is my module logic:
class HyperFeed extends Module {

 function __construct(){ blablabla }

 public function install(){ blablabla }

public function _getCategories(){

    $version_mask = explode('.', _PS_VERSION_, 3);
    if ($version_mask[1]<5){$id_category=1;}else{$id_category=0;}

    function getCategories($id_category){

        $sql = 'SELECT '._DB_PREFIX_.'category.id_category,name,'._DB_PREFIX_.'category.level_depth,'._DB_PREFIX_.'category.id_parent FROM '._DB_PREFIX_.'category
        INNER JOIN '._DB_PREFIX_.'category_lang ON '._DB_PREFIX_.'category_lang.id_category = '._DB_PREFIX_.'category.id_category
         WHERE id_parent = '.$id_category.' AND id_lang = 3';

        $contentTable = '
';
        if ($results = Db::getInstance()->ExecuteS($sql)){
            foreach ($results as $row){

                $contentTable .= '

                    <input type="checkbox" name="footerBox[]" class="cmsBox" id="1_1" value="1_1">
                    '.$row['id_category'].'

                    '.$row['name'].'

';

                getCategories($row['id_category']);

            }
        }
        $contentTable .=  '
';

    }

    getCategories(1);
    $this->_html .= $contentTable;

}

 public function getContent(){

$this->_html .='<form>blablabla';

$this->_getCategories();

$this->_html .='blablabla</form>';

}
    return $this->_html;
    }

All I get is a  "Undefined variable: contentTable", what Am I doing wrong??
Thanks in advance

A: Your $contentTable is defined within getCategories(), not _getCategories().
Therefore on the following lines, it is considered not defined.
getCategories(1);
$this->_html .= $contentTable;

You can try doing the following:
Find:
$contentTable .=  '
';

Replace with:
$contentTable .=  '
';
return $contentTable;

Find:
getCategories(1);
$this->_html .= $contentTable;

Replace with:
$contentTable = getCategories(1);
$this->_html .= $contentTable;

This should properly define the variable within the _getCategories() function, by returning and assigning the $contentTable variable from the getCategories() function.

A: i found something else
public static function getCategoryTree($id_product,$id_lang){
                $root = Category::getRootCategory();
                $selected_cat = Product::getProductCategoriesFull($id_product, $id_lang);
                $tab_root = array('id_category' => $root->id, 'name' => $root->name);
                $helper = new Helper();
                $category_tree = $helper->renderCategoryTree($tab_root, $selected_cat, 'categoryBox', false, true, array(), false, true);
                return $category_tree;
            }

$this->getCategoryTree(null,$id_lang);
and you have your category tree as prestashop backoffice associate tabs.
replace null by an $id_product and product categories will be checked.
Hope i'll help
sorry for my bad english i'm french


text:
Q: Как на nginx настроить правила 301 редиректа для .html .htm страниц? Есть сервер на nginx.
Мне необходимо настроить 301 редирект со страниц example.com/about.html на example.com/about/,
example.com/about.htm на example.com/about/ и т.д., чтобы исключить дубли и ошибочные страницы.
server {
    listen 80;
    server_name ${VIRTUAL_HOST};

    # redirect all http to https
    return 301 https://$server_name$request_uri;
}

A: Попробуйте так:
if ($request_uri ~ "^(.*)\.(?:php|html|htm)") {
   return 301 $1;
}


text:
Q: Clear Screen in Xcode I am making a Library Management System in Xcode using C++. As Xcode does not support libraries such as conio.h and system "cls" does not work in it. What code should I use to clear the screen when I want it to shift from one menu to the other?

A: Check this out.
https://discussions.apple.com/thread/1064635?start=0&tstart=0
There is no direct way to do that; the system() command will not work on Mac (Unix). One option is to add a lot of spaces using code i.e.\n or other way is to use curses library
 #include < curses.h > (curses.h) and then use system("clear"), which basically will do the same thing. So, its better to print spaces manually using the code rather than using some library.
One more thing you can do for POSIX (Unix, Linux, Mac OSX, etc) based systems [Note: I have not tested it myself]:
#include < unistd.h >
#include < term.h >
void ClearScreen()
{
  if (!cur_term)
  {
     int result;
     setupterm( NULL, STDOUT_FILENO, &result );
     if (result <= 0) return;
  }
  putp( tigetstr( "clear" ) );
}

You'll have to link to the proper library (one of -lcurses, -lterminfo, etc.) to compile that last one. (Source: http://www.cplusplus.com/forum/articles/10515/)


text:
Q: how to pass string data through fragments I've been working between Fragment's using FragmentManager's to keep the view of the navigation drawer in my project.
What I want is to get a String from Fragment A and show it on a TextView on the Fragment B. As I'm not working with Intent's, I don't know how to do that. Can anyone please help me?
Here is a piece of my code to explain how i change the views in my project.
Button button = (Button) view.findViewById(R.id.btn_next);
button.setOnClickListener(new View.OnClicklistener(){

    @Override
    public void onClick(View v){

        Fragment frag_A = new ViewClassB();
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction()
            .replace(R.id.container, frag_A)
            .commit();

    }
});

I have the Main class that have a xml with the Fragment Views called container, there is where i show the content of the Activity.
Here is an example for that XML:
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ViewClassA"
    >

    <FrameLayout android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="#fff"
        xmlns:android="http://schemas.android.com/apk/res/android">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Welcome"
            android:id="@+id/text1"
            android:layout_gravity="center"
            android:layout_marginTop="20dp"
            android:textColor="#52D5EC" />

         </LinearLayout>
     </FrameLayout>
 </android.support.v4.widget.DrawerLayout>

That's how I show the content in my project. In the View class B I just do a onCreateView to inflate the elements and work with them.
Again, what I need is to pass a String from the Fragment A to the Fragment B. I'm not using intents.
Can anyone help me, please?

A: From the Fragment documentation:

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

You can use Bundle to pass data from one Fragment to other:
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putString(<KEY>, <VALUE>);
myFragment.setArguments(args);

And at the receiver's end:
String value = getArguments().getString(<KEY>, <DEFAULT_VALUE>);

A: The way to share content between fragments depends on your preferences. There are many options, so choose the one you feel more comfortable with:

*

*Store the string in the activity that contains the fragments. The activity will act as a callback for the first fragment so it can receive this string when it changes. Since the activity is the one that swaps between them, just put the value in a bundle to provide the second fragment with the string value of the first one. (For me this is not the best option, but up to you)

*Store the string in the first fragment and provide a getter so the activity can get it. When there is a need to swap between fragments, just get the value on the first fragment and provide it in a bundle to the second one.

*If both fragments live together (which looks like it is not the case on your app) the clean option is to create an interface, implemented by the fragment that consumes the String, and used by the fragment which provides the String. Just let one fragment to know the other by this interface (not as the fragment itself).

Now, some code on this.
To put a bundle on a fragment:
 Bundle bundle = new Bundle();
 bundle.putString("someString", stringValue);
 fragment.putArguments(bundle);

To get this bundle value inside the fragment:
fragment.getArguments().getString("someString");
To get the current fragment that is in your container use the method FragmentManager#findFragmentById or FragmentManager#findFragmentByTag.


text:
Q: How do I pass an array of images to a variable of type UIImageView in swift? Or what is the right way to store multiple images in a single array? import UIKit

class ViewController: UIViewController {

/* Created IBOutlets for the dices on the Interface builder. */
@IBOutlet weak var diceImageView1: UIImageView!
@IBOutlet weak var diceImageView2: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func rollDiceButton(_ sender: UIButton) {
    diceImageView1.image = [UIImage(named: "DiceOne"), UIImage(named: "DiceTwo")]
 }
}

I want to pass a series of images to my diceImageView1 variable which is of type UIImageView but my code is not working. Any help will be appreciated. Thank you.

A: @IBAction func rollDiceButton(_ sender: UIButton) {
    diceImageView1.image = [UIImage(named: "DiceOne"), UIImage(named:   "DiceTwo")][1] // where 1 refers to the index, could be any number from 0
 }

I added an array index to the end of the array values and it worked fine.


text:
Q: Unit testing a SQL code generator The team I'm on is currently writing code in TSQL to generate TSQL code that will be saved as scripts and later run. We're having a little difficulty in separating our unit tests between testing the code generator parts and testing the actual code that they generate.
I've read through another similar question, but I was hoping to get some specific examples of what kind of unit test cases we might have.
As an example, let's say that I have a bit of code that simply generates a DROP statement for a view, given the view schema and name. Do I just test that the generated code matches some expected outcome using string comparisons and then in a later integration or system test make sure that the drop actually drops the view if it exists, does nothing if the view doesn't exist, or raises an error if the view is one that we are marking as not allowing a drop?
Thanks for any advice!

A: It is reasonable to test the code you want to generate first. Once you know this code works, you can chceck strings as you mentioned.


text:
Q: Access GET Variable on class instantiation PHP? How can I retrieve GET values inside a PHP Class construct or functions?
Similar subject can be found here which I referred to session values, scope.
Access Session Variable within a class
Example which doesn't retrieve value, set inside class construct.
$this->siteid = $_GET['siteid'];

or
$this->siteid = $_REQUEST['siteid'];

The purpose of the above is to retrieve id for testing params, goal is to hold these inside session, similar problem.

A: Can you please check what does var_dump($_REQUEST). I think that variable isn't present in $_GET variable in that particular page in where you are accessing the class.


text:
Q: How to specify the formula for a GLM Negative Binomial model in R I'm looking for some feedback on my approach to predicting a count variable in my dataset. I'm unsure as to whether my approach is sound. My dataset is stored here if anyone is interested.
Since my dependent variable is a positive count variable and the variance of the dependent variable is larger than the mean of the dependent variable I am using the glm.nb function in R.
var(data$depVar)/mean(data$depVar)
[1] 2.529426

My predictor variables consist of 1 factor and 2 discrete numeric variables plus a 4th variable that is used as an offset to explain the differences in the factor variable (indepVar1).

    summary(data)
   indepVar1      depVar        indepVar4      indepVar2       indepVar3
 Deep   :50   Min.   : 0.00   Min.   : 702   Min.   :70.00   Min.   : 2.00
 Shallow:50   1st Qu.: 3.00   1st Qu.: 891   1st Qu.:74.00   1st Qu.: 4.75
              Median : 8.00   Median :1750   Median :79.00   Median : 8.00
              Mean   : 7.77   Mean   :1820   Mean   :79.13   Mean   : 8.59
              3rd Qu.:12.00   3rd Qu.:2797   3rd Qu.:84.00   3rd Qu.:13.00
              Max.   :15.00   Max.   :2998   Max.   :90.00   Max.   :15.00

I'm unsure as to how I configure my formula in my glm.nb I don't understand when to use additive terms or product terms or a combination of both i.e.:
depVar ~ indepVar1 + indepVar2 + offset(log(indepVar3)) (model1)
depVar ~ indepVar1 + indepVar2 + indepVar3 + indepVar1:indepVar3 (model2)

Do I need to include interaction terms since the slope of the regression line for indepVar2 Vs. depVar is negative when viewed from the perspective of indepVar1 whereas the slope for indepVar2 Vs. depVar faceted by indepVar1 is positive? Is this the right approach to identify interaction terms?
I've read about stepwise feature selection based on AIC but the output of this approach indicates to me that there's no predictive power in adding any additional terms to the model other than indepVar1, have I interpreted this correctly?
out0 = glm.nb(depVar ~ 1, data = data)

AICout <- stepAIC(out0,depVar ~ indepVar1 + indepVar2 + indepVar3 + indepVar4, direction = c("both"))

Can this approach be used for feature selection for a glm.nb model and if not can you suggest any other methods that I can use to pick the best model?
Start:  AIC=587.05
depVar ~ 1
            Df    AIC
<none>         587.05
+ indepVar1  1 587.39
+ indepVar4  1 587.51
+ indepVar3  1 587.89
+ indepVar2  1 588.45


text:
Q: How to get post category name How I get post category name using AngularJS with WP-JSON in Wordpress
{{post.title}} working
{{post.content}} working
{{post.terms.category.name}} not working
or
{{post.category.name}} not working
Thanks

A: With {{post.terms.category.name}} you are coming close. However {{post.terms.category}} contains an array. You will have to loop through these values.
To test you can use the first item in line: {{post.terms.category[0].name}} should work for your example.


text:
Q: Array push to end keeping format I'm making a automated system to send out emails. I have an array containing info about registered users: their email and forum name/nickname:
$array = [
    ['jane.apples@gmail.com', 'Jane Apples'],
    ['jdoe@gmail.com', 'John Doe'],
];

To send the emails it uses a for each loop:
foreach ($array as list($email, $name)) {
    echo "$email   $name
";
}

This would yield:
jane.apples@gmail.com   Jane Apples
jdoes@gmail.com   John Doe

In the final code I would like it to do this:
foreach ($array as list($email, $name)) {
    email($email, $name);
}

Also, please note that I would like the array in a different file like: array.php and then include the file.
Please help me do this, and thanks in advance.

A: Update: I've found the solution while messing around a little bit here is the code:
<?php
$result = array();
$file = fopen("mail.txt", "r");
while(!feof($file)){
    $line = fgets($file);

  list($email, $name) = explode(":", $line);
  echo $email . ':' . $name .'
';

}
fclose($file);
?>

The mail.txt file looks like:
jane.apples@gmail.com:Jane Apples
jdoes@gmail.com:John Doe

If you where to use this yourself, edit the part where it echos: $email . ':' . $name . '
';


text:
Q: String returned by variable not working like the same string entered manually I am trying to make some adjustments to uploadify.php which comes with the latest version of uploadify (3.0 beta), so that it works with a session variable that stores the login username and adds it to the path for uploads.  Here is uploadify.php as it currently looks:
<?php
session_name("MyLogin");
session_start();

$targetFolder = '/songs/' . $_SESSION['name']; // Relative to the root

if (!empty($_FILES)) {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
    $targetFile = rtrim($targetPath,'/') .'/'. $_FILES['Filedata']['name'];

    // Validate the file type
    $fileTypes = array('m4a','mp3','flac','ogg'); // File extensions
    $fileParts = pathinfo($_FILES['Filedata']['name']);

    if (in_array($fileParts['extension'],$fileTypes)) {
        move_uploaded_file($tempFile,$targetFile);
        echo '1';
    } else {
        echo 'Invalid file type.';
    }
}

echo $targetFolder;

?>

I added echo $targetFolder; at the bottom so that I could make sure that the string returned was correct, and it is, i.e. '/songs/nick'.  For some reason though, uploads are not going to the correct folder, i.e. the username folder, but instead are going to the parent folder 'songs'.  The folder for username exists, with correct permissions, and when I manually enter $targetFolder = '/songs/nick'; all works fine.  Which strikes me as rather strange.  I have limited experience of using php, but wonder how if the correct string is returned by the session variable, the upload works differently than with the manually entered string.
Any help would be much appreciated.  It's the last issue with a website that was due to go live 2 days ago!
Thanks,
Nick

A: Hy
Try use 'songs/' , without the first '/'


text:
Q: ASP.NET MVC - How to keep collections value when calls an Action? I have a ViewModel like this:
public class MyViewModel
{
    public string SelectedItem { get; set; }
    public List<MyClass> Items { get; set; }
}

I fill these items on screen with a @Html.DropDownListFor(m => m.SelectedItem, new SelectList(...)).
Ok, but when I call any action which receives this ViewModel, I got this collection empty.
Is there a way to get back the DropDownList values when I call any action?

A: That's a normal behavior and it's how HTML works. Only the selected value of a <select> element is sent to the server, not the entire collection. In your POST action if you want to retrieve the collection all you have to do is exactly the same you did in your GET action to retrieve it in the first place. That's usually a database call. And if you are afraid that you might be hitting your database quite often, just cache the collection.

A: In a tag form you can only send the value selected in the tag select, in this case the value of SelectedItem.
If you need also send the list of values of Items, you have to create something like this:
@{
   var ind = 0;
   foreach(var item in Model.Items)
   {
      <input type="hidden" name="Items[@ind].Id" value="@item.Id"/>
      ind++;
   }
}

But id you can send the data by Ajax, in this case is mode simple, because you can create the data to send. See this plugin toDictionary

A: One way is to have the List<SelectListItem> as part of the view model and populate it via a method called from the controller and pass it to the view, e.g.
View model:
public List<SelectListItem> SelectList { get; set; }

And in the view:
@Html.DropDownListFor(model => model.SelectedItem, Model.SelectList)


text:
Q: I want show date and time on label in my own format and the datetime come from database is not looking good Curently m using this
@Html.Label( msg[i].datetime.ToString())

(4/23/2016 5:09:00 AM) but time is shown in this format
but i want show date and time in this format(23/4/2016 5:09 AM)
in my chat Application and
i am saving this datetime in my database as
 @Html.HiddenFor(model => model.datetime, new { @Value = DateTime.Now })

A: You can create the extension method for label control to display required date time format.
public static class HelperMethods
{
     public static HtmlString MyDateTime(this HtmlHelper htmlHelper, DateTime date)
     {
        return LabelExtensions.Label(htmlHelper, "LblDate", date.ToString("dd/MM/yyyy h:mm tt"));
     }
}

Use like below in .cshtml pages
@Html.MyDateTime(DateTime.Now)

A: Try this :
this will work if datetime is not nullable.
@Html.Label( msg[i].datetime.ToString("dd/MM/yyyy h:mm tt"))

A: There are many ways to accomplish this. The easiest way for me is to provide the string formatter in the view. Below is the the output with the string formatter:
23/4/2016 5:09 AM (month with no leading zero - like you specified)
@Html.Label(msg[i].datetime.ToString("dd/M/yyyy h:mm tt"))

23/04/2016 5:09 AM (month with a leading zero)
@Html.Label(msg[i].datetime.ToString("dd/MM/yyyy h:mm tt"))

If you need more samples check out this page:
http://www.csharp-examples.net/string-format-datetime/

A: try something like this:
@Html.Label(string.Format("{0:dd/MM/yyyy hh:mm:ss}",msg[i].datetime))
Hope it will help u ;)


text:
Q: Possible bug with pathlib.touch. Why does this raise FileNotFoundError? I have no way to explain the following exception in ipython. Why do the first two calls to touch succeed but the third fails?
from pathlib import Path
log_filename = Path('/mnt/c/Users/Michael/OneDrive/PycharmProjects/beta_numbers/logs/perron_numbers_log0.txt')
log_filename.touch() # success
log_filename = Path('/mnt/c/Users/Michael/OneDrive/PycharmProjects/beta_numbers/logs/perron_numbers_log_.txt')
log_filename.touch() # success
log_filename = Path('/mnt/c/Users/Michael/OneDrive/PycharmProjects/beta_numbers/logs/perron_numbers_log_0.txt')
log_filename.touch()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.10/pathlib.py", line 1166, in touch
    self._accessor.touch(self, mode, exist_ok)
  File "/usr/lib/python3.10/pathlib.py", line 331, in touch
    fd = os.open(path, flags, mode)
FileNotFoundError: [Errno 2] No such file or directory: '/mnt/c/Users/Michael/OneDrive/PycharmProjects/beta_numbers/logs/perron_numbers_log_0.txt'

Contents of /mnt/c/Users/Michael/OneDrive/PycharmProjects/beta_numbers/logs prior to the first touch:

*

*-3_-1_-7.log

*-7_-29_-43.log

*-8_-3_-17.log

*-9_-35_-51.log

*analyze.log

*find_close_orbit.log

*test_log.txt

*testy.log

*update_legacy_data.log

Technical details: I am using the SageMath 9.5 virtual environment through WSL2 on a Windows 10 device. Python version: 3.10.4.


text:
Q: How to get the closest match among three numbers I have a list :
[(1, 49, 47), (11, 44, 6), (24, 16, 31), (11, 29, 47), (41, 14, 24), (40, 29, 1), (32, 49, 44), (41, 14, 14), (24, 21, 49), (19, 24, 6)]

And a tuple (7,2,3) I need to choose a value from this list such that every element in the tuple should be less than or equal to the new value selected according to their positions, for example, if I select (19, 24, 6), the condition is true as
7 <= 19
2 <= 24
3 <= 6

How can I select the new tuple such that the individual values are minimum.
If I assume the numbers have a higher weightage towards left, I can sort them based on first element, then the second...
But is there are better way to do this? if the numbers did not have any weightage according to their position?

A: You could use all and a nested comprehension:
data = [(1, 49, 47), (11, 44, 6), (24, 16, 31), (11, 29, 47), (41, 14, 24), (40, 29, 1), (32, 49, 44), (41, 14, 14), (24, 21, 49), (19, 24, 6)]
find = 7,2,3

result = [t for t in data if all(x <= y for x, y in zip(find, t))]

[(11, 44, 6), (24, 16, 31), (11, 29, 47), (41, 14, 24), (32, 49, 44), (41, 14, 14), (24, 21, 49), (19, 24, 6)]

If you want the first one that satisfies the condition, then you can use next
result = next(t for t in data if all(x <= y for x, y in zip(find, t)))
# use random.choice instead to get a random one instead of the first

(11, 44, 6)


text: Q: Getting cursor position outside JS event? I want to get cursor position relative to the window, but not inside the JS event. Something like event.clientX and event.clientY but not for event, for the window itself.


text:
Q: Controlling a countdown from another Thread I'd like to implement a counter in my JavaFX application. The behavior is simply controlled via a Button:

*

*When the user clicks on the button first, then the countdown starts to countdown 10, 9, 8, ..., 0

*When the user clicks on the button during the countdown, the countdown should canceled

*After 2. the user should be able to run the countdown again starting by 10

During the countdown, some heavy math computing is processed (on my application audio analysing).
Can you please look at my source code, if I doing it in the right way? In particular should I do the Platform.runLater stuff on the CountdownController or in the CountdownView and can I use a simple Java Thread or should I use the JavaFX Service/Task classes? Any suggestions are welcome.
The application is divided into 3 components:

*

*CountdownTest: creates the Stage and start JavaFX)

*CountdownView: singleton, contains a simple Button, passes button events to CountdownController

*CountdownController: singleton, starts a new Thread. Within the Thread the countdown is performed, the CountdownView is updatet to show the new countdown state and some math stuff is processed.

CountdownTest.java
package org.example;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class CountdownTest extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        final Group root = new Group();
        final Scene scene = new Scene(root);
        root.getChildren().setAll(CountdownView.getInstance());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    @Override
    public void stop() throws Exception {
        super.stop();
        CountdownController.getInstance().stop();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

CountdownView.java
package org.example;

import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseEvent;

public final class CountdownView extends Group {
    private static final CountdownView instance = new CountdownView();

    private Button start;

    private CountdownView() {
        start = new Button("Start");
        start.setTooltip(new Tooltip("click to start countdown"));
        start.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                CountdownController.getInstance().onStartClick();
            }
        });

        this.getChildren().setAll(start);
    }

    public void startCountdown() {
        System.out.println("startCountdown");
        start.setTooltip(new Tooltip("click to stop countdown"));
    }

    public void setCountdown(final int countdown) {
        System.out.println("setCountdown " + countdown);
        start.setText(String.valueOf(countdown));
    }

    public void reset() {
        System.out.println("reset");
        start.setText("Start");
        start.setTooltip(new Tooltip("click to start countdown"));
    }

    public static CountdownView getInstance() {
        return instance;
    }
}

CountdownController.java
package org.example;

import javafx.application.Platform;

public final class CountdownController {
    private static final CountdownController instance = new CountdownController();

    private Thread countdownThread;
    private volatile boolean running = false;

    public void onStartClick() {
        if (!running) {
            countdownThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    running = true;
                    int countdown = 10;
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            CountdownView.getInstance().startCountdown();
                            CountdownView.getInstance().setCountdown(10);
                        }
                    });
                    final long start = System.currentTimeMillis();
                    int lastCountdown = countdown;
                    while (!Thread.interrupted() && countdown > 0) {
                        countdown = (int) (10 - (System.currentTimeMillis() - start) / 1000);
                        if (countdown != lastCountdown) {
                            lastCountdown = countdown;
                            final int currentCountdown = countdown;
                            Platform.runLater(new Runnable() {
                                @Override
                                public void run() {
                                    CountdownView.getInstance().setCountdown(
                                            currentCountdown);
                                }
                            });
                        }

                        // Do some heavy computing stuff
                        for (int i = 0; i < 10000000; i++) {
                            Math.sin(Math.random());
                        }
                    }
                    running = false;
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            CountdownView.getInstance().reset();
                        }
                    });
                }
            });
            countdownThread.start();
        } else {
            countdownThread.interrupt();
        }
    }

    public void stop() {
        if (countdownThread != null) {
            System.out.println("stop");
            countdownThread.interrupt();
        }
    }

    public static CountdownController getInstance() {
        return instance;
    }
}

A: Don't over-sweat it. The task and service classes are just some utilities built over executors, if you don't need what they have to offer then it's just extra work.
I think you are correct in using the controller to decide which thread things should be run on, your view has enough to do routing messages between the components and the controller.