text:
Q: Applying measure zero definition to Cantor sets I just learned about the concept of measure zero in real analysis, i.e. the definition that a set in $\mathbb{R}^n$ has measure zero if for any $\epsilon$ it can be covered by countably many rectangles whose volume sum to $<\epsilon$.
I'm wondering if knowing only this, I can prove that the Cantor-third set has measure zero, while the fat Cantor set doesn't have measure zero.
If the answer is that I should wait until I learn more about measures in general, I will happily do that. I'm just curious whether this definition alone is enough.

A: Yes, it is enough. If you think about the elimination process to create the Cantor set, after the first stage you see that the Cantor set can be covered by two intervals of length $1/3$ and a bit. After the second stage of middle-third removal,  you see that the Cantor set can be covered by four intervals of length $1/9$ plus a bit, etc. So after the $n^{\rm th}$ stage you see that the Cantor set can be covered in $2^n$ intervals of length $3^{-n}$ (and bit, but is is easier not to write it!). In other words, the outer measure of the Cantor set is less than $(2/3)^n$ for all $n$, and so it has to be zero.


text:
Q: Windows: change own password of standard user by using commandline I want to change the password of the current logged in Windows user (no Active Directory) in a scriptable way. The users have the right to change their own passwords and already can change the password via GUI. But I've no way to integrate this in a script.
I've tried net use %user% %newpassword% but that only seems to work if the current user has admin rights.
I've also tried a powershell script:
param (
    [string]$oldPassword = $( Read-Host "Old Password"),
    [string]$newPassword = $( Read-Host "New Password")
)

$MethodDefinition = @'
[DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
public static extern bool NetUserChangePassword(string domainname, string username, string oldPassword, string newPassword);
'@

$NetAPI32 = Add-Type -MemberDefinition $MethodDefinition -Name 'NetAPI32' -Namespace 'Win32' -PassThru

$NetAPI32::NetUserChangePassword('.', $env:username, $oldPassword, $newPassword)

This gives "True" but nothing changes.
Has anyone an idea how I can change the password via script?

A: I have found the answer:
$oldpw = "oldpassword"
$newpw = "newpassword"
$user = $env:username
$computer = $env:computername
$user = [adsi]"WinNT://$computer/$user"
$user.ChangePassword($oldpw, $newpw)

This worked for me. Thank you for your replies!

A: I don't have enough points here to change it, but this question looks like a duplicate of this one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: DataFrame.show() throwing error in Databricks I am trying to get data from Azure Data Warehouse using Azure Databricks.
Connection part is good as I can see the rows returned in DataFrame but when I try to save or show the record in DataFrame it throws error. Here is what I have tried:
df = spark.read \
  .format("com.databricks.spark.sqldw") \
  .option("url", sqlDwNew) \
  .option("tempDir", temDir_location) \
  .option("forwardSparkAzureStorageCredentials", "true") \
  .option("query", "select  * from AccessPermission") \
  .load()
df.count()

Output
(1) Spark Jobs
df:pyspark.sql.dataframe.DataFrame
AccessPermissionId:integer
AccessPermission:string
Out[16]: 4

Error
df.show()

Output
com.databricks.spark.sqldw.SqlDWSideException: SQL DW failed to execute the JDBC query produced by the connector.

A: To know exact reason, I would request you to check out the complete stack trace and try to find root cause of the issue.
As per my repro, I have faced exactly same error message and able to resolve the issue by looking at the stack trace and found issue with the configuration of the storage account.
com.databricks.spark.sqldw.SqlDWSideException: SQL DW failed to execute the JDBC query produced by the connector.
.
.
.
.
.

 Caused by: java.lang.IllegalArgumentException: requirement failed: No access key found in the session conf or the global Hadoop conf for Azure Storage account name: chepra

Step1: Set up the Blob storage account access key in the notebook session configuration.
spark.conf.set(
  "fs.azure.account.key.<your-storage-account-name>.blob.core.windows.net",
  "<your-storage-account-access-key>")

Step2: Load data from an Azure Synapse query.
df = spark.read \
  .format("com.databricks.spark.sqldw") \
  .option("url", "jdbc:sqlserver://<the-rest-of-the-connection-string>") \
  .option("tempDir", "wasbs://<your-container-name>@<your-storage-account-name>.blob.core.windows.net/<your-directory-name>") \
  .option("forwardSparkAzureStorageCredentials", "true") \
  .option("query", "select  * from table") \
  .load()

Step3: Display or Show dataframe
df.show()
display(df)

Reference: Azure Databricks - Azure Synapse Analytics


text:
Q: ¿Para que sirve el try y catch? en java En el siguiente código que función ejerce la clase try y catch?
package Package;
import java.io.*;

public class Textos {

    public void leer (String nombreArchive) {
        try {

            FileReader r= new FileReader (nombreArchive);
            BufferedReader buffer = new BufferedReader (r);
            //System.out.println(buffer.readLine());

            String temp="";
            while(temp!=null) {
                temp = buffer.readLine();
                if (temp==null)
                    break;
                System.out.println(temp);
            }
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

A: El try catch en programación se utiliza para manejar fragmentos de código que son propensos a fallar, como  puede ser: recibir un valor nulo, convertir un tipo de dato a otro o en tu caso, la lectura de un archivo.
Al leer un archivo que está almacenado en la memoria del dispositivo (interna o externa), se genera un flujo de bits (físicamente  corriente) desde dicha memoria a la memoria RAM. Ese flujo puede verse interrumpido por diferentes razones, lo que causaría que la tarea falle y que el programa se detenga. El try catch lo que hace es asegurarse que aunque la tarea que se esté ejecutando falle, el programa se siga ejecutando y no se detenga.
Si el código que está dentro del try falla, se ejecuta el catch y el programa se sigue ejecutando. Dentro del try se debe de colocar el código que es propenso a fallar y dentro del catch el código a ejecutarse si el try falla, como puede ser un mensaje de error.
El try catch se debe utilizar cuando se tenga un fragmento de código que es propenso a fallar, que se sabe que por una u otra razón puede fallar. Como por ejemplo la conversión de un tipo de dato a otro:
try {

    // Convierte un valor de tipo String a int
    int numero = Integer.parseInt("a456");

} catch(Exception e) {

    System.out.println("ERROR: el valor de tipo String contiene caracteres no numéricos");

}

En este caso el código que esta dentro del try fallaría y se ejecutaría el código que está dentro del catch. Si no se usará el try catch en este caso, al producirse el error el programa se detendría. Pero al utilizar el try catch, aunque se produzca el error el programa se seguirá ejecutando normalmente.

A: Try=Tratar, catch=atrapar,
Básicamente en el segmento de código dentro del try estará el proceso que tratara de seguir tu programa y en caso de que en este ocurra un error, excepción o falla por algún motivo, entonces catch atrapa dicho error o Excepcion en la variable e(e es solo el nombre de variable no es obligatorio llamarla siempre así pero si se aconseja).

Nota: Creo que en todo lenguaje de programación la funcionalidad es la misma

A: Una de las novedades que incorporó Java 7 es la sentencia try-with-resources con el objetivo de cerrar los recursos de forma automática en la sentencia try-catch-finally y hacer más simple el código. Aquellas variables cuyas clases implementan la interfaz AutoCloseable pueden declararse en el bloque de inicialización de la sentencia try-with-resources y sus métodos close() serán llamados después del bloque finally como si su código estuviese de forma explícita.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
https://picodotdev.github.io/blog-bitix/2018/04/la-sentencia-try-with-resources-de-java/


text:
Q: SSIS Error - The version number in the package is not valid The logs corresponding to the failed job are as follows:

04/11/2014 06:40:00,LPR_New,Error,0,USPHND0088,LPR_New,(Job
  outcome),,The job failed.  The Job was invoked by Schedule 14
  (LPR_New_Job).  The last step to run was step 1 (Upload
  Material).,00:00:00,0,0,,,,0
04/11/2014 06:40:00,LPR_New,Error,1,USPHND0088,LPR_New,Upload
  Material,,Executed as user: nestle\ussqldbserver. ...00.5324.00 for
  32-bit  Copyright (C) Microsoft Corp 1984-2005. All rights reserved.
  Started:  6:40:00 AM  Error: 2014-04-11 06:40:00.39     Code:
  0xC001700A     Source:       Description: The version number in the
  package is not valid. The version number cannot be greater than
  current version number.  End Error  Error: 2014-04-11 06:40:00.39
  Code: 0xC0016020     Source:       Description: Package migration from
  version 3 to version 2 failed with error 0xC001700A "The version
  number in the package is not valid. The version number cannot be
  greater than current version number.".  End Error  Error: 2014-04-11
  06:40:00.39     Code: 0xC0010018     Source:       Description: Error
  loading value "3" from node
  "DTS:Property".  End Error  Could not load package
  "\usphnd0088\dataxfer\LPR\LPR New\UploadMaterial.dtsx" becau...
  Process Exit Code 5.  The step failed.,00:00:00,0,0,,,,0

A: Per this blog: http://blogs.msdn.com/b/jason_howell/archive/2014/09/30/ssis-error-when-deploying-from-vs-2013-to-ssisdb-in-sql-2012.aspx
The underlying cause is that currently (Sept 2014 timeframe) SSDT BI 2014 for Visual Studio 2013 does not support SSIS packages for SQL Server 2012.
It is a common feature request, and the product group is well aware of the demand.
http://connect.microsoft.com/SQLServer/feedbackdetail/view/944882/ssdt-bi-2014-backward-compatibility-for-ssis-2012
At present SSDT for VS 2013 only works with SQL Server 2014. You have to use SSDT-BI for Visual Studio 2012 with SQL Server 2012 SSISDB.

A: To provide a newer answer, using SQL Server Data Tools 2015, you can set the Deployment Target Version for your integration project to 2012, 2014 or 2016 (It defaults to 2016 and will result in version number errors on 2012/2014 DBs until you set it correctly). I successfully deploy SQL 2012 integrations now from SSDT 2015 after setting to "SQL Server 2012".

A: Have you checked what version of BIDS the project file was built in? This happens when the sql server agent's version is different from the one used to build the project that the SSIS package lives in.
There is a suggestion to rebuild the project in the correct version of BIDS that matches the server agent used to run the job. One other option is to set the location/path of the DTEXEC file you want to use (depending on which version you are using).
References: MSDN / Package migration from version 3 to version 2 failed with error 0xC001700A. The version number in the package is not valid. The version number cannot be greater than current version number.

A: I had the same problem. here is how I easily solved it without messing with Visual studio. Of course the management studio on my desk is the latest version so when I exported/Imported using my management studio i had the error.

*

*Actually Remote desktop into the legacy server and export the SSIS Project from that version of management studio.

*While on the legacy server connect to the destination server of the same version and import.

*I also found some fancy stuff where I had some aliases in the configuration manager aliasing some decommissioned servers.

*One of the aliases was using Named pipes, that protocol was turned off on the destination so I turned that protocol on.

*Did step 3,4 for both the 32 bit and 64 bit, and of course RDP'd into the destination server to make those changes.


text:
Q: Eikonal equation - Snell's law I am interested in equations of the form $|\nabla d|= F(x)$, where $F(x)$ is piecewise constant and $d(x) = 0$ on $\Gamma_D$, a subset of the boundary. In particular, like in the figure, one can consider $F(x)$ taking two values, delimited by an interface $\Sigma$ (which can be considered smooth).
Snell's law gives a relation between the incidence angles of a ray passing through the interface: $\sin \theta_+/\sin \theta_- = V_+/V_-$. I cannot find any clear references proving that Snell's law holds for the eikonal equation described above. Therefore I arrive at my question:

*

*Does Snell's law hold across the interface $\Sigma$?

*If the answer to the first question is affirmative, can you indicate references where a proof can be found?

A: Yes, Snell's law holds for any smooth interface, it follows directly from the eikonal equation, see for example section 2.4 of González-Acuña and Chaparro-Romo  - Stigmatic Optics. I summarize the derivation:
We substitute into the eikonal equation the definition of a ray, being a unit vector ${\bf v}$ in the direction of $\nabla d$. Then the eikonal equation $|\nabla d|=F$ can be rewritten in vectorial form as $\nabla d=F{\bf v}$, and hence for any closed contour $C$ one has
$$\oint_C F\,{\bf v}\cdot {\rm d}{\bf l}=\oint_C\nabla d\cdot {\rm d}{\bf l}=0.$$
If you take a contour as in the figure (with tangential unit vector $\hat{\bf t}$ and infinitesimal perpendicular thickness), you arrive at
$$\hat{\bf t}\cdot(V^+{\bf v}_+-V^-{\bf v}_-)=0,$$
which implies Snell's law.


text:
Q: How to add encryption-provider-config option to kube-apiserver? I am using kubernetes 1.15.7 version.
I am trying to follow the link https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/#understanding-the-encryption-at-rest-configuration to enable 'encryption-provider-config' option on 'kube-apiserver'.
I edited file '/etc/kubernetes/manifests/kube-apiserver.yaml' and provided below option
- --encryption-provider-config=/home/rtonukun/secrets.yaml

But after that I am getting below error.
The connection to the server 171.69.225.87:6443 was refused - did you specify the right host or port?

with all kubectl commands like 'kubectl get no'.
Mainy, how do I do these below two steps?
3. Set the --encryption-provider-config flag on the kube-apiserver to point to the location of the config file.

4. Restart your API server.

A: I've reproduced exactly your scenario, and I'll try to explain how I fixed it
Reproducing the same scenario

*

*Create the encrypt file on /home/koopakiller/secrets.yaml:

apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
  - resources:
    - secrets
    providers:
    - aescbc:
        keys:
        - name: key1
          secret: r48bixfj02BvhhnVktmJJiuxmQZp6c0R60ZQBFE7558=
    - identity: {}

Edit the file /etc/kubernetes/manifests/kube-apiserver.yaml and set the --encryption-provider-config flag:
   - --encryption-provider-config=/home/koopakiller/encryption.yaml

Save the file and exit.
When I checked the pods status got the same error:
$ kubectl get pods -A
The connection to the server 10.128.0.62:6443 was refused - did you specify the right host or port?

Troubleshooting
Since kubectl is not working anymore, I tried to look directly the running containers using docker command, then I see kube-apiserver container was recently recreated:
$ docker ps
CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS               NAMES
54203ea95e39        k8s.gcr.io/pause:3.1   "/pause"                 1 minutes ago       Up 1 minutes                            k8s_POD_kube-apiserver-lab-1_kube-system_015d9709c9881516d6ecf861945f6a10_0
...

Kubernetes store the logs of created pods on /var/log/pods directory, I've checked the kube-apiserver log file and found a valuable information:

{"log":"Error: error opening encryption provider configuration file "/home/koopakiller/encryption.yaml": open /home/koopakiller/encryption.yaml: no such file or directory\n","stream":"stderr","time":"2020-01-22T13:28:46.772768108Z"}

Explanation
Taking a look at manifest file kube-apiserver.yaml is possible to see the command kube-apiserver, it runs into container, so they need to have the encryption.yaml file mounted into container.
If you check the volumeMounts in this file, you could see that only the paths below is mounted in container by default:

*

*/etc/ssl/certs

*/etc/ca-certificates

*/etc/kubernetes/pki

*/usr/local/share/ca-certificates

*/usr/share/ca-certificates

    ...
        volumeMounts:
        - mountPath: /etc/ssl/certs
          name: ca-certs
          readOnly: true
        - mountPath: /etc/ca-certificates
          name: etc-ca-certificates
          readOnly: true
        - mountPath: /etc/kubernetes/pki
          name: k8s-certs
          readOnly: true
        - mountPath: /usr/local/share/ca-certificates
          name: usr-local-share-ca-certificates
          readOnly: true
        - mountPath: /usr/share/ca-certificates
          name: usr-share-ca-certificates
          readOnly: true
    ...

Based on the facts above, we can assume that apiserver failed to start because /home/koopakiller/encryption.yaml doesn't actually mounted into container.
How to solve
I can see 2 ways to solve this issue:
1st - Copy the encryption file to /etc/kubernetes/pki (or any of the path above) and change the path in /etc/kubernetes/kube-apiserver.yaml:
   - --encryption-provider-config=/etc/kubernetes/encryption.yaml

Save the file and wait apiserver restart.
2nd - Create a new volumeMounts in the kube-apiserver.yaml manifest to mount a custom directory from node into container.
Let's create a new directory in /etc/kubernetes/secret (home folder isn't a good location to leave config files =)).
Edit /etc/kubernetes/manifests/kube-apiserver.yaml:
...
    - --encryption-provider-config=/etc/kubernetes/secret/encryption.yaml
...
  volumeMounts:
    - mountPath: /etc/kubernetes/secret
      name: secret
      readOnly: true
...
  volumes:
    - hostPath:
      path: /etc/kubernetes/secret
      type: DirectoryOrCreate
    name: secret
...

After save the file kubernetes will mount the node path /etc/kubernetes/secret into the same path into the apiserver container, wait start completely and try to list your node again.
Please let know if that helped!


text:
Q: notifyDataSetChanged() won't update view if with DBHelper? The following code updates the gridView automatically when I delete the button.
public View getView(int position, View convertView, ViewGroup parent) {
        final Item item = getItem(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_button, parent, false);
        }
        Button itemBtn = (Button)convertView.findViewById(R.id.itemBtn);
        itemBtn.setText(item.getName() + " (" + item.getPrice()+")");
        itemBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                     MainActivity.cart.addItem(item);
                }
        });

    itemBtn.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
                remove(item);
                notifyDataSetChanged();
            return true;
        }
    });
       itemBtn.setLongClickable(true);
        return convertView;
    }
}

