text:
Q: Template field disappears I have a gridview used to display records based on a selected value in a drop down.
Within the gridview, there are a dynamic number of bound field columns added in code behind, followed by a drop down list in a template field and a button in a second template field.
The problem is, when I click on the button, the template fields disappear.
GRID VIEW
<asp:UpdatePanel ID="upnlDetail" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:GridView ID="gvDetails" runat="server"
            AutoGenerateColumns="false"
            SkinID="gridviewGray"
            CellPadding="3"
            OnRowCommand="gvDetails_RowCommand"
            OnRowDataBound="gvDetails_RowDataBound"
            AllowSorting="true">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlStatus" runat="server"
                            AutoPostBack="true"
                            OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Button ID="btnSave" runat="server"
                            CommandName="Save"
                            CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
                            Text="Save" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

CODE BEHIND
while (gvDetails.Columns.Count > 2)  //Don't remove the rightmost columns
{
    gvDetails.Columns.RemoveAt(0);
}

gvDetails.Columns.Insert(0, GridViewTools.CreateBoundField(
                                "Request.Amount", "Amount", "Money", 50));
gvDetails.Columns.Insert(0, GridViewTools.CreateBoundField(
                                "Request.CustomerName", "Customer", "comment", 200));
gvDetails.Columns.Insert(0, GridViewTools.CreateBoundField(
                                "Request.BillAccountFormatted", "Account", "text", 100));
gvDetails.Columns.Insert(0, GridViewTools.CreateBoundField(
                                "Request.Id", "Request", "int", 50));

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

Method GridViewTools.CreateBoundField is a custom method that sets my default boundfield attributes and returns the BoundField object.
public static BoundField CreateBoundField(...){...}

In testing it, the gridview populates as desired on the initial load.  However, the RowCommand event does not fire and both template fields disappear when the button is clicked.  The next gridview.RowDataBound event then throws a null object error because the drop down list is no longer found in the row.
If I remove lines adding the bound fields [Columns.Insert], the RowCommand fires as expected when btnSave is clicked and the template fields persist.  If I add even a single bound field column again, the RowCommand does not fire and the template fields disappear.
Any suggestions?  Why would adding a new column to a gridview invalidate the RowCommand event for a pre-existing button and make the template fields disappear?
UPDATES
I've removed the template fields from the Grid View declaration and added the controls to a bound field instead, but still get the same result.  The show on the initial load, but disappear once clicked.
I've also looked at the grid view in the Page_Unload event, and it still contains the columns at that point, even though they don't show on screen.  Is there any event I can capture after Page_Unload?

A: Build everything in code behind. It is not a matter of preference. Please read Dynamic Web Server Controls and View State
WebForm:
<asp:GridView ID="gvDetails" runat="server"
    AutoGenerateColumns="false"
    SkinID="gridviewGray"
    CellPadding="3"
    OnRowDataBound="OnRowDataBound"
    OnRowCommand="gvDetails_RowCommand"
    AllowSorting="true">
</asp:GridView>

Code behind:
public class GridViewDropDownListTemplate : ITemplate
{
    public void InstantiateIn(Control container)
    {
        DropDownList ddlStatus = new DropDownList();
        ddlStatus.ID = "ddlStatus";
        ddlStatus.Items.Add(new ListItem("Status 1"));
        ddlStatus.Items.Add(new ListItem("Status 2"));
        ddlStatus.Items.Add(new ListItem("Status 3"));
        ddlStatus.Items.Add(new ListItem("Status 4"));
        ddlStatus.AutoPostBack = true;
        ddlStatus.SelectedIndexChanged += ddlStatus_SelectedIndexChanged;
        container.Controls.Add(ddlStatus);
    }

    public void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
    }
}

public class GridViewButtonTemplate : ITemplate
{
    public void InstantiateIn(Control container)
    {
        Button btnSave = new Button();
        btnSave.ID = "btnSave";
        btnSave.Text = "Save";
        container.Controls.Add(btnSave);
    }
}

public partial class Default : System.Web.UI.Page
{
    object[] data = new[]
    {
        new { Amount = 12500.00, Account = "1234-567-89" },
        new { Amount = 87000.00, Account = "0000-999-88" }
    };

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BuildBoundFields();
        }

        BuildTemplateFields();
        BindData();
    }

    protected void BuildBoundFields()
    {
        // Amount bound field
        BoundField boundFieldAmount = new BoundField();
        boundFieldAmount.DataField = "Amount";
        boundFieldAmount.HeaderText = "Amount";
        boundFieldAmount.SortExpression = "Amount";
        boundFieldAmount.ItemStyle.Width = Unit.Pixel(100);
        gvDetails.Columns.Add(boundFieldAmount);

        // Account bould field
        BoundField boundFieldAccount = new BoundField();
        boundFieldAccount.DataField = "Account";
        boundFieldAccount.HeaderText = "Account";
        boundFieldAccount.SortExpression = "Account";
        boundFieldAccount.ItemStyle.Width = Unit.Pixel(250);
        gvDetails.Columns.Add(boundFieldAccount);

        // ...
    }

    protected void BuildTemplateFields()
    {
        // Status template field
        TemplateField statusTemplateField = new TemplateField();
        statusTemplateField.ItemTemplate = new GridViewDropDownListTemplate();
        gvDetails.Columns.Add(statusTemplateField);

        // Save template field
        TemplateField saveTemplateField = new TemplateField();
        saveTemplateField.ItemTemplate = new GridViewButtonTemplate();
        gvDetails.Columns.Add(saveTemplateField);
    }

    protected void BindData()
    {
        gvDetails.DataSource = data;
        gvDetails.DataBind();
    }

    protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button btnSave = (Button)e.Row.FindControl("btnSave");
            if (btnSave != null)
            {
                btnSave.CommandArgument = e.Row.RowIndex.ToString();
            }
        }
    }

    protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
    }
}

A: This is interesting. It would appear to happen only when the BoundFields are Inserted. When adding BoundFields to the end of the Grid, it does work.
gvDetails.Columns.Add(GridViewTools.CreateBoundField("Request.Amount", "Amount", "Money", 50));

But you probably want the DropDown and the Button at the end of the GridView. So you could make those dynamic as well, instead of just adding data to the DropDownList.
So the first thing to do is add 2 extra dummy BoundField columns to hold the Button and DropDownList.
gvDetails.Columns.Add(GridViewTools.CreateBoundField("", "DropDownList", "int", 50));
gvDetails.Columns.Add(GridViewTools.CreateBoundField("", "Button", "int", 50));

Now change the RowDataBound event to add the controls.
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //create a dropdownlist and add some data
        DropDownList ddl = new DropDownList();
        ddl.ID = "ddlStatus";
        ddl.Items.Add(new ListItem() { Text = "Option 1", Value = "1" });
        ddl.Items.Add(new ListItem() { Text = "Option 2", Value = "2" });
        ddl.Items.Add(new ListItem() { Text = "Option 3", Value = "3" });

        //create a save button
        Button btn = new Button();
        btn.ID = "btnSave";
        btn.CommandName = "save";
        btn.Text = "Save";
        btn.CommandArgument = e.Row.RowIndex.ToString();

        //add the controls to the last 2 cells
        e.Row.Cells[e.Row.Cells.Count - 2].Controls.Add(ddl);
        e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(btn);
    }
}

But for this to work you need to place the DataBind() of the GridView outside the IsPostBack check, but keep the adding of the BoundFields inside it.
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack == false)
    {
         //add the boundfields here
    }

    //bind gridview on every postback
    gvDetails.DataSource = dt;
    gvDetails.DataBind();
}

The ASPX now looks like this
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false"
  OnRowDataBound="gvDetails_RowDataBound" OnRowCommand="gvDetails_RowCommand"></asp:GridView>

Well, you now have a fully dynamically created GridView.


text:
Q: How to change Query to contain data from joined table? I have simple Entity:

id
username
guard

"guard" is id of another user from the same Entity. I have to render view with simple table:

username | name of guard
-------------------------
John     | Bob

I tried to do that by query:

$ur = $this->getDoctrine()->getRepository(User::class)->createQueryBuilder('u')
            ->leftJoin(User::class, 'u2', \Doctrine\ORM\Query\Expr\Join::WITH, 'u.guard = u2.id')
            ->getQuery()
            ->getResult();

but it gives me just id and username, no joined data.
I know that entire query should be like:

SELECT
  *
FROM
  user u0_
  LEFT JOIN user u1_ ON (u0_.guard = u1_.id)

but I can't find the way to implement that by QueryBuilder and then to access that in twig template.
Regards

A: OK, I found out the mistakes in my code:

*

*I tried to set that OneToOne realtion and that was small mistake, but I needed here ManyToOne.

    /**
     * Many Users have One Guard (User)
     * @ORM\ManyToOne(targetEntity="User")
     */
    private $guard = 0;

*When I did that Symfony automatically force me to change my code and in column "guard" I have to insert User object.

