text:
Q: Extra directory can be created in hg rename-ing directory I try to rename directory which includes largefile-normal mixed via hg rename <orig-dir> <dest-dir>, and results as this:

*

*orig/foo.png(largefile) → dest/orig/foo.png

*orig/bar.txt(normal) → dest/bar.txt
...

I'm annoyed by this behavior, I'd like to know how to resolve this problem.

A: I guess what you are seeing is because the folder has a file which isn't tracked by mercurial.
Workaround might be to rename the folder then run hg rename --after
For example (windows):
  ren orig dest
  hg rename --after orig dest


text:
Q: How to get last value before a colon in bash I have a string like:
arn:aws:ecs:us-east-1:123456789:task-definition/myservice:10
Is there anyway I can get the last value 10? I tried to get last character but forgot that this int value can increase and eventually becomes 2 characters.

A: Well, many ways, this one works, though is not elegant :)
echo "arn:aws:ecs:us-east-1:123456789:task-definition/myservice:10" | sed 's/.*://'

redpajama_set_name: RedPajamaStackExchange


text:
Q: VBA Find Pattern Word file and export every two pages as .pdf I have Word file (154 pages). I need to take every 2 pages and export as .pdf (I did this), but I need also to add file name like EExxxxxxxx (patern), I set reg pattern like "(EE[0-9]{8})" it's ok in my opinion, because it find the first pattern, always EE and 8 numbers (examples below). The same pattern are on every two pages. I can't get it from this two pages, and add this value as file name, because I get only the first pattern (and script finish searching, when I go to next 2 pages inside Word file), but the same time next files (with 2 right pages) are creating.
Of cource every pages have a lot of different text, but the paterns are the most important.
Word File:
Page 1:EE30000229
Page 2:EE30000229
Page 3:EE30000089
Page 4:EE30000089
...
Page 153: EE30001889
Page 154: EE30001889
Script1:
Option Explicit
Sub SaveAsSeparatePDFs()

Dim strDirectory As String, strTemp As String
Dim ipgStart As Integer, ipgEnd As Integer
Dim iPDFnum As Integer, i As Integer
Dim vMsg As Variant, bError As Boolean
Dim Name As String
Dim RegEx As VBScript_RegExp_55.RegExp
Set RegEx = New VBScript_RegExp_55.RegExp
Dim Matches As VBScript_RegExp_55.matchCollection
Dim Match As VBScript_RegExp_55.Match

1:
strDirectory = InputBox("Directory to save individual PDFs? " & _
    vbNewLine & "(ex: C:\Users\Public)")
If strDirectory = "" Then Exit Sub
If Dir(strDirectory, vbDirectory) = "" Then
    vMsg = MsgBox("Please enter a valid directory.", vbOKCancel, "Invalid Directory")
    If vMsg = 1 Then
        GoTo 1
    Else
        Exit Sub
    End If
End If

2:
strTemp = InputBox("Begin saving PDFs starting with page __? " & _
    vbNewLine & "(ex: 32)")
bError = bErrorF(strTemp)
If bError = True Then GoTo 2
ipgStart = CInt(strTemp)

3:
strTemp = InputBox("Save PDFs until page __?" & vbNewLine & "(ex: 37)")
bError = bErrorF(strTemp)
If bError = True Then GoTo 3
ipgEnd = CInt(strTemp)

iPDFnum = ipgStart
On Error GoTo 4:

For i = ipgStart To ipgEnd Step 2

   '-- This code creating .pdf includes every two pages. But I need add some code that give to me also
   '-- right file name with EExxxxxxxx and exchange iPDFnum that is below
    ActiveDocument.ExportAsFixedFormat OutputFileName:= _
        strDirectory & "\Page_" & iPDFnum & ".pdf", ExportFormat:=wdExportFormatPDF, _
        OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:= _
        wdExportFromTo, From:=i, to:=i + 1, Item:=wdExportDocumentContent, _
        IncludeDocProps:=False, KeepIRM:=False, CreateBookmarks:= _
        wdExportCreateHeadingBookmarks, DocStructureTags:=True, _
        BitmapMissingFonts:=False, UseISO19005_1:=False
    iPDFnum = iPDFnum + 2

Next i
End

End
4:
vMsg = MsgBox("Unknown error encountered while creating PDFs." & vbNewLine & vbNewLine & _
    "Aborting", vbCritical, "Error Encountered")
End Sub

Private Function bErrorF(strTemp As String) As Boolean
Dim i As Integer, vMsg As Variant
bErrorF = False

If strTemp = "" Then
    End
ElseIf IsNumeric(strTemp) = True Then
    i = CInt(strTemp)
    If i > ActiveDocument.BuiltInDocumentProperties(wdPropertyPages) Or i <= 0 Then
        Call msgS(bErrorF)
    End If
Else
    Call msgS(bErrorF)
End If
End Function

Private Sub msgS(bMsg As Boolean)
Dim vMsg As Variant
    vMsg = MsgBox("Please enter a valid integer." & vbNewLine & vbNewLine & _
        "Integer must be > 0 and < total pages in the document (" & _
        ActiveDocument.BuiltInDocumentProperties(wdPropertyPages) & ")", vbOKCancel, "Invalid Integer")
    If vMsg = 1 Then
        bMsg = True
    Else
        End
    End If
End Sub

The next Sub, that can show all of the patterns (EExxxxxxxx) from Word file. I don't now how to add these two scripts so that they generate files contain 2 more pages from the Word file and their name includes the EExxxxxxxx template. I change .Global also with True, but still show only the first pattern from the list.
Script2:
 Sub Find()
 Dim RegEx As VBScript_RegExp_55.RegExp
 Set RegEx = New VBScript_RegExp_55.RegExp
 Dim Matches As VBScript_RegExp_55.matchCollection
 Dim Match As VBScript_RegExp_55.Match

 With RegEx
     .IgnoreCase = False
     .MultiLine = True
     .Global = False
     .Pattern = "(EE[0-9]{8})"
 End With
 Set Matches = RegEx.Execute(ActiveDocument.Content.Text)
 For Each Match In Matches
     MsgBox (Match.Value)
 Next Match

End Sub

Anyone can help to me? It's important project to my organisation.

A: You really don't need RegEx to do this. Word's built-in Find function can be used with wildcards to match patterns. The function below will return the text matching your pattern if found on the specified page.
Function FindPattern(pageNum As Long) As String
    Dim rngFind As Range
    Set rngFind = ActiveDocument.GoTo(What:=wdGoToPage, Name:=pageNum)
    Set rngFind = rngFind.GoTo(What:=wdGoToBookmark, Name:="\Page")
    With rngFind.Find
        .ClearFormatting
        .Text = "EE[0-9]{8}"
        .MatchWildcards = True
        .Wrap = wdFindStop
        If .Execute Then FindPattern = rngFind.Text
    End With
End Function

You would use it inside your loop, for example:
For i = ipgStart To ipgEnd Step 2
    text = FindPattern(i)

EDIT:
Code used for testing
Sub SaveAsSeparatePDFs()

    Dim strDirectory As String, strTemp As String
    Dim ipgStart As Integer, ipgEnd As Integer
    Dim iPDFnum As Integer, i As Long
    Dim vMsg As Variant, bError As Boolean
    Dim Name As String, patternText As String

1:
    strDirectory = InputBox("Directory to save individual PDFs? " & _
            vbNewLine & "(ex: C:\Users\Public)")
    If strDirectory = "" Then Exit Sub
    If Dir(strDirectory, vbDirectory) = "" Then
            vMsg = MsgBox("Please enter a valid directory.", vbOKCancel, "Invalid Directory")
            If vMsg = 1 Then
                  GoTo 1
            Else
                  Exit Sub
            End If
    End If

2:
    strTemp = InputBox("Begin saving PDFs starting with page __? " & _
            vbNewLine & "(ex: 32)")
    bError = bErrorF(strTemp)
    If bError = True Then GoTo 2
    ipgStart = CInt(strTemp)

3:
    strTemp = InputBox("Save PDFs until page __?" & vbNewLine & "(ex: 37)")
    bError = bErrorF(strTemp)
    If bError = True Then GoTo 3
    ipgEnd = CInt(strTemp)

    iPDFnum = ipgStart
    On Error GoTo 4:

    For i = ipgStart To ipgEnd Step 2
        patternText = FindPattern(i)
           '-- This code creating .pdf includes every two pages. But I need add some code that give to me also
           '-- right file name with EExxxxxxxx and exchange iPDFnum that is below
            ActiveDocument.ExportAsFixedFormat OutputFileName:= _
                  strDirectory & "\Page_" & iPDFnum & ".pdf", ExportFormat:=wdExportFormatPDF, _
                  OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:= _
                  wdExportFromTo, From:=i, to:=i + 1, Item:=wdExportDocumentContent, _
                  IncludeDocProps:=False, KeepIRM:=False, CreateBookmarks:= _
                  wdExportCreateHeadingBookmarks, DocStructureTags:=True, _
                  BitmapMissingFonts:=False, UseISO19005_1:=False
            iPDFnum = iPDFnum + 2

    Next i
    End

    End
4:
    vMsg = MsgBox("Unknown error encountered while creating PDFs." & vbNewLine & vbNewLine & _
            "Aborting", vbCritical, "Error Encountered")
End Sub


text:
Q: Select something and change the text of a TextBox -- #name? error For some sort of reason, which I can't seem to spot, this fails and I get a #Name? error.  When I tried to do this, I use pretty much the same code in another place in my form; the only difference is the "cbo" and the names of my txt and alike.
Private Sub cboVarenummer_AfterUpdate()
  Dim LSQLVareNavn  As String
    LSQLVareNavn = "select Varenavn from VARENUMMER where VARENUMMER.Varenummer = '" & cboVarenummer & "'"
    txtVarenavn.ControlSource = LSQLVareNavn
End Sub

Can anyone spot my error?
What I wish the code would do is when I Select something in my cboVarenummer, the TextBox txtVarenavn changes its text to what the sql statement returns.

A: Did you not want cboVarenummer.SelectedValue.Tostring (Or cboVarenummer.SelectedItem.Tostring dependant on how you populated the combo box) in the SQL Query?

A: what i wish the code would do is when i Select something in my cboVarenummer, the my txtbox txtVarenavn changes its text to what the sql statement returns
In that case, I think you should be changing txtVarenavn's .Value property rather than its .ControlSource property.
Also use the DLookup() function to retrieve the value you want to store in txtVarenavn.Value
Private Sub cboVarenummer_AfterUpdate()
    'Dim LSQLVareNavn  As String '
    Dim strWhere As String
    'LSQLVareNavn = "select Varenavn from VARENUMMER where VARENUMMER.Varenummer = '" & cboVarenummer & "'" '
    'txtVarenavn.ControlSource = LSQLVareNavn '
    strWhere = "Varenummer = '" & Me!cboVarenummer & "'"
    Me!txtVarenavn = DLookup("Varenummer", "Varenummerf", strWhere)
End Sub

Compare the DLookup expression to your previous SELECT statement.  You can see how the field name, table name, and WHERE clause correspond between the two.  Think of DLookup as a simple SELECT ... it returns only a single value rather than a recordset ... but that's exactly what you need here.
I also changed the table name to Varenummerf, as you listed in your comment to @Ben.  VARENUMMER as the table and Varenummer as the field name might not confuse Access' database engine, but it makes me uneasy.  :-)


text:
Q: On the weak closure of a sequence of projections Let $H$ be a Hilbert space with $\text{dim}=\infty$ , and $\{e_n\}$ be an orthogonal sequence of projections in $B(H)$. Show that $\{\sqrt{n}e_n ; n\geq 1\}$ does not admit a subsequence converging to zero weakly.
Suppose $\{\sqrt{n_k}e_{n_k}\}$ be a weakly convergent subsequence to zero , so
$$\sqrt{n_{k}}e_{n_k}\to 0 (\text{wot}) \Longrightarrow \sqrt{n_k} \langle e_{n_k}\xi,\eta\rangle \to 0~~~(\xi,\eta\in H)$$
$$~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\Longrightarrow \{\sqrt{n_k}\langle e_{n_k} \xi , \eta\rangle\} \text{is norm bounded}$$
Now I need to show the above subsequence is not bounded for a contradiction.
While I'm sure  that the subsequence is not bounded, but I can not show it. Please help me. Thanks.

