text:
Q: Which TLS version was negotiated? I have my app running in .NET 4.7. By default, it will try to use TLS1.2.
Is it possible to know which TLS version was negotiated when performing, for example, an HTTP Request as below?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(decodedUri);
if (requestPayload.Length > 0)
{
    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(requestPayload, 0, requestPayload.Length);
    }
}

I only need this information for logging / debugging purposes, so it's not important that I have this information before writing to the request stream or receiving the response. I do not wish to parse net tracing logs for this information, and I also don't want to create a second connection (using SslStream or similar).

A: You can use Reflection to get to the TlsStream->SslState->SslProtocol property value.
This information can be extracted from the Stream returned by both HttpWebRequest.GetRequestStream() and HttpWebRequest.GetResponseStream().
The ExtractSslProtocol() also handles the compressed GzipStream or DeflateStream that are returned when the WebRequest AutomaticDecompression is activated.
The validation will occur in the ServerCertificateValidationCallback, which is called when the request is initialized with request.GetRequestStream()
Note: SecurityProtocolType.Tls13 is include in .Net Framework 4.8+ and .Net Core 3.0+.
using System.IO.Compression;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

//(...)
// Allow all, to then check what the Handshake will agree upon
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |
                                       SecurityProtocolType.Tls |
                                       SecurityProtocolType.Tls11 |
                                       SecurityProtocolType.Tls12 |
                                       SecurityProtocolType.Tls13;

// Handle the Server certificate exchange, to inspect the certificates received
ServicePointManager.ServerCertificateValidationCallback += TlsValidationCallback;

Uri requestUri = new Uri("https://somesite.com");
var request = WebRequest.CreateHttp(requestUri);

request.Method = WebRequestMethods.Http.Post;
request.ServicePoint.Expect100Continue = false;
request.AllowAutoRedirect = true;
request.CookieContainer = new CookieContainer();

request.ContentType = "application/x-www-form-urlencoded";
var postdata = Encoding.UTF8.GetBytes("Some postdata here");
request.ContentLength = postdata.Length;

request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident / 7.0; rv: 11.0) like Gecko";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate;q=0.8");
request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");

using (var requestStream = request.GetRequestStream()) {
    //Here the request stream is already validated
    SslProtocols sslProtocol = ExtractSslProtocol(requestStream);
    if (sslProtocol < SslProtocols.Tls12)
    {
        // Refuse/close the connection
    }
}
//(...)

private SslProtocols ExtractSslProtocol(Stream stream)
{
    if (stream is null) return SslProtocols.None;

    BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
    Stream metaStream = stream;

    if (stream.GetType().BaseType == typeof(GZipStream)) {
        metaStream = (stream as GZipStream).BaseStream;
    }
    else if (stream.GetType().BaseType == typeof(DeflateStream)) {
        metaStream = (stream as DeflateStream).BaseStream;
    }

    var connection = metaStream.GetType().GetProperty("Connection", bindingFlags).GetValue(metaStream);
    if (!(bool)connection.GetType().GetProperty("UsingSecureStream", bindingFlags).GetValue(connection)) {
        // Not a Https connection
        return SslProtocols.None;
    }
    var tlsStream = connection.GetType().GetProperty("NetworkStream", bindingFlags).GetValue(connection);
    var tlsState = tlsStream.GetType().GetField("m_Worker", bindingFlags).GetValue(tlsStream);
    return (SslProtocols)tlsState.GetType().GetProperty("SslProtocol", bindingFlags).GetValue(tlsState);
}

The RemoteCertificateValidationCallback has some useful information on the security protocols used. (see: Transport Layer Security (TLS) Parameters (IANA) and RFC 5246).
The types of security protocols used can be informative enough, since each protocol version supports a subset of Hashing and Encryption algorithms.
Tls 1.2, introduces HMAC-SHA256 and deprecates IDEA and DES ciphers (all variants are listed in the linked documents).
Here, I inserted an OIDExtractor, which lists the algorithms in use.
Note that both TcpClient() and WebRequest() will get here.
private bool TlsValidationCallback(object sender, X509Certificate CACert, X509Chain CAChain, SslPolicyErrors sslPolicyErrors)
{
    List<Oid> oidExtractor = CAChain
                             .ChainElements
                             .Cast<X509ChainElement>()
                             .Select(x509 => new Oid(x509.Certificate.SignatureAlgorithm.Value))
                             .ToList();
    // Inspect the oidExtractor list

    var certificate = new X509Certificate2(CACert);

    //If you needed/have to pass a certificate, add it here.
    //X509Certificate2 cert = new X509Certificate2(@"[localstorage]/[ca.cert]");
    //CAChain.ChainPolicy.ExtraStore.Add(cert);
    CAChain.Build(certificate);
    foreach (X509ChainStatus CACStatus in CAChain.ChainStatus)
    {
        if ((CACStatus.Status != X509ChainStatusFlags.NoError) &
            (CACStatus.Status != X509ChainStatusFlags.UntrustedRoot))
            return false;
    }
    return true;
}

UPDATE 2:
The secur32.dll -> QueryContextAttributesW() method, allows to query the Connection Security Context of an initialized Stream.
[DllImport("secur32.dll", CharSet = CharSet.Auto, ExactSpelling=true, SetLastError=false)]
private static extern int QueryContextAttributesW(
    SSPIHandle contextHandle,
    [In] ContextAttribute attribute,
    [In] [Out] ref SecPkgContext_ConnectionInfo ConnectionInfo
);

As you can see from the documentation, this method returns a void* buffer that references a SecPkgContext_ConnectionInfo structure:
private struct SecPkgContext_ConnectionInfo
{
    public SchProtocols dwProtocol;
    public ALG_ID aiCipher;
    public int dwCipherStrength;
    public ALG_ID aiHash;
    public int dwHashStrength;
    public ALG_ID aiExch;
    public int dwExchStrength;
}

The SchProtocols dwProtocol member is the SslProtocol.
What's the catch.
The TlsStream.Context.m_SecurityContext._handle that references the Connection Context Handle is not public.
Thus, you can get it, again, only through reflection or through the System.Net.Security.AuthenticatedStream derived classes (System.Net.Security.SslStream and System.Net.Security.NegotiateStream) returned by TcpClient.GetStream().
Unfortunately, the Stream returned by WebRequest/WebResponse cannot be cast to these classes. The Connections and Streams Types are only referenced through non-public properties and fields.
I'm publishing the assembled documentation, it maybe help you figure out  another path to get to that Context Handle.
The declarations, structures, enumerator lists are in QueryContextAttributesW (PASTEBIN).
Microsoft TechNet
Authentication Structures
MSDN
Creating a Secure Connection Using Schannel
Getting Information About Schannel Connections
Querying the Attributes of an Schannel Context
QueryContextAttributes (Schannel)
Code Base (Partial)
.NET Reference Source
Internals.cs
internal struct SSPIHandle {  }
internal enum ContextAttribute {  }

UPDATE 1:

I saw in your comment to another answer that the solution using
TcpClient() is not acceptable for you. I'm leaving it here anyway so
the comments of  Ben Voigt in this one will be useful to anyone else interested. Also, 3 possible solutions are better than 2.

Some implementation details on the TcpClient() SslStream usage in the context provided.
If protocol informations are required before initializing a WebRequest, a TcpClient() connection can be established in the same context using the same tools required for a TLS connection. Namely, the ServicePointManager.SecurityProtocol to define the supported protocols and the ServicePointManager.ServerCertificateValidationCallback to validate the server certificate.
Both TcpClient() and WebRequest can use these settings:

*

*enable all protocols and let the TLS Handshake determine which one will be used.

*define a RemoteCertificateValidationCallback() delegate to validate the X509Certificates the Server passes in a X509Chain.

In practice, the TLS Handshake is the same when establishing a TcpClient or a WebRequest connection.
This approach lets you know what Tls Protocol your HttpWebRequest will negotiate with the same server.
Setup a TcpClient() to receive and evaluate the SslStream.
The checkCertificateRevocation flag is set to false, so the process won't waste time looking up the revocation list.
The certificate validation Callback is the same specified in ServicePointManager.
TlsInfo tlsInfo = null;
IPHostEntry dnsHost = await Dns.GetHostEntryAsync(HostURI.Host);
using (TcpClient client = new TcpClient(dnsHost.HostName, 443))
{
    using (SslStream sslStream = new SslStream(client.GetStream(), false,
                                               TlsValidationCallback, null))
    {
        sslstream.AuthenticateAsClient(dnsHost.HostName, null,
                                      (SslProtocols)ServicePointManager.SecurityProtocol, false);
        tlsInfo = new TlsInfo(sslStream);
    }
}

//The HttpWebRequest goes on from here.
HttpWebRequest httpRequest = WebRequest.CreateHttp(HostURI);

//(...)

The TlsInfo Class collects some information on the established secure connection:

*

*TLS protocol version

*Cipher and Hash Algorithms

*The Server certificate used in the SSL Handshake

public class TlsInfo
{
    public TlsInfo(SslStream secStream)
    {
        this.ProtocolVersion = secStream.SslProtocol;
        this.CipherAlgorithm = secStream.CipherAlgorithm;
        this.HashAlgorithm = secStream.HashAlgorithm;
        this.RemoteCertificate = secStream.RemoteCertificate;
    }

    public SslProtocols ProtocolVersion { get; set; }
    public CipherAlgorithmType CipherAlgorithm { get; set; }
    public HashAlgorithmType HashAlgorithm { get; set; }
    public X509Certificate RemoteCertificate { get; set; }
}

A: The below solution is most certainly a "hack" in that it does use reflection, but it currently covers most situations that you could be in with an HttpWebRequest. It will return null if the Tls version could not be determined. It also verifies the Tls version in the same request, before you've written anything to the request stream. If the stream Tls handshake has not yet occurred when you call the method, it will trigger it.
Your sample usage would look like this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("...");
request.Method = "POST";
if (requestPayload.Length > 0)
{
    using (Stream requestStream = request.GetRequestStream())
    {
        SslProtocols? protocol = GetSslProtocol(requestStream);
        requestStream.Write(requestPayload, 0, requestPayload.Length);
    }
}

And the method:
public static SslProtocols? GetSslProtocol(Stream stream)
{
    if (stream == null)
        return null;

    if (typeof(SslStream).IsAssignableFrom(stream.GetType()))
    {
        var ssl = stream as SslStream;
        return ssl.SslProtocol;
    }

    var flags = BindingFlags.NonPublic | BindingFlags.Instance;

    if (stream.GetType().FullName == "System.Net.ConnectStream")
    {
        var connection = stream.GetType().GetProperty("Connection", flags).GetValue(stream);
        var netStream = connection.GetType().GetProperty("NetworkStream", flags).GetValue(connection) as Stream;
        return GetSslProtocol(netStream);
    }

    if (stream.GetType().FullName == "System.Net.TlsStream")
    {
        // type SslState
        var ssl = stream.GetType().GetField("m_Worker", flags).GetValue(stream);

        if (ssl.GetType().GetProperty("IsAuthenticated", flags).GetValue(ssl) as bool? != true)
        {
            // we're not authenticated yet. see: https://referencesource.microsoft.com/#System/net/System/Net/_TLSstream.cs,115
            var processAuthMethod = stream.GetType().GetMethod("ProcessAuthentication", flags);
            processAuthMethod.Invoke(stream, new object[] { null });
        }

        var protocol = ssl.GetType().GetProperty("SslProtocol", flags).GetValue(ssl) as SslProtocols?;
        return protocol;
    }

    return null;
}