*After that I don't need join anymore - just select data from table and guard column includes User object which I can use in Twig, etc.

    namespace AppBundle\Entity;
    use Doctrine\ORM\EntityRepository;

    class UserRepository extends EntityRepository
    {
        public function findAllDB()
        {
            $qb = $this->createQueryBuilder('u');
            $query = $qb->getQuery();
            return $query->execute();
        }
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add an array to a nested array My PHP Code is the following, I need some assistance please:
//DB connection
$result = mysqli_query($con,"SELECT * FROM `clients`");
$info = array();
$count = 0;
$meta = array('page' => 1, 'pages' => 1, 'perpage' => -1, 'total' => 14, 'sort' => "asc", 'field' => "ID");

while ($row = $result->fetch_array(MYSQLI_ASSOC)) {

    $info[$row['clientid']]['id'] = $row['id'];
    $info[$row['clientid']]['name'] = $row['name'];
    $info[$row['clientid']]['email'] = $row['email'];
    $info[$row['clientid']]['cell'] = $row['cell'];

    $count++;
}

$data = json_encode(array_values($info));

echo $data;

My Result;
[{"ID":1,"name":"A","email":"a@a.com","cell":"082"},
 {"ID":2,"name":"B","email":"b@b.com","cell":"083"},
 {"ID":3,"name":"C","email":"c@c.com","cell":"079"}]

The JSON should add the meta array with the following result:
{"meta":
       {"page": 1,"pages": 1,"perpage": -1,"total": 3,"sort": "asc","field": ID"},
 "data": [{"ID":1,"name":"A","email":"a@a.com","cell":"082"},
          {"ID":2,"name":"B","email":"b@b.com","cell":"083"},
          {"ID":3,"name":"C","email":"c@c.com","cell":"079"}]
},

A: Create array of required structure and json_encode it:
$data = json_encode(array(
    'meta' => $meta,
    'data' => array_values($info),
));


text:
Q: arabic data issue with mysql charecter i have a php website with arabic language and the database consist of several tables
when i request data from the first table the browser shows it perfectly but when i request the data from other tables the data look like this "محمد"
notice : all the table are encoded in "UTF-8" and all the pages and the connection with the database depend on "UTF-8"
another notice : this problem was solved when i used (mysql 5) but when i use (mysql 4 or less) the problem come again
How can i make the browser shows the data perfectly with (mysql 4)

A: Try base_64 encoding the data before putting it into the db? It could be a special character causing corruption of the read.


text:
Q: How to store a group of data with 2 different search parameters? I have a class to contain following data relevant to this question (Xpos, Ypos, Timestamp)
The size is a 100x100 area (Xpos and Ypos), and have an update time on each position which is the timestamp, the class then is given a new timestamp for next update.
Now I could go through all of these data points and find any class where the Timestamp is up, and execute the action needed. To me this seems inefficient.
Alternative I could store this in a sorted list, with the Timestamp being the decider, so I only need to check through until I find an entry not ready to be updated, update those and remove/readd them with the new timestamp.
Now my kicked is, the expected next timestamp can be modified via workflow that finds the location via Xpos and Ypos, meaning I would have to loop through all entries again to perform this.
I could address this with the objects being in both a sorted list and a 100x100 array, problem is updating the timestamp via the 100x100 array listing, would not update its position in the sorted list.
Is there a good way to approach this "double sorting" without having to go through the full list from either the timestamp trigger point, or from the array update of timestamp.

A: One option would be to store your data in a priority queue.  The C5 Collection Library's IntervalHeap would be a good option for this.  The IntervalHeap<T>.Replace method allows you to replace an item (ie: change it's priority, which would be the Timestamp) directly.


text:
Q: Abstract Class comp error? Java I'm very new to Java and just trying to get the basics down. I am throwing a code with my main class objects in my abstract class and I'm not sure what to change.
public class Test {
    public static void main(String[] args) {
        m(new GraduateStudent());
        m(new Student());
        m(new Person());
        m(new Object());
    }

    public static void m(Student x) {
       System.out.println(x.toString());
    }
}

class GraduateStudent extends Student {
}

class Student extends Person {
    public String toString() {
        return "Student";
    }
}

class Person extends Object {
    public String toString() {
        return "Person";
    }
}

A: Simply Change
public static void m(Student x) {
        System.out.println(x.toString());
}

to
public static void m(Object x) {
        System.out.println(x.toString());
      }

Because all child classes can be casted to parent, parents can't be casted to child


text:
Q: Why my toolbar is overlapping my textView? This is the xml layout of the file
Here, when i made the layout the toolbar is overlapping the content of my textView, Why this is happening.
Have tried several other things but no luck..!!!
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout  xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.alpit.formula2.MainActivity">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="alpit isfdfsdfwefwes great jhfjhvjhhbnmbjk"
        android:textSize="20dp" />
</RelativeLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:menu="@menu/navigation_menu"

    >

</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

This is my current situation.

A: add top margin to relativelayout like
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:weightSum="1">

I should have written this as comment but I don't have reputations so I have added it as answer

A: try this give margin to Textview
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.alpit.formula2.MainActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text=" alpit isfdfsdfwefwes great jhfjhvjhhbnmbjk"
            android:textSize="20dp" />
    </RelativeLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/navigation_menu"
        ></android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

A: Don't put hard coded values to layout you can try this,
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:text="alpit isfdfsdfwefwes great jhfjhvjhhbnmbjk"
        android:textSize="?android:textAppearanceMedium" />
</RelativeLayout>

A: remove
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"

and use into relative_layout
android:layout_marginTop="@dimen/activity_vertical_margin"

A: Problem is just because you have given padding to your Drawer layout and your relative layout start drawing from top which includes paddingTop also
please try below code
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:weightSum="1"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="alpit isfdfsdfwefwes great jhfjhvjhhbnmbjk"
            android:textSize="20dp" />
    </RelativeLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/navigation_menu"

        >

    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

also you can use parent layout as relative layout and inside these use Drawer layout


text:
Q: How to return ActiveRecord Relation in GraphQL (Rails)? GraphQL queries are straight forward to define if you search for record e.g. by its id or exact value (in my case date).
My query should be returning not one ActiveRecord object but ActiveRecord Relation. How to define it to be consumable by GraphQL?
  field :file_data, !FileDataType, " Returns records based on given date: format 'yyyy-mm-dd hh:mm:ss'" do
  argument :created_on, !types.String, "format 'yyyy-mm-dd hh:mm:ss'"

  resolve -> (obj, args, context) do
    FileData.where("created_on > ?", args["created_on"])
  end
end

It works for one object: if I add to the relation 'last':
      FileData.where("created_on > ?", args["created_on"]).last

For many results I get an error in rails console:
NoMethodError (undefined method `attribute_name' [any defined & requested] for FileData::ActiveRecord_Relation:..>
I would appreciate any suggestion.

A: Use a list type for returning multiple objects:
field :file_data, types[FileDataType] do
  ...
end

types[...] defines a list type.


text:
Q: Kubectl get deployment yaml file I know how to list of pods for certain namespace as follows:
kubectl get pods -n mynamespace

There is one POD on the list which i am interested. I would like to be able to see what yaml deployment file was used for creation of that pod and the content of it. Moreover what would be kubectl command to edit such yaml file?

A: To get the deployment used to generate a pod, have to look at the pod yaml or describe the pod:
kubectl get pod -n {namespace} {pod-name} -o yaml

Look for the "ownerReferences" section. This will tell you what "owns" the pod. This will likely be a ReplicaSet (which is generated by the Deployment). For example, this is my one from my canonical-service-controller-manager pod:
$ kubectl get  pod -n asm-system canonical-service-controller-manager-67c8f5fff5-dzd4t -o yaml
apiVersion: v1
kind: Pod
metadata:
  ...
  namespace: asm-system
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: canonical-service-controller-manager-67c8f5fff5
    uid: 2504c96b-9ef7-45fa-b5d2-2a20f09486e1
  resourceVersion: "13507"
  uid: 54748cf7-26f8-4e8a-996a-725dbc89c66b
...

You can then find the replicaset and do the same thing. In my example, the replicaset is called "canonical-service-controller-manager-67c8f5fff5"
$ kubectl get replicaset -n asm-system canonical-service-controller-manager-67c8f5fff5 -o yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  annotations:
    ...
  generation: 1
  labels:
    ...
  name: canonical-service-controller-manager-67c8f5fff5
  namespace: asm-system
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: Deployment
    name: canonical-service-controller-manager
    uid: eafe2590-5005-492f-9673-0f02ac74a4d5
spec:
  replicas: 1
  ...

So you can see here, the deployment that created the replicaset, which in turn created my pod is canonical-service-controller-manager
So now I can get the deployment yaml using
$ kubectl get deployment -n asm-system canonical-service-controller-manager -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    ...
  creationTimestamp: "2022-06-14T06:35:58Z"
  generation: 1
  labels:
    ...
  name: canonical-service-controller-manager
  namespace: asm-system
spec:
  ...

If I wanted to edit the deployment, I can do so using this:
kubectl edit deployment -n asm-system canonical-service-controller-manager

Bear in mind, that editing the deployment will cycle all the pods in the deployment as they are all replicas.

A: To get the yaml file try
kubectl get deploy deploymentname -o yaml
To update the pod with the new yaml file first either find and edit the yaml file or copy the contents and make the changes you want to make, then run:
kubectl apply -f newDeployment.yaml to update the cluster with your changes.


text:
Q: Removing an item from systemd startup My boot time is very high and when I use
systemd-analyze blame

I get the following result
     25.282s home-arianhf-google\x2ddrive.mount
     23.567s systemd-journal-flush.service
     23.232s dev-sda9.device

and the result of systemctl list-units --type=mount
is :
UNIT                                    LOAD   ACTIVE SUB     DESCRIPTION
  -.mount                                 loaded active mounted Root Mount
  dev-hugepages.mount                     loaded active mounted Huge Pages File System
  dev-mqueue.mount                        loaded active mounted POSIX Message Queue File System
● home-arianhf-google\x2ddrive.mount      loaded failed failed  /home/arianhf/google-drive
  mnt-ubuntu.mount                        loaded active mounted /mnt/ubuntu
  proc-sys-fs-binfmt_misc.mount           loaded active mounted Arbitrary Executable File Formats File System

notice the failed mount.
i want to remove this from my systemd. How can I do this?

A: Try something like the following:
sudo systemctl disable home-arianhf-google\x2ddrive.mount

For more info check the man page of systemctl.
Also check etc/fstab for any relevant lines, and if found, remove them.


text:
Q: Why can't Mathematica evaluate this integral? I want to work with the rectangle function, which I define by
f[x_, m_] := Limit[1/((2*(x - m))^(2*k) + 1), k -> Infinity];

(I know that in theory I can use HeavisidePi[x-m] to obtain the same function, but using my definition evaluates to 1/2 at the discontinuities, which I want to retain.)
Clearly, the integral of f with respect to x over {x, m - 1/2, m + 1/2} should evaluate to 1. However, I can't persuade Mathematica to define the integral at all: the code
Clear["Global`*"];
f[x_, m_] := Limit[1/((2*(x - m))^(2*k) + 1), k -> Infinity];
Module[{m = 0}, Plot[f[x, m], {x, -1, 1}, GridLines -> Automatic]]
Module[{m = 0}, Integrate[f[x, m], {x, m - 1/2, m + 1/2}]]

yields the desired plot, but returns Undefined for the integral.
I have tried adding Assumptions but clearly not the right ones, because it doesn't work. I have tried using NIntegrate, but it doesn't work. I have tried changing the definition of f to HeavisidePi[x-m] (which I don't want to do anyway), but it doesn't work. I have tried using a Piecewise definition - same non-result...
How do I obtain the correct result?

A: Does this help?
f2[x_?NumericQ, m_] := Limit[1/((2*(x - m))^(2*k) + 1), k -> Infinity];

Module[{m = 0}, NIntegrate[f2[x, m], {x, m - 1/2, m + 1/2}]]

(* 1. *)

A: Do integration first and then take the limit k-> inf.
Use indefinite integration. Integrate  only finds a solution for m==0.
g[x_, m_, k_] = 1/((2*(x - m))^(2*k) + 1)

mint[x_, k_] = Integrate[g[x, 0, k], x]

(*   x Hypergeometric2F1[1, 1/(2 k), 1 + 1/(2 k), -4^k x^(2 k)]   *)

Use a trick. Tell Limit  that x^(2 k) is always positive. (Valid for Integer k)
That is only neccessary for x== -1/2. For all other positive and negative x Limit[mint[x, k], k -> \[Infinity]]  is x. Maybe this is a removable singularity at x== -1/2 ?
mint2[x_, k_] = mint[x, k] /. x^(2 k) -> Abs[x]^(2 k)

Limit[mint2[1/2, k] - mint2[-1/2, k], k -> \[Infinity]]

(*   1   *)

A graphic shows the same.
Manipulate[Plot[mint[x, k], {x, -.5, .5}], {k, 1, 1000}]

Rubi (https://rulebasedintegration.org/) does the integral with arbitrary m.
rint[x_, m_, k_] = Int[g[x, m, k], x]

(*   (-m + x) Hypergeometric2F1[1, 1/(2 k),
       1/2 (2 + 1/k), -4^k (-m + x)^(2 k)]   *)

rint2[x_, m_, k_] =
    rint[x, m, k] /. (-m + x)^(2 k) -> Abs[(-m + x)]^(2 k)

Limit[rint2[m + 1/2, m, k] - rint2[m - 1/2, m, k], k -> \[Infinity]]

(*   1   *)


text:
Q: OpenStack Designate: '_AuthTokenPlugin' has no attribute 'register_conf_options' I have recently started to use OpenStack. Here's the problem: I am setting up Designate for OpenStack (DNSaaS) and I have set it up accordingly to the instructions here -- https://designate.readthedocs.org/en/latest/getting-started.html
With the "noauth" auth_strategy, the API and Central services are working correctly, but I was looking for integration with OpenStack Keystone, so I changed a few things in the designate.conf file:
#-----------------------
# API Service
#-----------------------
[service:api]
# Address to bind the API server
api_host = 0.0.0.0

# Port the bind the API server to
api_port = 9001

# Authentication strategy to use - can be either "noauth" or "keystone"
auth_strategy = keystone

&&
#-----------------------
# Keystone Middleware
#-----------------------
[keystone_authtoken]
auth_host = xxx.xxx.xxx.xxx <-- redacted
auth_port = 35357
auth_protocol = http
admin_tenant_name = service
admin_user = redacted
admin_password = redacted

&&
##############
## Network API
##############
[network_api:neutron]
endpoints = RegionOne|http://xxx.xxx.xxx.xxx:9696
endpoint_type = publicURL
timeout = 30
admin_username = redacted
admin_password = redacted
admin_tenant_name = service
auth_url = http://xxx.xxx.xxx.xxx:35357/v2.0
#insecure = False
auth_strategy = keystone
#ca_certificates_file = /etc/path/to/ca.pem

After saving these changes and starting the Designate API the following error appears and the service is not started:
2015-02-23 11:44:09.534 27878 TRACE designate   File "/usr/local/lib/python2.7/dist-packages/keystonemiddleware/auth_token.py", line 667, in <module>
2015-02-23 11:44:09.534 27878 TRACE designate     _AuthTokenPlugin.register_conf_options(CONF, _AUTHTOKEN_GROUP)
2015-02-23 11:44:09.534 27878 TRACE designate AttributeError: type object '_AuthTokenPlugin' has no attribute 'register_conf_options'
2015-02-23 11:44:09.534 27878 TRACE designate

Apparently _AuthTokenPlugin has no attribute 'register_conf_options'. Upon closer inspection of the auth_token.py file, which was supplied with Designate (keystonemiddleware plugin).
There are only two instances of 'register_conf_options' being mentioned; this line 667 where it is called.
_AuthTokenPlugin.register_conf_options(CONF, _AUTHTOKEN_GROUP)

And earlier on line 335:
_AUTHTOKEN_GROUP = 'keystone_authtoken'
CONF = cfg.CONF
CONF.register_opts(_OPTS, group=_AUTHTOKEN_GROUP)
auth.register_conf_options(CONF, _AUTHTOKEN_GROUP)

Where would the problem lie? And how would I go about it? Thank you in advance for any hints or solutions.

A: Unfortunately those docs are very out of date. :( They should work for the most part though. I just ran through them on a Trusty VM, and it seemed to work for me.
The current docs are here -  http://docs.openstack.org/developer/designate/
It could be an incompatibility between the version of other OpenStack projects you have currently installed and the version of Designate you are trying to install.
It looks like an issue with keystonemiddleware. We don't ship that as part of Designate, it is included as a requirement.
The best place to start is to get the versions of OpenStack you have, followed by the output of pip freeze in the virtualenv.
The is usually a few people in #openstack-dns on freenode as well, who can run through things in real time

A: Same thing I am trying, but I am not getting error like this.
Eventually designate services are starting find but I when I am hitting api url using keystone username and password, its giving me 401 error.
I don't know where is the issue.
here is a trace of /var/log/designate/designate.api.log
keystonemiddleware.auth_token [-] Unable to find authentication token in headers
keystonemiddleware.auth_token [-] Invalid user token - rejecting request
eventlet.wsgi [-] 203.143.184.13,54.85.95.189 - - [23/Feb/2015 05:37:24] "GET /v1/servers HTTP/1.1" 401 282 0.001634


text:
Q: Derivative when change variable This may be a silly question but I am confused with some notation of a derivative function ater changing variable. For example, if I have $f(x) = x^2$. Let $u(x) = 1-e^x$ and $F(x) = f(u(x))$, then if I write
$$
f'(1-e^x) = -e^x\big(2(1-e^x)\big).
$$
Is it correct or not? Or it must be
$$
f'(1-e^x) = 2(1-e^x).
$$
Thank you for your answers.

A: Well what you have here is that you are thinking of two different statements. The first time when you have
$$f'(1-e^x)\neq -e^x[2(1-e^x)]$$
what you are really thinking is
$$\frac{d}{dx}f(g(x))=-e^x[2(1-e^x)]$$
which is true by the chain rule. However, what you have written is $f'$ evaluated at $g$ which is in fact just
$$f'(1-e^x)=2(1-e^x)$$
since $f'(x)=2x$ and then you just are plugging in $1-e^x$ for $x$.
So in short $\frac{d}{dx}f(g(x))$ (or in shorthand $[f(g(x))]'$) and $f'(g(x))$ are two different statements. The first one is the derivative of a composite function, while the second one is just the derivative of $f$ evaluated at $g$.


text:
Q: Triangle / Circle enclosing a set of points I have a set of points in 2D.
I want to find:

*

*the smallest triangle enclosing all the points

*the smallest circle enclosing all the points.

Are there any algorithm to do so?
I came across Convex Hull to fit a convex polygon for a set of points. But I want a circle and triangle.
Thanks in advance

A: There are O(n) algorithms for both these problems, but they are non-trivial. See http://en.wikipedia.org/wiki/Smallest-circle_problem and http://prografix.narod.ru/source/orourke1986.pdf. Computing an axis-aligned bounding box, or centring a circle or equilateral triangle on the mean of the co-ordinates of the convex hull would be much easier. This might be a good time to think about what your requirements really are, or to find a library implementation.

A: If by smallest you are referring to the area then the following algorithms could be potentially useful.
Triangle
The implementation of a linear (i.e. O(n)) algorithm for computing the minimal area triangle enclosing a given set of points in Euclidean 2D space is described in the following open access scientific note:
O. Parvu and D. Gilbert, Implementation of linear minimum area enclosing triangle algorithm, Computational and Applied Mathematics, Springer, pp. 1–16, November 2014.
This scientific note only provides a detailed description of the algorithms initially introduced in the following paper:
J. O'Rourke, A. Aggarwal, S. Maddila, and M. Baldwin, An optimal algorithm for finding minimal enclosing triangles, Journal of Algorithms, vol. 7, no. 2, pp. 258–269, Jun. 1986.
DISCLAIMER: I am one of the authors of this scientific note.
A C++ implementation of the algorithm is made available at:
https://github.com/IceRage/minimal-area-triangle
and will be included in the next major release (3.0) of OpenCV.
Circle
A minimal area enclosing circle algorithm is described in the following paper:
G. Bernd, Fast and Robust Smallest Enclosing Balls, Proceedings of the 7th Annual European Symposium on Algorithms (ESA), Springer, pp 325-338, 1999.
A C++ implementation of the algorithm is made available at:
http://www.inf.ethz.ch/personal/gaertner/miniball.html.


text:
Q: can inline JavaScript get its parent node in all browsers? my question is quite easy. code as belows:
<div id="parent">
  <script>
    // will this line be an error ? cannot find the dom?
    var dom = document.getElementById("parent");
  </script>
</div>

I test it in all broswers I can find, even IE6, it works well! But I wonder if any browser will make an error? Because after putting the code onto the network, some data tell me that it may result in an error? but how ? could you help me?

@2017.09.13 it seems to be a misunderstand, the code is ok

A: Your script should always be able to find its container element, because the element is included on the page before the script runs. but:

*

*Modifying the DOM before it is completely loaded may result in problems in older browsers:
https://stackoverflow.com/a/403992/5742681

*There may be problems accessing any child elements that are included in the parent after the script through the variable defined in the div.
Overall, it would probably be better to put your script outside the div.


text:
Q: Python: Scraping a CSV file request A frequent and long lurker on here: I usually find my questions answered on here. However, I have come across perhaps a simple, yet vague project that escapes me. I am fairly new to Python (currently using ver 3.6).
I am looking at: https://www.ishares.com/us/products/239726/
From what I can tell, there is some jquery stuff involved here: looking near the "Holdings" portion of the page. Instead of 'Top 10' selected, if 'All' is selected, there is an option to get holdings 'as of.'
If a specific historical month is selected, a prompt to download a .csv is created. What I would like to do is get each csv file that is produced from the drop down list, going back to Sept 29, 2006. In other words, automatically downloading the .csv file that is produced for each request given through this drop down list.
To give some (not necessarily relevant) context, I am familiar with pandas and bs4, and perhaps some other less popular libraries. As background, I keep a couple of desk references: 'Beginning Python' by Magnus Lie Hetland and 'Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython' by Wes McKinney.
I would like some small direction on how to approach this issue that I may be overlooking. In other words, breadcrumbs are helpful, but not asking for anyone to do all this work for me. I would like to explore and learn as much as humanly possible.
What libraries/methods should I perhaps use? I understand this is completely open-ended, so I would like to stick to bs4 and Pandas as much as possible. Other libraries are helpful as well, but those would be the focus.
Thanks!

A:
I would like some small direction on how to approach this issue

Using your browser's developer tools, examine the network requests being made. You will see that, when you choose a historical month, a request is made. If you copy the URL from that request, you can paste it into your browser to see if you can "replay" the request to get the payload. I tested it, and you can. What's more, you can see the query parameters quite clearly. They are not obfuscated. This means you can programatically generate URLs that you can then use cURL or wget on.
Do note that I tried to specify a file type of "csv" and got an empty response, but when I requested a file type of "json" I got the data. YMMV. Good luck!


text:
Q: file upload using fetch API in javaScript Hi I am trying to upload a tar file from so many days, but everytime I am failing. I am new to this JS, UI and https req/res domain.
My environment is: nodeJS, JavaScript for backend. ReactJS for frontend.
I need to upload tar file from my machine to remote server.
Here is my frontend code where I am making fetch request to upload a file.
export function postXCCDF () {
  let _headers = {
    'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
    'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu'
  };

  var formData = new FormData();
  formData.append('type', 'file');
  formData.append('file', 'C:\\MyDrive\\rules.zip');

  let uri = '/rest/policy';

  const options = { method: 'POST', headers: _headers, body: formData };
  return fetch(`${_host}${urlPrefix}${uri}`, options)
    .then(processStatus)
    .then(response => response.json());

}

Here is my backend code , where I am expecting the tar file to receive.
router.post('/policy', function(req, res) {
    console.log('hey I reached here');
    console.log('hemant req',req.body.formData); // prints hemant req undefined
    // Dont know how to save it to some directory. ??? :(
});

My whole idea is to upload a tar file to a server located at remote location. I have tried lot many other ways, but nothing seems to help.

A: The body-parser module only handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading files).
For multipart, you'd need to use something like connect-busboy or multer or connect-multiparty (multiparty/formidable is what was originally used in the express bodyParser middleware).


text:
Q: Merge nearby Contours I am trying to extract the straight line in the middle or get rid of the contours on the left and right side.
For removing the contours I am thinking of clustering the contours together then extracting each contours separately or i can cluster the contours and label them then remove a particular label, but i don't think it will work as i have large variety of images to deal with.
Secondly, I have to find whether the contours in the middle straight line are connected or not i.e. the line is broken or not in the original image.
Original image:

Dilated image:

After findContours:


text:
Q: Why am I seeing Unable to simultaneously satisfy constraints when using self sizing UITableView cells in iOS 8? I've used self-sizing cells quite frequently since iOS 8 was released, but recently I've been getting errors like this:
2015-07-31 08:25:10.610 Evensity[78297:3090623] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSLayoutConstraint:0x7fbae3485d50 V:[UITextField:0x7fbae3486ab0(55)]>",
    "<NSLayoutConstraint:0x7fbae3424790 V:|-(2)-[UITextField:0x7fbae3486ab0]   (Names: '|':UITableViewCellContentView:0x7fbae3486990 )>",
    "<NSLayoutConstraint:0x7fbae3487480 V:[UITextField:0x7fbae3486ab0]-(2)-|   (Names: '|':UITableViewCellContentView:0x7fbae3486990 )>",
    "<NSLayoutConstraint:0x7fbae0c525a0 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7fbae3486990(59)]>"
)

This is for a very simple cell that contains a UITextField and nothing else.

It's hard to see from the picture, but the text field has a height constraint of 55, and vertical spacing constraints (top and bottom) of 2 each. Due to self sizing, iOS adds the UIView-Encapsulated-Layout-Height vertical size constraint of 59 (55 + 2 + 2). This doesn't seem like a conflict to me, but I still see this warning in the logs.
Also FYI, the broken constraint message appears immediately upon entering the screen; it's not dependent on scrolling to cause cell reuse.
What am I missing here that would explain this, and how would I correct this? From the user's point of view, everything seems to be working as expected. But, I'm a big believer that if auto layout is writing warnings to the console, I should be correcting them as they're bound to be a problem someday.

A: Maybe each instructs the Auto Layout runtime to do something that contradicts the other.
Maybe try :
tableView.translatesAutoresizingMaskIntoConstraints = NO;


text:
Q: Binary Interpolation Search cannot find the number im looking for (C) I have an assignment demanding I utilize the algorithm of Binary Interpolation Search in order to find a number and its position in an array, which I'm entering through the keyboard. Unfortunately, while I get no errors, the program returns nothing even though it asks me to enter a number! If you have any idea what might be going wrong it will be helpful!
Here is my code:
#include<stdio.h>
#include<math.h>

int bis(int Array[],int x)
{
    int i;
    int hitpos;
    int left = 0;
    int right = sizeof(Array);
    int size = right - left + 1;
    int next;
    int a = x - Array[left];
    int b = Array[right]-Array[left];
    int c = right - left + 1;
    int d = (int)(i*sqrt(size));
    next = (size*a/b+1);
    do
    {
        i=0;
        size = right - left +1;
        if(x >= Array[next])
        {
            do
            {
                i = i+1;
                right = next + i*sqrt(size);
                left = next + (i-1)*sqrt(size);
            }
            while(x > Array[next + d -1]);
        }
        else if(x < Array[next])
        {
            do
            {
                i = i+1;
                right = next -(i-1)*sqrt(size);
                left = next - i*sqrt(size);
                next = left + (c*a/b);
            }
            while(x < Array[next - d + 1]);
        }
        else if(x = Array[next])
        {
            return next;
        }
        else
        {
            return -1;
        }
    }
    while (x != Array[next]);

}

int main()
{
    int Array[] = {1,8,10,14,31,55,56,78,87,101};
    printf("Please provide a number for binary interpolation search\n");
    int x;
    scanf("%d", x);
    int hit;
    hit = bis(Array,x);
    if (hit != -1)
    {
        printf("Element found at index %d", hit);
    }
    else
        printf("Element not found.");
    return 0;

}


text:
Q: Google Analytics Custom Event Tracking Partially Working I am trying to add a custom tracking event for 11 buttons on a website. However, google analytics is only tracking the two buttons on the home page (BtnHome1 and BtnHome2) and not the rest on the other pages. The code is inserted via Google Tag manager and set to trigger for all pages. The tracking code is the following:
<script>

document.getElementById("BtnHome1").onclick = function(){
    _gaq.push(['_trackEvent', 'BtnHome1', 'click', '']);
 }
   document.getElementById("BtnHome2").onclick = function(){
    _gaq.push(['_trackEvent', 'BtnHome2', 'click', '']);
 }
    document.getElementById("BtnMasterPlan").onclick = function(){
    _gaq.push(['_trackEvent', 'BtnMasterPlan', 'click', '']);
 }
    document.getElementById("BtnUbicacionAmenities").onclick = function(){
    _gaq.push(['_trackEvent', 'BtnUbicacionAmenities', 'click', '']);
 }
    document.getElementById("BtnDelMarResidents").onclick = function(){
    _gaq.push(['_trackEvent', 'BtnDelMarResidents', 'click', '']);
 }
    document.getElementById("BtnParaisoDelMar").onclick = function(){
    _gaq.push(['_trackEvent', 'BtnParaisoDelMar', 'click', '']);
 }
    document.getElementById("BtnSantaAnaDelMar").onclick = function(){
    _gaq.push(['_trackEvent', 'BtnSantaAnaDelMar', 'click', '']);
 }
    document.getElementById("BtnPorqueInvertir").onclick = function(){
    _gaq.push(['_trackEvent', 'BtnPorqueInvertir', 'click', '']);
 }
    document.getElementById("Btn4ventajasGolf").onclick = function(){
    _gaq.push(['_trackEvent', 'Btn4ventajasGolf', 'click', '']);
 }
    document.getElementById("BtnEcogolf").onclick = function(){
    _gaq.push(['_trackEvent', 'BtnEcogolf', 'click', '']);
 }
    document.getElementById("BtnConoceArquitectos").onclick = function(){
    _gaq.push(['_trackEvent', 'BtnConoceArquitectos', 'click', '']);
 }
 </script>

The site is here
Thanks in advance


text:
Q: Equation solver webapp in Python I am making an equation solver webapp in Python (Flask framework).  App takes user input [a, b, c] and sent to server by calling a server side python function and get the results displayed using AJAX.
Part of Client JavaScript:
$.getJSON($SCRIPT_ROOT + '/_serverFunction', { form data });

Server Python function:
@app.route('/_solve')
def solve():
    a = request.args.get('a')
    b = request.args.get('b')
    c = request.args.get('c')
    cof = [a, b, c]
    roots = np.roots(cof)
    return jsonify(roots)

Above works just fine and i get the results displayed as per the input.
However, I would also like to show a graph representing the solution next to the above results.
I am able to generate a dummy static graph at server using matplotlib and send to the client with the following:
<img src="/image.jpg" id='bg'>

Server side python code:
 @app.route('/image.jpg')
    def image_jpeg():
        image = StringIO()
        plot(image)
        image.seek(0)
        return send_file(image,
                         attachment_filename="image.jpg",
                         as_attachment=True)

def plot(image):
    x = np.linspace(0, 100)
    y = np.sin(x)
    pyplot.plot(x, y)
    pyplot.savefig(image, format='jpg')

Above works and I get a static curve when i load the page. But I would like this graph to change when user submits the input to the server to solve the equation every time.
How to make the both calls to the solve() and image_jpeg() from the same same AJAX call?
How do the I share the user data [a , b ,c] across functions so the graph can be generated and sent back.
Update:
$('img').attr('src',"data:image/png;base64"+ "," + data.imgdata);

On server:
    imgdata = image.getvalue()
import base64
imgdata = base64.b64encode(imgdata)

imgData is passed along with json.

A: One request can't become two, unfortunately, but there is a way of doing what you want.
In order to achieve this, you could send the image as a data url inside the JSON you request from your server, then in JS you simply set the image element's src attribute the data.
You would start by moving the image_jpeg function into your solve method, since you have the image data in a string already all you need to do is encode it into base64 and prefix it with "data:image/png;base64," changing the mime to suit the image format.
Also, to complete the answer, you can share user data across functions. You would usually use Cookies, in Flask they wrap cookies in Sessions to make it even easier for you, take a look. That being said, I don't think they fit this problem.

A: The simple way is to change the client to just explicitly load the image, passing the same arguments that it passed to the solve API.
Another option is to pass the image contents back from solve as another value. Your client code can then build an img with a data: in its src.
Finally, you can use a session to store information between calls from the same client, so every time someone calls solve you stash their arguments as "last_solve_args", and then you can use them inside image. (The client will, of course, still have to reload the image, so this is really no better than the first one.)


text:
Q: External link to see Swagger docs for azure function? If I have an Azure function:  http://foo.azurewebsites.net/api/v1/bar
What is the url for viewing the Swagger documentation that I created in the API definition table on the azure portal?

A: There should be a link available in the Api Definition page in the Azure Portal. The URL will look something like:
https://foo.azurewebsites.net/admin/host/swagger?code=abcdefghijk==
The link is on the left panel of the Api Definition page. You may have to click the "Expand/Collapse" button in order to toggle it.
Edit: Misunderstood the question -- there is currently no way to view the 'Documentation' page publicly. I've filed https://github.com/Azure/azure-functions-host/issues/2733 to track this.


text:
Q: pselect does not recognize the event I am working on a client-server application. There are two threads on each side(main and control thread I call). I am using pselect() in both the threads. The control thread's job is to send a control/signal packet to the control thread on client side to do an activity based on signals. The main thread's job it to read/write data continuously where as control thread communicate through a separate TCP -IPV4 connection.I am using sigusr signal on the server side that sets some global flags(using mutexes) and based on which the server control thread then sends signal packet to control thread on client side.
problem: I see that the server has sent the data (checking return value of send) but pselect() in control thread on client side isn't recognizing it on time.I sometime see that it receives data at the end(when data transfer over main thread is complete) or does not receive it at all . The same code when I run on different linux server works fine( 2.6.18-274.12.1.el5 #1 SMP Tue Nov 8 21:37:35 EST 2011 x86_64 x86_64 x86_64 GNU/Linux) but not on the current one(2.6.32-220.4.2.el6.x86_64 #1 SMP Mon Feb 6 16:39:28 EST 2012 x86_64 x86_64 x86_64 GNU/Linux)
The priority and scheduling scheme on both the server is same(0,0). I have read abt using sigproc for masking signals before using pselect but I am not sure what signal to handle as I am just signalling the server and not client. Also to add both client and server are running on same machine( I am using loopback address to communicate). I have tried both blocking(time struct in pselect is set to NULL) and non blocking mode for pselect.Also I am setting the socket id in FD_SET in the loop everytime.The code is as below. Please advice
/**** Code ****/
   while(vg_closeCtrlThread==0)
    {

            FD_ZERO(&vl_fdsctrl);
            FD_SET(vg_ctrlSocket.socket_id,&vl_fdsctrl);
            //fprintf(stdout,"Setting FD SET...Control thread \n");
            /* Set the select polling to few seconds */
            vl_tv.tv_sec = 0;//HS
            //vl_tv.tv_sec = 50;//HS
            vl_tv.tv_nsec = 10000;

            /* Set the select polling to few seconds */
            vl_tv2.tv_sec = 0;//HS
            vl_tv2.tv_nsec = 500;

            /* variable vg_ctrlpacket_sent and ip_proto_switch are set when sigusr is received for server process using mutexes , this if cond executes only on server side */
            if(vg_dataSocket->vst_iptype == IPV_BOTH && vg_ctrlpacket_sent && ip_proto_switch)
            {
                    fprintf(stdout,"vg_ctrlpacket_sent value:%d\n",vg_ctrlpacket_sent);
                    fprintf(stdout,"ip_proto_switch value:%d\n",ip_proto_switch);
                    if(vg_ctrlSocket.vst_isserver)
                    {
                            FD_ZERO(&vl_fds);
                            FD_SET(vg_dataSocket->sock_id[1],&vl_fds);

                            fprintf(stdout,"\t\t Switch protocol..Control Thread\n");
                            vl_ctrlInfo->vst_type = IP_SWITCH;

                            vlError = fn_send(&vg_ctrlSocket,(char *)&vl_ctrlInfo->vst_type,sizeof(vl_ctrlInfo->vst_type),NO_DATA_TX);
                            fprintf(stdout,"Ctrl packet Send error:%d\n",vlError);

                           if(vlError == -1)
                           {
                            fprintf(stderr,"Error in sending the data,Err:%s\n",fn_strerror_r(errno,err_buff),vg_ctrlSocket.vst_nm_thread);
                                    exit(EXIT_FAILURE);
                            }
                    }
                    vg_ctrlpacket_sent = 0;

                    pthread_mutex_lock(&socket_mutex_2);
                                            vg_ctrlpacket_recv = 1;
                    pthread_mutex_unlock(&socket_mutex_2);
            }
            //fprintf(stdout,"Before pselect ctrlthread..\n");

            /* check if any data is available on the socket */
            if(vg_ctrlSocket.vst_isserver)
                    vlError = pselect(vg_ctrlSocket.socket_id+1, &vl_fdsctrl,NULL, NULL, &vl_tv,NULL);
            else{
                    fprintf(stdout,"...Here is the PROBLEM*\n");
                    vlError = pselect(vg_ctrlSocket.socket_id+1, &vl_fdsctrl,NULL, NULL,NULL ,NULL);
                    //vlError = select(vg_ctrlSocket.socket_id+1, &vl_fdsctrl,NULL, NULL,NULL);

            }
            //perror("Just to check for illegal error\n");

            /* Reinitialize the polling to few seconds */
            vl_tv.tv_sec = 0;//HS

            vl_tv.tv_nsec = 10000;

            if(vlError == -1)
            {
                    perror("Error in select() function of Control thread");
                    exit(EXIT_FAILURE);//HS
            }
            else if(vlError > 0)
            {
                    memset(vlBuffer,0,56);
                    if(debug>1){
                            fprintf(stdout,"The socket id is:%d, Thread:%s\n",vg_ctrlSocket.socket_id,vg_ctrlSocket.vst_nm_thread);
                    }
                    vlError = fn_recv(&vg_ctrlSocket,(char *)&vl_ctrlInfo->vst_type,sizeof(vl_ctrlInfo->vst_type),NO_DATA_TX);
                    if(vlError < 0)
                    {
                            fprintf(stderr,"Error in receiving the data,Err:%s\n",fn_strerror_r(errno,err_buff));
                            exit(EXIT_FAILURE);
                    }
                    if(vlError > 0)
                    {
                            if(debug>1)
                                    fprintf(stdout,"Some data received: %d, Thread:%s..\n",vlError,vg_ctrlSocket.vst_nm_thread);
                            switch(vl_ctrlInfo->vst_type)
                            {
                            case BANDWIDTH_INFO:
                                    if(debug)
                                            fprintf(stdout,"Received bandwidth information..Control Thread\n");
                                    vlError = fn_recv(&vg_ctrlSocket,(char *)&vl_ctrlInfo->vst_info,sizeof(vl_ctrlInfo->vst_info),NO_DATA_TX);
                                    fprintf(stdout,"Bandwidth :%.3f\n",vl_ctrlInfo->vst_info.vst_info);
                                    if(vlError > 0)
                                            fn_setShmDownStreamInfo(vl_ctrlInfo->vst_info);
                                    break;
                            case PROTO_ACK_INFO:
                                            fprintf(stdout,"Received ack..Control Thread\n");
                                            vlError = fn_recv(&vg_ctrlSocket,(char *)vl_ctrlInfo,sizeof(st_ackPacket),NO_DATA_TX);
                                            if(vlError > 0)
                                                    fn_protoProcessAck(vlBuffer);
                                    break;
                            case IP_SWITCH:/* this is packet data for now */
                                            fprintf(stdout,"\t\t switch..Control Thread\n");
                                            pthread_mutex_lock(&socket_mutex_2);
                                                    fprintf(stdout,"Locking vg_ctrlpacket_recv..Control Thread\n");
                                                    vg_ctrlpacket_recv = 1;
                                                    pthread_mutex_unlock(&socket_mutex_2);
                         break;

                            } /* switch(vl_ctrlInfo->vst_type) */

                    } /* if(vlError > 0) */
                    else if(vlError == 0)
                    {
                            fn_cleanUpCtrlThread();
                    }/* if(vlError == 0) */
            }/* if(vlError) */
    }/* while(vg_closeCtrlThread==0) */

Thanks...


text:
Q: Query with date ranges I would like to know how to proceed to make a query in this example:
I have a User Table that has UserID, UserName, DateRegistered and roles.
I want to to make a query by selected two combobox, each combo has:
-Period Register User(current month, last month, current 15 days, last 15 days, this year and last year)
-Roles(different roles)
I want to show in a grid the result query referring with the selected combobox items.
For example: The user registered in the last 15 days with the status administrator.
I have the idea how to do it but I want to do something general and not do so many query depending on the Period.
I use EntityFramework.
This is not the code just an example of what I suppose it should be, because I dont know converting the periode and how to compare in case is not the current last 15 days.
    string period = dropDownList.SelectedValue.ToString();
    DateTime StarPeriode= new DateTime();
    switch (option.ToUpper())
    {
        case "0":
            // CURRENT 15 days
            StarPeriode = DateTime.Now.Subtract(-15);
            break;
        case "1":
            // LAST 15 days
            StarPeriode = DateTime.Now.Subtract(-30);
            break;
        case "2":
            // CURRENT MONTH
            break;
        case "3":
            // LAST MONTH
            break;
        case "4":
            // CURRENT YEAR
            break;
        case "5":
            // LAST YEAR
            break;
        default:
            break;
    }

    var _db = new Project.Models.UserContext();
    IQueryable<User> query = _db.User.GetUser;

    query = query.Where(p => p.User.RegisterDate <= StarPeriode ||        p.User.RegisterDate>DateTime.Now);

A: Just set a startDate and endDate variable in each situation and then use the same where clause on the LINQ statement
var startDate = DateTime.Today;
var endDate = DateTime.Today;
var now = DateTime.Today;

switch (option.ToUpper())
{
    case "0":
        // CURRENT 15 days
        startDate = now.AddDays(-15);
        endDate = now;
        break;
    case "1":
        // LAST 30 days
        startDate = now.AddDays(-30);
        endDate = now;
        break;
    case "2":
        // CURRENT MONTH
        startDate = new DateTime(now.Year, now.Month, 1);
        endDate = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));
        break;
    case "3":
        // LAST MONTH
        var lastMonth = now.AddMonths(-1);
        startDate = new DateTime(lastMonth.Year, lastMonth.Month, 1);
        endDate = new DateTime(lastMonth.Year, lastMonth.Month, DateTime.DaysInMonth(lastMonth.Year, lastMonth.Month));
        break;
    case "4":
        // CURRENT YEAR
        startDate = new DateTime(now.Year, 1, 1);
        endDate = new  DateTime(now.Year, 12, 31);
        break;
    case "5":
        // LAST YEAR
        var lastYear = now.AddYears(-1);
        startDate = new DateTime(lastYear.Year, 1, 1);
        endDate = new  DateTime(lastYear.Year, 12, 31);
        break;
    default:
        break;
}

var users = Users.Where(u => u.RegisterDate >= startDate && u.RegisterDate <= endDate);

Depending on how you store your RegisterDate values, you will want to watch your edge cases as my example assumes all time portions are 12:00:00 AM.


text:
Q: React Native Could not find com.android.tools.build:gradle:3.4.2 I am new to React native trying to start a new project. I followed google docs and already had the android studio installed. added ANROID_HOME to env variables and platform tools to system variables as mentioned in the docs. while running ```react-native run-android``. I get this error
error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'AwesomeProject'.

> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find com.android.tools.build:gradle:3.4.2.

my android studio version plugin is 3.4.2 and here is my build.gradle file :
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.2")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

and my gradle-wrapper.properties file
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.5-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

A: Thanks all for the Answers I think I will provide the answer here for others to use.
my issue was due to the version conflict of gradle and android studi plugin.
1- open android studio and start a new project
2- There should be a builde.gradle and gradle wrapper file
3- the versions you see for gradle here for e.g 5.1.1 or etc is the version you must use in your project**
4- change the classpath com.android.tools.build:gradle:to 3.4.2 in your project build.gradle file
5- change the gradle wrapper properties distribution path to  distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip


text:
Q: Display a line with a dot before and after I want to display something like this image :

I am struggling with the :before and :after, I can't manage to display a perfectly aligned line with the dots.

.line {
  height: 3px;
  width: 50px;
  background: green;
}

.line::before {
  content: "\A";
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: green;
}

.line::after {
  content: "\A";
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: green;
}

;
margin-bottom: 8px;
      &:before, &:after {
        @extend .dot;
      }
    }

  .dot {
    content: "\A";
    display: inline-flex;
    width: 10px;
    height: 10px;
    border-radius: 50%;
  }

A: You can make use of flexbox in this case. justify-content: space-between will align them horizontally and align-items: center would align them vertically.

.line {
  height: 3px;
  width: 50px;
  background: green;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.line::before {
  content: "\A";
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: green;
}

.line::after {
  content: "\A";
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: green;
}

A: How about this:

.line {
  height: 3px;
  width: 50px;
  background: green;
  position: relative;
}

.line:after,
.line:before {
  content: '';
  position: absolute;
  width: 10px;
  height: 10px;
  background: green;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 50%
}

.line:after {
  right: 0
}


text:
Q: EC2: can I provide default startup scripts to erase sensitive data in my AMI? I'm trying to use EC2 to provide an easy-to-use way to bootstrap a hard-to-build web application.
Trouble is, there is some sensitive configuration on the filesystem, such as password salts.
I've written a user-data script that replaces these salts with random values on first boot, and I put this in the user-data attribute of the instance from which I built my AMI.
But now it looks to me like user-data scripts are specific to instances, not AMIs - that is, it's only run when specified by the user doing the cloning, not the creator of the AMI (me).
Well... duh, I guess that makes sense given the name "user data".
Is that wrong? Is there any way for me to provide a script that's run automagically on new clones of my AMI?

A: If you are building the AMI, then you can put whatever you want on the file system.
For your high level question about running code on startup, you can add the code as a standard system startup script on the AMI file system.  The specific way to do this depends on the initialization software used by your particular Linux distro and release.
HOWEVER! Your specific example of overwriting sensitive data on the file system is not something that is safe to do in an AMI.  Sensitive, private, or secret information should never be placed in an AMI.  In fact, it should never touch the EBS volume used to build a public AMI as there are ways for users to restore the data that has been deleted.
I've written a couple articles about these security risks:

Creating Public AMIs Securely for EC2
http://alestic.com/2011/06/ec2-ami-security
Hidden Dangers in Creating Public EBS Snapshots on EC2
http://alestic.com/2009/09/ec2-public-ebs-danger


text:
Q: applying functions to pasted strings in R I have a dataframe,df, with many columns cola,colb etc each consisting of a sequence of integers 0 or 1
df$cola
[1] 1 0 0 1 0 1 0 0 etc.

I am using the subSeq function in the doBy package to obtain some sequences
and want to apply this to all columns
I have tried putting the columns into a vector
cols <- colnames(df) # "cola" "colb" etc.

and have tried without success this approach
subSeq(get(paste0("df$",cols[1]))) # error object 'df$cola' not found

Could not easily find an equivalent on site via search

A: I think you are looking for df[[cols[1]]].
Note that df[["foo"]] is the same as df$foo.


text:
Q: How can I fix this problem of showing the popup? I have a popup that shows up whenever the user types unallowed characters, then I put a delay to hold the popup on the screen for 6 seconds, and what I want to do is that when the user types the allowed characters, then the popup should immediately disappear, and when the user types the unallowed chars again, it should show the popup and then wait for 6 seconds if the user didn't type anything. I've done it this way, But it's not working, the popup shows up, and then if I type an allowed char, it set the IsOpen to false, but when the user types the unallowed chars again, the delay is not working anymore, it closes the popup in random seconds. How can I fix this problem, or what's the better way of doing this?
    private async void txtName_TextChanged(object sender, EventArgs e)
    {
        if (Regex.IsMatch(txtName.Text, @"[\\/:*?""<>|]"))
        {
            string pattern = @"[\\/:*?""<>|]";
            Regex regex = new Regex(pattern);
            txtName.Text = regex.Replace(txtName.Text, "");

            if (AlertPopup.IsOpen == false)
            {
                AlertPopup.IsOpen = true;
                await Task.Delay(6000); //It stays true for 6 seconds
                AlertPopup.IsOpen = false;
            }
        }
        else
        {
            AlertPopup.IsOpen = false;
        }
    }

This is the XAML code for popup:
    <Popup AllowsTransparency="True" PlacementTarget="{Binding ElementName=txtName}"
           Placement="Bottom" x:Name="AlertPopup">
        <Border Margin="0,0,35,35" Background="#272C30" BorderBrush="#6C757D"
                BorderThickness="2" CornerRadius="10">
            <Border.Effect>
                <DropShadowEffect Color="Black" BlurRadius="35" Direction="315"
                                  ShadowDepth="16" Opacity="0.2"/>
            </Border.Effect>
            <TextBlock Padding="8,3,8,5" Foreground="#ADB5BD" Background="Transparent" FontSize="12"
            Text="The file name can't contain any of the following
characters :   \  / : * ? " < > |"/>
        </Border>
    </Popup>

A: Task.Delay accepts a CancellationToken that you can use the cancel the task on each key stroke. Something like this:
private CancellationTokenSource cts;
private async void txtName_TextChanged(object sender, EventArgs e)
{
    if (cts != null)
    {
        cts.Cancel();
        cts.Dispose();
    }
    cts = new CancellationTokenSource();

    if (Regex.IsMatch(txtName.Text, @"[\\/:*?""<>|]"))
    {
        string pattern = @"[\\/:*?""<>|]";
        Regex regex = new Regex(pattern);
        txtName.TextChanged -= txtName_TextChanged;
        txtName.Text = regex.Replace(txtName.Text, "");
        txtName.TextChanged += txtName_TextChanged;

        if (AlertPopup.IsOpen == false)
        {
            AlertPopup.IsOpen = true;
            try
            {
                await Task.Delay(6000, cts.Token);
            }
            catch (TaskCanceledException) { }
            finally
            {
                AlertPopup.IsOpen = false;
            }
        }
    }
    else
    {
        AlertPopup.IsOpen = false;
    }
}


text:
Q: Firefox WebExtension: Input type="color" closes extension popup I developed a small extension where different words on the page are highlighted in different color. The user can pick a color for a specific word using <input type="color />.
This extension was made using chrome, with no issues at all regarding the color picker.
In firefox, however, a new window opens with a color picker.
The main issue is that firefox closes the popup's extension when the color picker is opened. The change event on the color picker is ignored, because it is stored in the popup.js file.
I already saw a question about this issue on stack overflow with no answers.
Thank you in advance.


text:
Q: Git cherry-pick issue When I tried to do a git cherry-pick, I received this error

commit xxx is a merge but no -m option was given.

When I tried to throw in -m, it gives

error: switch `m' requires a value.

Any idea why this error is happening? There seems to be a merge conflict on Gerrit but it doesn't show any merge conflict locally.

A: Merge commits have more than one parent and the resulting revision is (theoretically) the mixture of the changes from both parent branches. If you are trying to cherry-pick a merge revision, git wants to know which of the revision parents is the one you would like to consider as it it were your current HEAD (so to pull changes from the other parents of the merge revision).


text:
Q: Настройки для каждого пользователя NSUserDefaults. Spritekit. Swift Пишу игру на свифте. Хочу сделать что-то вроде логинов,  можно будет выбрать уже созданный, либо создать новый. Настройки должны сохраняться для каждого такого логина отдельно. через что лучше делать? ( сейчас делаю через NSUserDefaults). И как это лучше организовать?

A: Данные по игроку хранятся в словаре. Ключем для NSUserDefaults будет являться мыло или id пользователя.
Также отдельно хранится массив этих клюй (чтоб сохранился порядок пользователей, если он нужен).


text:
Q: Not able to enter decimal values in a text box with type = text ,by using sendkeys in protractor protractor
element(by.id('amt')).sendKeys('796.21');

Html code
<input _ngcontent-c34="" id="amt" maxlength="8" name="amt" pattern="^[0-9]*\.[0-9]{2}$" required="" type="text" class="ng-touched">


text:
Q: Accordion with prototype 1.7 I am migrating an application from prototype 1.4 to prototype 1.7.
In this application moo.fx is used for the accordian.
And a lot of code has been written for the effects like text autogrow.
I couldnt find an updated version for moo.fx based on prototype other than 1.4 version.
Do I need to choose some other alternative?
And what could that alternative be?

A: You can use script.aculo.us which goes hand in hand with prototype


text:
Q: How to give priority to spring bean with same id? In our project we are using spring with Junit for Junit testing. We have used @ContextConfiguration annotation for loading multiple file. We have two classes AbstractContextJUnitTest and ContextJUnitTest and ContextJUnitTest extends AbstractContextJUnitTest.
During code flow I have noticed that same bean Id in multiple files with different bean types. When I am testing these Junits and getting the below error.
Error:

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean
  named 'voterId' is expected to be of type [com.spring.test2.Student]
  but was actually of type [com.spring.test2.Parent]

My requirement is Student bean should load with VoterId instead of Parent Bean.
Below are the java files and spring bean xml files:
test.xml:
<beans>
    <context:annotation-config/>
    <bean id="voterId" class="com.spring.test2.Parent">
    <property name="Name" value="hai"/>
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
        <property name="username" value="system" />
        <property name="password" value="system" />
    </bean>
    <bean id="transactionManager"

        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

test1.xml
<beans>

    <context:annotation-config/>
    <bean id="voterId" class="com.spring.test2.Student">
        <property name="name" value="hello"/>
        <property name="number" value="2080"/>
     </bean>
</beans>

AbstractContextJUnitTest.java
@ContextConfiguration(locations="classpath:/com/spring/test2/test1.xml")
public class AbstractContextJUnitTest extends AbstractTransactionalJUnit4SpringContextTests{

}

ContextJUnitTest.java
@ContextConfiguration(locations={"classpath:/com/spring/test2/test.xml"})
public class ContextJUnitTest extends AbstractContextJUnitTest{

    @Test
    public void testStudent(){
        Student stud=applicationContext.getBean("voterId",Student.class);
        assertEquals(stud.getNumber(), 2080);
    }
}

A: Did you tried @Primary?
<bean id="voterId" class="com.spring.test2.Student" primary="true">
        <property name="name" value="hello"/>
        <property name="number" value="2080"/>
</bean>

You have to use @Qualifier for com.spring.test2.Parent wherever you need.
Or you can get the bean with type as:
applicationContext.getBeansOfType(Student.class).get("voterId")

A: This is probably because you have extended classes in that order..and your test.xml doesn't have any bean with of Student. So it is simply following inheritance and found parent.
Below lines make it look for bean voterid in test.xml first and it found it there.
ContextConfiguration(locations={"classpath:/com/spring/test2/test.xml"}) public class ContextJUnitTest


text:
Q: Python VSCode formatOnSave with black not working in WSL I am using WSL2 to work on some Python project, but black is not auto-formatting in VSCode (Remote - WSL).
System info:

*

*Base system: Windows 11 Pro x64

*WSL2 system: Ubuntu-22.04-LTS

*settings.json path in WSL: /home/<user>/.vscode-server/data/Machine/settings.json
My settings.json looks like:
{
  // Python linting and formatting customizations..
  "python.linting.pylintEnabled": false,
  "python.linting.flake8Enabled": true,
  "python.linting.enabled": true,
  "python.linting.flake8Args": ["--max-line-length=100", "--ignore=E501"],
  "python.formatting.provider": "black",
  "python.formatting.blackArgs": ["--line-length", "100"],
  "[python]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports": true
    },
    "editor.formatOnSave": true
  }
}

