text:
Q: How does a Coroutine Continuation internally work? I have been working with coroutines for few weeks and sometimes its tough to understand the real working difference between thread concurrency and coroutine concurrency.
How suspend functions works internally ? How is continuation block helping in resuming the computation after suspension.
How is sequential computation of the line of code inside coroutine not blocking the thread ? and how is it better than thread concurrency ?

A:
How suspend functions works internally?

Briefly, on the Java platform a suspend fun compiles into bytecode that is dramatically different from a plain function. It receives a hidden extra parameter (the continuation), creates its own continuation object, and the entire body of the function is implemented (approximately) as a big switch statement that allows the function to jump into the middle of the body when resuming.
When a suspend fun suspends, the underlying Java method actually returns. The return value is a special COROUTINE_SUSPENDED singleton object which the framework knows how to interpret. It is the responsibility of the suspend fun itself to save the continuation object where it will be accessible when the result of the function is ready.
The official documentation has a good in-depth description of these details.

How is continuation block helping in resuming the computation after suspension.

This is related to what I said above, that the suspend fun itself is responsible for ensuring it gets resumed later on. It must do that inside the block provided by the function suspendCoroutineOrReturn. User code doesn't call it directly, but the more high-level analogs suspendCoroutine and suspendCancellableCoroutine. These take over the concern of resuming the coroutine on the appropriate thread and the developer is responsible only for ensuring that continuation.resume() is called with the result when it becomes available. This typically happens in a callback you pass to an async call.
You can study this answer that tries to explain the suspend-resume mechanism in a self-contained example.

How is sequential computation of the line of code inside coroutine not blocking the thread?

Because it actually compiles into returning from the function and later on resuming by jumping into the middle of the function body.

and how is it better than thread concurrency?

Native threads are heavyweight resources that take time to create and destroy. Coroutines are much lighter-weight and consequently you can start many more of them, and more quickly.

A: The internal workings are explained in the original design document https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md which has a section on "Implementation Details".


text:
Q: Install4j: How to prevent file overwrites when using 'Add VM options' installation action? We are using some calculations with 'Add VM options' installer actions. Now every time we update our system using the installer all user changes in  '*.vmoptions' files are lost. Is there a good way to prevent it?
NB: We considered to use a 'Condition expression' to check if the vmoptions file is already present but have not found a way to determine proper filename because it is computed internally based on Launcher's name.

A: Set your condition expression to
new File(context.getLauncherById("123").getRelativeFileName().
    replaceAll(".exe", ".vmoptions")).exists()

then the action will only be executed if the .vmoptions file does not exist.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Projectives in the category of discrete G-modules  If $G$ is a profinite group, then the category $Mod(G)$ of discrete $G$-modules has sufficiently many injectives (Neukirch, Schmidt, Wingberg: Cohomology of Number Fields, 2.6.5).
Since the cited book says nothing on projectives within this category, I guess $Mod(G)$ doesn't have sufficiently many projectives. Can you give me an example of a discrete $G$-module $M$ such that there is no epimorphism  $P \to M$ with $P$ projective ?  If there are little projectives, is it even possible to classify them ?
Added: Note that a discrete $G$-module $M$ is an abelian group (with the discrete topology) with a continuous $G$-action $G \times M \to M$ (N-S-W, 1.1.5). For example $\mathbb{Z}$ with trivial $G$-action is a discrete $G$-module.

A: Discrete modules over a profinite group $G$ are the same thing as comodules over its group coalgebra $\mathbb Z(G)$.  There aren't supposed to be many (or, generally speaking, any) projectives in the abelian category of comodules.  One way to see this is to notice that infinite products of discrete $G$-modules aren't exact functors.  Infinite products are always exact in an abelian category with enough projectives.
There are enough projectives in the abelian category of $\mathbb Z(G)$-contramodules, though. This is another kind of module category associated with a coalgebra or coring (and, in particular, with a profinite group).  So the familiar algebra/discrete group situation of a module category with enough projectives and injectives splits in two halves when one passes to coalgebras/profinite groups---with two different kinds of module categories, one having enough injectives and another enough projectives.
Reference: Eilenberg, Moore.  Foundations of relative homological algebra.  Memoirs AMS vol.55, 1965.

A: Here is a link a proof that the category $\text{Mod}(G)$ does not have enough projectives, when $G$ is an infinite profinite group. I think the proof is fairly elementary. There might be a few details missing though - sorry about that.