A: Let $\{\sqrt{n_k}e_{n_k}\}_{k=1}^{\infty}$ be an arbitrary subsequence of $\{\sqrt{n}e_{n}\}_{n=1}^{\infty}$. It is clear that $k\leq n_k$. For each positive integer $k$, there exists
$\xi_k\in H$ such that $\| \xi_k\|=1$ and $e_{n_k}\xi_k=\xi_k$. Define the sequence of numbers $\{ \alpha_k\}_{k=1}^{\infty}$ as follows: $\alpha_k=\frac{1}{\sqrt[4]{n_k}}$ if $k$ is a power of $2$, i.e., if $k=2^m$ for some positive integer $m$; for $k\ne 2^m$, let $\alpha_k=0$. It follows that
$$ \sum_{k=1}^{\infty}|\alpha_k|^2=\sum_{m=1}^{\infty}|\alpha_{2^m}|^2\leq \sum_{m=1}^{\infty}\frac{1}{\sqrt[4]{2^m}}<\infty. \tag1 $$
Thus $\xi=\sum_{k=1}^{\infty}\alpha_k\xi_k$ is well defined vector in $H$. It follows from
$$ \langle \sqrt{n_k}e_{n_k}\xi,\xi\rangle=\sqrt{n_k}\alpha_{k}^{2}=\left\{ \begin{array}{cc} 1; & k=2^m\\ 0; & k\ne 2^m\end{array} \right. $$
that the sequence $\{ \langle \sqrt{n_k}e_{n_k}\xi,\xi\rangle\}_{k=1}^{\infty}$ does not converge to $0$ and therefore $\{ \sqrt{n_k}e_{n_k}\}_{k=1}^{\infty}$ does not converge  to $0$ in the weak operator topology.


text:
Q: Dynamical Systems Time Dependent Matrix Consider the time dependent matrix x'=Ax with $A = \begin{bmatrix}1&t\\0&-1\end{bmatrix}$
Find the general solution.
We were given a hint to solve the second component first.  I know how to solve this without time dependence, but we never did a problem in class with time dependence and my book does not give a good example.


text:
Q: Smooth scrolling with timer in HTML Synopsis:
The main idea behind this is to auto smooth scroll to the testimonials section of my html after a certain amount of time.
Achieved so far:
I'm able to scroll to the testimonials section of the page after X seconds without any problems using a simple script in my main index.html page. The script code is given below.

Auto scroll in the page after 5secs

Problem facing:
I've smooth scrolling in the entire page, but for the timer scrolling in my page, I'm unable to use smooth scroll. The uncertain transition is looking awkward, hence, I want to make it smooth scroll.
Also, I want this to happen only for the first time on page loading, i.e., if any operation is done in the page, this will not happen if visited index.html again.
TIA guys!

A:

function goTo(selector, timeout, cb) {
  var $el = $(selector);
  if (!$el[0]) return;
  var $par = $el.parent();
  if ($par.is("body")) $par = $("html, body");
  setTimeout(() => {
    $par.stop().animate({scrollTop: $el.offset().top}, 1000, cb && cb.call($el[0]));
  }, timeout || 0);
}

// USE LIKE:
goTo("#testimonials", 3000, function() {

  // You can use `this` to reference #testimonials! yey
  $(this).append("
Going to #contact in 3sec!");
  goTo("#contact", 3000);

});

// Alternatively, without using callbacks you can do
// goTo("#testimonials", 3000);
// goTo("#contact", 6000);

// Reuse function for elements click!
$("[href^='#']").on("click", function(e) {
  e.preventDefault();
  goTo($(this).attr("href"));
});
/*QuickReset*/
*{margin:0;box-sizing:border-box;} html,body{height:100%;font:14px/1.4 sans-serif;}

article {
  height: 150vh;
}

WELCOME (wait 3 sec)

ABOUT

OUR WORK

TESTIMONIALS

  CONTACT TO TOP


text:
Q: Mantener tecla pulsada windows.h SendInput() c++ Estoy intentando crear un script muy sencillo que mantenga las teclas pulsadas durante x tiempo, simulando la entrada de una persona real. No obstante mediante el uso de sendInput no consigo que la tecla se mantenga pulsada y que en el bloc de notas se imprima 'aaaaaaa' y no 'a' alguien sabe como hacer para que la tecla se mantenga pulsada hasta que se envíe el evento de KEYEVENTF_KEYUP?
gracias, saludos.

#include <windows.h>
#include <iostream>

using namespace std;

// 0x57 w
// 0x20 space
// 0x41 a

int main()
{
    INPUT input;
    input.type = INPUT_KEYBOARD;
    int x;

    while (1)
    {
        x = rand() % 3;
        switch (x)
        {
        case 0:
            input.ki.wVk = 0x41;
            break;
        case 1:
            input.ki.wVk = 0x20;
            break;
        case 2:
            input.ki.wVk = 0x57;
        }

        HWND hwnd = FindWindowA("NotePAD", 0);
        HWND hwnd2 = GetForegroundWindow();

        if (hwnd)
            SetForegroundWindow(hwnd);
        else
            std::cout << "no se encuentra el programa!\n";

        //boton hacia abajo
        input.ki.dwFlags = 0;
        SendInput(1, &input, sizeof(INPUT));
        Sleep((double)rand() / (RAND_MAX + 1) *3000);

        //boton hacia arriba
        input.ki.dwFlags = KEYEVENTF_KEYUP;
        SendInput(1, &input, sizeof(INPUT));

        //volvemos a nuestra pantalla y esperamos un tiempo
        SetForegroundWindow(hwnd2);
        Sleep((double)rand() / (RAND_MAX + 1) * 10000);
    }

A: Mantener las teclas pulsadas es una característica del controlador de teclado, no de Windows, yo diría que lo más factible es utilizar un timer.
Por ejemplo:
MSG msg;

SetTimer(NULL,
         0,
         300,
         (TIMERPROC)&keypress);
while(GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

La función keypress es algo como lo siguiente:
void CALLBACK keypress(HWND hwnd, UINT uMsg, UINT timerId, DWORD dwTime)
{
}


text:
Q: C# - A faster alternative to Convert.ToSingle() I'm working on a program which reads millions of floating point numbers from a text file. This program runs inside of a game that I'm designing, so I need it to be fast (I'm loading an obj file). So far, loading a relatively small file takes about a minute (without precompilation) because of the slow speed of Convert.ToSingle(). Is there a faster way to do this?
EDIT: Here's the code I use to parse the Obj file
http://pastebin.com/TfgEge9J
using System;
using System.IO;
using System.Collections.Generic;
using OpenTK.Math;
using System.Drawing;
using PlatformLib;

public class ObjMeshLoader
{
    public static StreamReader[] LoadMeshes(string fileName)
    {
        StreamReader mreader = new StreamReader(PlatformLib.Platform.openFile(fileName));
        MemoryStream current = null;
        List<MemoryStream> mstreams = new List<MemoryStream>();
        StreamWriter mwriter = null;

        if (!mreader.ReadLine().Contains("#"))
        {
            mreader.BaseStream.Close();
            throw new Exception("Invalid header");
        }

        while (!mreader.EndOfStream)
        {
            string cmd = mreader.ReadLine();
            string line = cmd;
            line = line.Trim(splitCharacters);
            line = line.Replace("  ", " ");

            string[] parameters = line.Split(splitCharacters);
            if (parameters[0] == "mtllib")
            {
                loadMaterials(parameters[1]);
            }

            if (parameters[0] == "o")
            {
                if (mwriter != null)
                {
                    mwriter.Flush();
                    current.Position = 0;
                }

                current = new MemoryStream();
                mwriter = new StreamWriter(current);
                mwriter.WriteLine(parameters[1]);
                mstreams.Add(current);
            }
            else
            {
                if (mwriter != null)
                {
                    mwriter.WriteLine(cmd);
                    mwriter.Flush();
                }
            }
        }

        mwriter.Flush();
        current.Position = 0;
        List<StreamReader> readers = new List<StreamReader>();

        foreach (MemoryStream e in mstreams)
        {
            e.Position = 0;
            StreamReader sreader = new StreamReader(e);
            readers.Add(sreader);
        }

        return readers.ToArray();
    }

    public static bool Load(ObjMesh mesh, string fileName)
    {
        try
        {
            using (StreamReader streamReader = new StreamReader(Platform.openFile(fileName)))
            {
                Load(mesh, streamReader);
                streamReader.Close();
                return true;
            }
        }
        catch { return false; }
    }

    public static bool Load2(ObjMesh mesh, StreamReader streamReader, ObjMesh prevmesh)
    {
        if (prevmesh != null)
        {
            //mesh.Vertices = prevmesh.Vertices;
        }

        try
        {
            //streamReader.BaseStream.Position = 0;
            Load(mesh, streamReader);
            streamReader.Close();
#if DEBUG
            Console.WriteLine("Loaded "+mesh.Triangles.Length.ToString()+" triangles and"+mesh.Quads.Length.ToString()+" quadrilaterals parsed, with a grand total of "+mesh.Vertices.Length.ToString()+" vertices.");
#endif
            return true;
        }
        catch (Exception er) { Console.WriteLine(er); return false; }
    }

    static char[] splitCharacters = new char[] { ' ' };
    static List<Vector3> vertices;
    static List<Vector3> normals;
    static List<Vector2> texCoords;
    static Dictionary<ObjMesh.ObjVertex, int> objVerticesIndexDictionary;
    static List<ObjMesh.ObjVertex> objVertices;
    static List<ObjMesh.ObjTriangle> objTriangles;
    static List<ObjMesh.ObjQuad> objQuads;
    static Dictionary<string, Bitmap> materials = new Dictionary<string, Bitmap>();

    static void loadMaterials(string path)
    {
        StreamReader mreader = new StreamReader(Platform.openFile(path));
        string current = "";
        bool isfound = false;

        while (!mreader.EndOfStream)
        {
            string line = mreader.ReadLine();
            line = line.Trim(splitCharacters);
            line = line.Replace("  ", " ");

            string[] parameters = line.Split(splitCharacters);

            if (parameters[0] == "newmtl")
            {
                if (materials.ContainsKey(parameters[1]))
                {
                    isfound = true;
                }
                else
                {
                    current = parameters[1];
                }
            }

            if (parameters[0] == "map_Kd")
            {
                if (!isfound)
                {
                    string filename = "";
                    for (int i = 1; i < parameters.Length; i++)
                    {
                        filename += parameters[i];
                    }

                    string searcher = "\\" + "\\";

                    filename.Replace(searcher, "\\");
                    Bitmap mymap = new Bitmap(filename);
                    materials.Add(current, mymap);
                    isfound = false;
                }
            }
        }
    }

    static float parsefloat(string val)
    {
        return Convert.ToSingle(val);
    }

    int remaining = 0;

    static string GetLine(string text, ref int pos)
    {
        string retval = text.Substring(pos, text.IndexOf(Environment.NewLine, pos));
        pos = text.IndexOf(Environment.NewLine, pos);
        return retval;
    }

    static void Load(ObjMesh mesh, StreamReader textReader)
    {
        //try {
        //vertices = null;
        //objVertices = null;
        if (vertices == null)
        {
            vertices = new List<Vector3>();
        }

        if (normals == null)
        {
            normals = new List<Vector3>();
        }

        if (texCoords == null)
        {
            texCoords = new List<Vector2>();
        }

        if (objVerticesIndexDictionary == null)
        {
            objVerticesIndexDictionary = new Dictionary<ObjMesh.ObjVertex, int>();
        }

        if (objVertices == null)
        {
            objVertices = new List<ObjMesh.ObjVertex>();
        }

        objTriangles = new List<ObjMesh.ObjTriangle>();
        objQuads = new List<ObjMesh.ObjQuad>();

        mesh.vertexPositionOffset = vertices.Count;

        string line;
        string alltext = textReader.ReadToEnd();
        int pos = 0;

        while ((line = GetLine(alltext, pos)) != null)
        {
            if (line.Length < 2)
            {
                break;
            }

            //line = line.Trim(splitCharacters);
            //line = line.Replace("  ", " ");

            string[] parameters = line.Split(splitCharacters);

            switch (parameters[0])
            {

                case "usemtl":
                    //Material specification
                    try
                    {
                        mesh.Material = materials[parameters[1]];
                    }
                    catch (KeyNotFoundException)
                    {
                        Console.WriteLine("WARNING: Texture parse failure: " + parameters[1]);
                    }

                    break;
                case "p": // Point
                    break;
                case "v": // Vertex
                    float x = parsefloat(parameters[1]);
                    float y = parsefloat(parameters[2]);
                    float z = parsefloat(parameters[3]);
                    vertices.Add(new Vector3(x, y, z));
                    break;
                case "vt": // TexCoord
                    float u = parsefloat(parameters[1]);
                    float v = parsefloat(parameters[2]);
                    texCoords.Add(new Vector2(u, v));
                    break;
                case "vn": // Normal
                    float nx = parsefloat(parameters[1]);
                    float ny = parsefloat(parameters[2]);
                    float nz = parsefloat(parameters[3]);
                    normals.Add(new Vector3(nx, ny, nz));
                    break;
                case "f":
                    switch (parameters.Length)
                    {
                        case 4:
                            ObjMesh.ObjTriangle objTriangle = new ObjMesh.ObjTriangle();
                            objTriangle.Index0 = ParseFaceParameter(parameters[1]);
                            objTriangle.Index1 = ParseFaceParameter(parameters[2]);
                            objTriangle.Index2 = ParseFaceParameter(parameters[3]);
                            objTriangles.Add(objTriangle);
                            break;
                        case 5:
                            ObjMesh.ObjQuad objQuad = new ObjMesh.ObjQuad();
                            objQuad.Index0 = ParseFaceParameter(parameters[1]);
                            objQuad.Index1 = ParseFaceParameter(parameters[2]);
                            objQuad.Index2 = ParseFaceParameter(parameters[3]);
                            objQuad.Index3 = ParseFaceParameter(parameters[4]);
                            objQuads.Add(objQuad);
                            break;
                    }
                    break;
            }
        }
        //}catch(Exception er) {
        //  Console.WriteLine(er);
        //  Console.WriteLine("Successfully recovered. Bounds/Collision checking may fail though");
        //}
        mesh.Vertices = objVertices.ToArray();
        mesh.Triangles = objTriangles.ToArray();
        mesh.Quads = objQuads.ToArray();
        textReader.BaseStream.Close();
    }

    public static void Clear()
    {
        objVerticesIndexDictionary = null;
        vertices = null;
        normals = null;
        texCoords = null;
        objVertices = null;
        objTriangles = null;
        objQuads = null;
    }

    static char[] faceParamaterSplitter = new char[] { '/' };

    static int ParseFaceParameter(string faceParameter)
    {
        Vector3 vertex = new Vector3();
        Vector2 texCoord = new Vector2();
        Vector3 normal = new Vector3();

        string[] parameters = faceParameter.Split(faceParamaterSplitter);

        int vertexIndex = Convert.ToInt32(parameters[0]);

        if (vertexIndex < 0) vertexIndex = vertices.Count + vertexIndex;
        else vertexIndex = vertexIndex - 1;

        //Hmm. This seems to be broken.
        try
        {
            vertex = vertices[vertexIndex];
        }
        catch (Exception)
        {
            throw new Exception("Vertex recognition failure at " + vertexIndex.ToString());
        }

        if (parameters.Length > 1)
        {
            int texCoordIndex = Convert.ToInt32(parameters[1]);

            if (texCoordIndex < 0) texCoordIndex = texCoords.Count + texCoordIndex;
            else texCoordIndex = texCoordIndex - 1;

            try
            {
                texCoord = texCoords[texCoordIndex];
            }
            catch (Exception)
            {
                Console.WriteLine("ERR: Vertex " + vertexIndex + " not found. ");
                throw new DllNotFoundException(vertexIndex.ToString());
            }
        }

        if (parameters.Length > 2)
        {
            int normalIndex = Convert.ToInt32(parameters[2]);

            if (normalIndex < 0) normalIndex = normals.Count + normalIndex;
            else normalIndex = normalIndex - 1;

            normal = normals[normalIndex];
        }

        return FindOrAddObjVertex(ref vertex, ref texCoord, ref normal);
    }

    static int FindOrAddObjVertex(ref Vector3 vertex, ref Vector2 texCoord, ref Vector3 normal)
    {
        ObjMesh.ObjVertex newObjVertex = new ObjMesh.ObjVertex();
        newObjVertex.Vertex = vertex;
        newObjVertex.TexCoord = texCoord;
        newObjVertex.Normal = normal;

        int index;

        if (objVerticesIndexDictionary.TryGetValue(newObjVertex, out index))
        {
            return index;
        }
        else
        {
            objVertices.Add(newObjVertex);
            objVerticesIndexDictionary[newObjVertex] = objVertices.Count - 1;
            return objVertices.Count - 1;
        }
    }
}

A: Based on your description and the code you've posted, I'm going to bet that your problem isn't with the reading, the parsing, or the way you're adding things to your collections. The most likely problem is that your ObjMesh.Objvertex structure doesn't override GetHashCode. (I'm assuming that you're using code similar to http://www.opentk.com/files/ObjMesh.cs.
If you're not overriding GetHashCode, then your objVerticesIndexDictionary is going to perform very much like a linear list. That would account for the performance problem that you're experiencing.
I suggest that you look into providing a good GetHashCode method for your ObjMesh.Objvertex class.
See Why is ValueType.GetHashCode() implemented like it is? for information about the default GetHashCode implementation for value types and why it's not suitable for use in a hash table or dictionary.

A: Edit 3: The problem is NOT with the parsing.
It's with how you read the file. If you read it properly, it would be faster; however, it seems like your reading is unusually slow. My original suspicion was that it was because of excess allocations, but it seems like there might be other problems with your code too, since that doesn't explain the entire slowdown.
Nevertheless, here's a piece of code I made that completely avoids all object allocations:
static void Main(string[] args)
{
    long counter = 0;
    var sw = Stopwatch.StartNew();
    var sb = new StringBuilder();
    var text = File.ReadAllText("spacestation.obj");
    for (int i = 0; i < text.Length; i++)
    {
        int start = i;
        while (i < text.Length &&
            (char.IsDigit(text[i]) || text[i] == '-' || text[i] == '.'))
        { i++; }
        if (i > start)
        {
            sb.Append(text, start, i - start); //Copy data to the buffer

            float value = Parse(sb); //Parse the data

            sb.Remove(0, sb.Length); //Clear the buffer
            counter++;
        }
    }
    sw.Stop();
    Console.WriteLine("{0:N0}", sw.Elapsed.TotalSeconds); //Only a few ms
}

with this parser:
const int MIN_POW_10 = -16, int MAX_POW_10 = 16,
    NUM_POWS_10 = MAX_POW_10 - MIN_POW_10 + 1;
static readonly float[] pow10 = GenerateLookupTable();
static float[] GenerateLookupTable()
{
    var result = new float[(-MIN_POW_10 + MAX_POW_10) * 10];
    for (int i = 0; i < result.Length; i++)
        result[i] = (float)((i / NUM_POWS_10) *
                Math.Pow(10, i % NUM_POWS_10 + MIN_POW_10));
    return result;
}
static float Parse(StringBuilder str)
{
    float result = 0;
    bool negate = false;
    int len = str.Length;
    int decimalIndex = str.Length;
    for (int i = len - 1; i >= 0; i--)
        if (str[i] == '.')
        { decimalIndex = i; break; }
    int offset = -MIN_POW_10 + decimalIndex;
    for (int i = 0; i < decimalIndex; i++)
        if (i != decimalIndex && str[i] != '-')
            result += pow10[(str[i] - '0') * NUM_POWS_10 + offset - i - 1];
        else if (str[i] == '-')
            negate = true;
    for (int i = decimalIndex + 1; i < len; i++)
        if (i != decimalIndex)
            result += pow10[(str[i] - '0') * NUM_POWS_10 + offset - i];
    if (negate)
        result = -result;
    return result;
}

it happens in a small fraction of a second.
Of course, this parser is poorly tested and has these current restrictions (and more):

*

*Don't try parsing more digits (decimal and whole) than provided for in the array.

*No error handling whatsoever.

*Only parses decimals, not exponents! i.e. it can parse 1234.56 but not 1.23456E3.

*Doesn't care about globalization/localization. Your file is only in a single format, so there's no point caring about that kind of stuff because you're probably using English to store it anyway.
It seems like you won't necessarily need this much overkill, but take a look at your code and try to figure out the bottleneck. It seems to be neither the reading nor the parsing.

A: Have you measured that the speed problem is really caused by Convert.ToSingle?
In the code you included, I see you create lists and dictionaries like this:
normals = new List<Vector3>();
texCoords = new List<Vector2>();
objVerticesIndexDictionary = new Dictionary<ObjMesh.ObjVertex, int>();

And then when you read the file, you add in the collection one item at a time.
One of the possible optimizations would be to save total number of normals, texCoords, indexes and everything at the start of the file, and then initialize these collections by these numbers. This will pre-allocate the buffers used by collections, so adding items to the them will be pretty fast.
So the collection creation should look like this:
// These values should be stored at the beginning of the file
int totalNormals = Convert.ToInt32(textReader.ReadLine());
int totalTexCoords = Convert.ToInt32(textReader.ReadLine());
int totalIndexes = Convert.ToInt32(textReader.ReadLine());

normals = new List<Vector3>(totalNormals);
texCoords = new List<Vector2>(totalTexCoords);
objVerticesIndexDictionary = new Dictionary<ObjMesh.ObjVertex, int>(totalIndexes);

See List<T> Constructor (Int32) and Dictionary<TKey, TValue> Constructor (Int32).

A: This related question is for C++, but is definitely worth a read.
For reading as fast as possible, you're probably going to want to map the file into memory and then parse using some custom floating point parser, especially if you know the numbers are always in a specific format (i.e. you're the one generating the input files in the first place).

A: I tested .Net string parsing once and the fastest function to parse text was the old VB Val() function.  You could pull the relevant parts out of Microsoft.VisualBasic.Conversion Val(string)
Converting String to numbers

Comparison of relative test times (ms / 100000 conversions)
Double  Single  Integer    Int(w/ decimal point)
14      13      6          16                 Val(Str)
14      14      6          16                 Cxx(Val(Str)) e.g., CSng(Val(str))
22      21      17          e!                Convert.To(str)
23      21      16          e!                XX.Parse(str) e.g. Single.Parse()
30      31      31         32                 Cxx(str)

Val: fastest, part of VisualBasic dll, skips non-numeric,
ConvertTo and Parse: slower, part of core, exception on bad format (including decimal point)
Cxx: slowest (for strings), part of core, consistent times across formats


text:
Q: how do i return in my class based view after updating data here is my views.py function:
class ProfileUpdateView(UpdateView):
    model = UserProfile
    fields = ['first_name','last_name','username','gender','datetimepicker','p_photo','h_photo','subtitles','political_incline',
            'about_me','birthplace','lives_in','country','province','city','occupation',
            'relationship_status','website','phone_number','religious_belifs','political_incline',
            'facebook','twitter','RSS','dibble','spotify']

urls.py
url(r'^updateprofile/(?P<pk>\d+)/$',views.ProfileUpdateView.as_view(success_url='/postlist/')),

A: add a succes url as below in your view
success_url = reverse_lazy('the_page_required')

if you want to go to your detail view you can define this way also.
def get_success_url(self):
         return reverse('detail_view_url', kwargs={'pk': self.pk})


text:
Q: Use one icon size in Xcode I generate a lot of apps for clients. Nowadays there are a lot of different icon sizes (57, 72, 114, 144, 120, 152, 180) in addition to the 1024 sized icon that we upload to iTunesConnect.
In practice, though, I just design the large 1024-sized icon, then manually resize the icon to all of those other sizes and put them in an asset catalog.
That seems like pointless busy work. Is it possible to just give Xcode my 1024x1024 icon and let the tools autoresize it to a smaller version?

A: The macOS Terminal can really help you here.
If you wanted to resize an image named myicon1024x1024.png to an image of the same filetype, but 72x72, open Terminal, use the cd command to change directories to where your myicon1024x1024.png image is, then execute this command:
sips -z 72 72 myicon1024x1024.png --out myicon72x72.png

The "sips" command has a lot of other options, which can be googled or learned from its man page.
You can also make a bash script which could take the input of your file's name, then call sips once for each icon size you want to create. Of course, the output of this bash script ends up being the same as what you would get from makeappicon.com, so you'd still have to move the files into Xcode.

A: I don't think Xcode will allow this. However you can try using a web based application for resizing your icons simply. Try makeappicon.com. I am sure there are others out there.

A: It makes me very sad to write it here but I use Unity for it :-) Yes, 3D engine! Just create empty project, switch platform to iOS, set one 1024 icon and let build the project. Then you can drag and drop pre-made AppIcon into you XCode.


text:
Q: Asymptotic vs. bootstrap test statistic, size and power properties I am running a VAR based Granger non-causality tests. I've obtained asymptotic and bootstrap $p$ values for Wald joint test of 0 restriction on a set of lagged variables. It appears that bootstrap based models fail to reject Granger non-causality more often than the models based on asymptotic theory.
My question is: How do I evaluate the size and power properties of these approaches/tests?
I know how to evaluate the size properties of the bootstrap based tests, but I'm not sure how to approach the asymptotic theory based tests.


text:
Q: Problem with showing properties of linear transformation Let $F:K^3\rightarrow K^3$ be a linear transformation, such that

*

*$(F-\lambda I)(F-\mu I)\neq0,$

*$(F-\mu I)^2\neq 0,$

*$(F-\lambda I)(F-\mu I)^2=0.$
With this knowledge I want to show that

*

*$\lambda$, $\mu$ are eigenvalues of $F$,

*$Ker (F-\mu I)\subseteq Im(F-\mu I)$,

*$F$ has in a certain basis matrix
\begin{equation*}
\begin{pmatrix}
\lambda & 0 & 0  \\
0 & \mu & 1  \\
0  & 0 &\mu
\end{pmatrix}.
\end{equation*}
My attempt:

*

*It seems to be a consequence of the third assumption, but I am not sure.

*We know that $Ker(F-\mu I)=\{v\in K^3:F(v)-\mu v=0\}$ and $Im(F-\mu I)=\{(F-\mu I)(v):v\in K^3\}=\{(F(v)-\mu v):v\in K^3\}$. Then the inclusion seems to be trivial, but I am also not sure.

*Unfortunately I have no idea how to begin.

A: I will assume $\lambda\neq \mu$.
Note that the factors $F-k I$ commute for all $k$.

*

*Let $v$ be a vector $v\in K^3$ such that $(F-\lambda I)(F-\mu I)\,v=u\neq 0$. Then:
$$
(F-\mu I)\,u=(F-\lambda I)(F-\mu I)^2\,v=0
$$
so $u$ is an eigenvector for $\mu$.

Analogously, let $w$ be a vector $w\in K^3$ such that $(F-\mu I)^2\,w=z\neq 0$. Then:
$$
(F-\lambda I)\,z=(F-\lambda I)(F-\mu I)^2\,w=0
$$
so $z$ is an eigenvector for $\lambda$.

*In part 3. we can see that the dimension of $Ker(F-\mu I)$ is 1, otherwise $F$ would be diagonalizable. So $u\in Ker(F-\mu I)$ from previous point is a basis of $Ker(F-\mu I)$. But $u=(F-\mu I)v'$ where $v'=(F-\lambda I)v$ thus $u\in Im(F-\mu I)$.

NOTE: I do not like this proof because it uses part 3. but right now I cannot think of something easier.

*The polynomial $(F-\lambda I)(F-\mu I)^2$ from statement 3 is the characteristic polynomial, because it has degree three, and it does not vanish when removing any of its factors. Thus $\mu$ has multiplicity 2 and the diagonal of the Jordan form of $F$ is $(\lambda,\mu,\mu)^\top$. But if $F$ were diagonalizable, then $(F-\lambda I)(F-\mu I)=0$, which is in contradiction with statement 1.


text:
Q: What is wrong with this command of mine? "ffmpeg crop and drawtext" I have some command line to process video and it is getting some errors, can you help me to fix it?
@ECHO OFF
Setlocal EnableDelayedExpansion
set INPUT=D:\Shorts\code\INPUT
set OUTPUT=D:\Shorts\code\OUTPUT
:: encode video:
for %%a in ("%INPUT%\*.*") DO ffmpeg -i "%%a" -vcodec libx264 -pix_fmt yuv420p -g 60 -r 30 -b:v 1000k -acodec libmp3lame -b:a 128k -ar 48000 -metadata title="" -metadata artist="" -metadata album_artist="" -metadata album="" -metadata date="" -metadata track="" -metadata genre="" -metadata publisher="" -metadata encoded_by="" -metadata copyright="" -metadata composer="" -metadata performer="" -metadata TIT1="" -metadata TIT3="" -metadata disc="" -metadata TKEY="" -metadata TBPM="" -metadata language="eng" -metadata encoder="" -filter_complex "drawtext=text='Centered Text':x=(w-text_w)/2:y=(h-text_h)/2:fontsize=24:fontcolor=white, crop=ih*(9/16):ih" -crf 21 -c:a copy -f segment -segment_time 12 -reset_timestamps 1 -preset ultrafast "%output%\%%~na_%%03d.mp4"
pause

Here is the error message:


text:
Q: If $W_t$ is a Wiener process, why is the limit $\lim_{n \rightarrow \infty} \sum_{i=0}^{n-1} (W_{S_{i+1}} - W_{s_i})^2$ equal to $t$? For a Wiener process $W_s$ and a partition $\{ S_0, S_1, \dots, S_n \}$ of $[0,t]$, I have been told that
$$
\lim_{n \rightarrow \infty} \sum_{i=0}^{n-1} (W_{S_{i+1}} - W_{s_i})^2 = t
$$
I am aware that the above summation is the expression for the 'quadratic variation' of $W_t$, but I am not sure why this is equal to $t$?
Can anyone please tell me how this result is derived?

A: (I will adapt an answer of mine in another post to answer this question)
Let $\pi=\{s_0,\dots,s_n\}$ denote the partition, we assume also $s_0=0$, $s_n=t$.
We define $$S_\pi(W):=\sum_{i=1}^n(W{_{s_i}}-W_{s_{i-1}})^2.$$
We want to show that $$\lim_{n\rightarrow\infty}S_{\pi}=t\ \ \ \  \text {in}\ \ \ L^2(\Omega),$$
which means $\lim_{n\rightarrow\infty}E[(S_\pi-t)^2]=0$ (where $\Omega$ denotes the measure space on which $W$ is defined).
Defining $Y_i:=(W_{s_{i}}-W_{s_{i-1}})^2-(s_i-s_{i-1})$ we can write $S_\pi-t=\sum_{i=1}^{n}Y_i$. We observe that the random variables $Y_1,...,Y_n$ are independent since each $Y_i$ is a function of $W_{s_{i}}-W_{s_{i-1}}$ and by the definition of Brownian motion its increments are independent. Moreover
$$E[Y_i]=E[(W_{s_{i}}-W_{s_{i-1}})^2]-(s_i-s_{i-1})=\text{Var}(W_{s_{i}}-W_{s_{i-1}})-(s_i-s_{i-1})=0.$$
Thus
$$E[(S_\pi-t)^2]=\sum_{i=1}^{n}E[Y_i^2].$$
We know that the distribution of $W_{s_{i}}-W_{s_{i-1}}$ is $N(0,s_{i}-s_{i-1})$ thus the distribution of $$Z:=\frac{W_{s_{i}}-W_{s_{i-1}}}{\sqrt{s_{i}-s_{i-1}}}$$ is $N(0,1)$. (Z doesn't depend on $i$ because we are interested only in its distribution and for every $i$ it is a standard normal). Using this fact we write
$$\sum_{i=1}^{n}E[Y_i^2]=\sum_{i=1}^n E[\ [(W_{s_{i}}-W_{s_{i-1}})^2-(s_{i}-s_{i-1})]^2\ ]=\\ \sum_{i=1}^n (s_{i}-s_{i-1})^2\  E[\ [\left( \frac{W_{s_{i}}-W_{s_{i-1}}}{\sqrt{s_i-s_{i-1}}}\right)^2-1]^2\ ]=\\
 \sum_{i=1}^n (s_{i}-s_{i-1})^2\  E[(Z^2-1)^2]=C\sum_{i=1}^n (s_{i}-s_{i-1})^2\leq \\ C \vert\vert\pi\vert\vert\sum_{i=1}^n s_{i}-s_{i-1}=Ct\vert\vert\pi\vert\vert,$$ where $C:=E[(Z^2-1)^2]$ is a constant and
$\vert\vert\pi\vert\vert$ denotes the norm of the partition. Now if
$n\rightarrow\infty$, then $\vert\vert\pi\vert\vert\rightarrow0$ and we have the result.


text:
Q: Solve for A as a function of x. Suppose $A(x)=x^2+\frac{4V}{x}$ where A is the surface area and V is a fixed volume. If $x=2^\frac{1}{3}\cdot V^\frac{1}{3}$ At this point I rewrote the formula for A with a common denominator $A=\frac{x^3+4V}{x}$ And then substituting for x I get $A=\frac{(2^\frac{1}{3}\cdot V^\frac{1}{3})^3+4V}{2^\frac{1}{3}\cdot V^\frac{1}{3}}$ simplifying I get $\frac{6V}{2^\frac{1}{3}\cdot V^\frac{1}{3}}$ Now can this last expression not be written as one product $2^1\cdot 3^1\cdot V^1\cdot 2^\frac{-1}{3}\cdot V^\frac{-1}{3}$ And so $A=3\cdot 2^\frac{2}{3}\cdot V^\frac{2}{3}$
The answer is $A=3\cdot 2^\frac{1}{3}\cdot V^\frac{2}{3}$ I'm having trouble where I've made the error with the fractional powers.


text:
Q: What about a sentence.like ...I like going to "new" places with "old" friends--- What can we call the above
I ENJOY GOING TO "NEW" PLACES WITH "OLD" FRIENDS
and can you think of other examples?

A: I would just refer to it as juxtaposition, I think? I don't know that there's a particularly easy way to refer to the contrasting of opposite words like these ones.

A: You're probably looking for the word 'aphorism'. There are entire books of aphorisms, online and off, and so no need to think of examples. As an example of such a book, consider Aphorisms, by Hippocrates. Often, aphorisms become cliches, and in the process lose their meaning. Exploiting this circumstance can deliver rhetorical and humorous profits:
"You must be the change you want to find in your pocket."


text:
Q: Derive $\dim(W_1\cap W_2\cap W_3)$?
How to get $\dim(W_1\cap W_2\cap W_3)$?

-edit-
$W_1=\{(x,y,z)|x+y-z=0\}$
$W_2=\{(x,y,z)|3x+y-2z=0\}$
$W_3=\{(x,y,z)|x-7y+3z=0\}$

A: As pointed out in the comments your formular is false. In your case it holds that $W_1\cap W_2\cap W_3=\{(0,0,0)\}$, so dim($W_1\cap W_2\cap W_3)=$dim$(\{(0,0,0)\})= 0$.


text:
Q: What is the difference in between those pieces of code? What is the difference in between:
k = setInterval(function(){loop();},100);

and
k = setInterval(loop(),100);

Why does the second one run once, like the setTimeout() function and the first one every 1/10 of a second?

A: In second one you are actually executing loop before setInterval is called, so you are passing result of the loop to the setInterval
More similar would be
k = setInterval(function(){loop();},100);

k = setInterval(loop,100);

A: first example allows you to do some work before calling loop and to pass some arguments if necessary
second one requires a function object as a 1st parameter and you cannot pass anything inside the brackets.
1st one is more widely spread pattern than 2nd (which is a little bit obsolete)

A: Lets checkout how doest JS run this code:
Fist way -
JS see setInterval - it should have 2 arguments and timer - in first variant everythink is trivial - you passed a function to be called on each interval and timer.
Lets check second variant - again setInterval, 2 params . But this time you dont pass link to function but called function and the result of this function will be passed to the setInterval. As you called function - it runs once, as it doesent return function setInterval cant run anything.


text:
Q: Tool for analyzing C++ sources (MSVC) I need a tool which analyzes C++ sources and says what code isn't used. Size of sources is ~500mb

A: PC-Lint is good.  If it needs to be free/open source your choices dwindle.  Cppcheck is free, and will check for unused private functions.  I don't think that it looks for things like uninstantiated classes like PC-Lint.

A: Once again, I'll throw AQTime into the discussion. Has static code analysis for most, if not all, of the supported languages. I didn't really go into that part though, I mainly used the dynamic profilers (memory, performance and so on).

A: You could use a code coverage tool  (dynamic analysis) to get an idea of what code isn't
being executed, and then hand analyze to see if that code is really useless.
If you want a static analysis, you need a tool that can read the entire
500Mb of source code (est. 20 million lines? Wow!) and compute a
conservative estimate of what is used.  This requires doing a points-to
analysis over the entire system.
Here's why: If you leave out any module Z, and
decide that FOO is unused, you
might find out later that Z happened to be the one that used FOO,
or more subtly, Z copied a pointer value that happened to have
&FOO in it to a third module M that in turn called the "unused" function
throught the pointer.
What this means is that no static analysis tool that reads just
single modules (compilation units) can answer this question safely.
And at your scale, you can't afford to make dumb mistakes.
My company, Semantic Designs has done points-to analysis for 35 million line systems
of C code using our DMS Software Reengineering Toolkit.  DMS
can read very large systems of source code.  It required
a custom tool, not so much because the source code was in an odd (archiac)
dialect of C++ (systems in extremely modern dialects can't be this big,
not enough time to code them!), but rather because in very large systems
there are other peculiar factors at play.  For the C system we did,
there was a custom dynamic linker, and that affected the points-to analysis,
which in turn had to be customized.
Because systems of the scale you are discussing alway have surprises like this (BIBSEH: "Because In Big Systems, Everything Happens"), you will
likely need a custom tool to answer the question.   DMS is designed
to be customized.
See http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html
and http://www.semanticdesigns.com/Products/FrontEnds/CppFrontEnd.html

A: Code coverage tool is what you need, but you will have to run our program through all functionality and see what is repoted as unused.  Since the code could be DLL exported functions you will have to make sure nothing uses them externally.  Some code coverage tools: Purify, CTC++, Boundschecker may have code coverage functionality if I remember right and a bunch of other tools.
Be very careful about removing any function that may have been exported without knowing what external program may be linking/using it.


text:
Q: Error while trying to play a video file uploaded to FTP server using FTPWebRequest When I try to play a video uploaded to the FTP server using .net code, it says 'Can't play. Item is unplayable, please reacquire the content. 0xc00d36e5'.
Following is the code that I am using to upload a video file to the FTP server:
Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
    Try
        Dim posFile As HttpPostedFile = Nothing
        posFile = MyFile.PostedFile

        Dim strFileName As String = ""
        strFileName = posFile.FileName

        Dim ext As String = ""
        Dim fileName As String = ""

        ext = System.IO.Path.GetExtension(strFileName)
        fileName = "Vid_" + Now().ToString("yyyyMMddHHmmsss") & ext

        If MyFile.PostedFile.FileName = "" Then
            lblMsg.Text = "Please select a file to upload."
            lblMsg.Visible = True
            lblMsg.CssClass = "error"
        Else
            Dim fileBytes As Byte() = Nothing
            Using fileStream As New StreamReader(posFile.InputStream)
                fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())
                fileStream.Close()
            End Using

            Try
                Dim ftp As String = System.Configuration.ConfigurationManager.AppSettings("FtpMediaServerURL") //ftp://www.server.com

                Dim ftpFolder As String = "/media/"

                Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftp & ftpFolder & fileName), FtpWebRequest)
                request.Method = WebRequestMethods.Ftp.UploadFile

                request.Credentials = New NetworkCredential(System.Configuration.ConfigurationManager.AppSettings("FtpMediaServerUserName"), System.Configuration.ConfigurationManager.AppSettings("FtpMediaServerPassword"))
                request.ContentLength = fileBytes.Length
                request.UsePassive = True
                request.KeepAlive = False
                request.UseBinary = True
                request.ServicePoint.ConnectionLimit = fileBytes.Length
                request.EnableSsl = False

                Using requestStream As Stream = request.GetRequestStream()
                    requestStream.Write(fileBytes, 0, fileBytes.Length)
                    requestStream.Close()
                End Using

                Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
                response.Close()

                lblMsg.Text = "Your file has been uploaded successfully."
                lblMsg.Visible = True
                lblMsg.CssClass = "confirmation"

            Catch ex As Exception
                lblMsg.Text = "An Error occured while uploading your file. Please try again."
                lblMsg.Visible = True
                lblMsg.CssClass = "error"
            End Try
        End If
    Catch ex As Exception
       //Handle Exception
    End Try
