text:
Q: Unable to download Django 2.0.7 in windows 10 DISCLAIMER - I am new to the world of Django and Python. If the question sounds stupid, please bear with me.
OS - Windows 10
Python Version Installed - 3.7
In the windows command prompt, I am trying the following command to download django on my system.
pip install django
pip3 install django
Collecting django
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/
Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/
Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/
Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/
Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/
Could not find a version that satisfies the requirement django (from versions: )
No matching distribution found for django
If anybody could help me out or show some direction that would be great. Thanks in advance.
DISCLAIMER 2 :- This is an office environment and not my personal system so there should be restrictions on the firewall and other such good stuffs.

A: You can try downloading Django unofficial binaries form https://www.lfd.uci.edu/~gohlke/pythonlibs/ (use ctrl + F to find the package)
and install using
pip install "path to downloaded wheel file"

Edit: Offline installation of Django worked with the OP as he did not like to install the unofficial binaries.

*

*Downloaded pytz from https://pypi.org/project/pytz/#files

*And then downloaded Django from https://pypi.org/project/Django/#files

*Installed wheel files of pytz first and Django next using pip.

A: This is because your internet proxy is blocking it. So download the installable(.whl,tz) from the server and copy to your local and install it with
pip install <downloaded file name>


text:
Q: AdMob - handle initialization failures on Unity I'm wondering which is the right way to handle the cases where admob initialization fails.
I'm specifically referring to the cases where we call:
MobileAds.Initialize(HandleInitCompleteAction);