but as I need to update the database as well, here is my current code now. The view does not update automatically and I still have to change tabs for the gridView to be updated and the button be removed.
itemBtn.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {
        DBHelper dbHelper = new DBHelper(mActivity);
        if (dbHelper.removeData(item.getName(), item.getType()) > 1) {
            remove(item);
            notifyDataSetChanged();
        } else {
            Toast.makeText(mActivity, "No such item to delete", Toast.LENGTH_SHORT);
        }
        dbHelper.close();
        return true;
    }
});

Why is this happening?

A: if did not update data then create a method in class or fragment which is load adapter again when long press then call this method instead of notifydatasetchanged

A: Solved. Code inside if statement does not run. I thought I was checking all along with the Toast.makeText() and was so sure that it was indeed running because toast would not show, until I had realized that I forgot to call .show(). Sorry for the stupid mistake, I already found the problem.


text:
Q: User Mapped to a certificate in SQL I need to create a user ,who can log on to a contained DB.In this context what is the benefit of using a user mapped to a certificate?

A: The benefit of users mapped to a certificate is to use certificate signatures to allow a signed object (like a stored procedure) to have permissions the user executing it doesn't have at all.
For instance, you could have a stored procedure that does something unutterably horrible (SUMMON Cthulu), and you have to allow that for X bad business decision, but you don't want to give Bob permissions to just SUMMON any monster - what if they summoned a gremlin in your system!
In this case, you could create a user mapped to a certificate, and then sign the stored procedure with that certificate.  The certificate mapped user is given the GRANT SUMMON right, while Bob gets only GRANT EXECUTE spSummon_Cthulu.
Thus, Bob can execute spSummon_Cthulu, and that SP is allowed to SUMMON('Cthulu') because the user mapped to the certificate that signed the SP has that right.
WARNING: Every time spSummon_Cthulu is changed, you'll need to resign in.  This is deliberate - that way even if Bob is allowed to alter the procedure, and Bob changes it to SUMMON('gremlin'), the changed SP no longer has a valid signature... and is thus no longer allowed to use the SUMMON command.
P.S. SUMMON is used as a fictional example for simplicity - xp_cmdshell 'bcp xxx' vs xp_cmdshell 'format D:' is a better horrific example, but involves cross-database permissions that are more complex than is necessary.
P.P.S. this may also make more sense if you consider it in the context of a database with multiple schemas not all owned by the same owner.


text:
Q: Summing up decimals returned within task I'm trying to run through a list of 1-X items and process them in Tasks in order to speed up completion of processing (they make web requests that can sometimes take a short while to finish).  I'm trying to sum up a decimal that is returned when the processing is finished without looping through the list a second time.  As it is right now, the sum is overwritten by each task instead of being added to.
I can insert a short pause before adding the decimal to the sum and this seems to work fine, but I'm sure there is a better solution out there.
I've seen mentions of SyncLock but I can't use it on a Decimal.
Here is some code I wrote for testing. The .Process method just waits a random number of seconds and sets the .Value property to a random decimal.
Any suggestions for improvement and calculating the sum in a proper way?
    Try
        Dim lstItem As List(Of clsItem) = GetList()
        Dim lstViewItem As New List(Of ListViewItem)
        Dim lstTasks As New List(Of Task)()
        Dim decTotal As Decimal = 0.0
        For i As Int32 = 0 To lstItem.Count - 1
            Dim j As Int32 = i
            Dim t As Task = Task.Run(Sub()
                                         lstViewItem.Add(New ListViewItem(New String() {j, lstItem(j).Process()}))
                                         'System.Threading.Thread.Sleep(j * 1000)
                                         decTotal += lstItem(j).Value
                                     End Sub)
            lstTasks.Add(t)
        Next
        Task.WaitAll(lstTasks.ToArray())
        lstView.Items.AddRange(lstViewItem.ToArray())
        lstView.Items.Add("")
        lstView.Items.Add(decTotal)
    Catch ex As Exception
        Debug.WriteLine(ex.Message)
    End Try

A: You should be able to use SyncLock to resolve your issue. SyncLock can only be used on reference types. All that's needed is to create a new object that is within the scope of the current instance and then let SyncLock lock on that object.
Here's a short little console application that utilizes SyncLock. I significantly simplified what you had. I didn't really feel like making listViews and such, and rather than returning a random decimal it just returns 1 so that the results should be the number of loop iterations.
Option Strict On
Option Explicit On

Imports System.Threading.Tasks

Module Module1
    Sub Main()
        Dim lstTasks As New List(Of Task)()
        Dim SyncLockedTotal As Decimal = 0D
        Dim decTotal As Decimal = 0D
        Dim sLock As New Object
        For i As Int32 = 1I To 1000I
            Dim t As Task = Task.Run(Sub()
                                         Dim tempDecimal As Decimal = clsItem.Process()
                                         decTotal += tempDecimal
                                         SyncLock sLock
                                             SyncLockedTotal += tempDecimal
                                         End SyncLock
                                     End Sub)
            lstTasks.Add(t)
        Next
        Task.WaitAll(lstTasks.ToArray())
        Console.WriteLine(String.Format("Value for decTotal: {0}", decTotal.ToString))
        Console.WriteLine(String.Format("Value for SyncLockedTotal: {0}", SyncLockedTotal.ToString))

        Console.ReadLine()
    End Sub