A: Putting together some ideas here and there, I did a simple method to test each protocol available, forcing one specific type of connection each try.
At the end, I get a list with the results to use as I need.
Ps: The test is valid only if you know that the website is online - you can make a previously test to check this.
    public static IEnumerable<T> GetValues<T>()
    {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }

    private Dictionary<SecurityProtocolType, bool> ProcessProtocols(string address)
    {
        var protocolResultList = new Dictionary<SecurityProtocolType, bool>();
        var defaultProtocol = ServicePointManager.SecurityProtocol;

        ServicePointManager.Expect100Continue = true;
        foreach (var protocol in GetValues<SecurityProtocolType>())
        {
            try
            {
                ServicePointManager.SecurityProtocol = protocol;

                var request = WebRequest.Create(address);
                var response = request.GetResponse();

                protocolResultList.Add(protocol, true);
            }
            catch
            {
                protocolResultList.Add(protocol, false);
            }
        }

        ServicePointManager.SecurityProtocol = defaultProtocol;

        return protocolResultList;
    }

Hope this will be helpfull

A: The only way I can figure out is use SslStream to make a test connection, then check SslProtocol property.
TcpClient client = new TcpClient(decodedUri.DnsSafeHost, 443);
SslStream sslStream = new SslStream(client.GetStream());

// use this overload to ensure SslStream has the same scope of enabled protocol as HttpWebRequest
sslStream.AuthenticateAsClient(decodedUri.Host, null,
    (SslProtocols)ServicePointManager.SecurityProtocol, true);

// Check sslStream.SslProtocol here

client.Close();
sslStream.Close();

I have checked that sslStream.SslProtocl will always be as same as the TlsStream.m_worker.SslProtocol that used by HttpWebRequest's Connection.


text:
Q: MODIS temperature and NDVI data? hope anyone could give me some hints here. I tried to download free MODIS data from their page(resolution 500m, 1km). Im interested in NDVI and temperature data. But when i load the hdf files into my project file I just get weird layers :/.   This for example should be the temperature layer, but that's nothing I can work with. You have a clue if these are the right files, or if not, if there are better ones?

A: These values are scaled Kelvin. You can see in the MODIS website detailed specification about the MOD11C3 data

If you multiply the raster by 0.02 you should get the values in Kelvin

A: For the NDVI you can use the product modis MOD13Q1 and for the supercial temperature MOD11A2, the arhivos in HDF format of the products other complementary products I recommend you to check the respective guides
MOD13Q1
MOD11A2

A: Well, MODIS MCD43A4 data can be found via landviewer and you may analyze any of the images with ease by applying NDVI index or create any other index via built-in calculator. However, an option to collect MODIS temperature data is expected to be added soon.
An example of such data can be found here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to mock Google Api Discovery HttpResponseSequence I'm trying to use Google Api Discovery HttpMockSequence, but I keep getting the following error:
InvalidJsonError:
-------------------- >> begin captured logging << --------------------
googleapiclient.discovery: INFO: URL being requested: GET https://www.googleapis.com/discovery/v1/apis/webmasters/v3/rest
googleapiclient.discovery: ERROR: Failed to parse as JSON: /home/user/development/projectname/tests/build_response_data.json
--------------------- >> end captured logging << ---------------------

here is what I have/trying to do:
tests.py
build_response = self.datafile('build_response_data.json')
request_data = self.datafile('saved_request_data.json')

http_auth = HttpMockSequence([
    ({'status': '200'}, build_response),
    ({'status': '200'}, request_data)
])

service = build('webmasters',
                'v3',
                http=http_auth,
                developerKey='myapikey1234')

you can see my json file here:
build_response_data.json
the problem happens in the line 253 of the function _retrieve_discovery_doc in the file googleapiclient/discovery.py
I just cant seem to understand what's going on..can anyone tell me what am I doing wrong here?

A: To anwser my own question and to help others in the same boat, the problem was that the funtion _retrieve_discovery_doc tries to load the content as json as per in the line 253:
service = json.loads(content)

but because I was not opening the file and reading its contents, json was actually trying to load the url as json.
So the solution for the first part was change the HttpMockSequence to:
http_auth = HttpMockSequence([
    ({'status': '200'}, open(build_response, 'rb').read()),
    ({'status': '200'}, open(request_data, 'rb').read())
])

Then to return the data from the request_data file you do:
site_url = 'www.example.com'
body = {
    'startDate': '2015-09-11',
    'endDate': '2015-12-12',
    'dimensions': ['date']
}
build_response_data = self.datafile('build_response_data.json')
request_data = self.datafile('saved_request_data.json')
http_auth = HttpMockSequence([
    ({'status': '200'}, open(build_response_data, 'rb').read()),
    ({'status': '200'}, open(request_data, 'rb').read())
])

service = build('webmasters',
                'v3',
                http=http_auth,
                developerKey='myapikey1234')
service.searchanalytics().query(siteUrl=site_url, body=body).execute()

Hopefully this will help someone else.


text:
Q: How to create an Angular Flex-Layout stylebuilder to generate a default fxLayoutGap? I am trying to create a style builder to generate a default fxLayoutGap if none is specified, as outlined here:
This is my setup
module
@NgModule({
    ...
    providers: [{
        provide: LayoutGapStyleBuilder,    // when default is requested
        useClass: DefaultLayoutGapStyleBuilder  // provide instead custom builder
    }]
})

default-layout-gap-style-builder.ts
import { Injectable } from '@angular/core';
import { LayoutGapParent, LayoutGapStyleBuilder, StyleDefinition } from '@angular/flex-layout';

@Injectable()
export class DefaultLayoutGapStyleBuilder extends LayoutGapStyleBuilder {
    buildStyles(input: string, parent: LayoutGapParent): StyleDefinition {

        input = input || '10px';

        return super.buildStyles(input, parent); // THIS RETURNS { }
    }
}

view.html
<div fxLayout="row wrap" fxLayoutGap>

Everything seems to be hooked up correctly, but the call to super.buildStyles is not returning anything so a default gap style of 10px is not applied.

A: According to the source code if the value you pass in, '10px' in this case, does not end in ' grid'; than it will return the empty object and not give you the gap layout.  I'm guessing you will want to use a different builder or input for your use case.

A: from @CaerusKaru: https://github.com/angular/flex-layout/issues/1011
may also need to override sideEffect:
sideEffect(gapValue: string, _styles: StyleDefinition, parent: LayoutGapParent): void {
  gapValue = gapValue ? gapValue : '0rem';
  super.sideEffect( gapValue,_styles,parent );
}

or as in 1011 @rovercoder could workaround with MediaMarshaller


text:
Q: JsonMappingException: Type id handling not implemented, with enableDefaultTyping and custom serializer I use Java 9, Jackson-core and jackson-databind 2.5.5
I would like to use custom serialization with the DefaultTyping.NON_FINAL option for writing class names in Json.
if I delete the default typing NON_FINAL, everything works.
When I add the NON_FINAL option, my custom serializer "MySerializer" is called and I have the exception JsonMappingException: Type id handling not implemented
public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enableDefaultTyping();
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(new MySerializer());

        objectMapper.registerModule(simpleModule);

        System.out.println(objectMapper.writeValueAsString(new MyObject(1)));
    }
}

public class MyObject {
    private int a = 0;

    public MyObject() {
    }

    public MyObject(int a) {
        this.a = a;
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }
}

public class MySerializer extends StdSerializer<MyObject> {
    protected MySerializer() {
        super(MyObject.class);
    }

    public void serialize(MyObject myObject, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeNumberField("newNameForFieldA", myObject.getA());
        jsonGenerator.writeEndObject();
    }
}

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.5</version>
        </dependency>
    </dependencies>

the result without NON_FINAL default typing :
{"newNameForFieldA":1}
the exception :
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Type id handling not implemented for type com.test.jackson.main2.MyObject (by serializer of type com.test.jackson.main2.MySerializer)
    at com.fasterxml.jackson.databind.SerializerProvider.mappingException(SerializerProvider.java:1047)
    at com.fasterxml.jackson.databind.JsonSerializer.serializeWithType(JsonSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer.serialize(TypeWrappedSerializer.java:32)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3387)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2781)
    at com.test.jackson.main2.Main.main(Main.java:18)

A: When DefaultTyping.NON_FINAL is enable, the objectMapper will use the method "serializeWithType" defined in the class "JsonSerializer" to do the serialiaztion works if a custom serializer is defined.
So to solve the problem, you need to override the method "serializeWithType".


text:
Q: Elliptic integral and Arithmetic Geometric Mean For real numbers $0 < a < b$ we let
\begin{align*}
F(a,b) = 2\int_a^b \frac{dt}{\sqrt{(t^2-a^2)(b^2-t^2)}}
\end{align*}
Using some substitutions, we can show that
\begin{align*}
F(a,b) = \int_{a^2}^{b^2} \frac{dt}{\sqrt{t(t-a^2)(b^2-t)}} = \int_{-\infty}^0 \frac{dt}{\sqrt{t(t-a^2)(b^2-t)}}.
\end{align*}
(For the first one take $u = t^2$, we get the second from the first by substituting $u = \frac{t-b^2}{t-a^2}$)
I would like to show that
\begin{align*}
    F(a,b) = \int_0^{\pi/2} \frac{d\theta}{\sqrt{a^2\cos^2(\theta) + b^2\sin^2(\theta)}},
\end{align*}
but was unable to do so. From
\begin{align*}
    F(a,b) = \int_{-\infty}^0 \frac{dt}{\sqrt{t(t-a^2)(b^2-t)}},
\end{align*}
I substituted $\theta = -\arctan(t)$. Then $d\theta = -(t^2 + 1)^{-1}dt$ and the bounds become $\pi/2$ and $0$.
\begin{align*}
    F(a,b) &= \int_{\pi/2}^0 \frac{-(t^2 + 1)d\theta}{\sqrt{\tan(-\theta)(\tan(-\theta)-a^2)(b^2-\tan(-\theta))}}\\
    &= \int_0^{\pi/2} \frac{\sec^2(-\theta)d\theta}{\sqrt{\tan(-\theta)(\tan(-\theta)-a^2)(b^2-\tan(-\theta))}}\\
    &= \int_0^{\pi/2} \frac{d\theta}{\sqrt{\cos^4(-\theta)\tan(-\theta)(\tan(-\theta)-a^2)(b^2-\tan(-\theta))}}
\end{align*}
I am stuck here as I could not figure out how to show that this becomes
\begin{align*}
    \int_0^{\pi/2} \frac{d\theta}{\sqrt{a^2\cos^2(\theta) + b^2\sin^2(\theta)}}.
\end{align*}
I am fairly certain it should be possible given this and this.