text:
Q: How to insert DropDownList selected value into GridView in asp.net?     using System;
     using System.Collections.Generic;
     using System.Linq;
     using System.Web;
     using System.Web.UI;
     using System.Web.UI.WebControls;
     using System.Data;
     using System.Drawing;

    namespace NewDPOcopy
    {
      public partial class UpdatePaperCost : System.Web.UI.Page
     {
       Services.ServiceAuthentication ser = new Services.ServiceAuthentication();
       // Services.ServiceAuthentication ser = new Services.ServiceAuthentication();

        protected void Page_Load(object sender, EventArgs e)
        {
            fillgrodPaperType();
            ddlcatid.Visible = true;
            ddlcatid.DataSource = ser.Getpapercategory();
            ddlcatid.DataTextField = "Cat_Name";
            //ddlcatid.DataValueField = "Cat_id";
            ddlcatid.DataBind();
        }

        protected void fillgrodPaperType()
        {
            Services.PaperTypes[] PaperInfo = ser.GetALLPaperTypeInfo();

            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("pt_id", typeof(string)));
            dt.Columns.Add(new DataColumn("pt_name", typeof(string)));
            dt.Columns.Add(new DataColumn("pt_weight", typeof(int)));

            dt.Columns.Add(new DataColumn("pt_size", typeof(string)));
            dt.Columns.Add(new DataColumn("pt_cost_per_sheet", typeof(double)));
            dt.Columns.Add(new DataColumn("pt_status", typeof(string)));

            dt.Columns.Add(new DataColumn("pt_used_by_247", typeof(Boolean)));
            dt.Columns.Add(new DataColumn("pt_front_finish", typeof(string)));
            dt.Columns.Add(new DataColumn("pt_back_finish", typeof(string)));

            dt.Columns.Add(new DataColumn("pt_default", typeof(Boolean)));
            dt.Columns.Add(new DataColumn("pt_colour", typeof(string)));
            dt.Columns.Add(new DataColumn("pt_nexpress", typeof(Boolean)));
            dt.Columns.Add(new DataColumn("pt_igen", typeof(Boolean)));
            dt.Columns.Add(new DataColumn("Cat_Name", typeof(string)));

            for (int i = 0; i < PaperInfo.Length; i++)
            {
                DataRow dr = null;
                dr = dt.NewRow();
                dr["pt_id"] = PaperInfo[i].Pt_id;
                dr["pt_name"] = PaperInfo[i].Pt_name;
                dr["pt_weight"] = PaperInfo[i].Pt_weight;

                dr["pt_size"] = PaperInfo[i].Pt_size;
                dr["pt_cost_per_sheet"] = PaperInfo[i].Pt_cost_per_sheet;
                // dr["pt_cost_per_sheet"] = 12;
                dr["pt_status"] = PaperInfo[i].Pt_status;

                dr["pt_used_by_247"] = PaperInfo[i].Pt_used_by_247;
                dr["pt_front_finish"] = PaperInfo[i].Pt_front_finish;
                dr["pt_back_finish"] = PaperInfo[i].Pt_back_finish;

                dr["pt_default"] = PaperInfo[i].Pt_default;
                dr["pt_colour"] = PaperInfo[i].Pt_colour;
                dr["pt_nexpress"] = PaperInfo[i].Pt_nexpress;
                dr["pt_igen"] = PaperInfo[i].Pt_igen;
                dr["Cat_Name"] = PaperInfo[i].Cat_Id;
                dt.Rows.Add(dr);
            }

            GrdvwPTID.DataSource = dt;
            GrdvwPTID.DataBind();

            //ddlPTID.DataSource = dt;
            //ddlPTID.DataTextField = "pt_name";
            //ddlPTID.DataValueField = "pt_id";
            //ddlPTID.DataBind();
        }

        protected void ClearPaperType()
        {
            txtptid.Text = "";
            txtptname.Text = "";
            txtptweight.Text = "";
            txtptsize.Text = "";
            txtptcostpersheet.Text = "";
            txtptstatus.Text = "";
            txtptfontfinish.Text = "";
            txtptbackfinish.Text = "";
            txtptcolor.Text = "";
            ddlptdefault.ClearSelection();
            ddlptdefault.Items.FindByText("<--select-->").Selected = true;
            ddlptnexpress.ClearSelection();
            ddlptnexpress.Items.FindByText("<--select-->").Selected = true;
            ddlptusedby247.ClearSelection();
            ddlptusedby247.Items.FindByText("<--select-->").Selected = true;
            ddlptigen.ClearSelection();
            ddlptigen.Items.FindByText("<--select-->").Selected = true;
            lblMessagePTYPE.Visible = false;
            HiddenField2.Value = "";
        }

        protected void GrdvwPTID_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void GrdvwPTID_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            int index = Convert.ToInt32(e.CommandArgument);
            Session["INDEX"] = index;

            lblMessagePTYPE.Visible = false;

            txtptid.Text = GrdvwPTID.Rows[index].Cells[1].Text;
            txtptname.Text = GrdvwPTID.Rows[index].Cells[2].Text;
            txtptweight.Text = GrdvwPTID.Rows[index].Cells[3].Text;
            txtptsize.Text = GrdvwPTID.Rows[index].Cells[4].Text;
            txtptcostpersheet.Text = GrdvwPTID.Rows[index].Cells[5].Text;
            txtptstatus.Text = GrdvwPTID.Rows[index].Cells[6].Text;

            ddlptusedby247.ClearSelection();
            if (GrdvwPTID.Rows[index].Cells[7].Text == "True")
            {
                ddlptusedby247.Items.FindByText("Yes").Selected = true;
            }
            else
            {
                ddlptusedby247.Items.FindByText("No").Selected = true;
            }

            txtptfontfinish.Text = GrdvwPTID.Rows[index].Cells[8].Text;
            txtptbackfinish.Text = GrdvwPTID.Rows[index].Cells[9].Text;
            ddlptdefault.ClearSelection();
            if (GrdvwPTID.Rows[index].Cells[10].Text == "True")
            {
                ddlptdefault.Items.FindByText("Yes").Selected = true;
            }
            else
            {
                ddlptdefault.Items.FindByText("Yes").Selected = false;
            }
            txtptcolor.Text = GrdvwPTID.Rows[index].Cells[11].Text;

            ddlptnexpress.ClearSelection();
            if (GrdvwPTID.Rows[index].Cells[12].Text == "True")
            {
                ddlptnexpress.Items.FindByText("Yes").Selected = true;
            }
            else
            {
                ddlptnexpress.Items.FindByText("No").Selected = true;
            }
            ddlptigen.ClearSelection();
            if (GrdvwPTID.Rows[index].Cells[13].Text == "True")
            {
                ddlptigen.Items.FindByText("Yes").Selected = true;
            }
            else
            {
                ddlptigen.Items.FindByText("Yes").Selected = false;
            }
            //ddlcatid.ClearSelection();
            //if (GrdvwPTID.Rows[index].Cells[14].Text == "True")
            //{
            //    ddlcatid.Items.FindByText("Yes").Selected = true;
            //}
            //else
            //{
            //    ddlcatid.Items.FindByText("Yes").Selected = false;
            //}
            HiddenField2.Value = "EditPAPERTYPE";

        }

        protected void btnsubmit_Click(object sender, EventArgs e)
        {
            if (txtptid.Text == "" || txtptname.Text == "" || txtptweight.Text == "" || txtptsize.Text == "" || txtptcostpersheet.Text == "" || txtptstatus.Text == "" || txtptfontfinish.Text == "" || txtptbackfinish.Text == "" || txtptcolor.Text == "" || ddlptdefault.SelectedItem.ToString() == "<--select-->" || ddlptnexpress.SelectedItem.ToString() == "<--select-->" || ddlptusedby247.SelectedItem.ToString() == "<--select-->" || ddlptigen.SelectedItem.ToString() == "<--select-->")
            {
                lblMessagePTYPE.Visible = true;
                lblMessagePTYPE.ForeColor = Color.Red;
                lblMessagePTYPE.Text = "FILL ALL THE FIELDS AND CLICK HERE TO SUBMIT";

            }
            else
            {

                Boolean ptused247;
                if (ddlptusedby247.SelectedItem.ToString() == "Yes")
                {
                    ptused247 = true;
                }
                else
                {

                    ptused247 = false;
                }
                Boolean ptDefault;
                if (ddlptdefault.SelectedItem.ToString() == "Yes")
                {
                    ptDefault = true;
                }
                else
                {
                    ptDefault = false;
                }
                Boolean ptNexPRESS;
                if (ddlptnexpress.SelectedItem.ToString() == "Yes")
                {
                    ptNexPRESS = true;
                }
                else
                {
                    ptNexPRESS = false;
                }
                Boolean ptIgen;
                if (ddlptigen.SelectedItem.ToString() == "Yes")
                {
                    ptIgen = true;
                }
                else
                {
                    ptIgen = false;
                }

                Boolean catName;
                if (ddlcatid.SelectedItem.ToString() == "Yes")
                {
                    catName = true;
                }
                else
                {
                    catName = false;
                }
                //insert Query Call...........

                if (HiddenField2.Value != "EditPAPERTYPE")
                {
                    bool InsertResultPT = ser.InsertPaperType(txtptid.Text, txtptname.Text, Convert.ToInt32(txtptweight.Text), txtptsize.Text, Convert.ToDouble(txtptcostpersheet.Text), txtptstatus.Text, ptused247, txtptfontfinish.Text, txtptbackfinish.Text, ptDefault, txtptcolor.Text, ptNexPRESS, ptIgen, catName);
                    if (InsertResultPT)
                    {
                        lblMessagePTYPE.Visible = true;
                        lblMessagePTYPE.ForeColor = Color.Green;
                        lblMessagePTYPE.Text = "PAPER TYPE VALUES INSERTED SUCCESSFULLY!";
                        fillgrodPaperType();
                    }
                    else
                    {
                        lblMessagePTYPE.Visible = true;
                        lblMessagePTYPE.ForeColor = Color.Red;
                        lblMessagePTYPE.Text = "YOU ENTERED WRONG VALUES !";
                    }

                    // ClearPaperType();
                    txtptid.Text = "";
                    txtptname.Text = "";
                    txtptweight.Text = "";
                    txtptsize.Text = "";
                    txtptcostpersheet.Text = "";
                    txtptstatus.Text = "";
                    txtptfontfinish.Text = "";
                    txtptbackfinish.Text = "";
                    txtptcolor.Text = "";
                    ddlptdefault.ClearSelection();
                    ddlptdefault.Items.FindByText("<--select-->").Selected = true;
                    ddlptnexpress.ClearSelection();
                    ddlptnexpress.Items.FindByText("<--select-->").Selected = true;
                    ddlptusedby247.ClearSelection();
                    ddlptusedby247.Items.FindByText("<--select-->").Selected = true;
                    ddlptigen.ClearSelection();
                    ddlptigen.Items.FindByText("<--select-->").Selected = true;
                    HiddenField2.Value = "";
                }

                else
                {
                    //Update Query Call...........
                    bool UpdateResult = ser.UpdatePaperTypes(txtptid.Text, txtptname.Text, Convert.ToInt16(txtptweight.Text), txtptsize.Text, Convert.ToDouble(txtptcostpersheet.Text), txtptstatus.Text, ptused247, txtptfontfinish.Text, txtptbackfinish.Text, ptDefault, txtptcolor.Text, ptNexPRESS, ptIgen,catName);
                    if (UpdateResult)
                    {
                        lblMessagePTYPE.Visible = true;
                        lblMessagePTYPE.ForeColor = Color.Green;
                        lblMessagePTYPE.Text = "PAPER TYPE VALUES UPDATED SUCCESSFULLY!";
                        fillgrodPaperType();
                        txtptid.Text = "";
                        txtptname.Text = "";
                        txtptweight.Text = "";
                        txtptsize.Text = "";
                        txtptcostpersheet.Text = "";
                        txtptstatus.Text = "";
                        txtptfontfinish.Text = "";
                        txtptbackfinish.Text = "";
                        txtptcolor.Text = "";
                        ddlptdefault.ClearSelection();
                        ddlptdefault.Items.FindByText("<--select-->").Selected = true;
                        ddlptnexpress.ClearSelection();
                        ddlptnexpress.Items.FindByText("<--select-->").Selected = true;
                        ddlptusedby247.ClearSelection();
                        ddlptusedby247.Items.FindByText("<--select-->").Selected = true;
                        ddlptigen.ClearSelection();
                        ddlptigen.Items.FindByText("<--select-->").Selected = true;
                        HiddenField2.Value = "";
                    }
                    else
                    {
                        lblMessagePTYPE.Visible = true;
                        lblMessagePTYPE.ForeColor = Color.Red;
                        lblMessagePTYPE.Text = "Updation failed please try again.";

                    }
                    HiddenField2.Value = "";
                }

            }
            txtptid.Text = "";
            txtptname.Text = "";
            txtptweight.Text = "";
            txtptsize.Text = "";
            txtptcostpersheet.Text = "";
            txtptstatus.Text = "";
            txtptfontfinish.Text = "";
            txtptbackfinish.Text = "";
            txtptcolor.Text = "";
            ddlptdefault.ClearSelection();
            ddlptdefault.Items.FindByText("<--select-->").Selected = true;
            ddlptnexpress.ClearSelection();
            ddlptnexpress.Items.FindByText("<--select-->").Selected = true;
            ddlptusedby247.ClearSelection();
            ddlptusedby247.Items.FindByText("<--select-->").Selected = true;
            ddlptigen.ClearSelection();
            ddlptigen.Items.FindByText("<--select-->").Selected = true;
            HiddenField2.Value = "";
        }

        protected void btndelete_Click1(object sender, EventArgs e)
        {
            if (HiddenField2.Value != "EditPAPERTYPE")
            {

                lblMessagePTYPE.Visible = true;
                lblMessagePTYPE.ForeColor = Color.Red;
                lblMessagePTYPE.Text = "PLEASE SELECT THE RECORD FROM TABLE!";
            }
            else
            {

                bool deletePaperType = ser.RemovePaperType(GrdvwPTID.Rows[Convert.ToInt16(Session["INDEX"].ToString())].Cells[1].Text);
                if (deletePaperType)
                {
                    lblMessagePTYPE.Visible = true;
                    lblMessagePTYPE.ForeColor = Color.Green;
                    lblMessagePTYPE.Text = "PAPER TYPE VALUES HAS BEEN DELETED SUCCESSFULLY!";
                    HiddenField2.Value = "";
                }
                else
                {
                    lblMessagePTYPE.Visible = true;
                    lblMessagePTYPE.ForeColor = Color.Red;
                    lblMessagePTYPE.Text = "No match found !";
                    HiddenField2.Value = "";
                }
                // ClearPaperType();
                txtptid.Text = "";
                txtptname.Text = "";
                txtptweight.Text = "";
                txtptsize.Text = "";
                txtptcostpersheet.Text = "";
                txtptstatus.Text = "";
                txtptfontfinish.Text = "";
                txtptbackfinish.Text = "";
                txtptcolor.Text = "";
                ddlptdefault.ClearSelection();
                ddlptdefault.Items.FindByText("<--select-->").Selected = true;
                ddlptnexpress.ClearSelection();
                ddlptnexpress.Items.FindByText("<--select-->").Selected = true;
                ddlptusedby247.ClearSelection();
                ddlptusedby247.Items.FindByText("<--select-->").Selected = true;
                ddlptigen.ClearSelection();
                ddlptigen.Items.FindByText("<--select-->").Selected = true;
                fillgrodPaperType();

            }

        }

        protected void btncancel_Click(object sender, EventArgs e)
        {
            ClearPaperType();
        }
    }
}

I have the above code in that in Page_lode event its binding the value to dropedown   but when i am going to insert but its not inserting and not showing into grideview but in dropedown all values are binded how to insert into grideview?

A: The proper way to do this is to keep a global variable as your datasource (the datatable you build yourself) before binding the gridbiew to it, and when someone selects something from the drop-down (or on whatever event you want), update the contents/insert into the global variable, and then re-bind it to the grid-view.
This will do what you want.


text:
Q: SSRS query using like with parameter won't return anything if full value is supplied with parameter I'm building a report where my user will need to supply EITHER the full a serial number or the last five characters of the serial number.
The WHERE clause of my query in SSRS is:
Where (Products.SerialNumber LIKE '%' + @prmSerialNumber)
I have a serial number in the database equal to '1C0127000000000000009132'.
If I supply '9132' as the parameter value, I get the appropriate results.  But if I supply the whole serial number '1C0127000000000000009132' as the parameter value, I get no rows returned.
Is there a way to build this query so that the user can supply either the full serial number OR just the last few characters?
I have also tried:
WHERE (Products.SerialNumber LIKE { fn CONCAT(N'%', @prmSerialNumber) }).
Same results

A: You could just use an OR
WHERE (Products.SerialNumber LIKE '%' + @prmSerialNumber)
OR (Products.SerialNumber = @prmSerialNumber)