This same settings works on my Windows 11 system. In local Windows, whenever I create a virtual environment for a python project and save a python file, vscode automatically asks me to install flake8 and black in the venv. But nothing of the sort happens in WSL.
Even if I install black in WSL Python venv, it does not auto-format the Python code; and there are no logs related to black visible in either Output > Python or Output > Log (Main) tab.
But manual formatting works after I install black in venv:
(venv) asif@MSI:~/vscode/myproject/$ black app_pkg/models.py
reformatted app_pkg/models.py

All done! ✨  ✨
1 file reformatted.

Note: I even tried adding "python.formatting.blackPath": "./venv/bin/black" to settings.json file, but it didn't work.
Any help would be much appreciated. Thanks in advance!
Edit: As suggested, I have these two settings enabled in my system,
Format on save applied universally:

Python code formatter set as black:

Still I am unable to make the Python formatOnSave work in VSCode-WSL.

A:
But manual formatting works after I install black in venv

It can be seen that black can work.Now let's set up automatic formatting for vscode:
First open the settings of vscode, search for format on save, and then check it. Set this step, and the code will be automatically typeset every time the file is saved.

Then search Python formatting provider and select black.


text:
Q: QDateTime with sqlite3 I'm using Sqlite3 with Qt , anyway to save the DateTime form in the db i used Text type , see this from my db :
data
so the INSERT and SELECT is work very , but how i could make specific SELECT !
my code :
QString("SELECT * from main.sell_cash_log WHERE 'when' >= '%1' AND 'when' <= '%2'").arg(ui->fromdate->dateTime().toString("dd-MM-yyyy:HH-mm-ss")).arg(ui->todate->dateTime().toString("dd-MM-yyyy:HH-mm-ss"))