End Sub

Can anyone point out what I am doing wrong or else I am missing anything?

A: Got this issue resolved!
Instead of uploading the video file directly to the FTP server, what I did was to upload the video to a temporary location somewhere on the website server and then transfer it to the FTP server using the FTPWebRequest.


text:
Q: JNI DETECTED ERROR IN APPLICATION: bad arguments & JNI ERROR (app bug): accessed stale global reference Recently I'm learning Android JNI. I wrote a demo and tried to call some Android SDK methods using JNI, then some stranges crash occurred.
1. Call IActivityManager.getLaunchedFromUid(IBinder token) using JNI, fail on some devices!
2. Call IPackageManager.getLaunchedFromUid(String packageName, int flags) using JNI, almost fail on all devices!
Here is my Java code.
public class HelloJni extends Activity {

    private static final String TAG = "HelloJni";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_jni);
        TextView tv = (TextView) findViewById(R.id.hello_textview);

        try {
            Class<?> activityManagerNativeClass = Class.forName("android.app.ActivityManagerNative");
            Field gDefaultField = activityManagerNativeClass.getDeclaredField("gDefault");
            gDefaultField.setAccessible(true);
            Object gDefault = gDefaultField.get(null);
            // gDefault is an android.util.Singleton Object
            Class<?> singleton = Class.forName("android.util.Singleton");
            // get the mInstance from ActivityManagerNative.gDefault. The mInstance implements IActivityManager
            Field mInstanceField = singleton.getDeclaredField("mInstance");
            mInstanceField.setAccessible(true);
            Object rawIActivityManager = mInstanceField.get(gDefault);

            // get ActivityToken
            Class<?> activityClazz = Class.forName("android.app.Activity");
            Method getActivityTokenMethod = activityClazz.getDeclaredMethod("getActivityToken");
            getActivityTokenMethod.setAccessible(true);
            Object activityToken = getActivityTokenMethod.invoke(this);

            Class<?> iActivityManagerClazz = Class.forName("android.app.IActivityManager");
            Method getLaunchedFromUidMethod = iActivityManagerClazz.getDeclaredMethod("getLaunchedFromUid", IBinder.class);
            getLaunchedFromUidMethod.setAccessible(true);
            // Call IActivityManager.getLaunchedFromUid(IBinder token) using reflection, success!
            int uid = (int) getLaunchedFromUidMethod.invoke(rawIActivityManager, activityToken);
            Log.d(TAG, "uid=" + uid);

            Class<?> iPackageManagerClazz = Class.forName("android.content.pm.IPackageManager");
            Method getPackageUidMethod = iPackageManagerClazz.getDeclaredMethod("getPackageUid", String.class, int.class);
            getPackageUidMethod.setAccessible(true);
            Class<?> activityThreadClazz = Class.forName("android.app.ActivityThread");
            Field sPackageManagerFiled = activityThreadClazz.getDeclaredField("sPackageManager");
            sPackageManagerFiled.setAccessible(true);
            Method method = activityThreadClazz.getDeclaredMethod("currentActivityThread");
            method.setAccessible(true);
            Object activityThread = method.invoke(null);
            Object sPackageManager = sPackageManagerFiled.get(activityThread);
            // Call IPackageManager.getLaunchedFromUid(IBinder token) using reflection, success!
            int packageUid = (int) getPackageUidMethod.invoke(sPackageManager, "com.example.hellojni", 0);
            Log.d(TAG, "packageUid=" + packageUid);

            // Call IActivityManager.getLaunchedFromUid(IBinder token) using JNI, fail on some devices!
            // Call IPackageManager.getLaunchedFromUid(String packageName, int flags) using JNI, almost fail on all devices!
            packageUid = getPackageUid(sPackageManager);
            tv.setText("uid=" + getLaunchedFromUid(rawIActivityManager, activityToken) + " packageUid=" + packageUid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public native int getPackageUid(Object iPackageManager);

    public native int getLaunchedFromUid(Object iActivityManager, Object activityToken);

    static {
        System.loadLibrary("hello-jni");
    }
}

Here is my C++ code.
extern "C" {
    JNIEXPORT jint JNICALL Java_com_example_hellojni_HelloJni_getPackageUid(JNIEnv * env, jobject thisObject, jobject iPackageManager);
    JNIEXPORT jint JNICALL Java_com_example_hellojni_HelloJni_getLaunchedFromUid(JNIEnv * env, jobject thisObject, jobject iActivityManager, jobject activityToken);
};

JNIEXPORT jint JNICALL Java_com_example_hellojni_HelloJni_getPackageUid(JNIEnv * env, jobject thisObject, jobject iPackageManager) {
    jclass IPackageManagerClazz = env->FindClass("android/content/pm/IPackageManager");
    jmethodID mid = env->GetMethodID(IPackageManagerClazz, "getPackageUid", "(Ljava/lang/String;I)I");
    jint uid = env->CallIntMethod(iPackageManager, mid, "com.example.hellojn", 0);
    return uid;
}

JNIEXPORT jint JNICALL Java_com_example_hellojni_HelloJni_getLaunchedFromUid(JNIEnv * env, jobject thisObject, jobject iActivityManager, jobject activityToken) {
    jclass IActivityManagerClazz = env->FindClass("android/app/IActivityManager");
    jmethodID midGetLaunchedFromUid = env->GetMethodID(IActivityManagerClazz, "getLaunchedFromUid", "(Landroid/os/IBinder;)I");
    int uid = env->CallIntMethod(iActivityManager, midGetLaunchedFromUid, activityToken);
    return uid;
}

Crash log when calling IActivityManager.getLaunchedFromUid(IBinder token) using JNI
E/art: JNI ERROR (app bug): attempt to pass an instance of android.app.IActivityManager as argument 1 to int android.app.IActivityManager.getLaunchedFromUid(android.os.IBinder)
E/art: JNI DETECTED ERROR IN APPLICATION: bad arguments passed to int android.app.IActivityManager.getLaunchedFromUid(android.os.IBinder) (see above for details)
E/art:     from int com.example.hellojni.HelloJni.getLaunchedFromUid(java.lang.Object, java.lang.Object)
E/art: "main" prio=5 tid=1 Runnable
E/art:   | group="main" sCount=0 dsCount=0 obj=0x755b12a0 self=0xf4bf6a00
E/art:   | sysTid=23997 nice=-1 cgrp=default sched=0/0 handle=0xf75f7de4
E/art:   | state=R schedstat=( 172765773 2780770 100 ) utm=12 stm=5 core=9 HZ=100
E/art:   | stack=0xff370000-0xff372000 stackSize=8MB
E/art:   | held mutexes= "mutator lock"(shared held)
E/art:     at com.example.hellojni.HelloJni.getLaunchedFromUid(Native method)
E/art:     at com.example.hellojni.HelloJni.onCreate(HelloJni.java:64)
E/art:     at android.app.Activity.performCreate(Activity.java:6288)
E/art:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)