text:
Q: How to get a GUI on debian 5 on the playstation 2 So recently I got Debian Lenny running on my PlayStation 2 slim. This by using a guide on this site: How to install Linux on the Playstation 2.
The problem is, a command line interface is nice and everything however I like to have the GUI that shows on the Sourceforge page from the guy who made the kernel and ramdisk (kernelloader project: https://sourceforge.net/projects/kernelloader/). On this wiki I see some images of a gui, I think this is NetSurf but I like to have a standard Linux GUI running.
Obviously, it has to be lightweight (32 mb of ram + 4 mb vram lol).
I have already tried some methods of getting gui packages on to the system(obviously all in root), for example apt-get install xfce and apt-get install xserver-xorg-core , lightdm and gdm. Every time I try this I get an error saying that the package doesn't exist. This shows that the network is properly configurated (I think) as the ps2 can connect to the archive.debian.org server and read the package lists, however, something still seems to be going wrong. Now I am a total Linux noob, so it could be I completely missed some things.
Does anyone know what I have done wrong? I would be very thankful if someone knows.


text:
Q: How can I check if a function throws an error which contains a text in Jest? function foo() {
  throw new Error('an error from (foo)');
}

I want to check if the error contains the text (foo), I tried:
expect(() => foo()).toThrow(expect.stringContaining('(foo)'))

But which is failed and does not work as expected:
 ● test › checks error containing text

    expect(received).toThrowError(expected)

    Expected asymmetric matcher: StringContaining "(foo)"

    Received name:    "Error"
    Received message: "an error from (foo)"

          1 | function foo() {
        > 2 |   throw new Error('an error from (foo)');
            |         ^

Although I can find a way with regex like:
expect(() => foo()).toThrowError(/[(]foo[)]/)

But which requires me to escape some special characters, which is not what I want.
Why is expect.stringContaining not supported in this case? Or do I miss anything?
A small demo for trying: https://github.com/freewind-demos/typescript-jest-expect-throw-error-containing-text-demo

A: toThrow doesn't accept a matcher. Per the documentation the optional error argument has four options:

You can provide an optional argument to test that a specific error is
thrown:

*

*regular expression: error message matches the pattern

*string: error message includes the substring

*error object: error message is equal to the message property of the object

*error class: error object is instance of class

In your case you can use either:

*

*the regex option
 .toThrow(/\(foo\)/)

(you don't need a character class just to escape parentheses) or by running the string through a function to escape it for you (see e.g. Is there a RegExp.escape function in JavaScript?) then passing it to new RegExp; or

*the string option
 .toThrow("(foo)")


text:
Q: character encoding issue with the BCP and ó I have a file that needs to go to Poland.  In my data I have an ó.  When I output the data to a table the ó is still there as the field is NVARCHAR.  When I cut and paste from the table into Excel or Notepad++ the ó stays
When I use the BCP utility to export the data, the ó is changed to a ¢ if I open the resulting text file in Excel or Notepad++.  If I change the encoding sometimes the character becomes a ˘.
I have tried the following command line switches, one at a time.
-n
-N
-w

A: Have you looked into -C?
-C { ACP | OEM | RAW | code_page }

    Specifies the code page of the data in the data file. code_page is
    relevant only if the data contains char, varchar, or text columns
    with character values greater than 127 or less than 32.

Given your table's data type is Unicode (NVARCHAR), you also have to use -c (which may lose some Unicode characters)
-c
    Performs the operation using a character data type. This option
    does not prompt for each field; it uses char as the storage type,
    without prefixes and with \t (tab character) as the field
    separator and \r\n (newline character) as the row terminator. -c
    is not compatible with -w.

    For more information, see [Use Character Format to Import or
    Export Data (SQL Server)].

CREATE TABLE [dbo].[Test] (
    [test] [nvarchar](100) NOT NULL
);

INSERT [dbo].[Test] ([test]) VALUES (N'helló wórld');

bcp dbo.Test out dbo.Test.dat -c -T -C ACP

-w without -c and -C ACP should also work as long as Notepad++ can detect the encoding (UCS-2 Little Endian). I had no problem with my simple example using Notepad++ 6.7.7.

Source: https://msdn.microsoft.com/en-us/library/ms162802.aspx


text:
Q: Change context properties from QML code Main goal: have a context property that is set by a item defined into a QML file (say file_1.qml), and which will be accessed at runtime by other item defined in a different QML file (say file_2.qml).
Question: Is it possible to set a new context property in file_1.qml and then read this property in file_2.qml?
(edit)
For example, I would need to use a value from file_2.qml in file_1.qml:
file_1.qml:
(...)
UiController.but_generate__onClicked(
   getContextProperty("sbx_money_quantity_value"),
   cal_daysoff.visibleMonth)
(...)

file_2.qml:
(...)
SpinBox {
        id: sbx_money_quantity
        objectName: "sbx_money_quantity"
        Layout.fillWidth: true
        minimumValue: 0
        maximumValue: 100000
        value: 20000

        onChanged: setContextProperty("sbx_money_quantity_value",value)
    }
(...)

Thanks!

A: You cannot access an item in some file from another one due to scope limitation. So you just need some proxy root object or may be some global singleton object or just to pass reference to one object to another one. For example:
File1.qml
Item {
    property someValue: 1
}

File2.qml
Item {
    property variant ref: null
    onChanged: ref.someValue = 2;
}

main.qml
File1 {
    item: file1
}
File2 {
    item: file2
    ref: file1
}


text:
Q: filter marker from json at google map : checkbutton doesn't work I searched the example code that filters the marker using checkbox at google map api . It gets marker data from arrangement.
below is the link:
https://jsfiddle.net/kimsngeon/5xw7jfkn/4/
Then I try to get marker data from "json" and make marker filter refer to the code, but it doesn't work.
The map and markers appear, but filter checkbox doesn't do anything.

var map;
var gmarkers1 = [];
var markers1 = [];

function initMap() {
    map = new google.maps.Map(document.getElementById('map-canvas'), {
          center: {lat: 37.5515, lng: 126.9250},
          zoom: 15
        });

    addMarker()
}

function addMarker() {
  console.log('creating markers')

  geojson_url = 'stores.json'
  $.getJSON(geojson_url, function(result) {
      // Post select to url.
      data = result['features']
      $.each(data, function(key, val) {
        var pos = new google.maps.LatLng(
                parseFloat(val['geometry']['coordinates'][1]),
                parseFloat(val['geometry']['coordinates'][0]));
        var title = val['properties']['title']
        var content = val['properties']['title']
        var category = val['properties']['description']

        var marker1 = new google.maps.Marker({
          position: pos,
          title: title,
          category: category,
          map: map,
          properties: val['properties']
         });

        gmarkers1.push(marker1);

      });
  });
}

updateView = function (element) {
   if (element) {
        //Get array with names of the checked boxes
        checkedBoxes = ([...document.querySelectorAll('input[type=checkbox]:checked')]).map(function(o) { return o.id; });
        console.log(checkedBoxes);
        for (i = 0; i < markers1.length; i++) {
          marker = gmarkers1[i];
            console.log(marker.category)
            //Filter to show any markets containing ALL of the selected options
          if(typeof marker.category == 'object' && checkedBoxes.every(function (o) {
        return (marker.category).indexOf(o) >= 0;})){
              marker.setVisible(true);
          }
            else {
              marker.setVisible(false);
          }
        }
   }
   else {
      console.log('No param given');
  }
}

$(document).ready(function() {
$(function() {
  $('input[type="checkbox"]').bind('click',function() {
    $('input[type="checkbox"]').not(this).prop("checked", false);
    })
  });
    });
// Init map
initMap();

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

    <input type="checkbox" id="hansik" onchange="updateView(this);"/> hansik
    <input type="checkbox" id="jungsik" onchange="updateView(this);"/> jungsik
    <input type="checkbox" id="yangsik" onchange="updateView(this);"/> yangsik

and this is my json link
http://likenikegirl.dothome.co.kr/stores.json

A: You have two issues with your code:

*

*your array name is gmarkers1.  Change this line (in the updateView function):

for (i = 0; i < markers1.length; i++) {

to:
for (i = 0; i < gmarkers1.length; i++) {

*category (in the example you based your code off of) is an array.  Change:

var marker1 = new google.maps.Marker({
          position: pos,
          title: title,
          category: category,
          map: map,
          properties: val['properties']
         });

To:
        var marker1 = new google.maps.Marker({
          position: pos,
          title: title,
          category: [category],
          map: map,
          properties: val['properties']
         });

proof of concept fiddle

var map;
var gmarkers1 = [];
var markers1 = [];

function initMap() {
    map = new google.maps.Map(document.getElementById('map-canvas'), {
          center: {lat: 37.5515, lng: 126.9250},
          zoom: 15
        });

    addMarker()
}

function addMarker() {
  console.log('creating markers')

  geojson_url = 'stores.json'
  //$.getJSON(geojson_url, function(result) {
      // Post select to url.
      var result = jsonData;
      data = result['features']
      $.each(data, function(key, val) {
        var pos = new google.maps.LatLng(
                parseFloat(val['geometry']['coordinates'][1]),
                parseFloat(val['geometry']['coordinates'][0]));
        var title = val['properties']['title']
        var content = val['properties']['title']
        var category = val['properties']['description']

        var marker1 = new google.maps.Marker({
          position: pos,
          title: title,
          category: [category],
          map: map,
          properties: val['properties']
         });

        gmarkers1.push(marker1);

      });
  // });
}

updateView = function (element) {
   if (element) {
        //Get array with names of the checked boxes
        checkedBoxes = ([...document.querySelectorAll('input[type=checkbox]:checked')]).map(function(o) { return o.id; });
        console.log(checkedBoxes);
        for (i = 0; i < gmarkers1.length; i++) {
          marker = gmarkers1[i];
            console.log(marker.category)
            //Filter to show any markets containing ALL of the selected options
          if(typeof marker.category == 'object' && checkedBoxes.every(function (o) {
        return (marker.category).indexOf(o) >= 0;})){
              marker.setVisible(true);
          }
            else {
              marker.setVisible(false);
          }
        }
   }
   else {
      console.log('No param given');
  }
}

$(document).ready(function() {
$(function() {
  $('input[type="checkbox"]').bind('click',function() {
    $('input[type="checkbox"]').not(this).prop("checked", false);
    })
  });
    });
// Init map
initMap();

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

    <input type="checkbox" id="hansik" onchange="updateView(this);"/> hansik
    <input type="checkbox" id="jungsik" onchange="updateView(this);"/> jungsik
    <input type="checkbox" id="yangsik" onchange="updateView(this);"/> yangsik


text:
Q: How can I retrieve WPA keys? I use Ubuntu 12.04.1
I try iwlist, but it is what I have:
user@comp-1:~$ sudo iwlist wlan0 keys
wlan0     2 key sizes : 40, 104bits
          4 keys available :
        [1]: off
        [2]: off
        [3]: off
        [4]: off
          Current Transmit Key: [1]
user@comp-1:~$ sudo iwlist wlan0 wpakeys
wlan0     2 key sizes : 40, 104bits
          4 keys available :

Error reading wpa keys (SIOCGIWENCODEEXT): Operation not supported

I want know WPA key for give it to wpa_supplicant. I tried use wpa_passphrase, but I have follow line in log:
WPA: 4-Way Handshake failed - pre-shared key may be incorrect


text:
Q: Problems upgrading jquery 1.4.2 to 1.5.1 I'm trying to upgrade from jquery 1.4.2 to 1.5.1 and I'm getting the following error:
Uncaught Syntax error, unrecognized expression: [rel*=address:]
I can't figure out what it's related to.  Any ideas?

A: I think you have to escape the colon in the attribute:
If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\.bar").
http://api.jquery.com/category/selectors/
Earlier versions of jquery seemed to be more forgiving

A: attribute selector needs to be enclosed by quote "
i.e. [rel*="address:"]

A: It may be that jQuery 1.4.2 just so happened to accept your invalid expression, but the correct expression is:
[rel*="address:"]

This is why it's very important that you read the documentation and use the correct syntax, regardless of whether or not your broken code "appears to work".


text:
Q: Integral Issues. $\displaystyle \int \cosh ^2t\,\sinh ^5t \; \textrm{d}t \,$
Can't for the life of me figure this one out. I have tried various substitutions. The pythagorean hyperbolic identity, the double variable identity. Nothing. Could someone give me a push please.

A: With some manipulation using $\cosh^2x-\sinh^2x=1\implies \sinh^4t=(\cosh^2t-1)^2$:
$$\cosh ^2t\,\sinh ^5t =\sinh t \cosh^6 t-2 \sinh t \cosh^4 t+\sinh t \cosh^2 t$$
Now try $x=\cosh t,{\rm d}x/{\rm d}t=\sinh t$

A: Using $u=e^t$, you have
$$\frac1{2^7}\int(u+u^{-1})^2(u-u^{-1})^5\frac{du}u=\frac1{2^7}\int\left(
u^6
-3u^4
+u^2
+5
-\frac5{u^2}
-\frac1{u^4}
+\frac3{u^6}
-\frac1{u^8}
\right)du.$$
Hence,
$$\frac1{2^7}\left(
\frac{u^7}7
-\frac{3u^5}5
+\frac{u^3}3
+5u
+\frac5{u}
+\frac1{3u^3}
-\frac3{5u^5}
+\frac1{7u^7}
\right)+C,$$
$$\frac1{2^6}\left(
\frac{\cosh 7t}7
-\frac{3\cosh5t}5
+\frac{\cosh3t}3
+5\cosh t
\right)+C,$$


text:
Q: How to assign within apply family? I have data.frame that contains several factors and i want to rename factor levels for all of these factors. E.g.:
mydf <- data.frame(col1 = as.factor(c("A","A",NA,NA)),col2 = as.factor(c("A",NA,NA,"A")))
mydf <- as.data.frame(lapply(mydf,addNA))

Note that the real life example has way more than just two columns. Hence I would like to use apply to assign other level names to all of these columns, just like in:
levels(mydf$col1) <- c("1","0")

I tried the following but it did not work…
 apply(mydf,1,function(x) levels(x) <- c("1","0"))

I am not really surprised it doesn't work but I have no better ideas right now. Should I use with maybe?
EDIT: I realized I made a mistake here by oversimplifying things. I used addNA to account for the fact, that NAs should not handled as NAs anymore. Thus I also want to relabel them.
This doesn't work with Andrie's suggestion and returns the following error message:
 labels = c("1",  : invalid labels; length 2 should be 1 or 1

Note that I updated my example df.

A: You can change levels by reference using setattr() from packages bit or data.table. This avoids copying the whole dataset, and since you said you have a lot of columns ...
require(bit)          # Either package
require(data.table)   #
setattr(mydf[[1]],"levels",c("1","0"))
setattr(mydf[[2]],"levels",c("1","0"))

That can be done in a simple for loop which is very fast.  It is your responsibility to ensure that you replace the levels vector with a vector of the same length, otherwise the factor may no longer be valid. And, you have to replace the whole levels vector with this method. There is an internal way in data.table to replace particular level names by reference, but probably no need to go that far.


text:
Q: AttributeError: 'str' object has no attribute 'is_xml' Я парсю дату с этого портала.Эту часть

Для этого написал такой код:
def get_item_datetime(item_page, resource_page, datetime_main_rule, datetime_rule, datetime1_rule):
    # < Проверка item_page на None.
    if item_page is None:
        return
    soup = BeautifulSoup(item_page, resource_page,  'lxml')
    main_page_datetime = soup.find(datetime_main_rule[0],{datetime_main_rule[1]:datetime_main_rule[2]})
    if (len(datetime_main_rule) == 3):
        main_page_datetime = soup.find(datetime_main_rule[0],{datetime_main_rule[1]:datetime_main_rule[2]})
    else:
        item_datetime = soup.find(datetime_rule[0],{datetime_rule[1]:datetime_rule[2]})
        if item_datetime is not None:
            item_datetime = soup.find(datetime_rule[0],{datetime_rule[1]:datetime_rule[2]}).text
            item_datetime = dateparser.parse(item_datetime, date_formats=['%d %B %Y %H'])
        else:
            if (len(datetime1_rule) == 3):
                item_datetime = soup.find(datetime1_rule[0],{datetime1_rule[1]:datetime1_rule[2]}).text
                item_datetime = dateparser.parse(item_datetime, date_formats=['%d %B %Y %H'])
            else:
                item_datetime = ''
            return (main_page_datetime,item_datetime)

В этом месте я парсю  именно с этой страницы дату:
soup = BeautifulSoup(item_page, resource_page,  'lxml')
    main_page_datetime = soup.find(datetime_main_rule[0],{datetime_main_rule[1]:datetime_main_rule[2]})
    if (len(datetime_main_rule) == 3):
        main_page_datetime = soup.find(datetime_main_rule[0],{datetime_main_rule[1]:datetime_main_rule[2]})

В item_pageу меня хранятся html данные с этой страницы для bs4
В resource_page у меня хранятся html данные с этой главной страницы  для bs4
Traceback:
Traceback (most recent call last):
  File "C:/Users/Администратор/PycharmProjects/Task/parser.py", line 146, in <module>
    call_all_func(resources)
  File "C:/Users/Администратор/PycharmProjects/Task/parser.py", line 128, in call_all_func
    item_datetime = get_item_datetime(item_page,resource_page,datetime_main_rule,datetime_rule,datetime1_rule)
  File "C:/Users/Администратор/PycharmProjects/Task/parser.py", line 48, in get_item_datetime
    soup = BeautifulSoup(item_page, resource_page,  'lxml')
  File "C:\Users\Администратор\AppData\Local\Programs\Python\Python37-32\lib\site-packages\bs4\__init__.py", line 258, in __init__
    self.is_xml = builder.is_xml
AttributeError: 'str' object has no attribute 'is_xml'

Process finished with exit code 1

Единственное что я понял,так это
у объекта 'str' нет атрибута 'is_xml'
Откуда начать копать?
P.S:Читал документацию bs4 ничего такого там не нашел.

A: Судя по документации у BeautifulSoup первые 3 аргумента следующие: markup, features и builder.

*

*markup для HTML-верстки (у вас это item_page);

*features для парсера (у вас это resource_page, но должен быть lxml);

*builder для подкласса TreeBuilder.

Таким образом у вас должно быть вот так:
soup = BeautifulSoup(item_page, 'lxml')


text:
Q: How to pass a service to constructor with only optional parameters? I have a Typescript class where all its constructor parameters are optional. How can I pass a service to it, as it acts as a required parameter ?
Current Situation :
constructor(label ? : String, location ? : any) {...}

Sort of what I am looking for :
constructor(private myService: MyService, label ? : String, location ? : any) {...}

A:
How can I pass a service to it, as it acts as a required parameter

You get an instance of the service using angular injector.
More
Get Injector : https://github.com/angular/angular/issues/4112#issuecomment-153811572

A: As @basarat mentioned you can use the Angular injector to "get" services which was explained here: Angular 2 conditionally inject service in component but this is not a suggested pattern as it seems from the comment section.

What you are looking for is explained here: https://angular.io/guide/dependency-injection#optional-dependencies

You can tell Angular that the dependency is optional by annotating the constructor argument with @Optional()

after annotating the dependency you simply do an if check in the constructor to see whether it's provided or not.


text:
Q: Angular 2 - ng2-dragula <column *ngFor="let col of columns">
  ...

        {{ ticket }}

</column>

I have few columns. Every column contain array with tickets. How can I detect which ticket moved and where?

A: Add id to your dragula Div. In your case use col.id
step -1

            {{ ticket }}

step 2  subscribe drop event.
 dragulaService.drop.subscribe((value) => {
                this.onDropModel(value.slice(1));
            });

step 3
on the on the onDrag(value) function  args are el, target, source, sibling
value[1] ==> target.id
value[2] ==> source.id
based on the id you can detect ticket moved between columns


text:
Q: Jquery FullCalendar Extend Start Date or End Date I am using Jquery FullCalendar.
Here is the link of calender I am using : http://arshaw.com/fullcalendar/
I have a case where I have startdate and enddate.
Now if I extend startdate or enddate by dragging it.
How can I get the response event that was triggered when I dragged/extend the date?
For Example:
When I move the event from one date to another I use eventDrop. It gives me the days added or subtracted to the original dates.
I need the same solution for extending startdate or enddate.
Possibilities I am facing:
Original Dates : 2013-12-04 to 2013-12-07
When Extends   : 2013-12-04 to 2013-12-10
OR
When Extends  : 2013-12-01 to 2013-12-07
Here are the cases I am facing. How can I track that what event I performed in Calender and what parameters it pass ?

A: You can use eventResize
below is the example from offical site:
http://arshaw.com/fullcalendar/docs/event_ui/eventResize/
$('#calendar').fullCalendar({
    events: [
        // events here
    ],
    editable: true,
    eventResize: function(event,dayDelta,minuteDelta,revertFunc) {

        alert(
            "The end date of " + event.title + "has been moved " +
            dayDelta + " days and " +
            minuteDelta + " minutes."
        );

        if (!confirm("is this okay?")) {
            revertFunc();
        }

    }
});

A: Jquery Fullcalender is providing alot of options where you play around wth your events , as per you requirement
Original Dates : 2013-12-04 to 2013-12-07
When Extends : 2013-12-04 to 2013-12-10
This is when you extend the event duration, to catch the event where you change the end date you can use the below code
eventResizeStart: function (event, jsEvent, ui, view) {
    console.log('RESIZE START ' + event.title);

},
eventResizeStop: function (event, jsEvent, ui, view) {
    console.log('RESIZE STOP ' + event.title);

},
eventResize: function (event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view) {
    console.log('RESIZE!! ' + event.title);
    console.log(dayDelta + ' days'); //this will give the number of days you extended the event
    console.log(minuteDelta + ' minutes');

},

Original Dates : 2013-12-04 to 2013-12-07
When Extends : 2013-12-01 to 2013-12-07
This is when you pre-pone the event , then you can use the below code
eventDragStart: function (event, jsEvent, ui, view) {
    console.log('DRAG START ' + event.title);
    console.log(this);
},
eventDragStop: function (event, jsEvent, ui, view) {
    console.log('DRAG STOP ' + event.title);
    console.log(this);
},
eventDrop: function (event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
    console.log('DROP ' + event.title);
    console.log(dayDelta + ' days'); //this will give the number of days you dragged before or after
    console.log(minuteDelta + ' minutes');
    console.log('allday: ' + allDay);

},

As per you comment above that if you want to restrict the user from dragging a event or resizing a event , then you can use eventDurationEditable , this is true by default
eventDurationEditable:false,


text:
Q: Examples of monotone functions where "number" of points of discontinuity is infinite We know that if $f:D(\subseteq \mathbb{R})\to\mathbb{R}$ be a monotone function and if $A$ be the set of points of discontinuity of $F$ then $\left\lvert A \right\rvert$ is countable. Where $\left\lvert A \right\rvert$ denotes the cardinality of $A$.
My question is,

If $D=[a,b]$ then does there exist any function for which $\left\lvert A \right\rvert=\aleph_0$ ?

Actually the question arose when I attempted to prove that $\left\lvert A \right\rvert$ is countable. Let me briefly discuss the argument.
Proof (certainly wrong in view of the comment below but can't find the flaw in the following argument)

Assume that $\left\lvert A \right\rvert$ is infinite. Then consider the quantity $$\displaystyle\lim_{x\to x_0+}f(x)-\displaystyle\lim_{x\to x_0-}f(x)$$for all $x_0\in A$. Now consider, $$B=\left\{\left\lvert\lim_{x\to x_0+}f(x)-\lim_{x\to x_0-}f(x)\right\rvert\mid x_0\in A\right\}$$Note that $B$ is bounded and $B\ne \emptyset$. So, $\sup B$ exists. Now define, $$\sup B\ge d_n> \dfrac{(n-1)\sup B}{n}$$ where $d_n\in B\setminus \{d_1,d_2,\ldots,d_{n-1}\}$
Then the series $\displaystyle\sum_{i=1}^\infty d_i$ diverges.

My conclusion followed from this argument.

A: Let me answer by first constructing a non-decreasing function $[0,1]\rightarrow[0,1]$ with a discontinuity at every point $2^{-n}$ for $n>0$. In particular, set $f(x)=1$ for every $x\in (\frac{1}2,1]$ and say $f(x)=\frac{f(2x)}2$ for every $x\in [0,1]$. This defines a function with infinitely many discontinuities with the following self-similar graph:
$\hskip1.5in$
One could also write this $f$ in closed form as $f(x)=2^{\lfloor\log_2(x)\rfloor}$. One could also consider the function $g(x)=f(x)+x$ if one desires a strictly increasing function with the same property.
Now, let us examine why your proof does not properly handle this case. The set $B$ is precisely:
$$B=\{2^{-n}:n>0\}\cup \{0\}$$
and satisfies
$$\sum_{b\in B}b=1$$
which immediately is a problem for your argument. Your argument correctly takes that there exists a $b\in B$ in any open interval around $\sup B$, but it incorrectly assumes these to be distinct. In this particular instance, $\sup B$ is the maximum of $B$ and is isolated from other points (rather than situation you seem to be imagining, where $\sup B$ is not in $B$, but rather is an accumulation point of $B$).

A: *

*Take the graphic of any function you like, which is both continuous and monotonous over a finite interval of your choice $[a,~b]$.

*Map said interval to $[0,1]$ using $x\mapsto\dfrac{x-a}{b-a}$.

*Divide the new interval $[0,1]$ into an infinite number of subintervals of the form $\bigg(\dfrac1{n+1},\dfrac1n\bigg]$.

*Let the graphic on $\bigg(\dfrac12,1\bigg]$ untouched, and move the graphic on $\bigg[0,\dfrac12\bigg]$ upwards by $\dfrac1{2^2}$, if the function is descending, or downwards by $\dfrac1{2^2}$, if it's ascending.

*Similarly for $\bigg(\dfrac13,\dfrac12\bigg]$ and $\bigg[0,\dfrac13\bigg]$, leaving the former untouched, and translating the latter vertically by $\dfrac1{3^2}$, etc.

*I intentionally chose the quantum of translation $\dfrac1{n^2}$ instead of just $\dfrac1n$, because I wanted to avoid follow up questions of the form: But then the value in $0$ will tend towards $\pm\infty$, since the harmonic series diverges, thus rendering the length of the function's value domain infinite. How could we avoid that, so that both its definition domain and image domain are finite ?
Hope this helps!


text:
Q: Does the surface area divided by bounding box feature have a name? I'm writing a connected component system and one of the descriptors I can easily compute is the surface area along with the component's rectangular bounding box.
What is surface area divided by bounding area called? (or any mixture of these two parameters).
For example, if my object were a rectangle, this parameter would be 1.0.

A: Extent or rectangularity, apparently:

Extent of an image object is defined as area of the image object
divided by the area of its bounding rectangle.

Source: Question text in https://dsp.stackexchange.com/questions/49026/what-is-the-application-difference-between-extent-and-solidity-in-image-processi

Rectangularity is the ratio of the object to the area of the minimum
bounding rectangle.

Source: Page 45 in http://www.cyto.purdue.edu/cdroms/micro2/content/education/wirth10.pdf
But the definitions I've run across do not always fully specify the rectangle. The ambiguity is related to the concept of "ferret box". Ferret boxes' edges do not have to be parallel to the image axes like good old bounding boxes. So depending on which you choose, your "extent" value might change.


text:
Q: Spinner at bottom of recyleview in kivy and kivymd I want to user to see the spinner when they reach the bottom of the Recycleview..
In this bellow code the spinner is visible in the viewport this is the issue so there is some code below..
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.recycleview import RecycleView
from kivy.uix.scrollview import ScrollView
from kivy.uix.screenmanager import Screen

Builder.load_string('''
<MyScreen>:
    ScrollView:
        BoxLayout:
            orientation:"vertical"
            size_hint_y:None
            height:root.height
            RV:
                size_hint_y:None
                height:root.height
                viewclass: 'Button'
                RecycleBoxLayout:
                    default_size: None, dp(56)
                    default_size_hint: 1, None
                    size_hint_y: None
                    height: self.minimum_height
                    orientation: 'vertical'
                    size_hint_y:None
                    height:self.minimum_height
            MDSpinner:
                size_hint:None,None
                width:dp(40)
                height:dp(20)
                pos_hint:{"center_x":.5}

''')

class MyScreen(Screen):
    pass

class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'text': str(x)} for x in range(25)]

class TestApp(MDApp):
    def build(self):
        return MyScreen()

if __name__ == '__main__':
    TestApp().run()

Thanks in advance..

A: If you want the last item in the RecycleView to be a spinner, you cannot do that with a viewclass of Button (unless you can make a Button look like a Spinner). However, you can design your own viewclass that can look like either a Button or a Spinner. So defining a custom viewclass like this:
class MyViewClass(RelativeLayout):
    text = StringProperty('')  # text for the Button
    spinner = BooleanProperty(False)  # if True, show a Spinner instead

Then add a rule for it in your kv:
<MyViewClass>:
    Button:
        text: root.text
        opacity: 0 if root.spinner else 1
    MDSpinner:
        pos_hint:{"center_x":.5}
        opacity: 1 if root.spinner else 0
        active: True if root.spinner else False
        size_hint: None, None
        height: root.height
        width: root.height

The above rule uses opacity to determine whether the Button or the Spinner is visible. And the active attribute of the MDSpinner is used to avoid having a spinning MDSpinner running in the items where it is not visible.
Then just specify MyViewClass as the viewclass:
viewclass: 'MyViewClass'

And remove the old MDSpinner from your kv.
The last thing to do is to adjust your data:
class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'text': str(x), 'spinner': False} for x in range(25)]
        self.data.append({'text': '', 'spinner': True})

The data now sets spinner to False for all the entries, and adds an extra entry with spinner set to True.


text:
Q: Is it possible to combine multiple SHA1 states to get a final state in Golang? In Go1.13, I have an upload server. This server accepts 2 types of upload.
Chunked and Chunked+Threaded. On chunked uploads everything works expected. I calculate every chunk while they are writing to disk. User can upload multiple chunks one-by-one in good order.
This means, I can save every chunk's SHA1 state to disk using BinaryMarshaler, then read previous state and continue to calculate next chunks until I find final hash. Final hash gives me whole file's SHA1 perfectly.
When its ordered, I can append to existing state. But problem starts on threaded.... (Simultaneously)
    hashComplete := sha256.New()
    // read previous sttate from disk
    state, err := ioutil.ReadFile(ctxPath)
    if err != nil {
        return err
    }

    if len(state) > 0 {
        unmarshaler, _ := hashComplete.(encoding.BinaryUnmarshaler)
        if err := unmarshaler.UnmarshalBinary(state); err != nil {
            return err
        }
    }

    // In here im writing file to disk and hash. file object is simple File.
    writer := io.MultiWriter(file, hashComplete)
    n, err := io.Copy(writer, src) // src is source (io.Reader)

    marshaler, _ := hashComplete.(encoding.BinaryMarshaler)
    newState, err := marshaler.MarshalBinary()
    if err != nil {
        return err
    }

    shaCtxFile.Write(newState) // Here im saving last state to disk.

    // Then later, after upload finishes, I read this file and get the SHA1 hex from it. It is correct.

Now this is chunked upload in specific/good order. The other upload method is Chunked+Threaded. This mean, User can upload chunks simultaneously at the same time then send a request to concatenate them together in given order (at last request).
I already calculate each chunk's SHA1 and save it to disk.
My question is it is possible to combine those states and get the final hash or do I need to rehash after concatenate. Is there a way to combine those states?

A: Assuming you mean the final hash over the whole file, then no, you cannot combine multiple SHA-1 hashes over partial data to create a hash over the whole file, as if it was calculated at once. The reason for this is that the initial SHA-1 state is always the same, and rehashing will restart at that specific state. Furthermore, the final block is padded and a length is added (internal to the hash function) before the final hash value is calculated.
However, you can of course create a hash list or hash tree, where you define how big the blocks are. Then you can hash all the hashes over the chunk to create a topmost hash value. Now you have a different hash value than just the SHA-1 over the file, but the hash is consistent with your definition and can be recalculated, even in a multi-threaded fashion. It is still unique for the data within the file (assuming of course that put in the hash values sequentially) so it can be used to validate the integrity of the file. And, as far as I know, that's for normal secure hash function the only way to use multi-threaded hash calculation.
For more information, Google about Merkle-trees.

Of course, SHA-1 has been broken for collision resistance. Unfortunately, that's exactly what you are using it for. So please use SHA-256. If 256 bits is too much then using SHA-256 and taking the leftmost 160 bits is a more secure alternative.


text:
Q: Crystal Reports in ASP.NET - Some Work, Some Don't I have 4 similar Crystal Reports made. When I set the report name to the CrystalReportSource (using the drop down, so I know it's spelled correctly), only 2 of them will give me a little preview, while the other 2 show nothing but the CrstalReportViewer control.
The same 2 reports show a blank report (nothing but the toolbar) when I run the web app.
All 4 reports display correctly in the report designer.
I've looked through every property I can think of, but don't see any difference between the ones that work, and the ones that don't.
Maybe someone can give me a better idea of where to look.
In case it makes a difference, 3 of the reports were clones off of the previous report with the database location changed.
Again, they all work in the designer.
Any ideas? :-)
<%@ Page Title="" Language="VB" MasterPageFile="~/AFRA.master" AutoEventWireup="false" CodeFile="ReportViewer.aspx.vb" Inherits="ReportViewer" %>
<%@ Register assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" namespace="CrystalDecisions.Web" tagprefix="CR" %>

<asp:Content ID="Content3" ContentPlaceHolderID="main" Runat="Server">
    <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
    AutoDataBind="true" DisplayGroupTree="False" Height="50px"
        ReportSourceID="CrystalReportSource1" />
    <CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
        <Report FileName="RPT\StatsRevenue.rpt">
        </Report>
    </CR:CrystalReportSource>
</asp:Content>

A: I finally just figured that those 2 reports were probably just corrupt. Since they were modified reports of clones of working reports, it only took me about an hour to just make new ones from scratch.


text:
Q: How to get IP from hostname on iOS How do I get the IP from a given hostname on iOS?
I've tried Google but found nothing.

A: The following code works with both IPv4 and IPv6. It uses getaddrinfo() to
retrieve a list of IP addresses for a host, and getnameinfo() to convert
each IP address into a string. (Error checking omitted for brevity.)
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;        // PF_INET if you want only IPv4 addresses
hints.ai_protocol = IPPROTO_TCP;

struct addrinfo *addrs, *addr;

getaddrinfo("www.google.com", NULL, &hints, &addrs);
for (addr = addrs; addr; addr = addr->ai_next) {

    char host[NI_MAXHOST];
    getnameinfo(addr->ai_addr, addr->ai_addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST);
    printf("%s\n", host);

}
freeaddrinfo(addrs);


text:
Q: why I get ENONET: no such file or directory when the file exists? node.js I'm doing a crash course on YouTube before I dive deeper into React and NodeJs.
Im trying to check the url from the code and display the right page.
so if the url ends with '/about' I will display the about html.
the problem is that it's not displaying the page.
the file is exist.
it says: ENOENT: no such file or directory.
this is the code:
const server = http.createServer((req,res)=>{
    let filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url)

// Checking the extension
let extName = path.extname(filePath)

// Content Type
let contentType = 'text/html'

// check ext and set ceontent type
switch (extName) {
    case '.js':
        contentType = 'text/javascript'
        break
    case '.css':
        contentType = 'text/css'
        break
    case '.json':
        contentType = 'application/json'
        break
    case '.png':
        contentType = 'image/png'
        break
    case '.jpg':
        contentType = 'image/jpg'
        break
}

console.log(contentType, "here")

// Read file
fs.readFile(filePath, (err,content) => {
    console.log(filePath)
    if (err) {
        console.log(err.message)
        if (err.code == 'ENONET') {
            //Page not found
            fs.readFile(path.join(__dirname, 'public', '404.html'), (err,content) => {
                res.writeHead(200, {'Content-Type': 'text/html'})
                res.end(content, 'utf-8')
            })
        } else {
            // some server error
            res.writeHead(500)
            res.end(`Server Error ${err.code}`)
        }
    }else {
        // Success
        res.writeHead(200, {'Content-Type': contentType})
        res.end(content,'utf-8')
    }
})
})