End Module

Public Structure clsItem
    Public Shared Function Process() As Decimal
        Dim rnd As New Random(DateTime.Now.Millisecond)
        Threading.Thread.Sleep(rnd.Next(10I))
        Return 1D
    End Function
End Structure

NOTE: Your application settings must target .NET 4.5 in order to use Task.Run(), if you are targetting .NET 4 you will have to use Task.Factory.StartNew(). If you are targeting .NET 3.5 or lower, this won't work for you because you won't have the System.Threading.Tasks namespace available.


text:
Q: Replace string but preserve whitespace I want to replace a string, but preserve the outer white space, if that makes sense.
Ex:
" Hello world  "

To:
"  Whatever I want  "

I figured there was a quick way to do this via regular expressions, but I can't figure it out. Any help would be appreciated. Thanks!

A: In Ruby this works
"  this is a message   ".gsub /^(\s*)(.*?)(\s*$)/, '\1and this is another\3'
=> "  and this is another   "

A: Generally speaking, a regex that greedily matches ^\s*(.*)\s*$ and replaces the first capture group (inside the parens) should do it. But the particulars depend on the flavor of regex you are using.

A: To replace " Hello world " to " Whatever you Want ", you can do something like:
"^\s*(.*?)\s*$"


text:
Q: getting the type of a types properties I currently have a type pulled from a third party. i'd like to get the type of a property of that type. for typescript.
e.g.

type GivenType = {
    prop: string;
}

type desiredType = <<getTypeOf GivenType.prop>>

desiredType === string // true;

I'm looking for the actual syntax for <<getTypeOf GivenType.prop>>
mostly I've looked through the typescript documentation and found that extracting type is generally acted on objects or interfaces. such commands like typeof or returnType

A: You can get the type of a property like this:
type SomePropertyType = SomeType["SomeProperty"];

This is an "indexed access operator"; there are details in this documentation section.
E.g.
// number
type LengthPropertyType = String["length"];

// () => number
type GetFullYearType = Date["getFullYear"];

type GivenType = {
    prop: string;
}

// string
type DesiredType = GivenType["prop"];


text:
Q: Cyclic subgroup of $S_n$
Find the smallest natural number n ∈ ℕ such that $S_n$ contains a cyclic subgroup of order 101.

Proof: We seek the smallest n such that Sn contains a permutation of order 101. Permutation can be written in terms of a collection of disjoint cycles. Let  σ  be permutation of order 101 consisting of q disjoint cycle, and let the length be ki,…,kq. The order of the element will be equal to the least common multiple of the length cycle.
 By the fundamental theorem of arithmetic, any number can be uniquely decomposed into a product of powers of prime numbers. It is easy to see that 101 =1 • 101, so each of the ki's must have a prime decomposition consisting of 1 & 101. Hence smallest natural number is 1

Is this correct or I am missing? If missing what will be the correct way?

A: As you note, every permutation can be expressed as a product of disjoint cycles.  The order of such a product is given by the least common multiple of the cycle lengths.  The smallest $n$ such that $S_n$ contains a permutation of that form is the sum of the cycle lengths.
Since 101 is prime, the only disjoint cycle expression of a permutation of order 101 is a single cycle of length 101.  So $n$ = 101.
A more interesting problem is given by replacing 101 with a composite number, such as 12.


text:
Q: Drawing certain parts of image offset from the corner? I'm using a sprite sheet of sorts to load in spaceships. The documentation of Graphics.drawImage() states the arguments are
boolean Graphics.drawImage(Image img,
   int dstx1, int dsty1, int dstx2, int dsty2,
   int srcx1, int srcy1, int srcx2, int srcy2,
   ImageObserver observer);

However, the documentation says that dstx1 and dsty2 are the coordinates of the top left corner, and when you use dstx2 and dsty2 to specify the area drawn, the dimensions are (dstx2- dstx1) and (dsty2 - dsty1). Unless I'm misunderstanding how the function works, It appears that this only loads portions of the image form the corner. How could one draw a part of the image that is not connected to the lefthand corner, for drawing different parts of a sprite sheet?

A: public abstract boolean drawImage(Image img,
                                  int dx1,
                                  int dy1,
                                  int dx2,
                                  int dy2,
                                  int sx1,
                                  int sy1,
                                  int sx2,
                                  int sy2,
                                  ImageObserver observer)

Parameters:

*

*img - the specified image to be drawn. This method does nothing if img is null.

*dx1 - the x coordinate of the first corner of the destination rectangle.

*dy1 - the y coordinate of the first corner of the destination rectangle.

*dx2 - the x coordinate of the second corner of the destination rectangle.

*dy2 - the y coordinate of the second corner of the destination rectangle.

*sx1 - the x coordinate of the first corner of the source rectangle.

*sy1 - the y coordinate of the first corner of the source rectangle.

*sx2 - the x coordinate of the second corner of the source rectangle.

*sy2 - the y coordinate of the second corner of the source rectangle.

*observer - object to be notified as more of the image is scaled and converted.

the ds are the destination, meaning where you want the image to be drawn on your surface. The ss are the coordinates of the source image.  For both, the first corner being the upper left, and the second corner being the bottom right.
So you can think of the source image as like a focus section of the image to be drawn. You can use the source coordinates to determine the rectangle region to extract.
The destination coordinates layout how/where the the source region is actually drawn. So if you just want to move the drawn image along the x axis, then you just move the dx1 and the dx2. You can actually use the coordinates to resize the drawn region, by just specifying a coordinate rectangle larger or smaller than the source rectangle
            Source Image                     Destination panel
 sx1, sy1
    +---------------+---------+        +-----------------------------+
    |               |         |        |                             |
    | region to     |         |        | dx1, dy1                    |
    |        draw   |         |        |    +----------+             |
    |               |         |        |    |          |             |
    +---------------+         |        |    |          |             |
    |           sx2, sy2      |        |    +----------+             |
    |                         |        |            dx2, dy2         |
    |                         |        |                             |
    +-------------------------+        +-----------------------------+

Here's a running example.
Disclaimer: My calculations may be a little off. Not sure if I'm capturing each every section of the image. Just whipped this up really quick.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class NerdGirl extends JPanel {
    private static final int SPRITE_ROWS = 5;
    private static final int SPRITE_COLUMNS = 2;
    private static final int DELAY = 150;

    private int DIM_W;
    private int DIM_H;

    private int x1Src;
    private int y1Src;
    private int x2Src;
    private int y2Src;

    private BufferedImage img;

    public NerdGirl() {
        try {
            img = ImageIO.read(getClass().getResource("/resources/nerd-girl.jpg"));
        } catch (IOException ex) {
            Logger.getLogger(NerdGirl.class.getName()).log(Level.SEVERE, null, ex);
        }
        DIM_W = img.getWidth() / SPRITE_ROWS;
        DIM_H = img.getHeight() / SPRITE_COLUMNS;
        x1Src = 0;
        y1Src = 0;
        x2Src = x1Src + DIM_W;
        y2Src = y1Src + DIM_H;
        Timer timer = new Timer(DELAY, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (x1Src >= img.getWidth() - DIM_H - 5) {  // 5 to take care of precision loss
                    x1Src = 0;
                    x2Src = x1Src + DIM_W;
                    if (y1Src >= DIM_H - 5) { // 5 to take care of precision loss
                        y1Src = 0;
                        y2Src = y1Src + DIM_H;
                    } else {
                        y1Src += DIM_H;
                        y2Src = y1Src + DIM_H;
                    }

                } else {
                    x1Src += DIM_W;
                    x2Src = x1Src + DIM_W;
                }

                repaint();
            }
        });
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(img, 0, 0, getWidth(), getHeight(), x1Src, y1Src, x2Src, y2Src, this);
    }

    @Override
    public Dimension getPreferredSize() {
        return (img == null) ? new Dimension(300, 300) : new Dimension(DIM_W, DIM_H);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new NerdGirl());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}


text:
Q: Grid of plots - alignment I'm trying to plot several plots and graphics into Grid, but I have no success with proper alignment. Here is my code:
(*just allocating auxiliary variables*)
ClearAll;
SetDirectory[NotebookDirectory[]];
data = Import["MISFIT-GOF.DAT", "Table"];
parameters =
Unevaluated /@ {fmin, fmax, NFREQ, MT, dt, nc, MaxV, EM1, PM1, EM2,
PM2, EM3, PM3, EG1, PG1, EG2, PG2, EG3, PG3, TFEM, TFPM, FEM, FPM,
 TEM, TPM, TFRS1, TFRS2};
MapThread[Set, {parameters, Flatten[data]}];
df = (fmax - fmin)/(NFREQ - 1);(*frequency sampling*)
tstart = 0.;
tend = dt (MT - 1);
time = Table[i, {i, tstart, tend, dt}];
frequency = Table[i, {i, fmin, fmax, df}];

(*plotting*)
(*ArrayPlot of data of size (NFREQ = 569,MT = 3000) with AspectRatio->1*)
TFEM = Flatten[Import["TFEM1.DAT", "Table"]];
plotTFEM =
ArrayPlot[Reverse[Partition[TFEM, MT]], AspectRatio -> 1,
ColorFunction -> "TemperatureMap", PlotLegends -> Automatic];

(*plot below ArrayPlot*)
TEM = Flatten[Import["TEM1.DAT", "Table"]];
maxTEM = Max[Abs[TEM]];(*max. value*)
TEM = Partition[Riffle[time, TEM], 2];
plotTEM =
ListLinePlot[TEM, PlotRange -> {{tstart, tend}, {-maxTEM, maxTEM}},
Frame -> True,
FrameLabel -> {{None,
Style["TEM", Black, 14]}, {Style["TIME[s]", Black, 14], None}},
FrameTicks -> {{None, All}, {All, None}},
FrameTicksStyle -> Directive[Black, 12],
AxesOrigin -> {tstart, -maxTEM}];

(*plot on left side from ArrayPlot*)
FEM = Flatten[Import["FEM1.DAT", "Table"]];
maxFEM = Max[Abs[FEM]];(*max. value*)
FEM = Partition[Riffle[frequency, FEM], 2];
FEM[[All, {1, 2}]] = FEM[[All, {2, 1}]];(*change of axis*)
plotFEM =
ListLinePlot[FEM, PlotRange -> {{-maxFEM, maxFEM}, {fmin, fmax}},
Frame -> True,
FrameLabel -> {{Style["Frequency[Hz]", Black, 14], None}, {None,
Style["FEM", Black, 14]}},
FrameTicks -> {{Automatic, None}, {None, All}},
FrameTicksStyle -> Directive[Black, 12],
AxesOrigin -> {maxFEM, fmin}, AspectRatio -> GoldenRatio];

(*plot below TEM plot*)
S1 = Transpose[
Delete[Transpose[Import["S1.DAT", "Table"]], {{3}, {4}}]];
maxS1 = Max[Abs[S1[[All, 2]]]];
S1[[All, 2]] /= maxS1;(*normalization*)
S2 = Transpose[
Delete[Transpose[Import["S2.DAT", "Table"]], {{3}, {4}}]];
maxS2 = Max[Abs[S2[[All, 2]]]];
S2[[All, 2]] /= maxS2;(*normalization*)
plotS = ListLinePlot[{S1, S2}, PlotRange -> {{tstart, tend}, {-1, 1}},
PlotLegends -> Placed[LineLegend[{"S1", "S2"}], {0.85, 0.85}],
Frame -> True,
FrameLabel -> {{None,
Style["Amplitude[m]", Black, 14]}, {Style["Time[s]", Black, 14],
None}},
FrameTicks -> {{None, All}, {All, None}},
FrameTicksStyle -> Directive[Black, 12]];