text:
Q: Multiple methods in single test case I am new to Junit. I have a class with four methods. I am creating a test class with test cases. Can I have a test case that uses more than one methods of testing class or there should one test case per one method. What is good practice ?

A:
Can I have a test case that uses more than one method of the tested class

Obviously yes, how will you otherwise test methods which need a specific initialization before? For example
  fooCalculator = new FooCalculator(someParameters);
  fooCalculator.SetOption1(valueForOption1);
  fooCalculator.SetOption2(valueForOption2);
  result = fooCalculator.Calc();
  Assert.AreEqual(expectedResultForTheseOptions,result);

If, however, your question is "Can I have a test case that tests more than one method", then the answer is "you should avoid that", because that will typically result in too large tests. See this former question for a detailed explanation.


text:
Q: Changing editability of NSTextfield and multi line text I have an NSTextField that is used as either a label or an editable text field depending on whether the application is in edit mode or in view mode.
The code to change the editability of the text field is:
var editable : Bool = false {
    didSet {
        if editable {
            titleTextField?.editable = true
            titleTextField?.bezeled = true
            titleTextField?.drawsBackground = true
            titleTextField?.cell?.usesSingleLineMode = false
            titleTextField?.cell?.wraps = true
            editButton?.state = NSOnState
        } else {
            titleTextField?.editable = false
            titleTextField?.bezeled = false
            titleTextField?.drawsBackground = false
            titleTextField?.cell?.usesSingleLineMode = false
            titleTextField?.cell?.wraps = true
            editButton?.state = NSOffState
        }
    }
}

@IBAction func editButtonPushed(sender : NSButton) {
    if sender.state == NSOnState {
        self.editable = true
    }else{
        self.editable = false
    }
}

I've defined the NSTextField in Interface Builder as editable and 'Uses Single Line Mode' is not selected. The text field is in a custom view which is the right view in a NSSplitView. The custom view also contains a button with which the user can toggle the edit mode (it is connected to the action in the above code).
When the title in the text field is long (i.e. more than one line) the title is displayed correctly in the editable text field. When I click the Edit button (turning of Edit mode) the text field is made non-editable (the else statement above).
The problem is that in non-edit mode the NSTextField (and the parent custom view) resizes so that the full title fits into the NSTextField (now a label) on ONE LINE. I want the text field to remain the same size and use two lines to display the title.
How can I prevent the resizing of the text field? I've tried using titleTextField?.cell?.usesSingleLineMode = false and titleTextField?.cell?.wraps = true, but neither solution works.


text:
Q: how to use shopify api php Hey i am new in shopify and i have create new private app in my store.i want to use shopify api in my php program.i have write following code in my php file.
Code:
<?php
    $API_KEY = 'XXX';
    $SECRET = 'XXX';
    $STORE_URL = 'XXX';
    $PRODUCT_ID = 'XXX';

    $url = 'https://' . $API_KEY . ':' . md5($SECRET) . '@' . $STORE_URL . '/admin/products/' . $PRODUCT_ID . '.xml';

    $session = curl_init();
    curl_setopt($session, CURLOPT_URL, $url);
    curl_setopt($session, CURLOPT_HTTPGET, 1);
    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));

    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($session);
    curl_close($session);
    $product_xml = new SimpleXMLElement($response);
    echo $product_xml->title;
    echo $product_xml->variants->variant->{'inventory-quantity'};
?>

i got the following error.
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in index.php on line 24
Exception: String could not be parsed as XML in C:\wamp\www\apis\index.php on line 24
please help me to short out this problem as soon as possible.please please...
thanks in advance.

A: $ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_URL, $url);

$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data );

Use the above code.
Shopify returns the data in the JSON format, so decode it and use it for your purpose.
Also make sure that the URL that you are using is correct by loading it in the browser.


text:
Q: Select multiple values in a dropdown in angular 9 I would like to select multiple values in a dropdown. But the dropdown options are asynchronously fetched through REST API. I tried with <select multiple> with ngFor Directive, but it didn't work.

A: You can always use check boxes in the drop-down list and create a custom directive that check if check box is selected then it triggers some CSS highlight style and furthermore if you don't want to show check-box set its visibility to invisible so it works but only under the hood
(Just an idea)
There would be some extra work like if the drop down goes out of focus you would want the check-boxes to be deselected again so you would also have to check for that in the directive.


text:
Q: Поддерживаются ли символы _ в названии хидера http запроса? Меня интересует можно ли использовать в кастомных http хидерах (названиях полей) символ _?

A: Символ _ использовать разрешено, он соответствует стандарту:

The  field-name must be composed of printable ASCII characters
(i.e., characters that  have  values  between  33.  and  126.,
decimal, except colon)

rfc822
Но Nginx пропускает заголовки с символом _, если специально не включить опцию underscores_in_headers:
underscores_in_headers on;

Добавим эту опцию и создадим файл для проверки headers.php:
<?php
var_export(getallheaders());

Проверим:
curl -sS 'http://localhost:8200/headers.php' -H '_Header: value'

# Ответ:
array (
  '_header' => 'value',
  'Accept' => '*/*',
  'User-Agent' => 'curl/7.61.0',
  'Host' => 'localhost:8200',
  'Content-Length' => '',
  'Content-Type' => '',
)


text:
Q: How can I get Yup form validator to recognize the react-select defaultValue and submit the form? I am attempting to render defaultValues in a react-select component.
var initValue = ['Chocolate', 'Strawberry', 'Vanilla];
The react-select components display with the correct default value.  However, my Yup validation doesn't recognize the default value (see image below) as a valid selection.

Therefore the form will not submit, although the fields are filled in.  Can someone advise how I can make my Yup validator recognize the defaultValue?  Please see working code version in my github repo, which demonstrates this issue.

A: You should use value instead of defaultValue.


text:
Q: WPF, display attribute value in TreeView instead of node name If I have the following data template for a TreeView, what do I need to change so that each TreeViewItem shows the value of the name attribute on each XML node, instead of the node name?
<HierarchicalDataTemplate x:Key="NodeTemplate">
    <TextBlock x:Name="tb"/>
    <HierarchicalDataTemplate.ItemsSource>
        <Binding XPath="child::node()" />
    </HierarchicalDataTemplate.ItemsSource>
    <HierarchicalDataTemplate.Triggers>
        <DataTrigger Binding="{Binding Path=NodeType}" Value="Text">
            <Setter TargetName="tb" Property="Text" Value="{Binding Path=Value}"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=NodeType}" Value="Element">
            <Setter TargetName="tb" Property="Text" Value="{Binding Path=Name}"/>
        </DataTrigger>
    </HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>

A: Replace your binding with this:
<Setter TargetName="tb" Property="Text" Value="{Binding Path=Attributes[Name].Value}" />

Found the answer in this question.

A: Neeeeever mind, just had to replace Path=Name and Path=Value with XPath=@name in the two Setters.


text:
Q: Run application with parameters I'd like to start an application (Google Chrome) with a parameter (--enable-sync), but how can you do this on OS X? I've tried creating a terminal script, but I get the error message, "Google Chrome.app" is a folder... (this is of course correct, because applications are bundles on OS X).

A: Right click your application and choose for Show Package Contents.
Now search for the chrome binary somewhere in there. Once you have found it, you can start it from a terminal session with

/Applications/Chrome.app/<path inside the app folder to the chrome binary> --enable-sync

A: They didn't make any change to the Mac Chromium Dev build, just on the Windows Dev Build.

A: It's possible to run a command line operation via AppleScript.
The command looks like this:
do shell script "{command}"
You can use the OSX Script Editor to create this script.  There's a pretty good intro here:
Script Editor Intro
Once you've made your script, you can "Save as Application" to have OSX create an application bundle for your AS file.  Then you can launch your application just like any other program!

A: The binary executables for Mac application bundles are located in <path_to_bundle>/Contents/MacOS/. So in order to execute an application with some command-line arguments, you'd do something like this:
/Applications/Chromium.app/Contents/MacOS/Chromium <arguments> &

A: open -a Google\ Chrome.app --args "--allow-file-access-from-files"
open is used to open an application in Mac...

A: You could wrap your shell script in an application bundle wrapper using Platypus:
http://sveinbjorn.org/platypus

"Platypus is a developer tool for the Mac OS X operating system. It can be used to create native, flawlessly integrated Mac OS X applications from interpreted scripts such as shell scripts or Perl, Ruby and Python programs. This is done by wrapping the script in an application bundle directory structure along with an executable binary that runs the script."