//creating the port either getting it from the host, or setting it to 5000
const PORT = process.env.PORT || 5000

// setting the server to listen on the port, and it get's also a call back so i print the server listens
server.listen(PORT, () => console.log(`Server Listening on port ${PORT}`))

I know that the problem is that I miss the extension in the filePath name.
but the thing is that the person I learn from, have the exact same code, and it works for him.

A:
I know that the problem is that I miss the extension in the filePath name. but the thing is that the person I learn from, have the exact same code, and it works for him.

This code could work only if the file about exists in the public directory (with no file extension on it).  So, rather than discuss how it worked for someone else, we should discuss how this code can work for you or what you would have to change in it to make it work for you.
Your code expects the path that is passed in the request to be an entire filename in your public directory.
So, when you send a request in for /about, you try to do fs.readFile("about", ...).  That's the file that has to exist.
If you want /about to serve a file named /about.html in your file system, then you have check if extName is empty and, if so, add ".html" to the filename to give it a default extension.  Or, in some cases, you might check for more than one possibility in the file system.  If about isn't found, then check for about.html.

You could add a default .html path by changing this part:
// Checking the extension
let extName = path.extname(filePath);

to this:
// Checking the extension
let extName = path.extname(filePath);

if (!extName) {
    extName = ".html";
    filePath += ".html";
}