A: You're probably better off using one of the date operaterators to get info for a specific date
https://www.tutorialspoint.com/sqlite/sqlite_data_types.htm
To select all in the month of November:
SELECT * FROM main.sell_cash_log WHERE strftime('%Y-%m-%d', when) BETWEEN "11-01-2016" AND "11-31-2016"
See also SQL Select between dates which is where I copied that query q

A: The problem was by the field called when , in insert query i was useing escape string ('when') but with select not work (' ' ) so i used (when) and it's workd :
:
CartItems->setQuery(QString("SELECT * from main.sell_cash_log WHERE datetime(`when`) BETWEEN datetime('%1') AND datetime('%2')").arg(ui->fromdate->dateTime().toString("yyyy-MM-dd hh:mm:ss")).arg(ui->todate->dateTime().toString("yyyy-MM-dd hh:mm:ss")));


text:
Q: Get HttpRequest full request string I'm working on a proxy that will relay connections to another server. I had implemented a IHttpHandler that takes requests for a specific address and sends them to my proxy.
My proxy basically starts a sockect connection to the proxied server and reads the original request:
var requestString = new StreamReader(httpRequest.InputStream).ReadToEnd();

My problem arises at this point: the input stream only contains the stream of the body of the HTTP request, not the complete request.
How can I retrieve the full HTTP Request without having to reconstruct it from the HttpRequest object?

