text:
Q: How Do I make my Explosions Append At My Enemy x and y? Pygame Video as you can see in the video the smoke appears somewhere else instead of the enemies x and y if I scroll and go kill the other enemy the smoke appears back where it was
in my reDraw Window I said if my enemies health is greater then -3 then show the explodes
but how can I make it appear in the enemies x and y?

            for enemys in enemying:
                if enemys.health < -3:
                    for explode in explodes:
                        explode.draw()

this is where I delete the enemys when they die

                # enemys 2
            for enemyshoot in enemyshooting:
                for bullet in bullets:
                    if bullet.rect.colliderect(enemyshoot.hitbox):
                        if enemyshoot.health > -8:
                            enemyshoot.health -= 1
                            bullets.pop(bullets.index(bullet))
                        else:
                            del enemyshooting[one]

this is my full explosion class

class explode:

        def __init__(self,x,y,height,width,color):
            self.x = x
            self.y = y
            self.height = height
            self.width = width
            self.explode = [
            pygame.image.load("smoke1.png"),
            pygame.image.load("smoke2.png"),
            pygame.image.load("smoke3.png"),
            pygame.image.load("smoke4.png"),
            pygame.image.load("smoke5.png"),
            pygame.image.load("smoke6.png"),
            pygame.image.load("smoke7.png"),
            pygame.image.load("smoke8.png"),
            pygame.image.load("smoke9.png"),
            pygame.image.load("smoke10.png"),
            pygame.image.load("smoke11.png"),
            pygame.image.load("smoke12.png"),
            pygame.image.load("smoke13.png"),
            pygame.image.load("smoke14.png"),
            pygame.image.load("smoke15.png"),
            pygame.image.load("smoke16.png"),
            pygame.image.load("smoke17.png"),
            pygame.image.load("smoke18.png"),
            pygame.image.load("smoke19.png"),
            pygame.image.load("smoke20.png"),
            pygame.image.load("smoke21.png"),
            pygame.image.load("smoke22.png"),
            pygame.image.load("smoke23.png"),
            pygame.image.load("smoke24.png"),
            pygame.image.load("smoke25.png")]

            self.explode = [pygame.transform.scale(image,(image.get_width()//2,image.get_height()//2)) for image in self.explode]

            self.rect = pygame.Rect(x,y,height,width)
            self.direction = "blobright"
            self.anim_index = 0
        def draw(self):

            self.rect.topleft = (self.x,self.y)
            if self.direction == "blobright":
                window.blit(self.explode[self.anim_index], self.rect)
                self.anim_index += 1
                if self.anim_index == len(self.explode):
                    self.anim_index = 0

    black = (0,0,0)
    explode1 = explode(400,450,50,50,black)
    explodes = [explode1]

A: The problem is right in your code:
    black = (0,0,0)
    explode1 = explode(400,450,50,50,black)
    explodes = [explode1]

When you create the explosion to draw, you set its explosion location immediately. No matter where the enemy is when it dies, the explosion will always be drawn at that (400,450) because that's where you set it to explode.
You need to tell the explosion where to draw itself when the enemy dies, not when the explosion is instantiated. What I would do is instead of giving the explode class its own stored x and y, just add x,y parameters to the draw() function, and pass the coordinates of the dying enemy at the time of its death. It would look something like this:
#Modified explode.draw() function:
        def draw(self,drawX,drawY):

            self.rect.topleft = (drawX,drawY)
            if self.direction == "blobright":
                window.blit(self.explode[self.anim_index], self.rect)
                self.anim_index += 1
                if self.anim_index == len(self.explode):
                    self.anim_index = 0

#Modified death loop
            for enemys in enemying:
                if enemys.health < -3:
                    for explode in explodes:
                        explode.draw(enemys.x,enemys.y)

Hope this helps!


text:
Q: Retain specific component in PCA I have an numpy array called "data" which has 500 rows and 500 columns. Using PCA from sklearn I can compress this to 500 rows and 15 columns. I believe that in essence I go from 500 axes and 500 points to 15 axes and 500 points. The axes are all orthogonal and explain my data very well.
But I want to know if there's anyway to ensure that one of the 15 axes (that I get after running PCA) is also one of the original 500. That is, can I keep one of the original axes and use PCA (or some-other method) to find the remaining 14?
My code is given below:
from sklearn.decomposition import PCA
#data is some 500x500 numpy array
pca = PCA(n_components = 15)
pca_result = pca.fit_transform(data)
#pca_result is a 500x15 numpy array

A: I think what you're trying to do is to first do a linear least-squares fit to the axis you want to keep:
axis_to_keep = data[:,column_number][:,np.newaxis]
# next line solves axis_to_keep*x = data
x = np.linalg.lstsq(axis_to_keep,data)[0]

Then subtract the fit generated using that model from data:
data_2 = data - np.dot(axis_to_keep,x)

at which point you can do your PCA on data_2 with 14 components. Your forced axis (almost certainly) won't be orthogonal to the others.

A: You can simply drop the axis you want to keep from the data:
mask = np.ones(data.shape[1], dtype=np.bool)
mask[special_axis] = False
data_new = data[:, mask]

pca_transformed = PCA(n_components=14).fit_transform(data_new)

This is the same as removing the projection along this feature.
You can then stack the original axis with the PCA result if you like:
stacked_result = np.hstack([pca_transformed, data[:, [special_axis]]])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rigid bodies and inelastic collision If two rigid bodies collide - how the collision can be inelastic?  where the energy goes?
If the energy transffered to heat, doesn't it contradict that the bodies are rigid?

A: Your intuition is mostly correct here. Perfectly rigid bodies would not be able to collide perfectly inelastically (assuming they interact via contact forces)
A perfectly inelastic collision is one where the final total kinetic energy in the center of momentum frame is zero. In the center of momentum frame you would have the two objects move towards each other and then come into contact. Each object needs to lose its kinetic energy. Since $\Delta K = F\Delta x_{CM}$ that means the center of mass each object must move at least a little for work to be done. But if the object is perfectly rigid the center of mass cannot move relative to its boundary, and its boundary can't move because it is in contact with the other object. Without some kind of infinite force the work done would have to be zero and inelastic collision would be impossible. (Actually, this proves that basically any kind of collision is impossible for perfectly rigid bodies!)
If you remove the assumption of contact forces things are a little different. For example, a positron and an electron are both perfectly rigid bodies (because they are point particles), and yet they can collide perfectly inelastically by forming a  positronium particle. The difference is that the electromagnetic force acts over a distance, starting well before they come in contact.

A: If the collision is inelastic, momentum is conserved, but energy is not. Some of the energy is converted to heat (and sound).

A: Yes,
Two inelastic rigid bodies is an idealization that does not reflect reality. It is just a shortcut for when the details are not important.


text:
Q: Stream Excel File for Download after getting Excel from WCF Service Got a problem here, and once again think I am close to a solution, however it is eluding me.
I am trying to download an Excel file from our ASP.NET website after getting the filestream from a WCF service. This seems to work okay, but I may be going the entirely wrong way about it.
Using breakpoints in the code I am able to see that the file is arriving in the method and being "streamed" to the browser, however it is not becoming available for download (when the little icon appears in the corner, or a prompt appears, depending on browser).
I've tried to adapt this code http://www.codeproject.com/Articles/166763/WCF-Streaming-Upload-Download-Files-Over-HTTP to accept .xls files.
Here is my FileTransfer.cs and IFileTransfer.cs WCF classes.
FileTransfer.cs
public RemoteFileData DownloadFile(DownloadRequest request)
            {
                RemoteFileData result = new RemoteFileData();
                try
                {
                    string filePath = System.IO.Path.Combine(@"C:\Files", request.FileName);
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

                    // does file exist?
                    if (!fileInfo.Exists)
                        throw new System.IO.FileNotFoundException("File not found", request.FileName);

                    // open the stream
                    System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                    // return result over the stream
                    result.FileName = request.FileName;
                    result.Length = fileInfo.Length;
                    result.FileByteStream = stream;
                }
                catch (Exception ex)
                {
                }
                return result;
            }

IFileTransfer.cs
[ServiceContract]

public interface IFileTransfer
{
    [OperationContract]
    RemoteFileData DownloadFile(DownloadRequest request);
}

[MessageContract]
public class DownloadRequest
{
    [MessageBodyMember]
    public string FileName;
}

[MessageContract]
public class RemoteFileData : IDisposable
{
    [MessageHeader(MustUnderstand = true)]
    public string FileName;

    [MessageHeader(MustUnderstand = true)]
    public long Length;

    [MessageBodyMember(Order = 1)]
    public System.IO.Stream FileByteStream;

    public void Dispose()
    {
        if (FileByteStream != null)
        {
            FileByteStream.Close();
            FileByteStream = null;
        }
    }
}

And here is the Linkbutton method/event.
protected void LnkBtn_genPAFFile_Click(object sender, EventArgs e)
{
    try
    {
        GSIISFileTransferService.IFileTransfer tClient = new GSIISFileTransferService.FileTransferClient();
        GSIISFileTransferService.DownloadRequest requestData = new GSIISFileTransferService.DownloadRequest();
        GSIISFileTransferService.RemoteFileData fileInfo = new GSIISFileTransferService.RemoteFileData();

        requestData.FileName = "form.xls";
        fileInfo = tClient.DownloadFile(requestData);

        Response.BufferOutput = false;
        byte[] buffer = new byte[6500];
        int bytesRead = 0;

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + requestData.FileName);

        bytesRead = fileInfo.FileByteStream.Read(buffer, 0, buffer.Length);

        while (bytesRead > 0)
        {
            if (Response.IsClientConnected)
            {
                Response.OutputStream.Write(buffer, 0, bytesRead);
                // flush data to HTML
                Response.Flush();

                buffer = new byte[6500];
                bytesRead = fileInfo.FileByteStream.Read(buffer, 0, buffer.Length);
            }
            else
            {
                bytesRead = -1;
            }
        }
    }
    catch (Exception ex)
    {
        System.Web.HttpContext.Current.Response.Write("Error : " + ex.Message);
    }
    finally
    {
        Response.Flush();
        Response.Close();
        Response.End();
        System.Web.HttpContext.Current.Response.Close();
    }
}

A: I assume that you have configured the MIME type for your excel file. You can check it from here how to create a MIME type:
http://technet.microsoft.com/en-us/library/cc725608(WS.10).aspx
In addition in your IIS if you are using SSL, on the HTTP Headers tab, under Custom HTTP Headers, you should see "Cache-Control no-cache" specified.  You should remove that option.
Also you can try this:
HttpContext.Current.Response.AddHeader("Content-Type: application/octet-stream");

This octet-stream content type forces IE to download the file.


text:
Q: How to display specific column data and row from database to excel? I want to export specific columns data. How to display only specific columns with data?
This is what i've tried so far:
For Each dc In datatableMain.Columns
  colIndex = colIndex + 1
  oSheet.Cells(1, colIndex1) = dc.ColumnName
  oSheet.Cells(1, colIndex2) = dc.ColumnName
  oSheet.Cells(1, colIndex3) = dc.ColumnName
  oSheet.Cells(1, colIndex4) = dc.ColumnName
  oSheet.Cells(1, colIndex5) = dc.ColumnName

Next
For Each dr In datatableMain.Rows
   rowIndex = rowIndex + 1
   colIndex = 0
   For Each dc In datatableMain.Columns
       colIndex = colIndex + 1
       oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
   Next
Next


text:
Q: Would it be possible to exist different mathematical notations for numbers with different properties? I was reading about how the hindu arabic notation (the notation we use worldwide for numbers) of numbers was benefic for mathematics. Because it makes much easier some operations, such as multiplication, and it facilitated the writing of the numbers. Before the hindu arabic notation it was hard to write and make operations with the greek notation for example.
And I was wondering if would be possible to exist different notations for numbers, or matrix, or functions, or ... that would have different properties than the usual and make some operations easier, with matrices for example.
Does exist some kind of research area about this topic?
I'm not a mathematician so I'm sorry if this question sounds not good.

A: To give at least a place-holder response:
Yes, issues of algorithmic efficiency, implicitly depending on how-to-represent integers, real numbers, matrices, etc., do play a large role in modern mathematics and computer science (and any science that depends on computations).
Decimals are not wonderful, but they're ok, or at least computer-representation equivalents.
Representation of (real?) numbers is not usually the serious bottleneck in algorithms, so far as I know (but the future may tell us otherwise?)
Ideas such as Fast Fourier Transform do show that the "obvious" ideas of how to compute things are markedly inefficient, especially with regard to scale.
Even the "square and multiply" algorithm for exponentiation is a bit surprising, as it scales up much better than most naive notions.


text:
Q: Why does a function prototype with an empty argument list conflicts with one that has a char argument? With the code below, both clang and gcc called with -std=c11 complain about conflicting types for foo.
int foo();

int main(void) {
  return foo(0);
}

int foo(char a) {
   return a;
}

According to the answer in https://stackoverflow.com/a/13950800/1078224, in (older?) C standards the type int has been assumed when no variable type was given. However, the C11 standard draft (http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), section 6.7.6.3, $14 says that

The empty list in a function declarator that is not part of a
  definition of that function specifies that no information about the number or types of the
  parameters is supplied.

From this I conclude that the code above should be actually valid. Or am I missing some other relevant section of the standard?

A: C 2011 (N1570) 6.7.6.3 15:

For two function types to be compatible, both shall specify compatible return types. Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types. If one type has a parameter type list and the other type is specified by a function declarator that is not part of a function definition and that contains an empty identifier list, the parameter list shall not have an ellipsis terminator and the type of each parameter shall be compatible with the type that results from the application of the default argument promotions.… [Emphasis added.]

char is promoted to int, so char a is not compatible with an empty list. int a would be; int foo(); int foo(int a); is allowed.
Essentially, the reason for this is that, if you declare a function int foo() and then call it, say with int foo(3), the compiler has to know what to pass it. The rules, derived from history, are to perform the default argument promotions. So int foo(3) gets called as if it were int foo(int).
Then, if you later define the function with int foo(char), the definition will not match the call. In many C implementations a char and an int may be put in the same place for calling a function, but a C implementation could do something different. A float and a double would be a greater conflict.


text:
Q: Tools for debugging xslt I have a Java servlet which generates xml, translates it with an xslt stylesheet, and then displays the resulting HTML. This is the first time I've worked with xslt. What's a good way to debug xslt? I have (or can get) some sample XML files to apply the transform too. But I'm not really even sure of the syntax so something that would give me syntax warnings would be great.

A: I once had to write and debug some complex XSLT documents. At the time I used debugged "printf-style" by outputting a lot of intermediate values. I later found out that there is a much easier way to do this - Altova XMLSpy. It allows you to single-step through the style-application process, watch intermediate output, etc. etc.
VS8 also has XSLT debugging support. See here: http://msdn.microsoft.com/en-us/library/ms255605(VS.80).aspx
I should also mention that both XMLSpy and VS8 have syntax highlighting as well. If you specify a XSD in your XML, VS8 even gives you intellisense!

A: PHPStorm and the other IntelliJ IDEs (commercial) support debugging XSLT. You can step through the document and see the output being generated step by step.

A: I work with XSLT nearly every day, and have for six or seven years.
I've found that "printf-style" debugging of XSLT is so effective that I've never derived a benefit from using any other debugging mechanism (and I've tried XMLSpy and Visual Studio).  It does sometimes happen that I want to be able to inspect the value of a variable and building logic that outputs it is a hassle.  But that's pretty rare.
It may be that having a debugger would have made learning XSLT easier.  (Anything would have.)

A: when learning, a syntax highlighting editor is usually enough for me (of course with the ref doc open on another window.
Kate is a great editor for XML and XSLT.

A: Xselerator is s great XSL debugging tool that will:

*

*Let you step through your XSLT dom

*Create watch statements

*Evaluate XPath statements against you XML DOM

*IDE with Intellisense

I've used this for years and it is a great tool.

A: If you want to do "printf-style" debugging and don't want to litter your output with debugging data, use the <xsl:message> tag to generate debugging output while processing the stylesheet. With the terminate="yes" attribute you can even halt the processing of the stylesheet.

A: Xalan should give you useful errors when you try to use an invalid XSLT.  If you want something more powerful, one option for debugging XSLT is Oxygen XML Editor.  It is integrated with Xalan and Saxon transform engines.  Its debugging mode allows you to set breakpoints, watch variables, and provides other such basic debugging functionality.  It may be overkill for you want, but it's very good.

A: An answer specifically for debugging XSLT 3.0 with <xsl:message>:
XSLT 3.0 has a new serialize() function that can help when used inside an xsl:message instruction.
However, for the new array and map types you need to use the adaptive serialisation method instead of default XML serialization:
<xsl:message select="serialize($n, map{'method':'adaptive'})"/>

The current drawback with serialize though is that it does not format the output.
A small xpath-result-serializer XSLT project provides ext:print() and ext:println() functions as an alternative to serialize(). There format (and optionally colorise) the XSLT output.
The output text uses an abbreviated notation for maps/array optimised for the human reader rather than a parser. For XML nodes with context, the XPath location is output alongside any text or attribute values.

A: Microsoft Visual Studio is also a great tool for xslt debugger. But you must install the


text:
Q: dequeueReusableHeaderFooterViewWithIdentifier not calling init method in ios9 I am using a custom header cell, and while it works correctly in ios8, when I try it on an ios9 device the table calls dequeueReusableHeaderFooterViewWithIdentifier but it doesn't call the initWithFrame (or any init function that I tried) function, and so I just get a blank space for a header file.
Is there a change in how dequeueReusableHeaderFooterViewWithIdentifier works in ios9 that I should be awear of?
Thanks

A: I had the same problem with a subclass of UITableViewHeaderFooterView. Changing from initWithFrame to initWithReuseIdentifier solved the problem for me.

A: I could observe the following different behavior under iOS 8 and 9:
Under iOS 8

*

*initWithReuseIdentifier: gets called first then

*initWithFrame:
whereas under iOS 9
only

*

*initWithReuseIdentifier:

gets called


text:
Q: Power Query In Excel Getting Errors I'm trying to figure out why this post request isn't working in Excel Power Query
let
    actualUrl = "fakeurl123",
    record = [grant_type="password",username="username",password="password"],
    body = Text.ToBinary(Uri.BuildQueryString(record)),
    uaaBasicKey= "Basic {encoded text}",
    options = [Headers =[#"Content-type"="application/x-www-form-urlencoded", #"Accept"="application/json", #"Authorization" = uaaBasicKey], Content=body],
    Source = Web.Contents(actualUrl, options),
    retVal = Json.Document(Source,65001),
    token = retVal[access_token]
in
    token

When I run the code with the correct password,username, key,etc I get an error saying that I can't use Web.Contents with the content option that I have because it is only supported when connecting anonymously. However, when I do change my connection to anonymous in settings it says I don't have the correct authentication even though I know it's right. If you have any solutions please let me know. Thanks

A: Needed to change username and password as those were for anonymous connecting.


text:
Q: scattered email list on excel, how to send one email per person? And how to include content of a cell in email body So I have an excel sheet organized by case that are assigned to emails. Each case is assigned to one email and each email is responsible for more than one case. Emails are not in order, they are scattered throughout the column.
I want to create an automated email that sends a reminder every Monday (this I havent figured out how yet) to submit the case.  Problem is I want to send one email per person regrouping all the cases assigned to them that are due. (When a case is closed it disappears from the sheet so no need to worry about this).
Here's what I already wrote:
    Sub datesexcelvba()

Dim myApp As Outlook.Application, mymail As Outlook.MailItem
Dim mydate1 As Date
Dim mydate2 As Long
Dim datetoday1 As Date
Dim datetoday2 As Long
Dim engineer As Range

Dim x As Long
lastrow = Sheets("Messages english").Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To lastrow

mydate1 = Cells(x, 3).Value
mydate2 = mydate1
Cells(x, 7) = mydate2

datetoday1 = Date
datetoday2 = datetoday1

Cells(x, 9).Value = datetoday2
Set daysLeft = mydate2 - datetoday2

Function itsokay()
If daysLeft <= 14 And daysLeft >= 8 Then
Set myApp = New Outlook.Application
Set mymail = myApp.CreateItem(olMailItem)

mymail.To = Cells(x, 2).Value
'.send

    With mymail
    .Subject = (xx)
    .Body =  (Message) (content of a cell) (message)...etc
    .Display
    End With

Cells(x, 10) = Date
Cells(x, 10).Interior.ColorIndex = 3
Cells(x, 10).Font.ColorIndex = 2
Cells(x, 10).Font.Bold = True

End If
End Function

Function comeon()
If daysLeft <= 7 And daysLeft >= 4 Then
Set myApp = New Outlook.Application
Set mymail = myApp.CreateItem(olMailItem)

mymail.To = Cells(x, 2).Value
'.send

    With mymail
    .Subject = (xx)
    .Body =  (Message) (content of a cell) (message)...etc
    .Display
    End With

Cells(x, 11) = Date
Cells(x, 11).Interior.ColorIndex = 3
Cells(x, 11).Font.ColorIndex = 2
Cells(x, 11).Font.Bold = True

End If
End Function
 Function late()
If daysLeft < 4 Then
Set myApp = New Outlook.Application
Set mymail = myApp.CreateItem(olMailItem)

mymail.To = Cells(x, 2).Value
'.send

    With mymail
    .Subject = (xx)
    .Body = (Message) (content of a cell) (message)...etc
    .Display
    End With

Cells(x, 12) = Date
Cells(x, 12).Interior.ColorIndex = 3
Cells(x, 12).Font.ColorIndex = 2
Cells(x, 12).Font.Bold = True

End If
End Function

engineer = Cell(x, 6).Value
If engineer = "PLM" Then
// here i should write the code that sends each email(functions created above to the engineer)

Next

Set myApp = Nothing
Set mymail = Nothing

End Function

Thank you !!
One last question: How can i show the info in a cell in between text in the .Body function??This is what my excel sheet looks like
The email has to be sent only when status is design, and the text of the email roughly look like this
Dear (F2),
This is a reminder that your dcp (A2) (b2) is due on the (G2),
your Dcp (a3) (b3) is due on the (g3)
error 13 screenshot

A: This will be a general approach since we do not have your actual data.
As far as I understand you are creating a loop on the cases data as a start. This is not a good way IMHO; if you set your first loop within e-mails data, then set a second loop within the cases data it will be much easier to handle the case. The second loop adds each case to a string which will be used as the mail body afterwards. The condition is whether the e-mail of the case is equal to the one you are looping outside.
After constructing the body for one e-mail (and if the body is not null), you will call the e-mail sending procedure.
I hope this helps, if not try providing some sample from your data which I or someone might create a functional code after then.
EDIT: Since you do not have a seperate e-mail addresses list, you shoul first create an array of the e-mails and then use that list as the outer loop. I don't have the chance of trying but below code should somehow help you to get a start on the loops, e-mail bodt construction etc:
 Sub datesexcelvba()
 ' create a dictionary object of unique e-mails
     Dim d As Object, c As Range, k, tmp As String

    Set d = CreateObject("scripting.dictionary")
    For Each c In Range("H:H").Cells
        tmp = Trim(c.Value)
        If Len(tmp) > 0 Then d(tmp) = d(tmp) + 1
    Next c

    For Each k In d.keys
     ' This is the outer loop of e-mails, the body shoul be constructed here and the e-mail should be sent at the end.
     ' I am keeping your inner loop since I assume that there is no problem with it
        lastrow = Sheets("Messages english").Cells(Rows.Count, 1).End(xlUp).Row
            For x = 2 To lastrow

                If Cells(x, 4).Value = "Design" And Cells(x, 8).Value = k Then
                    myMail.Body = "Dcp No:" & Cells(x, 1).Value
                    myMail.Body = myMail.Body & " | Desc:" & Cells(x, 2).Value
                    myMail.Body = myMail.Body & " | Due Date:" & Cells(x, 7).Value
                    myMail.Body = myMail.Body & Chr(13) 'line feed
                 End If

            Next x
         If myEmail.Body <> "" Then Send_Mail k, "Task is due!", myMail.Body
    Next k

 End Sub

Function Send_Mail(ByVal email_recipient As String, ByVal email_subject, ByVal email_body As String)

    Dim myApp As Outlook.Application
    Set myApp = New Outlook.Application

    Dim myMail As Outlook.MailItem
    Set myMail = myApp.createItem(olMailItem)

    With myMail
        .To = email_recipient
        .Subject = email_subject
        .Body = email_body
        '.Display
    End With

    Set myMail = Nothing
    Set myApp = Nothing

End Function

A: Okay so here's a pieced together version of a solution that might work for you. I noticed that you were missing the idea of a loop so I hope that you can at least work with this to make it do what you're looking for!
Sub DCP_Emails()

    Dim mydate1 As Date
    Dim mydate2 As Long
    Dim datetoday1 As Date
    Dim datetoday2 As Long
    Dim daysLeft As Integer

    Dim lastRow As Integer
    lastRow = Sheets("Messages english").Cells(Rows.Count, 1).End(xlUp).Row

    Dim x As Integer
    For x = 2 To lastRow

        mydate1 = Cells(x, "C").value
        mydate2 = mydate1
        Cells(x, "G") = mydate2

        datetoday1 = Date
        datetoday2 = datetoday1

        Cells(x, "I").value = datetoday2
        daysLeft = mydate2 - datetoday2

        If LCase$(Cells(x, "D").Value2) = "design" Then
            If daysLeft <= 14 And daysLeft >= 8 Then
                Send_Mail Cells(x, "H").Value2, "DCP Reminder - Priority: Low", _
                        "Dear " & Cells(x, "F") & ", " & Chr(10) & Chr(10) & _
                        "This is a reminder that your DCP " & Cells(x, "A") & " " & Cells(x, "B") & " is due on " & Cells(x, "G")

            ElseIf daysLeft <= 7 And daysLeft >= 4 Then
                Send_Mail Cells(x, "H").Value2, "DCP Reminder - Priority: Medium", _
                        "Dear " & Cells(x, "F") & ", " & Chr(10) & Chr(10) & _
                        "This is a reminder that your DCP " & Cells(x, "A") & " " & Cells(x, "B") & " is due on " & Cells(x, "G")

            Else
                Send_Mail Cells(x, "H").Value2, "DCP Reminder - Priority: High", _
                        "Dear " & Cells(x, "F") & ", " & Chr(10) & Chr(10) & _
                        "This is a reminder that your DCP " & Cells(x, "A") & " " & Cells(x, "B") & " is due on " & Cells(x, "G")

            End If

            With Cells(x, "J")
                .Value2 = Date
                .Interior.ColorIndex = 3
                .Font.ColorIndex = 2
                .Font.Bold = True
            End With
        End If

    Next x

    Set myApp = Nothing

End Sub

Function Send_Mail(ByVal email_recipient As String, ByVal email_subject, ByVal email_body As String)

    Dim myApp As Outlook.Application
    Set myApp = New Outlook.Application

    Dim myMail As Outlook.MailItem
    Set myMail = myApp.createItem(olMailItem)

    With myMail
        .To = email_recipient
        .Subject = email_subject
        .Body = email_body
        '.Display
    End With

    Set myMail = Nothing
    Set myApp = Nothing

End Function

A: @hakan
    Sub DCP_Emails()

Dim mydate1 As Date
Dim mydate2 As Long
Dim datetoday1 As Date
Dim datetoday2 As Long
Dim daysLeft As Long
 Dim lastRow As Long

Dim d As Object, c As Range, k, tmp As String

Set d = CreateObject("scripting.dictionary")
 For Each c In Range("H:H").Cells
 If c.Value <> "N/A" Then
    tmp = Trim(c.Value)
    If Len(tmp) > 0 Then d(tmp) = d(tmp) + 1
  Next c

 For Each k In d.keys
lastRow = Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row

Dim x As Long
For x = 2 To lastRow
    If Cells(x, 7).Value <> " " Then
        mydate1 = Cells(x, 7).Value
        mydate2 = mydate1
        Cells(x, "J") = mydate2

        datetoday1 = Date
        datetoday2 = datetoday1

        Cells(x, "K").Value = datetoday2
        daysLeft = mydate2 - datetoday2

        If LCase$(Cells(x, "D").Value2) = "design" And Cells(x, 8).Value = k Then

            If daysLeft <= 14 And daysLeft >= 8 Then

          Send_Mail k.Value2, "DCP Reminder - Priority: Low", _
         "Dear " & Cells(x, "F") & ", " & Chr(10) & Chr(10) & _
          "This is a reminder that your DCP " & Cells(x, "A") & " " & Cells(x, "B") & " is due on " & Cells(x, "G")

            End If

            With Cells(x, "L")
                .Value2 = Date
                .Interior.ColorIndex = 3
                .Font.ColorIndex = 2
                .Font.Bold = True
            End With
        End If
End If

Next x
Next k

Set myApp = Nothing

End Sub

Function Send_Mail(ByVal email_recipient As String, ByVal email_subject, ByVal email_body As String)

Dim myApp As Object
Set myApp = CreateObject("Outlook.Application")

Dim myMail As Object
Set myMail = myApp.createItem(0)

With myMail
    .To = email_recipient
    .Subject = email_subject
    .Body = email_body
    .Send
    '.Display
End With

Set myMail = Nothing
Set myApp = Nothing

End Function


text:
Q: haskell words from alphabet of a given length I have this function that generates a list of all words with a min length 0 and max length n, equals given as an input to the function:
import Data.List

words :: Int -> String -> [String]
words 0 alph = [[]]
words n alph = words (n-1) alph ++ [ ch:w | w <-words (n-1) alph, ch <- alph]

When I run this, the output is following:
> words 3 "AB"
["","A","B","A","B","AA","BA","AB","BB","A","B","AA","BA","AB","BB","AA","BA","AB","BB","AAA","BAA","ABA","BBA","AAB","BAB","ABB","BBB"]

The problem here is, that there are some words repeating, in this example, especially the words of length of 2 ("AA" is 3 times there). Can you see what am I doing wrong in my function, or do you have any idea how to solve it?

A: This is because the words (n-1) alph in the list comprehension does not only yield words of length n-1 but also n-2, n-3, etc., since that is how you defined the words function.
It might be better to make a helper function that only generates words of length n and then use that in an extra function that constructs strings with lengths up to n:
words :: Int -> String -> [String]
words 0 alph = [[]]
words n alph = [ ch:w | w <-words (n-1) alph, ch <- alph]

wordsUpTo :: Int -> String -> [String]
wordsUpTo n alph = concatMap (flip words alph) [0 .. n]

However words already exists, this is just a special case of replicateM :: Applicative m = > Int -> m a -> m [a], so we can write this as:
import Control.Monad(replicateM)

wordsUpTo :: Int -> String -> [String]
wordsUpTo n alph = [0 .. n] >>= (`replicateM` alph)

which will produce:
Prelude Control.Monad> wordsUpTo 3 "AB"
["","A","B","AA","AB","BA","BB","AAA","AAB","ABA","ABB","BAA","BAB","BBA","BBB"]

A: The Applicative instance for lists effectively computes a cross-product,
> (,) <$> ["A", "B"] <*> ["C", "D"]
[("A","C"),("A","D"),("B","C"),("B","D")]

elements of which can be joined with (++) instead of (,):
> (++) <$> ["A", "B"] <*> ["C", "D"]
["AC","AD","BC","BD"]

If you repeatedly apply this operation, you'll get the strings you want:
> (++) <$> ["A", "B"] <*> [""] -- base case
["A","B"]
> (++) <$> ["A", "B"] <*> ["A","B"]
["AA","AB","BA","BB"]
> (++) <$> ["A", "B"] <*> ["AA","AB","BA","BB"]
["AAA","AAB","ABA","ABB","BAA","BAB","BBA","BBB"]

The function you want to repeat is the section ((++) <$> ["A", "B"] <*>), which from now on we'll refer to as f:
> f = ((++) <$> ["A", "B"] <*>)

This repeated application is captured by the iterate function, which repeatedly feeds the output of one function application as the input of the next.
> take 3 $ iterate f [""]
[[""],["A","B"],["AA","AB","BA","BB"]]

We'll want to concatenate the results into a single list:
> take 7 $ concat $ iterate f [""]
["","A","B","AA","AB","BA","BB"]

So all combinations is just
allWords alph = concat $ iterate f [""]
  where f = ((++) <$> alph <*>)

To get the elements with some maximum length, we can either

*

*Use takeWhile (\x -> length x <= n), or

*Use take (2^(n+1) - 1) (given the order in which items are generated, all the strings of a given length occur before longer strings, and we can compute the total number of strings with a given maximum length)

So we can define either
words n = takeWhile p . allWords
  where p x = length x < 4

or
words n = take n' . allWords


text:
Q: Create an "Other" category by summing in dplyr I have the following dataset with ID's and a numeric value per ID. I require to show the top 10 of largest ID's and group the rest under an "Other" category.
I have researched this question/answer but it works with counts instead of sums. So that approach wont work for my case
My desired result
ID          Value
63366849    42084408
63475529    21879648
6774736     21321888
91274582    17393328
63445915    15215002
1097911044  9926442
1095812405  8971332
1097910557  5388376
37548920    5114854
OTHERS      153587848

My data:
df=structure(list(ID= c("63366849", "63475529", "6774736",
"91274582", "63445915", "1097911044", "1095812405", "1097910557",
"37548920", "1005153076", "13513021", "51991938", "1010090155",
"91265898", "91237574", "91344448", "1095956598", "28065538",
"63341531", "63335642", "5637749", "17419836", "5567029", "5651301",
"37839500", "63450446", "28424298", "29264885", "63328148", "63562603",
"51702988", "7416450", "1005234045", "91520220", "91159937",
"13801492", "9260536", "37722978", "63355924", "1098711718",
"63443769", "60306461", "28485149", "2151526", "2127233", "1096063398",
"27948572", "13834945", "27938888", "91179848", "41678031", "37837953",
"91233367", "5557908", "28012681", "33446782", "91243709", "1007790961",
"1095826946", "1095926858", "20189860", "24049724", "27903426",
"28133395", "41446577", "37319481", "2033552", "27950302", "91200190",
"91205127", "9527919", "1095303440", "13826841", "91218008",
"63280472", "24074310", "37805433", "13801074", "28037341", "63353740",
"1095793583", "1102371309", "1116493966", "2127316", "2153230",
"37316948", "51778219", "5503745", "1099735096", "1222254600",
"27786180", "2162536", "27964677", "2020408", "91349686", "37514200",
"30208806", "1102351224", "28354311", "27929976", "63523710",
"13838438", "28296329", "28410262", "28494063", "5721778", "91275248",
"91353706", "37751608", "1097610166", "1098080648", "13810090",
"63444976", "1221464992", "1097497475", "91100475", "1095312933",
"28131889", "63506738", "7922341", "28238547", "27985819", "27958501",
"23912889", "5707630", "1102388693", "24028654", "28128637",
"5554160", "63369230", "36521093", "91525097", "27929902", "63441041",
"1097919703", "40984557", "1097129811", "13843871", "63301433",
"28236969", "37831774", "1000942168", "1005220322", "1098661759",
"1095843775", "28399609", "37211106", "5683927", "28254346",
"91268076", "28295325", "28496274", "13820294", "28354968", "37793321",
"63495244", "63299126", "13849979", "63357743", "60262321", "1098753025",
"91435400", "2195064", "63345546", "63251135", "13827671", "2007126",
"40378506", "1097121371", "37828831", "5707059", "63324477",
"1102644458", "37796841", "28334234", "28010824", "28495363",
"27929493", "5558783", "51974763", "28296333", "63489129", "1102385538",
"13814150", "13829893", "28377189", "91342964", "164497637",
"52326169", "63286143", "1099738639", "63503298", "1097913686",
"91070753", "37652636", "60352132"), Value= c(42084408,
21879648, 21321888, 17393328, 15215002, 9926442, 8971332, 5388376,
5114854, 5093730, 5004621, 3696756, 3424872, 3347432, 3337895,
3105759, 3104409, 3056238, 2748870, 2738808, 2662730, 2555784,
2268480, 2126700, 2051811, 2035200, 2025495, 1962000, 1926012,
1829736, 1822980, 1657659, 1574901, 1546320, 1539355, 1480530,
1456140, 1372302, 1372302, 1367235, 1350330, 1330560, 1327761,
1289520, 1265556, 1258350, 1245060, 1228770, 1228545, 1209705,
1196100, 1180533, 1175274, 1170286, 1144792, 1106820, 1106820,
1080621, 1080621, 1080621, 1080621, 1080621, 1080621, 1080621,
1080621, 1080264, 1067400, 1067400, 1003000, 993510, 992520,
988560, 957408, 957408, 922350, 889893, 888300, 883800, 855150,
835920, 833481, 833481, 833481, 833481, 833481, 833481, 833481,
833481, 823458, 775300, 741420, 734760, 734760, 729882, 672660,
666740, 631020, 621000, 621000, 600651, 598050, 553410, 553410,
553410, 553410, 553410, 553410, 553410, 552690, 503340, 468120,
439800, 416040, 415136, 403235, 398700, 383629, 383629, 383629,
367380, 364941, 360207, 360088, 346680, 339582, 339201, 339201,
339201, 339201, 303120, 300450, 289080, 282042, 238080, 234060,
219531, 211300, 195447, 195447, 192960, 192960, 169000, 169000,
169000, 163868, 163868, 156540, 143460, 136080, 132048, 127818,
127818, 124920, 124920, 124920, 124920, 105120, 93690, 93690,
77580, 66024, 64650, 62460, 62460, 62376, 58800, 58338, 57240,
50524, 49260, 49260, 48240, 46528, 44100, 43110, 42930, 41640,
40755, 38715, 37050, 35685, 33012, 30687, 28620, 28620, 24678,
24570, 15189, 15120, 15120, 14504, 14310, 11424, 6000, 5940,
5428)), row.names = c(NA, -196L), class = c("tbl_df", "tbl",
"data.frame"))

A: A slightly cleaner option using the forcats package:
df %>%
  mutate(ID = fct_lump_n(factor(ID), n = 9, w = Value, other_level = "OTHERS")) %>%
  group_by(ID) %>%
  summarize(Value = sum(Value)) %>%
  arrange(ID == "OTHERS", desc(Value))

# A tibble: 10 × 2
# ID    Value
# <fct> <dbl>
# 63366849  42084408
# 63475529  21879648
# 6774736   21321888
# 91274582  17393328
# 63445915  15215002
# 1097911044    9926442
# 1095812405    8971332
# 1097910557    5388376
# 37548920  5114854
# OTHERS    153587848

A: You could do something like this, if I am understanding right.
Sort the Value column, keep the ID for the top 10, and then name the rest "Other". Then just sum over that new ID.
This shows the top 10 plus an "other" field. From your expected output, you might want n = 9 instead.
library(dplyr)

n <- 10

df %>%
  arrange(desc(Value)) %>%
  mutate(ID2 = if_else(row_number() <= n, ID, "Other"),
         SortOrder = if_else(row_number() <= n, row_number(), as.integer(n + 1))) %>%
  group_by(ID2, SortOrder) %>%
  summarize(Value = sum(Value), .groups = "drop") %>%
  arrange(SortOrder) %>%
  select(ID = ID2, Value)

# # A tibble: 11 x 2
#    ID             Value
#    <chr>          <dbl>
#  1 63366849    42084408
#  2 63475529    21879648
#  3 6774736     21321888
#  4 91274582    17393328
#  5 63445915    15215002
#  6 1097911044   9926442
#  7 1095812405   8971332
#  8 1097910557   5388376
#  9 37548920     5114854
# 10 1005153076   5093730
# 11 Other      148494118

A: Here is a solution with dplyr:
library(dplyr)

arrange(df, desc(Value)) %>%
  split(c(rep("top", 10), rep("rest", nrow(.) - 10))) %>%
  (\(s) bind_rows(s$top, data.frame(ID = "Other", Value = sum(s$rest$Value))))

Returns:
# A tibble: 11 x 2
   ID             Value
   <chr>          <dbl>
 1 63366849    42084408
 2 63475529    21879648
 3 6774736     21321888
 4 91274582    17393328
 5 63445915    15215002
 6 1097911044   9926442
 7 1095812405   8971332
 8 1097910557   5388376
 9 37548920     5114854
10 1005153076   5093730
11 Other      148494118

(Data used:)
df <- structure(list(ID = c("63366849", "63475529", "6774736", "91274582", "63445915", "1097911044", "1095812405", "1097910557", "37548920", "1005153076", "13513021", "51991938", "1010090155", "91265898", "91237574", "91344448", "1095956598", "28065538", "63341531", "63335642", "5637749", "17419836", "5567029", "5651301", "37839500", "63450446", "28424298", "29264885", "63328148", "63562603", "51702988", "7416450", "1005234045", "91520220", "91159937", "13801492", "9260536", "37722978", "63355924", "1098711718", "63443769", "60306461", "28485149", "2151526", "2127233", "1096063398", "27948572", "13834945", "27938888", "91179848", "41678031", "37837953", "91233367", "5557908", "28012681", "33446782", "91243709", "1007790961", "1095826946", "1095926858", "20189860", "24049724", "27903426", "28133395", "41446577", "37319481", "2033552", "27950302", "91200190", "91205127", "9527919", "1095303440", "13826841", "91218008", "63280472", "24074310", "37805433", "13801074", "28037341", "63353740", "1095793583", "1102371309", "1116493966", "2127316", "2153230", "37316948", "51778219", "5503745", "1099735096", "1222254600", "27786180", "2162536", "27964677", "2020408", "91349686", "37514200", "30208806", "1102351224", "28354311", "27929976", "63523710", "13838438", "28296329", "28410262", "28494063", "5721778", "91275248", "91353706", "37751608", "1097610166", "1098080648", "13810090", "63444976", "1221464992", "1097497475", "91100475", "1095312933", "28131889", "63506738", "7922341", "28238547", "27985819", "27958501", "23912889", "5707630", "1102388693", "24028654", "28128637", "5554160", "63369230", "36521093", "91525097", "27929902", "63441041", "1097919703", "40984557", "1097129811", "13843871", "63301433", "28236969", "37831774", "1000942168", "1005220322", "1098661759", "1095843775", "28399609", "37211106", "5683927", "28254346", "91268076", "28295325", "28496274", "13820294", "28354968", "37793321", "63495244", "63299126", "13849979", "63357743", "60262321", "1098753025", "91435400", "2195064", "63345546", "63251135", "13827671", "2007126", "40378506", "1097121371", "37828831", "5707059", "63324477", "1102644458", "37796841", "28334234", "28010824", "28495363", "27929493", "5558783", "51974763", "28296333", "63489129", "1102385538", "13814150", "13829893", "28377189", "91342964", "164497637", "52326169", "63286143", "1099738639", "63503298", "1097913686", "91070753", "37652636", "60352132"), Value = c(42084408, 21879648, 21321888, 17393328, 15215002, 9926442, 8971332, 5388376, 5114854, 5093730, 5004621, 3696756, 3424872, 3347432, 3337895, 3105759, 3104409, 3056238, 2748870, 2738808, 2662730, 2555784, 2268480, 2126700, 2051811, 2035200, 2025495, 1962000, 1926012, 1829736, 1822980, 1657659, 1574901, 1546320, 1539355, 1480530, 1456140, 1372302, 1372302, 1367235, 1350330, 1330560, 1327761, 1289520, 1265556, 1258350, 1245060, 1228770, 1228545, 1209705, 1196100, 1180533, 1175274, 1170286, 1144792, 1106820, 1106820, 1080621, 1080621, 1080621, 1080621, 1080621, 1080621, 1080621, 1080621, 1080264, 1067400, 1067400, 1003000, 993510, 992520, 988560, 957408, 957408, 922350, 889893, 888300, 883800, 855150, 835920, 833481, 833481, 833481, 833481, 833481, 833481, 833481, 833481, 823458, 775300, 741420, 734760, 734760, 729882, 672660, 666740, 631020, 621000, 621000, 600651, 598050, 553410, 553410, 553410, 553410, 553410, 553410, 553410, 552690, 503340, 468120, 439800, 416040, 415136, 403235, 398700, 383629, 383629, 383629, 367380, 364941, 360207, 360088, 346680, 339582, 339201, 339201, 339201, 339201, 303120, 300450, 289080, 282042, 238080, 234060, 219531, 211300, 195447, 195447, 192960, 192960, 169000, 169000, 169000, 163868, 163868, 156540, 143460, 136080, 132048, 127818, 127818, 124920, 124920, 124920, 124920, 105120, 93690, 93690, 77580, 66024, 64650, 62460, 62460, 62376, 58800, 58338, 57240, 50524, 49260, 49260, 48240, 46528, 44100, 43110, 42930, 41640, 40755, 38715, 37050, 35685, 33012, 30687, 28620, 28620, 24678, 24570, 15189, 15120, 15120, 14504, 14310, 11424, 6000, 5940, 5428)), row.names = c(NA, -196L), class = c("tbl_df", "tbl", "data.frame"))

A: One more tidyverse way
library(tidyverse)
df %>%
  split(dense_rank(-.$Value) >= 10) %>%
  map_if(c(F, T), ~ .x %>% summarise(ID = 'OTHERS',
                                            Value = sum(Value))) %>%
  map_dfr(~.x)

# A tibble: 10 x 2
   ID             Value
   <chr>          <dbl>
 1 63366849    42084408
 2 63475529    21879648
 3 6774736     21321888
 4 91274582    17393328
 5 63445915    15215002
 6 1097911044   9926442
 7 1095812405   8971332
 8 1097910557   5388376
 9 37548920     5114854
10 OTHERS     153587848


text:
Q: Почему не используют LDAP? У меня сколько проектов, ровно столько же иерархических структур хранения. В основном, и документы и единицы аппаратуры и и пути следования все это имеет иерархическую структуру хранения. Но многочисленные разработчики предлагают использовать различные субд, вместо старого доброго ldap. Почему?

A: SQL базы данных более распространены и более знакомы разработчикам.


text:
Q: Outlook Calendar: Showing a day has gone already Is there a way to show that a day has occurred? When I print my calendars out I like to cross out the days that have already happened and I wanted to know if there was a setting to do that for Outlook as well?

A: This was asked on Microsoft's site and an answer was given that may help you. Click here to see it: https://social.technet.microsoft.com/Forums/office/en-US/9c4cad00-80c5-43ac-9c06-4f595c8914f4/calendar-cross-or-mark-off-days-by-putting-x-on-them?forum=outlook.
The answer they gave is as follows:

I have searched for this feature extensively and couldn't come up with
  anything.  It simply doesn't exist and for some reason Microsoft won't
  do anything about it.  I don't understand how it could be that
  difficult.
Anyway, I've come up with a solution that works for me, because I
  don't really like having to look around the month view for where
  today's date is.  I just created a new appointment named "Done" (for
  days that are past) and categorized it in a new category called "Done
  Days" which I put a black label on.  Of course, you can use red, pink,
  green, or anything else that suits your fancy, but black shows up well
  for me.  I then posted that appointment on a day in the past and set
  it for "All Day" so that it wouldn't remind me.  If you click on the
  appointment once, just so that it selects it, you can hit Ctrl+C to
  copy and then click on any other day, and hit Ctrl+V to paste it into
  any past days.
This way, any past days have a black bar through them that says "Done"
  and at the end of a day, all you have to do is select one of those
  bars, and copy and paste it to the current day.  Maybe it's just me,
  but I think it's kind of satisfying to check off a day this way.


text:
Q: Why can't I use nth-child on mark tags? Nothing in my code overwrites this selector, so I'm confused as to why it's not working. I've googled about it and asked a few friends and they don't know. I checked the server wasn't just taking a while to update the page by updating text and it seems fine.
CSS
mark {
    color: #CCC;
    background: #333;
    padding: 5px;
    margin: 5px;
}
mark:nth-child(even) {
    background: #000;
}

HTML

warri0rYes

j3w1shNo

MrGuyI don't know

explode_Maybe...

USAUSAUSAWhy not?

Samuel01Absolutely

A: mark:nth-child(even) doesn't work because it is an only child of
.
Rewrite your CSS:
p:nth-child(even) mark {
    background: #000;
}

(select  of even
)
http://jsfiddle.net/hbxk3owh/

A: Because :nth-child looks for the parent element to find the child.
To easily understand it:
Wrap your code inside a div. Access the even paragraph using nth-child(2n) which is even children of the parent div mark.
You need not have parent div mask for your case because  is the parent. Just for explanation purpose I have added the class mask

mark {
  color: #CCC;
  background: #333;
  padding: 5px;
  margin: 5px;
}
.mark p:nth-child(even) mark {
  background: #000;
}

    warri0rYes

    j3w1shNo

    MrGuyI don't know

    explode_Maybe...

    USAUSAUSAWhy not?

    Samuel01Absolutely

A: Because nth-child use in a element like this:
mark {
  color: #CCC;
  background: #333;
  padding: 5px;
  margin: 5px;
}
mark:nth-child(even) {
  background: #000;
}

  warri0rYes

  j3w1sh<span<No

  MrGuyI don't know

Now p element has 3 child in yourself.


text:
Q: Ember data JSONAPIAdapter: fetch nested resources I'm trying to get Ember Data's JSONAPIAdapter to work with nested resources. For the server part django-rest-framework-json-api is used.
My (simplified) ember models:
case.js
export default Model.extend({
  firstName: attr('string'),
  lastName: attr('string'),
  comments: hasMany('comment'),
})

comment.js
export default Model.extend({
  text: attr('string'),
  case: belongsTo('case'),
})

The server's response for /api/v1/cases/4 looks like this:
{
  "data": [
    {
      "type": "cases",
      "id": "4",
      "attributes": {
         "first-name": "Hans",
         "last-name": "Peter",
      },
      "relationships": {
        "comments": {
          "meta": {
            "count": 1
          },
          "data": [
            {
              "type": "comments",
              "id": "5"
            }
          ],
          "links": {
            "related": "http://localhost:8000/api/v1/cases/4/comments"
          }
        }
      }
    }
  ]
}

Now, if i understand Ember Data and the JSON-API spec correctly, ember should request /api/v1/cases/4/comments when i reference the comments. Instead, it requests /api/v1/comments/5, which obviously returns a 404.
My questions in summary:

*

*Does the server response comply to the JSON-API spec?

*How do i get ember to respect the nested route?

I'm using ember v2.8.
Bonus question: I face the same problem for creating a new comment - how do i get ember to POST to /case/4/comments instead of /comments?

A: The JSON API spec does not enforce any specific URL pattern, so what you're trying to do is compliant. However, I find that working with a flat URL structure is easier with Ember Data, though there is a workaround.
You'll want to look at the ember-data-url-templates addon and add some logic from it to your model's adapter.
With that addon, here is what you can do with app/adapters/comment.js:
import ApplicationAdapter from './application';
import UrlTemplates from 'ember-data-url-templates';

export default ApplicationAdapter.extend(UrlTemplates, {
  namespace: 'api/v1', // You may or may not need this namespace setting:
                       // I'm a little rusty in this area :)

  urlTemplate: '{+host}/case/{caseId}/comments{/id}',

  urlSegments: {
    contentId: function(type, id, snapshot/*, query */) {
      return snapshot.belongsTo('case', { id: true });
    }
  }
});

Unless there is something else that the addon allows to get around this, I believe that this then locks you into that URL structure for comments across your entire app. So definitely weigh that tradeoff before deciding to go down this route.

A: Yes this works it should be setup as follows
models/client.js
export default DS.Model.extend({
    name: DS.attr('string'),
    telno: DS.attr('string'),

    campaigns: hasMany()
});

models/client.js
export default DS.Model.extend({
    name: DS.attr('string'),
    startdate: DS.attr('date'),
    enddate: DS.attr('date'),

    client: DS.belongsTo('client')
});

/templates/client/edit.bhs

                Name

            {{#each model.campaigns as |campaign|}}

                    {{campaign.name}}

            {{/each}}

http://localhost:3000/api/clients/1
{
{
  "links": {
    "self": "http://localhost:3000/api/clients/1"
  },
  "data": {
    "type": "clients",
    "relationships": {
      "campaigns": {
        "links": {
          "related": "http://localhost:3000/api/clients/1/campaigns"
        }
      }
    },
    "id": "1",
    "attributes": {
      "name": "Test",
      "telno": "123"
    },
    "links": {
      "self": "http://localhost:3000/api/clients/1"
    }
  }
}

http://localhost:3000/api/clients/1/campaigns
{
  "links": {
    "self": "http://localhost:3000/api/clients/1/campaigns"
  },
  "data": [
    {
      "type": "campaigns",
      "relationships": {
        "client": {
          "links": {
            "related": "http://localhost:3000/api/campaigns/1/client"
          }
        }
      },
      "id": "1",
      "attributes": {
        "enddate": "2019-01-01T00:00:00.000Z",
        "name": "test",
        "startdate": null
      },
      "links": {
        "self": "http://localhost:3000/api/campaigns/1"
      }
    }
  ]
}


text:
Q: Stinespring dialation Let $A\in End(\mathbb{C}^n)$ be Hermitian and with positive eigenvalues. Define the linear map $T:End(\mathbb{C}^n)\longrightarrow End(\mathbb{C}^n)$ with $T(M)=(tr(M))A$. How can I make an isometry $U\in Hom(\mathbb{C}^n,\mathbb{C}^n\times\mathbb{C}^n)$ such that $$T(M)=tr_B(UMU^H)$$ where $tr_B(N\otimes P)=(tr(N))P$ and $U^H$ is the Hermitian conjugation of $U$.
Just an algorithmic step-by-step receipt for computing this $U$ is my question not it's theoretical possibility.

A: The partial trace is not a standard feature of the Stinespring decomposition. I don't think you can get the decomposition you want in general.
Write
$$
U=\begin{bmatrix}V_1\\  \vdots \\ V_n\end{bmatrix}.
$$
Then
$$
UMU^H=\begin{bmatrix}V_1MV_1^*&V_1MV_2^*&\cdots&V_1MV_n^*\\
V_2MV_1^*&V_2MV_2^*&\cdots&V_2MV_n^*\\
\vdots \\
V_nMV_1^*&V_nMV_2^*&\cdots &V_nMV_n^*
\end{bmatrix},
$$
and
$$
\text{tr}_B(UMU^H)=\begin{bmatrix}\text{tr}(V_1MV_1^*)&\text{tr}(V_1MV_2^*)&\cdots&\text{tr}(V_1MV_n^*)\\
\text{tr}(V_2MV_1^*)&\text{tr}(V_2MV_2^*)&\cdots&\text{tr}(V_2MV_n^*)\\
\vdots \\
\text{tr}(V_nMV_1^*)&\text{tr}(V_nMV_2^*)&\cdots &\text{tr}(V_nMV_n^*)
\end{bmatrix}.
$$
You want this last matrix to be equal to $\text{tr}(M)A$ for all $M$. That is,
$$\tag{1}
\text{tr}(MV_j^*V_k)=\text{tr}(M)A_{kj}
$$
for all $M$. Taking $M=E_{kj}$ (matrix unit) we see that $\text{tr}(V_j^*V_k)=0$ if $k\ne j$. But now, taking $M=I$, we deduce that $A_{kj}=0$ when $k\ne j$, i.e. $A$ has to be diagonal. Now we have $\text{tr}(MV_j^*V_k)=0$, when $j\ne k$, for all $M$; it follows that $V_j^*V_k=0$.
From $U^HU=I_n$ we get $$\tag{2}V_1^*V_1+\cdots+V_n^*V_n=I_n.$$ Now adding over $k=j$ on $(1)$ we obtain
$$
\text{tr}(M)=\text{tr}(M)\,\sum_kA_{kk},
$$
so $\text{tr}(A)=1$.
Fix $k$. Going back to $(1)$, we have
$$
\text{tr}(MV_k^*V_k)=\text{tr}(M)A_{kk}
$$
for all $M$. As the right-hand-side does not change as we choose $M=E_{11},\ldots,E_{nn}$, we get that the diagonal of $V_k^*V_k$ is constant, equal to $A_{kk}$. Taking $M=E_{st}$ for any $s\ne t$ we get
$$
(V_k^*V_k)_{st}=\text{tr}(E_{1t}V_k^*V_kE_{s1})=\text{tr}(E_{st}V_k^*V_k)=\text{tr}(E_{st})A_{kk}=0.
$$
Thus, $V_k^*V_k=A_{kk}I_n$. As $A_{kk}>0$, we deduce that the matrix $V_k/A_{kk}^{1/2}$ is a unitary. But now we get that, for $j\ne k$,
$$
0=V_j^*V_k
$$
is a scalar multiple of a unitary: a contradiction. In conclusion, no such $U$ can exist.


text:
Q: JavaFX threads shutdown upon application exit I wonder if there is any neat and clean way of shutting down my application's thread executors when the main window closes.
If the threads are marked as daemon threads they are automatically interrupted when the application closes. But in my case I do not want to do that. if a task is writing a file I want the task to finish and the thread to shutdown only after the task has finished, otehrwise I end up with a corrupted file.
A possible solution could be using each executor only once and calling shutdown on it after submiting the task, but that has the overhead of having to create a new thread each time a new task is to be submitted.
In my current application having just one controller I am using the onClose event of the main window to call a method in the controller to shutdown the executor if there is one (code below). But that is not a clean solution if there are many controllers.
MainController controller = loader.getController();
stage.setOnCloseRequest(ev -> {
    controller.finalize();
});

Can anyone devise a better one?

A: Override stop and call shutdown on your executor service;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class CleanExecShutdown extends Application {

    private ExecutorService exec ;
    private int count ;

    @Override
    public void start(Stage primaryStage) {
        exec = Executors.newCachedThreadPool();
        ListView<String> completedTasks = new ListView<>();
        Button button = new Button("Start new task");
        Random rng = new Random();
        button.setOnAction(e -> {
            final int n = ++count;
            Task<String> task = new Task<String>() {
                @Override
                public String call() {
                    try {
                        Thread.sleep(rng.nextInt(1000)+1000);
                    } catch (InterruptedException exc) {
                        exc.printStackTrace();
                        Thread.currentThread().interrupt();
                    }
                    String message = "Task "+n+" completed";
                    System.out.println(message);
                    return message ;
                }
            };
            task.setOnSucceeded(evt -> completedTasks.getItems().add(task.getValue()));
            exec.execute(task);
        });

        BorderPane root = new BorderPane();
        root.setCenter(completedTasks);
        BorderPane.setAlignment(button, Pos.CENTER);
        BorderPane.setMargin(button, new Insets(5));
        root.setBottom(button);
        Scene scene = new Scene(root, 250, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    @Override
    public void stop() {
        if (exec != null) {
            exec.shutdown();
        }
    }

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

(Obviously you need to refactor that if you have your executor in another class, but the idea is basically the same.)


text:
Q: Find Duplicate Values in 2 Columns in MySQL The title isn't strictly accurate: I'm not just trying to find "duplicate" records; I'm trying to find all records that have a duplicate value in one column, but only if all of those records also have a duplicate value in another column.
As a real world problem, it's phrased this way: I want a list of all items for which every size of that item has the same status code.
Some example data:
table catalog_items
id, name
 0, Gloves
 1, Spade
 2, Seed

table catalog_sizes
id, f_id,  size, price, status
 0,    0, small,     1,  oos
 1,    0,   med,     2,  oos
 2,    0, large,     3,
 3,    1,   one,    12,  oos
 4,    1,   two,    20,  oos
 5,    2,   1oz,    10,  bo
 6,    2,   1lb,   100,  bo

(Note that id 2 aka large gloves is not oos like it's two smaller sizes.)  In our real data, all items will have at least 1 size, and most have 3-5.  Also, our data set will never be larger than 10,000 records.
This get's close:
SELECT f_id, status
FROM catalog_sizes
WHERE status != ''
GROUP BY f_id, status

but isn't correct because it also returns a record for items that have some sizes with duplicate status.  (e.g. f_id 0 has two sizes with status oos)  I need to get a list of items for which all sizes have the same status. Given the example data in catalog_sizes, my desired output is:
f_id, status
   1,  oos
   2,  bo

What's the best way to do this?  Can it be done in a single query?

A: I believe the following should work:
select ci.name, cs.f_id, MIN(cs.status) AS status
from catalog_items ci join catalog_sizes cs on ci.id = cs.f_id
group by ci.name, cs.f_id
having max(cs.status) = min(cs.status);

Le me know if this helps!

A: this query should do what you want. it compares the highest and lowest strings (to see if they are different) returns 0 if true so when its only 0 it will appear in query.
see working FIDDLE
SELECT f_id, status, COUNT(id)
FROM catalog_sizes
GROUP BY f_id
HAVING STRCMP(MIN(status), MAX(status)) = 0


text:
Q: Erro ao inserir dados com EntrityFramework C# estou com um problema muito estranho, tenho 3 tabelas, sendo elas, Paises, Estados e Cidades, todas elas estão configuradas certamente iguais, mas está dando erro apenas quando é inserido dados na tabela Cidades.

Classes:

public class Paises : EntityBase
{
    public Paises()
    {
        Estados = new List<Estados>();
    }

    public string Descricao { get; set; }
    public string Sigla { get; set; }
    public ICollection<Estados> Estados { get; set; }
}

public class Estados : EntityBase
{
    public Estados()
    {
        Pais = new Paises();
        Cidades = new List<Cidades>();
    }

    public string Descricao { get; set; }
    public string Sigla { get; set; }
    public int PaisHandle { get; set; }
    public Paises Pais { get; set; }
    public ICollection<Cidades> Cidades { get; set; }
}

public class Cidades : EntityBase
{
    public Cidades()
    {
        Estado = new Estados();
    }

    public string Descricao { get; set; }
    public string Sigla { get; set; }
    public int EstadoHandle { get; set; }
    public Estados Estado { get; set; }
}

Mapeamento

public class PaisesMapping : EntityTypeConfiguration<Paises>
{
    public PaisesMapping()
    {
        ToTable("PAISES");

        HasKey(x => x.Handle);

        Property(x => x.Descricao).HasMaxLength(150).IsRequired();
        Property(x => x.Sigla).HasMaxLength(3).IsRequired();

        HasMany(x => x.Estados);
    }
}

public class EstadosMapping : EntityTypeConfiguration<Estados>
{
    public EstadosMapping()
    {
        ToTable("ESTADOS");

        HasKey(x => x.Handle);

        Property(x => x.Descricao)
            .HasMaxLength(150)
            .IsRequired();

        Property(x => x.Sigla)
            .HasMaxLength(2)
            .IsRequired();

        HasRequired(x => x.Pais)
            .WithMany(x => x.Estados)
            .HasForeignKey(x => x.PaisHandle);
    }
}

public class CidadesMapping : EntityTypeConfiguration<Cidades>
{
    public CidadesMapping ()
    {
        ToTable("CIDADES");

        HasKey(x => x.Handle);

        Property(x => x.Descricao)
            .HasMaxLength(150)
            .IsRequired();

        Property(x => x.Sigla)
            .HasMaxLength(3)
            .IsRequired();

        HasRequired(x => x.Estado)
            .WithMany(x => x.Cidades)
            .HasForeignKey(x => x.EstadoHandle);
    }
}

Classe Context

public partial class AdventureContext : DbContext
{
    static AdventureContext()
    {
        Database.SetInitializer<AdventureContext>(null);
    }

    public AdventureContext()
        : base("Name=AdventureContext")
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

    public DbSet<Paises> Paises { get; set; }
    public DbSet<Estados> Estados { get; set; }
    public DbSet<Cidades> Cidades { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Aqui vamos remover a pluralização padrão do Etity Framework que é em inglês
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        /*Desabilitamos o delete em cascata em relacionamentos 1:N evitando
         ter registros filhos     sem registros pai*/
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        //Basicamente a mesma configuração, porém em relacionamenos N:N
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

        /*Toda propriedade do tipo string na entidade POCO
         seja configurado como VARCHAR no SQL Server*/
        modelBuilder.Properties<string>()
                  .Configure(p => p.HasColumnType("varchar"));

        modelBuilder.Properties()
           .Where(p => p.Name.ToUpper() == "HANDLE")
           .Configure(p => p.IsKey());

        modelBuilder.Configurations.Add(new PaisesMapping());
        modelBuilder.Configurations.Add(new EstadosMapping());
        modelBuilder.Configurations.Add(new CidadesMapping());
    }
}

Inserindo dados com o EntityFramework

O Erro é dados no 3° SaveChanges(), aprensentando:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
    private void Form1_Load(object sender, EventArgs e)
    {
        AdventureContext ac = new AdventureContext();

        Paises pais1 = new Paises();
        pais1.Handle = 1;
        pais1.Descricao = "BRASIL";
        pais1.Sigla = "BRA";
        pais1.DataCadastro = DateTime.Now;
        pais1.UsuarioCadastro = "Nicola Bogar";

        Paises pais2 = new Paises();
        pais2.Handle = 2;
        pais2.Descricao = "FRANÇA";
        pais2.Sigla = "FRA";
        pais2.DataCadastro = DateTime.Now;
        pais2.UsuarioCadastro = "Nicola Bogar";

        Estados estado1 = new Estados();
        estado1.Handle = 1;
        estado1.Descricao = "SÃO PAULO";
        estado1.Sigla = "SP";
        estado1.Pais = pais1;
        estado1.DataCadastro = DateTime.Now;
        estado1.UsuarioCadastro = "Nicola Bogar";

        Estados estado2 = new Estados();
        estado2.Handle = 2;
        estado2.Descricao = "RIO DE JANEIRO";
        estado2.Sigla = "RJ";
        estado2.Pais = pais2;
        estado2.DataCadastro = DateTime.Now;
        estado2.UsuarioCadastro = "Nicola Bogar";

        Estados estado3 = new Estados();
        estado3.Handle = 3;
        estado3.Descricao = "SANTA CATARINA";
        estado3.Sigla = "SC";
        estado3.Pais = pais1;
        estado3.DataCadastro = DateTime.Now;
        estado3.UsuarioCadastro = "Nicola Bogar";

        Cidades cidade1 = new Cidades();
        cidade1.Handle = 1;
        cidade1.Descricao = "GUARARAPES";
        cidade1.Sigla = "GUA";
        cidade1.Estado = estado1;
        cidade1.DataCadastro = DateTime.Now;
        cidade1.UsuarioCadastro = "Nicola Bogar";

        Cidades cidade2 = new Cidades();
        cidade2.Handle = 2;
        cidade2.Descricao = "ARAÇATUBA";
        cidade2.Sigla = "ARA";
        cidade2.Estado = estado1;
        cidade2.DataCadastro = DateTime.Now;
        cidade2.UsuarioCadastro = "Nicola Bogar";

        Cidades cidade3 = new Cidades();
        cidade3.Handle = 3;
        cidade3.Descricao = "BLUMENAU";
        cidade3.Sigla = "BLU";
        cidade3.Estado = estado3;
        cidade3.DataCadastro = DateTime.Now;
        cidade3.UsuarioCadastro = "Nicola Bogar";

        try
        {
            ac.Paises.Add(pais1);
            ac.Paises.Add(pais2);
            ac.SaveChanges();

            ac.Estados.Add(estado1);
            ac.Estados.Add(estado2);
            ac.Estados.Add(estado3);
            ac.SaveChanges();

            ac.Cidades.Add(cidade1);
            ac.Cidades.Add(cidade2);
            ac.Cidades.Add(cidade3);
            ac.SaveChanges();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

A: O problema que estava tendo era que criei o campo Sigla com 3 caracter, depois troquei para 2 caracteres e esqueci de executar o Update-DataBase.


text:
Q: Why are some files are not being added do my zipfile I have the following code:
with ZipFile('deploy.zip', 'w') as deploy:
    if os.path.isfile(artifact.source):
        deploy.write(artifact.source, artifact.target)
    else:
        for base, dirs, files in os.walk(artifact.source):
            for file_ in files:
                source = os.path.join(base, file_)
                target = os.path.join(base[base.index(artifact.target):], file_)
                deploy.write(source, target)

when this code finish, only the files that match when the artifact.source is a file are added to the deploy.zip. And in some cases artifact.source will be a directory (i have tested this case too) ad the for part will be executed.
The result of the following lines are valid and source exists for every iteration:
source = os.path.join(base, file_)
target = os.path.join(base[base.index(artifact.target):], file_)

Here the full code that i'm working: https://gist.github.com/khaoz/9b04d87b0900fba780f0
Set config.project_root to something like "c:\temp" and remove the import config line.
OBS: I'm a Python newbie, so ignore some crap code that  you will see :P
And here a example of my csv file: https://gist.github.com/khaoz/e9a59390f415f22d46db
What i'm doing wrong ?

A: JUST FYI
My interpretation of what you did, this seems to work.
from zipfile import ZipFile
from collections import namedtuple
import os

Artifact =  namedtuple('Artifact', ['source', 'target'])
artifact =  Artifact(source="Mongodb", target="g")

with ZipFile('deploy.zip', 'w') as deploy:
    if os.path.isfile(artifact.source):
        print "F"
        print "\n", artifact.source
        print "\n", artifact.target
        deploy.write(artifact.source, artifact.target)
    else:
        for base, dirs, files in os.walk(artifact.source):
            for file_ in files:
                print "base", base, file_
                source = os.path.join(base, file_)
                target = os.path.join(base[base.index(artifact.target):], file_)
                print "f"
                print "\t", source
                print "\t", target
                deploy.write(source, target)

unzip -l deploy.zip | tail
     2591  01-09-13 21:26   godb/Sortif/scratch.py
     2010  01-15-13 20:20   godb/Sortif/sortif_model.py
     2495  01-15-13 20:22   godb/Sortif/sortif_model.pyc
      161  01-15-13 20:45   godb/Sortif/sortif_scratch.py
        0  01-08-13 12:05   godb/Sortif/sortif/__init__.py
        0  01-08-13 12:05   godb/Sortif/sortif/models/__init__.py
     1408  01-21-13 18:05   godb/ZeroMQ/client.py
     3044  01-21-13 17:51   godb/ZeroMQ/controller.py
 --------                   -------
 11137644                   967 files

I'm unsure what you're trying to achieve with base[base.index(artifact.target):] are you wanting to change the prefix ? Because running it on my Mongodb directory target had to appear in the directory of the file base.
I'm unsure how you expect to drive the code as it seems that artifact.source is a constant. So first time around it finds a file and it will never do the part where it's looking for directory.
Shouldn't it be
with ZipFile('deploy.zip', 'w') as deploy:
    for artifact in articats:
        if os.path.isfile(artifact.source):
            ...

A: I discovered the problem. Sometimes, sleep is the best solution form some problems
I was doing:
for artifact in artifacts:
    if not artifact.name in contents:
        contents.append(artifact.name)

    with ZipFile('deploy.zip', 'w') as deploy:
        if os.path.isfile(artifact.source):
            deploy.write(artifact.source, artifact.target)
        else:
            for base, dirs, files in os.walk(artifact.source):
                for file_ in files:
                    source = os.path.join(base, file_)
                    target = os.path.join(base[base.index(artifact.target):], file_)
                    deploy.write(source, target)

But for every iteration in the artifacts close and open a new deploy.zip file.
The right way to do this is:
with ZipFile('deploy.zip', 'w') as deploy:
    for artifact in artifacts:
        if not artifact.name in contents:
            contents.append(artifact.name)

        if os.path.isfile(artifact.source):
            deploy.write(artifact.source, artifact.target)
        else:
            for base, dirs, files in os.walk(artifact.source):
                for file_ in files:
                    source = os.path.join(base, file_)
                    target = os.path.join(base[base.index(artifact.target):], file_)
                    deploy.write(source, target)

And everything works as expected.
Thank you very much for everyone that tried to help. Next time i will post the full source code or at last, some lines more. :)


text:
Q: ObjectContext disposed also in opened context of EF I have this method for creating DataTable:
private DataTable toDataTable<T>(IEnumerable<T> items)
    {
        var tb = new DataTable(typeof(T).Name);
        using (var context = new MyEntity())
        {
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var prop in props)
            {
                tb.Columns.Add(prop.Name, prop.PropertyType);
            }

            foreach (var item in items)
            {
                var values = new object[props.Length];
                for (var i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }
        }
       return tb;

    }

but it give me this error in second foreach:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

since I opened my EF's context;why again this error occurs?

A: The IEnumerable<T> that you are passing into toDataTable<T>() has not been realized yet. The context of items is already disposed. You have forgotten a ToList() in the calling code.

A: If items originates from EntityFramework as well then it may be the culprit--it's Context may have closed.
Do you know which line the exception originates from?

A: I'm assuming the items collection contains entities from EF. Those items originally belonged to an ObjectContext, which apparently was closed before you passed them into this method. Opening a brand new context doesn't help because that's not the context that these items belong to.
When you use reflection on one of these entities, it's likely attempting to lazily access a navigation property of the entity, which would require a database trip, but since the context that the entity belongs to is gone, that database trip cannot happen.
You can reattach the item to the new context, then this should work:
foreach (var item in items)
{
    context.Attach(item);
    ... // now your item is attached to a live context again, and it
        // can hit the database
}

This is assuming you want to lazily load this - if you want to eagerly load and avoid the second database hit, you'd need to Include it when you retrieve the item from the database in the first place.


text:
Q: Robot framework run on Github actions can't get test return codes I am using Github actions to run my test with robot framework, when test complete, and in bash shell I can get return code in special variable via $?, but even test fail it also get 0
name: Test
on: [workflow_dispatch]

jobs:
  TEST-Run:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: install
      run: |
        pip3 install -r requirements.txt

    - name: Run Tests
      run: |
        robot test.robot

    - name: Set Robot Return Code
      run: |
        echo "ROBOT_RC=$?" >> "$GITHUB_ENV"

    - name: If Auto Test Pass Rate Not 100%, Job Will Fail
      if: env.ROBOT_RC != '0'
      run: |
        echo "Auto Test Pass Rate Not 100%, Please Check Test Result"
        exit 1

Any help or explanation is welcome! Thank you.

A: According to jobs.<job_id>.steps[*].run:

Each run keyword represents a new process and shell in the runner environment. When you provide multi-line commands, each line runs in the same shell.

So, you need to combine those steps in one:
    - name: Run Tests
      run: |
        robot test.robot
        echo "ROBOT_RC=$?" >> "$GITHUB_ENV"

or,
    - name: Run Tests
      run: |
        robot test.robot; ROBOT_RC=$?
        echo "ROBOT_RC=$ROBOT_RC" >> "$GITHUB_ENV"

See jobs.<job_id>.steps[*].shell for more details.


text:
Q: MySQL 5.6 install on debian ERROR: I'm trying to install MySQL 5.6 on Debian.
Here what I do:
sudo dpkg -i mysql-5.6.12-debian6.0-i686.deb
cd /usr/local
ln -s /opt/mysql/server-5.6 mysql
cd mysql
scripts/mysql_install_db.sh --user=mysql --datadir=/var/lib/mysql

And this is the error that I get:
FATAL ERROR: Could not find @bindir@/my_print_defaults

If you compiled from source, you need to run 'make install' to
copy the software into the correct location ready for operation.

If you are using a binary release, you must either be at the top
level of the extracted archive, or pass the --basedir option
pointing to that location.

Could you please suggest something? I'm installing MySQL from scratch (previous version was completely removed).
Thanks.

A: I might not be able to help with the error you're getting. But apt-get install -f mysql-server-5.5 worked for me on Debian Wheezy. Try replacing 5.5 with 5.6 and see if it works as well, and probably precede it with sudo.


text:
Q: XSLT transform single attribute to element I am trying to transform single attribute to an element.
The XSL I use is :
   <xsl:template match="TextView/@*">
   <xsl:element name="{name()}">
   <xsl:value-of select="."/>
   </xsl:element>
   </xsl:template>

my xml:
    <TextView
     android:id="@+id/ti"
     style="@style/HTxt"
     android:text="@string/ti"
     custom:attribute="name" />

The above XSL transforms all the attributes to elements. But I want to transform only the 'custom:attribute' and ignore the others. How can I achieve this? Thanks in advance.

A: Replaced @* with @custom:attribute
Therefore try:
<xsl:template match="TextView/@custom:attribute">
        <xsl:element name="{name()}">
            <xsl:value-of select="."/>
        </xsl:element>
</xsl:template>

But attention: custom is a namespace prefix. You have to add it with the same namespace URL as in your XML to your xsl:stylesheet.
Something like:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
       xmlns:custom="CUSTOM_URL"
    version="1.0">


text:
Q: How to get PMD maven plugin to skip generated source code? So I'm creating a maven plugin using the maven-plugin-plugin. The HelpMojo in maven-plugin-plugin generates a java source file.
Unfortunately, PMD is picking this up and complaining about it. Is there a way to have PMD ignore just a single source file? Thanks!
Maven PMD Configuration:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-pmd-plugin</artifactId>
            <executions>
                <execution>
                    <id>pmd-verify</id>
                    <goals>
                        <goal>check</goal>
                        <goal>cpd-check</goal>
                    </goals>
                    <configuration>
                        <printFailingErrors>true</printFailingErrors>
                    </configuration>
                </execution>
            </executions>
        </plugin>

A: Generated sources usually end up (with maven) in a subdirectory in target/generated-sources, for the maven-plugin-plugin it's target/generated-sources/plugin.
You can exclude these complete directories with excludeRoots, e.g.
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-pmd-plugin</artifactId>
        <executions>
            <execution>
                <id>pmd-verify</id>
                <goals>
                    <goal>check</goal>
                    <goal>cpd-check</goal>
                </goals>
                <configuration>
                    <printFailingErrors>true</printFailingErrors>
                    <excludeRoots>
                        <excludeRoot>target/generated-sources/plugin</excludeRoot>
                    </excludeRoots>
                </configuration>
            </execution>
        </executions>
    </plugin>

There is also a file based exclude option.


text:
Q: OpenSSL + Self Signed Cert = OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed I've been trying to use an SSL (SAN) certificate for our internal Rails app.
I have created the certificate files using OpenSSL and have them working nicely with Apache:
<VirtualHost *:443>
  ServerName server-name
  RailsEnv uat

  DocumentRoot /var/www/server-name/current/public
  <Directory /var/www/server-name/current/public>
    AllowOverride All
    Options -MultiViews
  </Directory>

  SSLEngine on
  SSLCertificateFile /etc/apache2/ssl/hostname.cer
  SSLCertificateKeyFile /etc/apache2/ssl/hostname.key
</VirtualHost>

This works fine.
My issue is when using open-uri to communicate with some of the Rails controllers, i get the error message:
require "net/https"

uri = URI.parse("https://server-name.domain.com/controller.json?date=2013-09-03")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.start {
  http.request_get(uri.path) {|res|
    print res.body
  }
}

OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

I have seen many StackOverflow articles which suggest simply turning off SSL verification, using:
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

But I do not consider this a satisfactory approach. I have also seen articles which suggest i need to point open-uri to /etc/ssl/certs/ca-certificates.crt which is clearly for public certificates. So for my self signed certificate, i tried the following:
uri = URI.parse("https://server-name.domain.com/controller.json?date=2013-09-03")
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == "https"  # enable SSL/TLS
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  http.ca_file = "/etc/apache2/ssl/host-name.cer"
end
http.start {
  http.request_get(uri.path) {|res|
    print res.body
  }
}

Which worked.
My question is, how do i tell OpenSSL / OpenURI to always look in the /etc/apache2/ssl/ directory in addition to its current search path? I don't want to specify the path (which will change as the host name changes depending where we are working from) in each request i make.
Thanks

A: Extracted from here:

If there's already a CA bundle on disk that you want to use, point SSL_CERT_FILE or SSL_CERT_DIR environment variables to it, or set the ca_file= or ca_path= properties in Net::HTTP.

So all you have to do is this
ENV['SSL_CERT_FILE'] = "your certificate path"

and all should work.
You might find this resource useful:

*

*Who reads the value of ENV['SSL_CERT_FILE']?


text:
Q: Python pandas data frame issue. How can I conditionally insert rows and get the subtotal of the numeric column? Already solved it but any improvement?
With the change of Function, I want empty rows inserted below and the subtotal of Amount in the empty row below.
How can I imporve the code? A better or shorter way?
insertROW_df = pd.read_clipboard()
insertROW_df

insertROW_df['match'] = insertROW_df['Function'].eq(insertROW_df['Function'].shift(-1))
insertROW_df['insert_row_below?'] = insertROW_df['match'].apply(lambda x: 'Yes' if x == False else "No")
index_changed_row = insertROW_df.index[insertROW_df['match']==False]
type(insertROW_df)
line = pd.DataFrame({"Function": np.nan, "Budget": np.nan, "Amount":np.nan,"match":np.nan,"insert_row_below?":np.nan }, index=index_changed_row)
df = insertROW_df.append(line, ignore_index=False)
df = df.sort_index().reset_index(drop=True)

df['Total'] = df.groupby(['Function'])['Amount'].transform('sum')
df['Total'] = df['Total'].fillna(method="ffill")

df['Amount'] = df['Amount'].fillna(df['Total'])

print(df)
print(df[['Function', 'Budget', 'Amount']])
df.to_excel(r'Z:\Claiming FY17, 18, 19, 20, 21 & 22\November 2021\Pythonic approach\InsertBlankRows.xlsx', index=False, header=True)

DATAFRAME = pd.DataFrame({'Function':['AAA', 'AAA', 'AAA', 'AAA', 'BBB', 'BBB', 'BBB', 'CCC', 'CCC'],
                          'Budget': [550,550,550,680,550,550,550,860,860,],
                          'Amount': [14850,8640,2150,3210,5540,6660,2210,5555,5595,]
                          })


text:
Q: Update and delete for specific record I have written code to retrieve all the images from database for a specific city, and I want to be able to delete a specific image or to change the caption.
The problem is:
the code always work on the last image only!
I hope you guys will be able to help me with this problem.
Retrieve code:
<?php
$City_name=$_REQUEST['id'];
$Image_query = "SELECT * FROM image where City_name ='".$City_name."' ";
$Image_result = mysqli_query($dbcon,$Image_query);

echo "
";
while ($row = mysqli_fetch_array($Image_result))
{
    $image_id = $row['Image_id'];
    $image = $row['Image_url'];
    $Caption = $row['Caption'];

    echo "
";
    echo ""; ?> <img  src="<?php echo $image ; ?>"/>

        <input type="text" name="caption" value="<?php echo $Caption ;?>" />

 <input name="delete" type="submit" value="Delete picture" />

 <input name="Update_caption" type="submit" value="change caption" />
    <?php echo "	";
    echo ""; ?> <input class="input-image" type="hidden" name="id" value="<?php echo $image_id ;?>" />
    <?php echo "	";
} /* End of while loop */
echo "
";
echo"
";
?>

Update code :
if (isset($_POST['Update_caption'])) {
    $ImageID = $_POST['id'];
    $ImageCaption = $_POST['caption'];
    $sql = mysqli_query ($dbcon,"UPDATE `image` SET `Caption`='".$ImageCaption."' WHERE `Image_id`='".$ImageID."' ");
    if ($sql) {
        echo "done";
    } else { echo "error"; }
}

Delete code :
if (isset($_POST['delete'])) {
    $ImageID = $_POST['id'];
    $sql = mysqli_query ($dbcon,"DELETE FROM `image` where `Image_id` = '".$ImageID."' ");
    if ($sql) {
        echo "done";
    } else { echo "error"; }
}

A: $_POST['id'] (sql injection alert!) contains the contents of the input element that has a name attribute id.
You are echoing out your input elements in a loop, all with the same name so the last one will overwrite all the previous ones.
You should use an array like for example:
<input class="input-image" type="hidden" name="id[<?php echo $image_id ;?>]" value="<?php echo $image_id ;?>" />

So that your $_POST['id'] is an array containing all elements.
The same applies to other input elements like the caption.
An alternative, especially for your delete option, would be to wrap every image in its own form. But keep in mind that you will need valid html for that to work, you can't have a form that opens in a row element and spans different columns.
And note that you should really use a prepared statement to close the sql injection hole you have now.


text:
Q: How to load PhantomJS in Gradle automatically How can I configure my Gradle script to automatically download PhantomJS for my tests to use, so that I don't have to manually install it somewhere on my build server?
I see a phantomjs-maven-plugin that seems to do exactly what I want, but I don't know how to use it in Gradle.


text:
Q: Flattening hierarchical data with Linq in VB.NET Given the following structure:
Public Class Vendor
    Public Property Accounts As Account()
End Class

Public Class Account
    Public Property Services As Service()
End Class

Public Class Service
    Public Property Name As String
End Class

How do I get a flat list of all included Services in all accounts given a single Vendor? This is what I've tried so far:
vendor.Accounts.Select(Function(acct) acct.Services) 'Returns a collection of services collections

I know I'm just missing an obvious operator.

A: You're looking for SelectMany.
vendor.Accounts.SelectMany(Function(acct) acct.Services)

And if you want only the unique ones, slap a .Distinct() on the end.


text:
Q: Jenkins - Is it possible to store old builds in another directory? Say you have 2 artifacts.

*

*example.msi

*example2.msi

When example2 is built, I want the first build/artifact (example.msi) to be stored in another directory on disk so that I can only see example2.msi in our last successful artifacts.
Is this possible to do in Jenkins?

A: You can configure a post-build action to archive your old artifact. Here is a way to do it.


text:
Q: Open websites in new tabs but don't focus them (with python) I want to open 10 websites for reading in other tabs later. Therefore I don't want to focus them. The focus should remain on the actual tab. But when I use
url = "www.stackoverflow.com"
webbrowser.open(url, new=0)

the programm switches to the new tab.

A: From the documentation:
webbrowser.open(url, [new=0, [autoraise=True]])

If autoraise=True, the window is raised if possible. What you're looking for is to set autoraise=False so that the window stays in the background.
Note: that under many window managers this will occur regardless of the setting of this variable. Check what window manager you're calling. And accordingly modify this variable.


text:
Q: Interaction Trigger is not firing on Keyboard.LostKeyboardFocus My problem is the interaction triggers are not working on Keyboard.LostKeyboardFocus event. But when I do from code behind it works.
I have a Textbox with following code,
                      <TextBox
                        Text="{Binding PostRunPlateNotes, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                        Height="113"
                        Width="Auto"
                        ScrollViewer.HorizontalScrollBarVisibility="Auto"
                        ScrollViewer.VerticalScrollBarVisibility="Auto">
                        <i:Interaction.Triggers>
                            <i:EventTrigger
                                EventName="Keyboard.LostKeyboardFocus">
                                <i:InvokeCommandAction
                                    Command="{Binding SavePlateNotesCommand}"></i:InvokeCommandAction>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                    </TextBox>

And in the ViewModel here is the code,
#region CommandData
        private ICommand _savePlateNotesCommand;
        public ICommand SavePlateNotesCommand
        {
            get
            {
                return _savePlateNotesCommand ?? (_savePlateNotesCommand = new RelayCommand(OnSaveClick));
            }
            set
            {
                _savePlateNotesCommand = value;
                OnPropertyChanged("SavePlateNotesCommand");
            }
        }
        #endregion

In the code behind,
 public partial class RunInformationUserControl : UserControl, INotifyPropertyChanged
    {
        #region Accessors
        public RunInformationParameters RunInfoParams { get; set; }
        public RunInformationViewModel RunViewModel { get; set; }
        #endregion

        #region Constructor
        public RunInformationUserControl()
        {
            InitializeComponent();
            RunViewModel = null;
        }
        #endregion

        #region Methods
        public void SetParameters(RunInformationParameters parameters)
        {
            this.RunInfoParams = parameters;
            RunViewModel = new RunInformationViewModel(RunInfoParams);
            this.DataContext = RunViewModel;
        }

        #endregion

        #region EventHandlers
        private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (RunViewModel != null)
            {
                OnPropertyChanged("runInfoParams");
            }
        }

        #endregion

        #region INotifyPropertyChangedEvent
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion

    }

Problem is when I raise the keyboard lost focus from code behind it works. All the other properties are being bound correctly. But the Interaction Trigger is not working, please help.

A: Internally the EventTrigger will end up calling typeof(TextBox).GetEvent("Keyboard.LostKeyboardFocus") in its source code, and that will return null, because TextBox has no Keyboard.LostKeyboardFocus event. Since Keyboard.LostKeyboardFocus is an attached event, hence a WPF/XAML concept, GetEvent can't return it and the EventTrigger can't subscribe to it.
On the other hand TextBox inherits the LostKeyboardFocus from UIElement, so using that will work.


text:
Q: Golang MongoDB find, sort then insert to another collection I have a huge collection A with many documents.
Now I want to do a query to A, do some sorting, add some fields and save it to another collection B.
In SQL I can do everything in one query
INSERT INTO [DB].[B]
                   ([CorrelationID]
                   ,[RowNumber]
                   ,[SourceName]
                   ,SomeOther fields)
        SELECT
                    @CorrelationID
                    ,ROW_NUMBER() OVER(ORDER BY SequenceNumber ASC) AS RowNumber
                    ,[SourceName]
                    ,SomeOther fields
                FROM [DB].[A]
                WHERE  [SourceName] = @SourceName

I want do the same thing for mongoDB with Golang.
Right now I have to find with sort options first:
query := bson.D{{"source", sourceName},}

sort := bson.D{{"seq_num", 1},}

opts := options.Find()
opts.SetSort(sort)

collection := getCollectionA()
cursor, err := collection.Find(context.Background(), query, opts)

Then I decode the data from the cursor, add fields and then save them to a slice. And then insert back with:
collection = getCollectionB()
result, err := collection.InsertMany(context.Background(), dataSlice)

Which is not ideal, I am wondering if it possible to do such logic within mongoDB i.e using one query.


text:
Q: How to add conditions in Parameters section in AWS CloudFormation? So what I am trying to do is, I defined a Parameter called EnvType with allowed values test or production.
What should happen is when the user selects one of these environments test or production, lets say test
then he should be able to select another parameter called InstanceType in which allowed values would be all the 't' type instances in the drop-down list while creating the stack.
If the user selects production as the EnvType then the allowed values under the same parameter called InstanceType must be all instances types except 't' type for eg ('m' type).
And the same must apply for rds as well. Let's say user chooses EnvType as test then allowed values under parameter called DBInstanceType must be 'db.t' type instances otherwise 'db.r' type instances.
Parameters
Parameters:

  EnvType:
    Default: test
    Type: String
    AllowedValues:
      - production
      - test

  InstanceType:
    Type: String
    AllowedValues: !FindInMap
      - InstanceTypeMap
      - !Ref EnvType
      - instanceType

  DBInstanceType:
    Type: String
    AllowedValues: !FindInMap
      - InstanceTypeMap
      - !Ref EnvType
      - dbinstanceType

Mapping
    InstanceTypeMap:
      production:
        instanceType: [m1.small, m1.medium, m1.large, m1.xlarge, m2.xlarge, m2.2xlarge, m2.4xlarge]
        dbinstancetype: [db.r5.large, db.r5.xlarge]
      test:
        instanceType: [t1.micro, t2.nano, t2.micro, t2.small, t2.medium, t2.large]
        dbinstancetype: [db.t2.small, db.t2.medium, db.t3.small]

Resources
Resources:
  WebServer:
    Type: 'AWS::EC2::Instance'
    Properties:
      InstanceType: !Ref InstanceType

  DBInstance:
    Type: AWS::RDS::DBInstance
    Properties:
      DBInstanceClass: !FindInMap
        - MyEnvironmentMap
        - !Ref EnvType
        - dbinstanceType

Well i know the template is not valid, and is prone to errors in allowed values in InstanceType and DBInstanceType parameters but i am seeking an alternative of doing this.
Please help!!

A: Simply, such functionality is not possible in CloudFormation (CFN). Sadly, there is no alternative in CFN for that. You would have to develop a custom solution for deployment of such templates.