FYI, there's a misspelling too.  Change this:
if (err.code == 'ENONET')

to this:
if (err.code == 'ENOENT')

Another word of caution, your server may be vulnerable to some requests putting ../ into the path and then being able to access files outside of your public directory.  Most browsers will stop that, but scripted requests could do it.


text:
Q: MySQL query returns too many results with double join Ok I'm trying to return these 4 values for any entry in simacc_payments that has a verified value of 0.
    SELECT themes.value, members.real_name, simacc_payments.pay_amt, simacc_payments.pay_date
    FROM simacc_payments
    INNER JOIN members
    ON simacc_payments.id_member = members.id_member
    INNER JOIN themes
    ON simacc_payments.id_member = themes.id_member
    WHERE verified = "0"
    ORDER BY members.real_name ASC, simacc_payments.pay_date DESC

The array I'm getting out as my result comes out like this, simplied
    real_name, id_member, pay_amt, pay_date
    real_name, value, pay_amt, pay_date
    real_name, id_member, payments.pay_amt, payments.pay_date
    real_name, value, pay_amt, pay_date

So every second entry in the array is correct, I know this has something to do with the join but I can't for the life of me figure out how to fix it.  Please someone give me the answer while I still have some hair left :)

A: So just for anyone who ends up here with similar problems.  My issues was cause by a second value in my Themes table for each use.  Essentially I had to add an extra condition to my WHERE clause to filter these out.  Hope that helps someone.