A: I don't know of a definitive one-liner in ASP .NET, but you can get pretty close, as shown in this forum post.  What is suggested there is to build the first line out of HttpRequest properties, then add ServerVariables["ALL_RAW"], then the request body in the InputStream as you're already doing.

A: The only way to get the 'full HTTP Request' object is to actually reconstruct it in some way. I'm not sure you need the whole object for this process though. Perhaps you could just grab a subset of the items in HttpRequest for processing? You could manually concatenate the various portions of the object you need into something new. Once you deviate from using HttpRequest though, it's all custom to me.


text:
Q: how to install the oauth in php How to install the oauth in php. Can any one provide me the full description, links and all the libraries. I tried from here but I could not understand
I want to access the oauth token by the following code
$oauth = new OAuth(API_CONSUMER_KEY, API_CONSUMER_SECRET);

but this is not working because php extension for oauth is not installed

A: Yup, u need this file php_oauth.dll (windows)
Put into
/bin/php[version]/ext

And you need to change php.ini to load oauth (Dynamic Extensions)
extension=php_oauth.dll

A: First of you have to download pear run it. than Install the Oauth extension. For windows you should have compiled file. of .dll file of extension. Best of luck

A: You can find the correct dll files here
Make sure you select the correct file on the following factors:

*

*PHP version