(*finally creating a grid of plots*)
With[{size = 300},
Grid[{{Show[plotFEM, ImageSize -> {Automatic, size},
ImagePadding -> {{40, 5}, {Automatic, 40}}],
Show[plotTFEM, ImageSize -> {Automatic, size},
ImagePadding -> {{Automatic, 43}, {Automatic, 40}}]},
{Show[Graphics[{Black, Circle[]}], ImageSize -> {100, 100},
ImagePadding -> {{5, Automatic}, {5, 5}}],
Show[plotTEM, ImageSize -> {size, Automatic},
ImagePadding -> {{0, 50}, {Automatic, 5}}]},
{Show[Graphics[{White, Circle[]}], ImageSize -> {100, 100},
ImagePadding -> {{5, Automatic}, {5, 5}}],
Show[plotS, ImageSize -> {size, Automatic},
ImagePadding -> {{0, 50}, {Automatic, 5}}]}
}, Spacings -> {0, 0}]]

This is the output:

I would like to get something like this(in terms of spacing and alignment):

The last row of Grid contains white circle that's because in the last row I only want to have plotS. PlotS can have a same size as plotTEM or can be stretched across whole row. Please note that size and other parameters are not fixed and can be modified as one wish. The input files can be found here.
Any help, suggestion or improvement of the code are more than welcomed. Thank you in advance!


text:
Q: No continuous transformation $f([a,b])= ]a,b[$ $ a,b\in\mathbb R$ with $a<b $.
Now I want to show that there is NO continuous transformation $f: [a,b] \to \mathbb R $ with $f([a,b])= ]a,b[$

How can I proove that this transformation don't exist?

A: As suggested in the comments, the continuous image of a compact set is compact, and $]a,b[$ is not compact. For a more elementary proof, supposed such an $f$ existed. Then the function $[a,b]\to \mathbb{R}$, $x\mapsto \frac{1}{f(x)-a}$ is continuous and unbounded, but a function from $[a,b]$ to $\mathbb{R}$ must be bounded.

A: $f$ is continuous and $[a,b]$ is compact, so that $f([a,b])$ is also compact.

A: By the extreme value theorem, $f$ must attain a maximum $M$ on $[a,b]$, which by hypothesis is strictly smaller than $b$.  Hence the number $\frac{M+b}{2}$ is not in the image of $f$.


text:
Q: How to target NSNotification for different MPMoviePlayerControllers? I'm trying to create an app that displays a unique info page after different videos play. Currently, I am displaying the info page with the moviePlayBackDidFinish notification method but I can't figure out how to customize it for different videos. Here's my code...thanks very much in advance!!
EDIT after subclassing movieplayercontroller...how do I use new property in NSNotification?
//subclassed movieplayercontroller
myMovie.h
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>

@interface myMovie: MPMoviePlayerViewController
{
    myMovie *videoPlayer;
}

@property (nonatomic, strong) NSString *movieTitle;

@end

myMovie.m
#import "myMovie.h"

@interface myMovie ()

@end

@implementation myMovie

@synthesize movieTitle;

@end

//main viewcontroller
videoPlayViewController.h
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import "View2.h"
#import "myMovie.h"

@interface videoPlayViewController : UIViewController

-(IBAction) playMovie;

videoPlayViewController.m
#import "videoPlayViewController.h"
#import "myMovie.h"

@interface videoPlayViewController ()

@end

@implementation videoPlayViewController

-(void)playMovie
{
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                         pathForResource:@"sample" ofType:@"mov"]];

   myMovie *videoPlayer =  [[myMovie alloc]
                    initWithContentURL:url];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:videoPlayer.moviePlayer];

   videoPlayer.moviePlayer.controlStyle = MPMovieControlStyleDefault;
    videoPlayer.moviePlayer.shouldAutoplay = NO;
    videoPlayer.movieTitle = @"sample";
    [self.view addSubview:videoPlayer.view];
    [videoPlayer.moviePlayer setFullscreen:YES animated:YES];

}

- (void) moviePlayBackDidFinish:(NSNotification*)notification {
    MPMoviePlayerController *player = [notification object];
    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:MPMoviePlayerPlaybackDidFinishNotification
     object:player];

    NSLog(@"Is this working?");

    View2 *second =[[View2 alloc] initWithNibName:nil bundle:nil];

    [self presentModalViewController:second animated:YES];

    [player.view removeFromSuperview];

}

A: Create a subclass of MPMoviePlayerController with a property (or many properties) to hold the info that you need when the video ends.  Then, when the video ends, you'll get your customized MPMoviePlayerController in the notification object, and you can inspect the properties to find out whatever it was that you wanted to know about the movie that ended.


text:
Q: Comparing elements in Matlab and plotting I got 2 files that contain numbers. One number I use to calculate the max compression of a bone while the other number is the compression that is on the bone. If the second number is higher than the max compression I want to plot the dot in red, if it is less then it should be green.
My problem is that all my dots come out as red even though majority of the should be green. I have tried to debug it by printing out the H and C vector and there are like 100 numbers that should be red and the rest green. Any help or hints are appreciated.
This is my code
p=VarName5;
c=VarName7*2.5; %%The compression that is on the bone
if p<0.317;
  H=10500*p.^1.88; %%Calculate max compression the bone handles
else
  H=114*p.^1.72; %%Calculate max compression the bone handles
end
if(c < H) %% if the compression on the bone is smaller then max compression
  plot(p,c,'+G') %% plot using green+
  hold on
else
  plot(p,c,'+R')  %if the compression is higher than max compression use red+
end
hold off

A: You can create a logical vector where all elements larger than the max values are 1, and all others are 0:
ind = c > H;
plot(p(ind),c(ind),'+R')
hold on
plot(p(~ind),c(~ind),'+G')

You may then plot them separately.
To illustrate with some random data:
c = repmat([1:6 7:-1:1],1,2);  %// The compression
H = rand(1,numel(c))*8; %// The compression the bone handles (in this case: random)
p = 1:numel(c);

ind = c > H;  %// Index of elements where the bone is compressed more than it handles.
plot(p(ind),c(ind),'+R')
hold on
plot(p(~ind),c(~ind),'+G')

I'll leave it up to you to figure out how to implement it into your code.


text:
Q: Where to learn Euclidean geometry in-depth? I am interested in Euclidean geometry and using compass and rulers to do constructions. I took geometry in high school but I feel like it didn't go in-depth enough. Where can I learn this online? I am interested in  as a hobby.

A: There are two more recent books I like:

*

*Stillwell's "The Four Pillars of Geometry"

*Hartshorne's "Geometry: Euclid and beyond"

A: I suggest browsing the forums and resources at Art of Problem Solving. As for books, Coxeter's Geometry Revisited is excellent.


text:
Q: Custom error pages for the new blog Currently going to a page that doesn't exist on the blog, like http://blog.stackexchange.com/secretunicornpage gives the standard IIS error page.
On other (all?) network sites you get a custom page, such as https://stackexchange.com/secretunicornpage
Could a custom error page be added?

A: The new 404 page is live.
just this time, please don't follow the advice in the last sentence.
credits go to me and Jon Chan


text:
Q: What do we mean if a solution to some PDE is said to be nondegenerate? I know that there is a typical example:
$$\begin{cases}\tag{1}
\Delta u-u+u^p=0,\ u>0,\\
\quad\quad u\in H^1(\mathbb{R}^n),
\end{cases}
$$
where $1<p<2^*-1$. Denote the solution to (1) by $U$ and its linearized operator by $L$, namely
$$L(\phi)=\Delta \phi-\phi+pU^{p-1}\phi.$$
Then $U$ is said to be nondegenerate since the kernel of the linearized operator is $span\left\{\frac{\partial U}{\partial x_1},\dots,\frac{\partial U}{\partial x_n}\right\}$. But when we consider the problem:
$$\begin{cases}\tag{2}
\Delta u+u^{2^*-1}=0,\ u>0,\\
\quad\quad u\in D^{1,2}(\mathbb{R}^n),
\end{cases}
$$
the kernel of the corresponding linearized operator is $span{\left\{\frac{\partial U_\mu}{\partial \mu}\Big|_{\mu=1},\frac{\partial U_1}{\partial x_1},\dots,\frac{\partial U_1}{\partial x_n}\right\}}$ where $U_\mu$ is the solution to (2) with parameter $\mu$ and thus the definition of nondegeneracy of $U_\mu$ may be changed? Anyway, My question is what is the relation between the nondegeneracy of solution and the kernel of its linearized operator? In other words, what requirements will the kernel of the linearized operator satisfy if the solution to some given PDE is said to be nondegenerate?
By the way,  I also want to know the relation between the uniqueness of solution and the nondegeneracy of it since many say that they are two very closely related concepts but do not explain it for details. Thanks!


text:
Q: How to count number of rows using JPA? I try to count number of rows using JPA.I want to use where clause
however I can't.
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where();  //how to write where clause
return entityManager.createQuery(cq).getSingleResult();

How can I set where clause forexample where age="45".
Thanks in advance.

A: EntityManagerFactory emf =
                    Persistence.createEntityManagerFactory("your table name");
            EntityManager em = emf.createEntityManager();

            // JPA Query Language is executed on your entities (Java Classess), not on your database tables;

            Query query = em.createQuery("SELECT count(*) FROM your Classname WHERE ... etc");
            long count = (long) query.getSingleResult();

A: The best and simple way in jpa :
public interface YourEntityRepository extends JpaRepository<YourEntity, Serializable> {

Long countByAgeGreaterThan(Integer age);

}

A: Use ParameterExpression. Note: Untested.
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
ParameterExpression<Integer> p = qb.parameter(Integer.class);
q.where(qb.eq(c.get("age"), 45));
return entityManager.createQuery(cq).getSingleResult();

Reference.

A: If you use EntityManager.createQuery() instead of the CriteriaBuilder it looks like this:
final TypedQuery<Number> query = em.createQuery("SELECT COUNT(e) FROM MyEntity e WHERE e.age = :age", Number.class);
query.setParameter("age",45);
final long count = query.getSingleResult().longValue();

A: you can use the Query parameter,
Example :
StringBuilder strQuery ;
    strQuery= new StringBuilder();
    try {
        strQuery.append("FROM SSS s where s.age:age");
        Query query = this.getEntityManager().createQuery(
                strQuery.toString());
        query.setParameter("age", 45);
    } catch (Exception e) {
        LOGGER.info("Erreur", e);
    }

it's useful for you?


text:
Q: How to animate the vector field? As the question, how do I animate a series of plots instead of printing each individual plot? Thanks a lot!!!

import numpy as np
from matplotlib import pyplot as plt
from scipy.integrate import odeint
import matplotlib.animation as animation
%matplotlib inline

 # Define vector field
def vField(x,t,a):
    u = 2*x[1]
    v = -x[0] + a*(x[1] - 1/4 * x[1]**2)
    return [u,v]

vec = [-10,-5,0,5,10]

for a in vec:
    # Plot vector field
    X, Y = np.mgrid[-2:2:20j,-2:2:20j]
    U, V = vField([X,Y],0,a)

    fig, ax = plt.subplots(figsize=(10, 7))
    ax.quiver(X, Y, U, V)
    plt.pause(0.01)

plt.show()

