text:
Q: SSIS XMLSource only seeing null values in XML variable I have a Data Flow task with an XMLSource that references an XML Variable. The DataFlow task does recognize that there are x number of rows in the variable, but it only sees null values in every row:
The xml variable value:
<?xml version="1.0" encoding="utf-8"?>
<words>
   <word>butter</word>
   <word>crispy</word>
</words>

I used this source to generate the XSD within the XMLSource Editor - here is the auto-generated XSD:
<?xml version="1.0"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="words">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="0" maxOccurs="unbounded" name="word" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

The package compiles, executes, and processes all the rows in my XML, but only sees nulls rather than the actual text strings... Here is a shot of the DataViewer displaying 2 rows after reading the XML variable:

A: I discovered a way to get the values to populate... I'll post it here without giving myself points, in case anyone else encounters the same problem. This is just a "how to fix", but I'll give credit to anyone who can explain the "deeper whys".
Essentially, the XML needed to be wrapped in another root node:
<?xml version="1.0" encoding="utf-8"?>
<datarows>
   <words>
      <word>bacon</word>
      <word>roasted</word>
      <word>pork</word>
      <word>edamame</word>
   </words>
</datarows>

Even though the original XML I used was valid, SSIS wanted it to be wrapped in an additional root node, which I named datarows. Once I did that the package recognized the word values and completed successfully.

The associated schema:
<?xml version="1.0"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="datarows">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="0" maxOccurs="1" name="words">
          <xs:complexType>
            <xs:sequence>
              <xs:element minOccurs="0" maxOccurs="unbounded" name="word" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

A: I too had the same problem,. I was trying to consume a web service and import the output xml into a table in sql 2008.
The issue is really with the namespace that gets generated in the output xml by the webservice. The trick I have used was
1. Stored the output of the web service in a package level variable
2. Add a 'script task', to replace the unwanted name space.
3. Then used 'XMl Source Task' to import the data into a table.
-Kris...


text:
Q: Searching & sorting with AJAX pagination in MVC4 I am developing MVC4 application with Searching, Paging and Sorting. Everything works fine with normal view.
Now I am converting same application using Ajax & Partial View.
How can I pass my search & sort parameter through Paging control residing on partial View. Now, I am able to load filtered data in partial view but moving to next page, lost my search parameters and loads all records ignoring search filters.
My Paging Control in _PartialView.cshtml
@Html.PagedListPager(Model,
                        page => Url.Action("AjaxMethod",
                            new
                            {
                                page,
                                searchByUserName = Request.QueryString["searchByUserName"],
                                searchByReaderName = Request.QueryString["searchByReaderName"],
                                searchByReaderType = Request.QueryString["searchByReaderType"],
                                searchByUploadDate = Request.QueryString["searchByUploadDate"],
                                sortBy = Request.QueryString["sortBy"]
                            }),
                        //new PagedListRenderOptions.() { Display = PagedListDisplayMode.IfNeeded, DisplayPageCountAndCurrentLocation = true }
                        PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing( new AjaxOptions(){ HttpMethod = "GET", UpdateTargetId = "divData"})
                        )

Please suggest, what I am missing....

A: I came to know what I m missing, Partial View doesn't got Request.QueryString values thats why paging control lost search parameters and loads all records. So I modified Pager control in _PartialView.cshtml as follows :
@Html.PagedListPager(Model,
                        page => Url.Action("AjaxMethod",
                            new
                            {
                                page,
                                searchByUserName = ViewBag.searchByUserName, // Request.QueryString["searchByUserName"],
                                searchByReaderName = ViewBag.searchByReaderName, // Request.QueryString["searchByReaderName"],
                                searchByReaderType = ViewBag.searchByReaderType, // Request.QueryString["searchByReaderType"],
                                searchByUploadDate = ViewBag.searchByUploadDate, // Request.QueryString["searchByUploadDate"],
                                sortBy = ViewBag.sortBy // Request.QueryString["sortBy"]
                            }),
                        PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions()
                        { HttpMethod = "GET", UpdateTargetId = "divData", LoadingElementId="divloading" })
                        )
These ViewBag objects initialized in controllers action method.
Anyone having better solution than this for the above problem. Please suggest.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inheritance + RPC GWT It seems that I don't understand inheritance.
I have these classes : PicaAsset, VideoAsset that inherit from a class names Assets.
This is the Assets class declaration :
public class Assets {
protected int book=0;
protected int fromChapter=0;
protected int toChapter=0;
protected int fromVerse=0;
protected int toVerse=0;
protected String creator=null;
protected String discription=null;
protected String source=null;
protected String title=null;
protected String duration=null;
protected String url=null;

public Assets(int book, int fromChapter, int toChapter, int fromVerse,
        int toVerse, String creator, String discription, String source,
        String title, String duration, String url) {

    this.book = book;
    this.fromChapter = fromChapter;
    this.toChapter = toChapter;
    this.fromVerse = fromVerse;
    this.toVerse = toVerse;
    this.creator = creator;
    this.discription = discription;
    this.source = source;
    this.title = title;
    this.duration = duration;
    this.url = url;
}

public Assets() {
}

public int getBook() {
    return book;
}

public void setBook(int book) {
    this.book = book;
}
public int getFromChapter() {
    return fromChapter;
}
public void setFromChapter(int fromChapter) {
    this.fromChapter = fromChapter;
}
public int getToChapter() {
    return toChapter;
}
public void setToChapter(int toChapter) {
    this.toChapter = toChapter;
}
public int getFromVerse() {
    return fromVerse;
}
public void setFromVerse(int fromVerse) {
    this.fromVerse = fromVerse;
}
public int getToVerse() {
    return toVerse;
}
public void setToVerse(int toVerse) {
    this.toVerse = toVerse;
}
public String getCreator() {
    return creator;
}
public void setCreator(String creator) {
    this.creator = creator;
}
public String getDiscription() {
    return discription;
}
public void setDiscription(String discription) {
    this.discription = discription;
}
public String getSource() {
    return source;
}
public void setSource(String source) {
    this.source = source;
}
public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getDuration() {
    return duration;
}
public void setDuration(String duration) {
    this.duration = duration;
}
public String getUrl() {
    return url;
}
public void setUrl(String url) {
    this.url = url;
}

PicAsset :
public class PicAsset extends Assets implements IsSerializable {

  private int picId=0;

  public PicAsset(){
  }

  public PicAsset(int picId, int book, int fromChapter, int toChapter,
        int fromVerse, int toVerse, String creator, String discription,
        String source, String title, String duration, String url) {
    super(  book,  fromChapter,  toChapter,
             fromVerse,  toVerse, creator,  discription,
            source,  title,  duration,  url);
    this.picId = picId;
  }

  public int getIdpic() {
    return picId;
  }
  public void setIdpic(int idpic) {
    this.picId = idpic;
  }
}

Now I use an RPC call to use methods declared in the server side to get info from my datbase, as you can see the method return a List of PicAsset , List.
 rpcService.getPicture((books.getSelectedIndex()+1), (chapters.getSelectedIndex()+1), new AsyncCallback<List<PicAsset>>(){
                    public void onFailure(Throwable caught) {
                        Window.alert("Can't connect to database" + books.getSelectedIndex() + chapters.getSelectedIndex());
                    }

                    public void onSuccess(List<PicAsset> result) {
                        int listSize = result.size();
                        int i;
                        int flag = 0;

                        assetPicPanel.clear();

                          Label frameTitle = new Label("Pictures");
                                for(i=0;i<listSize;i++)
                                {
                                    if(flag == 0)
                                    {
                                        assetPicPanel.add(frameTitle);
                                        flag = 1;
                                    }

                                    HorizontalPanel vPanelPic = new HorizontalPanel();

                                    System.out.print("heeeeey" +" " + result.get(i).getFromChapter());
                                    Grid g = result.get(i).AssetGrid(result.get(i));

                                    vPanelPic.add(g);
                                    assetPicPanel.add(vPanelPic);
                                }
                    }
                });

Now when I print the ..get().getFromChapter() on the server side it brings the right values.
But when I print the values that have been returned to the RPC call I get the default constructor values... and not what have to be sent back.
Here also the getPicture implementation on the server side :
public List<PicAsset> getPicture(int book, int chapter) throws Exception