Crash log when calling IPackageManager.getLaunchedFromUid(String packageName, int flags) using JNI
E/art: JNI ERROR (app bug): accessed stale global reference 0xf392b302 (index 44224 in a table of size 300)
E/art: JNI DETECTED ERROR IN APPLICATION: use of deleted global reference 0xf392b302
E/art:     from int com.example.hellojni.HelloJni.getPackageUid(java.lang.Object)
E/art: "main" prio=5 tid=1 Runnable
E/art:   | group="main" sCount=0 dsCount=0 obj=0x755b12a0 self=0xf4bf6a00
E/art:   | sysTid=24310 nice=-1 cgrp=default sched=0/0 handle=0xf75f7de4
E/art:   | state=R schedstat=( 48943077 1340463 65 ) utm=1 stm=3 core=9 HZ=100
E/art:   | stack=0xff370000-0xff372000 stackSize=8MB
E/art:   | held mutexes= "mutator lock"(shared held)
E/art:     at com.example.hellojni.HelloJni.getPackageUid(Native method)
E/art:     at com.example.hellojni.HelloJni.onCreate(HelloJni.java:63)
E/art:     at android.app.Activity.performCreate(Activity.java:6288)
E/art:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
E/art:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2500)
E/art:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2613)
E/art:     at android.app.ActivityThread.access$900(ActivityThread.java:180)
E/art:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
E/art:     at android.os.Handler.dispatchMessage(Handler.java:111)
E/art:     at android.os.Looper.loop(Looper.java:207)
E/art:     at android.app.ActivityThread.main(ActivityThread.java:5710)
E/art:     at java.lang.reflect.Method.invoke!(Native method)
E/art:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)