A: You have to declare your fig, ax before the loop and clear it between each quiver.
Indeed, you want to use only one figure and not create one by iteration. Moreover, you want to clear the figure between each iteration or all plots will be shown on top of the others.
fig, ax = plt.subplots(figsize=(10, 7))

for a in vec:
    # Plot vector field
    X, Y = np.mgrid[-2:2:20j,-2:2:20j]
    U, V = vField([X,Y],0,a)

    ax.clear()
    ax.quiver(X, Y, U, V)
    plt.pause(0.01)

Please note that you will not see anything with your current vec because it is too short and the pause is 0.01. With a longer one you will see a smooth drawing.

A: You can use matplotlib's FuncAnimation:
import numpy as np
from matplotlib import pyplot as plt
from scipy.integrate import odeint
from matplotlib.animation import FuncAnimation

 # Define vector field
def vField(x,t,a):
    u = 2*x[1]
    v = -x[0] + a*(x[1] - 1/4 * x[1]**2)
    return [u,v]

vec = np.linspace(-10, 10, 100)

fig, ax = plt.subplots()
X, Y = np.mgrid[-2:2:20j,-2:2:20j]
U, V = vField([X,Y],0, vec[0])
q = ax.quiver(X, Y, U, V)

def animate(i):
    U, V = vField([X,Y],0, vec[i])
    q.set_UVC(U, V)

ani = FuncAnimation(fig, animate, frames=len(vec), repeat=False)
plt.show()


text:
Q: create coupon programmatically How to create rule  and action in shopping cart price rule in magento programmatically for the condition subtotal equal to or greater than 500.
Here Image that condition i want to write programmatically
like that:
conditions => array(
                        array(
                            'type' => 'salesrule/rule_condition_combine',
                            'aggregator' => 'all',
                            'value' => 1,
                            'new_child' => null
                        )
                    )


text:
Q: Mac Mini 2018 Reboot Loop? I have a newly acquired Mac Mini 2018 that cannot get out of reboot loops.
I've already formatted the drive using target disk mode and trying to install a fresh copy of Mojave. There is nothing to restore or backup at point. I've tried:

*

*resetting pram and nvram

doesn't make any difference just reboot loops

*making a bootable usb using the Apple Mojave install image and terminal instructions

the usb can be read, I boot holding down Apple key. The option will be given to install Mojave, once I hit enter, it doesn't take me to MacOS utilities, it reboots and continues to loop

*use internet recovery to install OS
i can successfully enter internet recovery mode, hardliners Ethernet. the progress bar goes to the end in about 5 minutes and instead of entering the installation program, it gets into a reboot loop and will restart in internet recovery mode and start the process all over again

*hold down d during boot to get diagnostic mode
this doesn't do anything. I don't know if this is because the drive is clean. I can hold down Apple D and it will take me internet recovery and then restart loop.

*hold down shift during boot to safe mode.

this doesn't work because there is no OS on the internal ssd

*install Mojave on an USB and hold down Apple to boot, I can get the drive to appear but hitting enter will just restart instead of trying to load the OS

any ideas? Is this computer a lemon?