 {

    System.out.print("getPicture ok " + book +"," + chapter);
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet result = null;
    List<PicAsset> relevantAssets = new ArrayList<PicAsset>();
    PicAsset relAsset;

    try {
        conn = getConnection();
        pstmt = conn.prepareStatement("SELECT * FROM picasset WHERE book = ? AND fromChapter <= ? AND toChapter >= ?");

        //System.out.print("connection" + conn);
        pstmt.setInt(1, book);
        pstmt.setInt(2, chapter);
        pstmt.setInt(3, chapter);

        result = pstmt.executeQuery();

      //  System.out.print(result);
        while (result.next()) {

            //System.out.print("in while");
            relAsset = new PicAsset(result.getInt("picId"),result.getInt("book"), result.getInt("fromChapter"), result.getInt("toChapter"),result.getInt("fromVerse"),result.getInt("toVerse"),result.getString("creator"),result.getString("discription"),result.getString("source"),result.getString("title"),result.getString("duration"),result.getString("url"));
            relevantAssets.add(relAsset);

        }
    }

        catch (SQLException sqle)
        {
            sqle.printStackTrace();
        }
        finally
        {
            // Cleanup
            result.close();
            pstmt.close();
            conn.close();
        }

    System.out.print("In MySql get Chapter  " + relevantAssets.get(0).getFromChapter() + " " + relevantAssets.get(0).getIdpic());
    return relevantAssets;
}

A: Within GWT RPC it would be much better to use raw arrays rather than collection interfaces - return from your method PicAsset[] instead of List. This will allow you (a) solve your problem and (b) escape unnecessary classes to be compiled into client code.
See "Raw Types" section at gwtproject.org


text:
Q: eBay API reviseItem call using Java SDK I have two ItemType objects: oldItem and newItem. I would like to Revise the oldItem to reflected changes in the newItem. To do this I assume after reading the documentation that we need to provide a list of removed/deleted fields.
Can anyone suggest an efficient way to go through all the fields (that can be changed) in the newItem, compare it to the oldItem and then actually come up with a string array of fields that was removed in the revision. And perhaps return and empty array of strings if no field was deleted.
PS. Let me know if my initial assumption about providing eBay with a list of deleted fields is incorrect. If that is incorrect then I am gonna have a much easier time revising items through the API.


text:
Q: How to return Datetimeoffset in SQL view using at time zone is it possible to return a value from a table that is of type datetime as datetimeoffset in a view using AT TIME ZONE?
When I try this with

CREATE VIEW TESTVIEW AS
SELECT        appointment_start AT TIME ZONE 'central european standard time' AS x
FROM            dbo.Appointments

the result is as expected, but when I open the view in SQL Management Studio, I get the message 'Unable to parse query text.'
The same when I try something like

SELECT TODATETIMEOFFSET(appointment_start, DATEPART(tz, appointment_start AT TIME ZONE 'central european standard time')) as y
FROM            dbo.Appointments

How do I get the datetime value converted to a datetimeoffset using AT TIME ZONE in an SQL view?
EDIT:
When I additionally select another column from the table, I also get the expected result, but the SQL Management Studio complains

SELECT
id, appointment_start AT TIME ZONE 'central european standard time' AS x
FROM dbo.Appointments

Error in SELECT clause: expression near 'TIME'.
Missing FROM clause.
Error in list of function arguments: 'AT' not recognized.
Unable to parse query text.

Thanks a lot

A: For whom it may concern:
Solved it by using an SQL function.
Maybe not the most elegant way but it seems to work.
CREATE FUNCTION [dbo].[TODATETIMEOFFSETINTIMEZONE]
(
    @Date AS DateTime,
    @Timezone as NVARCHAR(100)
)
RETURNS DateTimeoffset
AS
BEGIN
    DECLARE @NewDate As DateTimeoffset
    SELECT @NewDate = @Date AT TIME ZONE @Timezone
    RETURN @NewDate
END
GO

And in the SQL View
SELECT
    id,
    TODATETIMEOFFSETINTIMEZONE(appointment_start, N'W. Europe Standard Time') AS appointment_start
FROM dbo.Appointments


text:
Q: The fastest possible way to catch the screen? Any Language I need to take print-screens of a Windows application very very fast to make a video out of it... I have been using C# all the way, but I'm open to any language in which this process may be faster.
I have used many techniques:

*

*.net functions: Bitmap.CopyFromScreen()

*GDI

*Direct3d/DirectX

The fastest I've got was using GDI and still I get less than 10 fotograms per second. I would need a bit more than that, at least 20 or 30...
It seems very strange to me that such a simple operation is so demanding. And it looks as if using a faster cpu doesn't change the situation.
What can I do? Is it possible to directly capture the drawing of an application using gdi or something? Or maybe even lower-level functions to catch the info being thrown to the graphics card?
Any light on this issue would be pretty much appreciated.
Thanks a lot

A: A lot of programs use a driver and allows your application to hook into the lower level display routines. I'm not exactly sure how this is done, but it is possible.
Here is a starting point on writing Windows driver. http://msdn.microsoft.com/en-us/library/ms809956.aspx
Here is something I just found via Google:
http://www.hmelyoff.com/index.php?section=17

A: You probably want to use something like Camtasia. Depends on why you're making the video.
I use a rewritten version of Jeff's User-Friendly Exception Handling, and he uses BitBlt from GDI to capture screenshots. Seems fast enough to me, but I haven't benchmarked it, and we just use it for one-at-a-time shots when there's an unhandled exception thrown.
#region Win32 API screenshot calls

// Win32 API calls necessary to support screen capture
[DllImport("gdi32", EntryPoint = "BitBlt", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int BitBlt(int hDestDC, int x, int y, int nWidth, int nHeight, int hSrcDC, int xSrc,
                                 int ySrc, int dwRop);

[DllImport("user32", EntryPoint = "GetDC", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int GetDC(int hwnd);

[DllImport("user32", EntryPoint = "ReleaseDC", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int ReleaseDC(int hwnd, int hdc);

#endregion

private static ImageFormat screenshotImageFormat = ImageFormat.Png;

/// <summary>
/// Takes a screenshot of the desktop and saves to filename and format specified
/// </summary>
/// <param name="fileName"></param>
private static void TakeScreenshotPrivate(string fileName)
{
    Rectangle r = Screen.PrimaryScreen.Bounds;

    using (Bitmap bitmap = new Bitmap(r.Right, r.Bottom))
    {
        const int SRCCOPY = 13369376;

        using (Graphics g = Graphics.FromImage(bitmap))
        {
            // Get a device context to the windows desktop and our destination  bitmaps
            int hdcSrc = GetDC(0);
            IntPtr hdcDest = g.GetHdc();

            // Copy what is on the desktop to the bitmap
            BitBlt(hdcDest.ToInt32(), 0, 0, r.Right, r.Bottom, hdcSrc, 0, 0, SRCCOPY);

            // Release device contexts
            g.ReleaseHdc(hdcDest);
            ReleaseDC(0, hdcSrc);

            string formatExtension = screenshotImageFormat.ToString().ToLower();
            string expectedExtension = string.Format(".{0}", formatExtension);

            if (Path.GetExtension(fileName) != expectedExtension)
            {
                fileName += expectedExtension;
            }

            switch (formatExtension)
            {
                case "jpeg":
                    BitmapToJPEG(bitmap, fileName, 80);
                    break;
                default:
                    bitmap.Save(fileName, screenshotImageFormat);
                    break;
            }

            // Save the complete path/filename of the screenshot for possible later use
            ScreenshotFullPath = fileName;
        }
    }
}

/// <summary>
/// Save bitmap object to JPEG of specified quality level
/// </summary>
/// <param name="bitmap"></param>
/// <param name="fileName"></param>
/// <param name="compression"></param>
private static void BitmapToJPEG(Image bitmap, string fileName, long compression)
{
    EncoderParameters encoderParameters = new EncoderParameters(1);
    ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");

    encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, compression);
    bitmap.Save(fileName, codecInfo, encoderParameters);
}


text:
Q: How does initializing an integer as "a = {1,}" compile? I found this weird syntax:
int a = {1,};

And it works in all the compilers I've tried. How does it compile?
EDIT: I thought that scalar initializers can only have one element in it, spawning my question. Sorry for all the trouble.

A: As stated by Matt McNab in comments, the syntax of a braced initialized list is the same regardless of whether you are using it to initialize a scalar or anything else.
C++11 §5.17 states

A braced-init-list may appear on the right-hand side of

*

*an assignment to a scalar, in which case the initializer list shall have at most a single element.

The definition of braced-init-list is (from §8.5):
braced-init-list:
  { initializer-list ,opt }
  { }
where the 'opt' means that the trailing comma is optional.


text:
Q: Circles and squares and polygon
If i replace the square with circle, i can very easily find the area of circle and get some approximation for the area of the square.
Even the square is doable, but i was thinking that can we find the area of the regular polygon which is made to sit in place of the square ?
Since, i don't have the answer to that problem, i don't know if approximating that with circle would work.
Would a regular polygon of arbitrarily large number of sides fit into that space and can we find its area (i know only upto undergrad. maths)?
I am trying to solve it by coordinate geometry but i am not getting as many equations as many variables i have.
$a^2$+b(b-7)=49=$d^2$+c(c-7)=($e^2$+$f^2$)=($g^2$+$h^2$)=(f-b)(g-c)49/(e-a)(h-d)=$(f-b)^2$+$(e-a)^2$+49-$(g-c)^2$-$(h-d)^2$=$(a-c)^2$+$(b-d)^2$+49-$(e-g)^2$-$(f-h)^2$
Thank you.

A: I would argue that even with the square it is a very tough problem. At some point, you have to solve either quartic equation or the intersecting ellipses problem (which is again boils down to quartic equation). And the final answer is the smallest real root of $64x^4-144x^3+177x^2-100x+4=0$. You can express the root with radicals, but it's nasty as hell.
Good news is the problem with $n=6$ or $n=8$ isn't harder, since you get the same quadratic equation just with other coefficients.

True problem will appear at $n=10$, since the inscribed dodecagon touch the inner circles with its sides rather than vertices.

Although the calculation of this scenario isn't harder per se, it makes the general formula totally uncomprehensible, since you need to determine first whether the n-gon touches inner circles with sides or vertices and which sides vertices and then use the corresponding equation.
This problem is not that interesting to go through so much hassle.

A: A solution for a regular polygon with one edge a chord of the large circle and the vertices of the opposite edge on the smaller circles
Consider coordinates with $O$ as origin and the line of symmetry as the $x$-axis. Let the edge length of the regular polygon be  $2L$ and let the distance between opposite edges be $D$.

$D$ is $2L$ for a square, $2\sqrt 3L$ for a hexagon and $(2+2\sqrt 2)L$ for an octagon.
The large circle has equation $x^2+y^2=49$.
The upper small circle has equation $x^2-\frac{7}{\sqrt 2}x+y^2-\frac{7}{\sqrt 2}y=0$.

The line $y=L$ intersects the upper circle at $(x,L)$ and the large circle at $(x+D,L)$. Eliminating $x$ from the two equations for these points gives us a polynomial equation for $L$ in terms of $D$.
(1) $x^2+2Dx+D^2+L^2=49$.
(2) $x^2-\frac{7}{\sqrt 2}x+L^2-\frac{7}{\sqrt 2}L=0$.
First eliminate $x^2$.
$(7+2\sqrt 2 D)x=49\sqrt 2-\sqrt 2 D^2-7L$
Substituting into Equation 1 then gives us the required  polynomial. We shall now do this for the square.
$(7+4\sqrt 2 L)x=49\sqrt 2-7L-4\sqrt 2 L^2$
$(7+4\sqrt 2 L)(x+D)=4\sqrt 2 L^2+7L+49\sqrt 2$
$(4\sqrt 2 L^2+7L+49\sqrt 2)^2=(49-L^2)(4\sqrt 2 L+7)^2$

$64L^4+112\sqrt 2 L^3-686L^2-2058\sqrt 2 L+2401=0$

The relevant solution is $L=0.7274$ and so the length of a side is approximately $1.455$.

A: The intersection of the two small circles is 7/2,7/2.
With the transformation for the equation of circles at the point of intersection, we have
(x-7/2)^2+(y-7/2)^2=7^2  (1) big quadrant
(x-7/2)^2+y^2=(7/2)^2    (2) semicircle with horizontal diameter
x^2+(y-7/2)^2=(7/2)^2    (3) semicircle with vertical diameter
Now, the square has sides inclined at 45 degrees with some intercept.
Let c be the intercept.
Equation of straight line with slope as 1, and the intercept c is given by
y=x+c which is away from the line passing through the origin with unit slope equal to c/sqrt(2).
With points connecting on either side of the line through the origin, the side of the square is csqrt(2).
We need to solve for the intersesction of the straight line y=x+c with the big quadrant.
Followed by the evaluation of the intersection point of the straight line y=x+c and semicircle with vertical diameter.
It is a quadratic equation in each case.
Considering the positive values, we can equate the distance to csqrt(2) to get the dimensions of the expected square.


text:
Q: How is Argo resourceDuration for CPU and memory calculated I have an argo workflow with a single step where the following resources defined:
        resources:
          limits:
            cpu: "6"
          requests:
            cpu: "3"
            memory: 120Mi

After the workflow is executed and has completed successfully, I retrieved the run specifications, where the time duration for each pod and resource usage for CPU and memory  can be found:
status:
  artifactRepositoryRef:
    artifactRepository:
      archiveLogs: true
    configMap: artifact-repositories
    key: default-v1
    namespace: argo
  conditions:
  - status: "False"
    type: PodRunning
  - status: "True"
    type: Completed
  finishedAt: "2022-12-18T11:13:25Z"
  nodes:
    test-cpu-usageszprm:
      children:
      - test-cpu-usageszprm-4131026553
      displayName: test-cpu-usageszprm
      finishedAt: "2022-12-18T11:13:25Z"
      id: test-cpu-usageszprm
      name: test-cpu-usageszprm
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: main
      templateScope: local/test-cpu-usageszprm
      type: Retry
    test-cpu-usageszprm-1944147306:
      boundaryID: test-cpu-usageszprm-4131026553
      children:
      - test-cpu-usageszprm-2680509841
      displayName: step1
      finishedAt: "2022-12-18T11:13:25Z"
      id: test-cpu-usageszprm-1944147306
      name: test-cpu-usageszprm(0).step1
      outputs:
        artifacts:
        - name: main-logs
          s3:
            key: test-cpu-usageszprm/test-cpu-usageszprm-2680509841/main.log
        exitCode: "0"
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: step1
      templateScope: local/test-cpu-usageszprm
      type: Retry
    test-cpu-usageszprm-2680509841:
      boundaryID: test-cpu-usageszprm-4131026553
      displayName: step1(0)
      finishedAt: "2022-12-18T11:13:15Z"
      hostNodeName: center03-blade06
      id: test-cpu-usageszprm-2680509841
      name: test-cpu-usageszprm(0).step1(0)
      outputs:
        artifacts:
        - name: main-logs
          s3:
            key: test-cpu-usageszprm/test-cpu-usageszprm-2680509841/main.log
        exitCode: "0"
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: step1
      templateScope: local/test-cpu-usageszprm
      type: Pod
    test-cpu-usageszprm-4131026553:
      children:
      - test-cpu-usageszprm-1944147306
      displayName: test-cpu-usageszprm(0)
      finishedAt: "2022-12-18T11:13:25Z"
      id: test-cpu-usageszprm-4131026553
      name: test-cpu-usageszprm(0)
      outboundNodes:
      - test-cpu-usageszprm-2680509841
      phase: Succeeded
      progress: 1/1
      resourcesDuration:
        cpu: 173
        memory: 79
      startedAt: "2022-12-18T11:12:30Z"
      templateName: main
      templateScope: local/test-cpu-usageszprm
      type: DAG
  phase: Succeeded
  progress: 1/1
  resourcesDuration:
    cpu: 173
    memory: 79
  startedAt: "2022-12-18T11:12:30Z"

Knowing that resources for CPU and memory are set for each pod, I would like to know how resourceDuration CPU (173) and memory (79) are calculated.
I found this document (https://argoproj.github.io/argo-workflows/resource-duration/#example) which describes the calculation for the resourceDuration for CPU and memory however I am not able to get 173, and 79 for cpu and memory reosurce duration respectively based on the pods time duration and resource limits and requests.
Does anyone know how resourceDuration is calculated?


text:
Q: What is the antonym for ticklish?
I am very ticklish

What is the antonym for ticklish?
Is it "I am not ticklish"?

A: Well, the adjective ticklish is used for two reasons. When referred to a person, it means that the person is too sensitive when they are tickled and when referred to a problem or situation, it denotes difficulties.
You clarified that the context is human.
My medical brain has an answer to this:

hyposensitive -Less than the normal ability to respond to stimuli.

OxfordDictionaries too have this definition.

Hey, don't touch me. I'm very ticklish ~ Oh yeah? Try hard on me, I'm hyposensitive

We often describe a patient with less response to the stimuli quite opposite to someone who is ticklish.
[I think the words with prefix hypo- and hyper- are no longer medical terms as they are used broadly by normal public].

A: The idiomatic way to say that one is not ticklish: I'm not ticklish.
Words ending in the suffix -ish (e.g. skittish, bookish, snobbish, boorish, roguish, etc).
express a tendency to have, to some degree, the trait found in the word's stem; as tendencies, these words don't have antonyms.

A: Thick-skinned is the antonym I found for ticklish.


text:
Q: Abort a procedure with flag, return, exception, goto or break I've got a code which parses a file and breaks up if invalid conditions are met.
The code is in C++ and goes like that:
bool ok = true;
if (task1() == false)
    ok = false;
if (ok && (task2() == false))
    ok = false;
if (ok && (task3() == false))
    ok = false;
cleanup();
return ok;

Now I'm looking into cleaner alternatives to get the same result.
As far as I see there are:

*

*using a flag and many conditions as in the code above

*

*There are many redundant tests for the same information.
The effect on the runtime will be negligible and probably
entirely removed by the compiler but it still makes the code
more complicated.

*you could wrap the tasks in a method and return from it

*

*This looks much cleaner but you spread your code in multiple
functions. Depending on your context there might be a long
list of parameters. Further more many it is also not the
best to spread returns all over the method.

*you could use exceptions

*

*This will give some quite descriptive code but it is also
heavy as you just want to skip some calls. Further more it
might not be exactly an exceptional case.

*you could break from a do while(0) or another loop
or switch statement.

*

*Well, it is not really meant for such a task. Other than
that you get a lightweight and compact implementation with
and descriptive keyword.

*using a goto statement

*

*That seems to combine most advantages. Still, I am unsure.
Everywhere people are stating, that breaking multiple loops
is the only remaining sensible use for this keyword.

I didn't find a discussion about such a code. Which implementations are generally suggested? Is this case mentioned in any C++ coding guidelines? Are there other practical options?
Edit: My goal does not seem to be clear. I'm looking for the best way how to break from a procedure and not for a way to call three methods. The described problem is more of an example. I'm interested in arguments for and against different syntaxes to do this.
In the code of object each method is a placeholder for a couple of code lines which are similar but differ from each other. There are maybe 50 code blocks. An old code block was looking like the following (I know that there are more things to optimize than just the objective of this question):
if (ok)
{
    keyString = "speed";
    tmpVal = configuration->getValue(section, keyString, -1);
    if (tmpVal != -1)
    {
        m_speed = tmpVal;
        if (m_speed < m_minSpeed)
            m_minSpeed = m_speed;
        m_needSpeed = true;
    }
    else if (m_needSpeed)
    {
        ok = false;
        keyErr = keyString;
    }
}

A: Assuming that all of these functions return a bool, it looks to me like the shown code is logically identical to:
bool ok= task1() && task2() && task3();

cleanup();

return ok;


text:
Q: TextAngular tab to leave field I am using http://textangular.com/ but I need the tab to quickly move to the next field. Currently when the user presses tab it stays in the textangular field. How can I make the cursor move to the next field when tab is pressed?
See punker here
.

A: In the minified or full version of text angular js file, search for 'TabKey' and remove that entire line.
https://github.com/fraywing/textAngular/issues/939


text:
Q: Nginx cache seems to make chrome fail I'm running a MeteorJs app on a OVH vps, behind a Nginx proxy with a Let's encrypt SSL Cert.
Previously, I was using heroku to host my app.
I'm now facing a problem : on chrome, I "often" get that error message in the console logs : Uncaught SyntaxError: Unexpected end of input
I've browsed the web and seen that it's related to the cache, many SO questions says that I have to remove the cache.
The problem is that doing so (with ctrl + f5 or from the chrome tools panel) sometime works but it seems very random, and simple refreshes will eventually bring back the error.
I've modified my Nginx .conf to add several lines I've seen while browsing for a solution :
server_tokens off; # for security-by-obscurity: stop displaying nginx version

# this section is needed to proxy web-socket connections
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

# HTTP
server {
    listen 80 default_server; # if this is not a default server, remove "default_server"
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html; # root is irrelevant
    index index.html index.htm; # this is also irrelevant

    server_name www.talkalang.com talkalang.com; # the domain on which we want to host the application. Since we set "default_server" previously, nginx will answer all hosts anyway.

    # redirect non-SSL to SSL
    location / {
        rewrite     ^ https://$server_name$request_uri? permanent;
    }
}

# HTTPS server
server {
    listen 443 ssl; # we enable SPDY here
    server_name www.talkalang.com talkalang.com; # this domain must match Common Name (CN) in the SSL certificate

    root html; # irrelevant
    index index.html; # irrelevant

    ssl_certificate /etc/letsencrypt/live/talkalang.com/fullchain.pem; # full path to SSL certificate and CA certificate concatenated together
    ssl_certificate_key /etc/letsencrypt/live/talkalang.com/privkey.pem; # full path to SSL key

    # performance enhancement for SSL
    ssl_stapling on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 5m;

    # safety enhancement to SSL: make sure we actually use a safe cipher
    ssl_prefer_server_ciphers on;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-$

    # config to enable HSTS(HTTP Strict Transport Security) https://developer.mozilla.org/en-US/docs/Security/HTTP_Strict_Transport_Security
    # to avoid ssl stripping https://en.wikipedia.org/wiki/SSL_stripping#SSL_stripping
    add_header Strict-Transport-Security "max-age=31536000;";
        # If your application is not compatible with IE <= 10, this will redirect visitors to a page advising a browser update
    # This works because IE 11 does not present itself as MSIE anymore
    if ($http_user_agent ~ "MSIE" ) {
        return 303 https://browser-update.org/update.html;
    }

    # pass all requests to Meteor
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade; # allow websockets
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header X-Forwarded-For $remote_addr; # preserve client IP
        proxy_set_header X-Forwarded-Proto https;

        # this setting allows the browser to cache the application in a way compatible with Meteor
        # on every applicaiton update the name of CSS and JS file is different, so they can be cache infinitely (here: 30 days)
        # the root path (/) MUST NOT be cached
        if ($uri != '/') {
            #expires 30d;
        }
        add_header Cache-Control no-cache;
        proxy_cache off;
        expires off;
    }
}

Here are the lines I added :
add_header Cache-Control no-cache;
proxy_cache off;
expires off;

And it still doesn't solve the problem. I'm all out of ideas, I'm really not familiar with admin sys and ubuntu, specially nginx.
The problem is that the app is used by hundred of non-technical people every day, and I can't just ask them to spam ctrl+f5 until it works.
Has anyone an idea ? Any help would be very appreciated.
Thanks you.


text:
Q: Check sum in list comprehension Is it possible to also check the sum of the digits in the list in the same comprehension and make another except if the sum exceeds 50?
        k = input("input digits separated by spaces:")
        try:
            [int(i) for i in k.split()]
        except ValueError:
            print("input only digits")

The main thing is not to structure it with two except blocks, but to keep it as simple as possible make sure that the sum of the list is not more than 50.

A:     k = input("Input integers separated by spaces:")
    try:
        the_list = [int(i) for i in k.split()]
        if sum(the_list) > 50:
            raise ValueError("The user's numbers' summation is too large.")
    except ValueError:
        print("Input only integers separated by spaces with sum not greater than 50.")

A: assert sum([int(i) for i in k.split()]) <= 50 and add an except
AssertionError would do the trick:
k = input("input digits separated by spaces: ")
try:
    assert sum([int(i) for i in k.split()]) <= 50
except ValueError:
    print "input only digits"
except AssertionError:
    print "Sum of digits is grater than 50"

Though I must say that I find this a rather poor design...


text:
Q: TypeError: '<' not supported between instances of 'int' and 'str' when calling pd.cut() I want to create a function to classify each person in an age group with the following groupings: 0-10, 11-20, 21-30, 31-40, 41-50, 51-60, 60+. Add a new column in the DataFrame that identifies each person's age group. Then, count the number of survivalists in each age group
I got
TypeError: '<' not supported between instances of 'int' and 'str'
How fix that ? I didn't have '<' on my program
titanic_df['AgeGroup'] = 0

age_groups = ["0-10", "11-20", "21-30", "31-40", "41-50", "51-60", "61-70", "71-80"] # age groups
bins = [18, 30, 40, 50, 60, 70, 120]

titanic_df['AgeGroup'] = pd.cut(titanic_df["Age"],bins,labels = age_groups)

def age_group_summary(titanic_df, age_groups):

age_survival = titanic_df[['AgeGroup', 'Survived']].groupby('AgeGroup').agg(['mean','count','sum'])

  age_survival = age_survival.reindex(age_groups)

    age_survival.columns = age_survival.columns.droplevel()
    age_survival.columns = ['Survival rate', 'Total', 'Survived']

    age_survival['Died'] = age_survival['Total'] - age_survival['Survived']

    return age_survival

age_survival = age_group_summary(titanic_df, age_groups)

age_survival

I got :
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_28352/83336182.py in <module>
      5 bins = [18, 30, 40, 50, 60, 70, 120]
      6
----> 7 titanic_df['AgeGroup'] = pd.cut(titanic_df["Age"],bins,labels = age_groups)
      8
      9 def age_group_summary(titanic_df, age_groups):

~\anaconda3\lib\site-packages\pandas\core\reshape\tile.py in cut(x, bins, right, labels, retbins, precision, include_lowest, duplicates, ordered)
    285             raise ValueError("bins must increase monotonically.")
    286
--> 287     fac, bins = _bins_to_cuts(
    288         x,
    289         bins,

~\anaconda3\lib\site-packages\pandas\core\reshape\tile.py in _bins_to_cuts(x, bins, right, labels, precision, include_lowest, dtype, duplicates, ordered)
    419
    420     side = "left" if right else "right"
--> 421     ids = ensure_platform_int(bins.searchsorted(x, side=side))
    422
    423     if include_lowest:

TypeError: '<' not supported between instances of 'int' and 'str'


text:
Q: NHibernate Exceptions Breaking other Processes Before I begin, I'm in an environment that uses NHibernate with C#.  We don't use the JavaScript implementation; just C# on the backend.  We have a combination of ASP.NET 3.5 and .NET 3.5 in a Windows Service that spins off separate process threads.
Has anyone ever experienced an issue with NHibernate where an exception can cause other processes to break?
For example:
We have a Windows Service outside of our normal web application, which does a lot of data management and automated processes.  Let's consider the following scenario:
=> Service A is populating a table with the word "Hello" into a column with the data type VARCHAR(5)
=> Service B is updating values on a separate table from the word "August" to "September" with the data type VARCHAR(50)
Service A is in a transaction that has all inserts happening in the same transaction.
Service B is in a transaction that has all updates happening in the same transaction.
Service A and Service B obviously don't share the same transaction.
These services are running in separate threads and execute at the same time.
If Service A tries to enter "Hello Again" and violates the data constraints, Service B will exit without finishing the process.  There is usually a rollback will occur on Service A and Service B, due to this, so no changes are committed.
I apologize if this explanation is too cryptic, but the data and the process are irrelevant; it's the exception and results that are what are important.  Almost all of our processes do it and the exeption that occurs could be just about anything, including data type mismatches, timeouts or database deadlocks.
This is all theory, so I don't have specific code that can be guaranteed to replicate this.
I guess what I'm getting at is if NHibernate will roll back other transactions because a separate thread had an exception within it?
Please also understand that the Windows Service is the easiest way for us to replicate this, but we have also seen this happen during the ASP.NET processes.
Thank you in advance for any and all help!

A: I have a system where multiple processes and services responsible for specific db actions (Updates and Inserts). The idea is that updates are actionable in "quiet" periods, usually at night. (report building...slow..)

is if NHibernate will roll back other transactions because a separate thread had an exception within it?

It depends how you programmed it. A problem we had before, was where connections were not closed properly. When a worker thread failed, these connections were waiting to be closed explicitly. So now the nhibernate session code bits are wrapped in a try / catch /  finally thus making sure we clean up on exception. We can then roll back transactions on failure, and then retry again in a few seconds. I assume like my system, a lock on a database record may block another process on another service. On the other hand, if the main process dies, it is a different problem all together.


text:
Q: Scrapy does not go over the page Ні! Why doesn't spider go through the pages? I use the rule ... What do I do wrong? Іt only works on one page. Here is the code:
# -*- encoding: -*-

class JobSpider(CrawlSpider):
    name = 'superjob'
    allowed_domains = ['superjob.ru']
    start_urls = [
        'http://www.superjob.ru/vacancy/search/?t%5B0%5D=4&sbmit=1&period=7'
    ]

    rules = [
        Rule(SgmlLinkExtractor(allow='/vacancy/search/?',
                               restrict_xpaths=(
                                   u'//a[@class="h_border_none"]/следующая')),
             callback='parse',
             follow=True),
    ]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        titles = hxs.select(
                '//*[@id="ng-app"]/div[2]/div/div[2]/div/div[1]/div[2]/div/div/h2/a')
        items = []
        for title in titles:
            item = JobItem()
            item['title'] = title.select('//h2/a/text()').extract()
            items.append(item)
        # return items

A: 5 things to fix:

*

*the restrict_xpaths should point to the pagination block

*the callback should be called parse()

*use LinkExtractor, SgmlLinkExtractor is deprecated

*use xpath() instead of select() an response.xpath() shortcut

*fix the inner XPath expression - just get the text()
Fixed version:
# -*- coding: utf-8 -*-
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class JobSpider(CrawlSpider):
    name = 'superjob'
    allowed_domains = ['superjob.ru']
    start_urls = [
        'http://www.superjob.ru/vacancy/search/?t%5B0%5D=4&sbmit=1&period=7'
    ]

    rules = [
        Rule(LinkExtractor(allow='/vacancy/search/\?', restrict_xpaths=u'//div[@class="Paginator_navnums"]'),
             callback='parse_item',
             follow=True),
    ]

    def parse_item(self, response):
        titles = response.xpath('//*[@id="ng-app"]/div[2]/div/div[2]/div/div[1]/div[2]/div/div/h2/a')
        for title in titles:
            item = JobItem()
            item['title'] = title.xpath('text()').extract()
            yield item


text:
Q: Regex for double value in Swift 2 What's the new regex for a double, such as "123.45"
I've use the old ones [0-9]{1,}.[0-9]{1,}|[0-9]{1,} and \\d+(\\.\\d+)?. They work, but I can't use the .
When I tap . on the keyboard it doesn't appear in the field
I tested this on XCode 7 GM Seed - iOS 9 - iPad Air 2 Simulator
UPDATE:
    extension String {
        func stringsMatchingRegularExpression(expression: String) -> [String] {
            if let range = self.rangeOfString(expression, options: NSStringCompareOptions.RegularExpressionSearch, range: nil, locale: nil) {
                return [self[range]] + self[range.endIndex..<self.endIndex].stringsMatchingRegularExpression(expression)
            }
            return []
        }
}

This is the extension that I use and this function that removes everything except the regex:
func onlyDoubleUse(textField: AnyObject){
    let field = textField.object! as! UITextField
    let subStringArray = field.text!.stringsMatchingRegularExpression("\\d+(\\.\\d+)?")
    if(subStringArray.count>0){
        if(subStringArray[0] != ""){
            field.text = subStringArray[0]
        }else{
            field.text = ""
        }
    }else{
        field.text = ""
    }
}

NSNotificationCenter.defaultCenter().addObserver(self, selector: "onlyDoubleUse:", name: UITextFieldTextDidChangeNotification, object: theTextField)


text:
Q: C# Is there a way to put a Null-conditional operator (?) on T? I have an interface<T>. This interface has a method Compare(T x, T y).

*

*x can never be null.

*y has a large chance of being null.

I want to make this clear by using the Null-conditional operator ? on y: Compare(T x, T? y).
Is this possible and from what version of C#?
EDIT:
T can be a reference type and a value type.

A: I found the answer in a document suggested by @PanagiotisKanavos:
https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references#generics
In C# 8.0, using T? without constraining T to be a struct or a class did not compile. That enabled the compiler to interpret T? clearly. That restriction was removed in C# 9.0, by defining the following rules for an unconstrained type parameter T:

*

*If the type argument for T is a reference type, T? references the corresponding nullable reference type. For example, if T is a string, then T? is a string?.

*If the type argument for T is a value type, T? references the same value type, T. For example, if T is an int, the T? is also an int.

*If the type argument for T is a nullable reference type, T? references that same nullable reference type. For example, if T is a string?, then T? is also a string?.

*If the type argument for T is a nullable value type, T? references that same nullable value type. For example, if T is a int?, then T? is also a int?.
For my question, this means I need to constrain T to a class, since I am on C#8.

A: Given that till this answer is written, it's not mentioned that if there is a condition on T like this
public interface IDoWork<T> : where T: ???
{...}

we'll assume it to be a reference type
Now that it's assumed that T is a reference type then you should do this
public int Compare(T x, T y)
{

    if (y == null)
        //Take decision accordingly.
    else
        //Take decision accordingly.
}

Compare methods do not take parameters as nullable types. They take pure instances and then inside the method decide according to the expected behaviour.


text:
Q: logout when tab or browser window closed jsp I am new @jsp, and would like to call the logout function when the tab or the browser window is closed. i've made some research and found out that i need to use window.onbeforeunload. But the thing is , i don't know where to put it in my jsp page. Here is it's code:
<%@ page language="java" contentType="text/html; charset=windows-1256"
    pageEncoding="windows-1256"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">

       <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
        <%@ taglib uri="http://java.sun.com/jstl/fmt_rt"  prefix="fmt" %>
        <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
        <%@ taglib uri="http://java.sun.com/jstl/core-rt" prefix="c-rt" %>

  <link rel="stylesheet" href="css/login.css">
<title>Insert title here</title>

<form id="Form1" action="http://localhost:80/reports/rwservlet" method="Post"  target="_blank">

 <input type="hidden" id="cmdkey" name="cmdkey" value="repserv">
  <input type="hidden" id="temp" name="P_TO_EMP" value="0">
    <input type="hidden" id="femp" name="P_FROM_EMP" value="${puser.USR_USER}" >
    <input type="hidden" id="pcomp" name="P_COMP" value="${puser.USR_CP}">

 Years:<input type="text"  name="P_YEAR">

 Month:<input type="text"  name="P_PERIOD">

           <input type="submit" value="Report"  name="pbtn" onclick="switchURL()" />
           <input type="submit" value="Logout" name="pbtn"  onclick="Logout()"/>

</form>

can somebody help me plz.
Regards to all.

A: You have to add listener on window object as below
window.addEventListener("beforeunload", function(){
    //Ajax call to invoke logout action
});

Put this code in your jsp page.


text:
Q: How to run a plugin goal from terminal I have a multi-module project
One module uses a special plugin - maven-glassfish-plugin
I've got a problem with this plugin - it can't create new domain. Goal create-domain failed
I wanna to run this goal from terminal with key -X to view the full log. But I don't know how to do it - previously I used IDE to run goals
How to run chosen plugin goal from terminal?

A: Try mvn glassfish:<goal>
You can find the available goals and further documentation here
The maven binary must be accessible with the PATH lookup and the M2_HOME environment variable should be set to tell maven where to operate. You can find more details on configuring this here


text:
Q: Trayicon missing when restart Windows 7 When restart Windows, some tray icons were missing.
Is there a command to redraw trayIcon or prevent they missing ?

A: Try these DOS command:
%windir%\system32\taskkill.exe /IM explorer.exe /F
start %windir%\explorer.exe

Or make a batch file.


text:
Q: C++ container for list and map we have a collection of key and value pairs. We are in the need for a container which can help us to retrieve the value o(1) but also remember the insertion order so that when we do iteration, we could iterate like a inserting order. Since the key is a string, we will not able to use a set or similar structure.
Currently we have defined our own collection class which contains a list, also a map and the values are stored into 2 different structure.
Are there any readily available implementation available?

A: Sounds like you need a Boost Multi-Index container.


text:
Q: Adding third-party cookie exception to Cypress configuration Using Cypress, JavaScript end to end testing framework, is there a supported mechanism to add a third-party cookie exception, or some other Chromium preference (or Electron/ if not using e.g. --browser chromium)?
I have found a mechanism to do this but it involves wrapping the browser executable, effectively a man-in-the-middle between Cypress and the "browser" binary.

A: Presently, Cypress does not provide direct support for this.  There is a standing change request to provide API support for this and other Chromium/browser preferences: https://github.com/cypress-io/cypress/issues/3671
A solution I've created is to run Cypress with a custom browser which pre-populates the Chromium user data directory ("profile") with these preferences: https://github.com/cypress-io/cypress/issues/3671#issuecomment-549660119
#!/usr/bin/env bash

USER_DATA_DIR=`cut -d "=" -f 2 <<< ${*: -2:1}`
mkdir $USER_DATA_DIR/Default > $USER_DATA_DIR/Default/Preferences
cat << END_Preferences > $USER_DATA_DIR/Default/Preferences
{
"profile":{"content_settings":{"exceptions":{"cookies":{"example.com,*":{"setting":1}}}}}
}
END_Preferences
exec chromium $@


text:
Q: Get All Children to One List - Recursive C# C# | .NET 4.5 | Entity Framework 5
I have a class in Entity Framework that looks like this:
public class Location
{
   public long ID {get;set;}
   public long ParentID {get;set;}
   public List<Location> Children {get;set;}
}

ID is the identifier of the location, ParentID links it to a parent, and Children contains all of the children locations of the parent location. I'm looking for some easy way, likely recursively, to get all "Location" and their children to one single List containing the Location.ID's. I'm having trouble conceptualizing this recursively. Any help is appreciated.
This is what I have so far, its an extension to the entity class, but I believe it could be done better/simpler:
public List<Location> GetAllDescendants()
{
    List<Location> returnList = new List<Location>();
    List<Location> result = new List<Location>();
    result.AddRange(GetAllDescendants(this, returnList));
    return result;
}

public List<Location> GetAllDescendants(Location oID, ICollection<Location> list)
{
    list.Add(oID);
    foreach (Location o in oID.Children)
    {
            if (o.ID != oID.ID)
                    GetAllDescendants(o, list);
    }
    return list.ToList();
}

UPDATED
I ended up writing the recursion in SQL, throwing that in a SP, and then pulling that into Entity. Seemed cleaner and easier to me than using Linq, and judging by the comments Linq and Entity don't seem the best route to go. Thanks for all of the help!

A: I would like to contribute my own solution, which was modified from the references below:
public static IEnumerable<T> Flatten<T, R>(this IEnumerable<T> source, Func<T, R> recursion) where R : IEnumerable<T>
{
    var flattened = source.ToList();

    var children = source.Select(recursion);

    if (children != null)
    {
        foreach (var child in children)
        {
            flattened.AddRange(child.Flatten(recursion));
        }
    }

    return flattened;
}

Example:
var n = new List<FamilyMember>()
{
    new FamilyMember { Name = "Dominic", Children = new List<FamilyMember>()
        {
            new FamilyMember { Name = "Brittany", Children = new List<FamilyMember>() }
        }
    }
}.Flatten(x => x.Children).Select(x => x.Name);

Output:

*

*Dominic

*Brittany

Class:
public class FamilyMember {
    public string Name {get; set;}
    public List<FamilyMember> Children { get; set;}
}

Ref. https://stackoverflow.com/a/21054096/1477388
Note:  Can't find the other reference, but someone else on SO published an answer that I copied some code from.

A: Entity framework does not currently support recursion, and for that reason you can either

*

*Rely on lazy loading child collections as you have done (beware the N+1 problem)

*Query an arbitrary depth of objects (This will be an ugly query, though you could generate it using System.Linq.Expressions)

The only real option would be to avoid using LINQ to express the query, and instead resort to standard SQL.
Entity framework supports this scenario fairly well whether you're using code first or not.
For code-first, consider something along the lines of
var results = this.db.Database.SqlQuery<ResultType>(rawSqlQuery)

For model-first, consider using a defining query which I think is a good option as it allows further composition, or stored procedures.
To recursively get back data, you will need to understand recursive CTEs assuming you're using SQL Server, and that it is version 2005+
EDIT:
Here is the code for a recursive query to an arbitrary depth. I put this together just for fun, I doubt it would be very efficient!
var maxDepth = 5;

var query = context.Locations.Where(o => o.ID == 1);
var nextLevelQuery = query;

for (var i = 0; i < maxDepth; i++)
{
    nextLevelQuery = nextLevelQuery.SelectMany(o => o.Children);
    query = query.Concat(nextLevelQuery);
}

The flattened list is in the variable query

A: The accepted answer from @NikhilAgrawal will not recursively get all children and grandchildren as @electricalbah has pointed out.
I do miss the answer from @EricLippert that was given on Code Review.
https://codereview.stackexchange.com/a/5661/96658
static IEnumerable<T> DepthFirstTreeTraversal<T>(T root, Func<T, IEnumerable<T>> children)
{
    var stack = new Stack<T>();
    stack.Push(root);
    while(stack.Count != 0)
    {
        var current = stack.Pop();
        // If you don't care about maintaining child order then remove the Reverse.
        foreach(var child in children(current).Reverse())
            stack.Push(child);
        yield return current;
    }
}

Called like this:
static List<Location> AllChildren(Location start)
{
    return DepthFirstTreeTraversal(start, c=>c.Children).ToList();
}

I made an example below with SelectMany. As you can see from Immediate Window you will not even get the Parent Id if you use that solution.

A: You can do SelectMany
List<Location> result = myLocationList.SelectMany(x => x.Children).ToList();

You can use where condition for some selective results like
List<Location> result = myLocationList.Where(y => y.ParentID == someValue)
                                      .SelectMany(x => x.Children).ToList();

If you only required Id's of Children you can do
List<long> idResult = myLocationList.SelectMany(x => x.Children)
                                    .SelectMany(x => x.ID).ToList();

A: Create list to add all child using recursively
public static List list =  new List();
recursive funtion
 static  void GetChild(int id) // Pass parent Id
                {

                    using (var ctx =  new CodingPracticeDataSourceEntities())
                    {
                        if (ctx.Trees.Any(x => x.ParentId == id))
                        {
                            var childList = ctx.Trees.Where(x => x.ParentId == id).ToList();
                            list.AddRange(childList);
                            foreach (var item in childList)
                            {
                                GetChild(item.Id);
                            }

                        }

                    }
                }

Sample model
 public partial class Tree
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Nullable<int> ParentId { get; set; }
    }

A: This will do the trick:
class Extensions
{
    public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
    {
        var result = source.SelectMany(selector);
        if (!result.Any())
        {
            return result;
        }
        return result.Concat(result.SelectManyRecursive(selector));
    }
}

Use it like this:
List<Location> locations = new List<Location>();
//
// your code here to get locations
//
List<string> IDs = locations.SelectManyRecursive(l => l.Children).Select(l => l.ID).ToList();

A: Try this Extension method:
public static IEnumerable<T> Flatten<T, R>(this IEnumerable<T> source, Func<T, R> recursion) where R : IEnumerable<T>
{
    return source.SelectMany(x => (recursion(x) != null && recursion(x).Any()) ? recursion(x).Flatten(recursion) : null)
                 .Where(x => x != null);
}

And you can use it like this:
locationList.Flatten(x => x.Children).Select(x => x.ID);

A: I had no Children prop in my model, so Nikhil Agrawal's answer doesn't work for me, so here is my solution.
With following model:
public class Foo
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    // other props
}

You can get children of one item using:
List<Foo> GetChildren(List<Foo> foos, int id)
{
    return foos
        .Where(x => x.ParentId == id)
        .Union(foos.Where(x => x.ParentId == id)
            .SelectMany(y => GetChildren(foos, y.Id))
        ).ToList();
}

For ex.
List<Foo> foos = new List<Foo>();

foos.Add(new Foo { Id = 1 });
foos.Add(new Foo { Id = 2, ParentId = 1 });
foos.Add(new Foo { Id = 3, ParentId = 2 });
foos.Add(new Foo { Id = 4 });

GetChild(foos, 1).Dump(); // will give you 2 and 3 (ids)

A: Assuming Locations is a DbSet<Location> in your DB context, this will solve your problem "I'm looking for some easy way ... to get all 'Location' and their children to one single List containing the Location.ID's".  Seems like I'm missing something, so please clarify if so.
dbContext.Locations.ToList()
// IDs only would be dbContext.Locations.Select( l => l.ID ).ToList()

A: This is my method for Flattening the children.
private Comment FlattenChildComments(Comment comment, ref Comment tempComment)
    {
        if (comment.ChildComments != null && comment.ChildComments.Any())
        {
            foreach (var childComment in comment.ChildComments)
            {
                tempComment.ChildComments.Add(childComment);
                FlattenChildComments(childComment, ref tempComment);
            }
        }
        comment.ChildComments = tempComment.ChildComments;
        return comment;
    }

A: For the people who needs something generic:
/// <summary>
/// Recursively enumerate all children, grandchildren etc... in a 1-dimentional IEnumerable
/// </summary>
/// <typeparam name="TModel">The type of the model</typeparam>
/// <param name="root">The root from which to enumerate children</param>
/// <param name="childSelector">The selector on how to select the children of the root.</param>
/// <returns>A 1-dimentional IEnumerable of all it's children, grandchildren etc.. recursively.</returns>
public static IEnumerable<TModel> EnumerateChildren<TModel>(TModel root, Func<TModel, IEnumerable<TModel>> childSelector)
{
    var children = childSelector.Invoke(root);
    if (children == null)
    {
        yield break;
    }

    foreach (var child in children)
    {
        yield return child;

        foreach (var grandChild in EnumerateChildren(child, childSelector))
        {
            yield return grandChild;
        }
    }
}

Usage:
var location = GetLocation(); // Get your root.
var children = EnumerateChildren(location, l => l.Children);


text:
Q: Pull correct value as one variable depending on a condition Basically what I'm trying to do is say:
If there's a match on the key then insert the correct (new) value into a variable depending on the date. And if there isn't a match then I want the value from the old table The following is my sample code:
    proc sql;
create table fly.Formulary2017
as select
d.corp_ent_cd
,d.groupno
,case when p.EffectiveDate > d.cvmo
        then d.old
when p.EffectiveDate <= d.cvmo
        then p.new
else d.old
        end as WANT
,d.Key1
from lib.dsl d FULL JOIN lib.post p
on d.Key1=p.Key1
;
quit;

So there won't necessarily be a match on every key. For the ones where there are no matches I want the old value.

A: you need to include matching records logic in your code as shown below. here is small sample code below.  I have assigned the "new" and "old" instead you can have columns instead.
 /***partial code.***/

case when d.Key1 = p.Key1  and p.EffectiveDate > d.cvmo
    then "new"
when d.Key1 ne p.Key1
 then "old"
  when d.Key1 = p.Key1 and  p.EffectiveDate <= d.cvmo
    then "old"

 /*full code to try*/

 data post;
input key1 EffectiveDate:date9. ;
 format EffectiveDate date9.;
datalines;
10 10OCT2018
11 22OCT2018
12 27OCT2018
15 10NOV2018
16 22NOV2018
 17 27NOV2018
;

data dsl;
input key1 cvmo:date9. ;
format cvmo date9.;
datalines;
10 17OCT2018
11 1OCT2018
16 22NOV2018
17 27NOV2018
;

proc sql;
select
p.key1,
, case when d.Key1 = p.Key1  and p.EffectiveDate > d.cvmo
    then "new"
when d.Key1 ne p.Key1
 then "old"
  when d.Key1 = p.Key1 and  p.EffectiveDate <= d.cvmo
    then "old"
    end as WANT

from dsl d FULL JOIN post p
on d.Key1=p.Key1
 ;
quit;


text:
Q: Space between columns in bootstrap, last column jumps to the next row I have a problem with bootstrap. I would like to set 1% space between columns. If I set it like in code below the last column jumps to the next row.
HTML

        MaxCom MM720BB

        1zł
        (1,23 z VAT)

        MaxCom MM822 black

        1zł
        (1,23 z VAT)

        Goclever Quantum 2 400

        1zł
        (1,23 z VAT)

        Nokia 230

        1zł
        (1,23 z VAT)

CSS
.border {
    border: 1px solid #cdcccc;
    margin: 0px 1%;
}

A: Remember, when adding a margin, it adds to the width of that element. This extra width will bump the last col-lg-3 down to the next row.
Instead, what you can do is add another div inside the col-lg-3, and place a border on that. So, something like this:
HTML

        MaxCom MM720BB

        1zł
        (1,23 z VAT)

        MaxCom MM822 black

        1zł
        (1,23 z VAT)

        Goclever Quantum 2 400

        1zł
        (1,23 z VAT)

        Nokia 230

        1zł
        (1,23 z VAT)

CSS
.border {
    border: 1px solid #cdcccc;
}


text:
Q: Putty Closes when connecting to Remote Linux Machine after entering password When I try to Connect from Putty(Windows) to Remote Virtual Machine(RED HAT). Putty Closes suddenly. I look in the putty there no issues and IP address is able to ping in my command prompt.
Doubt: Does i need to made any configurations in my ssh_config and sshd_config files.

A: I found the problem in my sshd_config file, at the last line of file "ForceCommand cvs server" was uncommented ... it may happened by accident in my sshd_config file, I comment it and restart the sshd daemon.


text:
Q: Error with going back to a previous view in swift 3 Spritkit When I switch to my gamescene from my menu scene, it works perfectly fine.  But, when I try to go back, it is a disaster.  I get: unexpectedly found nil while unwrapping an Optional value.  The code for going back is:
let menuscene = MenuScene(size: self.size)
menuscene.scaleMode = scaleMode
self.view?.presentScene(menuscene)

The code that it says the error comes from is:
PlaygamebtnNode = self.childNode(withName: "PlaygamebtnNode") as! SKSpriteNode
NamelblNode = self.childNode(withName: "NamelblNode") as! SKLabelNode

This is odd because when the game launches, it is fine with this code.  The error has to come from the change in views/scenes. The code for the entrie MenuScene class is:
import SpriteKit
import GameplayKit

class MenuScene: SKScene {
    var PlaygamebtnNode:SKSpriteNode!
    var NamelblNode:SKLabelNode!

    override func didMove(to view: SKView) {

        PlaygamebtnNode = self.childNode(withName: "PlaygamebtnNode") as! SKSpriteNode
        NamelblNode = self.childNode(withName: "NamelblNode") as! SKLabelNode

        PlaygamebtnNode.texture = SKTexture(imageNamed: "Playgamebtn")
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first

        if let location = touch?.location(in: self){
            let nodesArray = self.nodes(at: location)

            if nodesArray.first?.name == "PlaygamebtnNode" {
                let transition = SKTransition.flipHorizontal(withDuration: 0.5)

                let nextScene = GameScene(size: self.size)
                self.view?.presentScene(nextScene, transition: transition)
            }
        }
    }
}

The reason this is not a ordinary found nil while unwrapping an Optional value question is because it does not show this error until I try to go back to the menu.

A: The problem started with this line:
PlaygamebtnNode = self.childNode(withName: "PlaygamebtnNode") as! SKSpriteNode

because as I said, self.childNode(withName:) was returning nil
The real problem however was related to this line (inside of leavegamefunc()):
let menuscene = MenuScene(size: self.size)

You have defined your  PlaygamebtnNode in MenuScene.sks and you are using wrong initializer (MenuScene.init(size:)).
The solution:
 func leavegamefunc() {
        if let menuScene = MenuScene(fileNamed: "MenuScene"){
            menuScene.scaleMode = scaleMode
            self.view?.presentScene(menuScene)
        }
    }


text:
Q: RTOS in a virtual machine Are there any opensource/free Unix like RTOS that can run a virtual machine like QNX Neutrino RTOS (http://www.qnx.com/products/evaluation/eval-target.html)?

A: RIOT is a good option. Its a microkernel based operating system highly designed for IoT applications. Few commands on your mac / linux terminal and you are into RIOT shell.
Please follow below links for more details:

*

*RIOT-OS : Their official Website

*RIOT-on-Git : RIOT on github


text:
Q: Write your own tidyselect functions I wrote an R package that utilizes the {tidyselect} selectors (e.g. contains(), starts_with(), etc.).  I would like to add a few more select helper functions to the package to select variables based on some attribute.  For example, select all numeric variables or perhaps all logical variables.
I have reviewed the {tidyselect} base code. But I can't surmise how the registration of the variables is working, and therefore can't extend it to select variables by their attributes.
I have done some searching, and it looks like the {recipes} package has successfully implemented additional helpers like I am looking for (e.g. all_numeric()), but I am struggling to write extension functions myself. https://github.com/tidymodels/recipes/blob/master/R/selections.R
What it comes down to, I believe, is that I do not understand what is happening when the variables are registered with the tidyselect::scoped_vars() function.  If I run tidyselect::scoped_vars(vars = names(mtcars)) in a clean environment, I don't see any changed being made.  But I am able to use the {tidyselect} helpers in the global environment after registering the variables.
names(mtcars)
#>  [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
#> [11] "carb"
tidyselect::scoped_vars(vars = names(mtcars))

# returns position of column 'mpg'
tidyselect::starts_with("mp")
#> 1

Any tips or direction to some documentation would be GREATLY appreciated!  Thank you!

A: When you call scoped_vars(), the given variable names are saved in an internal environment for the duration of the current function call:
(function() {
  print(tidyselect:::vars_env$selected)
  tidyselect::scoped_vars(names(mtcars))
  print(tidyselect:::vars_env$selected)
})()
#> NULL
#>  [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
#> [11] "carb"

print(tidyselect:::vars_env$selected)
#> NULL

As far as I can tell, this is the only information that {tidyselect} keeps about the variables; so if you want to select based on attributes, you have to maintain the attribute information yourself. This is also what {recipes} does, with a cur_info_env environment.
A crude implementation could look something like this:
type_env <- rlang::new_environment()

select_with_attributes <- function(.data, ...) {
  type_env$types <- purrr::map(.data, class)
  dplyr::select(.data, ...)
}

all_numeric <- function() {
  which(purrr::map_lgl(type_env$types, ~ any(.x %in% "numeric")))
}

head(select_with_attributes(iris, all_numeric()))
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1          5.1         3.5          1.4         0.2
#> 2          4.9         3.0          1.4         0.2
#> 3          4.7         3.2          1.3         0.2
#> 4          4.6         3.1          1.5         0.2
#> 5          5.0         3.6          1.4         0.2
#> 6          5.4         3.9          1.7         0.4

Created on 2019-06-13 by the reprex package (v0.2.1)


text:
Q: how can i send input int to another file in tkinter? i want to send input int to function in another file but i found error
this is home.py
a=Entry(win, width=21)
a.place(x=200, y=155)
b=Entry(win, width=22)
b.place(x=375, y=155)

this is function.py
t1=int(a.get())
t2=int(b.get())
t3=(1/3)*pi*t1*t1*t2

but after I run it i found erorr
t1=int(a.get())
NameError: name 'a' is not defined

A: NameError: name 'a' is not defined is causing because 'a' is not declared in function.py
you have to import another script in the working script if you want to use any variable/function that exists in another script.
example:
If, home.py contains a
b = 2
c = 3
a = b + c

and you want to use it inside function.py, then in function.py the code will be as follows:
import home
x = home.a
mult = x*x
print(mult)

This will output 25


text:
Q: LIVE555 - Set SPS and PPS after receiving first frame I have a device which delivers H264 encoded frames. Those I would like to transmit over the network using LIVE555.
Problem: These frames do not include the SPS and PPS NAL units. However, I have access to a function which delivers me the SPS and PPS NAL units after the device encoded the first frame.
Question: How can I set the SPS and PPS NAL units after the event loop of LIVE555 has already started? I've read numerous posts about similar issues but all these posts suggested the following solutions:

*

*LIVE555 sends the SPS and PPS NAL units when the DESCRIBE command is called

*Set the NAL units when calling createNewStreamSource()

*Set the NAL units when calling createNewRTPSink()

All these solutions aren't useful in my case because I haven't got the SPS and PPS NAL units at these moments. Is there some sort of way to update these NAL units after the event loop has already started?

A: You haven't provided enough information about the application design/architecture to provide a better answer:
Not sure if I understand your problem correctly, but it sounds like you are only instantiating the encoder after an RTSP client request. However the DESCRIBE request passes the SPS, PPS and at the time of DESCRIBE, you haven't encoded any data and hence don't have the SPS and PPS.
If the encoder is being instantiated in the live555 event loop after a client request, then one solution would be to

*

*instantiate an encoder with the desired configuration (or with all possible configurations) on application start-up

*encode a frame

*retrieve and save the SPS and PPS

*close the encoder

*proceed with "normal" event loop and await RTSP client connections.

In my experience the SPS and PPS don't usually change (often), and you must be getting your encoder configuration from somewhere (config file?).
If this does not answer your question, provide more detail about e.g. application threads, what event loops are running, encoder lifetimes, etc.

A: It has been quite some time. But as it has been requested, a general overview of what my solution was. I have no idea whether it was or is a good solution. For that it has been too long:

*

*I encoded one frame at the very start and used the mentioned function to grab the SPS and PPS NAL units

*... then immediately destroyed the encoder

*... removed the start code from the result

*... base64-encoded the SPS and PPS NAL units separately and concatenated them in the format SPS + "," + PPS

*... created a ServerMediaSession

*... created a custom MediaSubsession which extends OnDemandServerMediaSubsession with the methods createNewStreamSource and createNewRTPSink

*... created a new instance of the encoder and passed it to a H264VideoStreamDiscreteFramer in the createNewStreamSource method

*... used a H264VideoRTPSink in the createNewRTPSink method to which I passed the above mentioned concatenated SPS and PPS NAL units


text:
Q: use regex to replace long string I want to replace the string
ID12345678_S3_MPRAGE_ADNI_32Ch_2_98_clone_transform_clone_reg_N3Corrected1_mask_cp_strip_durastripped_N3Corrected_clone_lToads_lesions_seg

with
ID12345678

How can I replace this via regex?
I tried this - it didn't work.
import re
re.sub(r'_\w+_\d_\d+_\w+','')

Thank you

A: You can use re.sub with pattern [^_]* that match any sub-string from your text that not contain _ and as re.sub replace the pattern for first match you can use it in this case :
>>> s="ID12345678_S3_MPRAGE_ADNI_32Ch_2_98_clone_transform_clone_reg_N3Corrected1_mask_cp_strip_durastripped_N3Corrected_clone_lToads_lesions_seg"
>>> import re
>>> re.sub(r'([^_]*).*',r'\1',s)
'ID12345678'

But if it could be appear any where in your string you can use re.search as following :
>>> re.search(r'ID\d+',s).group(0)
'ID12345678'
>>> s="_S3_MPRAGE_ADNI_ID12345678_32Ch_2_98_clone_transform_clone_reg_N3Corrected1_mask_cp_strip_durastripped_N3Corrected_clone_lToads_lesions_seg"
>>> re.search(r'ID\d+',s).group(0)
'ID12345678'

But without regex simply you can use split() :
>>> s.split('_',1)[0]
'ID12345678'

A: I guess the first part is variable, then
import re
s = "ID12345678_S3_MPRAGE_ADNI_32Ch_2_98_clone_transform_clone_reg_N3Corrected1_mask_cp_strip_durastripped_N3Corrected_clone_lToads_lesions_seg"
print re.sub(r'_.*$', r'', s)


text:
Q: Sort Date column by month and year I have date format like "MM-dd-YYYY" in Excel file.
I would like to know if how can I sort it by month and year ?
Because when I sort, the 'year' doesn't work when we have different year like '2017' '2018'.
Thanks

A: *

*Convert your data to proper date format first. to do so perfom following steps:-

a.Simply select your dates in column A > Data tab of the ribbon > Text to Columns to open the Wizard:
Step 1 of the Wizard: Choose 'Delimited'
Step 2 of the Wizard: uncheck all Delimiters (just to be safe)
Step 3 of the Wizard: Choose 'Date' from the 'Column Data Format' options and choose your date format from the drop down list , and click the Finish button:
Tip: Note how the 'Date' drop down list above has many different combinations of D M Y, you simply choose what order your dates are formatted in from the list.
now sort your data and it will work as you want it to.
Check here for more:


text:
Q: Checking if the value for the key is the same as before I have been working on this code and I cannot find a answer.

*

*I have 2 lists
point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

*I want to set a:1 and b:3 and so on...and I want them put in a dictionary called point_letters.
This is my starter code.
point_letters = {}
point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

for x in letters:
    for i in point_values:
        if point_letters[x] != i: # is what I'm trying to do
            point_letters[x] = i
print(point_letters)

How should I do this?

A: point_letters = dict(zip(letters, point_values))

zip makes a list of pairs of corresponding elements; dict converts the list of pairs to a dictionary.
EDIT: changed the dict name. Also in response to comments, and the posted code:

This is great, but I still have not learned this. Is there a way to for loop it?

In general, in the real world, you'd use the above method. for is very low-level and you'd want to avoid it when you can. For the class, I won't solve your problem, but give you hints instead (so it's not plagiarism):

*

*You want to pair up the letters[i] and point_values[i] for the same i

*i should be going from 0 to the maximum index - one less than the length of your lists

*You can get a length of a list using len

*You can get a range using range (Python 3) or xrange (Python 2)
In your code,

*

*Having two loops is not what you need to do

*Your if cannot ever be true.
EDIT2: Changed "array" to "list", because Python has to be a special snowflake.


text:
Q: RoR: how can I get a micropost to be created by two seperate micropost forms according to an element? My microposts have a column called type which is a string. This can either be purchase or sale. I want two seperate input forms, where if you input content into one then it automatically fills in purchase as the type (when creating the micropost) and if you input content into the other it automatically fills in sale. .
Here is my form as it is
<%= form_for(@micropost) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_area :content, placeholder: "What's something else you want to buy?" %>

  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

I recently added type as a column in the micropost data table. That is why there is no input for it (yet). Read above for how I want the type to be automatically filled in
Im thinking one way to do it is to id each form with something. Then when the form is being filled in, I could somehow tell it to automatically fill in the hidden type field based on which form is filled in. IS this possible??

A: I think you are referring to the hidden_field here.  Use hidden_field to pass information to the controller without presenting it to the user.  Here is one form for the purchase:
<%= form_for(@micropost) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
    <%= f.hidden_field :type, 'purchase' %>

  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

and another for the sale:
<%= form_for(@micropost) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_area :content, placeholder: "What's something else you want to sell?" %>
    <%= f.hidden_field :type, 'sale' %>

  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>