Although we may not do such things in real application, I'm so curious about why these crashes occurred.
Thanks for your help!


text:
Q: how to use a shell variable inside another eval block I want to evaluate a variable conditionally for use in my docker image build
RUN ARCHFLAG="$(uname -m)" && ARCH=$([ $ARCHFLAG == "aarch64" ] &&  echo "arm64" ||  echo $ARCHFLAG) && curl -sL "https://get.helm.sh/helm-v${HELM_VERSION}-linux-${ARCH}.tar.gz" | tar -xvz && \
    mv linux-${ARCH}/helm /usr/bin/helm && \
    chmod +x /usr/bin/helm && \
    rm -rf linux-${ARCH}

I get the error
------
 > [ 5/13] RUN ARCHFLAG="$(uname -m)" && ARCH=$([ ARCHFLAG == "aarch64"] &&  echo "arm64" ||  echo $ARCHFLAG) && curl -sL "https://get.helm.sh/helm-v3.6.3-linux-${ARCH}.tar.gz" | tar -xvz &&     mv linux-${ARCH}/helm /usr/bin/helm &&     chmod +x /usr/bin/helm &&     rm -rf linux-${ARCH}:
#8 0.248 /bin/sh: 1: [: aarch64: unexpected operator
#8 1.295
#8 1.295 gzip: stdin: not in gzip format
#8 1.296 tar: Child returned status 1
#8 1.296 tar: Error is not recoverable: exiting now