And in the handler we obtain "NotReady".
private void HandleInitCompleteAction(InitializationStatus initstatus)
    {
        foreach (AdapterStatus s in initstatus.getAdapterStatusMap().Values)
        {
             if (s.InitializationState == AdapterState.NotReady)
            {  // WHAT SHOULD WE DO HERE??? any best practise to try again?

Should we retry to initialize the system? Are there any example of code to handle this situation?
In general it should be nice to have a message from Admob that tells us why the initialization is failing :/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Checking Time to allow form filling in PHP (and javascript) For a website, we have a form where a client enters in their ID number that sends them to a new page that allows them to make a request for our services.
We want to change it so that clients can only request our services from Tuesday-Friday from 12pm - 4pm. If they try to enter their id number during a time outside of Tuesday-Friday from 12pm - 4pm, it will tell them they cannot request our services.
What I want to do is that if the user accesses the page during times when they cannot make a request, an alert box (through javascript) will pop up telling them that. I also want to code something so that if they try to progres forward (clicking the create request button), they will not (though php).
I'm not sure how to check these times with PHP and Javascript in order to accomplish this. If anyone has any insight in how to do this, that would be fantastic. Thanks!

A: This should work:
<?PHP
$dayOfWeek = date("w");
$currentHour = date("G");

if ($dayOfWeek >= 2 && $dayOfWeek <= 5 && $currentHour >= 12 && $currentHour <= 16) {
  // Show Form
}
else {
    ?>
    <script>alert('Form only available Tuesday - Friday, 12:00pm to 4:00pm');</script>
    <?PHP
}
?>

For more information on PHP's date function, see: http://us1.php.net/manual/en/function.date.php
"G" = 24 hour format without leading 0's
"w" = Day of week, 0 = Sunday, 6 = Saturday


text:
Q: cURL error 60: SSL certificate problem: unable to get local issuer certificate i installed new wamp server 3.1.3 and php version 7.0.29 is selected
i have added this code in php.ini file
curl.cainfo ="C:/wamp64/bin/php/cacert.pem"

still getting 'cURL error 60: SSL certificate problem: unable to get local issuer certificate'


text:
Q: Git changes disappear when saving the file When I want to Stage my changes on my branch, I click the plus sign (Stage) in Visual Studio 2019's Git Changes panel on the right side of the changed file. Usually after that the files goes in the staged section and after writing a commit message I click commit and it's done.
Git Changes Panel in Visual Studio 2019
But after click the plus sign the vs asks me if I want to save the changes of the file and if I click 'save' the file just disappears from the Changes section.
Without staging and committing and right after it's visible in the development branch. Without even making a Pull request.
MSV Asks If I Want To Save Instead of Staging
What do I miss?
I don't really know what I can try. I have changed branches, I have deleted and created new branch.
It feels like I messed up some sort of settings. I have no idea honestly.


text:
Q: Why cant i do 48 hours? Im trying to make my label count down 42 hours. This is my code
    var end = DateTime.Parse("21:00");
        var now = DateTime.Now;      // Could also be some other point in time
        TimeSpan timeLeft = end - now;
        label1.Text = "" + timeLeft;

A: Your end variable is assigned by parsing a string which only contains the hour and minute. According to the docs:

A string with a time but no date component. The method assumes the
current date unless you call the Parse(String, IFormatProvider,
DateTimeStyles) overload and include
DateTimeStyles.NoCurrentDateDefault in the styles argument, in which
case the method assumes a date of January 1, 0001.

So 21:00 is converted to 9 PM on the current date of your local computer's timezone.
Any time on the current date can not (by definition of a day) exceed 23:59 from "Now". If you are newing up a date, you can pass in the full DateTime in the constructor, either as individual values or as an ISO8601 string. For example:
var a = new DateTime(2020, 8, 20, 9, 0, 0);
var b = new DateTime("2020-08-20 09:00:00");

The second thing that I will throw out there, is that you (almost certainly) should not be calculating the difference based on the local time. Even if you are fortunate enough to be able to assume the same timezone applies to both, this (like a lot of other DateTime math) will give you the wrong answer if you cross a Daylight Savings boundary. Rather, convert both start and end to UTC and do the subtraction with UTC.
Finally, you probably want to check out the docs on TimeSpan.ToString() to make sure your label text renders the timespan the way you are hoping. (It isn't going to show "48" by default even if you did have the right dates).


text:
Q: How to "push" to new view controller after successful login StackMob I'm using stack mob as back-end provider and I'm trying to get my login screen to work.
After a successful login I want to move to a new UIViewController. It seems simple enough but I'm having issues.
I thought I could do this:
MyViewController* viewController = [[MyViewController alloc] init];

[self.navigationController pushViewController:viewController animated:YES];

Inside of the onSuccess:
- (IBAction)login:(id)sender {

[self.client loginWithUsername:self.usernameField.text
             password:self.passwordField.text
             onSuccess:^(NSDictionary *results) {

NSLog(@"Login Success %@",results);

Is there a better way to do this? Please help!

A: What you posted is correct and it's the best way to do it.
If for some reason the view controller is not pushed correctly, it's probably because you are not pushing the new view controller on the right navigation controller stack.


text:
Q: How to update Ruby version in Window? I am trying to install an Amazon Web service gem into my project (I use window and Aptana RadRails) but it asked me to update current Ruby version (1.8.5) to 1.8.7.
I use InstantRails for Window platform. So could you tell me how can I upgrade my Ruby to new version?
Do I need to install new InstantRails? or Can I update with Ruby Gem? or may be there is your alternative idea for this activity. :)
Thank you.

A: Ruby-lang.org Downloads The 1.8.7 binary is right there.

A: Even better than the builds on ruby-lang.org is the preview versions of the Ruby Installer built with mingw which allows compiling of gems without Visual C++ 6.0.

*

*http://rubyinstaller.org/downloads/

*Tutorials


text:
Q: NumberFormatException for input String, confused as to why? I made a method within a class that is supposed to parse a file with the format: name, xxx-xxx-xxxx
for every line. I'm trying to grab the phone number and put every digit into an array of ints and return that array. Here is my code.
This is the line that causes the error---
theIntNumber=Integer.parseInt(justAnotherString);

If I had: Nicholas James, 912-345-6789
then....
justAnotherString = "9123456789" and it throws an error when trying to parse that string for an int. I'm confused as to why this is happening, shouldn't it parse the int from this string?
Thank you for any answers.
public int[] getPhoneNumberArray() throws FileNotFoundException
{
    Scanner scan = new Scanner(file);
    while(scan.hasNextLine())
    {
        String thePhoneNumber = "";
        String justAnotherString = "";
        int theIntNumber=0;
        String line = scan.nextLine();
        Scanner parser = new Scanner(line);
        parser.useDelimiter(",");
        parser.next();
        parser.useDelimiter(" ");
        parser.next();
        thePhoneNumber = parser.next();
        Scanner lol = new Scanner(thePhoneNumber);
        lol.useDelimiter("-");
        justAnotherString += lol.next();
        justAnotherString += lol.next();
        justAnotherString += lol.next();
        theIntNumber=Integer.parseInt(justAnotherString);

        for(int i=10;i>0;i--)
        {
            phoneNumberArray[i-1]=theIntNumber%10;
        }
    }
    for(int a=0;a<10;a++)
    {
        System.out.println("Phone Number: ");
    }
    return phoneNumberArray;
}

EDIT: Previous number was 123-456-7890. The number I had before was larger than the 2.1 billion that java can handle. 987-654-3210 is a better example.
This is the error I'm getting.
Exception in thread "main" java.lang.NumberFormatException: For input string: "9876543210"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at exam2.Contact.getPhoneNumberArray(Contact.java:71)
    at exam2.ExamTwoInput.main(ExamTwoInput.java:83)

A: Your code is working here, the only issue I see is that your formula for converting the digits of the int number to an array appears flawed. You don't need the int anyway, since you have it as justAnotherString. Basically, you could use Character.digit(char, int) like -
int[] phoneNumberArray = new int[justAnotherString.length()];
for (int i = 0; i < justAnotherString.length(); i++) {
    phoneNumberArray[i] = Character.digit(justAnotherString.charAt(i), 10);
}
System.out.println(Arrays.toString(phoneNumberArray));

Of course, you could also parse the telephone number with something like
String line = "Nicholas James, 123-456-7890";
// get everything after the last space.
String phone = line.substring(line.lastIndexOf(' ') + 1);
phone = phone.replace("-", ""); // remove the '-' symbols
int[] phoneNumberArray = new int[phone.length()];
for (int i = 0; i < phone.length(); i++) {
    phoneNumberArray[i] = Character.digit(phone.charAt(i), 10);
}
System.out.println(Arrays.toString(phoneNumberArray));

which has the advantage that it will work with (and without) dashes.

A: As an aside, you can't store a telephone number in an integer. It loses both leading zeroes, and the plus sign.
For instance, imagine you were given the number for the British Prime Minister, +44 20 7925 0918. The plus sign there indicates that the call is an international call. It would be replaced by 011 in the North American Numbering Plan, or by 00 in the European Telephony Numbering Space. How would you represent that telephone number as an int?

A: I know this question is so old, but till now not have accepted answer.
as your note:

EDIT: Previous number was 123-456-7890. The number I had before was larger than the 2.1 billion that java can handle. 987-654-3210 is a better example.

so, please use Long.valueOf(str) instead of Integer.parseInt(str) or Integer.valueOf(str)
hope this help u all :)


text:
Q: SelectList rendering with multiple = "multiple" when I don't want it to I am trying to create a simple SelectList that renders as a dropdown for use in a Create form generated with RazorPages.  For some reason, the SelectList renders with multiple="multiple" which results in all the options being shown in a frame with a scrollbar on the side instead of a dropdown.  I believe the issue lies with my controller and the fact that I am trying to set both the "Text" and "Value" attributes of the SelectListItems with an anonymous type, as I have achieved the desired result when not setting those attributes.
A lot of this is very new to me, so if anyone has any general advice with regard to my code, I would appreciate it.
Here is my view model:
public class CreateFileViewModel
    {
        public SelectList EnrolleeId { get; set; }
        public SelectList GroupId { get; set; }

        [DataType(DataType.Date)]
        public DateTime StartDate { get; set; }

        public string Status { get; set; }
    }

Here is my controller:
public IActionResult TestCreate()
        {
            //query items for SelectLists
            var users = from u in _context.Users
                        orderby u.LastName
                        select u;

            var groups = from g in _context.Group
                         orderby g.Name
                         select g;

            // Loop through queries above and convert to collections of SelectListItems
            var enrolleeSelectListItems = from u in users
                                        select new SelectListItem()
                                        {
                                            Value = u.Id.ToString(),
                                            Text = u.LastName + ", " + u.FirstName + " " + u.MiddleName
                                        };

            var groupSelectListItems = from g in groups
                                         select new SelectListItem()
                                         {
                                             Value = g.ID.ToString(),
                                             Text = g.Name
                                         };

            //convert SelectListItem collections into SelectLists within view
            var cfvm = new Models.TestModels.CreateFileViewModel();
            cfvm.EnrolleeId = new SelectList(enrolleeSelectListItems, "Value", "Text");
            cfvm.GroupId = new SelectList(groupSelectListItems, "Value", "Text");

            return View(cfvm);
        }

This is the relevant portion of my view:

                <select asp-for="EnrolleeId" asp-items="Model.EnrolleeId">
                    <option value="">Select</option>
                </select>

and here is how it renders in the browser:
<select id="EnrolleeId" multiple="multiple" name="EnrolleeId" aria-invalid="false" class="valid">
                    <option value="">Select</option>
                    <option value="3e60fabd-6901-45a1-ae2a-5056d77f415c"></option>
                    <option value="40ce8b6e-62a5-4c3c-808b-90e36d633ec0"></option>
                    <option value="c0c49df2-da52-4a01-9a8a-47bab6f5496d"></option>
</select>

A: Because the property you used for asp-for (EnrolleeId) is collection type. SelectList implements IEnumerable
Ideally you should have 2 properties, one for the collection of items needed to build the list of options and one for the selected option value
public class CreateFileViewModel
{
    public int SelectedEnrolleId {set;get;}  // This new one
    public SelectList EnrolleeId { get; set; }

    public SelectList GroupId { get; set; }
    [DataType(DataType.Date)]
    public DateTime StartDate { get; set; }
    public string Status { get; set; }
}

And in the view
<select asp-for="SelectedEnrolleId" asp-items="Model.EnrolleeId">
    <option value="">Select</option>
</select>

This will render the select element with name and id attribute values set to SelectedEnrolleId. So when you submit the form , that is where you should read it from.


text:
Q: Sparql operation between datetime in select I have to write a query that return an intensity value and the associated duration. Duration is calculated with the difference between two datetime values that are stored in the rdf ontology:

*

*startDate

*stopDate

I write:
SELECT ?intensityVal ?startVal ?stopVal ?duration ( (?stopVal - ?startVal) as ?duration)
     WHERE {
              ?event rrel:existDuringInterval ?interval .

              ?interval time:hasBeginning ?start .
              ?start time:inXSDDateTime ?startVal .

              ?interval time:hasEnd ?stop .
              ?stop time:inXSDDateTime ?stopVal .

              ?event rrel:hasIntensity ?intensity .
              ?intensity rrel:hasMIValue ?intensityVal .

}

After this result I have to count and group by ?duration.
The problem is that ?duration results is blank and I think that I am doing wrong the ?duration calculation.
See:


text:
Q: Variable de una comparación de un array de objetos me retorna datos undefined Tengo una función donde comparo dos array de objetos, el detalle es que en consola checando el resultado me imprime dos veces la primera bien y ya luego me imprime el mismo array de objetos pero como los campos undefined. No sé por qué me lo imprime así.
    jsonodsunicosparametros = [
      {id: undefined, id_ods_meta: 3, activo: true}
      {id: undefined, id_ods_meta: 4, activo: true}
    ]

    jsonods_modificar = [
      {id: 6, id_ods_meta: 1, activo: true}
      {id: 7, id_ods_meta: 2, activo: true}
    ]

    const mergeods = (odsA, odsB) => odsA.map((pA) => ({
         ...pA,
         activo: odsB.some((pB) => pB.id_ods_meta === pA.id_ods_meta ),
    }));
    const mergedods = mergeods(jsonodsunicosparametros, jsonods_modificar);
    console.log(mergedods)

y me lo imprime en consola así. Quiero que me guarde el primer resultado, pero al final me guarda el resultado del último impresión de consola:
    //primera impresion en consola
    {id: 6, id_ods_meta: 1, activo: false}
    {id: 7, id_ods_meta: 2, activo: false}

    //segunda impresion en consola
    {id: undefined, id_ods_meta: undefined, activo: false}
    {id: undefined, id_ods_meta: undefined, activo: false}

A: Ya lo resolví, lo tenía dentro de un for, entonces como era el número de registros que selecciona el usuario, si en este caso seleccionaba dos, pues dos veces me iteraba mi función, si elegía n cantidad n cantidad de veces se iba a ejecutar la función.


text:
Q: mysql collation is fine for phpmyadmin but not for sql i am having a database where i store both greek and english strings using collations : "greek_general_ci" and "utf8_general_ci" from phpmyadmin everything works fine !
but using mysql comand from terminal, or mysql_query from php i get some "?", do you have any idea why this happends ?
in the meanwhile everything is fine from phpmyadmin !
i have to note that i need sometimes to use english , so a collation that supports only greek may not be much helpful, but i believe that it is not matter of the collation
also i have to say that i use this in my html to display greek characters :
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

thank you

A: First of all: You are barking up the wrong tree. Your problem is not collation (or you have not yet found out so), but encoding.

*

*in the tables

*on your connection

I recommend you start debugging by putting a query like SET NAMES 'UTF8' at the start of your PHP scripts. Quite likely, this will make the immediate problem "go away", giving you a foot in the door for a more permanent fix.


text:
Q: Trying to Parse XML String from HTTP Request in PHP As a preface:  I cannot imagine this has not been asked before, but I have failed miserably at finding a solution...and I would think there is a simple solution and I am simply doing something completely wrong.
I have a simple index.php file that looks like so:
<?php
$data = file_get_contents('php://input');
echo "DATA : " . $data;

$xml = new SimpleXMLElement($data, 0, true);
echo "XML : " . $xml;

$RoundTrip = (string) $xml->RoundTrip;
$TransactionId = (string) $xml->TransactionId;

?>

The echo "DATA" shows:
<?xml version="1.0" encoding="utf-8"?><msg><head><Client>Test</Client><RoutingArea>811</RoutingArea><Source>MySRC</Source><Destination>BSRC</Destination><Version>2.27</Version><RoundTrip>ID=001088129291102</RoundTrip><TransactionId>12652b05-ceb9-11eb-a091-00505687f2ee</TransactionId><ServerId>03</ServerId></head><body><POdated>

...and the SimpleXMLElement is throwing an error:
PHP Warning:  SimpleXMLElement::__construct(): I/O warning : failed to load external entity "<?xml version="1.0" encoding="utf-8"?><msg><head

As if the string is being read as URLencoded...but the initial output is not URLencoded.
My Goal is to: receive the XML doc from the request as a string and be able to parse it.

A: It expects a file-path or URL, not file-content (because the 3rd parameter is true, while the default is false).
Try removing the 3rd parameter like:
$xml = new SimpleXMLElement($data, 0);

But if that does not work you still have the option:
$xml = simplexml_load_string($data);

// do something with $xml

A: The third parameter is $dataIsURL and you are specifying true.
https://www.php.net/manual/en/simplexmlelement.construct.php

dataIsURL
By default, dataIsURL is false. Use true to specify that data is a path or URL to an XML document instead of string data.

So, either change to false:
$xml = new SimpleXMLElement($tag, 0, false);

Or remove that third parameter:
$xml = new SimpleXMLElement($tag, 0);

Since you are providing a string and not a URL.


text:
Q: How to authenticate a user from an external Windows Domain (Active Directory) I have a service (AcmeService) running on a domain (ACME.COM) and a user running in another domain (DISNEY.COM).
mickey@disney.com wants to authenticate with the AcmeService. The service knows about the DISNEY.COM domain and it imported all the user in its local user database with LDAP by using a known credential of DISNEY.COM.
If mickey sends his fully qualified username/password, AcmeService can authenticate him using LDAP by connecting directly to the DISNEY.COM domain controller (which he already knows).
scrooge@disney.com wants to authenticate too with AcmeService, but wants to authenticate with integrated security because he doesn't trust AcmeService enough to give away his password. (In my scenario it is using .Net NegotiateStream which is a wrapper around SSPI)
My understanding of this problem is that AcmeService cannot authenticate with integrated security a user that is not part of his domain (ACME.COM).
I think the general solution would be to create an outgoing trust relationship between ACME.COM and DISNEY.COM, but it is not possible in my scenario.
Is there a solution to allow AcmeService to authenticate a user with SSPI if that user is in an external domain and there is no defined trust relationship? It is ok if the solution works only on the AcmeService machine.
I might be mistaken, but I am under the impression that it would be possible to do such a thing with an external MIT Kerberos by using ksetup /addkdc.
Any idea?
Thanks
UPDATE
The communication between the client and AcmeService is already secured with TLS (without mutual authentication). After the connection is complete, the client knows he's talking with the real AcmeService (thanks to TLS), but he now needs to authenticate his identity to the AcmeService using his DISNEY.COM credentials, a client certificate here is not an option, the AcmeService only knows about ActiveDirectory accounts that it previously imported.
NTLM (v2) would be good enough for my scenario, but I don't see why Kerberos would not be possible. AcmeService has a DISNEY.COM account (acmeuser@disney.com) it can use to mutually authenticate with Kerberos.
I think the problem is that while trying to authenticate a disney.com user with SSPI, AcmeService is unable to locate the domain controller automatically for the DISNEY.COM domain. The AcmeService machine needs to know that the DISNEY.COM controller can be located at "dc.disney.com".
Here is the results of dcdiag and nltest ran on the AcmeService machine:
dcdiag /s:dc.disney.com /u:disney.com\acmeuser /p:XXXX /test:LocatorCheck
   Running enterprise tests on : disney.com
      Starting test: LocatorCheck
         Warning: DcGetDcName(GC_SERVER_REQUIRED) call failed, error 1722
         A Global Catalog Server could not be located - All GC's are down.
         Warning: DcGetDcName(PDC_REQUIRED) call failed, error 1722
         A Primary Domain Controller could not be located.
         The server holding the PDC role is down.
         Warning: DcGetDcName(TIME_SERVER) call failed, error 1722
         A Time Server could not be located.
         The server holding the PDC role is down.
         Warning: DcGetDcName(GOOD_TIME_SERVER_PREFERRED) call failed, error 1722
         A Good Time Server could not be located.
         Warning: DcGetDcName(KDC_REQUIRED) call failed, error 1722
         A KDC could not be located - All the KDCs are down.
         ......................... disney.com failed test LocatorCheck

nltest /dsgetdc:disney.com
Getting DC name failed: Status = 1355 0x54b ERROR_NO_SUCH_DOMAIN

What I need is a magic command like "register-domain /domain:DISNEY.COM /controller:dc.disney.com", as I said previously, it's ok if only the AcmeService is able to authenticate DISNEY.COM users, the solution doesn't need to work with everyone in the ACME.COM domain.

A:
Is there a solution to allow AcmeService to authenticate a user with SSPI if that user is in an external domain and there is no defined trust relationship?

No.
If you are constrained to working with the .NET NegotiateStream class, then you will see in the MSDN documentation for the NegotiateStream class, [MS-NNS]:

The .NET NegotiateStream Protocol uses SPNEGO (which selects between Kerberos
  and NTLM) to determine the underlying security protocol to use.

So your choices are NTLM and Kerberos.

scrooge@disney.com wants to authenticate too with AcmeService, but wants to authenticate with integrated security because he doesn't trust AcmeService enough to give away [his] password.

Well then NTLM is out. NTLM v1, v2, and v2 with Session Security all rely on weak hashing algorithms, and furthermore the hashes of the password are essentially password-equivalent, so I agree with you that using NTLM to authenticate to a service is to give one's password away to that service.
So now you're left only with Kerberos.  And Kerberos as it's implemented by Active Directory is not going to authenticate credentials for an untrusted domain.
So now you have no choices left.

I think the general solution would be to create an outgoing trust relationship between ACME.COM and DISNEY.COM, but it is not possible in my scenario.

You are right that creating a trust would allow one Kerberos realm to trust the authentication mechanism of another Kerberos realm, but since you cannot create a trust, then you are SOL.
When you want to provide strong, mutual authentication between a client and a server and you cannot use Kerberos, then you use PKI, digital certificates, TLS.
I would normally suggest that you explore AD Federation Services, but chances are if you cannot create a traditional AD trust relationship for whatever reason, then you won't be able to create a Federation trust either.
So my suggestion is client certificates. (Schannel)


text:
Q: Lookahead regex in Ruby returns `nil` on irb I have input:
s = "<tag1 value = \"HelloWorld\" val = \"1234\">"

I want to fetch 'HelloWorld' and '1234'.
I am using this regex expression
(?<=\")+[a-zA-Z0-9]*+(?=\\)

On rubular, it gives the expected result, but on irb, it returns nil:
s.scan(/(?<=\")+[a-zA-Z0-9]*+(?=\\)/) # => []

Why this is happening can anybody explain ? what I am missing

A: s = "<tag1 value = \"HelloWorld\" val = \"1234\">"

the string value is:
<tag1 value = "HelloWorld" val = "1234">

It can be easily checked by executing e. g. puts s. You see the backslashes there because the string in ruby might be declared using double quotes and in this case the double quotes inside string are to be escaped with backslashes. Other ways to declare the same string in ruby are:
s = '<tag1 value = "HelloWorld" val = "1234">'
s = %|<tag1 value = "HelloWorld" val = "1234">|
s = <<STR
<tag1 value = "HelloWorld" val = "1234">
STR

neither requires escaping double quotes. If you have copied the string as it was displayed in IRB to rubular, with escaping backslashes, you've matched another string.
That said, since there are no backslashes in the original string, nothing was matched in ruby. There are other glitches with the regexp you've used.
Here is the most careful version of the regexp:
s.scan /(?<=")\w+(?=")/
#⇒ ["HelloWorld", "1234"]

A: I've changed the regex slightly to wrap around the last \" instead. I suspect it has to do with \ being the Ruby escape character.
> "<tag1 value = \"HelloWorld\" val = \"1234\">".scan(/(?<=\")+[a-zA-Z0-9]*+(?=\")/)
#=> ["HelloWorld", "1234"]


text:
Q: ComboxBox prompting a new form I am making a Window Forms in which I have a combo box where I have inputted all the "search results" I need (attached below) so I was wondering as I have several different inputs(Headache,Weak Immunity and etc.), if it is possible for the picture boxes in my 2nd form to only display pictures relevant to the text in the combo box (Lets say Headache is in the combo box which is in DropDownList style, my 2nd form will show pictures relevant to headaches and not like weak immunity). If I cannot, please let me know what I can do. And I'm using C# in Visual Studio
The first image is my search items
The second image is my form


text:
Q: What version of SQL must be installed in another system I create database with SQL Server 2008 R2.
Now, I want execute database with C# windows Application in Other system.
What version of SQL must be installed in another system?


text:
Q: How to run node app with sublime text How would you run node app with sublime text? Like this, open the file app.js in sublime, go to menu->tools->build, and it just runs. Simple like that

A: If you want to fix the plugin's path yourself. One option is changing Nodejs.sublime-build. It's located in the packages directory of sublime:
Mac: ~/Library/Application Support/Sublime Text 2/Packages/Nodejs/Nodejs.sublime-build

Linux: ~/.config/sublime-text-2/Packages/Nodejs/Nodejs.sublime-build

Note: On latest OS X versions the Library folder is hidden. If that's the case, from the menu select Go > Go to Folder... and type ~/Library.
Change "cmd": ["node", "$file"] to "cmd": ["/usr/local/bin/node", "$file"]

{
  "cmd": ["/usr/local/bin/node", "$file"],
  "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
  "selector": "source.js",
  "shell":true,
  "encoding": "cp1252",
  "windows":
    {
        "cmd": ["taskkill /F /IM node.exe & node", "$file"]
    },
  "linux":
    {
        "cmd": ["killall node; node", "$file"]
    }
}

Lastly, open your *.js file and press command + b. Everything should just work fine now.
Linux Users: This file is identical across all operating systems. Finding the path to Nodejs.sublime-build may require running a search. In most cases it's located in ~/.config/sublime-text-2/Packages/Nodejs/Nodejs.sublime-build

A: To run nodejs on sublime text, install node package "node dev" then create a sublime text build, the code should look like this
{
  "cmd": ["node-dev", "$file"],
  "selector" : "source.js",
  "path" : "/usr/local/bin"
}

Now to run a nodejs app, go to menu->tools->build.

A: Cmd+Shift+P , search for "Nodejs::Default File Settings" ,it will open file "Node.js.sublime-settings". you'll see:
{
  // save before running commands
  "save_first": true,
  // if present, use this command instead of plain "node"
  // e.g. "/usr/bin/node" or "C:\bin\node.exe"
  "node_command": false,
  // Same for NPM command
  "npm_command": false,

  "expert_mode": false,

  "ouput_to_new_tab": false
}

modify
"node_command": false,
to
"node_command": "/usr/local/bin/node",
if the node path is not the same with above, find it and change to yours.

A: What is going on is that you don't have the right PATH setup for your terminal.
try this command in a regular terminal:
> which node

I peronaly get this:
/usr/local/bin/node

As you can see this path is not in you environement path to add it in a regular terminal you would edit .bashrc or .bash_profile and add this line
export PATH=/usr/local/bin:$PATH

Here well you just have to look at the doc and find out that you need to modify the configuration file.

If you have a JavaScript file open, by selecting selecting Tools ->
  Build Systems -> Nodejs and then hitting Ctrl + B, you will activate
  the node build system on your file and node will try to run it. You
  may need to add a path variable to the settings object for this if
  your node executable is not found

Look at this.

A: On xubuntu, I made the build command in Nodejs.sublime-build explicity use the terminal:
"cmd": ["xfce4-terminal",  "--command", "node $file"]

A: Create a build sytem with this code:
{
   "cmd": ["node", "$file"],
   "selector" : "source.js"
}

A: First make sure node is installed properly.
Create new build system in sublime.
Tools > Build System > New Build System
It will create new file. replace the content with below comman
{
    "shell_cmd": "node $file"
}

save the file with extention .sublime-build
i.e. node.sublime-build
Now select build system in tools>build system>node (or whatever name you have set)
All set. open js file and hit ctrl+B or go Tools>build


text:
Q: Berkeley Socket Send returning 0 on successful non-blocking send I am writing a non-blocking chat server, so far the server works fine, but I can't figure out how to correct for partial sends if they happen. The send(int, char*, int); function always returns 0 on a success and -1 on a failed send. Every doc/man page I have read says it should return the number of bytes actually feed to the network buffer. I have checked to be sure that I can send to the server and recv back the data repeatedly without problem.
This is the function I use to call the send. I both tried to print the return data to the console first, then tried line breaking on the return ReturnValue; while debugging. Same result, ReturnValue is always 0 or -1;
int Connection::Transmit(string MessageToSend)
{
    // check for send attempts on a closed socket
    // return if it happens.
    if(this->Socket_Filedescriptor == -1)
        return -1;

    // Send a message to the client on the other end
    // note, the last parameter is a flag bit which
    // is used for declaring out of bound data transmissions.
    ReturnValue  = send(Socket_Filedescriptor,
                         MessageToSend.c_str(),
                         MessageToSend.length(),
                         0);

    return ReturnValue;
}

A: Why don't you try to send in a loop? For instance:
int Connection::Transmit(string MessageToSend)
{
    // check for send attempts on a closed socket
    // return if it happens.
    if(this->Socket_Filedescriptor == -1)
        return -1;

    int expected = MessageToSend.length();
    int sent     = 0;

    // Send a message to the client on the other end
    // note, the last parameter is a flag bit which
    // is used for declaring out of bound data transmissions.
    while(sent < expected) {
      ReturnValue  = send(Socket_Filedescriptor,
                         MessageToSend.c_str() + sent, // Send from correct location
                         MessageToSend.length() - sent, // Update how much remains
                         0);
      if(ReturnValue == -1)
        return -1; // Error occurred
      sent += ReturnValue;
    }

    return sent;
}

This way your code will continually try to send all the data until either an error occurs, or all data is sent successfully.


text:
Q: No wife, no pregnancy, but the son is already named
No  wife, not  her  pregnancy but  the  son's  name  is   soma  lingam (some ×)
Aalu  ledu, chulu  ledu kani  koduku  peru  matram  somalingam. (Telugu)

Some people  think  of the future  happening  without  any base  in the  present. This  idiom  is used  to  talk  about  such  people  in  a humorous context.
_It  is  not  equal to  building  castles  in the  air because  it  is  not  an  impossible  task  for  him to  marry  and  beget  a  son. He is  imagining  things  too  early.
The  idiom  is  used  to  talk  about   a  person who  talks  about  something  well  in  advance  without  any  scope  for  such  a  talk. A  married  man
may  talk  about   his/ her  son' s  being  christened but  it  is  a foolish  to  talk  about  the  name  of  a  son  well  before  his  marriage  without  having  a  wife.
Is  there  such  a   phrase  or   an idiom  in  English?

A: This is putting the cart before the horse:

to do things in the wrong order:

*

*Aren't you putting the cart before the horse by deciding what to wear for the wedding before you've even been invited to it?

A: You could call this getting ahead of yourself.

You have named your son soma lingam, but you are not married or pregnant. Aren't you getting ahead of yourself?


text:
Q: Why is not my div shrinking I could not comment on that post, that's why I posted a similar question.(I must have at least 50 reputation for that)
I wanted to know why it is not shrinking, I  understood the code exactly as this question's 1st answer was and then tried to code exactly same so that the results be same but nothing happened after scrolling my div's size remained same
Here's my entire code:

    ....

A: You forgot to add # before id.
Replace this part of your code with this:
 $(window).scroll(function(){
      if ($(document).scrollTop() > 0) {
        if ($('#header_nav').data('size') === ('big')) {
          $('#header_nav').data('size','small');
          $('#header_nav').stop().animate({
            height: '40px'
          }, 600);
        }
      }
      else{
        if ('#header_nav'.data('size') === ('small')) {
          $('#header_nav').data('size','big');
          $('#header_nav').stop().animate({
            height: '100px'
          }, 600)
        }
      }
    });

A: I think the issue is here:
if ($('#header_nav').data('size') === ('big')) {
    $('header_nav').data('size','small');
    $('header_nav').stop().animate({
        height: '40px'
    }, 600);
}

here $('header_nav').data('size','small'); doesn't have # in the selector.
So change it to:
$('#header_nav').data('size','small');

and try again.

A: Updated!!!
Remove # from this line because there are one extra # $('#header_nav').data('size','small');
And no need to add this line in else section, remove this line below
if('#header_nav').data('size') === ('small')) {      $('#header_nav').data('size','big');}

$(document).ready(function(){
 $('#header_nav').data('size', 'big');

 $(window).scroll(function(){
      if ($(document).scrollTop() > 0) {
        if ($('#header_nav').data('size') === ('big')) {
          $('#header_nav').data('size','small');
          $('#header_nav').stop().animate({
            height: '40px'
          }, 600);
        }
      }
      else{
       // Just add animate function only without any condition
        $('#header_nav').stop().animate({
            height: '100px'
          }, 600);
      }
  });
})
.container{padding-top:100px;}
  body {
    height: 500px;
    width: 100%;
    background-color: #00000;
  }

  #header_nav {
    width: 100%;
    height: 100px;
    background-color: #666;
    position: fixed;
    top: 0;
    left: 0;
  }


text:
Q: Remove grid lines(vertical and horizontal) from a handwritten scanned image I tried to remove the grid lines from the image using hough lines approach,but i am unable to generalize for all images.
My input image :input image
Output image:Output image
I want my output image to look like this:
expected output image


text:
Q: Using IsolatedStorage on a IIS server I'am a bit confused about the use of Isolated Storage on a IIS server.
I understand the goal of Isolated Storage : provides a safe place to store data with no worry about how and where is this place.
Since Isolated Storage have a by-user and by-assembly approach, I'am not too wild about using it on a IIS server where applications have almost their own identity.
I haven't really seen the interest of impersonating a web application and almost never seen impersonated web applications myself but this is my point of view.
Using Isolated Storage on a server mean (for Windows Server 2003) :

*

*Using Isolated stores in \Documents and Settings\<user>\

*Which mean \Documents and Settings\Default User\ when the application pool is owned by Local System or Network Services I guess

*Which also mean Write rights on this folder for Local System or Network Services

*Using of impersonation
Regarding a web application (logic), these ideas are confusing me... Document and Settings ? Default User ? Enable impersonation just for storage ? No control about storage on server ? Uh ?
Some points on the MSDN :

*

*Server storage. Server applications can use isolated storage to provide individual stores [...]. Because isolated storage is always segregated by user, the server must impersonate the user making the request. [...]

*Using isolated storage enables partially trusted applications to store data in a manner that is controlled by the computer's security policy.

*by default, code running from the local computer, a local network, [...] is granted the right to use isolated storage. Should I understand Network Services ? I would be surprised. That's not the case on my IIS servers (Windows 2003).
And then I'am a front of a dilema : use System.IO.Packaging (with Isolated Storage inside) on web applications or find an alternative ? Using IO.Packaging mean you must enable isolated storage ?
Am I wrong in my approach ? Did I miss something ?
I precise I don't especially want to use/enable it on a IIS server, I would like to understand if enabling it on a such environment is a good practice.
Any point of view is appreciated and an explanation about an "Isolated Storage with IIS philosophy" could be an anwser.
Thanks !

A: If you would need to use server side isolated storage for some reason, then you must impersonate the user and for that you would need to use windows integrated authentication so you get the http context's user principal populated with the requesting user.
The request thread would switch the identity to the requester user and I would assume ( haven't tested) that you would see the isolated storage under that account.
I am still not sure when would I use isolated storage on server side for an IIS app which normally in enterprise environment runs on a web farm.
It would be against best practices to store anything locally per user.
If that server goes down, then you've lost that data.


text:
Q: create request body and template API GATEWAY CDK Please tell me two things:
1. How to configure request body via sdk
2. how to configure template, for pulling pass or query param, converting to json, and then passing it to lambda
This is all in the api gateway and via cdk

A: Assume you have the following setup
    const restapi = new apigateway.RestApi(this, "myapi", {
            // detail omit
    });

    const helloWorld = new lambda.Function(this, "hello", {
       runtime: lambda.Runtime..PYTHON_3_8,
       handler: 'index.handler',
       code: Code.asset('./index.py')
    })

    restapi.root.addResource("test").addMethod("POST", new apigateway.LambdaIntegration(helloWorld))

and inside the lambda function (in python)
def handler(event, context):
  request_body = event['body']
  parameters = event[queryStringParameters]


text:
Q: Is it possible to make a loop of wire act as a longer range antenna? I have an ESP32-S3 WROOM 1U, which has an U. FL (IPEX)
connector. If I search on Google for an IPEX antenna, they are all very big and bulky. I know that wires can act as antennas but I'm not that familiar with the best approach to designing an antenna. Can I just use any wire to act as an antenna or what do I need to take into consideration? I need the antenna to reach my router from the basement.

A: If you imagine a camera for long range uses a large series of high quality lenses, you will understand better the tradeoff between beamwidth and gain or direction and range.
So a single loop , somewhat like dipole has an omnidirectional view like a wide angle lens with a very short range for the same quality. A poor example is stacking a bunch of magnifying lenses compared to a telescope but essentially they do the same tradeoff but with lower losses my optical impedance matching with low reflectance coatings and very low loss clear lenses shaped precisely for spacing and focus.
Adding more range means to focus the direction with more similar element sizes like a Yagi TV antenna. Except those often range in sizes to match a range if 1/2 wavelengths.
If the loop merely adds impedance without spacing each loop to capture more signal, then the gain is less than optimal.  A spiral helix is the best example of this, which can achieve gains well beyond 20 dB which can extend the range considerably from Friis Loss but at great expense to achieve ~  0.1% tolerances on the geometry.

A: I don't know what an "IPEX C" Connector is.
Have you thought about bringing better WiFi coverage nearer you basement?  Do you have the ability to add a WiFi access point?
You can purchase ESP32 boards with an external antenna connector:
https://www.amazon.com/gp/product/B0811KLGDD/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&th=1
You can then purchase an external antenna to connect to the ESP32 board:
https://www.amazon.com/gp/product/B00ZBJNO9O/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1


text:
Q: Afterlogic Webmail Lite custom theme / skin I would like to make a custom dark theme for a web client.
I tried everything but no matter what I changed I cannot get any changes to take effect. I found out this page in the documentation but I cannot get it to work:
https://afterlogic.com/docs/webmail-lite-8/developers-guide/creating-new-skin
Does anyone have some experience with this webmail client?

A: The recommended option for creating a new skin is to clone and rename one of the existing skins, and upon making changes to it, run gulp styles --themes YOUR_THEME_NAME command. Once this operation is performed, check static/styles/themes/YOUR_THEME_NAME and see if you get your changes reflected there. If the changes are in place, then it's probably browser cache causing it, try clearing it and see if that helps.
In fact, it's not required to deal with .less files, you can simply create a copy of an existing theme under static/styles/themes directory - but in either case, you need to make sure the new theme is listed in ThemeList section of data/settings/modules/CoreWebclient.config.json configuration file.


text:
Q: Count Consonants Before First Vowel in a String I'm creating a simple pig Latin translator. Here's what I have so far:
while True:
  phrase = input('Translate > ').lower().split()

  for word in phrase:
    if word[0] in 'aeiou': # If the first letter is a vowel
      print(word + '-way') # Add suffix 'way'
    else:
      c = # Number of consonants before the first vowel
      print (word[c:] + word[0:c] + '-ay')

How can I make c equal to the number of consonants preceding the first vowel in word as simply as possible? I'd prefer not to use functions.
EDIT: Yeah, I meant I'd prefer not to define my own functions. Sorry about that.

A: Use itertools.takewhile
 from itertools import takewhile

 c = len(list(takewhile(lambda x: x not in "aeiou", word)))

takewhile takes a predicate which is the lambda here, it will take the elements while the predicate is True so in this case as soon as we come across a vowel the method will stop and return the list of consonants up to that point and we just use the len function to check how many consonants are in the list giving us the index for c.


text:
Q: Why are Android versions older than 5.0 not vulnerable to CVE-2017-13156? I was just reading about the Janus vulnerability (CVE-2017-13156) and there is one thing I cannot understand.
The vulnerability lies in the implementation of the installation of the APK and Signature Scheme v1 (JAR signature). It allows you to craft a mallicious APK file by prepending a mallicious DEX file to a legitimate APK. The mallicious DEX file is installed instead of the DEX file of the legitimate APK. The signature (if using v1 scheme) is not broken.
The writeup in the link above mentions the vulnerable versions of Android being 5.0 and newer (the CVE record mentions 5.1.1 to 8.0, but that's not the main problem now).
So my question is:
Why is 5.0 the lowest vulnerable version of Android? Does Android older than 5.0 use a different signature scheme? Or is there a difference in the way APKs are being installed on Android 5.0 and newer and Android lower than 5.0?

A: ART, the Android Runtime replaced the Dalvik VM since Android 5.0.
And obviously, an ART exploit does not apply to the Dalvik VM.


text:
Q: Insufficient Privileges in Email Body pane on contact Activity Email My client has a weird bug where they can see the whole tab for Email in the Activity Tab on the Contact page, but the rich text editor for entering the body of the email shows an Insufficient Privileges error.

A: @hgolov I'm running into this exact issue. Here are a few additional things that I've noticed, which may/may not be relevant:

*

*As admin user, the user is not able to edit the HTML body portion of an email template record, when going straight to the email template record.

*This is is a trial org (contract signed, awaiting end of trial period).

Privileges granted to profile including "Edit HTML Templates", "Send Email through External Email Service", "Manage Public Lightning Email Templates", "Send Email", "Mass Email", "Create Folders for Lightning Email Templates".
If you have any luck figuring this one out, I'd be very interested to hear what you discover.


text:
Q: Adding environment variable from command prompt / batch file I am trying to add a environment variable (System) in my batch file.
The below command says ERROR: Invalid syntax. Can some one help.
For me it looks good.
reg add HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment /v ToDelete /t REG_SZ /d "192.168.00.00"

Thanks

A: I think you need to quote the registry key as it has spaces
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v ToDelete /t REG_SZ /d "192.168.00.00"

A: SetX.exe is probably the easiest way to do this in a batch file.  It also feels a bit safer than directly writing to the Registry just to add an Environment Variable.
SetX syntax page
For your example the variable's:

*

*Space = System

*Name  = ToDelete

*Value = 192.168.00.00

The SetX command line would be:
SetX.exe ToDelete "192.168.00.00" /m

Note that this CMD was executed as an administrator.  Depending on your systems setup SetX may not run under your users permissions.

Another thing to remember about SetX is that the update does not happen to the Environment in the current CMD window.  you have to either also run a Set for the variable (temporary) or close and reopen CMD to see the update.
In most cases (in scripts) it means running both commands. Note below this is a standard CMD session (has been closed and reopened).


text:
Q: Quartz´s configuration with Oracle How to configure the Quartz's configuration file to work with Oracle. I'm using Quartz.NET 2.0, Oracle 10G and Visual Studio 2010.
I have implemented Quartz 1.0.3 in a project. I have to update the Quartz project to version 2.0, in order to do that i created a Job in a test project and added references to the Quartz's Dlls. The weird is that the Job is working well without install the Quartz service... how is this possible???

A: *

*Run Oracle table creation scripts contained in quartz.net package. I
think the script is under Quartz\database\tables\tables_oracle.sql

*Modify Quartz.Config
quartz.jobStore.tablePrefix = your table prefix , I think default is QRTZ_

quartz.jobStore.dataSource = myDS

quartz.dataSource.myDS.connectionString = your connection string

quartz.dataSource.myDS.provider = OracleClient-20

I think you will be good to go, if you are running quartz as embedded you can number 2 in ypur code.
For more see this tutorial

A: The Oracle database has many options for running scheduled jobs. So maybe you do not really need Quartz for what you want to do. You can use the older DBMS_JOB package or the newer and more sophisticated  DBMS_SCHEDULER is also available in 10g.


text:
Q: How to convert date String array into string using javascript below is my JSON format which i got via dynamic data
{"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]}

and how can i want to  convert this into  below format
range(20180723,20180723)

below is my code :
var data:Date[] = {"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]}

  for(let i=0;i<=data.range.length;i++){
       console.log(,data.range[i]);
       }

A: I'm going to take a crack at this based on what I think you mean.
So in order for us to convert the string date to the format, you would like we can go about this multiple ways. The easiest way is to use a library like moment.js or date.js. These libraries can take inputs like 2018-07-23T16:03:26.861Z and convert them to a Date object. You can then use the date object to get the relevant values, for example;
const dateString = "2018-07-23T16:03:26.861Z";
let dateObject = moment(dateString, "YYY-MM-DDTHH:mm:ssZ").toDate();
let finalDateString = dateObject.getFullYear().toString()+dateObject.getMonth().toString()+dateObject.getDays().toString();

You can read up more about how to achieve this using the moment.js library in their docs.
Alternatively, you can split the date string at the T and replace the - now contained in the first array item in order to achieve this as well;
const dateString = "2018-07-23T16:03:26.861Z";
const outputDateString = dateString.split("T")[0].replace(/-/g,"");

You can read more about the String.prototype.split() here and more about the String.prototype.replace() here if you're interested.
Both these approaches would work and can be easily implemented in your already existing for loop e.g.
let data = {"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]}

let output = "range("
for(let i=0;i<=data.range.length;i++){
   output += data.range[i].split("T")[0].replace(/-/g,"")+(i===0 ? "," : ")");
}
console.log(range) //"range(20180723,20180723)"

A: Try the following:

var obj = {"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]};
for(var k in obj){
  var str = '';
  var temp = obj[k].map(d => {
    var m = (new Date(d).getMonth()+1) <= 9? '0' + (new Date(d).getMonth()+1):''+(new Date(d).getMonth()+1);
    d = new Date(d).getFullYear().toString() + m + new Date(d).getDate();
    return d;
  });
  str = k + '(' + temp.join(',') + ')';
  console.log(str);
}

A: Split on T, take the first part, remove the dashes. Would be one approach

A: You can get the desired string by data.range[i].split("T")[0].replace(/-/g,'')
May be you want something like this:

var data = {
  "range": ["2018-07-23T16:03:26.861Z", "2018-07-23T16:03:26.861Z"]
}

var result = [];// for ouput
var strKey=Object.keys(data)[0];//key of main object.i.e. range
var objData=data[strKey];//value of key

for (let i = 0; i < objData.length; i++) {
     result.push(getFormattedDate(objData[i]));
}

var prepend=strKey+"(";//prepended
var postpend=")";//postpender
result =prepend+result.join(",") + postpend;
console.log(result);

function getFormattedDate(date) {
    return date.split("T")[0].replace(/-/g,'');
}

A: If I understood your requirements properly then this small snippet will do your job with your existing codeblock. You just need the to split the datetime value by T using split() and replace the - using replace()

var data = {"range":["2018-07-22T15:03:26.861Z","2018-07-23T16:03:26.861Z"]}
var expected =[];
for(var i=0;i<data.range.length;i++){
 expected.push(data.range[i].split('T')[0].replace(/-/g,""))
}
console.log('range('+ expected.join(',') +')');


text:
Q: $G - u - v$ is not matchable if and only if $G$ has a barrier $B$ such that $u, v \in B$.
Question: Let $G$ be a matchable graph, and let $u$ and $v$ be distinct vertices of $G$. Show that $G - u - v$ is not matchable if and only if $G$ has a barrier $B$ such that $u, v \in B$.

My approach: Suppose that $G$ has a barrier $B$ such that $u,v \in B$. We will show that $G-u-v$ is not matchable. $G$ is matchable, implies that $c_{odd}(G-B) = |B|$. Let $B':=B-u-v$. Since $u,v\in B$, note that $G-B$ can be obtained by sequentially subtracting any permutation of $\{u,v,B'\}$ from $G$. This implies that $G-B = G-u-v-B'$. Hence, $c_{odd}(G-B) = c_{odd}(G-u-v-B')$. Let $H:=G-u-v$. Now $B'\subset B \subseteq V(G)$ and by definition $B'\cap \{u,v\}=\emptyset$, so $B'\subseteq V(G-u-v)=V(H)$. Then $|B| = c_{odd}(G-B) = c_{odd}(H-B')$. Since, $B'=B-u-v$, $|B'|=|B|-2\implies |B|=|B'|+2$. So, we have $$c_{odd}(H-B')=|B'|+2\implies c_{odd}(H-B')>|B'|.$$ Hence, by Tutte's theorem, $H=G-u-v$ is not matchable.
Now suppose that $G-u-v$ is not matchable. We will show that $G$ has a barrier $B$ such that $u,v \in B$. Let $H:=G-u-v$. Since $H$ is not matchable, by Tutte's Theorem there exists $S\subseteq V(H)$ such that $\mathrm{def} (S)>0$, that is, $c_{odd}(H-S)>|S|$. Now let $S':=S\cup\{u,v\}\subseteq V(G)$. Since $G$ is matchable, by Tutte's Theorem $c_{odd}(G-S')\le |S'|$. Note that $S\cap \{u,v\}=\emptyset$. This implies that $S=S'-u-v$, $|S|=|S'|-2$, and $$c_{odd}(G-S')=c_{odd}(G-u-v-S)=c_{odd}(H-S)>|S|=|S'|-2.$$ So, we have $|S'|-1\le c_{odd}(G-S')\le |S'|$, that is, either $c_{odd}(G-S')=|S'|$ or $c_{odd}(G-S')=|S'|-1$. If the former is true, then $S'$ is a barrier of $G$ (since $G$ is matchable) with $u,v\in S'$ (by definition), and we are done.
As one may note, I have already proved one direction of the statement in the question, but I am stuck with the other direction. In fact, given that $c_{odd}(G-S')=|S'|-1$, I am not able to construct a subset $S''\subseteq V(G)$ with $u,v\in S''$ such that $c_{odd}(G-S'')=|S''|$.
So, any hint along the above lines or any alternative ways of solving the problem would be appreciated. Thanks!

A: Nice work! You're almost there.
Hint:

 Show that $c_{odd}(G - S')$ and $|S'|$ have the same parity.

A: Below is the remaining part of the proof.
So, we have $|S'|-1\le c_{odd}(G-S')\le |S'|$, that is, either $c_{odd}(G-S')=|S'|-1$ or $c_{odd}(G-S')=|S'|$. Suppose that the former is true. We know that for any graph $F$ and any proper subset $A$ of $V(F)$, we have $$c_{odd}(F-A)-|A|\equiv |V(F)|\pmod 2.$$ Now since $G$ is matchable, $|V(G)|$ is even, that is, $|V(G)|\equiv 0 \pmod 2$. So, for any proper subset $A$ of $V(G)$, we have $c_{odd}(G-A)-|A|\equiv 0 \pmod 2$. Now either $S'=V(G)$ or $S'\subset V(G)$. If the former is true then $c_{odd}(G-S') = 0$, and since $|V(G)|$ is even, $|S'|$ is also even. So, $c_{odd}(G-S')-|S'|=-|S'|\equiv 0 \pmod 2$. But we have $c_{odd}(G-S')-|S'|=-1\equiv 1 \pmod 2$. Contradiction! Now suppose that $S'\subset V(G)$. So, we must have $c_{odd}(G-S')-|S'| \equiv 0 \pmod 2$. But we have $c_{odd}(G-S')-|S'|=-1\equiv 1 \pmod 2$. Contradiction!
So, $c_{odd}(G-S')=|S'|$. Hence, $S'$ is a barrier of $G$ (since $G$ is matchable) with $u,v\in S'$ (by definition), and we are done.


text:
Q: How to set nginx by IP server without domain, problem with tutorial I tried to do this tutorial with simple flask app using nginx and gunicorn https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04
and i got problems with last step - how to correctly set IP but not domain address at /etc/nginx/sites-available/myproject ? I got only IP, when i used just previous steps with IP:5000 its works well with gunicorn and flask, and now when i tried to complete it together its doesnt work.
server {
    listen 80;
    server_name _;

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
    }
}

I tried to use server_name IP; and listen IP; but no effect. What i do wrong? Thanks!

A: when you do not have a domain name to use, you can just set the server_name as the IP itself, like:
server_name 10.0.0.1;

As long as your port is open, the service is running, and the IP is reachable from your source - this will work fine.
A good test is to simply curl the port from the local machine where nginx is running:
curl http://localhost:80/

If this returns what you expect - then the chances are your IP is not reachable from whatver source you are hitting from on the outside.
tips

*

*Check your IP is reachable from your source with a telnet or something similar

*Is any firewalls blocking your port? If this is AWS or Azure, take a look at the inbound rules.

*What response do you get from the browser? if you get something like bad request then it's safe to assume nginx is working fine but your proxy pass is service something wrong.


text:
Q: A simplified proof of the uniqueness theorem for finitely generated abelian groups I'd like to have the following proof verified. Feedback welcome.
Suppose that $G$ is a finitely generated abelian group and $G=\mathbb Z_{r_1} \oplus\cdots \oplus \mathbb Z_{r_s} \oplus F_1$ where $r_1|r_2|\cdots|r_s$ and $F_1$ is a free abelian group. If also $G=\mathbb Z_{w_1} \oplus...\oplus \mathbb Z_{w_t} \oplus F_2$ is another such decomposition, I wish to show that $r_s=w_t, r_{s-1}=w_{t-1},\ldots$ whence $s=t$. We assume that we have already proved that $F_1 \cong F_2$.
To prove my claim, any element of $G/F_1$ of maximal order has order $r_s$ so that any element of maximal order in $G/F_2$ must have order $r_s$ as well, but such as element has already order $w_t$ so that $r_s=w_t$. Using the fact that finite groups are simplifiable as mentioned in the comments below, we deduce that $r_{s-1}= w_{t-1}$, and so on (a few trivial details such as $G/F_1 \cong G/F_2$ have been implicitly used).


text:
Q: Copying text from CKEditor to Word change one particular font size? I am implementing CKEditor for one of my project. When I copy paste a set of lines with varying font size from MS word to CKEditor, then paste the same back to MS word. like this,

*

*In MS word create multiple lines with different font size

*Copy paste the content to Ckeditor

*In CKeditor, copy paste the same content to MS Word again

All formatting is preserved except font size 11. Which get converted to 13.5.
In CKeditor, I have set
config.pasteFromWordRemoveFontStyles = false;
config.pasteFromWordRemoveStyles = false;

By default CKEditor use Px and we can customize it to use points or em.
My doubts:

*

*What type of font size MS word use ? Points or Pixels ?

*Why only font size 11 get change to 13.5 while other font size remain unchanged ?

A: I have a similar issue (with ckeditor, and word).
If the text in ckeditor is using the default font (ie you have not explicitly set the font, in my case arial), you select some text and change the font size to 12 points, and then copy and paste it into word, the font get changed to 11 points.
Note pasting into Wordpad and Excel, the font is correctly set to 12 points.
If you explicitly set the font and the size then it works properly (stays at 12 points).
My theory is that word is analyzing the html on the clipboard, and deciding to apply the word default font - (callibri 11 point), then changes it to arial, but decides to leave the font size as 11 points.


text:
Q: Downloading Video from Website Ubuntu 16.04: I have used youtube-dl to successfully download videos, so that they can be watched sans network connectivity
I would like to download the set of videos from the USPTO:
https://www.uspto.gov/video/cbt/efswebtraining/index.htm
Is there a more general class of utilities that perform this function?  Suggestions to tackle the goal are appreciated.


text:
Q: Does QGIS 3.4 locks the row while editing the postgis data? I want to know if QGIS locks the row of a postgis table for editing  or can this behavior be force implemented? Suppose there is another user who wants to edit the same row-- this must not be allowed.

A: I did a quick test (qgis 3.10 / postgresql 12 / postgis 3)
If I am opening a table for editing in qgis, I have no problem editing the same row from a psql prompt. It seems to me that the only locking that is going on is at the moment the row is stored.
So - I can open the attribute table for the layer "sns" in qgis and set comment to 'something' for the feature with id=1, at the same time I can do
update sns set comment = 'something else' where id =1;

in pgsql, and whatever is saved the last will stay in the database.
To a certain degree, this makes sense, as each of the updates are just taking place at the client level until the update is stored, but on the other side, in certain cases, it should be possible to lock against updates from other clients when a table is being edited in qgis, but that probably will be easiest to implement as table level locks (I was not able to see anything about locking when doing a quick look at the qgis postgis connection dialog)
There has actually been a feature request for this:
https://issues.qgis.org/issues/972


text:
Q: EntryPointNotFoundException on Windows XP with Windows API Code Pack I am trying to use the MS Windows API Code Pack in my application.
string docRef = @"adocument.docx";
var shellFile = Microsoft.WindowsAPICodePack.Shell.ShellFile.FromFilePath(docRef);

It works fine with Windows 7, while it raises an error with Windows XP (with installed .NET 3.5):

"System.EntryPointNotFoundException: Unable to find an entry point named 'SHCreateItemFromParsingName' in DLL 'shell32.dll'."

What do I need to do to launch MS WACP on Windows XP?

A: This method has been introduced in Windows Vista and doesn't exist in Windows XP. See its documentation.
The Windows API Code pack exists to allow you managed access to Windows 7 and - I think - Windows Vista features. These features simply don't exist in Windows XP, so you can't use them.

A: The API Code Pack relies on Windows 7 only API's, so they are not valid on Windows XP.  You need to check the version of the operating system, and execute alternate code if it's not Windows 7 (or presumably Windows 8 now).


text:
Q: Having problem highlighting lines in Leaflet? I have some walking tracks displayed on a map using Leaflet. Some of these tracks go across each other as they are extensions of the same walking rout for certain parts of their paths. So this makes it hard for the user to determine where a track starts and ends when I have two tracks that might share a 5km section and so you just end up with a black line displaying on the map and clicking in the area where they are exactly the same coordinates they are just seeing the popup details of whatever polyline got drawn on top.Ideally I think the best user interface would be to just show pin icons on the map for each walk and then when you click the pin it then displays the track and only that one track.Then if I click any other track's pin it then hides the track from before and now displays the new track.
Is there a method that I can do this in Leaflet?
Alternatively if this is not possible I would like to highlight the selected map by making it a thicker weight line. I have tried this, but the problem I am having with this is that for some longer walks it is not highlighting the whole track, just the portion of the geojson that got clicked. My geojson for longer walks is made up of a feature collection of linestrings. So in some of my walks the geojson has an array of linestring items in a FeatureCollection item. If there is a way to highlight the whole feature collection instead of just one linestring within the collection then that would be a good solution too.
Any help greatly appreciated as I am a newbie to mapping & leaflet.
Cheers
Craig
This is what I am using to highlight the line:
function onEachParkFeature(feature, layer) {
  layer.on({
    mouseover: highlightFeature,
    mouseout: resetHighlight
  });
}

function highlightFeature(e) {
  var layer = e.target;

  layer.setStyle({
    weight: 3,
    opacity: 1,
    fillOpacity: 0.0
  });

  if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
    layer.bringToFront();
  }
}

My code that adds each walk onto the map:
sb.Append(
  "L.geoJSON(" +
    item["LocationGeoJSON"].ToString() +
    ", {style: lineStyle, pane: 'walksPane', onEachFeature: onEachParkFeature}" +
    ', markerOptions).addTo(map).bindPopup("' +
    walkInfo +
    '").openPopup();' +
    System.Environment.NewLine
);


text:
Q: GPO will only work after an Admin logs in with same policy being applied to the admin account I have created a GPO that will put a shortcut on our receptionists desktops that is linked to a file share that is full of Internet shortcuts for Insurance verification. This has worked for almost 90% of my users. I have that remaining 10% that just don't want to behave. I can run gpresult /r and see that the result of the GPO should be displaying but it isn't. The only thing that I've found will "jump start" the GPO is if I log into the problem machine and I have the policy applied to the OU my user account is a member of. If I log into the machine without the policy being applied to my account the domain users experience will not change. So something must be happening to the system when I log in as a domain admin and have the policy applied to my account that then allows all other domain user accounts to accept the policy when they log in after me. I haven't found a lot out there googling this topic. The GPO is a user Policy. Any ideas?

A: If the GPO place the shortcut in the Public / All User's folder, then it's a local security problem.
The way you push the shortcut can be made other some other way. Like with a GPP's GPO and create it directly with the %desktop% location. No need for a central's file and it's place it on the user's own desktop directly.
A restricted user by default can only write in it own's profile.
The description from Microsoft;

What is a standard user account?
A standard user account lets a person use most of the capabilities of
  the computer, but permission from an administrator is required if you
  want to make changes that affect other users or the security of the
  computer.
When you use a standard account, you can use most programs that are
  installed on the computer, but you can't install or uninstall software
  and hardware, delete files that are required for the computer to work,
  or change settings on the computer that affect other users. If you're
  using a standard account, some programs might require you to provide
  an administrator password before you can perform certain tasks.


text:
Q: Heuristics of the sum of squared naturals $(1^2 + 2^2 + 3^2 \cdots + n^2)$ I'm new and this is my first question (though I've been lurking). English is not my native language. Studying on my own.
I'm really interested in deriving the formula $1^{2} + 2^{2} + 3^{2} + \cdots+ n^{2} = \frac{n(n+1)(2n+1)}{6}$ using only the following:
Given: for $n$, $a$, $b$, $c$, $z$, $y$ positive integers
$1 + 2 + 3 + \cdots + n = \frac{n(n+1)}{2}$ $ a^2 + b^2 + c^2 \cdots+ z^2 =(a + b + \cdots + z)^2 - 2ab - 2ac - \cdots - 2az - 2bc - \cdots -2bz - \cdots - 2$zy
I could write
$$1^{2} + 2^{2} + 3^{2} + \cdots+ n^{2} = [\frac{n(n+1)}{2}]^{2} - 2(1\cdot2) - 2(1\cdot3) - \cdots- 2(1\cdot n) - 2(2\cdot3) - \cdots - 2(2\cdot n) - \cdots -2(n-1)(n)$$
And then notice that:
$1^{2} + 2^{2} + 3^{2} + \cdots+ n^{2} = [\frac{n(n+1)}{2}]^{2} - 2[1(2 + 3 + \cdots+n)] - 2[2(3 + 4 + \cdots+ n)] - \cdots -2[(n-1)(n)]$
Which is
$1^{2} + 2^{2} + 3^{2} + \cdots n^{2} = [\frac{n(n+1)}{2}]^{2} - 2[\frac{n(n+1)}{2} -1] - 2[\frac{2n(n+1)}{2} - (1 +2)] -\cdots -2[\frac{(n-1)n(n+1)}{2} - (1 +2 + \cdots+n -1)]$
Simplifying to
$1^{2} + 2^{2} + 3^{2} + \cdots+ n^{2} = [\frac{n(n+1)}{2}]^{2} - 2[(1 + 2 +\cdots+ n-1)\frac{n(n+1)}{2} - 1(n-1) -2(n-2) - \cdots - (n-1)1]$
Edit (29/01): thought about it
$1^{2} + 2^{2} + 3^{2} + \cdots+ n^{2} = [\frac{n(n+1)}{2}]^{2} - 2[(1 + 2 +\cdots+ n-1)\frac{n(n+1)}{2} - 2(1 + 2 +\cdots n-1)]$
And then
$1^{2} + 2^{2} + 3^{2} + \cdots+ n^{2} = [\frac{n(n+1)}{2}]^{2} - 2[(\frac{(n-1)n}{2})(\frac{n(n+1)}{2}) - \frac{2n(n-1)}{2}]$
So
$1^{2} + 2^{2} + 3^{2} + \cdots+ n^{2} = [\frac{n(n+1)}{2}]^{2} - 2[\frac{n^{2}(n^{2}-1)}{2} - \frac{2n(n-1)}{2}]$
Then
$1^{2} + 2^{2} + 3^{2} + \cdots+ n^{2} = [\frac{n^{2}(n^{2}+2n+1)}{4}] - 4[\frac{n^{4}-3n^{2}-2n}{4}]$
But now
$1^{2} + 2^{2} + 3^{2} + \cdots+ n^{2} = \frac{n(-3n^{3}+2n^{2}-11n-2)}{4}$
Ok, now I know it's messed up, but still can't figure why

A: The best way I have seen is to start with a difference of $(p+1)$-th powers, where $p$ is the power in the summation you want (I think this is what Jaycob Coleman is alluding to in his comment on 3 April). In our case:
$(k+1)^3 - k^3 = 3k^2 + 3k + 1$
Then apply this identity from $k=1$ to $k=n$, where $n$ is the upper limit of the summation. This is a telescoping series:
$\boxed{\begin{eqnarray*}
    2^3 - 1^3 &= 3\cdot1^2 + 3\cdot1 + 1 \\
    3^3 - 2^3 &= 3\cdot2^2 + 3\cdot2 + 1 \\
     &... \\
    (n+1)^3 - n^3 &= 3\cdot{n^2} + 3\cdot{n} + 1 \\
\end{eqnarray*}}$
Summing up all terms (and cancelling on the left-hand side):
$(n+1)^3 - 1^3 = 3\displaystyle\sum\limits_{k=1}^{n}{k^2} + 3\displaystyle\sum\limits_{k=1}^{n}{k} + \displaystyle\sum\limits_{k=1}^{n}{1}$
Calling the sum we want $S$, and recognising the last two sums as $\dfrac{n^2+n}{2}$ and $n$ we have,
$3S + 3\dfrac{n^2+n}{2} + 3n = (n+1)^3 - 1 = n^3 + 3n^2 + 3n$
Solve this to get $\boxed{S = \frac{1}{3}n^3 + \frac{1}{2}n^2 + \frac{1}{6}n}$
which can be factored as
$\boxed{S = \dfrac{n(n+1)(2n+1)}{6}}$
Remarks
The beauty of this approach is that you can derive the sum of the $p-th$ powers of $1,...,n$ with only knowledge of the sums of all lower powers of $1,...,n$
and some algebra.


text:
Q: typescript : get all combinations of fixed length without repetition I have the following input :
interface Option{
  name:string
  travelMode:string
}

const options:Option[] = [
  {
    name:"john",
    travelMode:"bus"
  },
  {
    name:"john",
    travelMode:"car"
  },
  {
    name:"kevin",
    travelMode:"bus"
  },
  {
    name:"kevin",
    travelMode:"car"
  },
]

I want to get all combinations possible of length 2 inside this collection, to do so, I am doing :
const getCombinations=(options:Option[],startIndex:number,combination:Option[],combinationSize:number)=>{
  if (combination.filter(e => e!==undefined).length === combinationSize)
  {
    console.log(combination)
  }
  else if (startIndex<options.length){
    combination[startIndex]=undefined
    getCombinations(options,startIndex+1,combination,combinationSize)

    combination[startIndex]=options[startIndex]
    getCombinations(options,startIndex+1,combination,combinationSize)
  }
}

getCombinations(options,0,[],2)

This seems to be working well, I get the following output :
[
  undefined,
  undefined,
  { name: 'kevin', travelMode: 'bus' },
  { name: 'kevin', travelMode: 'car' }
]
[
  undefined,
  { name: 'john', travelMode: 'car' },
  undefined,
  { name: 'kevin', travelMode: 'car' }
]
[
  undefined,
  { name: 'john', travelMode: 'car' },
  { name: 'kevin', travelMode: 'bus' },
  undefined
]
[
  { name: 'john', travelMode: 'bus' },
  undefined,
  undefined,
  { name: 'kevin', travelMode: 'car' }
]
[
  { name: 'john', travelMode: 'bus' },
  undefined,
  { name: 'kevin', travelMode: 'bus' },
  undefined
]
[
  { name: 'john', travelMode: 'bus' },
  { name: 'john', travelMode: 'car' },
  undefined,
  undefined
]

However, I have one doubt and one remaining problem :
My doubt : why does all the printed combination are of length 4, my breaking condition should normally stop the recursion if we have already 2 defined elements : I don't understand why the last combination printed in my output contains 4 elements (first 2 defined and the remaining 2 undefined) => I am afraid that my program continues to iterate even if it has already 2 elements in its combination, and that's not what I want
Remaining problem : I dont want to calculate combination where name is the same, I only want combination with 2 distinct names (john and kevin but not john and john or kevin and kevin)
To do so, I first thought to keep my program like that, calculating everything, and just remove at the end combination with duplicated names, but I quickly realized that it was not the best solution, especially when my input options will have much more data (others individuals and others individuals options).
So I tried the following solution (stop the program if we already have visited the individual) :
const getCombinations=(options:Option[],startIndex:number,combination:Option[],combinationSize:number)=>{
  if (combination.filter(e => e!==undefined).length === combinationSize)
  {
    console.log(combination)
  }
  else if (startIndex<options.length){
    combination[startIndex]=undefined
    getCombinations(options,startIndex+1,combination,combinationSize)

    let individualAlreadyVisited = false
    if (startIndex>0)
    {
      for (let i =0;i<startIndex;i++)
      {
        if (combination[i] && combination[i].name===options[startIndex].name)
        {
          individualAlreadyVisited=true
          break
        }
      }
    }

    if (!individualAlreadyVisited)
    {
      combination[startIndex]=options[startIndex]
      getCombinations(options,startIndex+1,combination,combinationSize)
    }
  }
}

getCombinations(options,0,[],2)

But this is not working as expected, I am getting the following output :
[
  undefined,
  undefined,
  { name: 'kevin', travelMode: 'bus' },
  { name: 'kevin', travelMode: 'car' }
]
[
  undefined,
  { name: 'john', travelMode: 'car' },
  undefined,
  { name: 'kevin', travelMode: 'car' }
]
[
  undefined,
  { name: 'john', travelMode: 'car' },
  { name: 'kevin', travelMode: 'bus' },
  undefined
]
[
  { name: 'john', travelMode: 'bus' },
  undefined,
  { name: 'kevin', travelMode: 'bus' },
  undefined
]

*

*I still have combination with duplicated names, see first element

*I see some missing combination, for example, the following is not displayed :
 { name: 'john', travelMode: 'bus' },
 { name: 'kevin', travelMode: 'car' }

Thanks in advance for your help, I've spend a few hours trying to understand and get what I want.

A: I think the confusion comes from mutating the array during the recursive steps. That makes the code hard to understand and hard to debug.
I'd use a generator function to go over the array, take the element at the current index, and get combinations from all following elements with n - 1 elements:
 function* combine<T>(array: T[], n: number, start = 0, prev: T[] = []) {
   if(n <= 0) {
     yield prev;
     return;
   }

   for(let i = start; i <= array.length - n; i++) {
     yield* combine(array, n - 1, i + 1, [...prev, array[i]]);
   }
 }

 const result = [...combine([1, 2, 3, 4], 2)];

To fullfill your extra requirement, you can skip elements that are already included, like:
   if(prev.some(el => compare(el, array[i]))) continue;


text:
Q: Angular 7 Bootstrap 4 sidebar It is possible to create Bootstrap 4 sidebar with sub menus in Angular 7,something like this
thanks

A: I use this:
https://ng-bootstrap.github.io/#/components/accordion/examples
You can nest the accordion several levels deep in the exposed panes to get the effect you're looking for.

A: Yes! It possible with bootstrap and you can also use Angular material for side nav which is easy and modern approach.


text:
Q: How do you mock FileSystem.cacheDirectory in jest? I am trying to test a service that uses expo-file-system.  Specifically I just want to mock out FileSystem.cacheDirectory since that's the first instance of my code that uses FileSystem.
I tried __mocks__/expo-file-system.ts
export default {
  cacheDirectory: jest.fn(() => "<cache>/"),
};

And
jest.mock("expo-file-system", () => {
  return jest.fn().mockImplementation(() => {
    return {
      cacheDirectory: jest.fn(() => "<cache>/"),
    };
  });
});

My test I think looks simple enough
import * as FileSystem from "expo-file-system";

// This part I tried commenting out
jest.mock("expo-file-system", () => {
  return jest.fn().mockImplementation(() => {
    return {
      cacheDirectory: jest.fn(() => "<cache>/"),
    };
  });
});

it("verify mock", () => {
  expect(FileSystem.cacheDirectory).toBe("<cache>/");
});

But I always get FileSystem.cacheDirectory as undefined
I also have the jest-expo dependency and preset.
This is a simple scenario compared to Why doesn't expo-file-system work in Jest?

A: If you look in node_modules\jest-expo\src\preset\setup.js you can find the jest.mock("expo-file-system", () => ({...})); call.
Notice that cacheDirectory property is not included in the mock, which is why it is undefined when the tests are run.
I don't know how to get the current mock set for a module in jest (ie. as we often see with ...jest.requireActual(...)), so if you want to give cacheDirectory a value, the best solution I see is to copy\paste the entire jest.mock(...) call to your test file and add cacheDirectory to the mocked module prior to running your tests.
ie.
jest.mock('expo-file-system', () => ({
    downloadAsync: jest.fn(() => Promise.resolve({ md5: 'md5', uri: 'uri' })),
    getInfoAsync: jest.fn(() => Promise.resolve({ exists: true, md5: 'md5', uri: 'uri' })),
    readAsStringAsync: jest.fn(() => Promise.resolve()),
    writeAsStringAsync: jest.fn(() => Promise.resolve()),
    deleteAsync: jest.fn(() => Promise.resolve()),
    moveAsync: jest.fn(() => Promise.resolve()),
    copyAsync: jest.fn(() => Promise.resolve()),
    makeDirectoryAsync: jest.fn(() => Promise.resolve()),
    readDirectoryAsync: jest.fn(() => Promise.resolve()),
    createDownloadResumable: jest.fn(() => Promise.resolve()),
    cacheDirectory: "file:///test-directory/",
  }));


text:
Q: How to avoid duplicate entries in SCSS/SASS? I have recently started working with SASS in combination with Eclipse at work, and everything's working peachy:
Building an application through Ant executes a .bat which runs a Ruby command line which compiles any relevant .scss files into .css files.
One thing we've noticed however is that there can be duplicates. Granted, the general .css overrule rules apply (last one first), but having x-amount of the same statement is quite redundant. Take a a look at the following example of compiles .css code (it's not perfect, I was merely testing something)
/* line 2, ../../../sass/common/style.scss */
nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
/* line 8, ../../../sass/common/style.scss */
nav li {
  display: inline-block;
}
/* line 9, ../../../sass/common/style.scss */
nav li {
  display: inline-block;
}
/* line 11, ../../../sass/common/style.scss */
nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}

/* line 1, ../../../sass/webshop/_button-style.scss */
div:hover {
  padding: 12px 12px;
}

/* line 5, ../../../sass/webshop/_button-style.scss */
img {
  padding: 12px 24px;
}

/* line 2, ../../../sass/webshop/_webshop-style.scss */
nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
/* line 8, ../../../sass/webshop/_webshop-style.scss */
nav li {
  display: inline-block;
}
/* line 9, ../../../sass/webshop/_webshop-style.scss */
nav li {
  display: inline-block;
}
/* line 11, ../../../sass/webshop/_webshop-style.scss */
nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}

/* line 18, ../../../sass/webshop/_webshop-style.scss */
div:hover {
  padding: 12px 12px;
}

In this test style.scss contains the main styling for the webshop, _button-style.scss for any buttons present and _webshop-style contains any overrules for style.scss.As you can see, there are duplicates from style.scss and _webshop-style.scss present in this file, which is something we'd rather avoid. Can this be avoided? If yes: How?; If no: Is there a workaround/manual method to avoid this?
NOTE: _button-style.css is of no importance to this question/problem. It's just here to show you in a complete way what I'm doing.
For further reference, here's some important files:
config:
require 'compass/import-once/activate'
require "sass-globbing"
# Require any additional compass plugins here.

# Set this to the root of your project when deployed:
#http_path = "/"
css_dir = "../webapp/static/css"
sass_dir = "common"
add_import_path = "../webshop/"
images_dir = "images"
javascripts_dir = "javascripts"

style.scss:
nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li { display: inline-block; }
  li { display: inline-block; }

  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

@import "../webshop/_*";

_webshop-style.scss:
nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li { display: inline-block; }
  li { display: inline-block; }

  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

div:hover {
  padding: 12px 12px;
}

A: Sass will not attempt to remove any styling, ever, under any circumstance (only empty selectors and whitespace/comments are removed, depending on the chosen output style).  Sass has no way of knowing if you are overriding previous declarations with a different selector (eg. .foo .bar and p.bar might match the same element), so it writes things out exactly as you specified.
If you want to continue writing/using duplicate declarations in your Sass, you will need to use a 3rd party tool (eg. linter) to remove them.


text:
Q: SELECT UUID() inside an insert statment MySQL I'm trying to use SELECT UUID() INSIDE an insert query.
Here is my uery
INSERT INTO `posts`(`post_id`, `user_id`, `content`, `time`) VALUES (SELECT uuid(),1,'my content',mytime)

I'm getting error a comma or a closing bracket was expected mysql near uuid

A: uuid is a function, that you can use on its own without having to write select.
INSERT INTO `posts`(`post_id`, `user_id`, `content`, `time`) VALUES (uuid(),1,'my content',mytime)


text:
Q: Programmatically change headphone's button behavior Is it possible to programmatically change the process that starts once the user click the LifeChat LX-3000 center button?
I don't have any kind of experience programming with hardware so don't know if it's even possible. The problem is, a client of us has a lot of this headphones and we want to be able to change the default behavior of that button from open live messenger to open our CRM. I try to follow this instructions to modify the registry as doing (not programmatically):

*

*Find HKEY_CLASSES_ROOT\CLSID{F5F545A6-39C4-40B5-814D-B45040A89FB5}\LocalServer32

*Remove the (Default) value by double clicking it and deleting the text

*Change the value to OurCRMExePath
But this doesn't work. I suppose things changed since the date that web page was wrote. Any idea? I suppose first step would be to know which registry entry does that button modify and then go and change it. But, how can one get to know that?


text:
Q: Local variable referenced before assignment - Django 2.1 I´ve been looking for ways to authenticate an user without password in Django, but that is not my doubt.
I´ve seen this answer which has 24 upvotes. The answer says I have do that in my views.py:
user = authenticate(username=user.username)
login(request, user)

When I execute the code, I´m getting this error: UnboundLocalError: local variable 'user' referenced before assignment. This is obvious for me, I´m defining a variable using that variable.
So, why does the answer have 24 upvotes if it isn´t working? What do I have to do to get above code working?
Django version: 2.1

A: As @chepner explained in simple words, the issue here is to do with the use of it in the local scope.
If you followed those steps correctly, in the relevant function in views.py, you need to add the aforementioned lines of code. The user would be your User Object that you are trying to authenticate without the password.
You can see more about the User object here.


text:
Q: Monotonicity of a function defined by this equation Let the probability $p\in\left(0,1\right)$ be defined through the
equation:
$\left\{ 1-\left(1-p\right)^{n}\right\} \cdot\frac{1}{n\cdot p}=c$
where $c\in\left(\frac{1}{n},1\right)$ and $n$ is a natural
number. I wish to prove that $p=p\left(n\right)$ is decreasing and that $n\cdot p$
is also decreasing in $n$. Thank you for any inputs!
-- UPDATE --
Showing that $p=p\left(n\right)$ is decreasing can be seen by taking the derivative indeed. For the behavior of $\lambda(n):=n\cdot p(n)$ notice the following. Let $R\left(\lambda,n\right)=\left\{ 1-\left(1-\frac{\lambda}{n}\right)^{n}\right\} \frac{1}{\lambda}-c$.
By the Implicit Function Theorem applied to $R\left(\lambda,n\right)=0$
we have
$
\frac{d\lambda}{dn}=-\frac{\frac{\partial R}{\partial n}}{\frac{\partial R}{\partial\lambda}}<0
$
provided that the partial derivatives satisfy my conjecture: $\frac{\partial R}{\partial n}<0$
and $\frac{\partial R}{\partial\lambda}<0$. How to show this last part?

A: In order to prove $p$ is decreasing in $n$, you could differentiate the given equation w.r.t $n$,
$$-(1-(1-p)^n)\dfrac{1}{(np)^2}\,(p + n\,\dfrac{dp}{dn}) + \dfrac{1}{np}\,(1-p)^n\,log(1-p)\,\dfrac{dp}{dn} = \dfrac{dc}{dn}$$
Rearranging terms,
$$\dfrac{dp}{dn}\,\left(\dfrac{-1}{np^2}\,(1-(1-p)^n)\, + \dfrac{(1-p)^n\,log(1-p)}{p\,n} \right) = \dfrac{dc}{dn} + \dfrac{1-(1-p)^n}{p\,n^2}$$
$$\dfrac{dp}{dn} \left(\dfrac{(1-p^n)(1+p \, log(1-p))-1}{n\,p^2}\right) = \dfrac{dc}{dn} + \dfrac{1-(1-p)^n}{p\,n^2}$$
Since $1/n<c<1$ for each $n$, $c$ is increasing in $n$. Hence RHS $\geq0$. Moreover, $(1-p^n)(1+p \, log(1-p)) < 1$ since $0<p<1$. Hence, $\dfrac{dp}{dn}< 0$ ; thus $p$ is decreasing in $n$.
Let $E(p,n) = p\,n$ and $F(p) = (1-p^n)(1+p \, log(1-p))-1 <0$. Differentiating $E$ w.r.t $n$, $\dfrac{dE}{dn} = p + n\,\dfrac{dp}{dn}$. From previous result,
$$p + n\,\dfrac{dp}{dn} = p +  \left(\dfrac{n^2\,p^2\dfrac{dc}{dn}}{F(p)} + \dfrac{p(1-(1-p)^n)}{F(p)}\right)$$
$$= \dfrac{n^2\,p^2\dfrac{dc}{dn}}{F(p)} + p \left(\dfrac{1-(1-p)^n + F(p)}{F(p)}\right) $$
$$= \dfrac{n^2\,p^2\dfrac{dc}{dn}}{F(p)} + p \left(\dfrac{-(1-p)^n + (1-p)^n (1+p\,log(1-p))}{F(p)}\right) $$
$$= \dfrac{n^2\,p^2\dfrac{dc}{dn}}{F(p)} + p \left(\dfrac{(1-p)^n\,p\,log(1-p)}{F(p)}\right)  $$
Now, $log (1-p) <0$; so is $F(p)$. The first expression is $< 0$ but the second one is non-negative so it's difficult to argue that $dE/dn < 0$. (Let me check this later)


text:
Q: Ruby on Rails, multiple requests delay I have a Rails app deployed on Heroku. It has "Item" model, in "create" action some data is being processed (text analysis, sometimes huge texts), and this process takes a long time. If another request comes to the web server it takes too long to load any page. What is the best way to avoid such delay?

A: In a situation like this, you would typically use a background job manager like DelayedJob or Resque.  If you're just starting out, I'd recommend playing with DJ as it's quite simple to set up and does not require any external dependencies.
Since you've mentioned Heroku, they have a nice write up here on how to get it started with your app.
Essentially, you would take long-running tasks and add them to a job queue (in DJ's case, just another table in your database), where another process will monitor that table and run jobs as they appear. This way, you can return a response to your user immediately while the job is being worked in the background, keeping your web dyno free to handle requests concurrently.
If you're on Heroku, then you would need to pay for a worker dyno to run alongside your web dyno.
Also it depends on your server setup. If you were using an application server like Unicorn, you should be able to run multiple Rails processes within a single dyno, so you can still handle web requests even if one is tied up doing your text analysis.
But in all honesty, it sounds like your app isn't quite ready to run in production on Heroku anyway, as this issue should have already had a solution in place before you even deployed there.  You don't want to keep web processes tied up doing work that may be better suited for a background worker process.


text:
Q: laravel5 eloquent foreign key hasOne() I've got a transaction table containing the data of transactions like: id|user_id|amount|payment_method_id|...
The payment_methods table contains the different payment methods. Table design is: id|name
Content of the table is like:
1|paypal
2|credit card.
Now I would like to display a transaction history. This works fine but laravel always displays the number of the payment method, not the name. My transaction model looks like:
public function payment_method_id()
 {
  return $this->hasOne('App\Payment_Method', 'id', 'tpayment_method_id');
 }

All the time it displays the number, but not the correct name of payment method. Where's my fault?

A: You should define relationship this way:
public function paymentMethod()
{
    return $this->belongsTo('App\Payment_Method', 'payment_method_id');
}

And now you can display payment method name this way:
echo $transaction->paymentMethod->name;

In your example you used the same name of relationship as column and you used hasOne relationship instead of belongsTo

A: Assuming that you have an Transaction model containing payment_method_id() method that define the relationship between transaction and payment method tables. Now, you can access all columns/property from any transaction object. It should be something like followings:
$transection->payment_method_id->name;


text:
Q: A word to describe the next level of action Is there a word to describe the next level of action? I know there is but I can't remember the word.
For example, if plan A fails, plan B is the next level of action to take. And if plan B fails, the next level of action to take is plan C.
So in this case, plan B is a what of plan A, and plan C is a what of plan B. The what is the word I'm trying to find.

A: The phrase "contingency plan" comes to mind first, for me.  "Fallback" is another term you might find useful.


text:
Q: Elixir/Phoenix: Missing beam file elf_format <<"/usr/lib/erlang/lib/hipe-3.11.2/ebin/elf_format.beam" While trying to compile a release of my Phoenix project, the following error comes up:
$ mix release
....
==> Generated .appup for myapp 0.0.1 -> 0.0.2
===> Missing beam file elf_format <<"/usr/lib/erlang/lib/hipe-3.11.2/ebin/elf_format.beam">>
could not find app plug {0,10,0}

$ elixir --version
Elixir 1.0.3

The Phoenix version is 0.10.0. Am I doing something wrong, or is this a bug in Phoenix?

A: This is fine. It is because you don't have hipe compiler enabled but you don't need one. Everything should work just fine™.

A: Basically, it's about missing erlang-base-hipe package in ubuntu in my case.
See the issue that I have created regarding the same warning you get
https://github.com/bitwalker/exrm/issues/107
The solution here is
1. Just ignore. There is no harm in the warning. Though I believe exrm can produce better messages to the users and not confuse them.
2. Install erlang-base-hipe package which will resolve the issue.
If you go to https://www.erlang-solutions.com/downloads/download-erlang-otp
and see the ubuntu tab, you will find this info as the last FAQ.

*I have heard about HiPE. What is it? How to get it?

  HiPE stands for High-Performance Erlang Project. It is a native code
  compiler for Erlang. In most cases, it positively affects performance.
  If you want to download it, call the following:
sudo apt-get install erlang-base-hipe This will replace the Erlang/OTP
  runtime with a HiPE supported version. Other Erlang applications do
  not need to be reinstalled. To return to the standard runtime, call:
sudo apt-get install erlang-base


text:
Q: Finding linear equation for the plane of equidistant point I'm trying to do some practice questions in my book and I encountered this question:
Find a linear equation for the plane consisting of all point $(x,y,z)$ in space that are equidistant from the origin and the point $(2,2,2)$.
The answer key for the book gives me the solution:
$x^2 + y^2 + z^2 = (x-2)^2 + (y-2)^2 + (z-2)^2$
$x^2 + y^2 + z^2 = x^2 - 4x + 4 + y^2- 4y +4 +z^2 -4z +4$
$x + y + z = 3$
Can someone please explain how this solution works? Where does $x^2 + y^2 + z^2$ come from? And what does equating it to the right equation do? Can you please assume I'm starting to learn Calc 3 when explaining? Thanks in advance!

A: Using the distance formula, the distance between the point $(x,y,z)$ and the origin $(0,0,0)$ is:
$$\sqrt{(x-0)^2+(y-0)^2+(z-0)^2}$$
Using the distance formula, the distance between the point $(x,y,z)$ and the origin $(2,2,2)$ is:
$$\sqrt{(x-2)^2+(y-2)^2+(z-2)^2}$$
Hence, $(x,y,z)$ is equidistant from the origin and $(2,2,2)$ if and only if these distances are equal:
$$\sqrt{(x-0)^2+(y-0)^2+(z-0)^2} = \sqrt{(x-2)^2+(y-2)^2+(z-2)^2}$$
Now, square both sides and simplify to get the equation of the plane. That is what your book did.