*Architecture (x86 or x64)

*Thread Safety (Yes/No)

You can find these info using php_info(); of your server.


text:
Q: Mapping a document with partly-defined schema I'm writing a demo app using Spring & MongoDB as a database.
My main domain class looks like:
@Document
public class Person {

    @Id
    private String id;

    //Some other fields
    private DBObject additionalData;

}

The key is that additionalData is a subdocument with no schema specified, it is kind of user-defined JSON. But when I am parsing this json (using (DBObject) JSON.parse(value) expression), it is stored as a string in MongoDB, and I need it to be a nested document structure.
Searched for couple of hours, found no solution. Any ideas?

A: I'm not really sure of the expected result of casting the result of
JSON.parse(value)

to DBObject, which is an interface, not a class.
Try casting the result to an implementation of DBObject BasicDBObject (or BasicDBList), or a Map<String, Object> as mentioned in the comments (it is also an interface, but it does work).
If you're working with Spring Data Rest, you will probably not need to deserialize "manually", Spring will do it for you. Check this answer for a basic example of what to do.
Having data with no schema specified may not be the best idea around (mongodb saves you from doing it at the database level, but you should do it at the application level), but I use similar tricks in production, and you can somehow make it work.


text:
Q: What exactly is and is not a concentration inequality? Hoeffding's inequality is surely a concentration inequality. It can be written in the form:
$\Pr(\bar X + f(n,\delta) \geq \mu) \geq 1-\delta,$
for some function $f$, where $X$ is a set of i.i.d. samples of a random variable with mean $\mu$, $\bar X$ is the sample mean, and $\delta \in [0,1]$. Maurer and Pontil presented an empirical Bernstein bound that uses the sample mean and sample standard deviation. It can be written in the form:
$\Pr(\bar X + f(X, n, \delta) \geq \mu) \geq 1-\delta,$
for some other function f that now depends on the sample $X$ (specifically, on the sample standard deviation of $X$).
Interestingly, Maurer and Pontil do not call their inequality a "concentration inequality". Notice that the width of the confidence interval it would provide on the mean depends on the samples, X. Similarly, Anderson (1969) presented a high-confidence bound on the mean that cannot (immediately) be formulated as a deviation from the sample mean. That is, its most natural form would be:
$\Pr(f(X, n, \delta) \geq \mu) \geq 1-\delta,$
for some other function f that one could (with work) phrase as the sample mean plus another term that depends on the sample, but which is not naturally in this form.
Which of these is a "concentration inequality"? Is Anderson's inequality not a concentration inequality because it is not clearly showing how the sample mean deviates from the expected value? Is even Maurer and Pontil's inequality not a concentration inequality because its confidence interval around the sample mean depends on the sample (and hence it cannot be written in the form Hoeffding's inequality is usually presented in)?
If Maurer & Pontil's inequality and/or Anderson's inequality are not concentration inequalities, what would you call them? Is the term "concentration inequality" sufficiently vague that it is up to personal interpretation whether each of these is a concentration inequality?


text:
Q: Display a textbox based on checkbox selected when checkbox list is dynamic using JSF I have a requirement in my project which specifies to display 2 textboxes based on a checkbox is checked. For every check box selected the 2 textboxes are the same. The twist is the check box list is dynamic to accomodate additions in the future. The check box list comes from DB.
How can this be done in JSF?

A: You can use valueChangeListener property of  tag.
      <h:selectManyCheckbox id="" value="#{bean.selectedItems}" valueChangeListener="#{bean.renderTextBox}">
         <f:selectItems value="#{bean.checkBoxList}"/>
      </h:selectManyCheckbox>
<h:inputText value="" rendered="#{bean.render}"/>

Have property called render in your bean.
In valuechange method i.e renderTextBox write following code
public void renderTextBox(event)
{

 if(isInvokeApplicationPhase(event))
{
//change the value of render property to true or false depending on checkbox is checked or not
}

}
public boolean isInvokeApplicationPhase(FacesEvent event){
    if(event.getPhaseId() != PhaseId.INVOKE_APPLICATION){
        event.setPhaseId(PhaseId.INVOKE_APPLICATION);
        event.queue();
        return false;
    }
    return true;
}

And to get checkbox list from database write following method
 public List getcheckBoxList()
{
public List checkBoxList = null
// retrieve list of checkbox from your db(write query here and assign returned list to checkBoxList  variable and return that varaible)
}

getcheckBoxList()  is a getter method. I've bound checkBoxList variable to <f:selectItems> tag

A: You can use javascript to hide and display the input box
 var checkbox=document.getElementById("ID");

        if(checkbox.value== 'null')
            checkbox.style.display = "none";
        else
            checkbox.style.display = "inline";


text:
Q: How does a Python listening socket get setup? When you setup a simple TCP listening socket using the Python 'socket' module, what are the different steps involved doing?
The code I'm talking about looks like this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 50000))
s.listen(1)
conn, addr = s.accept()

The s = ... seems pretty straightforward - you are expressing your intent to create an ipv4 TCP socket, without having done anything yet.
What I'm curious about is this:

*

*What does it mean to bind to a socket, without listening?

*How does limiting the number of unaccepted connections using listen(n) work?

*

*If you have listen(1), you're in the middle of dealing with the first connection you accepted, and a second client tries to connect, is the second client waiting for the SYN-ACK? Or does the 3 way handshake happen, and he's waiting for actual data?

*What happens if a third client tries to connect - does he immediately get a TCP RST?

*Does setting the number of unaccepted connections here set some option in the kernel to indicate how many connections it should accept? Or is this all handled in Python?

*How can you be listening without accepting? What does it mean to accept a connection?

Every article I've come across seems to just assume these steps make sense to everyone, without explaining what exactly it is that each one does. They just use generic terms like

listen() starts listening for connections
bind() binds to a socket
accept() just accepts the connection

Defining a word by using that word in the definition is kind of a dumb way to explain something.

A: it's basically a 1-to-1 from the POSIX c calls and as such I'm including links to the man pages, so that you can read their explanation and corresponding c code:
socket creates a communication endpoint by means of a file-descriptor in the namespace of the address-family you specified but assigns neither address nor port.
bind assigns an address and port to said socket, a port which may be chosen randomly if you request a port for which you do not have the privilige. (like < 1024 for non-root user)
listen makes the specific socket and hence address and port a passive one, meaning that it will accept incoming connections with the accept call. To handle multiple connections one after the other, you get to specify a backlog containing them, connections that arrive while you're handling one get appended. Once the backlog is full, the system will respond as such to those systems with an approach that makes them reconnect by withholding SYN, withholding ACK response etc..
As usual you can find someone explaining the previous to you a lot better.
accept then creates a new non-listening socket associated with a new file descriptor that you then use for communication with said connecting party.
accept also works as a director for your flow of execution, effectively blocking further progress until a connection is actually available in the queue for it to take, like a spinlock. The only way around that is to declare the socket non-blocking in which case it would return immediately with an error.


text:
Q: gmaps4rails validates before validates presence set to true I encountered the following error when I submit an empty address field.
Gmaps4rails::GeocodeInvalidQuery in LocationsController#create
You must provide an address
My Model
class Location < ActiveRecord::Base
  validates :address, :presence => true

  acts_as_gmappable
  def gmaps4rails_address
    address
  end

  def gmaps4rails_infowindow
    "
#{name}
" << "
#{address}
"
  end
end

The question why it never validates the address field presence or not and directly throw error?

A: Fixed in 0.8.7 it will now normally add error to the address field.
Gmaps4rails already checks whether or not the address is empty or nil. It's part of the options described here.
You can, for instance, set your own validation message this way:
acts_as_gmappable :msg => "Errrrrrrror"


text:
Q: nested problems about react usestate and setstate Hi I mimic a project and there is no problem but can not display the ui,I am not sure what kind of problem it is.The object project link:https://codesandbox.io/s/learning-react-color-organizer-2-iytxb?file=/src/StarRating.js
My project link:https://codesandbox.io/s/nervous-flower-xv669?file=/src/App.js
My project has 2 warnings,this first warning is Each child in a list should have a unique "key" prop.  which direct to the app.js:
import React, { useState } from "react";
import Data from "./color-data.json";

import RatingList from "./RatingList";
export default function App() {

   const [colors,setColors]=useState(Data)
   const removeId=id=>{
      const newcolors=colors.filter(color=>color.id !== id);
      setColors(newcolors);
   }

  return (

      {
        <RatingList
          colors={colors}
          onDelete={removeId}

        />
      }

  );
}

the second warning is  Cannot update a component (App) while rendering a different component (ColorRating).which direct to the ColorRating.js:
import React from "react";
import Star from "./Star";
import { AiFillDelete } from "react-icons/ai";
export default function ColorRating({id,
  title,
  color,
  rating,
  onDelete = (f) => f,

}) {

  return (

{title}

        <AiFillDelete onClick={onDelete(id)} />

      {[...Array(5)].map((n, i) => (
        <Star key={i} selected={rating > i} />
      ))}

{rating} of 5 stars

  );
}

A: No, I mean remove the { } curly brackets from the return block.
And also, change this line:
<AiFillDelete onClick={onDelete(id)} />

to this (right now you invoke it's on every rerender):
<AiFillDelete onClick={() => onDelete(id)} />