text:
Q: Getting 404 errors on getting resources after deploying Flutter Web project into Azure Web I got this error 404 which is not loading my resources and assets from my created flutter web application after deploying into Azure web app.
See the example photo:

I use FTP method to upload files and used FileZilla as my tool. I upload all the files include in this generated files after running "flutter build web"
build/web/all_my_files

I already configured properly my pubspec.yaml file.
Note: This works all fine on GitHub pages but after I tried to deploy on azure this happens and I don't know why.

A: The web.config should be configured with the other external static files like .json. It should be deployed beside the Flutter index.html file.
The web.config should be like the following:
<?xml version="1.0"  encoding="utf-8" ?>

<configuration>
    <system.webServer>
        <staticContent>
            <!-- JSON Manifests -->
            <mimeMap fileExtension=".json" mimeType="application/json" />
            <!-- Fonts -->
            <mimeMap fileExtension=".otf" mimeType="application/octet-stream" />
            <mimeMap fileExtension=".ttc" mimeType="application/octet-stream" />
            <mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
            <mimeMap fileExtension="woff" mimeType="application/font-woff" />
            <mimeMap fileExtension="woff2" mimeType="application/font-woff2" />
        </staticContent>
    </system.webServer>
</configuration>


text:
Q: CSV access via ADO.NET in 64-bit? In a 32-bit .NET app, I can use this OLEDB connection string to connect to a CSV file via ADO.NET:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\foo;"

or this ODBC one:
"Driver={{Microsoft Text Driver (*.txt; *.csv)}};Dbq=c:\foo"

However there apparently arent 64-bit versions of either the OLEDB Jet drivers or the ODBC text driver.
I could parse the CSV line by line or run the app in 32-bit mode, but ideally I'd just like to find a different driver that runs as 64-bit.
Any ideas?

A: I had this exact same problem and after much trial & error this was what I found that worked:
1. Enable Adhoc procedures
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

2. Install this file on server:
http://www.microsoft.com/downloads/en/details.aspx?familyid=C06B8369-60DD-4B64-A44B-84B371EDE16D&displaylang=en
3. Use this query format:
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=C:\SQL\;HDR=Yes;','SELECT * FROM [test.csv]');

4. Enable OLE Automation procedures:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE with override
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE with override;
GO

A: Alexis,
Do you need a driver at all?  If you just need to read a CSV file line by line there are a number of free parsers out there.  If you need to also write out a CSV check out FileHelpers.

A: It's not a driver, but I've been pleased with Sebastien Lorion's CSV reader.  Note that I've never used it in a 64-bit environment, but I'm not aware of any compatibility issues.
http://www.codeproject.com/KB/database/CsvReader.aspx

A: I ended up having to convert my application to 32-bit because I was having the same problem, although with accessing a Microsoft Access Database. I know this will work, but you may not want this solution. If anyone knows the answer to this question I woud love to hear it as well.

A: You're in luck-- in December 2010 Microsoft published a a 64-bit OLEDB driver for CSV and XLSX files!
See this answer for download links, install details, connection strings, etc.


text:
Q: Make offsetting file contents during build I'm trying to use Make to ... make modular Dockerfiles. Long story short, I want to centralize certain elements and make the composable and reusable, like classes and functions really, but the Dockerfile syntax does not - and according to the developers, will not - offer any facilities in the image of C's #include or similar composability solutions. Not to worry, #include and friends to the rescue!
Except...
I have the following Makefile in my project:
BUILD_DIR := ${CI_PROJECT_DIR}/build