I've enclosing it as a string too, in the IDE the first $ARCHFLAG shows up in the same colours as rest of the strings while the second $ARXCHFLAG does show up as variable.

A: You are using [ $ARCHFLAG == "aarch64" ]. This would work in bash, or in a "halfway POSIX shell" (for instance, a bash which is started in POSIX mode and implements the == operator), but in a POSIX shell, you would get _ unexpected operator_. From the error message you posted, we see that you are not executing bash. I suggest that you either switch to bash, or write the test as [ "$ARCHFLAG" = "aarch64" ].

A: I don't have aarch64 and arm64
However I tried your script using bash.exe at windows
#!/bin/bash
set -x
unset -f uname
uname ()
{
        echo -n aarch64
}
HELM_VERSION=3.9.2
ARCHFLAG="$(uname -m)" && ARCH=$([ "$ARCHFLAG" == "aarch64" ] &&  echo "arm64" ||  echo $ARCHFLAG) && curl -sL "https://get.helm.sh/helm-v${HELM_VERSION}-linux-${ARCH}.tar.gz" | tar -xvz && \
echo mv linux-${ARCH}/helm /usr/bin/helm && \
echo chmod +x /usr/bin/helm && \
echo rm -rf linux-${ARCH}
set +x

Sample output:
$ ./73542210.sh
-bash 13 unset -f uname
-bash 13 HELM_VERSION=3.9.2
--bash 13 uname -m
--bash 13 echo -n aarch64
-bash 13 ARCHFLAG=aarch64
--bash 13 '[' aarch64 == aarch64 ']'
--bash 13 echo arm64
-bash 13 ARCH=arm64
-bash 13 curl -sL https://get.helm.sh/helm-v3.9.2-linux-arm64.tar.gz
-bash 13 tar -xvz
linux-arm64/
linux-arm64/helm
linux-arm64/LICENSE
linux-arm64/README.md
-bash 13 echo mv linux-arm64/helm /usr/bin/helm
mv linux-arm64/helm /usr/bin/helm
-bash 13 echo chmod +x /usr/bin/helm
chmod +x /usr/bin/helm
-bash 13 echo rm -rf linux-arm64
rm -rf linux-arm64
-bash 13 set +x
$ ls -ltr linux-arm64/helm
-rwxr-xr-x 1 murugesan openssl 45875200 Jul 21 23:11 linux-arm64/helm
$ ls -ltr linux-arm64
total 44816
-rwxr-xr-x 1 murugesan openssl 45875200 Jul 21 23:11 helm
-rw-r--r-- 1 murugesan openssl     3367 Jul 21 23:21 README.md
-rw-r--r-- 1 murugesan openssl    11373 Jul 21 23:21 LICENSE

I have used mv and rm commands using echo.
I used uname function to test your script.
Output obtained without using set -x and set +x commands.
Updated script:
$ rm -rf linux-arm64
$ ./73542210.sh
linux-arm64/
linux-arm64/helm
linux-arm64/LICENSE
linux-arm64/README.md
mv linux-arm64/helm /usr/bin/helm
chmod +x /usr/bin/helm
rm -rf linux-arm64
$ ./73542210.sh
ls -ltr linux-arm64
total 44816
-rwx---r-x+ 1 murugesan openssl 45875200 Jul 21 23:11 helm
-rw----r--+ 1 murugesan openssl     3367 Jul 21 23:21 README.md
-rw----r--+ 1 murugesan openssl    11373 Jul 21 23:21 LICENSE


text:
Q: Fastest way in JS to detect number of leading zeros I am working on a project where I need to quickly check if there are a certain number of leading zeros in string. I have had success using regex:
var regex = new RegExp('^[0]{' + difficulty + '}.+');
if (regex.test(hash))

Also with substring and repeat:
if (hash.substring(0, difficulty) === '0'.repeat(difficulty))

For my specific purpose, speed is the most important element. I must find the fastest way to check if the number of leading zeros matches the difficulty. I have ran benchmark tests on both methods, but the results fluctuate in a way that I cannot tell which one is better. Also, if there is another better method, please let me know. Thanks in advance.

A: if (Number(n).toString() !== n){
    console.log("leading 0 detected")
}

this may not be the fastest, but simpler than writing a function

A: function detect(hash, difficulty) {
    for (var i = 0, b = hash.length; i < b; i ++) {
        if (hash[i] !== '0') {
            break;
        }
    }
    return i === difficulty;
}

Your methods have drawbacks that you construct intermediate objects and do heavy arithmetics (especially with regexp but with substring and full string comparisons as well). This one should be quite fast.


text:
Q: escaping dots in json evaluation in WSO2 Datamapper I have a JSON object as payload, which contains a dot (".") in one of the identifier names and I want to map this object to another JSON object using the datamapper mediator.
The problem I am facing is that the JSON evaluation uses the dot notation for nested elements. The field "example":
{ "a": { "b": "example"} }

is evaluated by asking for a.b
My object however looks like:
{ "a": { "b.c": "example"} }

I cannot evaluate a.b.c, because it thinks b and c are two seperate nested elements.
Escaping this identifier name in the datamapper.dmc javascript code does not seem to work. No matter what I try ('', "", [''], [""]) I get the error:
Error while reading input stream. Script engine unable to execute the script javax.script.ScriptException: <eval>:8:43 Expected ident but found [

A: This may not be exact solution as I did not specifically tried it for Data Mapper, but I had similar problem in WSO2 Property Mediator while parsing incoming JSON to get a value and set it to property. I was able to parse such JSON using following syntax
json-eval($.A.['b.c'])

Where 'A' is JSON object containing 'b.c' JSON element.
I saw you mentioned that you already tried something similar, but just wanted to give my working example in case it helps.


text:
Q: How to use Media queries with Material UI makestyles I'm pretty bad a CSS/styling and would appreciate some help here
I was trying to change the height of certain cards based on the screen width.
using
let mainContainerHeight = window.innerWidth < 750 ? "50vh" : "80vh"

and assigning it to the height attribute, but it only applies when I refresh the page and not as a resize it.
I tried googling media queries and material UI but it looks completely different and tbh confusing...
https://material-ui.com/components/use-media-query/
Is there an easy way to just inject media queries into my code below??
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';

let mainContainerHeight = window.innerWidth < 750 ? "50vh" : "80vh"

const useStyles = makeStyles({
  root: {
    minWidth: 275,
    border: "3px solid black",
    borderRadius:"5px",
    boxShadow: "10px 5px 5px red",
    padding: 0,
    height: mainContainerHeight,
    overflow:"scroll"
  },
  small:{
    border: "5px solid black",
    borderRadius:"5px",
    boxShadow: "10px 5px 5px grey",
    marginBottom:"5px",
    marginTop:"8px",
    padding:"0px"
  },
  nomination:{
    border: "3px solid black",
    borderRadius:"5px",
    boxShadow: "10px 5px 5px red",
    padding: 0,
    height:mainContainerHeight,
    overflow:"scroll"
  },
  noPadding:{
    padding:"0px !important",
  }
});

export default function SimpleCard(props) {
  const classes = useStyles();
  const style = props.small ? classes.small : props.nomination ? classes.nomination : classes.root
  const padding = props.noPadding ? classes.noPadding : ""

  return (
    <Card className={style}>
      <CardContent className={padding}>
       {props.children}
      </CardContent>
    </Card>
  );
}

A: You could use 50vh as your default height and then use theme.breakpoints.up(750) to change it to 80vh.
const useStyles = makeStyles((theme) => {
  return {
    root: {
      minWidth: 275,
      border: "3px solid black",
      borderRadius: "5px",
      boxShadow: "10px 5px 5px red",
      padding: 0,
      height: "50vh",                    // primary height
      overflow: "scroll",
      [theme.breakpoints.up(750)]: {
        height: "80vh"                   // secondary
      }
    },
    ...
  };
});


text:
Q: Why does this seemingly recursive code work, in skimage's source? In the module _denoise.py of skimage I found the following piece of code:
def estimate_sigma(image, average_sigmas=False, multichannel=False):
        # some more code here
        sigmas = [estimate_sigma(image[..., c], multichannel=False)...
    return _sigma_est_dwt(detail_coeffs, distribution='Gaussian')

Inside estimate_sigma there's an estimate_sigma? How and why does that work? The imports are
import scipy.stats
import numpy as np
from math import ceil
from .. import img_as_float
from ..restoration._denoise_cy import _denoise_bilateral, _denoise_tv_bregman
from .._shared.utils import skimage_deprecation, warn
import pywt
import skimage.color as color
import numbers

which doesn't seem to sneak in any new functions.

A: Note that the recursive call of estimate_sigma is inside an if-clause:
if multichannel:
    sigmas = [estimate_sigma(image[..., c], multichannel=False)...
...
return _sigma_est_dwt(detail_coeffs, distribution='Gaussian')

Case A) If we call estimate_sigma with multichannel=False, the function won't get inside the if-clause, thus won't invoke itself and will return reaching the end of its body.
Case B) If we call estimate_sigma with multichannel=True the condition will succeed, so estimate_sigma will call itself. As seen from the piece of source above, when estimate_sigma calls itself, it passes multichannel as False. It means that during the recursive invocation "case A" will happen. This time the program will not enter the above if block and recursion will end, ending execution of the function and returning.

Basically the idea is: if we've got multiple channels, let's divide them into separate ones and perform sigma estimation on each channel


text:
Q: Есть ли альтернативный способ добавления в кортеж? Пытаюсь добавить значения в кортеж так:
#!/usr/local/lib/python3

q = (1, 2, 3)
e = q + (5,)
print(e)

Этот способ работает, но не красиво. Потому что приходится после пятёрки добавлять запятую. А без запятой этот способ не работает:

TypeError: can only concatenate tuple (not "int") to tuple

Скажите пожалуйста, не существует ли другого способа добавления значения в кортеж?
UPD:
#!/usr/local/lib/python3

q = (1, 2, 3)
print(id(q))
q = q + (5,)
print(q)
print(id(q))

видно, что id не изменился: https://i.yapx.ru/DZVAd.png

A: Кортеж (tuple) это неизменяемая коллекция, поэтому вопрос о добавлении в нее элемента просто странный :)
А вот тут, вы например:
q = (1, 2, 3)
e = q + (5,)

Не добавили элемент в кортеж, а создали новый.

Аналогом кортежа будет список (list):
q = [1, 2, 3]
q.append(5)
print(q)  # [1, 2, 3, 5]

UPD.
Создается новый объект:
>>> a = (1, 2, 3)
>>> hex(id(a))
'0x202dfc73870'
>>> a += (5,)
>>> hex(id(a))
'0x202dfc740e8'