text:
Q: Audio no longer working after AMD Catalyst install, Xubuntu 12.04 On a fresh Xubuntu install today I installed fglrx-updates, fglrx-amdcccle-updates and fglrx-updates-dev and, after restarting, everything worked fine apart from audio. The volume indicator is greyed out and there are no sound options to be found anywhere. I installed pavucontrol and xfce4-mixer but neither of them will open, and every time I try to play a song, the music player (I've tried VLC and gmusicbrowser) either freezes or sits at 0:00. Firefox hangs and eventually needs to be forced closed if I try to watch a video on Youtube or elsewhere.
lspci | grep Audio returns the following:
00:1b.0 Audio device: Intel Corporation 6 Series/C200 Series Chipset Family High Definition Audio Controller (rev 05)
01:00.1 Audio device: Advanced Micro Devices [AMD] nee ATI Device aab0

EDIT: I'm using a Radeon HD 7750 card. I'm not using the HDMI audio from it, but two speakers that are plugged into the port for the onboard audio.

A: George A. solved the problem in his question:

The problem must lie with Pulseaudio, as I followed the instructions here to uninstall it and, after rebooting, everything worked perfectly!


text:
Q: Can I define the XML syntax using an operator precedence grammar? Let's focus on the following parts with the following assumptions,

*

*any identifier having an Uppercase initial character is a Terminal (Misc, CharData, Reference, CDSect, PI, Comment)

*otherwise (lowercase initial character), a nonterminal (document, prolog, element)

[1]  document      ::=      prolog element Misc*
[39] element       ::=      STag content ETag
[43] content       ::=      CharData? ((element | Reference | CDSect | PI | Comment) CharData?)*

I want to write it into an operator precedence grammar. But I failed to complete the rule content. How can I define it?
document : prolog element
         | prolog element misc
         ;
misc     : misc Misc
         | Misc
         ;
element  : STag ETag
         | STag content ETage
         ;

A: That grammar is not an operator grammar, so attempting to write an operator precedence parser for it is bound to fail. If you really want to pursue that project, you'll need to rewrite the grammar.
Recall that there are two essential features of an operator grammar:

*

*Every production includes at least one operator (terminal).

*No production includes two consecutive non-terminals.

The first rule prohibits empty and unit productions. Those can be mechanically eliminated at the cost of bloating the grammar.
The second rule prohibits right-hand sides like document: prolog element. But more critically, it won't let you use element as a non-terminal because the language itself permits juxtaposed elements. That modification should be possible, since every element in fact starts and ends with a terminal, so you should be able to eliminate element from the grammar by macro-replacing all of its uses with the definitions. But it's also going to be tedious.(Also, I'm not convinced that making STag and ETag terminals really reflects the syntax; a start tag is a syntactically complicated object which must somehow be parsed.)
Once you've done all that, you'll need to cope with the essential context-sensitivity of XML, which results from the need for agreement between start and end tags. Most people simply redefine that as "semantic", in order to be able to use a context-free grammar, but it is still required for a correct parse.


text:
Q: Getting SSH timeout while building QCOW2 image from Ubuntu 18.04 ISO with packer Getting timeout while building a QCOW2 image with Ubuntu 18.04  ISO with a packer, using the below-mentioned template. Below is the packer.json used.
Any help on this will be appreciated on this. The same Template works for 14.04 image. Added highligted qemuargs for UEFI: [ "-bios", "/usr/share/qemu/OVMF.fd"]  which was needed with 18.04 ubuntu image:
[packer-host] out: 2020/02/06 04:36:02 packer: 2020/02/06 04:36:02 [INFO] Attempting SSH connection...
[packer-host] out: 2020/02/06 04:36:02 packer: 2020/02/06 04:36:02 reconnecting to TCP connection for SSH
[packer-host] out: 2020/02/06 04:36:02 packer: 2020/02/06 04:36:02 handshaking with SSH
[packer-host] out: 2020/02/06 04:36:33 ui error: [1;31m==> qemu: Timeout waiting for SSH.[0m
[packer-host] out: [1;31m==> qemu: Timeout waiting for SSH.[0m
[packer-host] out: 2020/02/06 04:36:33 ui: [1;32m==> qemu: Deleting output directory...[0m

   {
  "builders":
  [
    {
      "type": "qemu",
      "iso_url": "xxxx-xxxxx-9e3083d.iso",
      "iso_checksum": "b9fc1719eaee3c31e65dda6d6ba31313",
      "iso_checksum_type": "md5",
      "output_directory": "output",
      "ssh_wait_timeout": "30s",
      "disk_size": 81920,
      "format": "qcow2",
      "headless": true,
      "accelerator": "kvm",
      "ssh_host_port_min": 2222,
      "ssh_host_port_max": 2229,
      "ssh_username": "admin",
      "ssh_password": "xxxx123",
      "ssh_port": 22,
      "qemuargs": [
         [ "-serial", "file:serial.out" ],
         [ "-device", "e1000,netdev=user.0" ],
         [ "-cpu", "host" ],
         [ "-smp", "4" ],
         [ "-m", "8192M" ],
         [ "-bios", "/usr/share/qemu/OVMF.fd"]
      ],
      "ssh_wait_timeout": "120m",
      "shutdown_command": "echo xxxx123 | sudo -S shutdown -P now",
      "vm_name": "xxxx-xxxx-9e3083d.qcow2",
      "net_device": "virtio-net",
      "disk_interface": "virtio",
      "boot_wait": "2s",
      "boot_command": [
        "<enter><wait>",
        "<enter>"
      ]
    }
  ],
  "provisioners": [
    {
       "type": "file",
       "source": "/etc/init/ttyS0.conf",
       "destination": "/var/tmp/ttyS0.conf"
    },
    {
      "type": "shell",
      "inline": [
         "sleep 120",
         "echo '=> Enabling ttyS0 service'",
         "echo xxxx123 | sudo -S cp /var/tmp/ttyS0.conf /etc/init/",
         "echo xxxx123 | sudo -S bash -c 'echo Azure > /opt/xxxx/etc/cloud_instance'",
         "echo xxxx123 | sudo -S chmod g+r /opt/xxxx/etc/cloud_instance",

         "echo '=> Updating hugetlbfs mount point'",
         "echo xxxx123 | sudo -S mkdir -p /huge",
         "echo xxxx123 | sudo -S grep -q hugetlbfs /etc/fstab && sudo sed -i '/hugetlbfs/d' /etc/fstab && sudo bash -c 'echo \"hugetlbfs /huge hugetlbfs defaults 0 0\" >> /etc/fstab'",

         "echo '=> Disabling password authentication'",
         "echo xxxx123 | sudo -S sed -i 's/#PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config",

         "echo '=> Disabling SWAP partition for Azure builds'",
         "echo xxxx123 | sudo -S sed -i '/swap/d' /etc/fstab",
         "echo xxxx123 | sudo -S sed -i 's/^/#/' /etc/initramfs-tools/conf.d/resume",

         "echo '=> Cleaning up SSH keys'",
         "echo xxxx123 | sudo -S rm -rf /home/admin/.ssh/*",
         "echo xxxx123 | sudo -S shred -fu /etc/ssh/*_key /etc/ssh/*_key.pub",

         "echo '=> Cleaning up cloud-init dir'",
         "echo xxxx123 | sudo -S rm -rf /var/lib/cloud/*",
         "echo xxxx123 | sudo -S rm -rf /var/log/cloud-init*",

         "echo '=> Copy the 91_xxxx.cfg file to cloud.cfg.d folder'",
         "echo xxxx123 | sudo -S cp /etc/cloud.cfg.d/91_xxxx.cfg /etc/cloud/cloud.cfg.d/ 2>/dev/null || :",

         "echo '=> Change the Permissions for 91_xxxx.cfg file'",
         "echo xxxx123 | sudo -S chown xxxx:xxxx /etc/cloud/cloud.cfg.d/91_xxxx.cfg",
         "echo xxxx123 | sudo -S chmod 664 /etc/cloud/cloud.cfg.d/91_xxxx.cfg",

         "echo '=> Adding Azure DataSource'",
         "echo xxxx123 | sudo -S sed -i 's/datasource_list.*/datasource_list: [ ConfigDrive, OVF, Azure ]/g' /etc/cloud/cloud.cfg.d/91_xxxx.cfg",

         "echo '=> Uncomment the apt repository in sources.list file to download packages'",
         "echo xxxx123 | sudo -S [ ! -f /etc/init.d/vnms ] && echo xxxx123 | sudo -S sed -i.bak '7,$ s/# #_//' /etc/apt/sources.list",
         "echo '=> Updating apt sources list to Azure'",
         "echo xxxx123 | sudo -S sed -i 's/[a-z][a-z].archive.ubuntu.com/azure.archive.ubuntu.com/g' /etc/apt/sources.list",
         "echo xxxx123 | sudo -S sleep 120",
         "echo xxxx123 | sudo -S apt-get update",
         "echo xxxx123 | sudo -S sleep 120",

         "echo '=> Installing LTS HWE kernel'",
         "echo xxxx123 | sudo -S apt-get install --yes linux-image-virtual-lts-vivid linux-lts-vivid-tools-common",

         "echo '=>Installing HyperV KVP daemon'",
         "echo xxxx123 | sudo -S apt-get install --yes hv-kvp-daemon-init",

         "echo '=> Updating Grub command line'",
         "echo xxxx123 | sudo -S sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT.*/GRUB_CMDLINE_LINUX_DEFAULT=\"console=ttyS0,115200n8 earlyprintk=ttyS0,115200 rootdelay=300\"/' /etc/default/grub",
         "echo xxxx123 | sudo -S [ -f /etc/default/grub.d/50-xxxx-grub.cfg ] && sudo -S sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT.*/GRUB_CMDLINE_LINUX_DEFAULT=\"console=tty1 console=ttyS0,115200n8 earlyprintk=ttyS0,115200 rootdelay=300\"/' /etc/default/grub.d/50-xxxx-grub.cfg",
         "echo xxxx123 | sudo -S rm -f /etc/grub.d/50_xxxx",
         "echo xxxx123 | sudo -S update-grub2",

         "echo '=> Installing Windows Azure Linuxagent and update /etc/waagent.conf'",
         "echo xxxx123 | sudo -S apt-get purge --yes waagent*",
         "echo xxxx123 | sudo -S apt-get install --yes walinuxagent",
         "echo xxxx123 | sudo -S service walinuxagent restart",
         "echo xxxx123 | sudo -S waagent -force -deprovision",
         "export HISTSIZE=0",

         "echo '=> Revert to original sources.list file after downloading the packages.'",
         "echo xxxx123 | sudo -S [ ! -f /etc/init.d/vnms ] && echo xxxx123 | sudo -S mv /etc/apt/sources.list.bak /etc/apt/sources.list",

         "echo '=> Clearning Bash history'",
         "echo xxxx123 | sudo -S rm -rf .bash_history && unset HISTFILE"
       ]
    }
  ]
}


text:
Q: Laravel 5.2 MongoDB & MySQL in Same App Error I have a MongoDB connection & MySQL Connection details setup in my config/database.php file. I can connect to the MongoDB Details and get a response but when i try connect to the MySQL database, i get the following error:
FatalThrowableError in Builder.php line 1514:
Call to a member function compileSelect() on null

I've tried the solutions from this page:
Issue with Out of the box Laravel Authentication but none of the solutions have worked.
I'm not using any authentication on the app, just querying a MySQL database to return data.
[Updated]
Route link from app/Http/routes.php
Route::get('v1/{showdata}/{name}', 'ShowDataController@percentData');

Controller: ShowDataController.php
namespace App\Http\Controllers;
use App\ShowData;
use App\MongoDataPull;

class ShowDataController extends BaseController
{

public function percentData($showdata, $name)
{
    $showdata;
    $name;

        $signupsremaining = 0;
        //Percentage Calculator
        if ((ShowData::where('name', '=', $name)->first()) === null) {
        // If not found, change status to Not Listed
        $percentagetakeup = 'Not Listed';
    } else {
        // If found, Run Percentage Calculator
        $totalrequired = ShowData::select('total_required')->where('name', '=', $name)->value('total_required');
        $currentinterest = ShowData::select('current_interest')->where('name', '=', $name)->value('current_interest');
        $percentagetakeup = round((($currentinterest) / $totalrequired) * 100);

        // Calcualte the number of signups remaining for the fibrehood.
        $signupsremaining = $totalrequired - ($currentinterest);

        if ($signupsremaining < 0) {
            $signupsremaining = 0;
        } else {
            $signupsremaining = $signupsremaining;
        }
    }

    return ['percentagetakeup' => $percentagetakeup, 'signupsremaining' => $signupsremaining];

}

}

From ShowData Model ShowData.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class ShowData extends Model
{
    protected $table='qualify';
    protected $fillable=[
        'id',
        'name',
        'total_required',
        'current_interest',
        'status'
    ];

}


text:
Q: Reseting file permissions I am having trouble with file permissions on my WordPress site and I found a blog post that suggests to reset them with the following commands:
find /path/to/site/ -type f -exec chmod 664 {} \;
find /path/to/site/ -type d -exec chmod 775 {} \;

However, I am not sure with what I should replace "/path/to/site/". Can someone help?

A: In this context /path/to/site means the absolute path to the root of the content directory of the website.  You can find this by navigating to the directory where you installed wordpress and running the command pwd (assuming you are on linux).  That will output the path you are looking for.  By default in many linux/apache installations, this path is /var/www/html.
If you do not know where wordpress was installed, the process is slightly more involved.
Still assuming your server is an Linux server running Apache, to find the "/path/to/site/" you can run the command apachetl -S (on Debian/Ubuntu) or the command httpd -S (on Redhat/Centos).
That will output a block that will include a path to a config file.  Open the config file and find the line that starts
 <Directory...

The path in the quotes after the word Directory is the path you are looking for.


text:
Q: How to use getpagesize(2) to get the size of a file after opening it i have a file hello.txt
and a pointer *i pointing to the file, i have opened the file using c open(*i) function. i want to get the size of file using getpagesize(2) to read the content of the file and further write that content to a destination file. so getting the size of the file i required to now how big is the file and how much content there is to read.

A: getpagesize only tells you how big the memory pages are on the system; it has nothing to do with files. You should look at the stat call; it does what you need.
If operating on FILE *, you can use fseek(f, 0, SEEK_END) and ftell(f) to figure out how long the file is.

A: If you are using the open system function to open the file, you should look into the fstat function to get the size:
int fd = open(...);

struct stat st;
fstat(fd, &st);

printf("File size: %ld bytes\n", st.st_size);


text:
Q: Set local variable in rdlc expression Is it possible to somehow create variable in rdlc report expression in 'online' manner?
For example, I have following expression:
=IIf(First(Fields!BillingAccount_billtostateprovince.Value, "Invoice") <> "",
First(Fields!BillingAccount_billtostateprovince.Value, "Invoice") + " ",
"")

I suppose that I'm evaluating following expression First(Fields!BillingAccount_billtostateprovince.Value, "Invoice") twice. I don't like it and it looks ugly... I would prefer to create variable in the scope of current expression and use it.
Is it possible?

A: As user3056839 said, Welcome to SSRS!
Anyway, what you want is not possible since what you are writing right now is not a script but it's just an expression. It's a single statement that returns a value, so you cannot declare variables, use loops or anything that is part of a script.
You have to use exactly what you are writing.
Also it's not rare to see an IIF expression like yours. The one I constantly see is IFF( IS NOT NULL, , 'N/A'). The field may actually be evaluated twice, but there's nothing you can do. It's ugly but it's the only way you can do that.
Just think about the CASE WHEN clause:
SELECT
CASE WHEN MyField IS NOT NULL THEN
   MyField ELSE 0
END

You are evaluating the field twice, but there's nothing you can do :)

A: It is possible to do it in SQL Server 2008 and above. You can create a Report Variable which can be accessed through out your report.

Reference: sqlchick.com


text:
Q: What helps (justification) to decide cut score/cutoff points for 5-point likert scale? I am wondering what are the factors involved in deciding the cutoff value / cut score for 5-point likert scale from:
1 = not ready at all,
2 = not ready,
3 = moderately ready,
4 = ready,
5 = highly ready.

Is it proper for the cut score (in mean value) to be as such if i want it in 3 categories:
below 2 = not ready,
2 - 4 = ready,
above 4 = highly ready.

And if yes, how do I justify my decision? Are there any references or empirical ways to help decide?
I was told that I could justify that the inherent meaning of the scale helps to make such decision - especially using the information embodied in the numerical value - which expert said that?
Thank you.


text:
Q: How should Kotlins Map.minus be used? How does Kotlins Map.minus work? I would have expected that the entries with the same key are removed.
fun main()
{
    val left = mapOf(1 to "first", 2 to "second")
    val right = mapOf(1 to "first")
    val diff = left.minus(right)

    println(left)
    println(right)
    println(diff)
}

Output:
{1=first, 2=second}
{1=first}
{1=first, 2=second}

Expected:
{1=first, 2=second}
{1=first}
{2=second}

From the Kotlin documentation:

Returns a map containing all entries of the original map except the
entry with the given key. The returned map preserves the entry
iteration order of the original map.

A: The parameter of minus is K, not another map:
operator fun <K, V> Map<out K, V>.minus(key: K): Map<K, V>

So you should do:
val diff = left.minus(1)
// or
val diff = left - 1

Passing in a Map also compiles (but does not do what you expect) because minus's receiver is a map with a covariant (out) key type. The compiler simply treats your left map as a Map<Any, String>, and tries to remove the key mapOf(1 to "first") from it. Of course, your map does not have another map as a key, so nothing is removed. Notice that the diff produced this way is of type Map<Any, String>.
Note that the documentation also says "the given key", not "the keys in the given map", so you are supposed to give a key here.
If you want to remove multiple keys, you can give it an Iterable, Array, or Sequence of keys (not maps!). This will call the other overloads of minus.
val diff = left - right.keys


text:
Q: angularjs using directive inside another directive template I am trying to create a tab within a directive template, the tab works but I don't know how to render other directives when appropriate tab is selected.
Here is the code for my tabs directive.
angular.module('myApp')
    .directive('q2022Tabs', ['$rootScope', function ($rootScope) {
        return {
            restrict: 'EA',
            transclude: true,
            scope: {
                max: '=',
                label: '='
            },
            require: "q2022PieRadarChart" + "q2022RadarChart",
            template: `
            <form name="outerForm" class="tab-form-demo">
    <uib-tabset active="activeForm">
      <uib-tab index="1" heading="Radar Chart">
        (content tab)
      </uib-tab>
      <uib-tab index="2" heading="Pie Radar Chart">
        (content tab 2)
      </uib-tab>
    </uib-tabset>
  </form>
        `
        };
    }])
    .controller('ExController', ['$scope', '$rootScope', function ($scope, $rootScope) {

    }])

A: First I updated the template code as follows:
template: '
' +
          '
' +
          '

' +
          '
' +
          '
',

Note that I created a new 'view' directive. Next the view directive definition as follows:
app.directive('view', ['$compile', function (compile) {

    return {
        restrict: 'A',
        scope: {
            view: '@'
        },
        replace: true,
        template: '

',

        controller: ['$scope', function (scope) {
            scope.$watch('view', function (value) {
                scope.buildView(value);
            });
        }],

        link: function (scope, elm, attrs) {

            scope.buildView = function (viewName) {
                var view = compile('

')(scope);
                elm.append(view);
            }
        }
    }
}]);

So essentially, the view.dir variable is passed as an attribute to the 'view' directive, which then watches it's value and compiles a template with the directive in it.


text:
Q: Login form on netbeans with 2 tables at backend(for users and admin) I've inserted awt choice class for choices(Admin, User) and using if-else I wanna engage table admins(with columns 'username' and 'password') when c=="Admin"(or c.equals(Admin)) and table users(with columns 'username' and 'pass') when c is anything else.
while everything's good with admin login, user login will always give an error.
error: Invalid Username or Password
which comes from else block that's inside try block of user login part.
any suggestions on this?
   if(c.equals("Admin")){
       users.admin=1;
    try{
        String sql="select * from admins where username=? and password=?";
        pst=conn.prepareStatement(sql);
        pst.setString(1, TF_USER.getText());
        pst.setString(2, PW.getText());
        rs=pst.executeQuery();
        if(rs.next()){

            WelcomeUser j = new WelcomeUser();
               j.setVisible(true);
               this.dispose();
        }
        else{
            JOptionPane.showMessageDialog(null,"Invalid Username or Password","Action Deinied",JOptionPane.ERROR_MESSAGE);

        }
    }
     catch(Exception e){
       JOptionPane.showMessageDialog(null, e);
    }
    finally {

        try{
            rs.close();
            pst.close();

        }
        catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
        }
    }
   }
   else{
       users.admin=0;
   try{
        String Sql="select * from users where username=? and pass=?";
        pst=conn.prepareStatement(Sql);
        pst.setString(1, TF_USER.getText());
        pst.setString(2, PW.getText());
        rs=pst.executeQuery();
        if(rs.next()){

            WelcomeUser j = new WelcomeUser();
               j.setVisible(true);
               this.dispose();
        }
        else{
            JOptionPane.showMessageDialog(null,"Invalid Username or Password","Action Deinied",JOptionPane.ERROR_MESSAGE);

        }
    }
     catch(Exception e){

    }
   finally {

        try{
            rs.close();
            pst.close();

        }
        catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
        }
    }
   }


text:
Q: How does encrypting /home partition with ecryptfs on linux stop malicious modification of /boot or /(root)? This is a page where a developer of ecryptfs explains the difference between ecryptfs and dm-crypt: https://stackoverflow.com/questions/18230784/what-is-difference-between-linux-kernel-subsystem-dm-crypt-and-ecryptfs/18234635#18234635. However, this left me with a question, if ecryptfs only encrypts the /home partition, what stops a malicious hacker from modifying the / or /boot partition to maybe sniff the encryption password or modify a program, etc...
In short, how can I be sure that not only is my computer's data not able to be read by an unauthorized person, but also how can I be sure that nothing on my computer is modified without me knowing about it?
Also, where does this end because at some point, the booting code must be unencrypted in order for the processor to understand it? (Unless you use some sort of hardware decryption) But by definition, anything unencrypted can be modified?
(As a side point, I can see a way of determining integrity of the boot sequence by keeping a hash of the unencrypted part of the booting code in the encrypted part and on decryption comparing a the precomputed hash to a hash of the unencrypted part of the boot sequence at runtime. However, this doesn't solve the problem of having unencrypted areas, just a way to know after the fact if something was modified)

A: The short answer is "very little" stops a hacker from modifying /boot - really only time, undetected physical access and the ability to recompile initrd with a key logger.
Nothing stops a malicious hacker modifying an ecryptfs based / or /boot if they have physical system access - but see later - thats not what this is about.
"/" can be protected using full disk encryption like LUKS (but not, to my knowledge, per file encryption)- As the system is initially booted from /boot initrd can request the passphrase needed to unlock the volume prior to mounting /
I think you are overestimating the ability of full disk encryption - I put to you that it is designed to stop protect people against non-persistant threats, like a laptop being stolen, or when you want to RMA a hard drive with personal information - in both cases the data is of no further use to you, but you want to stop an unknown third party from accessing it - and, very often, file based encryption of your documents is adequate - who cares if they have an unencrypted copy of the system binaries - they are open source anyway.
You can't protect your system from unauthorised people with local access to it - so the solution to this is to prevent physical access.  You can go some way towards ensuring things are not modified without your knowledge by checksumming your all your systems files and doing compares with an offline backup - this is not fullproof as you need to make sure you are running an unmodified checksum program - and one which makes collision hashes practically impossible to recreate.   [ You may be able to simplify this if you seperate your filesystems and make some of them readonly, then keep a single hash for the each readonly partition ].  This whole process is cumbersome though.
When using full disk encryption "/"
You would typically not use the computer as "root" except for upgrades etc - this provides a fair degree of


text:
Q: Change target of all links inside an iframe to "_parent" jquery im trying to set the target to all links inside an iframe to "_parent" using jquery but im not sure how to do it, can anyone help me?
<script src="jquery-1.5.2.min.js">
$('a').target("_parent");
</script>

<iframe src="http://google.com" frameborder="0"></iframe>

Im doing this because I want to customize my firefox 4 homepage to show me the Google's start page with the restore session button near the "Sign in" link, and I almost do it but i don't wanna open the new links or searches inside the iframe.
Thanks
P.S. If is there another way without using jquery it would be great.

A: It's
$('a').attr("target", "_parent");

There's no method in jQuery called target() ;) Read about the attr method in jQuery - http://api.jquery.com/attr/
To go along with that, you should have the two <script /> tags separate.
<script src="jquery-1.5.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('a').attr("target", "_parent");
</script>

And just so you know, you cannot access the content of an iframe if its content is hosted on a different domain than its parent document.

A: It might be noted that you could do this without scripting anything with a base tag
<base target="_parent">

in the head.


text:
Q: How to unmount a nfs or ntfs when a NAS is not reachable? I have this environemnt:
Redhatlinux Enterprise
on fstab a NAS mounted as NFS
yyyy.xxx.com:/vol/yyyy_nec_nosnap12/prod_data on /prod_data type nfs (rw,bg,addr=x.y.z.w)
when the NAS doesn't reply (due to maintenance or issues) the system degrade and became stuck.
Is there any param to ask linux to umount the NAS when unreachable?

A: I would suggest using autofs to mount the NFS share.  When your NFS server isn't reachable, it won't be able to automount the volume.


text:
Q: How to create a list of values and their frequency in a list? I run a report daily which lists various files based on a particular identifier which indicates what is within the file. In the hopes of expediting my workflow, I'd like to set these files in a simple report by identifier, along with how frequently each identifier occurred, and organize this list from most to least frequent. Below is what I'm working with:

*

*This is a VBA based terminal emulator with limited object library references, so Excel isn't an option

*There's usually anywhere from 0-200 separate identifiers on any report, and they don't always appear on each. Since there are thousands of possible identifiers that could appear, I'd rather just have the macro list what it finds than look for them specifically.

*I use a bit of code utilizing ADOdb streaming to write similar reports to a .txt file, which I would like to use here. I'm sure I can make that happen after the data is sorted, but felt it worth mentioning in case the nature of how the filtered/organized list would be utilized would affect how it is addressed.

*I'm a novice, self-taught programmer with a particular fear of arrays (and I know this is going to come down to arrays...). So I don't necessarily know what commands and options are available to me in coding. (ie, a lot of what I've read involved possibly using dictionaries or collections, but I'm unsure I even have these available, let alone how to use them.)

I'd rather avoid creating multiple arrays, and creating multiple For loops if possible. It seems like a two dimensional dynamic array SortList(category, frequency) would be the route to go, but I can't find a way to filter unique values into it, while counting any of the values it has already found, and then sorting it afterwards.
I found a REALLY nifty bit of code on one site that can filter unique values without using a loop... (credit to where it's due: http://www.jpsoftwaretech.com/finding-values-in-an-array-without-looping/), but it seems it can only work for one dimensional arrays:
    Function IsInArray(arr As Variant, valueToFind As Variant) As Boolean
    IsInArray = (UBound(Filter(arr, valueToFind)) > -1)
    End Function

Does anyone have any suggestions on how I should try and tackle this dilemma?
8/14 - Suppose this is also important to note: these are not individual files one can access in a folder somewhere; the data I'm working with is presented simply as a list. It might be better to state what I'm doing is having these identifiers read as strings. It's the strings I want to count, sort, and organize... it seems like something that can be done with beginner's programming techniques, I just can't seem to find a way to do it without extraneous arrays or unnecessary nested loops and if/then conditions. Thoughts?

A: If you are familiar with ADO/DAO you could try querying the files ensuring the field in question is in GROUP BY and outputting the result of a COUNT() of the identifier.

A: Alternatively you could use a combination of collections and arrays.
GSeg illustrates quite well how you could utilise a collection of arrays here.
Collection of Arrays
By using a collection you can add an identifier as a Key and its count as the second array element.
As you cant duplicate keys in collections, if you use the identifier as a key it will give you a unique list.  When you try and add a duplicate key you therefre just need to trap the error and increase the count for that key. The count would be the second element in the array for that collections key.
Hope this makes sense. Good luck.


text:
Q: useEffect maximum update depth exceeded While creating a protected route for a react app using react router v6 i check the auth state of an AWS user on the project. The protection works after the useEffect makes too many attempts and is throttled by the browser, but i would like to stop this error from happening, this is the error message that is received...

react-dom.development.js:86 Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

here is the code for the useEffect that checks a current authenticated user

  const [isAuthenticated, setLoggedIn] = useState(true);
  useEffect(() => {
    (async () => {
      let user = null;

      try {
        user = await Auth.currentSession();
        if (user) {
          console.log("protected route use effecrt");
          setLoggedIn(true);
        } else {
          setLoggedIn(false);
          console.log("NO permission");
        }
      } catch (e) {
        setLoggedIn(false);
      }
    })();
  }, []);


text:
Q: Freeing Nodes in Linked List I'm trying to free each node in my linked list which was allocated in the addRec function.
CHANGE: Renamed my free funcion to free_list.
My call to free is as follows:
main()
{
    struct record * start = NULL;
    runmenu(......,start); //Ends when user chooses option to quit
    .
    .
    free_list(start);
}

void runmenu(.....,struct record * pstart)
{
    addRec(&start,....);
}

void addRec(struct record ** start,.....)
{
    struct record *toAdd;
    toAdd = (struct record*)malloc(sizeof(struct record));

    if (*start = NULL)
    {
        *start = toAdd;
    } else {
        struct record *current = start;
        toAdd->next = current->next;
        current->next = toAdd;
        .
        . //Adds into linked list
    }
}

My free function looks like:
void free_list(struct record* head)
{
    struct record *temp;

    while((temp = head) != NULL)
    {
    head = head->next;
    free(temp);
    }
}

I still seem to be having memory leaks. Was this correct?

A: You've provided your own function called free(), which means that the standard one isn't available.  Rename your function free_list() and call that in main() to release the list.  Inside the (now renamed) free_list() function, you still call the standard free() function.


text:
Q: How to import a project with only specific branches from BitBucket to GitHub My BitBucket project (let's call it Foo) contains 3 branches (let's call them master, bar and foobar). I would like to import this project to GitHub such that only master and foobar branches get imported.
The web interface for import on GitHub imports all the branches. But I don't wish bar to be imported at all.
A naive way would be to create another project, create the two branches in this new project, and then move the code into these new branches. But by doing this, I will lose the commit history and code evolution meta-data, which is not desirable.
Is there a way to achieve this?

A: Follow the steps:

*

*First, clone the repository from bitbucket in your system.

*Create a repository in github.

*Change the remote-url as like below command:
git remote set-url origin github_repo_link.git

*Then push the master branch to github repo running below command:
git push origin master

*Then, push the foobar branch:
git push origin foobar

Hope, this will help.


text:
Q: OpenLayers 3 editing properties in application through form I have a web page built with the QGIS webappbuilder by Boundless and the WFS-T widget.  Right now, the comments say that it only currently supports geometry updates.  I wanted to know if it would be possible to support properties (attribute) updates (i.e., non-spatial data in other columns).
Here is the code for the drawing:
{
key: '_onDrawEnd',
value: function _onDrawEnd(evt) {
  var wfsInfo = this._layer.get('wfsInfo');
  var feature = evt.feature;
  var node = this._format.writeTransaction([feature], null, null, {
    gmlOptions: {
      srsName: this.props.map.getView().getProjection().getCode()
    },
    featureNS: wfsInfo.featureNS,
    featureType: wfsInfo.featureType
  });
  this._doPOST(this._serializer.serializeToString(node), function (xmlhttp) {
    var data = xmlhttp.responseText;
    var result = this._readResponse(data);
    if (result) {
      var insertId = result.insertIds[0];
      if (insertId == 'new0') {
        // reload data if we're dealing with a shapefile store
        this._layer.getSource().clear();
      } else {
        feature.setId(insertId);
      }
    }

I have tried to add a properties argument in the writeTransaction line but I don't think I have the right syntax.  After digging through other forums and the OL3 API, I came across the setproperties command in the API.  Is it possible for a form to be generated with the OL library to update attributes as well with the setProperties command?
I saw similar post here: How do I set attributes when creating vectors using OpenLayers and WFS-T?
But it didn't seem to approach my end goal of having the user on the client end to input data as a form built from a GeoServer WFS request.
Another issue that I've been running across is that a lot of fixes involve using OL2, not OL3.


text:
Q: Twython 401 on stream, but REST works fine NO KIDDING. My code was working yesterday
So I'm writing a script to get streaming data using twython. But today it's giving me 401 errors. Even with the example code
I tried new keys, and a new app, but it still gives me 401.
However, normal REST api interface in Twython (see next code block) works just fine.
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
print twitter.get_home_timeline()

Some Googlefu led me to this SO thread which suggested using ntpd -q, but this doesn't solve my issue!

A: This affects only some of the servers behind stream.twitter.com.  Perhaps their clocks are off.
Some kind of geo-aware load balancing appears to be used and can the domain name resolves to a number of different IP addresses, depending on where you are doing the resolving.
Connecting to 199.59.148.229 or 199.59.148.138 gives the 401 error for me (these I get resolving from AWS Oregon), but 199.16.156.20 works (this I get resolving from my home network).
Therefore, my temporary workaround for this was to add this to /etc/hosts:
199.16.156.20 stream.twitter.com

I expect the original problem to go away in a few hours, but this works for me, for now.


text:
Q: How to set the dependencies of a service from its provider in AngularJs? I'm trying to do the following:
var myApp = angular.module('myApp', []);
myApp.provider('routeResolver', ['$q','$rootScope',function($q, $rootScope)
    {
        console.log( $q, $rootScope );
        this.$get = function()
        {
            return this;
        }
    }]

);

However, this gives the error: Unknown Provider $q
So I changed the code to the following:
myApp.provider('routeResolver', ['$qProvider','$rootScopeProvider',function($q, $rootScope)
    {
        console.log( $q.defer() );
        console.log( $rootScope );
        this.$get = function()
        {
            return this;
        }
    }]
);

This however gives the error of uknown function.. Even doing:
console.log( $q.$get().defer() );

doesn't work. Any ideas?

A: Instead of:
this.$get = function()
  {
    return this;
  }

try this:
return {
  // object being returned has to implement $get method
  $get: function() {
    // you should be able to use $q and $rootScope here
    return this;
  }
};

Besides $get, it should be possible to have other methods which can also access all the injected services:
return {
  // object being returned has to implement $get method
  $get: function() {
    // you should be able to use $q and $rootScope here
    return this;
  },
  // you can also have more methods here
  someOtherMethod: function() {
    // you should be able to use $q and $rootScope here as well
    // for example:
    $rootScope.$apply();
  }
};

That is assuming you injected $q and $rootScope into the constructor function (regardless of whether you're using array notation or not).
This is what I infer from here and here


text:
Q: Select in a mysql table with self-join relationship I am not very familiar with the self-join relationships but i wanted to know if it is possible, performing a SELECT, to show the products in relation to other products directly under the product referenced, in this table mysql

Sample data:

Desired output:

I tried several queries but I only get a field with the list, for example, of related products in the row itself:
select p1.idP, p1.name, group_concat(p2.idP)
from prodotti p1
left join prodotti p2 on p1.idP = p2.prodotti_idP
group by p1.idP;

I would like to show the records connected to others ONLY directly under the "parent" product
SQL Fiddle
Thank you

A: You can do this without using any "Self Join". A conditional ORDER BY using CASE .. WHEN expressions would work. If prodotti_idP is null, it basically means that it is a parent product. So we can simply sort it by its idP value; otherwise we will use its parent id (prodotti_idP) to sort upon. A second level sorting has to be done on idP value.
select idP, name, prodotti_idP
from prodotti
order by
  case when prodotti_idP is null then idP
       else prodotti_idp
  end,
  idP

SQL Fiddle Demo: http://sqlfiddle.com/#!9/72ffbcf/6


text:
Q: Experiment to determine the relation between applied voltage and angle of output shaft of a DC Servo motor? My project need to control the position of a DC Servo motor, but I don't know the plant model of my motor. So, I want to make an experiment to acquire the data between the applied voltage and angle of rotate shaft, after that I can use "System Identification Toolbox",in Matlab, to model my motor. There for I can choose PID parameters to control my motor position.
I work on an Arduino Uno board and a L298 driver. Please tell me how to do the experiment to acquire date for "System Identification Toolbox". Thank you !

A: There's not necessarily any correlation between the applied voltage and the shaft angle.  (Suppose the rotor is locked for example, no matter what voltage you apply the angle is the same.)  Servo motors use some sort of sensor/encoder for position and/or velocity feedback.
Your particular servo motor might have a position sensor like Hall effect devices, or an optical encoder or a resolver, but without any data on your motor we don't know.
There are techniques for brushless motors (especially in salient pole motors) to do sensorless measurement of the approximate shaft angle, but they are relatively complex, you can't just use the applied motor voltage.


text:
Q: Logparser - Selecting data in the past 2 weeks I am trying to use LogParser to return the data from my iis log files for the past 2 weeks. When I run the following I get "Error: Syntax Error: : no valid content: expecting opening parenthesis instead of token 'DATEADD(day,-14,'"
logparser "SELECT * FROM mylogfile.log WHERE date >= DATEADD(day,-14, GETDATE())" -o:datagrid

A: Neither DATEADD nor GETDATE are valid function names in the LogParser language. You may check function names by running logparser -h -i:func.
What you probably want is:
WHERE date >= SUB(SYSTEM_DATE(), DURATION('14', 'd'))


text:
Q: ng-class not responding to model update This is very straightforward: My angular view displays rows of printOrders generated via ng-repeat. If a print order has been printed, it applies the class 'panel-pink'

{{printOrder.GcodePath}},{{printOrder.Flavor}},{{printOrder.Finishing}}

             Print

When it loads the page, it correclty applies the 'panel-pink' class for those that are printed, but when I change the printOrder status via ng-click it doesn't
When a users click on a "print" button the following code on the print order controller executes:
$scope.doPrintOrder = function (printOrder) {
        PrintOrdersAPIService.printOrder(printOrder.Id, printOrder.UserId, printOrder.GcodePath).then(function (data) {
            printOrder.Printed = true; //this line should change the model
        });
    }

Everything works ok, the only problem is that the ng-class dosen't get appied when the model changes (printOrder.Printed = true;)
What should I do in order to make the styling work dynamically?

A: Change your ng-class to this:
ng-class="{'panel-pink' : printOrder.Printed}"

You don't need the curly braces.


text:
Q: Validación de un formulario con Jquery: con input type button no hace nada; Con el type submit funciona **cuál seria el problema ya que no esta entrando al darle click al botón tipo button, y con el botón tipo submit si funciona, estoy tratando de solucionarlo más no lo e conseguido, este es mi código de antemano gracias. **
$(function(){
          $.validator.addMethod("alfanumOespacio", function(value, element) {
         **evitar introducir carácteres**
       return /^[a-z0-9áéíóúüñ]*$/i.test(value);
         **validación de carácteres**
        }, "Ingrese sólo letras, números o espacios.");
           $("form[name='validFormulario']").validate({
        rules: {
         **nombre de los campos**
          nombre: {
               alfanumOespacio: true,
               required: true,
           },
          asunto: {
               required: true,
           },
          mensaje: {
               required: true,
           },
          correo: {
            required: true,
            correo: false
          },
        },
    **mensajes de validación**
        messages: {
          nombre: "
Se Requiere LLenar Este Campo
",
          asunto: "
Se Requiere LLenar Este Campo
",
          mensaje: "
Se Requiere LLenar Este Campo
",
          correo: "
Por Favor Ingrese Un Correo Válido
"
        },

        submitHandler: function(form) {
          form.submit();
        }
      });
    });

este es mi formulario el cuál quiero validar pero al momento de dar click no hace nada y si lo cambio al submit si funciona
<form method="post" name="validFormulario">

                <input type="text" class="form-control" name="nombre"  id="nombre" placeholder="Nombre">

                <input type="email" class="form-control" name="correo" id="correo" placeholder="Correo Electrónico">

              <input type="text" class="form-control" name="asunto" id="asunto" placeholder="Asunto">

              <textarea style="min-height: 150px; max-height: 300px;" class="form-control" name="mensaje" id="mensaje" rows="5" placeholder="Mensaje"></textarea>

               **este es el boton tipo button el cual no funciona  **

<input type="button" name="btn_EnviarCorreo" onclick="enviar();" value="Enviar Ahora">

          </form>

A: Solo funciona con submit porque estás utilizando submitHandler. Al botón le faltaría el id y sin el onClick:
<input type="button" name="btn_EnviarCorreo" id="btn_EnviarCorreo" value="Enviar Ahora">

Como estás utilizando jQuery entonces llamas a la función click del botón:
$(document).ready(function() {
    $("#btn_EnviarCorreo").click(function(){
        //Puedes hacer una prueba agregando un alert
        alert("click");
        //Agregas las validaciones de los campos
    });
});


text:
Q: smallest constant $c$ for which: $|x^k - y^k| < c \cdot |x - y|$, with $x,y < 1/2$ Let $k \in \{2,3,\dots\}, a \in [0,1/2)$ and $x,y \in [0,a)$.
I haven't really shown it but am $99\%$ certain the following holds following inequality holds:
$$
|x^k - y^k| < |x - y|,
$$
But I am looking for a constant $c < 1$ in function of $k$ and $a$ s.t.:
$$
|x^k - y^k| < c|x - y|.
$$

A: Hint: Think about mean value theorem applied for $f(x)=x^k$. I.e.
$$\left|f(x)-f(y)\right|=\left|f'(\varepsilon)\right||x-y|$$
where $\varepsilon \in (x,y) \subset[0,a)$ (assuming $x<y$) of course.

A: $$x^k-y^k = (x-y)(x^{k-1}+x^{k-2}y+....+y^{k-1})<(x-y)k\Big({1\over 2}\Big) ^{k-1}$$
so $c\leq k\Big({1\over 2}\Big) ^{k-1}$


text:
Q: matlab: delete the last row in excel I have an excel file with contents and background color,
something like the first row:

I want to delete all the contents in the first row, there is a command that do that?
UPDATE:
I succeeded to delete the cells of A3:I3:
esh.Range('A1:I1').value = [];

I tried to color the J1 cell by white, but it let me the cell of J2 and I need to get the cell of J3.
so I need to color J1 by 'NoFill'.
how can I do that?
I have to say that I always want to delete the last row in the file (the example doesn't show that but always the last line)
you can assume I have the range/number_of_the_row that I want to delete
e = actxserver ('Excel.Application'); %# open Activex server
ewb = e.Workbooks.Open(filename); %# open the file
esh = ewb.ActiveSheet;
clr = [255 255 255] * [1 256 256^2]';
esh.Range('A1:I1').value = [];
esh.Range('J1:J1').Interior.Color = clr;
set(e, 'DisplayAlerts', 0); % Stop dialog!
xlWorkbookNormal = excelWorkbook; %# it's the Excel constant, not sure how to pass it other way
ewb.SaveAs(filename, xlWorkbookNormal)
ewb.Close(false)
e.Quit
e.delete

A: esh.Range(J1).interior.ColorIndex = 0;


text:
Q: Make XML+CSS file content editable in firefox I have a XML document that I want do show in Firefox together with an assigned CSS file. I want to enable edit/design mode in firedox to enable the user to edit the text content. Same like contenteditable="true" would do for HTML content. Is this possible with XML+CSS content?
sample.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="sample.css" ?>
<doc>
    <red>red text</red>
    <blue>blue text</blue>
    <green>and... green text</green>
</doc>

sample.css
red {
    display: block;
    color: red;
}

blue {
    display: block;
    color: blue;
}

green {
    display: block;
    color: green;
}

Thanks,
Ingo


text:
Q: Spark Shell allowing to redeclare the same immutable variable I am working with Spark-shell for Scala and found a strange behaviour in Spark-shell REPL which is not there if i use any IDE.
I can declare the same immutable variable again and again in REPL, but the same is not allowed in IDE.
Here is the code in REPL:
scala> val rdd = sc.textFile("README.md")
rdd: org.apache.spark.rdd.RDD[String] = README.md MapPartitionsRDD[5] at textFile at <console>:24

scala> val rdd = sc.textFile("README.md")
rdd: org.apache.spark.rdd.RDD[String] = README.md MapPartitionsRDD[7] at textFile at <console>:24

scala> val rdd = sc.textFile("README.md")
rdd: org.apache.spark.rdd.RDD[String] = README.md MapPartitionsRDD[9] at textFile at <console>:24

scala>     val rdd = sc.textFile("README.md")
rdd: org.apache.spark.rdd.RDD[String] = README.md MapPartitionsRDD[11] at textFile at <console>:24

And here is the same thing I am trying in Eclipse IDE, and it shows compile time error:

Is there anything i am missing any configuration for Spark-shell REPL?
Or is it the expected behaviour?

A: In your REPL, your code is actually translated as follows:
object SomeName {
  val rdd = sc.textFile("README.md")
}
object Some_Other_Name {
  val rdd = sc.textFile("README.md")
}

Since both your rdd vals are defined in separate Singletons, there is no name collision between them. and since this happens behind the scenes in the REPL, you feel as if you are making reassignments to the same val.
In an IDE, all our code is written inside Classes or Scala singletons(Objects), so in the same scope (inside the resp. Class/Object) you are returned an error.


text:
Q: Looping over lenses, and using each with view and set This is a version of some code I have been working on, with the specifics removed. Hopefully it's clear what I'm trying to do, but if not I can clarify. I'm quite new to using lenses, and the complicated types involved often make them seem more trouble than they're worth.
-- some data type
type AType = ...

data Thing = Th { _v, _w, _x :: AType, _otherStuff :: ... }

makeLenses ''Thing

-- some operation that can be performed on corresponding x or w or v values in two Things.
f :: AType -> AType -> AType
f = ...

-- apply f to the corresponding v, and w, and x values in a and b; then store each result in the respective field of a, leaving other fields untouched.
transform :: Thing -> Thing -> Thing
transform a b =
    let transformVorWorX :: Lens' Thing AType -> AType
        transformVorWorX lens =
            let vwx  = view lens a
                vwx' = view lens b
            in  f vwx vwx'

    in  foldl (\a' lens -> set lens (transformVorWorX lens) a') a [v,w,x]

When I compile, ghc spits out
Could not deduce (f ~ Identity)
from the context (Functor f)
  bound by a type expected by the context:
             Functor f => (AType -> f AType) -> Thing -> f Thing
  at ...
  'f' is a rigid type variable bound by
      a type expected by the context:
        Functor f => (AType -> f AType) -> Thing -> f Thing
      at ...
Expected type: (AType -> f AType) -> Thing -> f Thing
  Actual type: ASetter Thing Thing AType AType
In the first argument of 'transformVorWorX', namely 'lens'
In the second argument of 'set', namely '(transformVorWorX lens)'

Why doesn't this code work? I found that replacing lens with cloneLens lens lets it compile, but I'm not sure why, and this feels very ugly - is there a more elegant way to do what I want, that is perhaps more general?
Many thanks

A: Lens' is under the hood universally quantified
type Lens' s a = ∀ f . Functor f => (a -> f a) -> s -> f s

So the type of [v,w,x] would have to be
[∀ f . Functor f => (AType -> f AType) -> Thing -> f Thing]

– with a quantor inside the list. Such types are called impredicative types, and Haskell doesn't support them. (A GHC extension with that name has been around for a while, but it doesn't work.) [Edit: work on impredicatives is ongoing as of 2021.]
There's a relatively easy way that always works to get around this: hide the quantor in a newtype. In the lens library, this is ReifiedLens. With it you can write
transform a b =
    let transformVorWorX :: ReifiedLens' Thing AType -> AType
        transformVorWorX (Lens lens) =
            let vwx  = view lens a
                vwx' = view lens b
            in  f vwx vwx'
    in  foldl (\a' lens -> set (runLens lens) (transformVorWorX lens) a') a
            [Lens v, Lens w, Lens x]

This code has exactly the runtime behaviour of the one you envisioned, but it's clearly pretty ugly.
The alternative solution you've discovered yourself does effectively the same thing too but is rather nicer. To see what's actually going on there, I'll put the cloneLens within transformVorWorX:
transform a b =
    let transformVorWorX :: ALens' Thing AType -> AType
        transformVorWorX lens =
            let vwx  = view (cloneLens lens) a
                vwx' = view (cloneLens lens) b
            in  f vwx vwx'
    in  foldl (\a' lens -> set (cloneLens lens) (transformVorWorX lens) a') a [v,w,x]

The reason this works is that, like ReifiedLens – but unlike Lens – ALens' has no quantor. It is just a concrete instantiation of the Functor f, thus it doesn't require impredicativity but you can directly use v, w and x in a [ALens' Thing AType] list. The functor instance is cleverly chosen to not lose any of the generality, hence cloneLens is able to give you back a full, universally-quantised lens.
Rather than cloning it, you can also use the ^# operator, which directly views an ALens, and storing instead of set:
transform a b =
    let transformVorWorX :: ALens' Thing AType -> AType
        transformVorWorX lens =
            let vwx  = a^#lens
                vwx' = b^#lens
            in  f vwx vwx'
    in  foldl (\a' lens -> storing lens (transformVorWorX lens) a') a [v,w,x]

If we condense that to a less verbose form, it looks quite good IMO:
transform a b = foldl updater a [v,w,x]
 where updater a' lens = a' & lens #~ f (a^#lens) (b^#lens)

Let me also suggest an entirely different solution: you define a single optic that accesses all the values of interest, namely
vwx :: Traversal' Thing AType
vwx f (Thing в ш к otherVals)
    = (\в' ш' к' -> Thing в' ш' к' otherVals)
      <$> f в <*> f ш <*> f к

Instead than defining this yourself, you can also let the Template Haskell helper do it for you:
makeLensesFor [("_v", "vwx"), ("_w", "vwx"), ("_x", "vwx")] ''Thing

Now, a traversal can be used as a simple fold, and thus to get a list of all the values. You can then use a standard zip to perform the transformation of the elements:
transform a b = ...
 where tfmedVals = zipWith f (a^..vwx) (b^..vwx)

To put that list of modified values back in a container, the library has also a function: partsOf. And with that, your entire transformation boils down to
transform a b = a & partsOf vwx .~ zipWith f (a^..vwx) (b^..vwx)


text:
Q: Find the mistake (AM GM ineqality) According to AM GM inequality
$$\frac{\left(x^3-\frac{1}{x}-\frac{1}{x}+\frac{2}{x}\right)}{4}\ge\left[(x^3)\left(-\frac{1}{x}\right)\left(-\frac{1}{x}\right)\left(\frac{2}{x}\right)\right]^\frac{1}{4}$$
$$\Rightarrow x^3 \ge 2^\frac{9}{4}\;\;\;\;;\;
\forall\; x\in \mathbb R^+ $$
which is not true

A: Your use of the AM-GM is equivalent to saying something like $$\frac{2 + (-1) + (-1)}{3} \ge \sqrt[3]{2(-1)(-1)}.$$  It doesn't work because we require each term to be a nonnegative real number.

A: The $GM-AM$ said the following
Let $$a,b>0 \, \, \text{Then the following inequality holds} \sqrt{ab}< \frac{a+b}{2}$$
as @Benjamin Wang remark your RHS is non positive.


text:
Q: A basic question on convergence in prob. and a.s. convergence If random variables $X_n$ are dominated by an integrable random variable then $E[X_n]\to E[X]$ follows if $X_n$ converges to $X$ in probability.
Proof: Take any subsequence $\{E[X_{n_k}]\}$. I need to show that it converges to $E[X]$. Now I know that $X_{n_k}$ contains a further subsequence $X_{n_k(i)} $where almost sure convergence is guranteed. and so, $E[X_{n_k(i)}]\to E[X]$. We can say upto this much. But, I have to prove $\{E[X_{n_k}]\} \to E[X]$ . How to proceed from here.

A: *

*Use Fatou's lemma and the dominating random variable to get the next sandwich:

$$
\mathsf{E}\liminf_n|X_n|\le \liminf_n\mathsf{E}|X_n|\le \limsup_n\mathsf{E}|X_n|\le \mathsf{E}\limsup_n|X_n|.
$$

*Convergence $X_n\xrightarrow{d}X$ (or $X_n\xrightarrow{p}X$) and (1) imply your result.


text:
Q: Best practice for having one centralized database across different regions (MongoDB) App is hosted in North America, Europe and Asia. All regions have the same instance of the app, but connected to different MongoDB databases hosted in Atlas in the same region as the app.
Each region's app is connected to different database because it would take long for database requests if the app is not hosted in the same region as the database itself.
The biggest issue now is if the user is registered in North America's instance, his user record will be stored in North America's database. So if the same user tries to login later in the Europe or Asia instance, he would not succeed since these databases do not have that user record.
What is the best practice to have one centralized database that would be fast for all regions globally. Can that be done with Atlas? Is it possible to host replicas set of one cluster in different regions?
All suggestions and recommendations are welcomed.

A: If I understand correctly, you want low global latency while keeping the integrity of your data no mather where your user queries from.
Since you are currently using Atlas, I highly suggest you switch to a Global Cluster with local read-only nodes. Here's why:
On the integrity of your cluster

*

*You would have one cluster sharded by the country code from your regions as  location. No need to manage multiple clusters anymore, the location would be used to distribute geographically. You will also need another shard key for a proper distribution, but that will not be a problem.

When the user creates the document from a region

*

*When writing data, your application will need to indicate to which region it belongs by using the location field.

When the user reads from the region he created the document

*

*You can read by passing the location field and the request would be sent to the correct region. But you end up with a high latency problem if the user is requesting from a different region. See the correct solution below.

When the user reads from a different region

*

*To support low latency when a user requests from a different region, you need to make your read preference to nearest and indicate the location of the data. Your application will always fetch the copied version of your data from the same (or closest) region as the local read-only nodes. You need to make sure you toggle the option from the screenshot below when setting up the cluster.


text:
Q: How to properly create dimensions and groups in Crossfilter? I have a data set like so:
[
  {
    event: 'open',
    delay: 120,
    createdAt: 157643454332
  },
  {
    event: 'click',
    delay: 240,
    createdAt: 157866452342
  }
  // roughly a 1000 records with data in the above format
]

I want to create a crossfilter which looks like this.
Conditions are as follows:

*

*If Day of the Week is changed, it changes the other 3 graphs

*If Hour of the Day is changed, it changes the other 3 graphs

*If Opens graph is changed, it changes the Day of Week and Hour of Day but doesn't change Clicks

*If Clicks graph is changed, it changes Day of Week and Hour of Day but doesn't change Opens

I've tried a host of things, and am horribly stuck. Googling hasn't helped either.
Anyone with any pointers which will help me proceed in the right direction, would be helpful!
I have also read the documentation, but it's all terribly confusing.
Update: Here is a codesandbox which basically does everything I am doing now to setup crossfilters.
How do I filter it to act like a crossfilter? That is what is confusing me.
https://codesandbox.io/s/l4w2vn5rpz

A: I got what I was having trouble understanding.
For anyone landing here in the future, the following snippets I found in a blog post and the API docs will help.

The function must return naturally-ordered values, i.e., values that
  behave correctly with respect to JavaScript's <, <=, >= and >
  operators.
In particular, this means that your dimension and group value
  functions must never return NaN, undefined, or null.

.

The dimension reads the dataset and groups the item with the same result in the function.

.

Dimensions allow us to group items in different subsets. Applying a filter is excluding a subset of items from our dataset.

.

The crossfilter tool used to sort the data is the dimension so the idea is to change the dimension.

The original post can be found here. Also, it is really helpful to thoroughly go through the API Reference and Crossfilter Gotchas, after you've gone through the blog post as it helps clarify some things I felt were complicated in the docs.
I hope this helps someone!


text:
Q: Best visualization tool for streaming graph updations? I am working on a kinesis POC.  I have a small python script running to generate stream data.  The streaming data is passed via a kinesis agent, kinesis firehose, and finally the data is inserted into Redshift table at regular interval of 5 minutes.
I wanted to view the updated records by way of a graphical representation so as to see the trend of data as the data comes in.
I tried with AWS Quicksight, but the issue with Quicksight is that the scheuled refresh interval is daily/weekly/monthly, so it doesn't solve my purpose to view update data every 5 minutes.
Is there any visualisation tool that i can connect to redshift?  Please help me with suggestions.
Thanks

A: After some googling, I found Metabase to be a good tool to satisfy my requirement (to view real time data updates on a dashboard, with auto refresh scheduled), and I find it awesome for the following reasons:

*

*Open source, for Windows/Mac, download the jar file and run it using
"java -jar metabase.jar" and you are ready to go. (JRE is required)

*Can be run on Docker, AWS EBS, and other environments as well. Can be
connected to many databases such as AWS Redshift, BQ, Druid, Google
Analytics, MongoDB, PostgreSql, MySql, SqlServer, etc.

*Dashboard auto refresh at 1,5,10,15,30,60 minutes. Can be integrated
with Slack, Mails for sharing updates/alerts, etc.

*Interactive queries, many report formats, dashboard (day /night
mode).

*LDAP integration, and provisions for SSH based db connections.

*Ease of use
https://www.metabase.com/start/
I was able run my kinesis agent running on a EC2, capture the streaming data to a Redshift table via Kinesis Firehose.  The I download metabase.jar file on my windows and configured redshift database in my metabase, ooh, am able to view streaming data on metabase dashboard.  We can schedule autorefresh every 1 minute,5 minute, or 15, 30, 60 minutes.