A: Wiping the entire internal storage may have been a bad idea, as it also contains the Recovery Partition, and some 'keys' used to authenticate Secure Boot. (Also note that by default, you can't boot to a USB external: you need to set the Secure Boot options to allow that.)
https://support.apple.com/en-gb/HT208198
Your best bet is to install it from another Mac using Target Disk Mode.

A: I ended up finding a solution. For anyone else that runs into this problem, I used Apple Configurator 2, put the bricked Mac mini in DFU mode  (I didn't know you could with MacOS products) and another Mac to revive or restore the computer. The computer will install BridgeOS which will get the computer back to a state where you can reinstall the OS. I believe in my situation, the security firmware was corrupted during a previous failed installation. More here:
https://support.apple.com/guide/apple-configurator-2/revive-or-restore-a-mac-with-apple-silicon-apdd5f3c75ad/mac


text:
Q: Chrome opens to untitled blank page I am working on a computer that had a lot of malware on it. I removed most of it to my knowledge. Now when I open Google Chrome I get a blank untitled page, with the traditional sign-in URL on top.  If I go to the settings, the settings tab opens up blank as well. All pages that I navigate to will come up blank as well. The browser doesn't even perform a postback, it is like it is unresponsive. I did some googling and have seen people with similar errors, but no fixes.
IE 8 works great without issues.
Re-installing Chrome was the first thing I did!
Any suggestions?

A: This was not my computer but one i was fixing for a friend. The issue was the it was running in Compatibility mode for windows XP service pack 2. After re installs it set it self back to that i am assuming because i did not set it to that. Thanks for the help .

A: Check out the compatibility mode in the shortcut's properties.
Mine was checked with Windows XP SP2.
Unchecked it, now Chrome works perfect!
Seems stupid, but it worked.

A: I was having the same problem with Chrome & as I was performing the solution here I discovered a different problem. "Run this program as an administrator" box was checked in the Compatibility tab. After clearing the box & applying it Chrome went right back to work as usual. Yeah!


text:
Q: Setting Response.StatusCode using MvcContrib.TestHelpher I've got a very simple test method, using MvcContrib.TestBuilder to setup the controller (and mock the HttpContext etc...)
    [Test]
    public void http404_returns_status_code_of_404()
    {
        var builder = new TestControllerBuilder();
        controller = new ErrorController();

        builder.InitializeController(controller);

        var result = controller.Http404();

        Assert.That(controller.Response.StatusCode, Is.EqualTo(404));
    }

My implementation looks as simple as:
    public ActionResult Http404()
    {
        Response.StatusCode = 404;

        return View();
    }

However, my test is always failing, because Response.StatusCode is always 0
Even if I debug, and evaluate Response.StatusCode after Response.StatusCode = 404;
 it is still 0

A: The HttpResponse instance is a mock. So you should assert it like this:
controller.Response.AssertWasCalled(x => x.StatusCode = 404);

instead of:
Assert.That(controller.Response.StatusCode, Is.EqualTo(404));

But instead of setting some status codes in my controller action I would simply return the proper ActionResult:
public ActionResult Http404()
{
    return new HttpNotFoundResult();
}

and test it like this:
// arrange
var builder = new TestControllerBuilder();
var sut = new ErrorController();
builder.InitializeController(sut);

// act
var actual = controller.Http404();

// assert
actual.AssertResultIs<HttpNotFoundResult>();

Looks more readable IMHO.


text: Q: Question about repetition of numbers in the continued fraction of Euler-Mascheroni Constant I noticed in the Continued Fraction expansion of the Euler-Mascheroni Constant that some numbers recur a lot, like the number 1 or the number 10. Is it known if there are infinitely many of the same number in the Continued Fraction expansion of the Euler-Mascheroni Constant? In particular, does 1 appear infinitely many times?


text:
Q: Progress bar on scroll to the right - React - e-commerce product row I'm trying to make a progress bar that starts as the user scrolls to the right for a row of products for a sample e-commerce site. I've been getting a number of type errors to which I've made adjustments, but I'm now still getting the error
"TypeError: Cannot read property 'addEventListener' of null" for line 12.
Please could someone provide assistance so it will work? (fyi pardon this code, still a bit of a React newbie). Thanks!
import React from 'react';
import { taskData } from "./cdg-data";
import ProgressBar from './progress';

class CDG extends React.Component {
  state = {
    scrollPosition: 0
  }

  listenToScrollEvent = () => {
    const element = document.querySelector("CDG");
    element.addEventListener("scroll", () => {
      requestAnimationFrame(() => {
        element.calculateScrollDistance();
      });
    });
  }

  calculateScrollDistance = () => {
    const element = document.querySelector("CDG");
    const pixels = element.scrollLeft; // CURRENT number of pixels scrolled by the user

    const elementWidth = element.clientWidth; // width of just the element (no scrolling)
    const fullElementWidth = element.scrollWidth; // full total distance of the element (with scrolling)

    const totalScrollableDistance = fullElementWidth - elementWidth;
    const scrollPosition = Math.floor(pixels / totalScrollableDistance * 100) // gets the percentage that the user has scrolled

    element.setState({
      scrollPosition,
    })
  }

  componentDidMount() {
    this.listenToScrollEvent();
  }

  render() {
    return(

THE COLLECTION

        {taskData.map(item => {
          return (

{item.title}

{item.price}

          );
        })}

        <ProgressBar scroll={this.state.scrollPosition + '%'}/>

    );
  }
}

export default CDG;

A: The syntax for querySelector is incorrect. Try prefixing with a . here since you are selecting by a class:
const element = document.querySelector('.CDG')
For future reference, MDN's docs on writing query selectors for different types of ID/selectors/tags
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

A: This is the final correct solution if anyone needs it:

import React from 'react';
import { taskData } from "./cdg-data";
import ProgressBar from './progress';

class CDG extends React.Component {
  state = {
    scrollPosition: 0
  }

  listenToScrollEvent = () => {
    const element = document.querySelector(".CDG");
    element.addEventListener("scroll", () => {
      requestAnimationFrame(() => {
        this.calculateScrollDistance();
      });
    });
  }

  calculateScrollDistance = () => {
    const element = document.querySelector(".CDG");
    const pixels = element.scrollLeft; // CURRENT number of pixels scrolled by the user

    const elementWidth = element.clientWidth; // width of just the element (no scrolling)
    const fullElementWidth = element.scrollWidth; // full total distance of the element (with scrolling)

    const totalScrollableDistance = fullElementWidth - elementWidth;
    const scrollPosition = Math.floor(pixels / totalScrollableDistance * 100) // gets the percentage that the user has scrolled

    this.setState({
      scrollPosition,
    })
  }

  componentDidMount() {
    this.listenToScrollEvent();
  }

  render() {
    return(

THE COLLECTION

        {taskData.map(item => {
          return (

{item.title}

{item.price}

          );
        })}

        <ProgressBar scroll={this.state.scrollPosition + '%'}/>

    );
  }
}

export default CDG;
import React from 'react';

const ProgressBar = (props) => {
    const { scroll } = props;

    const containerStyles = {
        height: 5,
        width: '33%',
        backgroundColor: '#939191',
        margin: '0 auto 50px',
    }

    const fillerStyles = {
        height: '100%',
        width: `${scroll}`, // dependent on JavaScript scroll, not the percentage completed as in the example
        backgroundColor: '#A50209',
        textAlign: 'center'
    }
    return (

    );
};

export default ProgressBar;


text:
Q: laravelffmpeg color filter effects How can I apply a color filter effect in my video using laravel-ffmpeg package and what is the proper way to do it?
The package have a custom filters but i dont know how to translate the ffmpeg command for color filter to laravel-ffmpeg.
From FFMPEG cmd
"eq=brightness=0.3:saturation=1.3:contrast=1.1"

To LARAVEL-FFMPEG package
->addFilter('eq=brightness=0.3:saturation=1.3:contrast=1.1')

And I saw that there are -vf in custom Filter in laravel-ffmpeg package, so i try to use the ffmpeg cmd command for color filter, I dont know the proper way to use it in laravel.
Here are my code with EncodingException error

FFMpeg::fromDisk('videos-temp')
        ->open('buck.mp4')
        ->export()
        ->toDisk('videos-temp')
        ->addFilter('eq=brightness=0.3:saturation=1.3:contrast=1.1')
        ->inFormat(new \FFMpeg\Format\Video\X264)
        ->save('sample.mp4');

A: Maybe you should try to use the custom method.
Try something like:
use FFMpeg\Filters\Video\VideoFilters;

///
->addFilter(function (VideoFilters $filters) {
  $filters->custom('eq=brightness=0.3:saturation=1.3:contrast=1.1');
})

or maybe:
->addFilter('eq', 'brightness=0.3:saturation=1.3:contrast=1.1')

I haven't tried it, I'll let you reply in comments if it doesn't work.


text:
Q: How to  Entity with dynamic fields into Spring Roo Entity I have a Logging Entity that needs to map an Entity that is a dynamic set of Properties where the JSON data looks like this:
{
"timestamp" : ISODate("2012-01-17T22:30:19.839Z"),
"level" : "INFO",
"thread" : "main",

"properties" : {
    "cookieId" : "EDE44DC03EB65D91657885A34C80595E"
    "field-1" : "foo"
    "field-n" : "bar"
},

"applicationName" : "D2",
"eventType" : "Development"
}

How can I create a Properties object that is dynamic for pulling fields?
Any help would be greatly appreciated.

A: U should create field like java.util.Map .
example:
field other --fieldName properties --type java.util.Map
I try that with web mvc, but it's not working property, because a custom editor not exist for this type.....
So if U wanna use with spring mvc U have to write your custom editor for that.
PS: after you created this field recommended change that generic type to <String,Object>...


text:
Q: (Script)How to start gnu screen interactively and then run some command in it? What I want to achieve is as the following:

*

*Start from bash in some terminal

*Run gnu screen: exec screen

*Start my desktop session in background: startx &

*So now I end up with a terminal with screen running and X running in backgroud(in some vt) ready to use and connect from elsewhere through screen.

But I want to automate the above procedure in a script(in fact to put it in my ~/.bashrc). What's the simple and elegant way to do it?
The closest shot I got is like this:
exec screen bash -c "startx; bash"

but this way startx cannot get into background. That is,
exec screen bash -c "startx &; bash"

won't work.
Also, I ran into this thread when googling. But
exec screen bash -i << EOF
startx &
exec < /dev/tty
EOF

don't work either. I also tried
exec screen bash -i --rcfile /tmp/somefile

with startx & in /tmp/somefile. Again not working.
Any ideas?

A: Both & and ; are command terminators; you can only use one or the other.
exec screen bash -c "startx & bash"


text:
Q: How to configure the pylintrc config file on my Mac system I was getting a Warning: Config file not used, Using default configuration when i ran pylint
I ran pylint--generate-rcfile> ~/.pylintrc.
then i got two warning messages :
Warning: option include-ids is deprecated and ignored.
Warning: option symbols is deprecated and ignored.
I solved these errors by commenting out the below line in pylintrc
    #include-ids


text:
Q: Can jQuery.getJSON put a domain's cookies in the header of the request it makes? (Note: See also the related question Can browsers react to Set-Cookie specified in headers in an XSS jquery.getJSON() request?)
I can't seem to set a cookie (whose name is mwLastWriteTime) in the request header of a JSON operation.  The request itself is a simple one from the Freebase MQL tutorials, and it is working fine otherwise:
// Invoke mqlread and call the function below when it is done.
// Adding callback=? to the URL makes jQuery do JSONP instead of XHR.
jQuery.getJSON("http://api.sandbox-freebase.com/api/service/mqlread?callback=?",
{query: JSON.stringify(envelope)},   // URL parameters
displayResults);                     // Callback function

I'd hoped that I could set this cookie with something along the lines of:
$.cookie('mwLastWriteTime', value, {domain: ".sandbox-freebase.com"});

Unfortunately, looking in FireBug at the outgoing request header I see only:
Host    api.sandbox-freebase.com
User-Agent  [...]
Accept  */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  115
Connection  keep-alive
Referer [...]

But if I don't specify the domain (or if I explicitly specify the domain of the requesting site) I can get mwLastWriteTime to show up in the headers for local requests.  Since the .sandbox-freebase.com domain owns these cookies, shouldn't they be traveling along with the GET?  Or does one need a workaround of some sort?
My code is all JavaScript, and I would like to set this cookie and then call the getJSON immediately afterward.

A: You cannot set a cross-domain cookie, because that would open the browser (and therefore the user) to XSS attacks.
To quote from the QuirksMode.org article that I reference above:

Please note that the purpose of the
  domain is to allow cookies to cross
  sub-domains. My cookie will not be
  read by search.quirksmode.org because
  its domain is www.quirksmode.org .
  When I set the domain to
  quirksmode.org, the search sub-domain
  may also read the cookie. I cannot set
  the cookie domain to a domain I'm not
  in, I cannot make the domain
  www.microsoft.com . Only
  quirksmode.org is allowed, in this
  case.

If you want to make cross-site request with cookie values you will need to set up a special proxy on a server you control that will let you pass in values to be sent as cookie values (probably via POST parameters).  You'll also want to make sure that you properly secure it, lest your proxy become the means by which someone else's private information is "liberated".

A: Are you running all of your tests through localhost?  Are you using IE?  If so it will be enforcing its own special brand of security requirements and likely dumping your cookies.  Open fiddler and use http://ipv4.fiddler to bypass that.
If that type of trickery is not going on (as it appears you are using FireFox) , it may also be the case that you do need to explicitely set the cookie's domain to be the same as the domain of your JSON request.  A browser won't send cookies set for domain A to a request to domain B. I am not 100% sure this is the case though.


text:
Q: How to convert apiVersion of Kubernetes objects? As kubectl convert is deprecated since v1.14 and will be removed in v1.17, how do you convert Kubernetes object's API versions?
Are there other easy and safe solutions for doing that?

A: This is being discussed in https://github.com/kubernetes/kubectl/issues/725. At the moment there is no alternative for this command.
The plan was to remove it on 1.17 but I have 1.18 running and the command is still working.
I would say that for now you don't need to worry about alternatives as it still works.
$ kubectl version
Client Version: version.Info{Major:"1", Minor:"18", GitVersion:"v1.18.2", GitCommit:"52c56ce7a8272c798dbc29846288d7cd9fbae032", GitTreeState:"clean", BuildDate:"2020-04-16T11:56:40Z", GoVersion:"go1.13.9", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"18", GitVersion:"v1.18.2", GitCommit:"52c56ce7a8272c798dbc29846288d7cd9fbae032", GitTreeState:"clean", BuildDate:"2020-04-16T11:48:36Z", GoVersion:"go1.13.9", Compiler:"gc", Platform:"linux/amd64"}

$ kubectl convert --help
Convert config files between different API versions. Both YAML and JSON formats are accepted.

 The command takes filename, directory, or URL as input, and convert it into format of version specified by
--output-version flag. If target version is not specified or not supported, convert to latest version.

 The default output will be printed to stdout in YAML format. One can use -o option to change to output destination.

Examples:
  # Convert 'pod.yaml' to latest version and print to stdout.
  kubectl convert -f pod.yaml

  # Convert the live state of the resource specified by 'pod.yaml' to the latest version
  # and print to stdout in JSON format.
  kubectl convert -f pod.yaml --local -o json

  # Convert all files under current directory to latest version and create them all.
  kubectl convert -f . | kubectl create -f -

Options:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
  -f, --filename=[]: Filename, directory, or URL to files to need to get converted.
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
      --local=true: If true, convert will NOT try to contact api-server but run locally.
  -o, --output='yaml': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --output-version='': Output the formatted object with the given group version (for ex: 'extensions/v1beta1').
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --validate=true: If true, use a schema to validate the input before sending it

Usage:
  kubectl convert -f FILENAME [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

A: kubectl apply -f pod.yaml --dry-run=client -o json


text:
Q: Eclipse Java IDE JUnit5: junit.jupiter.api.Assertions is not accessible I'm new to the whole programming stuff but here's my problem:
I used to add my JUnit test cases in Eclipse by right clicking on the project, and just add New > JUnit Test Case.
Currently, I am not able to implement any test methods because Eclipse tells me on the line
import static org.junit.jupiter.api.Assertions.*;

the error message
The type org.junit.jupiter.api.Assertions is not accessible.

Error I get in the IDE:

I tried the following:

*

*Reinstalling Eclipse, using a fresh workplace.

*Adding the JUnit to Build path

Nothing helped.
It worked and works in older projects just fine.
Here is how the Package Explorer looks:

What am I missing?

A: You use the Java Platform Module System (JPMS) by having a module-info.java file in the default package probably without the required requires <module>; statement. JPMS was introduced in Java 9.
Do one of the following:

*

*Delete the module-info.java file (if needed, you can recreate it via right-clicking the project folder and choosing Configure > Create module-info.java)

*In module-info.java add the corresponding requires statement, e.g. by going to the line with the import statement and using the corresponding Quick Fix (Ctrl+1)


text:
Q: Move file and folder with progress bar in c# window form Sir i want to move folder and file with progress bar in c# window form. kindly anybody give me helpful material.

A: Basically, you will need to use RunWorkerAsync.
RunWorkerAsync starts an execution of a background operation. ( copy files etc..)
You will need to connect your progressbar with this method.
Check this answer to have a practic example:
Running a method in BackGroundWorker and Showing ProgressBar


text:
Q: New to Parse, not able to sign up a ParseUser I am just following the basic Parse quickstart guide found here:
https://www.parse.com/apps/quickstart#social/mobile/android/native/new
Everything compiled and ran just fine, but I checked and found that no user was actually being signed up on Parse. I checked the log and here is the error I am getting:
PARSE.COM﹕ FAILEDjava.lang.IllegalArgumentException: Cannot save a ParseUser until it has been signed up. Call signUp first.-1

Here is the code I am working with. As you can see, I just copied the tutorial exactly with the addition of outputting to the Log.
public class ParseApplication extends Application {

  @Override
  public void onCreate() {
  super.onCreate();

  // Initialize Crash Reporting.
  ParseCrashReporting.enable(this);

  // Enable Local Datastore.
  Parse.enableLocalDatastore(this);

  // Add your initialization code here
  Parse.initialize(this, "myappid", "mykey");

  ParseUser.enableAutomaticUser();
  ParseACL defaultACL = new ParseACL();
  // Optionally enable public read access.
  // defaultACL.setPublicReadAccess(true);
  ParseACL.setDefaultACL(defaultACL, true);

  ParseUser user = new ParseUser();
  user.setUsername("my name");
  user.setPassword("my pass");
  user.setEmail("email@example.com");

  // other fields can be set just like with PareObject
  user.put("phone", "650-555-0000");

  user.signUpInBackground(new SignUpCallback() {
        public void done(ParseException e) {
            if (e == null) {
                Log.e("PARSE.COM", "SUCCESS");
            } else {
                Log.e("PARSE.COM","FAILED" + e.getMessage() + Integer.toString(e.getCode()));
                // Sign up didn't succeed. Look at the ParseException
                // to figure out what went wrong
            }
        }
    });
    }
  }

I don't understand why the error is prompting me to call signUp first, is that not exactly I am doing with signUpInBackground? Any help would be greatly appreciated.

A: it looks like a same bug.
https://developers.facebook.com/bugs/426365424187686/
if you delete "Parse.enableLocalDatastore(this);" it will be work fine.
(API level doesn't matter)
and.. they assured me that they will fix the bug with next release.
but despite of updates(1.8.2->1.9.0) it is remained yet.
i'm sorry about my broken english.


text:
Q: jQuery .live event propagation I have a little problem with jQuery .live method. I am using it for catching ajax events for Google Analytics on my website, but in case I have a link with an inner image, the click event is fired up from the image and my live binded click event does not catch it.
I really dont like to add these events manually everytime after changing content and I dont like to bind it to the image (because of the missing href parameter, this case I had use some .parent method), so what is the best way how to handle this?
Notice: I am not sure about efficiency of the .live method, so in case there are big performance differences, please tell me that:) I tried to profile it in webkit profiler, but I didn't see any difference..

A: Just place a click(function(event) { ... }) handler on the static parent element, and find the element which started the event with event.target.

A: Assuming you have an a containing an img, any event on the img should bubble to the a, which will catch it.

A: You could also try using the .delegate() method (http://api.jquery.com/delegate/)
Here is some more info regarding .live() vs. delegate():

*

*http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery

*http://www.youtube.com/watch?v=23Q4S9hmHQY

*jQuery: live() vs delegate() [stackoverflow.com]

Update:
Here is a post by Jupiter 24 about "Why you should never use jQuery live":

*

*http://jupiterjs.com/news/why-you-should-never-use-jquery-live


text:
Q: p is prime. Show that there is at most one $(m,n) \in \mathbb Z^2$ with $0I've been trying to solve this question without great success.
I've found that the problem is correct for $p \equiv 1 \mod 4$.
Thank you,

A: Let $p=2$, then $p=1^2+1^2$. So assume $p$ is an odd prime s.t. $p=a^2+b^2$, hence neither $a$ nor $b=0$. Now $a$ has a multiplicative inverse $c$ modulo $p$: $ac\equiv1\pmod{p}$.
$$(ac)^2+(bc)^2\equiv1+(bc)^2\equiv0\pmod{p}\implies (bc)^2\equiv-1\pmod{p}$$
and so $-1$ is a quadratic residue modulo $p$. Let $bc\equiv d$ then
$$d^2+1\equiv0\pmod{p}\tag{1}$$
Now $\gcd(d,p)=1$ so there exists a unique solution to the congruence
$$dx\equiv y\pmod{p}\tag{2}$$
where $0<|x|<\sqrt{p}$ and $0<|y|<\sqrt{p}$. To see this let $m=\lfloor\sqrt{p}\rfloor$, and consider the $(m+1)^2$ numbers $jd+k$, where $1\le j,k\le m+1$. Since $(m+1)^2>p$, at least two of the numbers are in the same residue class, say
$$x_1d+y_1\equiv x_2d+y_2\pmod{p}\implies (x_1-x_2)d\equiv (y_2-y_1)\pmod{p}$$
where $x_1\neq x_2$ or $y_1\neq y_2$. Since if one of the terms is zero, so is the other, then neither is, and we have $x=x_1-x_2$, $y=y_2-y_1$.
Multiply $(1)$ by $x^2$ and use $(2)$ to give
$$(d^2+1)x^2=(dx)^2+x^2\equiv y^2+x^2\equiv0\pmod{p}\tag{3}$$
Now $0<x^2+y^2<2p$, implying $x^2+y^2=p$.
To discover which primes can be written as the sums of two squares we have that if $\gcd(a,p)=1$ then Euler's criterion gives
$$(-a|p)\equiv(-a)^{(p-1)/2}\equiv(-1)^{(p-1)/2}a^{(p-1)/2}\equiv(-1)^{(p-1)/2}(a|p)\pmod{p}$$
from which $(-a|p)=(-1)^{(p-1)/2}(a|p)$ (here $(a|p)$ is the Legendre symbol). This gives the results:
If $p=4n+1$, $(p-1)/2$ is even, so
$$(-a|p)= (a|p)$$
If $p=4n+3$, $(p-1)/2$ is odd, so
$$(-a|p)=-(a|p)$$
This shows an odd prime $p$ can be written as the sum of two squares if and only if it is of the form $4n+1$ (for then $(-1|p)=(1|p)=1$, and we need $-1$ a quadratic residue modulo $p$).
We now show these are the only numbers that can be represented in this way.
By the Brahmagupta-Fibonacci Identity has it that if two numbers can be written as the sum of two squares then so can their product:
$$(a^2+b^2)(d^2+c^2)=(ad+bc)^2+(ac-bd)^2$$
Now if $N=m^2k$ where $k$ is square free, then $N$ can be written as the sum of two squares if and only if $k$ contains no factors of the form $4n+3$. If $k$ has no such factors we can write $k=f^2+g^2$, and so $m^2k=(mf)^2+(mg)^2$ is the sum of two squares.
Conversely if $N=a^2+b^2=m^2k$, and $\gcd(a,b)=d$ then $d^2\mid m^2$. Let $a=a_1d$, $b=b_1d$. Then
$$a_1^2+b_1^2\equiv0\pmod{k}\tag{4}$$
Now $\gcd(a_1,b_1)=1$, so if an odd prime $p\mid k$ then one of $a_1$, $b_1$ is prime to $k$. Say $\gcd(a_1,k)=1$. Then there exists a multiplicative inverse $c$ s.t.
$$ca_1\equiv1\pmod{p}$$
and so by $(4)$
$$(a_1c)^2+(b_1c)^2\equiv1+(b_1c)^2\equiv0\pmod{p}\implies (b_1c)^2\equiv-1\pmod{p}$$
implying $-1$ is a quadratic residue modulo $p$. Hence $p$ is of the form $4n+1$.

A: It is easy to see $m$ or $n$ is odd and the other is even.
So let $m=2x-1$ and $n=2y$. $p=m^2+n^2=4x^2-4x+1+4y^2=4(x^2-x+y^2)+1$. Hence $p$ has to be of the form $4\ell+1$.
Let $x=m+in \in \mathbb{Z[i]}$. Let $N(x)$ be the norm of $x$.
Since $N(x)= m^2+n^2=p$ a prime, Hence $x$ is a prime in $\mathbb{Z[i]}$.
Now suppose $m_1^2+n_1^2=m_2^2+n_2^2$ then
$(m_1+in_1)(m_1-in_1)=(m_2+in_2)(m_2-in_2)$.
Since $m_1+in_1$ is a prime :$(m_1+in_1)$ divides $(m_2+in_2)$ or $(m_2-in_2)$.
Let
$(m_1+in_1)$ divide $(m_2+in_2)$ and since primes are irreducible in $\mathbb{Z[i]}$:
$u(m_1+in_1)=(m_2+in_2)$
where $u$ is a unit in  $\mathbb{Z[i]}$ and units in $\mathbb{Z[i]}$ are just $1,-1,i,-i$.
Hence proved.


text:
Q: Codeigniter Pagination Infinite Scroll Using Ajax And Jquery giving only Duplicate data I want to create pagination page into infinite scroll. I'm using codeigniter. But it is duplicating the data. So please help me to edit my pagination code. I had struggle for days. I will be so grateful if you can help me. Thank you.
When I use the below code
$(window).scrollTop() + $(window).height() == $(document).height()

Its working fine
And when I try to load when scroller reaches the footer div it gives only duplicate data.
$(window).scrollTop()+$(window).height() >= $('#footerdivid').offset().top

My code is given below
View

Codeigniter Pagination Infinite Scroll

Controller
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Content extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this -> load->model('content_model');
    }

    public function index()
    {
        $total_data = $this->content_model->get_all_count();
        $content_per_page = 5;
        $this->data['total_data'] = ceil($total_data->tol_records/$content_per_page);
        $this->load->view('content_page', $this->data, FALSE);
    }

    public function load_more()
    {
        $group_no = $this->input->post('group_no');
        $content_per_page = 5;
        $start = ceil($group_no * $content_per_page);
        $all_content = $this->content_model->get_all_content($start,$content_per_page);
        if(isset($all_content) && is_array($all_content) && count($all_content)) :
            foreach ($all_content as $key => $content) :
                 echo '
'.$content->title.'
';
                 echo '
'.$content->description.'
';
            endforeach;
        endif;
    }

}

Model
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Content_model extends CI_Model
{
    public function get_all_count()
    {
        $sql = "SELECT COUNT(*) as tol_records FROM content_information";
        $result = $this->db->query($sql)->row();
        return $result;
    }

    public function get_all_content($start,$content_per_page)
    {
        $sql = "SELECT * FROM  content_information LIMIT $start,$content_per_page";
        $result = $this->db->query($sql)->result();
        return $result;
    }

}

A: When the user scrolls, it fires the $(window).scroll event multiple times. This is why your script is requesting the same data more than once and you get duplicate data.
There is a simple solution to this. You can use a Boolean array to mark the requests that have been made. And then request only if the current request is not yet made.
Change the script in the view file as follows:

Codeigniter Pagination Infinite Scroll


text:
Q: Orientation Matrix from Heading, Pitch and Roll I have a problem converting Heading, Pitch and Roll to an Orientation Matrix
How would I go about improving this to ensure Y and Z and are correctly calculated.
--[[
  get_orientation - Returns the orientation matrix of an object based on its heading, pitch, and roll in degrees.

  @param heading number - The heading of the object in degrees.
  @param pitch number - The pitch of the object in degrees.
  @param roll number - The roll of the object in degrees.
  @returns orientation table - The orientation matrix of the object, represented as a table with three unit vectors: x, y, and z.
]]
local function get_orientation(heading, pitch, roll)
    local orientation = {}

    -- Convert the heading, pitch, and roll from degrees to radians using math.rad
    heading = math.rad(heading)
    pitch = math.rad(pitch)
    roll = math.rad(roll)

    -- Calculate the x unit vector
    -- x is the Vec3 unit vector that points in the direction of the object's front
    orientation.x = {}
    orientation.x.x = math.cos(heading) * math.cos(pitch)
    orientation.x.y = math.sin(pitch)
    orientation.x.z = math.sin(heading) * math.cos(pitch)

    -- Calculate the y unit vector
    -- y is the Vec3 unit vector that points in the direction of the object's top
    orientation.y = {}
    orientation.y.x = -math.cos(heading) * math.sin(pitch)
    orientation.y.y = math.cos(pitch)
    orientation.y.z = -math.sin(heading) * math.sin(pitch)

    -- Calculate the z unit vector
    -- z is the Vec3 unit vector that points in the direction of the object's right side
    orientation.z = {}
    orientation.z.x = -math.sin(heading)
    orientation.z.z = -math.cos(heading) * math.cos(roll)
    orientation.z.y = math.sin(roll)

    -- Return the orientation matrix of the object
    return orientation
end

---------------------------------------------------
---------------------------------------------------
local lat = 41.610278
local lon = 41.599444
local heading = 90
local pitch = 25
local roll = 0
local alt = 100

local x, y = terrain.convertLatLonToMeters(lat, lon)

local orientation = get_orientation(heading, pitch, roll)

local position = {
    x=orientation.x,
    y=orientation.y,
    z=orientation.z,
    p={x=x,y=alt,z=y}
}

Export.LoSetCameraPosition(position)
local actual = Export.LoGetCameraPosition()

return {position=position, actual=actual}

There is a little more information about the Orientation here
https://www.digitalcombatsimulator.com/en/support/faq/1256/#:~:text=level%2010%20m-,Orientation,-Object%20orientation%20is
I am attempting to build a function that takes lat, lon, alt, heading, pitch and roll and produce the Position matrix.
I have the example function so far, which does work but everything goes funky after -81 pitch and the roll does not work as intended.

A: Formulas for 3D rotation are not simple, but they can be simply deduced from three consecutive 2D rotations.
local function apply_rotation(a, b, angle)
   local ax, ay, az, bx, by, bz = a.x, a.y, a.z, b.x, b.y, b.z
   a.x = math.cos(angle) * ax + math.sin(angle) * bx
   a.y = math.cos(angle) * ay + math.sin(angle) * by
   a.z = math.cos(angle) * az + math.sin(angle) * bz
   b.x = math.cos(angle) * bx - math.sin(angle) * ax
   b.y = math.cos(angle) * by - math.sin(angle) * ay
   b.z = math.cos(angle) * bz - math.sin(angle) * az
end

local function get_orientation(heading, pitch, roll)

    -- Convert the heading, pitch, and roll from degrees to radians using math.rad
    heading = math.rad(heading)
    pitch = math.rad(pitch)
    roll = math.rad(roll)

    -- x is the Vec3 unit vector that points in the direction of the object's front
    -- y is the Vec3 unit vector that points in the direction of the object's top
    -- z is the Vec3 unit vector that points in the direction of the object's right side
    local o = {
        x = { x=1, y=0, z=0 },
        y = { x=0, y=1, z=0 },
        z = { x=0, y=0, z=1 },
    }

    apply_rotation(o.x, o.z, heading)
    apply_rotation(o.x, o.y, pitch)
    apply_rotation(o.z, o.y, roll)

    -- Return the orientation matrix of the object
    return o
end


text:
Q: Minimatch exclude pattern in VSTS publish task I've been wrestling with getting this minimatch exclude pattern to work.
The **\src!(packages) pattern works as expected but I need to also exclude web.template.config files under the src directory.  I've tried several things including **\src!(packages|Web.template.config)
Can anyone help or point me to a good way of troubleshooting this?  I'm stuck.

A: To get this to work,

*

*I added the Copy Files task

*Applied the minimatch filter to the Copy Files task

*Used the Publish Task to copy the entire $(build.artifactstagingdirectory) directory.

The minimatch filter is as follows...
**/src/**/!(*eb.*emplate*.config)
!**/packages{,/**}


text:
Q: Linking for both 32 bit and 64 bit DLLs I have Some DLLs for both 32bit and 64bit system, The DLLs have the same name for both versions.
How can I link my c++ project to those DLLs
I do the following for linking:
From solution explorer in visual studio, right click on project -> properties ->
Linker -> Input -> put the name of .Lib files
I do the same steps for all configurations, The linking worked perfectly for 32bit, but did not for 64bit.


text:
Q: Detecting Slashdot effect in nginx Is there a way I can make Nginx to notify me if hits from a referrer goes beyond a threshold?
e.g If my website is featured at Slashdot and all of sudden I have 2K hits coming in an hour I want to be notified when goes beyond 1K hits an hour.
Will it be possible to do this in Nginx? Possibly without lua? (since my prod is not lua compiled)

A: The nginx limit_req_zone directive can base its zones on any variable, including $http_referrer.
http {
    limit_req_zone  $http_referrer  zone=one:10m   rate=1r/s;

    ...

    server {

        ...

        location /search/ {
            limit_req   zone=one  burst=5;
        }

You will also want to do something to limit the amount of state required on the web server though, as the referrer headers can be quite long and varied and you may see an infinte variet. You can use the nginx split_clients feature to set a variable for all requests that is based on the hash of the referrer header. The example below uses only 10 buckes, but you could do it with 1000 just as easily. So if you got slashdotted, people whose referrer happened to hash into the same bucket as the slashdot URL would get blocked too, but you could limit that to 0.1% of visitors by using 1000 buckets in split_clients.
It would look something like this (totally untested, but directionally correct):
http {

split_clients $http_referrer $refhash {
               10%               x01;
               10%               x02;
               10%               x03;
               10%               x04;
               10%               x05;
               10%               x06;
               10%               x07;
               10%               x08;
               10%               x09;
               *                 x10;
               }

limit_req_zone  $refhash  zone=one:10m   rate=1r/s;

...

server {

    ...

    location /search/ {
        limit_req   zone=one  burst=5;
    }

A: The most efficient solution might be to write a daemon that would tail -f the access.log, and keep track of the $http_referer field.
However, a quick and dirty solution would be to add an extra access_log file, to log only the $http_referer variable with a custom log_format, and to automatically rotate the log every X minutes.

*

*This can be accomplished with the help of standard logrotate scripts, which might need to do graceful restarts of nginx in order to have the files reopened (e.g., the standard procedure, take a look at /a/15183322 on SO for a simple time-based script)…

*Or, by using variables within access_log, possibly by getting the minute specification out of $time_iso8601 with the help of the map or an if directive (depending on where you'd like to put your access_log).
So, with the above, you may have 6 log files, each covering a period of 10 minutes, http_referer.Txx{0,1,2,3,4,5}x.log, e.g., by getting the first digit of the minute to differentiate each file.
Now, all you have to do is have a simple shell script that could run every 10 minutes, cat all of the above files together, pipe it to sort, pipe it to uniq -c, to sort -rn, to head -16, and you have a list of the 16 most common Referer variations — free to decide if any combinations of numbers and fields exceeds your criteria, and perform a notification.
Subsequently, after a single successful notification, you could remove all of these 6 files, and, in subsequent runs, not issue any notification UNLESS all six of the files are present (and/or a certain other number as you see fit).

A: Yes, of course it is possible in NGINX!
What you could do is implement the following DFA:

*

*Implement rate limiting, based on $http_referer, possibly using some regex through a map to normalise the values.  When the limit is exceeded, an internal error page is raised, which you can catch through an error_page handler as per a related question, going to a new internal location as an internal redirect (not visible to the client).

*In the above location for exceeded limits, you perform an alert request, letting external logic perform the notification; this request is subsequently cached, ensuring you will only get 1 unique request per a given time window.

*Catch the HTTP Status code of the prior request (by returning a status code ≥ 300 and using proxy_intercept_errors on, or, alternatively, use the not-built-by-default auth_request or add_after_body to make a "free" subrequest), and complete the original request as if the prior step wasn't involved.  Note that we need to enable recursive error_page handling for this to work.
Here's my PoC and an MVP, also at https://github.com/cnst/StackOverflow.cnst.nginx.conf/blob/master/sf.432636.detecting-slashdot-effect-in-nginx.conf:
limit_req_zone $http_referer zone=slash:10m rate=1r/m;  # XXX: how many req/minute?
server {
    listen 2636;
    location / {
        limit_req zone=slash nodelay;
        #limit_req_status 429;  #nginx 1.3.15
        #error_page 429 = @dot;
        error_page 503 = @dot;
        proxy_pass http://localhost:2635;
        # an outright `return 200` has a higher precedence over the limit
    }
    recursive_error_pages on;
    location @dot {
        proxy_pass http://127.0.0.1:2637/?ref=$http_referer;
        # if you don't have `resolver`, no URI modification is allowed:
        #proxy_pass http://localhost:2637;
        proxy_intercept_errors on;
        error_page 429 = @slash;
    }
    location @slash {
        # XXX: placeholder for your content:
        return 200 "$uri: we're too fast!\n";
    }
}
server {
    listen 2635;
    # XXX: placeholder for your content:
    return 200 "$uri: going steady\n";
}
proxy_cache_path /tmp/nginx/slashdotted inactive=1h
        max_size=64m keys_zone=slashdotted:10m;
server {
    # we need to flip the 200 status into the one >=300, so that
    # we can then catch it through proxy_intercept_errors above
    listen 2637;
    error_page 429 @/.;
    return 429;
    location @/. {
        proxy_cache slashdotted;
        proxy_cache_valid 200 60s;  # XXX: how often to get notifications?
        proxy_pass http://localhost:2638;
    }
}
server {
    # IRL this would be an actual script, or
    # a proxy_pass redirect to an HTTP to SMS or SMTP gateway
    listen 2638;
    return 200 authorities_alerted\n;
}

Note that this works as expected:
% sh -c 'rm /tmp/slashdotted.nginx/*; mkdir /tmp/slashdotted.nginx; nginx -s reload; for i in 1 2 3; do curl -H "Referer: test" localhost:2636; sleep 2; done; tail /var/log/nginx/access.log'
/: going steady
/: we're too fast!
/: we're too fast!

127.0.0.1 - - [26/Aug/2017:02:05:49 +0200] "GET / HTTP/1.1" 200 16 "test" "curl/7.26.0"
127.0.0.1 - - [26/Aug/2017:02:05:49 +0200] "GET / HTTP/1.0" 200 16 "test" "curl/7.26.0"

127.0.0.1 - - [26/Aug/2017:02:05:51 +0200] "GET / HTTP/1.1" 200 19 "test" "curl/7.26.0"
127.0.0.1 - - [26/Aug/2017:02:05:51 +0200] "GET /?ref=test HTTP/1.0" 200 20 "test" "curl/7.26.0"
127.0.0.1 - - [26/Aug/2017:02:05:51 +0200] "GET /?ref=test HTTP/1.0" 429 20 "test" "curl/7.26.0"

127.0.0.1 - - [26/Aug/2017:02:05:53 +0200] "GET / HTTP/1.1" 200 19 "test" "curl/7.26.0"
127.0.0.1 - - [26/Aug/2017:02:05:53 +0200] "GET /?ref=test HTTP/1.0" 429 20 "test" "curl/7.26.0"
%

You can see that the first request results in one front-end and one backend hit, as expected (I had to add a dummy backend to the location that has limit_req, because a return 200 would take precedence over the limits, a real backend isn't necessary for the rest of the handling).
The second request is above the limit, so, we send the alert (getting 200), and cache it, returning 429 (this is necessary due to the aforementioned limitation that requests below 300 cannot be caught), which is subsequently caught by the front-end, which is free now free to do whatever it wants.
The third request is still exceeding the limit, but we've already sent the alert, so, no new alert gets sent.
Done!  Don't forget to fork it on GitHub!

A: I think this would be far better done with logtail and grep.  Even if it's possible to do with lua inline, you don't want that overhead for every request and you especially don't want it when you have been Slashdotted.
Here's a 5-second version.  Stick it in a script and put some more readable text around it and you're golden.
5 * * * * logtail -f /var/log/nginx/access_log -o /tmp/nginx-logtail.offset | grep -c "http://[^ ]slashdot.org"

Of course, that completely ignores reddit.com and facebook.com and all of the million other sites that could send you lots of traffic.  Not to mention 100 different sites sending you 20 visitors each.  You should probably just have a plain old traffic threshold that causes an email to be sent to you, regardless of referrer.


text:
Q: removePersistentStore(_:) doesn't return Bool in Swift I'm trying to store the return value of removePersistentStore(_:) which is clearly a Bool according to the documentation:

I'm using it like that:
let removed = try! storeCoordinator.removePersistentStore(store)

But get an alert that removed is just Void:

What's the deal with this? Am I missing something?

A:
Return Value
YES if the store is removed, otherwise NO.

in the NSPersistentStoreCoordinator documentation refers to the Objective-C signature of
the method:
- (BOOL)removePersistentStore:(NSPersistentStore *)store
                    error:(NSError * _Nullable *)error

In Swift, the method throws an error instead of returning a boolean:
func removePersistentStore(_ store: NSPersistentStore) throws

so that you can call it as
try! storeCoordinator.removePersistentStore(persistentStore)

or better:
do {
    try storeCoordinator.removePersistentStore(persistentStore)
} catch let error as NSError {
    print("failed", error.localizedDescription)
}

Compare Error Handling in the "Using Swift with Cocoa and Objective-C" reference:

If the last non-block parameter of an Objective-C method is of type NSError **, Swift replaces it with the throws keyword, to indicate that the method can throw an error.
...
If an error producing Objective-C method returns a BOOL value to indicate the success or failure of a method call, Swift changes the return type of the function to Void.