Или вот еще:
>>> a = (1, 2, 3)
>>> hex(id(a))
'0x202dfc73900'
>>> b = a + (5,)
>>> hex(id(a))
'0x202dfc73900'
>>> hex(id(b))
'0x202dfc740e8'

У a id не поменялся, т.к. по этой ссылке остался старый кортеж ((1, 2, 3)), но в b уже новый, который был создан при сложении кортежей


text:
Q: Почему при применении градиента обрезается фигура? Почему при применении градиента вырезается часть окружности?

<svg width="900" height="200" viewBox="0 0 900 200" style='border: 1px solid black' >
 <defs>
    <radialGradient id="MyGradient"
                    fx="25%" fy="25%" r="30%" >
      <stop offset="0%" stop-color="white"/>
      <stop offset="100%" stop-color="blue"/>
    </radialGradient>
  </defs>
  <circle cx="75" cy="75" r="70"
          fill="url(#MyGradient)" />
</svg>

A: Из-за параметров заданных в MyGradient fx="25%" fy="25%" r="30%" Хотите, чтобы не обрезалось (Элемент был круглым) задайте r="100%"

<svg width="900" height="200" viewBox="0 0 900 200" style='border: 1px solid black' >
 <defs>
    <radialGradient id="MyGradient"
                    fx="25%" fy="25%" r="100%" >
      <stop offset="0%" stop-color="white"/>
      <stop offset="100%" stop-color="blue"/>
    </radialGradient>
  </defs>
  <circle cx="75" cy="75" r="70"
          fill="url(#MyGradient)" />
</svg>

A: Немного теории:

Атрибут gradientUnits, который описывает систему измерений, которую
  Вы собираетесь использовать, когда описываете размеры или ориентацию
  градиента. Данный атрибут принимает два возможных значения:
  userSpaceOnUse или objectBoundingBox - дефолтное значение.
  objectBoundingBox автоматически адаптирует градиент к размеру
  объекта, так что Вы можете указать координаты в виде значений от 0 до
  1, и браузер автоматически их отпозиционирует. userSpaceOnUse
  позиционирует градиент в абсолютных единицах измерения.

Другими словами, если не указан атрибут gradientUnits он примет значение по умолчанию, - gradientUnits="objectBoundingBox" и все значения атрибутов градиента нужно указывать либо в процентах, либо в долях от единицы. Поэтому можно написать r="100%" или r="1", либо совсем не указывать радиус и он примет значение по умолчанию r="100%"

<svg width="900" height="200" viewBox="0 0 900 200" style='border: 1px solid black'>
 <defs>
    <radialGradient id="MyGradient"
                    fx="0.25" fy="0.25" r="1" >
      <stop offset="0" stop-color="white"/>
      <stop offset="1" stop-color="blue"/>
    </radialGradient>
  </defs>
  <circle cx="75" cy="75" r="70"
          fill="url(#MyGradient)" />
</svg>

атрибуты fx="0.25" fy="0.25" указывают координаты начальной точки радиального градиента, то есть откуда будут рисоваться цветные круги.  Значение по умолчанию fx="50%" fy="50%", центр объекта, опять же можно не указывать.

<svg width="900" height="200" viewBox="0 0 900 200" style='border: 1px solid black' >
 <defs>
    <radialGradient id="MyGradient"
                    fx="0.5" fy="0.5" r="1" >
      <stop offset="0" stop-color="white"/>
      <stop offset="1" stop-color="blue"/>
    </radialGradient>
  </defs>
  <circle cx="75" cy="75" r="70"
          fill="url(#MyGradient)" />
</svg>

Анимация градиента
Для анимации градиента можно использовать любые атрибуты.
В примере ниже для анимации использованы атрибуты fx, fy
Получилась имитация движения источника света

<svg width="200" height="200" viewBox="0 0 200 200"  >
 <defs>
    <radialGradient id="MyGradient"
                    fx="25%" fy="25%" r="100%" >
      <stop offset="0%" stop-color="#FFFFDB" stop-opacity="0.45"/>
      <stop offset="45%" stop-color="#C14092" stop-opacity="0.95"/>
     <animate attributeName="fx" begin="0s" dur="10s" values="15%;75%;75%;15%;15%" repeatcount="indefinite" />
    <animate attributeName="fy" begin="0s" dur="10s" values="10%;55%;55%;5%;5%" repeatcount="indefinite" />
    </radialGradient>
  </defs>
  <circle cx="75" cy="75" r="70"
          fill="url(#MyGradient)" />
</svg>

Пример сложной анимации градиента
Работает во всех современных браузерах, включая Edge
Здесь использована система координат для градиента userSpaceOnUse поэтому значения атрибутов указаны в пикселях
<radialGradient id="sky-gradient" cx="737.45" cy="94.64" r="800.05" gradientUnits="userSpaceOnUse">

Отражение градиента реализовано с помощью вырезания прямоугольника с градиентом
<clipPath id="reflection">
      <rect width="1000" height="500"/>
    </clipPath>
<g clip-path="url(#reflection)" class="reflection">
      <use xlink:href="#sky" class="sky"></use>
      <rect id="ocean_light" class="ocean"  width="1000" height="500"/>
    </g>

и его переворачивания на 180 градусов вокруг оси Х

.reflection {
  -webkit-transform: scaleY(-1);
          transform: scaleY(-1);
  -webkit-transform-origin: 500px 500px;
          transform-origin: 500px 500px;
}

Ниже полный код:

body {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  height: 100vh;
  width: 100vw;
  background: #456;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
}
body:before {
  content: "";
  display: block;
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/17271/cork-wallet.png");
  mix-blend-mode: multiply;
}

.world {
  width: 100vw;
  height: 80vh;
  vertical-align: bottom;
}

@-webkit-keyframes sunset {
  25%,
  60% {
    -webkit-transform: rotateZ(180deg);
            transform: rotateZ(180deg);
  }
  80%,
  100% {
    -webkit-transform: rotateZ(360deg);
            transform: rotateZ(360deg);
  }
}

@keyframes sunset {
  25%,
  60% {
    -webkit-transform: rotateZ(180deg);
            transform: rotateZ(180deg);
  }
  80%,
  100% {
    -webkit-transform: rotateZ(360deg);
            transform: rotateZ(360deg);
  }
}
.sun {
  fill: #ffd7ac;
}

.sky {
  -webkit-transform-origin: 500px 500px;
          transform-origin: 500px 500px;
  -webkit-animation: sunset 15s infinite;
          animation: sunset 15s infinite;
}

.reflection {
  -webkit-transform: scaleY(-1);
          transform: scaleY(-1);
  -webkit-transform-origin: 500px 500px;
          transform-origin: 500px 500px;
}

.ocean {
  fill: #fff;
  opacity: 0.2;
}

.hill {
  fill: #6d5d91;
}

.hill_back,
.hill_reflection {
  fill: #77669d;
}

.hill_reflection {
  opacity: 0.2;
}

@-webkit-keyframes stars {
  0%,
  100% {
    opacity: 0.3;
  }
  50% {
    opacity: 0.8;
  }
}

@keyframes stars {
  0%,
  100% {
    opacity: 0.3;
  }
  50% {
    opacity: 0.8;
  }
}
.stars {
  fill: #fff;
}

.star {
  opacity: 0.3;
  -webkit-animation: stars 5s infinite;
          animation: stars 5s infinite;
}

.star:nth-child(1) {
  -webkit-animation-delay: 0.5s;
          animation-delay: 0.5s;
}

.star:nth-child(2) {
  -webkit-animation-delay: 1s;
          animation-delay: 1s;
}

.star:nth-child(3) {
  -webkit-animation-delay: 1.5s;
          animation-delay: 1.5s;
}

.star:nth-child(4) {
  -webkit-animation-delay: 2s;
          animation-delay: 2s;
}

.star:nth-child(5) {
  -webkit-animation-delay: 2.5s;
          animation-delay: 2.5s;
}

.star:nth-child(6) {
  -webkit-animation-delay: 3s;
          animation-delay: 3s;
}

.star:nth-child(7) {
  -webkit-animation-delay: 3.5s;
          animation-delay: 3.5s;
}
<body>
  <svg viewBox="0 0 1000 1000" class="world" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
  <defs>

    <clipPath id="clip-path">
      <circle  cx="500" cy="500" r="400"/>
    </clipPath>

    <clipPath id="reflection">
      <rect width="1000" height="500"/>
    </clipPath>

    <symbol id="star" viewBox="-20 -20 40 40">
      <circle class="stars" r="20"/>
    </symbol>

    <radialGradient id="sky-gradient" cx="737.45" cy="94.64" r="800.05" gradientUnits="userSpaceOnUse">
      <stop offset="0.03" stop-color="#ffd7ac"/>
      <stop offset="0.5" stop-color="#f8a7a1"/>
      <stop offset="0.92" stop-color="#6d5d91"/>
    </radialGradient>

    <symbol id="sky" viewBox="0 0 1000 1000">
      <rect width="1000" height="1000" fill="url(#sky-gradient)"/>
      <circle id="sun" class="sun" cx="658" cy="265" r="62"/>
      <use width="10" height="10" x="350" y="550" xlink:href="#star" class="star" />
      <use width="10" height="10" x="470" y="650" xlink:href="#star" class="star" />
      <use width="8" height="8" x="430" y="750" xlink:href="#star" class="star" />
      <use width="9" height="9" x="250" y="650" xlink:href="#star" class="star" />
      <use width="9" height="9" x="590" y="780" xlink:href="#star" class="star" />
      <use width="5" height="5" x="700" y="750" xlink:href="#star" class="star" />
      <use width="4" height="4" x="300" y="800" xlink:href="#star" class="star" />
    </symbol>
  </defs>

  <g id="planet" clip-path="url(#clip-path)">
    <use xlink:href="#sky" class="sky" ></use>
    <g clip-path="url(#reflection)" class="reflection">
      <use xlink:href="#sky" class="sky"></use>
      <rect id="ocean_light" class="ocean"  width="1000" height="500"/>
    </g>
    <path class="hill_reflection" d="M638 547H457l51-32H-22l294 148 35-22 148 71 183-165"/>
    <path class="hill_back" d="M-22 526l294-177 236 177H-22"/>
    <path class="hill" d="M108 547l347-159 183 159H108"/>
  </g>
</svg>

</body>

Источник, немного доработанный

A: Ответ к комментарию @Leks

в элементе <radialGradient id="MyGradient" fx="0.5" fy="0.5" r="1" >
  будет рисовать круг заданных цветов если круг сдвинут в угол fx и fy
  он обрезается т.к выходит за рамки фигуры circle верно ? –

При fx="0.5" fy="0.5" r="1" Начальная точка градиента расположена точно по центру фигуры. fx=0.5 или, что тоже самое fx=50% - это получается симметричный, равный половине отступ от краев, то есть центр.
Смещение, например в левый верхний угол будет при fx="0" fy="0"естественно при таком смещении на фигуре будет находиться только одна, нижняя, правая  четверть кругового градиента.
Ниже пример анимации демонстрирующий наложение градиента на элемент при разных
 значениях fx,  fy
<animate xlink:href="#radGrad"
      attributeName="fy"
      dur="2s"begin="gr1.click"
      values="0%;50%;50%;100%;100%;0%"
      keyTimes="0;0.1;0.5;0.9;1"
      repeatCount="1"
      restart="whenNotActive" />

При fy="0%" начальная точка градиента в левом, верхнем углу
при  fy="50%" - в центре
при  fy="100%" - начальная точка градиента в правом, нижнем углу

svg {
 width:50%;
 height:50%;
 }
 .txt {
 font-family:sans-serif;
 font-size:28px;
 font-weight:bold;
 text-anchor:middle;
 fill:#FFDD00;
  }
<div id="shine-div">
   <svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 400 100">
   <defs>
  <radialGradient id="radGrad"  fx="0%" fy="0%" r="100%">
        <stop offset="0%" stop-color ="#FFFFFF" />
     <stop offset="4%" stop-color ="#ffb3ff" />
     <stop offset="12.25%" stop-color ="#ff33ff" />
     <stop offset="31.25%" stop-color ="#800080" />
     <stop offset="50%" stop-color ="#b300b3" />
  </radialGradient>
   </defs>
    <g id="gr1" >
      <rect id="rect1" fill="url(#radGrad)" x="5%" y="5%" width="95%" height="95%" rx="10%"/>
       <text class="txt" x="50%" y="60%"> Sun shine </text>
 </g>
    <animate xlink:href="#radGrad"
   attributeName="fy"
   dur="2s"begin="gr1.click"
   values="0%;50%;50%;100%;100%;0%"
   keyTimes="0;0.1;0.5;0.8;0.9;1"
   repeatCount="1"
   restart="whenNotActive" />

      <animate xlink:href="#radGrad"
     attributeName="fx"
     dur="2s"begin="gr1.click"
     values="0%;50%;50%;100%;100%;0%"
     keyTimes="0;0.1;0.5;0.8;0.9;1"
     repeatCount="1"
     restart="whenNotActive" />
  </svg>
