text:
Q: Unable to use Swift debugger in one particular class file I'm able to use the debugger to see values in memory everywhere in my app except one class. Every time I try, no matter what value I try to po, I get the same error message:
(lldb) po searchInstitution.name
error: <EXPR>:2:1: error: cannot convert value of type 'Int' to expected argument type 'Device'
searchInstitution.name
^~~~~~~~~~~~~~~~~
<EXPR>:15:7: error: cannot convert value of type 'Int' to expected argument type 'Device'
  if (1==1) {
      ^

Device is a struct in the file with this definition:
private struct Device: Hashable {
    let type: String
    let mask: String

    var hashValue: Int {
        return type.hashValue ^ mask.hashValue
    }
}

private func ==(lhs: Device, rhs: Device) -> Bool {
    return lhs.type == rhs.type && lhs.mask == rhs.mask
}

But it has nothing to do with the string property of the SearchInstitution class instance that I'm trying to inspect.
Has anyone seen anything like this? Any ideas on what I may need to change to fix it? It makes debugging that view controller extremely frustrating.

A: This is a known bug.  The conflict with the "if (1 == 1)" in the code the expression parser uses to wrap your expression is fixed in github lldb (by switching to "do" - which wasn't available when this code was first written...), and should make it into the next official tools release.
If you want to work around it in the meantime, just make your == operator public rather than private.  The expression evaluator was trying to force priority for local private definitions over potentially conflicting global ones, and didn't do it correctly so that ONLY the private local one was seen.
Note, that more general bug is not fixed yet, so if you actually use a private operator in a context where it is visible, ONLY that operator definition will be used.


text:
Q: Array and $_REQUEST I need to use Ajax DataTable.
Order request is in array.
On inspect:

Request parametersid: order[0][column]:"4" , order[0][dir]:"asc" and start:"0" .
If i want to get value of "start" i use:
$str=$_REQUEST['start'];

Now i don't know how to get value "4" and "asc"?
I have tried with this (current(current($_REQUEST['order']))) and it returns "4", but for "asc", until now. no solution found.

A: Check values of
$_REQUEST['order'][0]["column"]

and
$_REQUEST['order'][0]["dir"]

A: Try:
$str = $_REQUEST['order'][0]['column'];

and
$str2 = $_REQUEST['order'][0]['dir'];

redpajama_set_name: RedPajamaStackExchange


text:
Q: When a pod can't be scheduled, what does the 3 in "Insufficient cpu (3)" refer to? When I create a Pod that cannot be scheduled because there are no nodes with sufficient CPU to meet the Pod's CPU request, the events output from kubectl describe pod/... contain a message like No nodes are available that match all of the following predicates:: Insufficient cpu (3).
What does the (3) in Insufficient cpu (3) mean?
For example, if I try to create a pod that requests 24 CPU when all of my nodes only have 4 CPUs:
$ kubectl describe pod/large-cpu-request
Name:           large-cpu-request
Namespace:      default
Node:           /
Labels:         <none>
Annotations:    <none>
Status:         Pending
IP:
Controllers:    <none>
Containers:
  cpuhog:
    ...
    Requests:
      cpu:              24
...
Events:
  FirstSeen     LastSeen        Count   From                    SubObjectPath   Type            Reason                  Message
  ---------     --------        -----   ----                    -------------   --------        ------                  -------
  23m           30s             84      default-scheduler                       Warning         FailedScheduling        No nodes are available that match all of the following predicates:: Insufficient cpu (3).

At other times I have seen event messages like No nodes are available that match all of the following predicates:: Insufficient cpu (2), PodToleratesNodeTaints (1) when a pod's resource requests were too high, so the 3 does not seem like a constant number - nor does it seem related to my 24 CPU request either.

A: A pod can't be scheduled when it requests more cpu than you have in your cluster. For example, if you have 8 Kubernetes CPU (see this page to calculate how many kubernetes cpu you have) in total and if your existing pods have already consumed that much cpu then you can't schedule more pods unless some of your existing pods are killed by the time you request to schedule a new pod. Here is a simple equation can be followed in Horizontal Pod Autoscaler (HPA):
RESOURCE REQUEST CPU * HPA MAX PODS <= Total Kubernetes CPU
You can always tune up these numbers. In my case, I adjusted my manifest file for the RESOURCE REQUEST CPU. It can be 200m, or 1000m (= 1 kubernetes cpu).

A: It means that your Pod doesn't fit on 3 nodes because of Insufficient CPU and 1 node because of taints (likely the master).


text:
Q: Class behavior based on given data I am receiving an IFormFile from a controller.
What I want to do next is to process it and get its content. I expect to get .docx, .txt or .pdf file and I want a single class to process any of these files based on extension given. I created and made my class to do it like that:
{
    public static class DocumentProcessor // Should it be like this?
    {
        public static string GetContent(IFormFile file)
        {
            var result = new StringBuilder();

            switch (Path.GetExtension(file.FileName))
            {
                case ".txt":
                {
                    using(var reader = new StreamReader(file.OpenReadStream()))
                    {
                        while (reader.Peek() >= 0)
                            result.AppendLine(reader.ReadLine());
                    }
                    break;
                }
            }
            return result.ToString();
        }
    }
}

Anyway, I feel like it is an extremely bad solution just because it is static. I could use the strategy pattern, but how do I define what strategy context has to use?
Should I create another class that
returns a Strategy object depending on IFormFile object extension. But I feel it is also a bad solution
I would like to know what is the best way to solve this problem

A: Create a new interface
interface IDocumentParser {
    string GetContent(IFormFile file);
}

Implement that interface once per parser extension, e.g.:
class TextFileParser : IDocumentParser {
    public string GetContent(IFormFile file) {
        //your implementation code here
    }
}

Then implement a factory:
class ParserFactory {
    public static IDocumentParser GetParserForFilename(string filename) {
        /*
           This is the simple way. A more complex yet elegant way would be for all parsers to include a property exposing the filetypes it supports, and they are loaded through reflection or dependency injection.
        */
        switch (Path.GetExtension(fileName))
            {
                case ".txt":
                {
                    return new TextFileParser();
                }
                // add additional parsers here
            }
            return null;
    }
}

And use:
IDocumentParser parser = ParserFactory.GetParserForFilename(file.FileName);
string content = parser.GetContent(file);

This is known as "Inversion of Control".


text:
Q: JAX-WS No Enum generated parsing WSDL with list of restrictions (enums) In case WSDL type definition is following:
<xs:simpleType name="AccountStatus">
    <xs:restriction base="xs:string">
        <xs:enumeration value="Open" />
        <xs:enumeration value="Closed" />
        <xs:enumeration value="CreditOnly" />
        <xs:enumeration value="BudgetOnly" />
        <xs:enumeration value="Frozen" />
        <xs:enumeration value="Reserved" />
        <xs:enumeration value="Cancelled" />
    </xs:restriction>
</xs:simpleType>

Ordinary Java enum AccountStatus gets generated in client classes.
But when definition is changed to list of this enums as following:
<xs:simpleType name="AccountStatus">
    <xs:list>
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="Open"/>
                <xs:enumeration value="Closed"/>
                <xs:enumeration value="CreditOnly"/>
                <xs:enumeration value="BudgetOnly"/>
                <xs:enumeration value="Frozen"/>
                <xs:enumeration value="Reserved" />
                <xs:enumeration value="Cancelled" />
            </xs:restriction>
        </xs:simpleType>
    </xs:list>
</xs:simpleType>

No enum class is generated for AccountStatus. On the object itself that is supposed to have account statuses list. Currently it has
List<List<String>> statuses

Instead of
List<AccountStatus> statuses

A: I am generating client from third party vendor Web Services WSDL, that I cannot alter. So far I found the way of managing my issue with JAXB Bindings:
<jxb:bindings schemaLocation="../main/resources/META-INF/wsdl/AccountsService.wsdl#types?schema4" node=".//xs:simpleType[@name='AccountStatus']/xs:list/xs:simpleType">
    <jxb:typesafeEnumClass name="AccountStatus">
        <jxb:typesafeEnumMember value="Open" name="Open" />
        <jxb:typesafeEnumMember value="Closed" name="Closed" />
        <jxb:typesafeEnumMember value="CreditOnly" name="CreditOnly" />
        <jxb:typesafeEnumMember value="BudgetOnly" name="BudgetOnly" />
        <jxb:typesafeEnumMember value="Frozen" name="Frozen" />
        <jxb:typesafeEnumMember value="Reserved" name="Reserved" />
        <jxb:typesafeEnumMember value="Cancelled" name="Cancelled" />
    </jxb:typesafeEnumClass>
</jxb:bindings>

It is important to write correct XPath query and the result is:
List<AccountStatus> statuses

code generated on client stub classes.

A: I've never used xs:list before, but as I understand it, your're actually defining AccountStatus as a list of strings.
Instead, I'd do the following:
<xs:simpleType name="AccountStatus">
    <xs:restriction base="xs:string">
        <xs:enumeration value="Open" />
        <xs:enumeration value="Closed" />
        <xs:enumeration value="CreditOnly" />
        <xs:enumeration value="BudgetOnly" />
        <xs:enumeration value="Frozen" />
        <xs:enumeration value="Reserved" />
        <xs:enumeration value="Cancelled" />
    </xs:restriction>
</xs:simpleType>

<xs:complexType name="AccountStatusHolder">
    <xs:sequence>
        <xs:element name="status" type="tns:AccountStatus" maxOccurs="unbounded" />
    </xs:sequence>
</xs:complexType>

Notice the maxOccurs="unbounded" setting, resulting in the following class (JAXB generated):
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AccountStatusHolder", propOrder = "status")
public class AccountStatusHolder implements Serializable {
    private final static long serialVersionUID = 0L;

    @XmlElement(required = true)
    protected List<AccountStatus> status;
}


text:
Q: How to describe this region in spherical coordinates? How can you describe the region $B$ in spherical coordinates?
$$B=\{(x,y,z)\in\Bbb R^3:x^2+y^2+z^2\leq 9,\ x^2+y^2\leq z^2\ z\geq 0\}$$
region equation

A: First, remember that $x^2+y^2+z^2 = r^2$, so the first equation becomes $r^2 \leq 9$, or $r < 3$. The second equation comes out of $x = r \sin \theta \cos \varphi$, $y = r \sin \theta \sin \varphi$ and $z = r \cos \theta$ (all important identities to memorize). Thus, we get $x^2 + y^2 = r^2 \sin^2 \theta$ and $z^2 = r^2 \cos^2 \theta$. Therefore, we have $r^2 \sin^2 \theta \leq r^2 \cos^2 \theta$, or $\tan^2 \theta \leq 1$. The last equation should be self explanatory from earlier statements

A: Reacalling that
$$
\begin{align}
x&=\rho\sin\phi\cos\theta\;,\\
y&=\rho\sin\phi\sin\theta\;,\\
z&=\rho\cos\phi\;,
\end{align}
$$
with $\rho\geq 0$, $\theta\in [0,2\pi)$ and $\phi\in [0,\pi]$,
then
\begin{align}&x^2+y^2+z^2\leq 9\Leftrightarrow \rho^2\leq 9\Leftrightarrow \rho\leq 3\\
&x^2+y^2\leq z^2\Leftrightarrow \rho^2\sin^2\phi\leq \rho^2\cos^2\phi\Leftrightarrow |\tan\phi|\leq 1\\
&z\geq 0\Leftrightarrow \rho\cos\phi\geq 0\Leftrightarrow \cos\phi\geq 0\end{align}
Can you take it from here?


text:
Q: cant figure out how to delete an already existing time sheet using AL language i have been trying the code down below in the picture but it didnt work i am new at al coding and i cant seem to find good videos or site on the net (if u have good sites or youtube channels they might help too).
this is my try

this is my page

A: procedure DeleteTimeSheet(TimeSheetCode: Code[20])
var
    TimeSheetHeader: Record "Time Sheet Header";
begin
    if TimeSheetHeader.Get(TimeSheetCode) then
        TimeSheetHeader.Delete(true);
end;

A few notes and recommendations.
The length of Code variables should be aligned with respective table fields which this code applies to. In this case, time sheet code in the Time Sheet Header table is Code[20], so it's a good idea to keep the variable the same length. This can protect your code from possible overflow runtime errors.
Variable name "TimeSheetHeader" is more human-readable than RecL950. Yes, the internal table ID of the timesheet header is 950, but I bet there is no developer who remembers all table numbers in BC. Best to name variables in a way that helps identify the object they reference.
Delete needs the primary key to be initialized, and it's a good idea to call it with the true parameter to invoke the OnDelete trigger. Code in the header trigger deletes linked timesheet lines and comments. TimeSheetHeader.Delete() will not call the table trigger, and will leave orphan time sheet lines.
You can search for AL books, there are a few available. "Business Central Development Quick Start Guide" by Duilio Tacconi, is one recommendation.
Or you can try "AL for Beginners" by Krzysztof Bialowas, it's free: http://www.mynavblog.com/2022/07/25/al-for-beginners-workbook-version-2-0/

A: like said the user Alexander Drogin, there's some issues with your code.
In a "best practice" way and a logic way; the most important is the logic way.
In you case you're trying to do the comparison with a null value inside the Record variable RecL950."No.". You have to filter this variable and do the find function in base to your requirements.
Please check this article directly from Microsoft!
https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/record/record-findfirst-method
(I've attached to you the case of the findfirst, please check also the other ones.)


text:
Q: how to get a slider value on a release tap event in jquery mobile? i have a simple slider
<input type="range" name="slider" id="slider" min="0" max="100" value="50">

i would like to get its value when i release a tap event on it.
something like what the change event does in the example below
$('#time_slider').on("change", function(){
    var val = $(this).val();
});

I'm open to examples outside JQM as well
any ideas?

A: found it
$('#time_slider').on("slidestop", function(){
    var val = $(this).val();
});


text:
Q: Warnsdorff's algorithm for custom move in Scala I have written a program to find the list for move required to cover all square of the chessboard using Warnsdorff's algorithm. it is perfectly working for 7x7 board but not working for board like 8x8, 10x10 or 16x16. Its goes on running for long. The below are the code. Please point out where I am going wrong.
object PawnTourMain {

  def main(args: Array[ String ]): Unit = {

    val kt = PawnTour(7)
    kt.findTour(0, 1, 0)
    kt.printSolution
  }

  class PawnTour(size: Int, board: Array[ Array[ Int ] ], possibleMoves: Array[ Array[ Array[ Point ] ] ]) {

    val UNUSED = -1

    def findTour(x: Int, y: Int, current: Int): Boolean = {
      if (board(x)(y) != UNUSED) return false
      //Mark current position as 'current'
      board(x)(y) = current
      if (current == size * size - 1) { //done :)
        return true
      }
      for (d <- possibleMoves(x)(y)) {
        if (findTour(d.x, d.y, current + 1)) return true
      }
      //if we are here, all our options ran out :(
      //reset the current cell and return false
      board(x)(y) = UNUSED
      false
    }

    def printSolution: Unit = {
      board foreach {
        row =>
          row foreach (number => print(number + " ")); println
      }
    }
  }

  case class Point(x: Int, y: Int)

  object PawnTour {

    val DIRECTIONS = Array(Point(3, 0), Point(-3, 0), Point(2, -2), Point(2, 2), Point(0, 3), Point(0, -3), Point(-2, -2), Point(2, 2))

    def apply(n: Int): PawnTour = {
      val board = Array.fill[ Int ](n, n)(-1)
      val possibleMoves = Array.tabulate(n, n) { (x, y) =>
        DIRECTIONS.flatMap { d =>
          val nx = x + d.x
          val ny = y + d.y
          if ((nx >= 0 && nx < n) && (ny >= 0 && ny < n)) Option(Point(nx, ny)) else None
        }
      }

      var x = 0
      while (x < n) {
        var y = 0
        while (y < n) {
          val moves: Array[ Point ] = possibleMoves(x)(y)
          moves.sortBy((o1: Point) => possibleMoves(o1.x)(o1.y).size)
          y += 1
          println(moves.toList)
        }
        x += 1
      }
      new PawnTour(n, board, possibleMoves)
    }

    def printSolution(array: Array[ Array[ Int ] ]): Unit = {
      array foreach {
        row =>
          row foreach (number => print(number + " ")); println
      }
    }
  }
}

A: From Wikipedia

The knight is moved so that it always proceeds to the square from which the knight will have the fewest onward moves

Your implementation does not take into account already visited squares. It creates and sorts possible moves on empty board but forgets to update them when algorithm makes a move.
When square is visited you should remove it from possible moves and then reorder possible moves again


text:
Q: Prove for any vector I've got to prove for any vector given, $\vec{x} = [x_{1}, \dots, x_{n}]^{T} \in \mathbb{C}^{n}$ that it's true that:
$| x_{1} + \dots + x_{n} | \leqslant \sqrt{n} \cdot \| x \| $
Please give me some hints for that. I know that in this case: $ \| x \| = \sqrt{| x_{1}|^2 + \dots + | x_{n} |^{2}}$, but what's that giving me?

A: This is an application of the Cauchy-Schwarz inequality:
$$\left \vert \vec{x} \cdot \vec{y} \right \vert \leq \left \Vert \vec{x} \right \Vert_2 \left \Vert \vec{y} \right \Vert_2$$
Taking $\vec{y} = \begin{bmatrix} 1 & 1 & \cdots & 1\end{bmatrix}^T$, we obtain
$$\left \vert x_1 + x_2 + \cdots + x_n \right \vert \leq \sqrt{n} \left \Vert \vec{x} \right \Vert_2$$

In fact we can obtain a stronger inequality by setting $\vec{y} = \begin{bmatrix} \text{sign}(x_1) & \text{sign}(x_2) & \cdots & \text{sign}(x_n)\end{bmatrix}^T$.
This gives us
$$\left \vert x_1 \right \vert + \left \vert x_2 \right \vert + \cdots + \left \vert x_n \right \vert \leq \sqrt{n} \left \Vert \vec{x} \right \Vert_2$$


text:
Q: Unable to find Rolling Update Option For Managed Instance Group in GCP I have created a Managed Instance Group (Stateless) in GCP.
The MIG has a starter script ,like this
apt-get install -y apache2
apt-get install -y php7.0
service apache2 restart
echo "Hi" > /var/www/html/index.html

The MIG is then kept as a backend for a load balancer.

*

*Once the MIG is created , I am tryin to add a new instance template
and update the MIG

*I selected the MIG  and in the top of the page I expected to see a Rolling Update button , but That is not visible .

*There is a Update Vms option , through which I am able to add the new
template. So , what would be the difference between Rolling Update
and the Update VMs option ? When would one choose one over the other ? Or are they the same option?

This is the snap of how I am using the update Vms option to switch to a new instance template

A: You can refer to Updating instances in a MIG document, this will help you to choose which update will be better for your implementation.
Rolling update The MIG automatically rolls out a new version of an instance template to all or to a random subset of managed instances in the MIG.
You can handle this Rolling updates you need follow thw next steps.

*

*Go to [Compute Engine > Instance group].

*Select the instance group that you want update.

*At the top, you will find "UPDATE VMS".

*Create a new template.

*Update the VMs.

Selective update you can specifically target selected instances for an update. Use this method if you want to orchestrate the update manually.
So for the selective update you can control it and it will be helpful if you need to do some tests for an update.
For this update will be necessary to set up the new template with the following command in gcloud.
   gcloud compute instance-groups managed set-instance-template
   INSTANCE_GROUP_NAME \
   --template=INSTANCE_TEMPLATE \
   [--zone=ZONE | --region=REGION]

To apply the update to specific instances, can be executed the following command.
    gcloud compute instance-groups managed update-instances
    INSTANCE_GROUP_NAME \
    --instances INSTANCE_NAMES \
    --most-disruptive-allowed-action DISRUPTION_LEVEL \
    --minimal-action DISRUPTION_LEVEL


text:
Q: Can I install Windows server and enble Hyper-V on a VM on Ubuntu 14.04 Can I enable Hyper-V role on windows Guest OS(VM) running on Ubuntu 14.04.
I hitting with issue
Hyper-V cannot be installed: A hypervisor is already running.

A: This isn't possible to my knowledge.  Xen and KVM don't support Hyper-V in a VM.
Hyper-V is a type 1 hypervisor. It runs on bare metal then runs the parent as if it's a privileged VM.  We've been doing a lot of work recently around nested virtualization (link) on a Hyper-V host but nothing for Hyper-V on other hypervisors as of now.
Note:  I work on the Hyper-V team at Microsoft.


text:
Q: Does Azure Pipelines support building and releasing multiple feature branches using same pipeline when TFVC is source repository? Question
We'd like to be able to build and deploy code from our different feature branches to our various environments without having to clone and modify a build and release pipeline every time we have a feature branch. Does Azure Pipelines support building multiple branches and doing branch based conditional tasks in pipelines when TFVC source control is being used? If yes, how?
Background
Running Azure DevOps Server 2020 Update 1 on premise. Have multiple applications in our code repository, each with their own dev, main, and feature branches using TFVC as source control repository.
Source Control Repository structure is as follows:
Team Project
  /Apps
    /App 1
      /dev branch
      /dev-feature-1 branch
      /dev-feature-2 branch
      / main branch
    /App 2
      /dev branch
      /dev-feature-1 branch
      /dev-feature-2 branch
      / main branch
  /Utilities
  /SomeCommonStuff

We have classic (not YAML) build pipelines that build, do gated checkins, and publish artifacts for each of our dev and main branches.
We then have release pipelines that take the artifacts from those builds and deploy them to our different environments (dev, QA, production)
Research done so far on question
According to this documentation: it seems like Azure Pipelines supports building multiple branches in one build pipeline using Git as the source control repository because you can specify doing certain tasks such as only building certain solution files in certain branches using a condition that supports the Build.SourceBranch variable (as mentioned here).
However, when using TFVC as the source and trying to do a build, it doesn't set the Build.SourceBranch variable to the branch name (ie: dev, dev-feature-1, main, etc. in our case), but instead just sets it to the root of the Team Project (ie: $/Team Project in our case), so we aren't able to do conditional logic to perform certain tasks depending on the branch being built, which makes it so we can't have multiple branches built using one build definition, and may leave us with only being able to create a new build and release pipeline for each feature branch (which will be tedious).

A: No, Azure Pipelines doesn't support advanced mapping for builds, nor does TFVC support YAML pipelines.
There are workarounds, but before we explore those, I must strongly urge you and your team to consider moving to Git. TFVC is clearly at the end of its lifetime and Azure DevOps itself is being replaced by GitHub in the future. TFVC is a dead end.
As for the workarounds:

*

*You could have a pipeline that triggers when a new branch is added and then takes the pipeline for your default branch and duplicates that. This can be accomplished using the REST API. You'd have to rewrite the mapping and triggers to match th etarget branch and if all other references to files use the $(Build.SourceDirectory) variable to find the files they need, then the whole pipeline can easily be ported from one branch to another.

*You can use my TFVC - Do not sync sources task to prevent your build from creating a workspace and checking out the files. Then rely on a custom script to setup the correct mapping and fetching files prior to the rest of the pipeline.

*You can use the above task with the TFVC Get task to fetch the sources without having to rely on workspace configuration at all.

To ensure you know which branch to build, you could set a variable at queue time or look at the changeset that triggered the build to fiwure out what branch it triggered on.
But whatever workaround you choose, start planning your migration to Git.


text:
Q: How many times can one edit one's own post? I usually don't need to edit my posts more than five times (at least, I haven't done so so far).
I am just worried, is there any limit to the number of edits allowed? (Apart from the I am a human testing, is there any objection from Stack Exchange's side?)

A: I'm not aware of any limits on the number of times authors can edit their posts.
However, if you edit your post 10 times it will be switched over to community wiki mode. You can see all of the implications of that in this answer to "What are 'Community Wiki' posts?"
In a comment, Grace Note provided some additional references:

For exact limits, see the comments on this question. For which kinds of
  edits actually affect it, see this answer. – Grace Note


text:
Q: Sending S/MIME encrypted emails through SendGrid SMTP I am setting up a WordPress site that will send S/MIME encrypted emails via SendGrid using a plugin called WP PGP Encrypted Emails (looks like it uses PHP's openssl_pkcs7_encrypt). I have successfully sent, and decrypted S/MIME emails with my hosting provider's postfix SMTP servers. However I have to take into account deliverability, so I would like to use SendGrid (which is not a changeable requirement for me) to improve their deliverability.
The issue that I am running into is that first SendGrid's API will reject emails that have the content-transfer-encoding set to "base64". I don't know how significant this header is in the context of S/MIME emails, but whenever I remove it or change it, my emails don't come through as expected. I did some research and found that the API simply doesn't allow changing this header, but that I should be able to modify the content-transfer-encoding header if I send directly to SendGrid's SMTP at smtp.sendgrid.net. If I do that, I can indeed send out an email that arrives with an encrpyted attachment, as expected. The problem is that when I try to decrypt the attachment in Outlook (another requirement), I get a message saying that "the underlying security system cannot verify your Digital ID".
My questions are whether or not anyone has encountered this issue before and been able to resolve it, do SendGrid SMTP servers allow content-transfer-encoding to be modified, and what role does this header play in sending and recieving S/MIME encrypted emails?
Edit: Email Headers
X-Mailer: PHPMailer 6.5.3 (https://github.com/PHPMailer/PHPMailer)
Content-Disposition: attachment; filename="smime.p7m"
Content-Transfer-Encoding: base64
MIME-Version: 1.0
Content-Type: application/pkcs7-mime; smime-type=enveloped-data; name="smime.p7m"; charset=UTF-8


text:
Q: Spark Datagrid editor - numbers only I want a spark datagrid that allow a user to input numbers only. They can only input number with up to 5 decimal places. I am struggling with this in Spark. I can do it in Flex by using the itemEditEnd parameter of the MX DataGrid.
How do I do this is Spark? Any pointers would be great.
Thanks in advance

A: Adding to the previous answer: for simplicity you can extend the default grid item editor and override its 'restrict' property.
import spark.components.gridClasses.DefaultGridItemEditor;

public class GridItemEditorNumber extends DefaultGridItemEditor {

  public function GridItemEditorNumber() {
    super();
    textArea.restrict = "0-9\\.";
  }

}

or, if you prefer to use an inline declaration in the GridColumn:
<s:itemEditor>
  <fx:Component>
    <s:DefaultGridItemEditor initialize="textArea.restrict='0-9\.'"/>
  </fx:Component>
</s:itemEditor>

A: Use an itemEditor that is a custom TextInput that uses the restrict property to limit the characters entered in editable phase.
This is probably the same way I would have done it with the MX DataGrid, I'm not sure what you did in itemEditEnd.  If you want to validate the input the user entered outside of the actual itemEditor component, probably gridItemEditorSessionSave is the closest analogy to itemEditEnd.


text:
Q: Anything wrong with using direct ASCII fonts on webpages? Take this text as an example:

If you make an HTML file copy and paste the above text directly in your text editor from StackOverflow, it will show up on the webpage with that font. Why isn't this the standard way for using fonts in HTML and instead most people just use font color when they could simply use ASCII?

A: For one thing, these specific characters have very specific meanings beyond just the font. See Mathematical Alphanumeric Symbols on Wikipedia and its Unicode chart.
Secondly, presentation and content are separate matters. When the appearance of text has no bearing on the meaning of the text, then the appearance should be controlled by CSS, not the text itself. (Plus, why would you sacrifice all manner of flexibility by hardcoding the appearance in the content itself?)


text:
Q: Explain the aggregate functionality in Spark (with Python and Scala) I am looking for some better explanation of the aggregate functionality that is available via spark in python.
The example I have is as follows (using pyspark from Spark 1.2.0 version)
sc.parallelize([1,2,3,4]).aggregate(
  (0, 0),
  (lambda acc, value: (acc[0] + value, acc[1] + 1)),
  (lambda acc1, acc2: (acc1[0] + acc2[0], acc1[1] + acc2[1])))

Output:
(10, 4)

I get the expected result (10,4) which is sum of 1+2+3+4 and 4 elements.  If I change the initial value passed to the aggregate function to (1,0) from (0,0)  I get the following result
sc.parallelize([1,2,3,4]).aggregate(
    (1, 0),
    (lambda acc, value: (acc[0] + value, acc[1] + 1)),
    (lambda acc1, acc2: (acc1[0] + acc2[0], acc1[1] + acc2[1])))

Output:
(19, 4)

The value increases by 9.  If I change it to (2,0),  the value goes to (28,4) and so on.
Can someone explain to me how this value is calculated?  I expected the value to go up by 1 not by 9, expected to see (11,4) instead I am seeing (19,4).

A: Explanation using Scala
Aggregate lets you transform and combine the values of the RDD at will.
It uses two functions:
The first one transforms and adds the elements of the original collection [T] in a local aggregate [U] and takes the form: (U,T) => U. You can see it as a fold and therefore it also requires a zero for that operation. This operation is applied locally to each partition in parallel.
Here is where the key of the question lies: The only value that should be used here is the ZERO value for the reduction operation.
This operation is executed locally on each partition, therefore, adding anything to that zero value will add to the result multiplied by the number of partitions of the RDD.
The second operation takes 2 values of the result type of the previous operation [U] and combines it in to one value. This operation will reduce the partial results of each partition and produce the actual total.
For example:
Given an RDD of Strings:
val rdd:RDD[String] = ???

Let's say you want to the aggregate of the length of the strings in that RDD, so you would do:

*

*The first operation will transform strings into size (int) and accumulate the values for size.
val stringSizeCummulator: (Int, String) => Int  = (total, string) => total + string.lenght`

*provide the ZERO for the addition operation (0)
val ZERO = 0

*an operation to add two integers together:
val add: (Int, Int) => Int = _ + _
Putting it all together:
rdd.aggregate(ZERO, stringSizeCummulator, add)

with Spark 2.4 and higher version
rdd.aggregate(ZERO)(stringAccumulator,add)

So, why is the ZERO needed?
When the cummulator function is applied to the first element of a partition, there's no running total. ZERO is used here.
Eg. My RDD is:

*

*Partition 1: ["Jump", "over"]

*Partition 2: ["the", "wall"]

This will result:
P1:

*

*stringSizeCummulator(ZERO, "Jump") = 4

*stringSizeCummulator(4, "over") = 8

P2:

*

*stringSizeCummulator(ZERO, "the") = 3

*stringSizeCummulator(3, "wall") = 7

Reduce: add(P1, P2) = 15

A: You can use the following code (in scala) to see precisely what aggregate is doing. It builds a tree of all the addition and merge operations:
sealed trait Tree[+A]
case class Leaf[A](value: A) extends Tree[A]
case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]

val zero : Tree[Int] = Leaf(0)
val rdd = sc.parallelize(1 to 4).repartition(3)

And then, in the shell:
scala> rdd.glom().collect()
res5: Array[Array[Int]] = Array(Array(4), Array(1, 2), Array(3))

So, we have these 3 partitions: [4], [1,2], and [3].
scala> rdd.aggregate(zero)((l,r)=>Branch(l, Leaf(r)), (l,r)=>Branch(l,r))
res11: Tree[Int] = Branch(Branch(Branch(Leaf(0),Branch(Leaf(0),Leaf(4))),Branch(Leaf(0),Leaf(3))),Branch(Branch(Leaf(0),Leaf(1)),Leaf(2)))

You can represent the result as a tree:
+
| \__________________
+                    +
| \________          | \
+          +         +   2
| \        | \       | \
0  +       0  3      0  1
   | \
   0  4

You can see that a first zero element is created on the driver node (at the left of the tree), and then, the results for all the partitions are merged one by one. You also see that if you replace 0 by 1 as you did in your question, it will add 1 to each result on each partition, and also add 1 to the initial value on the driver. So, the total number of time the zero value you give is used is:
number of partitions + 1.
So, in your case, the result of
aggregate(
  (X, Y),
  (lambda acc, value: (acc[0] + value, acc[1] + 1)),
  (lambda acc1, acc2: (acc1[0] + acc2[0], acc1[1] + acc2[1])))

will be:
(sum(elements) + (num_partitions + 1)*X, count(elements) + (num_partitions + 1)*Y)

The implementation of aggregate is quite simple. It is defined in RDD.scala, line 1107:
  def aggregate[U: ClassTag](zeroValue: U)(seqOp: (U, T) => U, combOp: (U, U) => U): U = withScope {
    // Clone the zero value since we will also be serializing it as part of tasks
    var jobResult = Utils.clone(zeroValue, sc.env.serializer.newInstance())
    val cleanSeqOp = sc.clean(seqOp)
    val cleanCombOp = sc.clean(combOp)
    val aggregatePartition = (it: Iterator[T]) => it.aggregate(zeroValue)(cleanSeqOp, cleanCombOp)
    val mergeResult = (index: Int, taskResult: U) => jobResult = combOp(jobResult, taskResult)
    sc.runJob(this, aggregatePartition, mergeResult)
    jobResult
}

A: I don't have enough reputation points to comment on the previous answer by Maasg.
Actually the zero value should be 'neutral' towards the seqop, meaning it wouldn't interfere with the seqop result, like 0 towards add, or 1 towards *;
You should NEVER try with non-neutral values as it might be applied arbitrary times.
This behavior is not only tied to num of partitions.
I tried the same experiment as stated in the question.
with 1 partition, the zero value was applied 3 times.
with 2 partitions, 6 times.
with 3 partitions, 9 times and this will go on.

A: I wasn't fully convinced from the accepted answer, and JohnKnight's answer helped, so here's my point of view:
First, let's explain aggregate() in my own words:
Prototype:

aggregate(zeroValue, seqOp, combOp)

Description:
aggregate() lets you take an RDD and generate a single value that is of a different type than what was stored in the original RDD.
Parameters:

*

*zeroValue: The initialization value, for your result, in the desired
format.

*seqOp: The operation you want to apply to RDD records. Runs once for
every record in a partition.

*combOp: Defines how the resulted objects (one for every partition),
gets combined.

Example:

Compute the sum of a list and the length of that list. Return the result in a pair of (sum, length).

In a Spark shell, I first created a list with 4 elements, with 2 partitions:
listRDD = sc.parallelize([1,2,3,4], 2)

then I defined my seqOp:
seqOp = (lambda local_result, list_element: (local_result[0] + list_element, local_result[1] + 1) )

and my combOp:
combOp = (lambda some_local_result, another_local_result: (some_local_result[0] + another_local_result[0], some_local_result[1] + another_local_result[1]) )

and then I aggregated:
listRDD.aggregate( (0, 0), seqOp, combOp)
Out[8]: (10, 4)

As you can see, I gave descriptive names to my variables, but let me explain it further:
The first partition has the sublist [1, 2]. We will apply the seqOp to each element of that list and this will produce a local result, a pair of (sum, length), that will reflect the result locally, only in that first partition.
So, let's start: local_result gets initialized to the zeroValue parameter we provided the aggregate() with, i.e. (0, 0) and list_element is the first element of the list, i.e. 1. As a result this is what happens:
0 + 1 = 1
0 + 1 = 1

Now, the local result is (1, 1), that means, that so far, for the 1st partition, after processing only the first element, the sum is 1 and the length 1. Notice, that local_result gets updated from (0, 0), to (1, 1).
1 + 2 = 3
1 + 1 = 2

and now the local result is (3, 2), which will be the final result from the 1st partition, since they are no other elements in the sublist of the 1st partition.
Doing the same for 2nd partition, we get (7, 2).
Now we apply the combOp to each local result, so that we can form, the final, global result, like this: (3,2) + (7,2) = (10, 4)

Example described in 'figure':
            (0, 0) <-- zeroValue

[1, 2]                  [3, 4]

0 + 1 = 1               0 + 3 = 3
0 + 1 = 1               0 + 1 = 1

1 + 2 = 3               3 + 4 = 7
1 + 1 = 2               1 + 1 = 2
    |                       |
    v                       v
  (3, 2)                  (7, 2)
      \                    /
       \                  /
        \                /
         \              /
          \            /
           \          /
           ------------
           |  combOp  |
           ------------
                |
                v
             (10, 4)

Inspired by this great example.

So now if the zeroValue is not (0, 0), but (1, 0), one would expect to get (8 + 4, 2 + 2) = (12, 4), which doesn't explain what you experience. Even if we alter the number of partitions of my example, I won't be able to get that again.
The key here is JohnKnight's answer, which state that the zeroValue is not only analogous to the number of partitions, but may be applied more times than you expect.

A: Great explanations, it really helped me to understand the underneath working of the aggregate function. I have played with it for some time and found out as below.

*

*if you are using the acc as (0,0) then it will not change the result of the out put of the function.

*if the initial accumulator is changed then it will process the result something as below

[ sum of RDD elements + acc initial value * No. of RDD partitions +
  acc initial value ]

for the question here, I would suggest to check the partitions as the number of partitions should be 8 as per my understanding as every time we process the seq op on a partition of RDD it will start with the initial sum of acc result and also when it is going to do the comb Op it will again use the acc initial value once.
for e.g.
   List (1,2,3,4) & acc (1,0)
Get partitions in scala by RDD.partitions.size
if Partitions are 2 & number of elements is 4 then =>  [ 10 + 1 * 2 + 1 ] => (13,4)
if Partition are  4 & number of elements is 4 then =>  [ 10 + 1 * 4 + 1 ] => (15,4)
Hope this helps, you can check here for explanation. Thanks.

A: Thanks to gsamaras.
My viewgraph is as below,

A: For people looking for Scala Equivalent code for the above example - here it is. Same logic, same input/result.
scala> val listRDD = sc.parallelize(List(1,2,3,4), 2)
listRDD: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[2] at parallelize at <console>:21

scala> listRDD.collect()
res7: Array[Int] = Array(1, 2, 3, 4)

scala> listRDD.aggregate((0,0))((acc, value) => (acc._1+value,acc._2+1),(acc1,acc2) => (acc1._1+acc2._1,acc1._2+acc2._2))
res10: (Int, Int) = (10,4)

A: I try many experiments about this question. It is better to set num of partition for aggregate. the seqOp will process each partion and apply the initial value, what' more, combOp will also apply the initial value when combines all partitions.
So, I present the format for this question:
final result = sum(list) + num_Of_Partitions * initial_Value + 1

A: I will explain the concept of Aggregate operation in Spark as follows:
Definition of the aggregate function
**def aggregate** (initial value)(an intra-partition sequence operation)(an inter-partition combination operation)

val flowers = sc.parallelize(List(11, 12, 13, 24, 25, 26, 35, 36, 37, 24, 25, 16), 4)   --> 4 represents the number of partitions available in our Spark cluster.
Hence, the rdd is distributed into 4 partitions as:
11, 12, 13
24, 25, 26
35, 36, 37
24, 25, 16

we divide the problem statement into two parts:
The first part of the problem is to aggregate the total number of flowers picked in each quadrant; that's the intra-partition sequence aggregation
11+12+13 = 36
24+25+26 = 75
35+36+37 = 108
24+25 +16 = 65

The second part of the problem is to sum these individual aggregates across the partitions; that's the inter-partition aggregation.
36 + 75 + 108 + 65 = 284

The sum, stored in an RDD can further be used and processed for any kind of transformation or other action
So the code becomes like:
val sum = flowers.aggregate(0)((acc, value) => (acc + value), (x,y) => (x+y))         or
val sum = flowers.aggregate(0)(_+_, _+_)
Answer: 284
Explanation: (0) - is the accumulator
The first + is the intra-partition sum, adding the total number of flowers picked by each picker in each quadrant of the garden.
The second + is the inter-partition sum, which aggregates the total sums from each quadrant.
Case 1:
Suppose, if we need to reduce functions after the initial value. What would happen if initial value weren't zero??. If it were 4, for example:
The number would added to each intra-partition aggregate, and also to the inter-partition aggregate:
So the first calculation would be:
11+12+13 = 36 + 5 = 41
24+25+26 = 75 + 5 = 80
35+36+37 = 108 + 5 = 113
24+25 +16 = 65 + 5 = 70

Here's the inter-partition aggregation calculation with the initial value of 5:
partition1 + partition2 + partition3+ partition4 + 5 = 41 + 80 + 113 + 70 = 309

So, coming to your query: The sum can calculated based on the number of partitions the rdd data is distributed. i thought that your data is distributed as below and that's why you have the result as (19, 4). So, when doing aggregate operation be specific with number of partition value:
val list = sc.parallelize(List(1,2,3,4))
val list2 = list.glom().collect
val res12 = list.aggregate((1,0))(
      (acc, value) => (acc._1 + value, acc._2 + 1),
      (acc1, acc2) => (acc1._1 + acc2._1, acc1._2 + acc2._2)
)

result:
list: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[19] at parallelize at command-472682101230301:1
list2: Array[Array[Int]] = Array(Array(), Array(1), Array(), Array(2), Array(), Array(3), Array(), Array(4))
res12: (Int, Int) = (19,4)

Explanation: As your data is distributed in 8 partitions, the result is like (by using the above explained logic)
intra-partition addition:
0+1=1
1+1=2
0+1=1
2+1=3
0+1=1
3+1=4
0+1=1
4+1=5

total=18

inter-partition calculation:
18+1 (1+2+1+3+1+4+1+5+1) = 19

Thank you


text:
Q: Redis - `CONFIG REWRITE failed: Permission denied` I am trying to install and configure a redis service on centos7.
redis tries to rewrite its configuration file from time to time with no success, so it throws the following error:
CONFIG REWRITE failed: Permission denied

the file exists in /etc/redis.conf, and it's permissions are:
-rw-r--r--. 1 redis redis 46765 Jun 13 06:20 /etc/redis.conf

I even tried to change the permission to chmod 777 /etc/redis.conf, and that did not fix the issue.
redis runs under the user redis.
How can I fix this?

A: Most certainly you have issues with SElinux. Either disable it (which I don't recommend) with setenforce 0 for a temp disable, or change the permissive/disabled mode in /etc/selinux/config for a permanent "solution".
What you should do is configure SElinux to allow redis to work - I suggest you start from here: Unable to start Redis under SELinux


text:
Q: VS15 gives warnings but compiles std::function instantiated with std::bind I've been trying to figure out how to properly instantiate a vector of std::pairs of std::functions (e.g. std::vector<std::pair<std::function<bool()>, std::function<void(int)>>>). Upon doing so however, Visual Studios 15 gives me a red underlining warning in my code even though it still compiles. I decided to start with just a basic std::function initialization using std::bind, but that too gave me an underlining error that compiles.
I kind of understand it's that std::bind doesn't return an std::function, but I've seen numerous examples of instantiating std::functions the way I do with the second underlining/warning.
Am I setting myself up for failure here, or is visual studios just giving me a false positive on these errors?

CODE:
#include <functional>
#include <vector>

class A {
public:
    bool myFunc() {
        return false;
    };
    void myDoFunc(int x) {
        std::cout << "HiXXX";
    };
    class Seq{
    public:
        std::vector<std::pair<std::function<bool()>, std::function<void(int)>>> sequencePieces;
        const char* name;

        Seq(const char* _name, std::vector<std::pair<std::function<bool()>, std::function<void(int)>>> _sequencePieces):
            name(_name),
            sequencePieces(_sequencePieces)
        {}
    };
    std::function<bool()> sequenceStep;
    Seq seq1;

    A() :
        seq1( "ASDF",
    {
        /*Error 1*/
        std::pair<std::function<bool()>, std::function<void(int)>>(
            std::bind(&A::myFunc,this),
            std::bind(&A::myDoFunc, this, 1)
            )
    }
        )
    {
        /*Error 2*/
        sequenceStep = std::bind(&A::myFunc, *this);
    };
};


text:
Q: Getting rid of a blank line but keeping others intact After deleting an entry from a file, am left with a blank line where the entry used to be, and would like to know how to get rid of it at the same time of script execution.
My data.txt file has the following entries:
1
12
123 (line to be deleted)
1234
(blank line, carriage return)

plus an empty line at the bottom of the line which I would like to keep but not the one left after an entry has been deleted.
what I'm left after entry has been deleted:
1
12

1234
(blank line, which I want to keep intact)

Here is my present working code below:
$bodycont = preg_replace("/\b({$_POST['inscripnum1']})\b/","",$index);

How can I implement something on the same line to delete the line that the number was on?
Any help would be greatly appreciated.
Thank you

A: Capture the line break in the regex:
$bodycont = preg_replace("/\b({$_POST['inscripnum1']})\b\n/","",$index);


text:
Q: Reflexive relation of sharing with yourself? I'm looking at Sets, Logic and Maths for Computing by David Makinson and on page 56 is an example

Identify the status of the following relations as
reflexive/irreflexive/neither over the set of all people living in the
UK: sibling of, shares at least one parent with, ancestor of, lives in
the same city as, has listened to music played by.

Then, the explanation says

The relation 'sibling of' as ordinarily understood is not reflexive
since we do not regard a person as a sibling of himself or herself. In
fact, it is irreflexive. By contrast, shares at least one parent with'
is reflexive. It follows that these two relations are not quite the
same. 'Ancestor of' is irreflexive. 'Lives in the same city as', under
its most natural meaning, is neither reflexive nor irreflexive, since
not everyone lives in a city. 'Has listened to music played by' is
neither reflexive nor irreflexive for similar reasons.

For "shares at least one parent with," this relationship to be reflexive would have to be, e.g., I share at least one parent with myself. I see this as symmetric since two siblings can say that, but not reflexive.


text:
Q: how to get value from json click event array in react I have a list of data displayed from an API and when clicked shows relating data for example a list of authors which shows papers they have wrote once clicked. due to database restrictions I need to get the paper ID value from the paper that shows when an author is clicked.
does anybody know how to do this?
data from fetch
Paper.js
import React from "react";
import AuthorsNoClick from './authorsNoClick';

class Paper extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            display: false
        }
    }

    handleClick = () => {
        this.setState({display:!this.state.display})
    }

    render() {
        let details ="";
        if (this.state.display){
            details =

Abstract

{this.props.paper.abstract}

                <AuthorsNoClick paperid={this.props.paper.paper_id}/>

        }
        return (

{this.props.paper.title}

                {details}

         );
    }
}

export default Paper;

AuthorNoClick.js
import React from "react";

class AuthorNoClick extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            display: false
        }
    }

    render() {

        return(

{this.props.author.first_name + ' ' + this.props.author.last_name}

        )
    }
}

export default AuthorNoClick;

AuthorsNoClick.js
import React from 'react';
import AuthorNoClick from './authorNoClick';

class AuthorsNoClick extends React.Component {
    constructor(props){
        super(props)
        this.state = { results : [] } // declaring state
        console.log("constructor");
    }

    componentDidMount() {
        let url = "http://localhost/api/authors";

        if (this.props.paperid !== undefined){
            url += "?paperid=" + this.props.paperid;
        }

        fetch(url)
        .then((response) => {

            if (response.status === 200) {
                return response.json()
              } else {
                throw Error(response.statusText);
              }
        })
        .then((data) => {
            this.setState({results:data})
        })
        .catch((err) => {
            console.log("something went wrong", err)
        })
        console.log("mounted")
    }
    render() {
        console.log("render");
        console.log(this.state.results);
        return (

Authors:

                {this.state.results.map( (author, i) => (<AuthorNoClick key={i} author={author} />) )}

        )
    }
}

export default AuthorsNoClick;

papers.js
class Papers extends React.Component {
    constructor(props){
        super(props)
        this.state = { results : [] } // declaring state
        console.log("constructor");
    }

    componentDidMount() {
        let url = "http://localhost/api/papers";

        if (this.props.author_id !== undefined){
            url += "?authorid=" + this.props.author_id;
        }

        fetch(url)
        .then((response) => {
            if (response.status === 200) {
                return response.json()
              } else {
                throw Error(response.statusText);
              }

        })
        .then((data) => {
            this.setState({results:data})
        })
        .catch((err) => {
            console.log("something went wrong", err)
        })
        console.log("mounted")
    }
    render() {
        console.log("render");
        console.log(this.state.results);

        return (

                {this.state.results.map( (paper, i) => (<Paper key={i} paper={paper}/>) )}

        )
    }
}

export default Papers;

A: There are a lot of ways to achieve that, and there are several steps to do: (I will write functional components, but the logic is the same)

*

*In the Author component add an id prop and in that way you will identify the component <Author id={author.id}/>

*After fetching the whole list of authors, you need to create a click handler and a different state for the selected user
 const handleAuthor = (e) => { setSelectedAuthor(e.target.id)}

*Once you have the id saved in the new state, you can use Array.filter() to display posts that only matches the id you have in the state
authors.filter(author => author.id === selectedAuthor.id && <Author />)


text:
Q: Entity Framework Inheritance: Foreign Key in the same table I am using Entity framework.  I am using inheritance, which puts different object types in the same table (via discriminator).
However, this causes an issue as relationships between objects in the same table can not be illustrated via a foreign key.  Any suggestions how to solve?  Some code below.
public abstract class DivBase
{
    public int Id { get; set; }

    [Required]
    public DateTimeOffset DateCreated { get; set; }

    [Required]
    public int CreatedByUserId { get; set; }

    [Required]
    public DateTimeOffset DateModified { get; set; }

    [Required]
    public int ModifiedByUserId { get; set; }
}
public abstract class DivClaim : DivBase
{
    [Required]
    [MaxLength(256)]
    public string ClaimType { get; set; }

    [Required]
    [MaxLength(256)]
    public string Name { get; set; }

    [MaxLength(10000)]
    public string Description { get; set; }

    public ICollection<DivUserClaim> UserClaims { get; set; }
}

public class DivCustomer : DivClaim
{
    public ICollection<DivProject> Projects { get; set; }
}

public class DivProject : DivClaim, IDivEvent
{
    public int CustomerId { get; set; }
    public DivCustomer Customer { get; set; }
    public DateTimeOffset StartDate { get; set; }
    public DateTimeOffset EndDate { get; set; }
}

A: In this case where your base class just defines common attributes for all your entities, simply exclude the base class from the DbContext.  Each of your Entities will get its own table, but they will all have the properties inherited from the base class.  You just won't be able to query over the base entity type.


text:
Q: Google translate API POST 11second delay? EDIT: 11.5 seconds for 28 messages
Single requests work fine. This code below takes 11 seconds, measured using postman setting route in API to access.
Am I doing something wrong? I feel as though it shouldn't take 11 seconds even without cache.
$xs = ChatMessage::where('chat_room_id','=',$roomId)
->with('user')
->orderBy('created_at','DESC')
->get();

    foreach($xs as $r){

        $translate = new TranslateClient([
            'key' => 'xxxxxxxxxxxxxxxxxxxxxxx'
        ]);

        $result = $translate->translate($r->message_english, [
            'target' =>'es',
            'source' => 'en',
        ]);

        $r->message = $result['text'];
    }

return $xs;

A: I think you can easily speed the process by just moving the client out of the for each loop. You are creating a client each time you iterate. That's not optimal. You should be able to reuse the client per translate call. That should speed your translation process. You can find samples of this usage in the official github client project
Here is a pseudo code sample:
client = new TranslateClient()

foreach(message in messages)
   result = client.translate(message)
   print(result)

Also, how long is your translated text? You should pass the whole text to be translated into a single call (as long as the supported library allows) So you also reduce the calls done to the API.
If you still have issues you can go by using multiple request in parallel as mentioned in the comments.
Some useful links about this:

*

*PHP Documentation Overview

*Translate Client


text:
Q: Kafka Streams Window Store Retain Duplicates The docs are unclear.  When would I want to set retain duplicates to false/true.  What is this used for?  Is it for something particular in RocksDB?
https://kafka.apache.org/21/javadoc/org/apache/kafka/streams/state/Stores.html#persistentWindowStore-java.lang.String-java.time.Duration-java.time.Duration-boolean-
Digging through streams internal code seems to being used to set some sequence number?
RocksDBWindowStore.java
private void maybeUpdateSeqnumForDups() {
    if (this.retainDuplicates) {
      this.seqnum = this.seqnum + 1 & 2147483647;
    }

A: Well, as the name indicates, you can enable storing duplicates if you want to store multiple rows, with the same key. For window stores, the key is comprise of record key and window start timestamp.
Kafka Streams uses this feature for KStream-KStream joins. For this case, each input record is stored in its own window in the store (using the record timestamp as window start timestamp). Because there might be multiple records with the same key and same timestamp, it's required to enable this flag to compute the correct join. Otherwise, the join result might be incomplete.


text:
Q: How to carry out arithmetic operations based on months over a combination of years? Consisting of drought report/index for every month (there's multiple reports/indices per month), 2000–2021:

I want to show drought indices for all the months from a combination of 2000 through 2021, i.e., summing drought indices of Jan 2000, Jan 2001, Jan 2002, Jan 2003, Jan 2004, ... and Jan 2021, and returning it. And then summing drought indices for Feb 2000, Feb 2001, Feb 2002, Feb 2003, Feb 2004, ... and Feb 2021, and returning it. And then summing drought indices Mar 2000, Mar 2001, Mar 2002, Mar 2003, Mar 2004, ... and Mar 2021, and returning it. And then summing for Apr 2000, Apr 2001, Apr 2002, Apr 2003, Apr 2004, ... and Apr 2021, and returning it. And so on for the rest of the months.
I tried creating a regex str.contains() function to sum all the drought indices for all column values containing a certain month; however, that method only works for string, not datetime.
How do I go about carrying out this task?
Appreciate any assistance! (beginner at pandas and the whole jupyter environment)

A: You could split the date first
iDate = str(20000104)
year = iDate[0:4]
month = iDate[4:6]
day = iDate[6:8]
year, month, day

('2000', '01', '04')

Then you might use the some of the various time and time looping functions of python. Some of them are used here as an example


text:
Q: Menu inflater exits fullscreen I want to run my app in fullscreen and have a popup menu. Triggering the menu also exits fullscreen by overlaying the navigation and action bar. I don't want this to happen and can't for the life of me figure it how to fix this. The menu otherwise works fine.
The Menu xml
<?xml version="1.0" encoding="utf-8"?>

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

 <item android:title="Data"
    android:id="@+id/data"></item>
 <item android:title="Calibrate"
    android:id="@+id/calibrate"></item>
 <item android:title="Help"
    android:id="@+id/help"></item>

 </menu>

The trigger
public void showPopup(View v) {
  PopupMenu popup = new PopupMenu(this, v);
  popup.inflate(R.menu.menu_main);
  popup.show();
}


text:
Q: Three.js - Edit plane geometry So, I want to make a simple terrain editor. So, on mouseDown, I want the selected face to move up.
The intersection works great, and I try to modify the geometry like so:
        var intersects2 = ray.intersectObjects([plane]);
        if (intersects2.length > 0) {
            var face = intersects2[0].face;
            var obj1 = intersects2[0].object;

            var geo = obj1.geometry;

            geo.vertices[face.a].z += 50;
            geo.vertices[100].z += 50;
            geo.vertices[0].z += 50;

            geo.computeVertexNormals();
            geo.computeFaceNormals();

            geo.__dirtyVertices = true;
            geo.__dirtyNormals = true;

            console.log(face.a);

        }

The console log shows the correct vertex index, but nothing on the plane moves. Any ideas why?
The plane is created like this:
    var planegeo = new THREE.PlaneGeometry( 500, 500, 10, 10 );
    planegeo.dynamic = true;
    plane = new THREE.Mesh( planegeo, new THREE.MeshPhongMaterial( { color: 0x99ff66 } ) );
    plane.receiveShadow = true;
    scene.add( plane );

A: Looking at your code, it looks like you are using syntax pre R49. It may just be that you need to update your dirty flag code to (assuming you are now using a newer library!):
geo.verticesNeedUpdate = true;
geo.normalsNeedUpdate = true;


text:
Q: System.AccessViolationException with double pointer? I want to compress textures to pvrtc in managed code so I've found a source which does what I want but I get a System.AccessViolationException. This is the code I use so far:
[DllImport("x86/pvrtc.dll", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr CompressTexture(byte[] data, int height, int width, int mipLevels, bool preMultiplied, bool pvrtc4bppCompression, ref IntPtr dataSizes);

public static byte[] Compress(byte[] data, int height, int width, int mipLevels, bool preMultiplied, bool pvrtc4bppCompression)
{
    IntPtr dataSizesPtr = Marshal.AllocCoTaskMem(data.Length + 1);

    var texDataPtr = CompressTexture(data, height, width, mipLevels, preMultiplied, pvrtc4bppCompression, ref dataSizesPtr);
    //Store the size of each mipLevel
    var dataSizesArray = new int[mipLevels];
    //Copies data from an unmanaged memory pointer to a managed 8-bit unsigned integer array.
    Marshal.Copy(dataSizesPtr, dataSizesArray, 0, dataSizesArray.Length);
    var levelSize = 0;
    byte[] levelData = new byte[0];

    for (int x = 0; x < mipLevels; x++)
    {
        levelSize = dataSizesArray[x];
        levelData = new byte[levelSize];

        Marshal.Copy(texDataPtr, levelData, 0, levelSize);

        texDataPtr = IntPtr.Add(texDataPtr, levelSize);
    }
    return levelData;
}

Any help is very much appreciated.


text:
Q: Group [time] by 5 sec intervals I have data containing seconds [time] value. I'd like count my data based on how many records/second.
This works like this:
SELECT [Time], count(*)

FROM [dbo].[Times]
GROUP BY
[Time] ORDER By [Time]

This gives me:
+----------+----+
| 00:00:00 | 4  |
+----------+----+
| 00:00:01 | 2  |
+----------+----+
| 00:00:02 | 1  |
+----------+----+
| 00:00:08 | 2  |
+----------+----+
...

I'd like to group and count them in 5 second intervals, so the result would look like:
+----------+----+
| 00:00:05 | 7  |   <--   # of records between 0:00:00 and 0:00:05
+----------+----+
| 00:00:10 | 2  |   <--   # of records between 0:00:05 and 0:00:10
+----------+----+
...

Any good way yo do this in MS SQL?

A: Here is one method:
select cast(dateadd(second, (datediff(second, 0, [time]) / 5) * 5, 0) as time(0)) as [time],
       count(*)
from [dbo].[Times] t
group by dateadd(second, (datediff(second, 0, [time]) / 5) * 5, 0)
order by min([time]);

EDIT:
As pointed out in a comment, you can write:
select v.[Time], count(*)
from [dbo].[Times] t cross apply
     (values (cast(dateadd(second, (datediff(second, 0, [time]) / 5) * 5, 0) as time(0)) )
     ) as v([Time])
group by v.[Time]
order by v.[Time];

This puts the complicated calculation in only one place -- preventing the type of error that I made when editing the original answer.


text:
Q: MVC: Generating an AntiForgeryToken for a AJAX response to the client I've spent a good few hours tonight trying to work this one out. Basically I have a form in MVC with an AntiForgeryToken so when I post back everything is validated and it's all good.  The problem is that I have a JSON result method that generates a load of markup and returns HTML to the user. I am regenerating forms to return to the user in an ajax way, so I need to put the token into the HTML I return to the client otherwise when they POST back again the antiforgery stuff will still work.
So the essence of my problem is how would I access the token in order to put it in my dynamically generated html server side and how would I generate the matching cookie and then send it all back in the response to the user? Can't seem to find anything on google about this but people must be doing it.  Help would be very much appreciated as my brain is starting to shutdown!
Thanks
This is the form
<form action="/DoSomething" method="post">
    <input name="__RequestVerificationToken" type="hidden" value="saTFWpkKN0BYazFtN6c4YbZAmsEwG0srqlUqqloi/fVgeV2ciIFVmelvzwRZpArs" />
    <!-- rest of form goes here -->
</form>

So in my controller i am building tis form with a stringbuilder to send back to the client in a JSON result but i need to be able to add the value for the __RequestVerificationToken to the input so that my security will still work


text:
Q: Threadpool implementation: condition_variables vs. yield() I try to develop a threadpool in C++ and I wonder if it is better to yield() the thread in the main loop of the worker thread or to wait on a condition variable:
void worker_thread( void )
{
    // this is more or less pseudocode
    while( !done )
    {

        if( task_available )
             run_task();
        else
            std::this_thread::yield();
    }
}

versus
void worker_thread( void )
{
    // this is more or less pseudocode

    std::unique_lock< std::mutex > lk( mutex_ );
    while( !done )
    {

        if( task_available )
             run_task();
        else
            condition_.wait( lk );
    }
}

Any ideas? Will there be any performance differences between both versions?

A: The cost of a thread switch is the same either way. As for whether you should use polling or condition variables, the latter can rest the processor by kicking the thread off until there is really something to do. That results in lower CPU utilization. The polling method will allow the thread to return and "try again", effectively running the CPU indefinitely.
It's worth point-out that there are a few applications that prefer polling, like when task_available is false for very short amounts of time (i.e. there is usually work to do). In that case, you will want to poll task_available in a loop with a counter; only yield the thread when the counter exceeds a threshold.

A: if your threads in the thread pool are constantly fed with tasks and you need fast response time, then yield is what you want, but yield will burn cpu cycles no matter what the waiting thread is doing.
if not, you can use the conditional approach, threads will sleep until a task is ready (note though, a conditional can wake a thread, even if no ready signal was sent), the response time might be slower, but you will not burn cpu cycles.
i would recommend the conditional approach, and if the reaction time is too slow, switch to yield.


text:
Q: How to bind a multi record HTML form data to AutoPopulatingList I am building a paginated form which allows traversing the entire "Book" table page by page and allows updating the entire page of records with one submission.
The screen will have a two dimensional form with rows and columns of text boxes, like a spread sheet, where each row corresponds to one Book object in the page and each column corresponds the fields of the Book object.
Steps taken:
1.Used a PagingAndSortingRepository to retrieve Page records
2.Copied the list of books to a FormBean backed by AutoPopulatingList
I am using freemarker templates for screen(because Spring boot documentation advises to avoid JSP while developing a spring boot app)
Help needed on:
Q1) How to bind the AutopopulatingList to freemarker's @Spring.bind and render one row of @spring.formInput text boxes (one text box per Book fields) (presently i rendered it using plain html and freemarker <#list> tags)
Q2) How to read the submitted form values into myFormBean.AutoPopulatingList
My Form Bean
//Form Bean backed by AutoPopulatingList
//Use AutoPopulatingList to allow flexible page sizes
public class MyBookListFormBean {

    private AutoPopulatingList<Book>  booksList;
    //getter, setter, constructor
    public void add(List<Book> books) {
        booksList.addAll(books); //copy paged data into AutoPopulatingList
    }
}

Controller methods
  //show Form page method.
  //This allows to navigate through the table
  //and show a form screen per page of data which can be submitted to different URL.
  //this method is run when "first/prev/next/last" links below the form are clicked
  @RequestMapping(value="/books")
  public String showPagedForm(Model model, Pageable page,
                @ModelAttribute("booksForm") MyBookListFormBean formBean ) {

    Page<Book> allBooks = booksRepository.findAll(pageable);
    model.addAttribute("booksPage",allBooks);
    formBean.addToList(allBooks.getContent());  //add current page data to Form Bean
    return "/books/index";
  }

  //submit Form
  @RequestMapping(value="/books/updateAPageOfRecords" method=RequestMethod.POST)
  public String updateAPageOfRecords( Model model, Pageable page,
         @ModelAttribute("booksForm") MyBookListFormBean formBean,
         BindingResult result  )   {
    //tried to print the submitted data
    //NOTHING got bound !!!

  }


text:
Q: Joint Entropy of Cascaded BSC H(X|Y,Z) I'm trying to calculate the H(X, Y, Z) of the cascaded BSC channel. So I calculated partly but I couldn't calculate some parts. Could you please help me?
Here is the Channel diagram -
enter image description here
$$H(X,Y,Z)=H(Y,Z)+H(X|Y,Z) $$
I calculate the first term H(Y, Z) like as below.
$$H(Y,Z)=H(Y)+H(Z|Y) $$
$$H(Y)=1/2$$
$$H(Z|Y) = -\sum p(y)\sum p(z|y)\log_2p(z|y))$$
$$=-p(y=0).p(z=0|y=0)\log_2p(z=0|y=0)$$
$$-p(y=0).p(z=1|y=0)\log_2p(z=1|y=0)$$
$$-p(y=1).p(z=0|y=1\log_2p(z=0|y=1)$$
$$-p(y=1).p(z=1|y=1)\log_2p(z=1|y=1$$
$$=-\left [ 0.5(1-\varepsilon ) \log_2(1-\varepsilon )+0.5(1-\varepsilon ) \log_2(1-\varepsilon )+0.5(\varepsilon ) \log_2(\varepsilon )+0.5(\varepsilon ) \log_2(\varepsilon )\right ]$$
$$=-(1-\varepsilon ) \log_2(1-\varepsilon )-(\varepsilon ) \log_2(\varepsilon )$$
How could I calculate the below term? I couldn't understand how to do that.
$$H(X│Y,Z)=?$$

A: This is a Markov process $X \to Y \to Z$, hence $$H(X,Y,Z) = H(Z|Y,X) + H(Y|X)+H(X)=H(Z|Y) + H(Y|X)+H(X)$$
Now, $H(Y|X)=H(Z|Y)=h(\epsilon)$ where $h(x)=-x \log(x) - (1-x) \log(1-x)$ is the binary entropy function.
As for $H(X)$, that is not something given by the channel, but by the input distribution. Assuming a uniform input distribution, $H(X)=1$ bit (I guess your $H(Y)=1/2$ is a mistake).
Hence, finally $H(X,Y,Z)= 2 h(\epsilon) +1$ bits.


text:
Q: How to receive a stack element in a function I'm currently using stack library on c++ but i don't know how to receive a stack of numbers in a function.. example---->
int main
{
    stack <int> pila1;
    juegoEnsayo(pila1);
}

void juegoEnsayo(/*What is supposed to be here???*/ &unaPila)
{
    unaPila.push(6);
    unaPila.push(9);
    unaPila.push(8);
}

A: I suppose stack <int> to be there.
#include <stack>

using namespace std;

void juegoEnsayo(stack<int> &unaPila)
{
    unaPila.push(6);
    unaPila.push(9);
    unaPila.push(8);
}

int main()
{
    stack <int> pila1;
    juegoEnsayo(pila1);
}

A: Use stack<int>. So prototype of function will be:
    void juegoEnsayo(stack<int>& unaPila);
Following is working example. You can find it working here:
#include <stack>
#include <iostream>

using namespace std;

void juegoEnsayo(stack<int>& unaPila)
{
    unaPila.push(6);
    unaPila.push(9);
    unaPila.push(8);
}

template<typename T> void printElm(stack<T> mystack)
{
    while (!mystack.empty())
    {
        cout << mystack.top() << " | ";
        mystack.pop();
    }
}

int main()
{
    stack<int> pila1;
    printElm(pila1);
    cout<<endl;
    juegoEnsayo(pila1);
    printElm(pila1);
    return 0;
}


text:
Q: Aggregate by month-year and keep type as date I want to create some summary statistics of a data.table, aggregating by month and year of the date column. Here's what I start with:
> head(monthly)
      betnr   persnr idnum frau gebjahr   te_med      month   tentgelt status
1: 50536344 62181514 40442    1    1960 76.52142 1993-12-01  0.5777598   fire
2: 50536344 62744472 40442    0    1963 76.52142 1993-08-01  0.5777598   fire
3: 50536344 63071749 40442    0    1947 76.52142 1993-12-01  0.5777598   fire
4: 50536344 63385685 40442    1    1946 76.52142 1993-07-01  0.5777598   fire
5: 50536344 63918388 40442    0    1952 76.52142 1993-12-01  0.5777598   fire
6: 50536344 61961225 40442    0    1980 71.90094 1994-12-01 23.1001672   fire

To create my statistics, I then run
statistics2 <- monthly[, list(NOBS = .N, MWAGE=mean(tentgelt)), by=list(status, month=format(month, '%m-%Y'))]

This creates the correct statistics, but the month column now contains a string. I try to change the type to date by fixing the days to be 01 always:
x <-apply(statistics2, 1, function(x) paste('01-',x['month'], sep=''))
statistics2[, month:= as.Date(x, '%d-%m-%Y')]

Which gives me the desired output:
> head(statistics2)
   status      month  NOBS      MWAGE
1:   hire 1993-01-01 37914  0.5820961
2: normal 1993-01-01   790  0.5787695
3:   hire 1994-01-01  6471 15.1267445
4: normal 1994-01-01 23931 22.8101928
5:   hire 1993-02-01   435  0.5946736
6: normal 1993-02-01 38661  0.5820226

However, my whole approach feels a bit cloddy. Is there a cleaner way of getting the desired output?

A: Yes, you can make it simpler and do everything in one go. Just do the whole conversion to Date class in the aggregation process
statistics2 <- monthly[, list(NOBS = .N,
                         MWAGE = mean(tentgelt)),
                         by = list(status, month = as.Date(format(month, '%Y-%m-01')))]
statistics2
#    status      month NOBS      MWAGE
# 1:   fire 1993-12-01    3  0.5777598
# 2:   fire 1993-08-01    1  0.5777598
# 3:   fire 1993-07-01    1  0.5777598
# 4:   fire 1994-12-01    1 23.1001672

Some side notes:

*

*As @beginner mentioned in his comment, there is no "Year-Month" date
type in R, see this
r-faq

*Your apply method is not how you should have done this with data.table. You could accomplish your last step simply by doing:
statistics2[, month := as.Date(paste0("01-", month), "%d-%m-%Y")]


text:
Q: Wordpress getting updated meta for multiple posts I am working with wp updating meta values.In my codes here is the main function :
$get_post_ids = array();
$get_post_ids[] = $_REQUEST['ids'];

foreach ($get_post_ids as $post_id) {
  $meta_value = get_post_meta( $post_id, 'resturent_featured', true );
  if( $meta_value == 'yes' ){
     $new_value = update_post_meta( $post_id, 'resturent_featured', 'no' );
  }else{
     $new_value = update_post_meta( $post_id, 'resturent_featured', 'yes' );
  }
}

Its working when i select one post.but not working when selecting multiple posts.

A: Something might be wrong here.If you $get_post_ids[] is a array with a key and a value with comma separated then it must be $_REQUEST['ids'] comma separated.Then you have to use this way:
$get_post_ids = $_REQUEST['ids'];
$get_post_ids = explode(',', $get_post_ids);


text:
Q: vb6 custome application setup.exe run on windows7 gives "An error occureed while registering the file 'C:\Windows\System32\hid.dll'" I have written multiple applications in VB6 that we send to customers for my companies product configuration in the field.
    I use the package and deployment wizard in VB6 SP6
    When customers in the field run the setup.exe, they get the error-

An error occurred while registering the file 'C:\Windows\System32\hid.dll'

This happens for many files - such as Ws32_32.dll, setupapi.dll, mswinsck.ocx...
I have read that this has to do with SysWOW64 having pre-compiled drivers in it that are an older revision than VB6 has access to, and that the vb6 setup.exe that is part of the package cannot update the SysWOW64 drivers.
Is there a way to make a VB6 package that installs on Windows 7?  If not is there at least a way to suppress the errors so that customers do not see them, the application does run.


text:
Q: State the range of each function $f:\mathbb{R} \rightarrow \mathbb{R}$
$f(x) = 4\cos(6x)$
$f(x) = -2(x-3)^2+5$

For the first one I just graphed it and found $y = -4$ and $y = 4$
For the second one I also graphed it and found $y = 5$
Did I state the range correctly or must it be in some different format?

A: Without graph, note that, for $(1)$ we have:
$-1\le \cos \alpha  \le 1 \quad \forall \alpha \in \mathbb{R}$ , so:
$-4 \le \cos (6x) \le 4 \quad \forall x \in \mathbb{R}$.
For $(2)$ note that:
$(x-3)^2 \ge 0 \quad \forall x \in \mathbb{R} $ so that $-2(x-3)^2 \le 0 \quad \forall x \in \mathbb{R} $ and:
$5-2(x-3)^2\le 5 \quad \forall x \in \mathbb{R}$.


text:
Q: Spark 2.1 + Yarn application has already ended we are using spark application version 2.1 in out ambari cluster
ambari thrift servers isn't stable and restarted all times
from the log we can see that:
ERROR SparkContext: Error initializing SparkContext.
org.apache.spark.SparkException: Yarn application has already ended! It might have been killed or unable to launch application master.

we found the following link that described solution for this problem
https://markobigdata.com/2016/08/11/yarn-application-has-already-ended-it-might-have-been-killed-or-unable-to-launch-application-master/
but after we set the parameters as described in the article , the problem still  exsist
please advice what is the solution for this?
full log:
tail -f  spark-hive-org.apache.spark.sql.hive.thriftserver.HiveThriftServer2-1-master01.sys873dns.com.out
Spark Command: /usr/jdk64/jdk1.8.0_112/bin/java -Dhdp.version=2.6.0.3-8 -cp /usr/hdp/current/spark2-thriftserver/conf/:/usr/hdp/current/spark2-thriftserver/jars/*:/usr/hdp/current/hadoop-client/conf/ -Xmx10000m org.apache.spark.deploy.SparkSubmit --conf spark.driver.memory=50g --properties-file /usr/hdp/current/spark2-thriftserver/conf/spark-thrift-sparkconf.conf --class org.apache.spark.sql.hive.thriftserver.HiveThriftServer2 --name Thrift JDBC/ODBC Server --executor-cores 7 spark-internal
========================================
Warning: Master yarn-client is deprecated since 2.0. Please use master "yarn" with specified deploy mode instead.
18/02/08 09:38:07 ERROR SparkContext: Error initializing SparkContext.
org.apache.spark.SparkException: Yarn application has already ended! It might have been killed or unable to launch application master.
        at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.waitForApplication(YarnClientSchedulerBackend.scala:85)
        at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.start(YarnClientSchedulerBackend.scala:62)
        at org.apache.spark.scheduler.TaskSchedulerImpl.start(TaskSchedulerImpl.scala:156)
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:509)
        at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2320)
        at org.apache.spark.sql.SparkSession$Builder$$anonfun$6.apply(SparkSession.scala:868)
        at org.apache.spark.sql.SparkSession$Builder$$anonfun$6.apply(SparkSession.scala:860)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.sql.SparkSession$Builder.getOrCreate(SparkSession.scala:860)
        at org.apache.spark.sql.hive.thriftserver.SparkSQLEnv$.init(SparkSQLEnv.scala:47)
        at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2$.main(HiveThriftServer2.scala:81)
        at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2.main(HiveThriftServer2.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:745)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
18/02/08 09:38:07 WARN YarnSchedulerBackend$YarnSchedulerEndpoint: Attempted to request executors before the AM has registered!
18/02/08 09:38:07 ERROR Utils: Uncaught exception in thread main
java.lang.NullPointerException

I give also the yarn logs:
   grep -i erro yarn-yarn-resourcemanager-master01.sys873dns.com.log

018-02-08 11:19:00,993 INFO  zookeeper.ClientCnxn (ClientCnxn.java:logStartConnect(1019)) - Opening socket connection to server master01.sys873dns.com/23.1.29.61:2181. Will not attempt to authenticate using SASL (unknown error)
2018-02-08 11:19:15,767 ERROR resourcemanager.ResourceManager (LogAdapter.java:error(69)) - RECEIVED SIGNAL 15: SIGTERM
2018-02-08 11:19:27,281 INFO  zookeeper.ClientCnxn (ClientCnxn.java:logStartConnect(1019)) - Opening socket connection to server master01.sys873dns.com/23.1.29.61:2181. Will not attempt to authenticate using SASL (unknown error)
2018-02-08 11:29:00,064 INFO  zookeeper.ClientCnxn (ClientCnxn.java:logStartConnect(1019)) - Opening socket connection to server master01.sys873dns.com/23.1.29.61:2181. Will not attempt to authenticate using SASL (unknown error)
2018-02-08 11:29:01,839 INFO  zookeeper.ClientCnxn (ClientCnxn.java:logStartConnect(1019)) - Opening socket connection to server master01.sys873dns.com/23.1.29.61:2181. Will not attempt to authenticate using SASL (unknown error)
2018-02-08 11:29:15,725 ERROR resourcemanager.ResourceManager (LogAdapter.java:error(69)) - RECEIVED SIGNAL 15: SIGTERM
2018-02-08 11:29:27,033 INFO  zookeeper.ClientCnxn (ClientCnxn.java:logStartConnect(1019)) - Opening socket connection to server master03.sys873dns.com/23.1.29.63:2181. Will not attempt to authenticate using SASL (unknown error)

ons.YarnException: Unauthorized request to start container.
2018-02-08 12:56:11,144 INFO  amlauncher.AMLauncher (AMLauncher.java:run(273)) - Error launching appattempt_1518089370033_0028_000008. Got exception: org.apache.hadoop.yarn.exceptions.YarnException: Unauthorized request to start container.
2018-02-08 12:59:39,822 INFO  amlauncher.AMLauncher (AMLauncher.java:run(273)) - Error launching appattempt_1518089370033_0029_000002. Got exception: org.apache.hadoop.yarn.exceptions.YarnException: Unauthorized request to start container.
2018-02-08 13:00:01,671 INFO  amlauncher.AMLauncher (AMLauncher.java:run(273)) - Error launching appattempt_1518089370033_0029_000004. Got exception: org.apache.hadoop.yarn.exceptions.YarnException: Unauthorized request to start container.
2018-02-08 13:00:18,062 INFO  amlauncher.AMLauncher (AMLauncher.java:run(273)) - Error launching appattempt_1518089370033_0029_000006. Got exception: org.apache.hadoop.yarn.exceptions.YarnException: Unauthorized request to start container.
2018-02-08 13:00:20,245 INFO  amlauncher.AMLauncher (AMLauncher.java:run(273)) - Error launching appattempt_1518089370033_0030_000003. Got exception: org.apache.hadoop.yarn.exceptions.YarnException: Unauthorized request to start container.
2018-02-08 13:00:42,100 INFO  amlauncher.AMLauncher (AMLauncher.java:run(273)) - Error launching appattempt_1518089370033_0030_000006. Got exception: org.apache.hadoop.yarn.exceptions.YarnException: Unauthorized request to start container.
2018-02-08 13:00:56,310 INFO  amlauncher.AMLauncher (AMLauncher.java:run(273)) - Error launching appattempt_1518089370033_0030_000008. Got exception: org.apache.hadoop.yarn.exceptions.YarnException: Unauthorized request to start container.
2018-02-08 13:00:58,511 INFO  amlauncher.AMLauncher (AMLauncher.java:run(273)) - Error launching appattempt_1518089370033_0030_000010. Got exception: org.apache.hadoop.yarn.exceptions.YarnException: Unauthorized request to start container.
2018-02-08 13:00:58,537 INFO  rmapp.RMAppImpl (RMAppImpl.java:transition(1063)) - Application application_1518089370033_0030 failed 10 times due to Error launching appattempt_1518089370033_0030_000010. Got exception: org.apache.hadoop.yarn.exceptions.YarnException: Unauthorized request to start container.

last log
2018-02-08 14:14:54,410 INFO  rmapp.RMAppImpl (RMAppImpl.java:handle(778)) - application_1518089370033_0050 State change from FINAL_SAVING to FAILED
2018-02-08 14:14:54,410 INFO  capacity.ParentQueue (ParentQueue.java:removeApplication(385)) - Application removed - appId: application_1518089370033_0050 user: hive leaf-queue of parent: root #applications: 1
2018-02-08 14:14:54,412 INFO  integration.RMRegistryOperationsService (RMRegistryOperationsService.java:onApplicationCompleted(119)) - Application application_1518089370033_0050 completed, purging application-level records
2018-02-08 14:14:54,412 INFO  integration.RMRegistryOperationsService (RMRegistryOperationsService.java:purgeRecordsAsync(198)) -  records under / with ID application_1518089370033_0050 and policy application: {}
2018-02-08 14:14:55,393 INFO  rmcontainer.RMContainerImpl (RMContainerImpl.java:handle(422)) - container_e09_1518089370033_0049_10_000001 Container Transitioned from RUNNING to COMPLETED
2018-02-08 14:14:55,393 INFO  scheduler.SchedulerNode (SchedulerNode.java:releaseContainer(220)) - Released container container_e09_1518089370033_0049_10_000001 of capacity <memory:10240, vCores:1> on host worker02.sys768.com:45454, which currently has 0 containers, <memory:0, vCores:0> used and <memory:30720, vCores:6> available, release resources=true
2018-02-08 14:14:55,393 INFO  attempt.RMAppAttemptImpl (RMAppAttemptImpl.java:rememberTargetTransitionsAndStoreState(1209)) - Updating application attempt appattempt_1518089370033_0049_000010 with final state: FAILED, and exit status: -1000
2018-02-08 14:14:55,398 INFO  attempt.RMAppAttemptImpl (RMAppAttemptImpl.java:handle(809)) - appattempt_1518089370033_0049_000010 State change from LAUNCHED to FINAL_SAVING
2018-02-08 14:14:55,399 INFO  integration.RMRegistryOperationsService (RMRegistryOperationsService.java:onContainerFinished(144)) - Container container_e09_1518089370033_0049_10_000001 finished, purging container-level records
2018-02-08 14:14:55,400 INFO  integration.RMRegistryOperationsService (RMRegistryOperationsService.java:purgeRecordsAsync(198)) -  records under / with ID container_e09_1518089370033_0049_10_000001 and policy container: {}
2018-02-08 14:14:55,408 INFO  resourcemanager.ApplicationMasterService (ApplicationMasterService.java:unregisterAttempt(685)) - Unregistering app attempt : appattempt_1518089370033_0049_000010
2018-02-08 14:14:55,408 INFO  security.AMRMTokenSecretManager (AMRMTokenSecretManager.java:applicationMasterFinished(124)) - Application finished, removing password for appattempt_1518089370033_0049_000010
2018-02-08 14:14:55,408 INFO  attempt.RMAppAttemptImpl (RMAppAttemptImpl.java:handle(809)) - appattempt_1518089370033_0049_000010 State change from FINAL_SAVING to FAILED
2018-02-08 14:14:55,408 INFO  rmapp.RMAppImpl (RMAppImpl.java:transition(1330)) - The number of failed attempts is 10. The max attempts is 10
2018-02-08 14:14:55,409 INFO  rmapp.RMAppImpl (RMAppImpl.java:rememberTargetTransitionsAndStoreState(1123)) - Updating application application_1518089370033_0049 with final state: FAILED
2018-02-08 14:14:55,409 INFO  rmapp.RMAppImpl (RMAppImpl.java:handle(778)) - application_1518089370033_0049 State change from ACCEPTED to FINAL_SAVING
2018-02-08 14:14:55,409 INFO  recovery.RMStateStore (RMStateStore.java:transition(228)) - Updating info for app: application_1518089370033_0049
2018-02-08 14:14:55,409 INFO  capacity.CapacityScheduler (CapacityScheduler.java:doneApplicationAttempt(811)) - Application Attempt appattempt_1518089370033_0049_000010 is done. finalState=FAILED
2018-02-08 14:14:55,409 INFO  scheduler.AppSchedulingInfo (AppSchedulingInfo.java:clearRequests(124)) - Application application_1518089370033_0049 requests cleared
2018-02-08 14:14:55,410 INFO  capacity.LeafQueue (LeafQueue.java:removeApplicationAttempt(795)) - Application removed - appId: application_1518089370033_0049 user: hive queue: default #user-pending-applications: 0 #user-active-applications: 0 #queue-pending-applications: 0 #queue-active-applications: 0
2018-02-08 14:14:55,417 INFO  rmapp.RMAppImpl (RMAppImpl.java:transition(1063)) - Application application_1518089370033_0049 failed 10 times due to AM Container for appattempt_1518089370033_0049_000010 exited with  exitCode: -1000
For more detailed output, check the application tracking page: http://master02.sys768.com:8088/cluster/app/application_1518089370033_0049 Then click on links to logs of each attempt.
Diagnostics: org.apache.hadoop.hdfs.BlockMissingException: Could not obtain block: BP-1212891131-25.1.53.61-1518077044052:blk_1073741833_1009 file=/hdp/apps/2.6.0.3-8/spark2/spark2-hdp-yarn-archive.tar.gz
Failing this attempt. Failing the application.
2018-02-08 14:14:55,418 INFO  rmapp.RMAppImpl (RMAppImpl.java:handle(778)) - application_1518089370033_0049 State change from FINAL_SAVING to FAILED
2018-02-08 14:14:55,418 INFO  capacity.ParentQueue (ParentQueue.java:removeApplication(385)) - Application removed - appId: application_1518089370033_0049 user: hive leaf-queue of parent: root #applications: 0
2018-02-08 14:14:55,419 INFO  integration.RMRegistryOperationsService (RMRegistryOperationsService.java:onApplicationCompleted(119)) - Application application_1518089370033_0049 completed, purging application-level records
2018-02-08 14:14:55,419 INFO  integration.RMRegistryOperationsService (RMRegistryOperationsService.java:purgeRecordsAsync(198)) -  records under / with ID application_1518089370033_0049 and policy application: {}
[root@master02 yarn]#


text:
Q: Syntax logic between Pandas and numpy I have a syntax question between numpy and Pandas, and probably more Python modules. To be effective in numpy can do this :
b = np.ones((5,5))
b[1:-1, 1:-1] = 0
print(b)

But, when i want to do something on a Dataframe with Pandas i have use a variable else it doesn't work, like this :
df2 = pd.concat(out, ignore_index=True, axis=1)
df2 = df2.fillna(method='ffill')

Expect df.to_csv for example. I don't understand why Python's modules doesn't use similar syntax. Am i missing something ?

A: It does work, it's just not the default for pandas. You have to do it like this:
df2.fillna(method='ffill', inplace=True)

Probably this is not the default because it wouldn't nesting operations like this:
df2 = pd.concat(out, ignore_index=True, axis=1).fillna(method='ffill').replace(...).apply(...)

Pandas actually uses numpy arrays. you can access them like this
df.values

or this
df["column"].values


text:
Q: The way to convert single maven project to multi module gradle project? I have som single maven projects that are relevant each other.
I want to convert them to a multi module gradle project.
Is there effective way? (The maven projects are spring boot projects.)


text:
Q: AppleScript `activate` from Sandboxed app does not bring window to foreground I am attempting to open System Preferences from a Sandboxed macOS application, so that the user can manually enable a certain preference.

AppleScript activate

Brings an application to the front, launching it if necessary.

I am running macOS 10.13.6 and Xcode 10.0. The Deployment Target is set to OS X 10.11.
I run the following AppleScript from a sandboxed app:
let script = """
             tell application "System Preferences"
                 activate
                 set current pane to pane id "com.apple.preferences.extensions"
             end tell
             """
let appleScript = NSAppleScript(source: script)
var errorInfo: NSDictionary? = nil
appleScript?.executeAndReturnError(&errorInfo)

I also add a scripting targets Sandbox Entitlement enabling System Preferences to reveal panes:
<key>com.apple.security.scripting-targets</key>
<dict>
    <key>com.apple.systempreferences</key>
    <array>
        <string>preferencepane.reveal</string>
    </array>
</dict>

This somewhat works, once I add the Entitlement. The Systems Preferences app launches if closed and opens the correct pane.
The errorInfo dictionary is nil and presents no error info.
In the console I see a message, which is perhaps unrelated log spam:

AppleEvents: received mach msg which wasn't complex type as expected in getMemoryReference.

However, the app does not activate. The System Preferences window does not come to the front. The app  navigates to the correct tab, but does not come to the foreground as the docs for activate state. It remains behind any other foreground windows.
In the case where System Preferences is closed, the app does launch. But the window is not added to the screen in the foreground or background until you click the dock icon. The window then appears, already navigated to the correct pane.
Why does the app not activate?
Are there any other needed Sandbox Entitlements that will allow for activation of the System Preferences window?

A: I suggest that you do the following (this was tested by me on macOS Mojave and works as intended).

*

*Open Script Editor

*Paste your script code into it (without the external quotes, of course)

*Save it as an app

*Go to the place in Finder where you saved it and with the right button click on "Show Package Contents".

*Go to Contents and the open Info.plist in Xcode

*Check the entitlements this app used, in particular the Privacy - AppleEvents Sending Usage Description (NSAppleEventsUsageDescription).

*Replicate that in your app, but please do not use all the entitlements this Applescript app uses by default, only the ones you really need.

A: It seems like a bug to me that the activate command is not allowed from your script. However, I confirmed in a simple test application that even though I reproduce the behavior you described, the problem can be worked around by using NSWorkspace to launch System Preferences instead. This procedure has a side effect of activating the app if it is already launched. So, add code like this before your AppleScript executes:
NSWorkspace.shared.launchApplication(withBundleIdentifier: "com.apple.systempreferences", options: [], additionalEventParamDescriptor: nil, launchIdentifier: nil)
Something else weird: if you leave the "activate" in the script it seems to cause the running app to reactivate. So the complete workaround seems to require adding something like the above in code and removing the 'activate' from the script.


text:
Q: PHP socket_close() Not Closing Server Connections I am doing a 2 part app that requires two different socket connections to Window-based apps.
My app:  Opens to read and query from an appliance via Socket #1.  Socket #2 opens at the same time as Socket #1 to another appliance and waits to send commands to that appliance.
Both work fine for reading and sending as expected.
What I am running into is that I close Socket #2 on my side (client) the appliance side still shows an active connection and never seems to close them -- there are connections for a few days on there.
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, $host, $port) or die('ERROR');

socket_write($sock, $buffer, $len);
print_r(simplexml_load_string(socket_read($sock, 65535)));

socket_shutdown($sock, 2);
socket_close($sock);

I have tried socket_shutdown + socket_close, I have changed methods to pfsocketopen/fclose, fsocketopen/fclose, etc.  I am not even sure there is anything I can do.
Thoughts?

A: So I tried a whole bunch of different things. Turns out that if I ctrl+c from the command line that will do it. So updated to send a ^C through the socket and its all good

A: I ran into the same problem and this worked for me.

*

*You'll need to set the Linger options, and for this to work you will need to be in blockmode.

If l_onoff is non-zero and l_linger is zero, all the unsent data will be discarded and RST (reset) is sent to the peer in the case of a connection-oriented socket.

*Then use register_shutdown_function to

Registers a callback to be executed after script execution finishes or
exit() is called.

// After socket_create $s
socket_set_block($s);

// Set Linger Options ($o)
$o=['l_onoff'=>1, 'l_linger'=>0];
socket_set_option($s, SOL_SOCKET, SO_LINGER, $o);

// Use register shutdown to trigger socket shutdown and close
register_shutdown_function('socket_shutdown', $s,2);
register_shutdown_function('socket_close', $s);

// do the rest of your stuff

This worked for me flawlessly about 10 times in a row. I was even able to CTRL-C the server, restart it in the seconds and send more from the client without him even noticing. For your reference and proof-of-work see working code snippet below.

*

*Seems to be working without registering the shutdown function

*The ending close function is most likely obsolete but haven't got there yet.

*Client will loop for input (and press ENTER) and echo the server's response.

*Server will echo message sent from the client and send it back to the client.

server.php
<?php
$h="localhost";
$p=65535;
set_time_limit(0);
$s=socket_create(AF_INET, SOCK_STREAM, 0) or die("create\n");

// START
socket_set_block($s);
$o=['l_onoff'=>1, 'l_linger'=>0];
socket_set_option($s, SOL_SOCKET, SO_LINGER, $o);
register_shutdown_function('socket_shutdown', $s,2);
register_shutdown_function('socket_close', $s);
// END

socket_bind($s, $h, $p) or die("bind\n");
socket_listen($s, 3) or die("listen\n");
while(true) {
  $a=socket_accept($s);# or die("accept\n");
  $i=socket_read($a, 1024);# or die("read\n");
  if($a && $i):
    echo $o='Client message:'.$i.PHP_EOL."\n";
    socket_write($a, $o, strlen ($o)) or die("write\n");
  endif;
  socket_close($a);
}
socket_close($s);

client.php
<?php
$h="127.0.0.1";
$p=65535;
while(true){
  echo "Input: \n";
  $i=trim(fgets(fopen("php://stdin","r")));
  $s=socket_create(AF_INET, SOCK_STREAM, 0) or die("create\n");

  // START
  socket_set_block($s);
  $o=['l_onoff'=>1, 'l_linger'=>0];
  socket_set_option($s, SOL_SOCKET, SO_LINGER, $o);
  register_shutdown_function('socket_shutdown', $s,2);
  register_shutdown_function('socket_close', $s);
  // END

  if($i&&$s):
    socket_connect($s, $h, $p) or die("connect\n");
    socket_write($s, $i, strlen($i)) or die("write\n");
    $o=socket_read($s, 1024) or die("read\n");
    echo 'Server response: '.$o.PHP_EOL;
  endif;
}
socket_close($s);