TEMPLATE_FILES := $(shell find ${CI_PROJECT_DIR} -name '*.build')
TEMPLATE_FILENAMES := $(foreach file,$(TEMPLATE_FILES),$(BUILD_DIR)/$(notdir $(file)).built)
BUILT_TEMPLATES := $(TEMPLATE_FILENAMES:.build.built=.built)

DOCKER_FILES := $(shell find ${CI_PROJECT_DIR} -name '*.Dockerfile')
DOCKER_OBJS := $(foreach file,$(DOCKER_FILES),$(BUILD_DIR)/$(notdir $(file)))

all: $(BUILT_TEMPLATES) $(DOCKER_OBJS)

$(BUILD_DIR)/%.built: $(TEMPLATE_FILES) $(BUILD_DIR) # build any templated Dockerfiles
    cpp -E -P -o $(BUILD_DIR)/$(notdir $@) -I ${CI_PROJECT_DIR}/modules $<
    sed -i 's/__NL__ /\n/g' $(BUILD_DIR)/$(notdir $@)

$(BUILD_DIR)/%.Dockerfile: $(DOCKER_FILES) $(BUILD_DIR)
    cp $< $(BUILD_DIR)/$(notdir $(@))

$(BUILD_DIR):
    mkdir -p $(BUILD_DIR)

.PHONY: clean
clean:
    -rm -r $(BUILD_DIR)

The objective is to run the templated Dockerfiles through GCC to compile the #includes in them into proper Docker instructions, and just copy the rest of the files. Sounds simple enough.
Except that it looks like all the target files are "offset" from their sources - like the file names are correct, but the contents are from a file elsewhere in the list, and with no discernible order either.

One thing that I'm fairly sure is wrong - but even more wrong otherwise - is the line
$(BUILD_DIR)/%.built: $(TEMPLATE_FILES) $(BUILD_DIR) # build any templated Dockerfiles

By all manuals and documentation, it ought to be
$(BUILD_DIR)/%.built: %.build $(BUILD_DIR) # build any templated Dockerfiles

but that's even worse, because then Make just says make: *** No rule to make target '/docker/build/runner-dart-2-18-firebase.built', needed by 'all'.  Stop.
I'm out of ideas here, along with my limited knowledge of Make. What am I missing to make Make make - sorry - my Dockerfiles?

A: This line:
$(BUILD_DIR)/%.built: $(TEMPLATE_FILES) $(BUILD_DIR)

Says that if make wants to build a target that matches that pattern, and it can find all the prerequisites, then the pattern rule matches and the recipe can be used.  Let's ignore BUILD_DIR (note that it's always a bad idea to list a directory as a prerequisite, but that's not causing this problem).  Suppose TEMPLATE_FILES is set to the value ./foo/foo.build ./bar/bar.build.  Now the above rule expands to:
./build/%.built: ./foo/foo.build ./foo/bar.build ./build

What is the recipe?
cpp -E -P -o $(BUILD_DIR)/$(notdir $@) -I ${CI_PROJECT_DIR}/modules $<

First it's always wrong to create a file that is not exactly $@ so you should use just $@ not $(BUILD_DIR)/$(notdir $@).  But more importantly, what will $< be set to?  It is always set to the first prerequisite, and the first prerequisite is always ./foo/foo.build.  So every time you run this recipe, regardless of which .built file you're trying to create, you will always be preprocessing the first .build file.
Your idea that you want this instead:
$(BUILD_DIR)/%.built: %.build $(BUILD_DIR)

is correct, in general.  Why do you get the error?  Because if you are trying to build the target ./build/foo.built, then the stem (part that matches %) is foo.  Then make will look to see if the prerequisite foo.build exists or can be created, because you said the prerequisite is %.build.  That file does NOT exist and CANNOT be created (make doesn't know how to create it), because the file is ./foo/foo.build not foo.build which is a totally different file.
You have three options.  You can either write separate rules for each source directory:
$(BUILD_DIR)/%.built: foo/%.build
    ...
$(BUILD_DIR)/%.built: bar/%.build
    ...

Or, you can change your generated files so they are not all in the same directory but instead keep the source directory structure; you would change this:
TEMPLATE_FILENAMES := $(foreach file,$(TEMPLATE_FILES),$(BUILD_DIR)/$(notdir $(file)).built)
BUILT_TEMPLATES := $(TEMPLATE_FILENAMES:.build.built=.built)

to just this:
BUILT_TEMPLATES := $(patsubst %.build,$(BUILD_DIR)/%.built,$(TEMPLATE_FILES))

then create the output directory as part of the recipe:
@mkdir -p $(@D)
cpp -E -P -o $@ -I ${CI_PROJECT_DIR}/modules $<
sed -i 's/__NL__ /\n/g' $@

Or finally, you could use VPATH to tell make what directories to look in to find the *.build files:
VPATH := $(sort $(dir $(TEMPLATE_FILES)))

(note, you should choose only one of these options).


text:
Q: How can I get all days (name, number) of 4 weeks from current day (in the future)? I want to get all days 4 weeks from my current day. For example, today is June (Thu, 23), I want to get (24, Fri) .... up until (21, Thu) July.

A: You can generate days like
  late List<DateTime> days = List.generate(
    7 * 4, // 4weeks
    (index) => DateTime.now().add(
      Duration(days: index+1),
    ),
  );

And to get days name I am using intl package. and formatter is
final formatter = DateFormat('EEEE');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: days.length,
        itemBuilder: (context, index) => Text(
            "name: ${formatter.format(days[index])} number:${days[index].day}  "),
      ),
    );
  }

A: Using DateFormat
final DateFormat formatter = DateFormat('MMMMd');
    _nextDateFormatted = formatter.format(widget.nextDate);

In your case, you will have 4 dates. Heres with the first date
_firstDateFormatted = formatter.format(DateTime.now().add(days:1).millisecondsSinceEpoch)

A: List<dynamic> data = [];
                        for (int i = 1; i < 29; i++) {
                          data.add(DateFormatters()
                              .dMy
                              .format(DateTime.now().add(Duration(days: i))));
                        }
                        log("$data");


text:
Q: JavaScript: inline function vs. regular statements Once again I found JavaScript code on the Internet that contains an inline function where, in my opinion, regular statements would make just as much sense. Here's the first sample:
function outerHTML(node){
  // if IE, Chrome take the internal method otherwise build one
  return node.outerHTML || (
         function(n) {
           var div = document.createElement('div'), h;
           div.appendChild(n.cloneNode(true));
           h = div.innerHTML;
           div = null;
           return h;
         })(node);
}

If you'd ask me to code the same thing, it would look like this:
function outerHTML(node){
  var div, h;

  // if IE, Chrome take the internal method otherwise build one
  if (node.outerHTML) {
    return node.outerHTML;
  }

  div = document.createElement('div')
  div.appendChild(node.cloneNode(true));
  h = div.innerHTML;
  div = null;

  return h;
}

EDIT: As OverZealous stated, there is a difference in logic on this one. I leave it here so nobody gets confused about that answer.
And maybe another original sample (yes, this doesn't "compile" as it's just a code fragment):
addGetters: function (attributes) {
  var that = this;
  function addGetter(attr) {
    that.prototype["get" + attr.capitalize()] = function() { return this[attr]; };
  }

  for(var i = 0; i < attributes.length; i++) {
    var attr = attributes[i];
    addGetter(attr);
  }
},

compared to my attempt
addGetters: function (attributes) {
  for(var i = 0; i < attributes.length; i++) {
    var attr = attributes[i];
    this.prototype["get" + attr.capitalize()] = function() { return this[attr]; };
  }
},

Is there a difference? Doesn't the original version consume more space since a function needs to be created and/or isn't it slower because of this? Is there a possible memory leak?
The utilisation of CPU and memory is very important as I'm coding in an environment where both are limited and any "less" is good. And since there's no sizeof() in JavaScript and its implementation attempts aren't safe to interpret any thinking-ahead-fixes are important.
Please note that as far as the "my version" is concerned I didn't test it. I'm just trying to explain what I'm trying to ask.
EDIT: Even though this question has an answer, I'm still wondering about the memory utilisation. If somebody has some insights, please don't hesitate to add it here.

A: For the first one, I don't believe there is any reason for the function.  It might have (d)evolved into that state through small changes, but the extra function wrapper isn't providing any benefit that I can see.
The second example, however, is actually critical to use the function wrapper.  The reason is due to JavaScript's (sometimes frustrating) function-level scope.  In your example, there is only one attr variable.  It is shared across the different attributes.  This means that, in the end, every attribute will return the value of last attribute in the array.
e.g:
var attrs = ['foo', 'bar', 'baz']
obj.addGetters(attrs);

obj.getFoo(); // returns obj.baz
obj.getBar(); // returns obj.baz

By wrapping the getter creation in a function, you eliminate that issue, because attr ends up being scoped to the creating function.  This is why Douglas Crockford's JSLint says "Don't create a function inside a loop".  It leads to unexpected bugs like that one.

A: As OverZealous pointed out, one needs to be sure about the logic that's happening. +1 for that.
As far as the performance is concerned I finally had the time to do some testing on my own. However, I'm working in an environment where I can't really check memory utilisation. So I tried to fool around with the performance.
The result is that it may have an impact depending on how often this feature is used. On my target system the simple creation of an inline function that does close to nothing, e.g.
myArray.each(function inlineFunc(el) { return el; });

takes about 1.8 seconds for 10,000 creations of such a function (in the example above myArray had no elements). Just in comparison the PC-version of that browser needs 1,000,000 iterations to get somewhere close to that (obviously this also depends on the hardware).
Since the 10,000 iterations are reached in the code we use (not directly in one loop, but functions are created all over the code), we will have a word with our subcontractor.

A: The answer lies in the eye of the beholder.
It's a matter of preference.
It's up to you if you put "speed" above modularity.
Ask yourself this: why do you use a for when it can be done with a while? It is proven that in some cases the while structure is a bit faster.