</div>


text:
Q: Getting value and key from python Collection I'm struggling to get single value and key pairs from a Counter in a for loop
I have the following code:
test= ["test1", "test2", "apps1", "apps2", "random"]

return collections.Counter(i[:4] for i in test)

I get the following:
{
    "rand": 1,
    "test": 2,
    "apps": 2,
}
I want to know it there a way to get these values & keys based on there position if a for loop, because I'm trying to add it to a json object for an angular app.
The JSON object I want to create looks like this,
returnObject = []
            for i in range(len(collections.Counter(i[:4] for i in test))):
                tempObject ={
                'value': #add counter value in pos i,
                'color': 'rgb(0,19,255)',
                'label': #add counter key in pos i,
                'order': i+1,
                }
                returnObject.append(tempObject)

            print returnObject

Sorry I'm new to this and have tried a lot of different things, but thank you in advance for any help.

A: Using range(len) is not the canonical way to loop over a container and not very useful for a dict type.
You can directly iterate over containers, e.g.:
counts = collections.Counter(i[:4] for i in test)
for key in counts:
    print(key, counts[key])

Or more directly using .items():
counts = collections.Counter(i[:4] for i in test)
for key, value in counts.items():
    print(key, value)


text:
Q: How to consume ServiceStack's ServerEventsClient OnMessage asynchronously I'm looking for a way for this part of the code to be asynchronous.
var sse = new ServerEventsClient(apiUrl)
{
  OnMessage = HandleResponse
};

I've looked at "Using C# Async/Await friendly API's" here https://docs.servicestack.net/csharp-server-events-client#using-c-asyncawait-friendly-apis and I'm not sure if the code provided only works for one future message or every message that will come. I'll be sending a lot of requests in which I expect server responses via SSE so I'd like every response to be handled.

A: OnMessage is a synchronous event which fires as soon as it receives a message, it doesn't have an async alternative callback.
If you want to handle the messages asynchronously you can decouple the producer from its consumers which can do using a BlockingCollection where you can the SSE Client capturing messages as soon as they're sent, e.g:
using var bc = new BlockingCollection<ServerEventMessage>();
using var sse = new ServerEventsClient(apiUrl) {
  OnMessage = bc.Add
};
await sse.Connect();
//...

Then you can have multiple sync & async consumers handling messages at their own pace independent of how fast they're being received with Take, TryTake or GetConsumingEnumerable APIs, e.g:
await Task.Run(async () => {
    foreach (var msg in bc.GetConsumingEnumerable())
    {
        // handle msg
        await Task.Delay(100);
    }
});

When you want to stop handling messages (e.g. when disposing ServerEventsClient) you can notify and short-circuit consumers with:
bc.CompleteAdding();


text:
Q: tkinter gui formatting menu's with frames (pyhon2.7) I am currently a high school student taking a beginner programming class. We just started a new unit learning Tkinter in python and I had a few questions regarding a project we have. I decided to do my project on making a currency converter. I finished everything regarding api's, and now I've hit a road block when making my gui. I am having a problem moving my button around to desired locations. Currently my button is stuck in the middle, and if I change the rows and columns, it moves to random locations and ruins the white background. Any help would be greatly appreciated!
Thanks so much.
import Tkinter as tk
import tkMessageBox

CURRENCY_CODES = ('USD','GDP')

class Application(tk.Frame):
    def __init__(self, parent = None):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.setupUI()
        self.createWidgets()

    def setupUI(self):
        self.parent.title("User Input")
        self.grid()
        self.centerWindow()

    def centerWindow(self):
        app_width = 307
        app_height = 350

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        x = (sw - app_width)/2
        y = (sh - app_height)/2
        self.parent.geometry('%dx%d+%d+%d' % (app_width, app_height, x, y))

    def createWidgets(self):
        self.emptyFrame = tk.Frame(self.parent,bg="white")
        self.emptyFrame.grid(row=0,column=0,sticky="news")
        self.parent.grid_columnconfigure(0,weight=1)
        self.parent.grid_rowconfigure(0,weight=1)

A: you can chuck it anywhere you please with the 'x' & 'y' coordinates like so,
        self.currencyMenu.place(x = 10, y = 250)

A: Your question doesn't show a complete program, nor does it show any buttons, so it's impossible to tell you all the problems. However, you're doing a couple of things that are definitely leading you down the wrong path.
The first problem is this:
self.grid()

As a general rule, the function that creates a widget is the function that should add the widget with a geometry manager. Wherever you call Application() should be responsible for putting the frame in its container.
app = Application(root)
app.grid(...)

Second, is this line of code:
self.emptyFrame = tk.Frame(self.parent,bg="white")

A child of a frame or root window (which is what Application is) should never put widgets outside of itself. Everything inside of Application should be literally inside of Application. Otherwise it becomes impossible to juggle all of the geometry management. That empty frame needs to be inside of Application (eg: self):
self.emptyFrame = tk.Frame(self, bg="white")

If you have a class that inherits from some other widget class, it should only ever affect itself and it's children1. It should never do anything that affects its parent.  If you stick to that principle, widget layout becomes much, much, much easier.
1 I realize there are many examples on the internet that violate this principle, but they are all doing it wrong. While it's more-or-less OK for trivial applications, it quickly becomes quite a burden with complex applications. If you practice proper coding on the simple apps, then you won't have to change your technique when you graduate to more complex apps.


text:
Q: C++ / warning: control reaches end of non-void function [-Wreturn-type] I am just a beginner today and trying to learn desktop programming with C++. And I am confused that why doesnt this work:
The code:
int math(int opt, int x, int y){
    switch(opt){
        case 1:
            return x + y;
            break;
        case 2:
            return x - y;
            break;
        case 3:
            return x * y;
            break;
        case 4:
            return x / y;
            break;
        default:
            break;
    }
}

The use:
cout << to_string(math(1,1,2)));
The error:
main.cpp: In function 'int math(int, int, int)':
main.cpp:38:1: warning: control reaches end of non-void function [-Wreturn-type]
   38 | }
      | ^

Thank you all,
as I understand:

*

*break; after return is extra because will be never executed

*need to return something in all cases(i.e. if opt is bigger than 5)

So this works now:
int math(int opt, int x, int y){
    switch(opt){
        case 1:
            return x + y;
        case 2:
            return x - y;
        case 3:
            return x * y;
        case 4:
            return x / y;
        default:
            return 0;
    }
}

A: A function that has any return type other than void needs to reach a return statement with the correct value type specified.
A function is built like this: returnType name(type parameterName, ...){}
If the return type is (as in your case) an int, the path of execution must reach a return foo; statement, where foo is, or convertible to, an int.
int math(int opt, int x, int y){
    switch(opt){
        case 1:
            return x + y;
        case 2:
            return x - y;
        case 3:
            return x * y;
        case 4:
            return x / y;
        default:
            throw std::invalid_argument("math parameter opt out of range!");
    }
}

Also, any code after reaching a return is not executed, so the break; statements are extraneous.

A: The problem is, if you pass "invalid" opt value, default case gets selected, and your function returns nothing. So one solution would be to decide what to return if you pass invalid opt.
You should fix your problem like this:
enum class Opt { PLUS, MINUS, TIMES, DIVIDED };

int math(Opt opt, int x, int y) {
    switch(opt){
        case Opt::PLUS:
            return x + y;
        case Opt::MINUS:
            return x - y;
        case Opt::TIMES:
            return x * y;
        case Opt::DIVIDED:
            return x / y;
    }
    // it is important to not have default: case
    // above because now compiler will issue warning,
    // you add new values to Opt.

    // below line should never be reached, so value doesn't matter,
    // but it's needed to disable warning on some compilers.
    return 0;
}

// test
int main() {
    return math(Opt::PLUS, 1, 2); // exit code 3
}

Using enum class has the benefit, that if you want to shoot yourself into foot by passing random integer as opt, you have use an explicit cast to convert the integer into an enum class value.


text:
Q: Why do some literals disappear when passing from CNF to DNF $(p \Rightarrow q) \land (q \Rightarrow r) \land \neg(r \Rightarrow p)$
According to wolframalfa the result is $\neg p \land r$.
Could you tell me how did this happen? where did $q$ disappear and why?

A: The only possibility that $\neg (r \Rightarrow p) $ is true is that $ \neg p \land r$. For ($q \Rightarrow r$) to be true also, we can take $q$ or $\neg q$, hence $(q \lor \neg q)$. That is also the case for $(p \Rightarrow q)$, since we already have $\neg p$, so we can take $q$ or $\neg q$, hence $(q \vee \neg q)$. Since ($q \lor \neg q$) is always true, we can remove it because it doesn't impose any restrictions on the proposition. Hence we get $ \neg p\wedge r$ as our final result.

A: Suppose $(p \to q) \land (q \to r) \land \neg(r \to p)$

*

*Assume $q$, then we have $(p\to \top) \wedge (\top\to r)\wedge \neg (r\to p)$, which is $r\wedge \neg p$

$$\begin{array}{l}(p\to \top) \wedge (\top\to r)\wedge \neg (r\to p)\\ \top \wedge (\top\to r)\wedge \neg(r\to p)\\ (\top\to r)\wedge \neg(r\to p)\\ r\wedge \neg (r\to p)\\ r\wedge \neg p\end{array}$$

*

*Assume $\neg q$, then we have $(p\to\bot)\wedge (\bot\to r)\wedge \neg(r\to p)$ which is $r\wedge \neg p$.

$$\begin{array}{l}(p\to \bot) \wedge (\bot\to r)\wedge \neg (r\to p)\\ \neg p \wedge (\bot\to r)\wedge \neg(r\to p)\\ \neg p\wedge \top\wedge\neg (r\to p) \\ \neg p\wedge\neg (r\to p)\\\neg p \wedge r \end{array}$$
So the value of $q$ is factually irrelevant to the evaluation of the statement.
That is why it "disappears" when the expression is algebraically simplified.


text:
Q: ayuda con mi error 'if' (T_IF) hola necesito de su ayuda con mi error en mi código:
<?php
    $db_host="localhost";
    $db_user="nombre_de_usuario";
    $db_password="contraseña";
    $db_name="nombre_de_base_de_datos";
    $db_table_name="nombre_de_tabla";
    $db_connection = mysql_connect($localhost, $nombre_de_usuario, $contraseña)

    if(!$db_connection) {
        die('No se ha podido conectar a la base de datos');
    }
    $subs_name = utf8_decode($_POST['nombre']);
    $subs_last = utf8_decode($_POST['apellido']);
    $subs_email = utf8_decode($_POST['email']);
    $subs_password = utf8_decode($_POST['password']);

    $resultado=mysql_query("SELECT * FROM ".$db_table_name." WHERE Email = '".$subs_email."'", $db_connection);

    if (mysql_num_rows($resultado)>0)
    {

        header('Location: Fail.html');

    } else {

        $insert_value = 'INSERT INTO `' . $db_name . '`.`'.$db_table_name.'` (`Nombre` , `Apellido` , `Email`) VALUES ("' . $subs_name . '", "' . $subs_last . '", "' . $subs_email . '")';

        mysql_select_db($db_name, $db_connection);
        $retry_value = mysql_query($insert_value, $db_connection);

        if (!$retry_value) {
            die('Error: ' . mysql_error());
        }

        header('Location: Success.html');

    }

    mysql_close($db_connection);
?>

A: Deberías utilizar mysqli_connect, mysql_connect ya no está soportado en la versión 7 de PHP, te dejo un enlace a la documentación de PHP.
<?php
$db_host="localhost";
$db_user="nombre_de_usuario";
$db_password="contraseña";
$db_name="nombre_de_base_de_datos";
$db_table_name="nombre_de_tabla";
$db_connection = mysqli_connect($db_host, $db_user, $db_password,$db_name);