text:
Q: copy all webalizer.hist files via ssh I have file webalizer.hist in every user acount /home/*/tmp/webalizerftp/webalizer.hist
* - is username.
I need to copy them all to another dir '/home/stats/' and rename them in this style
/home/some_username/tmp/webalizerftp/webalizer.hist -> /home/stats/some_username.hist
/home/another_username/tmp/webalizerftp/webalizer.hist -> /home/stats/another_username.hist
I need to do it via SSH.
Can you help me please?


text:
Q: Difference between composer update and composer global update What are the differences between composer update and composer global update in yii2?

A: It's not anything to do with Yii directly.
Composer allows you to install dependencies globally or per-project (the default).
https://getcomposer.org/doc/03-cli.md#global

This is merely a helper to manage a project stored in a central location that can hold CLI tools or Composer plugins that you want to have available everywhere.

You might want to install something like phpunit or phpcs globally (so it's available for every project) whereas installing a library or framework that you need for your project should be a per-project installation.


text:
Q: Subsonic class has reference to HttpContext.Current.User in a Windows app I'm using SubSonic 2.1. I ran it against a database and it created all the files seemingly correctly. However, when I went to use one of the classes, the app wouldn't built. I'm making a Windows application, but in the SubSonic file there's a reference to HttpContext.Current.User. Does anyone know why that would happen?

A: SubSonic was initially designed to be used within a asp.net application.
However it works very well in a Windows.Forms application. But you need to include System.Web into your project.
Look in the ClassTemplate.aspx: http://github.com/subsonic/SubSonic-2.0/blob/master/SubSonic/CodeGeneration/Templates/CS_ClassTemplate.aspx
if (System.Web.HttpContext.Current != null)
    item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
    item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);

If the code is executed inside a asp.net webpage it pulls the username from the context and outside gets the username from the current thread.
There is a convention in subsonic that, if your table contains a CreatedBy and ModifiedBy column and you use the item.Save("username") method these columns get's updated, too.
If you change the CS_ClassTemplate.aspx file to not use System.Web and regenerate your DAL you probably won't need the reference to System.Web anymore.


text:
Q: Is not an enclosing class - Android В методе onClick() вызывая активность, код выделяется красным, говоря Is not an enclosing class
Класс ScrollingActivityGroups:
public class ScrollingActivityGroups extends AppCompatActivity {
    private List<Card> groups;
    private RecyclerView rv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scrolling);

    rv = findViewById(R.id.rv_groups);

    LinearLayoutManager llm = new LinearLayoutManager(this);
    rv.setLayoutManager(llm);

    initializeData();
    initializeAdapter();

} //далее несколько методов

Класс RVAdapterGroups:
public class RVAdapterGroups extends RecyclerView.Adapter {
public static class CardViewHolder extends RecyclerView.ViewHolder {

    CardView cardView;
    TextView groupName;
    TextView groupConsist;
    ImageView groupPhoto;
    int currentCardPosition;
    Context mContext;

    CardViewHolder(View itemView, Context context) {
        super(itemView);
        cardView = (CardView) itemView.findViewById(R.id.cv);
        groupName = (TextView) itemView.findViewById(R.id.dish_name);
        groupConsist = (TextView) itemView.findViewById(R.id.dish_consist);
        groupPhoto = (ImageView) itemView.findViewById(R.id.dish_photo);
        mContext = context;
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                if(mContext instanceof ScrollingActivityGroups){
                    switch (currentCardPosition) {
                        case 0: Intent intent2 = new Intent(ScrollingActivityGroups.this, ScrollingActivitySoups.class); //выделено красным
                            Intent.startActivity(intent2);
                    }
                }
            }
        });
    }
}

Класс ScrollingActivitySoups абсолютно аналогичен ScrollingActivityGroups. Я использую RecylerView+CardView, и могла ли быть ошибка из-за того, что onClick() прописан в адаптере?
Также, читая форумы, предлагают писать в выделенной строчке Intent intent2 = new Intent(this, ScrollingActivitySoups.class);, но тогда первый параметр метода принадлежит View.onClickListener и метод не выполняется. Как правильнее переписать эту строчку?


text:
Q: How can i install ubuntu without data loss How can i install Ubuntu without data losing and only removing windows 10 partition [c drive] and not other partitions [d,e,f drives]

A: A tutorial shows the steps at https://tutorials.ubuntu.com/tutorial/tutorial-install-ubuntu-desktop .
When you get to Allocate Drive Space  choose Something Else. Pick the drive with Windows on it and tell the installer to erase the Windows system (C:) partition only, and not to install to any other drive or partition.
It is common for multiple drive letters to be assigned to space on one drive and the installation program will show you a map of 'partitions' like this. Read up on the program which handles this, gparted. https://www.pcworld.com/article/3050495/windows-10s-hidden-hard-drive-partitions-how-to-find-them-how-to-remove-them.html may also be helpful.


text:
Q: Archimedean Hecke Algebra of $\operatorname{GL}_1(F)$ for $F = \mathbb{R}$ or $\mathbb{C}$ Suppose  we have a $\operatorname{GL}_1$ over a number field $F$. I am interested in a description for the archimedean Hecke algebra (always taking the maximal compact subgroup). We know will be the tensor product of the archimedean Hecke algebras on the real places and the complex places. So that reduces the problem to a description of the Hecke algebras for $\mathbb{R}^{\times}$ and $\mathbb{C}^{\times}$. We have for $\mathbb{R}^{\times}$ that $K=\{1,-1\}$. That should mean that the Hecke algebra should be given by derivatives of all orders at $\{1,-1\}$, but I can not get a good sense of the convolution product.Is this isomorphic to something more familiar? The case for $\mathbb{C}^{\times}$ is even more confusing. A reference for the archimedean Hecke algebra will be also good. I only know the book Cohomological Induction and Unitary Representations by Knapp and Vogan, but there is no copy in my library.

A: Let $G = \operatorname{GL}_1(F)$ for $F = \mathbb{R}$ or $\mathbb{C}$, and fix a maximal compact subgroup $K$ of $G$.
The archimedean Hecke algebra $H(G,K)$ is the algebra of right- (or left-) $K$-finite distributions on $G$ supported in $K$.
Case 1: $F = \mathbb{R}$
Here, as you say, a maximal compact subgroup is $K = \{\pm 1\}$. Accordingly, the $K$-finiteness condition is unnecessary, and the space $H(G,K)$ consists of all distributions supported on $\pm 1$.
The distributions supported at a point $g \in G$ are spanned by the Dirac delta $\delta_g$ and all of its derivatives, so in this case $H(G,K)$ takes the form $\mathbb{C}[d/dx]\delta_1 \oplus \mathbb{C}[d/dx]\delta_{-1} \cong U(\mathfrak{g}) \oplus U(\mathfrak{g})$.
Case 2: $F = \mathbb{C}$
This case is a bit more complicated since both $K = S^1 = \{z \in \mathbb{C} : |z| = 1\}$ and derivatives on $G$ (that is, the Lie algebra of $G$) is less trivial. I can leave it as an exercise or come back and provide a revision when time permits.
Instead let me write up a brief summary of a process by which you can analyze $H(G,K)$.
Take $\mathfrak{g}_\mathbb{R}$ for $\operatorname{Lie}(G)$ as a real Lie algebra and $\mathfrak{g}$ for the complexification $\mathfrak{g}_\mathbb{R} \oplus i\mathfrak{g}_\mathbb{R}$ of $\mathfrak{g}_\mathbb{R}$.
Similarly define $\mathfrak{k}$ as a complexification of the real vector space $\mathfrak{k}_\mathbb{R}$ corresponding to $\operatorname{Lie}(K)$ by forgetting complex structure.
Let $U(\mathfrak{g})$ and $U(\mathfrak{k})$ denote the universal enveloping algebras of $\mathfrak{g}$ and $\mathfrak{k}$, respectively.
Finally, let $H(K)$ denote the space of right- (or left-) $K$-finite distributions on $K$.
(Left- and right-$K$-finiteness are equivalent for distributions on $K$.)
By fixing a Haar measure $dk$ on $K$, the space $H(K)$ may be identified with the convolution algebra of measures $C^\infty(K) \cdot dk$.
The algebra $H(K)$ can be embedded into $H(G,K)$, where the action of $T_f := f \cdot dk \in H(K)$ on $F \in C^\infty(G)$ is given by
$$
    T_f(F) = \int_K f(k) F(k)\,dk.
$$
In fact, for each $u \in U(\mathfrak{g})$ and each $T_f \in H(K)$, we may form the tensor $u \otimes T_f$ and let it act as a distribution on $G$ by setting
$$
    (u \otimes T_f)(F) = \int_K f(k) (\partial(u)F)(k)\,dk.
$$
Here $\partial(u)F \in C^\infty(G)$ is the $u$-th right derivative of $F$ (that is, the image of $F$ under the canonical extension to $U(\mathfrak{g})$ of the action of $\mathfrak{g}$ on $C^\infty(G)$ by right-differential operators).
Extending to linear combinations of these tensors, it turns out we exhaust $H(G,K)$; one has an isomorphism of algebras
$$
    H(G,K) \cong U(\mathfrak{g}) \otimes_{U(\mathfrak{k})} H(K),
$$
where the tensor product is over $U(\mathfrak{k})$ rather than, say, $\mathbb{C}$ due to relationship between the actions of the two factors.
If you look closely, our characterization in the real case is a decomposition of exactly this form, and you can use the same decomposition to compute $H(G,K)$ for $F = \mathbb{C}$ (and in general).


text:
Q: Writing Escape Characters to a Csv File in Python I'm using the csv module in python and escape characters keep messing up my csv's. For example, if I had the following:
import csv

rowWriter = csv.writer(open('bike.csv', 'w'), delimiter = ",")

text1 = "I like to \n ride my bike"
text2 = "pumpkin sauce"

rowWriter.writerow([text1, text2])
rowWriter.writerow(['chicken','wings'])

I would like my csv to look like:
I like to \n ride my bike,pumpkin sauce
chicken,wings

But instead it turns out as
I like to
ride my bike,pumpkin sauce
chicken,wings

I've tried combinations of quoting, doublequote, escapechar and other parameters of the csv module, but I can't seem to make it work. Does anyone know whats up with this?
*Note - I'm also using codecs encode("utf-8"), so text1 really looks like "I like to \n ride my bike".encode("utf-8")

A: The problem is not with writing them to the file. The problem is that \n is a line break when inside '' or "". What you really want is either 'I like to \\n ride my bike' or r'I like to \n ride my bike' (notice the r prefix).

A: Firstly, it is not obvious why you want r"\n" (two bytes) to appear in your file instead of "\n" (one byte). What is the consumer of the output file meant to do? Use ast.evaluate_literal() on each input field? If your actual data contains any of (non-ASCII characters, apostrophes, quotes), then I'd be very wary of serialising it using repr().
Secondly, you have misreported either your code or your output (or both). The code that you show actually produces:
"I like to
 ride my bike",pumpkin sauce
chicken,wings

Thirdly, about your "I like to \n ride my bike".encode("utf-8"): str_object.encode("utf-8") is absolutely pointless if str_object contains only ASCII bytes -- it does nothing. Otherwise it raises an exception.
Fourthly, this comment:

I don't need to call encode anymore, now that I'm using the raw
  string. There are a lot of unicode characters in the text that I am
  using, so before I started using the raw string I was using encode so
  that csv could read the unicode text

doesn't make any sense -- as I've said, "ascii string".encode('utf8') is pointless.
Consider taking a step ot two backwards, and explain what you are really trying to do: where does your data come from, what's in it, and most importantly, what does the process that is going to read the file going to do?