text:
Q: Opening a file from List View? This is my first question on the site and I am fairy new at how code works. I need to be able to open a file from a list view. I can get the file path to open up my file explorer, but can not get it to directly open the selected file. It gives me an error saying "System.ComponentModel.Win32Exception: 'The system cannot find the file specified" I've checked the file path from my file explorer and the path it pulls from and they both seem to match. Here is an example of what I've written.
Private Sub ListView1_Function(sender As Object, e As EventArgs) Handles ListView1.ItemSelectionChanged
    If Not ListView1.SelectedItems.Item(0).Text = "" Then
        For Each ListViewItemVar As ListViewItem In ListView1.Items
            Dim filePath As String = $"C:\Users\{My.User.Name.Split("\").ElementAt(1)}\S & J Tube Inc\Files_Storage - Documents\Shipping Wizard\"
            Dim selectedFile As String = ListViewItemVar.Text
            If ListViewItemVar.Selected = True Then
                If MessageBox.Show("You are about to open " & filePath & ".  Are you sure?", "Open File", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = DialogResult.Yes Then
                Process.Start(filePath + selectedFile)
                ElseIf DialogResult.No Then
                    MsgBox("You decided not to open the file.")
                End If
            End If
        Next
    End If
End Sub

A: You have to use ListView1_ItemActivate
1.Create a project with Form with ListView1 and Label1 controls on it
2.Replace yourName in dirInfo with your name from Users\eee\Documents
And all the code you need is :
Imports System.IO
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'CreateHeadersAndFillListView
    ListView1.View = View.Details
    ListView1.Columns.Add("Filename")
    ListView1.Columns.Add("Size")
    ListView1.Columns.Add("Last accessed")

    Dim dirInfo As New DirectoryInfo("C:\Users\yourName\Documents")
    Dim fileInfo As FileInfo

    Dim lvi As ListViewItem
    Dim lvsi As ListViewItem.ListViewSubItem

    For Each fileInfo In dirInfo.GetFiles("*.*")
        lvi = New ListViewItem With {
            .Text = fileInfo.Name,
            .ImageIndex = 1,
            .Tag = fileInfo.FullName
            }

        lvsi = New ListViewItem.ListViewSubItem With {
            .Text = fileInfo.Length.ToString()
            }

        lvi.SubItems.Add(lvsi)

        lvsi = New ListViewItem.ListViewSubItem With {
            .Text = fileInfo.LastAccessTime.ToString()
            }

        lvi.SubItems.Add(lvsi)

        ListView1.Items.Add(lvi)
    Next

    'after populating the list this will size columns to the width of column data
    ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
    Label1.Text = "C:\Users\yourName\Documents" + Environment.NewLine + " (Double click to open file !)"

    AddHandler ListView1.ItemActivate, AddressOf ListView1_ItemActivate
End Sub

Private Sub ListView1_ItemActivate(sender As Object, e As System.EventArgs)
    Dim filename As String = ListView1.SelectedItems(0).Tag.ToString()

    Try
        Process.Start(filename)
    Catch
        Return
    End Try
End Sub


text:
Q: python reading byte by byte from bin file takes too long i am trying to read the bytes from a bin file with the following code:
with open("filedata.bin","rb") as file:
   data = file.read()
   for byte in data:
         print byte

this works fine but the issue is that it takes too long (about 4 minutes). The goal is to read any byte of the bin file and send them over a serial interface.
My file is 101 kByte. Until now i didn't send any data over the serial interface. So this can not be the problem. I verify the rate over the python shell with the "print byte". It prints me the first byte to the last byte.
Does someone has an idea how i could read the bytes more quickly?

A: when using file.read() without any arguments, you read the entire file into memory at once. This is often slow.
To speed this up, you will want to read the file a few bytes at a time.
You can do this is by specifying how many bytes you want to read, for example:
with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte:
        # do something with the byte
        byte = f.read(1)

A more advanced method to do this is to use the iter function:
for i in iter(lambda x: f.read(1), b""):
    # do something with the byte

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is a $TEM_{900}$ cavity radiation mode? I am reading a paper by Serge Haroche stating the cavity they use sustains a Gaussian mode of the e.m. field called $TEM_{900}$. I understand what Gaussian means. I found this explaining what TEM means, but if I am working in a cavity, what is the "direction of propagation"? And above all, why three indices instead of two?

A: The solutions for a electric field in a perfectly conductive cylindrical cavity separate into the form
$$ E(r,\phi,z) = R(r)\Phi(\phi)Z(z)\quad ,$$
and quantize in each of the coordinate directions (periodic boundary conditions on $\phi$).
Likewise of the magnetic field.
The "T" in "TEM" is "transverse, which means that the intensity of the two fields must have the same dependence on the coordinates.
Accordingly we can label the modes with a set of three integers.
The thing I can't recall off the top of my head is the numbering scheme. Is it $(\text{radial},\text{angular},\text{longitudinal})$ or $(\text{longitudinal},\text{radial},\text{angular})$ which matters in your case. There may be a hint in the text.

A: I know this is very old, but here's an explanation anyways:
There are three indexes and the first one indicates the number of anti-nodes along the cavity direction (k vector of the field). In the specific paper that you showed the fields with frequencies of the order of 50 Ghz, which is equivalent to wavelengths of 6 mm. The cavity have 27 mm between the mirrors, fitting 4.5 wavelengths inside, that is, 9 anti-nodes.
The two other indexes indicates the mode pattern as usual, in this case $TEM_{00}$ indicates a Gaussian form.


text:
Q: Open two dropdowns with the same function in ReactJS I have two dropdown menus, one to choose the columns of my Table and another one to choose a filter for this column.
Actually I have two functions to open both of dropdowns (one function per dropdown) and I would like to have just one function for both of them.
It maybe simple, but I don't know how to do it.. if someone had the solution, it would be great.
My state:
const [anchorEl, setAnchorEl] = React.useState({
  column: null,
  filter: null
});

The two functions for the two dropdowns:
const handleClickDropdownColumn = (event) => {
  setAnchorEl({
    column: event.currentTarget,
  });
};
const handleClickDropdownFilter = (event) => {
  setAnchorEl({
    filter: event.currentTarget,
  });
};

And the two buttons for open the two dropdowns:
<Button
  variant="contained"
  size="small"
  aria-controls="simple-menu"
  aria-haspopup="true"
  onClick={handleClickDropdownColumn}
  endIcon={<ArrowDropDownIcon/>}
>
  {currentColumn}
</Button>

<IconButton onClick={handleClickDropdownFilter}>
  {currentFilter}
</IconButton>

A: Method 1: Pass in your name as second argument to your function handler
You can write your onClick props as the following,
<Button
  variant="contained"
  size="small"
  aria-controls="simple-menu"
  aria-haspopup="true"
  onClick={e => handleClickDropdown(e, 'column')}
  endIcon={<ArrowDropDownIcon/>}
>
  {currentColumn}
</Button>

<IconButton onClick={e => handleClickDropdown(e, 'filter')}>
  {currentFilter}
</IconButton>

Then in your handler
const handleClickDropdown = (event, name) => {
    setAnchorEl({
        [name]: event.currentTarget,
    });
};

Method 2: Function that returns a function handler
<Button
  variant="contained"
  size="small"
  aria-controls="simple-menu"
  aria-haspopup="true"
  onClick={handleClickDropdown('column')}
  endIcon={<ArrowDropDownIcon/>}
>
  {currentColumn}
</Button>

<IconButton onClick={handleClickDropdown('filter')}>
  {currentFilter}
</IconButton>

In your handler, you call a function with name and returns a handler for that property.
const handleClickDropdown = (name) => (event) => {
    setAnchorEl({
        [name]: event.currentTarget,
    });
};

A: You could set your handler function to this and use it for both buttons.
const handleClickDropdown = (event, type) => {
  if(type in anchorEl){
    setAnchorEl({
      ...anchorEl,
      [type]: event.currentTarget,
      })
  }
}


text:
Q: Analyze rails app I am wondering if there is a tool that will tell how many lines of code are present in my Rails app, what are controllers and models present as well?

A: Try rake stats. It's built into Rails.


text:
Q: Shiro multiple principals must be unique I am using shiro v1.2.2 for authentication in a web program. I have 2 principals for each user, a primary value and some other value and so I am using the SimplePrincipalCollection to store these 2 principals.
The problem I am having is that if the 2 principals are the same value (although they represent 2 distinct concepts in my system), the SimplePrincipalCollection only stores 1 value and so calls to SecurityUtils.getSubject().getPrincipals() only has 1 value.
My realm doGetAuthenticationInfo implementation looks something like this:
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
    ...
    List<Integer> principalList = new ArrayList<>();
    principalList.add(primaryPrincipal); // This is the primary principal so should be first in the list
    principalList.add(secondaryPrincipal);

    PrincipalCollection principals = new SimplePrincipalCollection(principalList, getName());
    AuthenticationInfo authInfo = new SimpleAuthenticationInfo(principals, credentials);
    return authInfo;
}

So if primaryPrincipal and secondaryPrincipal are the same value, the SimplePrincipalCollection only stores 1 value. I have verified this with a simple test:
@Test
public void testMultiplePrincipal() {
    final String realmName = "TestRealm";

    List<Integer> principalList = new ArrayList<>();
    principalList.add(1);
    principalList.add(2);

    PrincipalCollection principals = new SimplePrincipalCollection(principalList, realmName);
    assertThat((List<?>) principals.asList(), hasSize(2)); // This passes

    principalList = new ArrayList<>();
    principalList.add(1);
    principalList.add(1);

    principals = new SimplePrincipalCollection(principalList, realmName);
    assertThat((List<?>) principals.asList(), hasSize(2)); // This fails because size = 1
}

Upon debugging, I found that this behaviour is caused by SimplePrincipalCollection using a LinkedHashSet to store the principals.
I know that I can define my own custom principal object and use the constructor SimpleAuthenticationInfo(Object principal, Object credentials, String realmName) but then I would have to change the code that calls SecurityUtils.getSubject().getPrincipal().
Am I using the SimplePrincipalCollection the wrong way and is there a way I can get around this unique principal problem without defining a custom principal?


text:
Q: Get data from website <span itemprop="streetAddress">

    **94 Grand St**

</span>

how to get this data through getelementby method in excel vba
I have tried getelementbyid, getelementbyname etc. but nothing is working
Option Explicit

Sub find()
'Uses late binding, or add reference to Microsoft HTML Object Library
'  and change variable Types to use intellisense
Dim ie As Object 'InternetExplorer.Application
Dim html As Object 'HTMLDocument
Dim Listings As Object 'IHTMLElementCollection
Dim l As Object 'IHTMLElement
Dim r As Long
    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = False
        .Navigate "http://www.yelp.com/biz/if-boutique-new-york#query:boutique"
        ' Don't show window
        'Wait until IE is done loading page
        Do While .readyState <> 4
            Application.StatusBar = "Downloading information, Please wait..."
            DoEvents
        Loop
        Set html = .Document
    End With
    Set Listings = html.getElementsByTagName("span") ' ## returns the list
    MsgBox (Listings(0))
    For Each l In Listings
        '## make sure this list item looks like the listings Div Class:
        '   then, build the string to put in your cell
        Range("A1").Offset(r, 0).Value = l.innerText
            r = r + 1
    Next

Set html = Nothing
Set ie = Nothing
End Sub

The above program is used by me to get the innerText value inside the span tag... but its not working

A: For the single result you are looking for in detail you want to use these two lines in your code (there is only 1 listing at the detailed level)
Adapt your IE code
  Set Listings = html.getElementbyid("bizInfoBody") ' ## returns the list
  Range("A1").Offset(r, 0).Value = Listings.innerText

with XMLHTTP
Sub GetTxt()
Dim objXmlHTTP As Object
Dim objHtmlDoc As Object
Dim objHtmlBody As Object
Dim objTbl As Object

Dim strResponse As String
Dim strSite As String

Set objHtmlDoc = CreateObject("htmlfile")
Set objHtmlBody = objHtmlDoc.body

Set objXmlHTTP = CreateObject("MSXML2.XMLHTTP")
strSite = "http://www.yelp.com/biz/if-boutique-new-york"

With objXmlHTTP
    .Open "GET", strSite, False
    .Send
    If .Status = 200 Then
    strResponse = .responseText
    objHtmlBody.innerHTML = objXmlHTTP.responseText
    Set objTbl = objHtmlBody.Document.getElementbyid("bizInfoBody")
    MsgBox objTbl.innerText
    End If
End With

End Sub


text:
Q: ActionBarSherlock: open submenu with menu button I'm using ActionBarSherlock-4.1.0-0 and I would like to open my submenu in the Actionbar with the hardware menu button. I'm planing an update and in my old version I used the "normal" menu. I'd like to help users to get used to the new design.
I got the submenu and the main-menu:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater i = getSupportMenuInflater();
    i.inflate(R.menu.main_menu, menu);
    SubMenu subMenu = (SubMenu) menu.findItem(R.id.actionbar_submenu);
    Menu mainMenu = menu;
    return super.onCreateOptionsMenu(menu);
}

and I got a listener to the hardware menu button:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(event.getAction() == KeyEvent.ACTION_DOWN){
        switch(keyCode) {
        case KeyEvent.KEYCODE_MENU:
            // TODO: expand submenu from actionbar
            return true;

        }
    }
    return super.onKeyDown(keyCode, event);
}

I couldn't find a method or anything else to call.

A: This is how I solved the issue
mainMenu.performIdentifierAction(id_of_menu_item, 0);

So in your case I would imagine it would be like this
private Menu mainMenu; // local variable for menu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater i = getSupportMenuInflater();
    i.inflate(R.menu.main_menu, menu);
    SubMenu subMenu = (SubMenu) menu.findItem(R.id.actionbar_submenu);
    mainMenu = menu; // store the menu in an local variable
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(event.getAction() == KeyEvent.ACTION_DOWN){
        switch(keyCode) {
        case KeyEvent.KEYCODE_MENU:
            SubMenu subMenu = (SubMenu) mainMenu.findItem(R.id.actionbar_submenu);
            mainMenu.performIdentifierAction(subMenu.getItem().getItemId(), 0);

            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

In short:

*

*Store the menu in a local variable

*Use that variable to look for the sub menu

*Use that variable to call the performIdentifierAction method

Hopefully this will work.

A: I always got a NullPointerException with the solution of Fredrik Sundmyhr, then I changed a few things and it worked. Here's my solution:
@Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_UP){
            switch(keyCode)
            {
            case KeyEvent.KEYCODE_MENU:
                SubMenu subMenu = mainMenu.getItem(2).getSubMenu();
                mainMenu.performIdentifierAction(subMenu.getItem().getItemId(), 0);

                return true;
            }
        }
        return super.onKeyUp(keyCode, event);
    }

A: I try this solution from Frederik with android actionbar and I run into the problem that the submenu opens and closes immediately. Changing to onKeyUp solved this issue.
Here is my code:
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_MENU){
        if (event.getAction() == KeyEvent.ACTION_DOWN && optionsMenu != null && optionsMenu.findItem(R.id.sub_menu) != null)
        {
            Log.i(TAG, "performIdentifierAction");
            optionsMenu.performIdentifierAction(R.id.sub_menu, 0);
            return true;
        }
    }
    return super.onKeyUp(keyCode, event);
}

I do check if optionsMenu != null && optionsMenu.findItem(R.id.sub_menu) != null because of compatibility issues with older Android versions without actionbar. This isn't nessesary if you use ActionBarSherlock for all versions.


text:
Q: How can i optimize the code for duplicate elements removal? I have tried to remove the duplicate elements from an array
using c language, here I'am using 3 for loop to remove the duplicate elements.
How can this  optimize the code?
any other simple method to remove the duplicate elements?
Thanks.
#include <stdio.h>

#define MAX_SIZE 100 // Maximum size of the array

int main()
{
    int arr[MAX_SIZE];
    int size;
    int i, j, k;

    printf("Enter size of the array : ");
    scanf("%d", &size);

    printf("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    for(i=0; i<size; i++)
    {
        for(j=i+1; j<size; j++)
        {

            if(arr[i] == arr[j])
            {

                for(k=j; k<size; k++)
                {
                    arr[k] = arr[k + 1];
                }

                size--;

                j--;
            }
        }
    }

    printf("\nArray elements after deleting duplicates : ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", arr[i]);
    }

    return 0;
}


text:
Q: How, to interpret the geometry of a 2nd degree polynomial equation, which contains an elliptic quadratic form and whose constant coefficient is zero? $$
\mathbf x =    \begin{bmatrix}
    x & y
    \end{bmatrix}^\mathsf T
$$
$$
Q = \begin{bmatrix}
    A & B/2 \\
    B/2 & C
    \end{bmatrix}
$$
Eigendecomposition of $Q$:
$
~Q = \begin{bmatrix}
    \mathbf e_1 & \mathbf e_2
    \end{bmatrix}^\mathsf T \begin{bmatrix}
    \lambda_1 & 0 \\
    0 & \lambda_2
    \end{bmatrix} \begin{bmatrix}
    \mathbf e_1 & \mathbf e_2
    \end{bmatrix}
$
$$
0 \lt \lambda_1 \le \lambda_2
$$
$$
\mathbf e_1 = \begin{bmatrix}
    e_1 &  e_2
    \end{bmatrix}^\mathsf T
$$
$$
\alpha = \arctan \frac{e_2}{e_1}
$$
$$
\mathbf T =    \begin{bmatrix}
    h & k
    \end{bmatrix}^\mathsf T
$$
$$
\mathbf x^\mathsf T Q \mathbf x + \mathbf T^\mathsf T \mathbf x = 1 \label{a}\tag{1}
$$
Equation (1) is a 2nd degree polynomial equation whose geometry I can interpret and for which I can get a definite parameterization. If I am not mistaken, the ellipse defined in (1) is parameterized as:
$$
\mathcal E = \begin{bmatrix}
    \cos \alpha & \sin \alpha \\
    -\sin \alpha & \cos \alpha
    \end{bmatrix} \begin{bmatrix}
    \frac {1}{\sqrt \lambda_1} \cos t \\ \frac {1}{\sqrt \lambda_2} \sin t
    \end{bmatrix} + \begin{bmatrix}
    h \\ k
    \end{bmatrix} ~;~ 0 \le t \lt 2 \pi
$$
Now let's consider another second degree polynomial equation.
$$
\mathbf x^\mathsf T Q \mathbf x + \mathbf T^\mathsf T \mathbf x = 0 \label{b}\tag{2}
$$
I can neither get a parameterization for, nor can I interpret the geometry of the curve defined by equation (2). Here is the question: How does the curve defined in equation (2) get parameterized and/or what are the geometric properties of that curve?


text:
Q: Backbone: how the trigger function works I'm trying to learn Backbone by looking at an app that someone I know made together with the backbone documentation.  The app has a Bucket model and a Company model (i.e. you put companies in the bucket).  There's one thing in this bit that I'm unclear about, namely, how it uses the trigger method.
Backbone documentation has this to say about trigger:
trigger object.trigger(event, [*args])

Trigger callbacks for the given event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks.

In the code I'm looking at, trigger is called like this:
this.trigger("add:companies", Companies.get(companyId));

Two questions:

*

*The event I assume is adding a company, but at what point in the code below does that actually happen? Is it when this.set({ "companies": arr }, { silent: true }); is run or when this.save(); is run (or something else)?

*If Companies.get(companyId) is the optional argument, what function is it actually passed to?
Excerpt from original code
window.Bucket = Backbone.Model.extend({
  defaults: function() {
    return {
      companies: []
    };
  },

  addCompany: function(companyId) {
    var arr = this.get("companies");
    arr.push(companyId);
    this.set({ "companies": arr }, { silent: true });
    this.save();
    this.trigger("add:companies", Companies.get(companyId));
  },

  // ...

A: The companies property of the bucket is being updated in the addCompany method you describe. An annotated version of your example shows what's taking place:
  // 1. get array of companies currently included in the bucket:
  var arr = this.get("companies");

  // 2. add a company to the array
  arr.push(companyId);

  // 3. replace the bucket's company list with the array,
  //    suppressing validation and events:
  this.set({"companies": arr}, {silent: true});

  // 4. save the bucket:
  this.save();

trigger isn't actually affecting the model--it's just a way of letting other pieces of the application know that the company has been added. You could turn around and catch it somewhere else using on with the bucket model:
var bucket = new window.Bucket();

// do stuff

bucket.on('add:companies', function(company) {
  alert('a new company has been added to the bucket.');
});


text:
Q: Find certain information within array So I'm trying to set where the user adds one line of text containing the Name(Last, First Middle) as well as id number, ssn, and birthday. Example:  Doe, John Hank        12345678901          123-45-6789    Jan. 01, 1801
I first split it by using " " to break it up into the array. I then need to find which array value has the ssn in it. Because the name can change from Sr, Jr, no middle name, etc. the array value can't be static at like ssn = eachpart(3). Is there a way to search each piece of the array with the criteria for a mask of a ssn?

A: You could create and array using Split:
Parts = Split(Input, " ")

Then loop this checking for
IsNumeric(Parts(i))

That found will be the ID.
The next will be the SSN.


text:
Q: Convert to binary for VHDL compiler I have a lot of data points that need to be converted to binary format.
For example:
if clk_cntr = (STAR +3400) then  --6.8us

    DAC <= "01110100011111";   --7455  2.8v

end if;

DAC is a std_logic_vector and must be in binary mode from my understanding.
I have a stack of these if-thens. Currently, I have to "look up" the value and convert to binary. I am new to VHDL and I am looking for a way to allow the compiler to convert my std_logic_vector DAC value from readable to binary. Something like...
if clk_cntr = (STAR +3400) then  --6.8us

    DAC <= binary(14)[7455];   --7455  2.8v

end if;

I have looked in all of the incorrect places on the web and in a few books I have but have not been successful.
How do I get the compiler to convert to 14 bit binary for VHDL to understand?


text:
Q: Knockout Validation not working with a DatePicker bindingHandler So I am using Knockout Validation to validate my viewmodel and a custom knockout datepicker bindingHandler to attach a jQuery-UI datepicker to dynamically added items in my observableArray.
It seems my bindingHandler is destroying or breaking the validation rules on that field. Neither of the validation rules for the Start or End date seem to be getting enforced.
JSFiddle Link of my code
HTML code:
<form>
    Add New Medication

    <h6 data-bind="visible: patientMeds().length < 1">No medications entered.

 0">

                Med
                From
                To

                    <input class="form-control" data-bind="value: MedicationID" />

                    <input class="form-control" data-bind="datepicker: StartDate, datepickerOptions: { changeMonth: true, changeYear: true, showButtonPanel: true }" />

                    <input class="form-control" data-bind="datepicker: DiscontinuedDate, datepickerOptions: { changeMonth: true, changeYear: true, showButtonPanel: true }" />

                    <button class="btn btn-default" data-bind="click: $parent.removeMed">Delete</button>

</form>

Javascript / ViewModel code:
ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var options = allBindingsAccessor().datepickerOptions || {};

        $(element).datepicker(options);

        //handle the field changing
        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            observable($(element).datepicker("getDate"));
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).datepicker("destroy");
        });

    }
};

function PatientMedication(p) {
    var self = this;
    p = p || {};

    self.MedicationID = ko.observable(p.MedicationID || 1)
        .extend({
        required: {
            params: true,
            message: 'Please enter a medication'
        },
        number: true
    });
    self.StartDate = ko.observable(p.StartDate).extend({
        required: {
            params: true,
            message: 'Please enter a date'
        },
        date: true
    });

    self.DiscontinuedDate = ko.observable(p.DiscontinuedDate || '').extend({
        required: {
            params: true,
            message: 'Please enter a date'
        },
        date: true
    });
}

function MedicationViewModel() {
    var self = this;

    self.patientMeds = ko.observableArray([]);

    self.addMed = function () {
        self.patientMeds.unshift(new PatientMedication());
    };

    self.removeMed = function (med) {
        self.patientMeds.remove(med)
    };
};

var medvm = new MedicationViewModel();
ko.applyBindings(medvm);

A: The validation plugin only hooks into the value, checked, textinput and selectedOptions bindings.
If you want to make your custom binding trigger the validations you need to call the validation.makeBindingHandlerValidatable method of the plugin and pass in the name of your custom binding:
ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        //...
    }
};
ko.validation.makeBindingHandlerValidatable('datepicker');

Demo JSFiddle.


text:
Q: How can I apply where clause to the existing IEnumerable for incremental filtering the record I am trying to filter the record by giving where clause conditionally from  controller. I have the list of records as IEnumerable list . How can I give where condition to the IEnumerable.
Here is my code
    public IActionResult UniformIssueList(UniformDeliveryVM uniformDeliveryVM)
{
     var issuesList = _unitOfWork.UniformReceiptRepo.GetUniformDeliveryList(uniformDeliveryVM.FromDate, uniformDeliveryVM.ToDate);
         if (uniformDeliveryVM.DepotNo>=0)
         {
           issuesList  = issuesList.Where(d => d.DepotNo == uniformDeliveryVM.DepotNo
         }
     if (uniformDeliveryVM.DepartmentNo >=0)
         {
           issuesList  = issuesList.Where(d => d.DepartmentNo == uniformDeliveryVM.DepartmentNo
         }
          if (uniformDeliveryVM.EmployeeId >=0)
         {
           issuesList  = issuesList.Where(d => d.EmployeeId == uniformDeliveryVM.EmployeeId
         }
}

A: In fact, your idea is correct, you only need to add Tolist() after the Where condition.
like this:
if (uniformDeliveryVM.DepotNo >= 0)
            {
                issuesList = issuesList.Where(d => d.DepotNo == uniformDeliveryVM.DepotNo).ToList();
            };
            if (uniformDeliveryVM.DepartmentNo >= 0)
            {
                issuesList = issuesList.Where(d => d.DepartmentNo == uniformDeliveryVM.DepartmentNo).ToList();
            }
            if (uniformDeliveryVM.EmployeeId >= 0)
            {
                issuesList = issuesList.Where(d => d.EmployeeId == uniformDeliveryVM.EmployeeId).ToList();
            }

Hope this can help you.


text:
Q: PHP cURL request headers isn't working with a global variable I've set a global variable to equal an access token, and when I print_($session_id) the token is visible. What I'd like to do is pass that variable into my CURLOPT_HTTPHEADER, and have it equal to "Session" in the function get_field_data_id() below:
function get_session_id() {
global $session_id;

$curl = curl_init();
$session_url = "/auth";

curl_setopt_array($curl, array(
    CURLOPT_URL => $session_url ,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
        "Accept: application/json",
        "username: USER",
        "password: PASS",
        "authorizationkey: KEY"
    ),
));

$response = curl_exec($curl);

curl_close($curl);

$session_id = $response;

} add_filter( 'gform_after_submission_4', 'get_session_id' );

function get_field_data_id() {
global $session_id;

$curl = curl_init();
$file_url = "URL";

curl_setopt_array($curl, array(
    CURLOPT_URL => $file_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
        "Accept: application/json",
        "Session: {$session_id}"
    ),
));

$response = curl_exec($curl);

curl_close($curl);

echo $response;}

However when I run this function, I get an error message that the session ID is invalid. What am I missing?
{"Message":"Invalid Authorization. Session ID is invalid. "}


text:
Q: Why I'm not getting full width in vertical mobile? I'm trying to design a web with Bootstrap and Adobe dreamweaver and it works fine in desktop, horizontal view in mobiles and other views but whenever I choose to display it on vertical smartphones, the containers don't use the full width. Some code:
HTML

¿Qué servicios ofrecemos?

Diseños web responsive

Nos encargamos de que tu sitio web luzca profesional y se adapte por igual a todos los dispositivos en los que se visualice.

Traducción de tu sitio web

Traducimos tu sitio web a Español, Inglés y Polaco. Consulta nuestras tarifas de traducción.

Personalización

Diseñamos los elementos gráficos de tu web para que tenga su propia personalidad.

I expect this to show as:
Column 1 | Column 2 | Column 3 in desktop
and one above another in mobile. I would like to keep the original 1|2|3 format but I don't know who. Thing is it works as expected but doesn't get the full width. This is only an example, the problem occurs in the whole site.
CSS
html{
    scroll-behavior: smooth;
}

body {
  padding-top: 56px;
}

.bg-image-full {
  background: no-repeat center center scroll;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
}

.custom-control-input:checked~.custom-control-label::before {
    color: white !important;
    background-color: green !important;
}

Some images of the problem
Desktop
Mobile
It's truly weird since I respected the grid documentation, is the only thing I suspected to be causing this and it's not the case. I'm just trying to learn, don't be too harsh if I missed something.
Edit: I know I'm using 'br' and independent style tags, I use them at first and then use CSS, is just for the beginning, because I sometimes I don't want to be switching tabs lol.
Thanks in advance!


text:
Q: How cfs s3 uploading works I've previously used slingshot and the process it pretty simple: we upload the image and it returns the uploaded url of the s3 bucket.
Now I want to resize the image and need to perform some operations on the image, so I switched to the cfs:s3 package. But when I try to upload the image, it returns some record with no url and in the db it stores it as:
{
    "_id" : "Rwa7Xo65pv6cAP2aY",
    "copies" : {
        "thumbs" : {
            "name" : "306032-facebook.jpg",
            "type" : "image/jpeg",
            "size" : 4262,
            "key" : "thumbs/Rwa7Xo65pv6cAP2aY-306032-facebook.jpg",
            "updatedAt" : ISODate("2015-02-14T06:44:04.476Z"),
            "createdAt" : ISODate("2015-02-14T06:44:04.476Z")
        }
    },
    "original" : {
        "name" : "306032-facebook.jpg",
        "updatedAt" : ISODate("2015-01-30T09:48:58.000Z"),
        "size" : 4262,
        "type" : "image/jpeg"
    },
    "uploadedAt" : ISODate("2015-02-14T06:43:59.062Z")
}

*

*How can I get the URL from this record? (I suppose it is key in thumbs) Is it linking my server url to amazon s3 url?

*What are the advantages of this method over slingshot?

*How do I know the upload is completed? I can't figure out any ui helpers, are there any reactive helpers to track download percentage?

A: *

*The URL will be your s3 end point (e.g. s3-us-west-2.amazonaws.com/) + the key. I suggest you to create a constant for your end point and a register helper to return the URL.

Something like this
Template.registerHelper('THUMBS_URL', function(key){
  return S3_ENDPOINT + key;
})

*I haven't used slingshot yet so can't comment on it.

*There is a isUploaded helper function in collectionFS.
https://github.com/CollectionFS/Meteor-CollectionFS#isuploaded


text:
Q: Put trivariate PDF in terms of bivariate PDFs Let there be the random variables $X$, $Y$, and $Z$. Let all the bivariate PDFs $f_{X, Y}$, $f_{X, Z}$, and $f_{Y, Z}$ be known.
Can we write the unknown trivariate PDF $f_{X, Y, Z}$ in terms of the known bivariate PDFs?

A: Here is an example, obtained by tweaking a 2D counterexample: Let $(X,Y,Z)$ be such that
$$
f_{X,Y,Z}(x,y,z)=
\begin{cases}
2 \phi(x)\phi(y)\phi(z) & xyz>0\\
0 & \text{otherwise}
\end{cases}
$$
where $\phi$ is the standard 1D Gaussian pdf.  Then the bivariates $f_{X,Y}, f_{Y,Z}, f_{Z,X}$ are all standard 2D Gaussians, but of course $(X,Y,Z)$ is not Gaussian.  Now both the standard 3D Gaussian and this $f$ give the same distribution of bivariates.

A: Let $f(x,y,z)=1$ when $x,y,z\in [0,1]$, and be zero otherwise. Then $f_{X,Y}$ is uniform on the unit square, and same for $f_{X,Z}$ and $f_{Y,Z}$. On the other hand, let
$$
g(x,y,z)=1+\sin(2\pi (x+y+z)) \hspace{1cm}\text{for }x,y,z\in [0,1]
$$
Then $g_{X,Y},g_{X,Z}$ and $g_{Y,Z}$ are also uniform on the unit square.


text:
Q: Illegal Invocation instantiating BS Modal I'm trying to call a bootstrap Modal in angular via the component rather than using it's HTML attribute. I'm getting an error (i.e. illegal invocation).
Component:
@ViewChild('myModal') div:any;

ngAfterViewInit() {let bs = new bootstrap.Modal(this.div);}

HTML

...

A: You need to use the service instead creating an instance of it. Make these changes to the code :
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
...
...
@ViewChild('myModal') div:any;

constructor(private modalService: NgbModal )

ngAfterViewInit() {
     // make sure you get the instance of the child.
     this.modalService.open(this.div);
}


text:
Q: "'sockaddr_in' undeclared (first use in this function)" error despite including the requisite headers #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <stdlib.h>
#include <memory.h>
#include <ifaddrs.h>#include <net/if.h>
#include <stdarg.h>

#define BACKLOG 10

void * get_in_addr(struct sockaddr *sa){
    if(sa->sa_family == AF_INET){
            return &((sockaddr_in *)sa)->sin_addr;
    }
    else if(sa->sa_family == AF_INET6){
            return &((sockaddr_in6 *)sa)->sin6_addr;
    }
}

I am using the sockaddr_in struct in my code to chekc whether an incoming connection is an IPv4 or an IPV6 address. I get the error "'sockaddr_in' undeclared (first use in this function)" here despite including the netinet/in.h header in my code. Is there something that I am not seeing here?

A: sockaddr_in  is not typedef, so try using it with struct like following
(struct sockaddr_in *)


text: Q: Distribute $n$ identical presents to $k$ children so that each child receives at most $3$ presents I know that to distribute n identical presents to k children so that each child gets at least one is $\binom{n-1}{k-1}$ and that to distribute n presents to $k$ children is $\binom{n+k-1}{k-1}$, and I understand why. In order for each child to get at least $2$ presents is $\binom{n-k-1}{k-1}$. However I have no clue how to make it so a child doesn't receive more than a certain number. Any ideas? Thanks


text:
Q: Using swift style access with rclone and non-classic OCI object storage Can anyone comment on if it should be possible to use rclone's swift support to access buckets in OCI object storage (new OCI, not classic).
I'm interested in it because S3 compatibility mode is limited to a single designated compartment and I'd like to be able to use rclone with any bucket in my tenancy.
I know that for public buckets there is still a swift style URL. The 3 functional URLs styles seem to be:

*

*Native: https://objectstorage.{region}.oraclecloud.com/n/{object-storage-namespace}/b/{bucket}/o/{filename}

*Swift: https://swiftobjectstorage.{region}.oraclecloud.com/v1/{object-storage-namespace}/{bucket}/{filename}

*S3: https://{object-storage-namespace}.compat.objectstorage..oraclecloud.com/{bucket}/{filename}

https://docs.cloud.oracle.com/en-us/iaas/Content/Identity/Tasks/managingcredentials.htm talks a little bit about Swift password (Auth Tokens) and you can create one in the console.
But I can't find anything about what the auth URL would be for the non-classic version of object storage. And storage_url with a auth_token doesn't seem to work either.
Using -vvvv doesn't show anything more than 401 Unauthorized.

A:
I'm interested in it because S3 compatibility mode is limited to a single designated compartment and I'd like to be able to use rclone with any bucket in my tenancy.

The designated compartment only controls where buckets created via that protocol (S3 or Swift) are placed. The designated compartment does not affect authorization. Authorization is controlled by the relevant IAM policies.

But I can't find anything about what the auth URL would be for the non-classic version of object storage. And storage_url with a auth_token doesn't seem to work either.

The new/current OCI Object Storage does not support auth URLs. You must use HTTP basic-style auth with Swift on OCI. It does not seem that rclone supports HTTP basic auth with swift directly (it is possible to create the basic auth header yourself and have rclone send it).
All that said, using rclone with s3 is the best approach for OCI Object Storage. Ensure you set the "region" option to the correct region name like "us-phoenix-1" and you should be good.
Thanks!


text:
Q: WebRTC record both myself and caller I am trying to figure how would I record one on one video chat using webrtc and place it locally on receivers computer?
I am well aware that the server doesn't know anything about our call, but the client does so I think it would be possible to record both users on the client side.
Any pointers where I should go too look for info? and is this even possible?

A: You may want to checkout MediaRecorder
Personally I did not record a webRTC Chat yet, but I recorded my webcam with that. It should work for the stream as well.


text:
Q: How can I move XML elements with PHP's SimpleXML? How can I move an xml element elsewhere in a document? So I have this:
<outer>
    <foo>
        <child name="a"/>
        <child name="b"/>
        <child name="c"/>
    </foo>
    <bar />
</outer>

and want to end up with:
<outer>
    <foo />
    <bar>
        <child name="a"/>
        <child name="b"/>
        <child name="c"/>
    </bar>
</outer>

Using PHP's simpleXML.
Is there a function I'm missing (appendChild-like)?

A: You could make a recusrive function that clones the attributes and children. There is no other way to move the children with SimpleXML

A: class ExSimpleXMLElement extends SimpleXMLElement {
    //ajoute un object à un autre
    function sxml_append(ExSimpleXMLElement $to, ExSimpleXMLElement $from) {
        $toDom = dom_import_simplexml($to);
        $fromDom = dom_import_simplexml($from);
        $toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));
    }
}

    $customerXML = <<<XML
    <customer>
        <address_billing>
            <address_book_id>10</address_book_id>
            <customers_id>20</customers_id>
            <telephone>0120524152</telephone>
            <entry_country_id>73</entry_country_id>
        </address_billing>
        <countries>
            <countries_id>73</countries_id>
            <countries_name>France</countries_name>
            <countries_iso_code_2>FR</countries_iso_code_2>
        </countries>
    </customer>
    XML;

$customer = simplexml_load_string($customerXML, "ExSimpleXMLElement");
$customer->sxml_append($customer->address_billing, $customer->countries);

echo $customer->asXML();

    <?xml version="1.0"?>
    <customer>
        <address_billing>
            <address_book_id>10</address_book_id>
            <customers_id>20</customers_id>
            <telephone>0120524152</telephone>
            <entry_country_id>73</entry_country_id>
            <countries>
               <countries_id>73</countries_id>
               <countries_name>France</countries_name>
               <countries_iso_code_2>FR</countries_iso_code_2>
            </countries>
        </address_billing>
    </customer>


text: Q: JBoss AS 7 Module classloader WEB-INF lib I'm trying to configure my web application to jboss 7.1.1.Final. It turns out that using modules, then there is a moment that a class that is in a class module needs to access a folder that is inside the WEB-INF/lib of my war file. When this happens there is a java.lang.ClassNotFoundException. I think the module classloader can not see classes in my WEB-INF/lib. How could I solve this?


text:
Q: Error 'An object with the same key already exists in the ObjectStateManager' Tengo las siguientes sentencias para Modificar un objeto del Entity Framework que está enlazado a una base de datos de oracle:
        using (BASEntities context = new BASEntities())
            {
        //Este método comprueba que exista en caso de existir modificar
        string RespuestaValidacion = ExisteConcepto(context, ConceptoTo);
             CONCEPTO objConceptoBasico = new  CONCEPTO
               {
                  CODIGOCTO = ConceptoTo.CodigoConcepto,
                  CODIGOENTIDAD = ConceptoTo.CodigoEntidad,
                   demas codigo.....
                };

         if (string.IsNullOrEmpty(RespuestaValidacion))
                {
                    context.CONCEPTO.Add(objConceptoBasico);
                    context.SaveChanges();
                }
                else
                {
                  context.CONCEPTO.Attach(objConceptoBasico);
                 context.CONCEPTO.System.Data.Entity.EntityState.Modified(objConceptoBasico);
                  context.SaveChanges();
                }

el método para Buscar si existe el registro es el siguiente:
   private string ExisteConcepto(BASEntities context, ConceptoTO ConceptoTo)
    {
        try
        {
            var qRegistro = context.SMT_CONCEPTOBASICO.Where(k =>
                                    k.CODIGONEG == ConceptoTo.CodigoNegocio
                                    && k.CODIGOCTO == ConceptoTo.CodigoConcepto
                                    && k.IDAPLICACION == ConceptoTo.IdAplicacion
                                    demas codigo......).FirstOrDefault();

            return qRegistro == null ? "" : qRegistro.ESTADO;
        }
        catch (Exception error)
        {
            throw error;
        }
    }

Y sale el mencionado error:

Error 'An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.'

realice el cambio de entity 5 a entity 6

A: Ese es un error causado por las validaciones de EF.
Para solucionarlo puedes hacer algo como:
try
{
  context.Configuration.ValidateOnSaveEnabled = false;

  context.CONCEPTO.Attach(objConceptoBasico);
  context.Entry(objConceptoBasico).State = EntityState.Deleted;
  context.SaveChanges();
}
finally
{
  context.Configuration.ValidateOnSaveEnabled = true;
}

================== EDICIÓN ======================
El error ocurre porque estas intentando agregar una entidad que ya ha sido agregada de forma implícita al realizar el FirstOrDefault en el método: ExisteConcepto.
Conosco 2 formas para solucionar el mismo:

*

*Puedes en el método: ExisteConcepto retornar el objeto en vez de string y al objeto (si existe) cambiarles las propiedades de forma manual o con AupoMapper (por ejemplo).

Algo como:
private string ExisteConcepto(BASEntities context, ConceptoTO ConceptoTo)
    {
        try
        {
            return context.SMT_CONCEPTOBASICO.Where(k =>
                                    k.CODIGONEG == ConceptoTo.CodigoNegocio
                                    && k.CODIGOCTO == ConceptoTo.CodigoConcepto
                                    && k.IDAPLICACION == ConceptoTo.IdAplicacion
                                    demas codigo......).FirstOrDefault();
        }
        catch (Exception error)
        {
            throw error;
        }
    }

Luego en tu método principal:
...
CONCEPTO concepto = ExisteConcepto(context, ConceptoTo);

if(concepto == null) concepto = new CONCEPTO();
...

Luego proceder a cambiar las propiedades si el concepto existe o a agregarlas si es nuevo:
concepto.CODIGOCTO = ConceptoTo.CodigoConcepto;
...

Esta es la forma que recomiendo de forma personal.

*La segunda forma es hacer un Count en vez de un FirstOrDefault en el método: ExisteConcepto entonces retornaras la cantidad de elementos que coinciden con los criterios del where y en el método principal solo evaluaras en vez de: string.IsNullOrEmpty(RespuestaValidacion) algo como: RespuestaValidacion == 0


text:
Q: Android Studio heap snapshot analyzer - what does "Dominating size" represent? After dumping heap in Android Studio and viewing the created snapshot, there's a field called "dominating size".
What does it stand for?

A: That's the size of that object + everything it keeps alive by direct or indirect references.
I'm not sure about Android Studio, but generally, "dominating" would mean that you only count the objects that are only accessible through your Bitmap objects here -- i.e., if your Bitmap is freed, all of those objects could be freed as well.
In your case, each Bitmap object itself only takes 60 bytes -- but they each have a (separately allocated) pixel buffer of some kind that they're keeping alive.


text:
Q: Unable to read json file and print output user = {}
max_length = 4

while len(user) < max_length:
  name = input("What is your name? ")
  food= input("What is your favourite food?  ")
  user[name]= food
  users = json.dumps(user)

  if name.lower() == 'q' or food.lower()== 'q':
    break

with open('users.json', 'a') as outfile:
    outfile.write(f"{users.title()}\n")

with open('users.json') as outfile:
  user= json.load(outfile) - **the code fails here**

print(user)

The while loop runs a user input with two questions, and the answers are placed in a dictionary that are placed in a dictionary in a json file. I want to read this file and print the output in the terminal but I keep getting an error. I'm not sure how to fix this because everything I've tried isn't working.
This is the error:
Traceback (most recent call last):
  File "main.py", line 53, in <module>
    json.load(outfile)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/json/decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 32 (char 31)

KeyboardInterrupt

A: The main problem is that you are adding data to a JSON file in a non-JSON format. To keep this consistent, I recommend using json.dump for placing the data in the file too.
Edit: when you define the first user, store the data as a dictionary, but inside an array. That way, you can append to it later on. Still, you will need to read and then write the whole array to the outfile. Appending to the file won't work the way that is intended here. This works well for text files, not JSON as far as I know.
with open("users.json") as reader:
    all_users = json.load(reader)

all_users.append(user)

Then completely rewrite to the file.
with open("users.json","w") as outfile:
    json.dump(user,outfile)

This does assume that user is in a valid JSON format, though.


text:
Q: Bash script in ANT to remove text in file I have this script:
# run this command to create production version of project.html
/<!-- BEGIN PRODUCTION|END PRODUCTION -->/  { next }
/<!-- (BEGIN|END) DEVELOPMENT -->/ { skip = !skip; next }
!skip

Long story short, it replaces text in an HTML file when I compile my application for production. It removes all code between my BEGIN DEVELOPMENT comment and END DEVELOPMENT comment and uncomments the BEGIN PRODUCTION code. Here's an example of the text that would be replaced:
<!-- BEGIN DEVELOPMENT -->
<link rel="stylesheet" href="/style.css" type="text/css" media="screen">
<script type="text/javascript" src="/script.js"></script>
<!-- END DEVELOPMENT -->

<!-- BEGIN PRODUCTION
<link rel="stylesheet" href="/style.min.css" type="text/css" media="all" />
<script type="text/javascript" src="/script.min.js"></script>
END PRODUCTION -->

This is working great. But I need to do the same in a PHP file and I need to use this syntax instead:
/* BEGIN DEVELOPMENT */
{PHP CODE}
/* END DEVELOPMENT */
/* BEGIN PRODUCTION
{PHP CODE}
END PRODUCTION */

It follows the same concept but I can't get the shell script working. Can somebody tell me why this is not correct?:
# run this command to create production version of project.html
/\/* BEGIN PRODUCTION|END PRODUCTION *\//  { next }
/\/* (BEGIN|END) DEVELOPMENT *\// { skip = !skip; next }
!skip

Thanks for any help!
As per the comment below, here's the correct syntax and it works:
# run this command to create production version of project.html
/\/\* BEGIN PRODUCTION|END PRODUCTION \*\//  { next }
/\/\* (BEGIN|END) DEVELOPMENT \*\// { skip = !skip; next }
!skip

A: This can now be marked as answered:
# run this command to create production version of project.html
/\/\* BEGIN PRODUCTION|END PRODUCTION \*\//  { next }
/\/\* (BEGIN|END) DEVELOPMENT \*\// { skip = !skip; next }
!skip


text:
Q: Suppress __init__.py in Eclipse PyDev How to suppress __init__.py from showing in the project tree [Eclipse PyDev]?

A: You can open the dropdown menu on the toolbar (Ctrl + F10) and choose Setup Custom Filters. Here you should be able to add a custom filter for __init__.py files.


text:
Q: Ubuntu server 20.4 nginx always returns a 404 on any php page, html works perfectly As stated in the title Nginx always return a 404 on any php page... :( getting mad here :)+
I'm not an expert on Linux an I'm trying to make it work php 7.4, but i also tried php 8.0 on a distro of Ubuntu Server 20.
I researched the net for 3 days so far and i can't find the solution to the problem, please help me.
these are my config files :
Nginx default.conf
server {
    listen       80;
    server_name  localhost;
    #return 302 https://$server_name$request_uri;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.php index.html index.htm;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        include fastcgi_params;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}

server {

    # SSL configuration

    listen 443 ssl;
    server_name localhost;
    include snippets/self-signed.conf;
    include snippets/ssl-params.conf;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.php  index.htm;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}

Nginx.conf
user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}

 http {
    limit_conn_zone $binary_remote_addr zone=addr:5m;
    limit_conn addr 1;
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    server_tokens off;
    client_body_buffer_size  1K;
    client_header_buffer_size 1k;
    client_max_body_size 1k;
    large_client_header_buffers 2 1k;
    client_body_timeout 10;
    client_header_timeout 10;
    keepalive_timeout 5 5;
    send_timeout 10;
    upstream php {
        server unix:/var/run/php/php7.4-fpm.sock;
    }

    server{
        # Only requests to our Host are allowed i.e. hexadix.com, static.hexadix.com, www.hexadix.com
        if ($host !~ ^(hexadix.com|static.hexadix.com|www.hexadix.com)$ ) {
                return 444;
        }
        if ($request_method !~ ^(GET|HEAD|POST)$ ){
                return 444;
        }
        # Block download agents
        if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
            return 403;
        }
        # Block some robots
        if ($http_user_agent ~* msnbot|scrapbot) {
            return 403;
        }

    }
}

thanks for your time and hopefully help.
Kate :)
this is the error log there's nothing :(

2021/08/26 19:01:02 [notice] 22861#22861: getrlimit(RLIMIT_NOFILE): 1024:524288
2021/08/26 19:01:02 [notice] 22863#22863: start worker processes
2021/08/26 19:01:02 [notice] 22863#22863: start worker process 22864
2021/08/26 19:01:02 [notice] 22863#22863: start worker process 22865
2021/08/26 19:01:02 [notice] 22863#22863: start worker process 22866
2021/08/26 19:01:02 [notice] 22863#22863: start worker process 22867

snippets/fastcgi-php.conf
# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+?\.php)(/.*)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;

fastcgi_params
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

I added them :)

; Start a new pool named 'www'.
; the variable $pool can be used in any directive and will be replaced by the
; pool name ('www' here)
[www]

; Per pool prefix
; It only applies on the following directives:
; - 'access.log'
; - 'slowlog'
; - 'listen' (unixsocket)
; - 'chroot'
; - 'chdir'
; - 'php_values'
; - 'php_admin_values'
; When not set, the global prefix (or /usr) applies instead.
; Note: This directive can also be relative to the global prefix.
; Default Value: none
;prefix = /path/to/pools/$pool

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = www-data
group = www-data

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = /var/run/php/php7.4-fpm.sock

; Set listen(2) backlog.
; Default Value: 511 (-1 on FreeBSD and OpenBSD)
;listen.backlog = 511

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions. The owner
; and group can be specified either by name or by their numeric IDs.
; Default Values: user and group are set as the running user
;                 mode is set to 0660
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
; When POSIX Access Control Lists are supported you can set them using
; these options, value is a comma separated list of user/group names.
; When set, listen.owner and listen.group are ignored
;listen.acl_users =
;listen.acl_groups =

; List of addresses (IPv4/IPv6) of FastCGI clients which are allowed to connect.
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
; must be separated by a comma. If this value is left blank, connections will be
; accepted from any ip address.
; Default Value: any
;listen.allowed_clients = 127.0.0.1

; Specify the nice(2) priority to apply to the pool processes (only if set)
; The value can vary from -19 (highest priority) to 20 (lower priority)
; Note: - It will only work if the FPM master process is launched as root
;       - The pool processes will inherit the master process priority
;         unless it specified otherwise
; Default Value: no set
; process.priority = -19

; Set the process dumpable flag (PR_SET_DUMPABLE prctl) even if the process user
; or group is differrent than the master process user. It allows to create process
; core dump and ptrace the process for the pool user.
; Default Value: no
; process.dumpable = yes

; Choose how the process manager will control the number of child processes.
; Possible Values:
;   static  - a fixed number (pm.max_children) of child processes;
;   dynamic - the number of child processes are set dynamically based on the
;             following directives. With this process management, there will be
;             always at least 1 children.
;             pm.max_children      - the maximum number of children that can
;                                    be alive at the same time.
;             pm.start_servers     - the number of children created on startup.
;             pm.min_spare_servers - the minimum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is less than this
;                                    number then some children will be created.
;             pm.max_spare_servers - the maximum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is greater than this
;                                    number then some children will be killed.
;  ondemand - no children are created at startup. Children will be forked when
;             new requests will connect. The following parameter are used:
;             pm.max_children           - the maximum number of children that
;                                         can be alive at the same time.
;             pm.process_idle_timeout   - The number of seconds after which
;                                         an idle process will be killed.
; Note: This value is mandatory.
pm = dynamic

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI. The below defaults are based on a server without much resources. Don't
; forget to tweak pm.* to fit your needs.
; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
; Note: This value is mandatory.
pm.max_children = 5

; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: (min_spare_servers + max_spare_servers) / 2
pm.start_servers = 2

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 1

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 3

; The number of seconds after which an idle process will be killed.
; Note: Used only when pm is set to 'ondemand'
; Default Value: 10s
;pm.process_idle_timeout = 10s;

; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
;pm.max_requests = 500

; The URI to view the FPM status page. If this value is not set, no URI will be
; recognized as a status page. It shows the following informations:
;   pool                 - the name of the pool;
;   process manager      - static, dynamic or ondemand;
;   start time           - the date and time FPM has started;
;   start since          - number of seconds since FPM has started;
;   accepted conn        - the number of request accepted by the pool;
;   listen queue         - the number of request in the queue of pending
;                          connections (see backlog in listen(2));
;   max listen queue     - the maximum number of requests in the queue
;                          of pending connections since FPM has started;
;   listen queue len     - the size of the socket queue of pending connections;
;   idle processes       - the number of idle processes;
;   active processes     - the number of active processes;
;   total processes      - the number of idle + active processes;
;   max active processes - the maximum number of active processes since FPM
;                          has started;
;   max children reached - number of times, the process limit has been reached,
;                          when pm tries to start more children (works only for
;                          pm 'dynamic' and 'ondemand');
; Value are updated in real time.
; Example output:
;   pool:                 www
;   process manager:      static
;   start time:           01/Jul/2011:17:53:49 +0200
;   start since:          62636
;   accepted conn:        190460
;   listen queue:         0
;   max listen queue:     1
;   listen queue len:     42
;   idle processes:       4
;   active processes:     11
;   total processes:      15
;   max active processes: 12
;   max children reached: 0
;
; By default the status page output is formatted as text/plain. Passing either
; 'html', 'xml' or 'json' in the query string will return the corresponding
; output syntax. Example:
;   http://www.foo.bar/status
;   http://www.foo.bar/status?json
;   http://www.foo.bar/status?html
;   http://www.foo.bar/status?xml
;
; By default the status page only outputs short status. Passing 'full' in the
; query string will also return status for each pool process.
; Example:
;   http://www.foo.bar/status?full
;   http://www.foo.bar/status?json&full
;   http://www.foo.bar/status?html&full
;   http://www.foo.bar/status?xml&full
; The Full status returns for each process:
;   pid                  - the PID of the process;
;   state                - the state of the process (Idle, Running, ...);
;   start time           - the date and time the process has started;
;   start since          - the number of seconds since the process has started;
;   requests             - the number of requests the process has served;
;   request duration     - the duration in µs of the requests;
;   request method       - the request method (GET, POST, ...);
;   request URI          - the request URI with the query string;
;   content length       - the content length of the request (only with POST);
;   user                 - the user (PHP_AUTH_USER) (or '-' if not set);
;   script               - the main script called (or '-' if not set);
;   last request cpu     - the %cpu the last request consumed
;                          it's always 0 if the process is not in Idle state
;                          because CPU calculation is done when the request
;                          processing has terminated;
;   last request memory  - the max amount of memory the last request consumed
;                          it's always 0 if the process is not in Idle state
;                          because memory calculation is done when the request
;                          processing has terminated;
; If the process is in Idle state, then informations are related to the
; last request the process has served. Otherwise informations are related to
; the current request being served.
; Example output:
;   ************************
;   pid:                  31330
;   state:                Running
;   start time:           01/Jul/2011:17:53:49 +0200
;   start since:          63087
;   requests:             12808
;   request duration:     1250261
;   request method:       GET
;   request URI:          /test_mem.php?N=10000
;   content length:       0
;   user:                 -
;   script:               /home/fat/web/docs/php/test_mem.php
;   last request cpu:     0.00
;   last request memory:  0
;
; Note: There is a real-time FPM status monitoring sample web page available
;       It's available in: /usr/share/php/7.4/fpm/status.html
;
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set
;pm.status_path = /status

; The ping URI to call the monitoring page of FPM. If this value is not set, no
; URI will be recognized as a ping page. This could be used to test from outside
; that FPM is alive and responding, or to
; - create a graph of FPM availability (rrd or such);
; - remove a server from a group if it is not responding (load balancing);
; - trigger alerts for the operating team (24/7).
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set
;ping.path = /ping

; This directive may be used to customize the response of a ping request. The
; response is formatted as text/plain with a 200 response code.
; Default Value: pong
;ping.response = pong

; The access log file
; Default: not set
;access.log = log/$pool.access.log

; The access log format.
; The following syntax is allowed
;  %%: the '%' character
;  %C: %CPU used by the request
;      it can accept the following format:
;      - %{user}C for user CPU only
;      - %{system}C for system CPU only
;      - %{total}C  for user + system CPU (default)
;  %d: time taken to serve the request
;      it can accept the following format:
;      - %{seconds}d (default)
;      - %{miliseconds}d
;      - %{mili}d
;      - %{microseconds}d
;      - %{micro}d
;  %e: an environment variable (same as $_ENV or $_SERVER)
;      it must be associated with embraces to specify the name of the env
;      variable. Some exemples:
;      - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
;      - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e
;  %f: script filename
;  %l: content-length of the request (for POST request only)
;  %m: request method
;  %M: peak of memory allocated by PHP
;      it can accept the following format:
;      - %{bytes}M (default)
;      - %{kilobytes}M
;      - %{kilo}M
;      - %{megabytes}M
;      - %{mega}M
;  %n: pool name
;  %o: output header
;      it must be associated with embraces to specify the name of the header:
;      - %{Content-Type}o
;      - %{X-Powered-By}o
;      - %{Transfert-Encoding}o
;      - ....
;  %p: PID of the child that serviced the request
;  %P: PID of the parent of the child that serviced the request
;  %q: the query string
;  %Q: the '?' character if query string exists
;  %r: the request URI (without the query string, see %q and %Q)
;  %R: remote IP address
;  %s: status (response code)
;  %t: server time the request was received
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;      The strftime(3) format must be encapsuled in a %{<strftime_format>}t tag
;      e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
;  %T: time the log has been written (the request has finished)
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;      The strftime(3) format must be encapsuled in a %{<strftime_format>}t tag
;      e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
;  %u: remote user
;
; Default: "%R - %u %t \"%m %r\" %s"
;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"

; The log file for slow requests
; Default Value: not set
; Note: slowlog is mandatory if request_slowlog_timeout is set
;slowlog = log/$pool.log.slow

; The timeout for serving a single request after which a PHP backtrace will be
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_slowlog_timeout = 0

; Depth of slow log stack trace.
; Default Value: 20
;request_slowlog_trace_depth = 20

; The timeout for serving a single request after which the worker process will
; be killed. This option should be used when the 'max_execution_time' ini option
; does not stop script execution for some reason. A value of '0' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_terminate_timeout = 0

; The timeout set by 'request_terminate_timeout' ini option is not engaged after
; application calls 'fastcgi_finish_request' or when application has finished and
; shutdown functions are being called (registered via register_shutdown_function).
; This option will enable timeout limit to be applied unconditionally
; even in such cases.
; Default Value: no
;request_terminate_timeout_track_finished = no

; Set open file descriptor rlimit.
; Default Value: system defined value
;rlimit_files = 1024

; Set max core size rlimit.
; Possible Values: 'unlimited' or an integer greater or equal to 0
; Default Value: system defined value
;rlimit_core = 0

; Chroot to this directory at the start. This value must be defined as an
; absolute path. When this value is not set, chroot is not used.
; Note: you can prefix with '$prefix' to chroot to the pool prefix or one
; of its subdirectories. If the pool prefix is not set, the global prefix
; will be used instead.
; Note: chrooting is a great security feature and should be used whenever
;       possible. However, all PHP paths will be relative to the chroot
;       (error_log, sessions.save_path, ...).
; Default Value: not set
;chroot =

; Chdir to this directory at the start.
; Note: relative path can be used.
; Default Value: current directory or / when chroot
;chdir = /var/www

; Redirect worker stdout and stderr into main error log. If not set, stdout and
; stderr will be redirected to /dev/null according to FastCGI specs.
; Note: on highloaded environement, this can cause some delay in the page
; process time (several ms).
; Default Value: no
;catch_workers_output = yes

; Decorate worker output with prefix and suffix containing information about
; the child that writes to the log and if stdout or stderr is used as well as
; log level and time. This options is used only if catch_workers_output is yes.
; Settings to "no" will output data as written to the stdout or stderr.
; Default value: yes
;decorate_workers_output = no

; Clear environment in FPM workers
; Prevents arbitrary environment variables from reaching FPM worker processes
; by clearing the environment in workers before env vars specified in this
; pool configuration are added.
; Setting to "no" will make all environment variables available to PHP code
; via getenv(), $_ENV and $_SERVER.
; Default Value: yes
;clear_env = no

; Limits the extensions of the main script FPM will allow to parse. This can
; prevent configuration mistakes on the web server side. You should only limit
; FPM to .php extensions to prevent malicious users to use other extensions to
; execute php code.
; Note: set an empty value to allow all extensions.
; Default Value: .php
;security.limit_extensions = .php .php3 .php4 .php5 .php7

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

; Additional php.ini defines, specific to this pool of workers. These settings
; overwrite the values previously defined in the php.ini. The directives are the
; same as the PHP SAPI:
;   php_value/php_flag             - you can set classic ini defines which can
;                                    be overwritten from PHP call 'ini_set'.
;   php_admin_value/php_admin_flag - these directives won't be overwritten by
;                                     PHP call 'ini_set'
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.

; Defining 'extension' will load the corresponding shared extension from
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
; overwrite previously defined php.ini values, but will append the new value
; instead.

; Note: path INI options can be relative and will be expanded with the prefix
; (pool, global or /usr)

; Default Value: nothing is defined by default except the values in php.ini and
;                specified at startup with the -d argument
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
;php_flag[display_errors] = off
;php_admin_value[error_log] = /var/log/fpm-php.www.log
;php_admin_flag[log_errors] = on
;php_admin_value[memory_limit] = 32M

A: use
fastcgi_pass unix:/var/run/php/7.4/fpm.sock;

instead of
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;

in your default nginx configuration file and don't forgot to restart nginx and fpm


text:
Q: Confidence Interval for Centered Moving Average of Timeseries Data (Smoothing) I'm having trouble finding a good resource on this.
I'm plotting some timeseries data over the last 200 years that has a clear trend, although there is also a lot of noise. I have smoothed the data using a simple centered moving average of all observations with +/- 2 years of each year (some years have many observations, some none).
I wanted to also plot a confidence interval of the moving average. Naively, I thought I could just find the standard error of the observations included in the window for each year. For example, my data might look like:

year
value

4
1

4
2

5
2

7
5

7
4

8
7

9
5

10
9

10
8

For year 5, the observations in the window are 1,2,2,5,4. The moving average is 2.8. The standard deviation of these observations is 1.47, and the standard error is that divided by $\sqrt{5}$, which is 0.66. Assuming normal noise, this would give a 95% CI of +/- 1.96*0.66 = 1.29. That seems right to me but I cannot find a resource to confirm that.
Is that a reasonable thing to do? And could anyone point me to a resource that tells why that is/isn't ok

A: While your approach is not wrong, it can be improved if you are willing to assume that the variance around the trend line is constant. In that case, it would be to estimate the standard error from all the residuals.
Let $y_t$ denote the observation at time $t$. Then the estimated trend is given by
$$\hat{f}(t) = (y_{t-2} + y_{t-1} + y_t + y_{t+1} + y_{t+2})/5.$$
(Note that this doesn't need "centering" as it uses an odd number of observations.) The residuals are given by $e_t= y_t - f(t)$ and the estimated residual variance is
$$\hat\sigma^2 = \frac{1}{T-4}\sum_{t=3}^{T-2} e_t^2,$$
where $T$ is the length of the series. The first two and last two trend estimates are missing due to insufficient observations at the start and end of the series.
A 95% confidence interval for the fitted line is
$$\hat{f}(t) \pm 1.96 \frac{\hat{\sigma}}{\sqrt{5}}.$$


text:
Q: записывается ток 1 кб от 349 кб #include <iostream>
#include <cstdlib>
#include <string>
#include <cstdio>
using namespace std;
#pragma warning(disable: 4996)
int main(int argc, char* argv[])
{
    FILE* ptrFile1 = fopen("test.png", "rb");

if (ptrFile1 == NULL)
{
    fputs("Ошибка файла", stderr);
    exit(1);
}

fseek(ptrFile1, 0, SEEK_END);                          // устанавливаем позицию в конец файла
long lSize = ftell(ptrFile1);                            // получаем размер в байтах
rewind(ptrFile1);                                       // устанавливаем указатель в конец файла

char* buffer = (char*)malloc(sizeof(char) * lSize); // выделить память для хранения содержимого файла
if (buffer == NULL)
{
    fputs("Ошибка памяти", stderr);
    exit(2);
}

size_t result = fread(buffer, 1, lSize, ptrFile1);       // считываем файл в буфер
if (result != lSize)
{
    fputs("Ошибка чтения", stderr);
    exit(3);
}

//содержимое файла теперь находится в буфере
puts(buffer);

// завершение работы
fclose(ptrFile1);

FILE* ptrFile = fopen("test1.png", "wb");

fwrite(buffer, 1, sizeof(buffer), ptrFile); // записать в файл содержимое буфера
fclose(ptrFile);
free(buffer);
return 0;

}
из 349 кб записывается 1кб,
как можно это исправить?

A: Записывается далеко не 1 Кбайт, а sizeof(buffer) байт, т.е. 4 или 8, в зависимости от разрядности вашего приложения.
buffer - это указатель, а sizeof(buffer) — размер указателя, а вовсе не того, на что он указывает.
Вас спасет
fwrite(buffer, 1, lSize, ptrFile); // записать в файл содержимое буфера


text:
Q: Angular Universal server API requesting I just migrated my application to Angular 6 + Universal. It`s great but I have 2 issues to fix. Please help me for both ones:
1- How can I run the Angular Universal app in --watch mode for developing time?
Before that I opened 2 terminal. In one of them I wrote command: nodemon server.js and in another on : ng build --watch. In this situation I was developing my application fast by real-time editing.
But now after each edit I use command npm run build:ssr. I takes lots of time. There should be another way for increase developing time in Angular Universal?!
2- The other issue is before I migrate to Angular Universal, I was using express to for server side same as now. I have called an API handler file like this:
const api = require('./routes/api');
app.use('/api', api);

How can I do this in new angular universal package like before in server.ts file?

A: For Angular7 run npm run ssr:watch
package.json
    "ssr:watch": "run-p ssr:universal:build:*",
    "ssr:universal:build:browser": "ng run universal-demo:build --watch",
    "ssr:universal:build:server": "node ./node_modules/npm-delay 12000 && ng run universal-demo:server --watch",
    "ssr:universal:build:webpack": "node ./node_modules/npm-delay 20000 && webpack --config webpack.config.js --watch",
    "ssr:universal:build:nodemon": "node ./node_modules/npm-delay 25000 && nodemon --inspect server.js",


text:
Q: Difference between JSONParser and JSONRenderer I was going through django rest framework tutorial on serialization in which I got stuck at JSONRenderers and JSONParsers.Below is the code mentioned there:
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from django.utils.six import BytesIO

snippet = Snippet(code='foo = "bar"\n')
snippet.save()

snippet = Snippet(code='print "hello, world"\n')
snippet.save()
serializer = SnippetSerializer(snippet)
serializer.data
# {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
content = JSONRenderer().render(serializer.data)
content
# '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'

stream = BytesIO(content)
data = JSONParser().parse(stream)

I know JSONParser is used for deserializing the data and JSONRenderer is used for serializing it , but I still don't  have a sound understanding of the difference between serializing and deserializing of a data. Can someone provide me a clear understanding of this.(Answer with an example is highly appreciated.)
And also how does JSONRenderer and JSONParser work?

A: I will start with viewsets. View and viewsets are classes in DRF, where most of application logic happens.
Eg. ModelViewSet is class responsible for CRUD operations in response to POST, PUT, PATCH, GET, DELETE HTTP methods.
Lets take look at default create method from https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py this method create instance of your model, from data (if they are valid) send via HTTP POST method and persist them to database.
def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

def perform_create(self, serializer):
        serializer.save()

This is whats happening here.
self.get_serializer() create new instance of serializer (you set serializer class before), it takes request.data as argument. request.data is (this is importent) dictionary. Dictionary is generic python data structure.
serializer.is_valid() method checks if request.data are valid. If yes you can access serializer.data - also a dictionary.
serializer.save() method creates and persist actual instance of your model (Snippet) to database.
You can directly access instance like this
instance = serializer.save()

Then you return Response object populated with serializer.data back to client.
As you can see, there is no Form data,JSON, XML, HTML etc. in viewset. You work with python data types and serializer is reponsible of "translating" dictionary to instance of your specific model and backwards.
But client send data (in your case) in HTTP request in form of JSON.
JSONParser is responsible of converting JSON to dictionary. Parsing is implemented inside request class https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/request.py , please notice that is not standard django HttpRequest  model.
You can set multiple parsers, then request will choose proper one according to HTTP request header: Content-type.
Second thing is, you have to return serializer.data back to client in form of JSON, not dictionary. Thats what JSONRenderer does. It convert dict to JSON and its implemented inside Response class https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/response.py. Also you can set multiple renderers and then the proper one is choose according to accepted media type http header.
Example of full viewset definition might be:
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

class SnippetViewSet(viewsets.ModelViewSet):

    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    renderer_classes = (JSONRenderer, )
    parser_classes = (JSONParser,)


text:
Q: Change Superuser name in Ubuntu? I mistyped my superuser. It should be "masi" instead of "maasi". I do not want to configure and install all packages again. How can I change it?

A: If you're not talking about UID 0 (which is almost always called root, and probably hardcoded as that name in a few admin applications), then the 'super user' is just a user in the admin group. You can use the method mentioned above (though make sure you also edit /etc/shadow and /etc/gshadow, and use vipw and vigr), but I'd recommend simply creating a new account with the correct name, adding it to the admin group (adduser masi admin), and migrating your data to it (copying the home directory and chown -R masi are probably sufficient). Log in to the new account and confirm that you can run sudo before deleting the old account. This is much less likely to leave you locked out of your system.

A: You will want to use the usermod command. It will update all files needed for you as well.
You must make note of the caveats though:

CAVEATS:
usermod will not allow you to change
  the name of a user who is logged in.
  You must make certain that the named
  user is not executing any processes
  when this command is being executed if
  the user's numerical user ID is being
  changed. You must change the owner of
  any crontab files manually. You must
  change the owner of any at jobs
  manually. You must make any changes
  involving NIS on the NIS server.

A: Just edit the entry in /etc/password to what you want. You may also need to update /etc/group for consistency. Then rename your home directory (in /home) to match.
All file permissions are done by user/group ID (the number associated with your name) so by updating the name, it should "just work".


text:
Q: Google Chrome Portable's Extension is being reset I have my own extension and apply in my Chrome Portable without any user logged.
But when I copy the Chrome Portable folder to another machine and launch the browser, the extension is lost, somehow is like a fresh start.
But I have check the local path of the extension is still there.
How can I keep the extension whenever I copy the folder to another machine to use other than sync to a user?

A: Currently chrome portable works differently from any other portable browser because it only stores extension by login using google account, not possible by local account only and if u are using different machine then you have to relogin again.
I recommend using firefox portable, because it did stores everything including extension even after being copied to different machine without need to login into firefox account.


text:
Q: Rotation in iOS6 There are many questions and answers about the changed rotation in iOS6.
But I have really not solved one problem about that.
Using Xcode 4.5.2.
If I do not set anything in the info.plist or by the buttons "Supported Interface Orientations", the app will rotate between portrait and landscape depending of the device rotation.
Now I mean the rotation caused by how holding the device, not a default orientation when opening a ViewController.
I know how to prevent landscape mode
- (BOOL)shouldAutorotate
{

    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return (UIInterfaceOrientationMaskPortrait);
}

but it does not have any effect.
Yes it has effect if I add a FlipsideController from the NavBar. In FlipsideView the code above prevents the rotation.
In the other ViewControllers it does not have any effect at all, whatever code I write.
Take a Sample given by Apple, UICatalog.
Can anybode give me a hint how to controll the rotation for the whole table and also for a separate ViewController using code and not by the Buttons or info.plist which only gives a result for everything together which is not very practical for all views.


text:
Q: How to destroy monster nests? I've played for several hours now and already cleared 3-4 monster nests but I could not figure out how to destroy those. I got the bombs for so how to destroy the nests with it?

A: Grapeshot & Samum bombs can both be used to destroy nests...
You start with both of these recipes and can craft them yourself (you do not need a craftsman) once you find the materials. You can loot/harvest the materials in the starting area but saltpetre is not common however if you can buy it from a herbalist. Once you have crafted the bombs you can use them to destroy nests simply by pressing the action button/key when near a nest and Geralt will light and drop one in resulting in the nest exploding and you being rewarded with XP for destroying it a few seconds later.
Be sure to stick around for after the explosion as the monster nest usually drops valuable loot and crafting components.

A: You can destroy Monster Nests just like in Witcher 2. Crafting or Buying Bombs and using them on the Nests.
In the Witcher 3 it works the same way you have to blow up the nests but with some new twists. Before you would go to the nest and press a button to drop the bomb.
Now in the Witcher 3 you can throw a bomb towards the nest or use a destructive sign at it to destroy it.

"look around the chamber until you spot the two smoking mounds lying
  either side of the pit. As instructed, use either bombs or one of your
  destructive spells to obliterate them" - Quote from Guide

The specific bomb to destroy nests in the Witcher 2 was the Grapeshot Bomb.
EDIT:
Ghouls Nests and Nekker Nests can only be destroyed with bombs. Get a Samum Bomb or Grapeshot Bomb (Most Common) and go to the Nest and will ask you to press a button to drop de bomb just like in Witcher 2. Some nests can be destroyed by using the bomb and Igni and some only with Igni.
Endrega nests (Eggs) can be destroyed using Igni and so can rats nests.
If you need to replenish your bombs just meditate with Strong Alcohol like Alcohest and they will refill along with your potions.


text:
Q: Turn Title bar filters on at all time We have a number of custom lists, and on some of the larger ones the sidebar popping up is undesirable.  We added Filter=1 to the links to the lists which turns on the filters at the top, which is great.
The issue we have is when someone selects a filter the filters at the top go away.  Is there a way to keep them on all the time?   I wasn't sure how to access the onchange property, or if there is an easier way.
Thanks,

A: I've never done this. but..
You could try to modify the XSLT of the WebPart.

In the default XSLT the filters are rendered when $dvt_adhocmode equals filter. I'm not sure how one would get hold of the default XSLT to modify, since you're using "online"...
Beware that this would only work in classic pages (i.e. on the "old" list view webpart). The better solution would be to design "better" views.

A: You don't need to add "?Filter=1" to the links to the lists which turns on the filters at the top.
You can just use column header filter.

Reference:
https://sharepointmaven.com/3-ways-filter-sharepoint-lists-libraries/


text:
Q: Arithmetic Progression, Tn and Tm proving sum How can I prove this?
If in an A.P., Tm=n, Tn=m, prove d=-1.

A: Assume it is given that $m\ne n$.
You have $T(m)=n$ and $T(n)=m$. So,
$$a+(m-1)d=n\quad \text{and} \quad a+(n-1)d=m$$
Hint: Subtract the two equalities.

A: Notwithstanding the imprecision of the question, and assuming $m\neq n$:
The slope is $\frac{T_m-m}{T_n-n}=\frac{n-m}{m-n}=-1$

A: we have
$(T_i) $ arithmetic sequence
$$\implies T_n=T_m+(n-m)d $$
$$\implies m-n=(n-m)d $$
$$\implies (d+1)(n-m )=0$$
$$\implies d=-1$$


text:
Q: printf implementation for embedded system where can I find an almost complete implementation (float, width, etc.) suitable for embedded systems (few nested funtction call, low stack and ram usage, no heap, mo syscall)

A: Have you checked out ChibiOS's implementation of chvprintf? It's Apache-licensed and float-support (costly) is a compile-time option via define.
It's built with microcontrollers in mind. The macros are all pretty much only calls to a function pointer in the supplied BaseSequentialStream struct and you can replace them as you see fit. The var-args list is your regular stdarg.h implementation.

A: For transmitting on the serial port, the quickest thing is:
int32_t printfDebugSerial(const char *format, ...)
{
  if (strlen(format) >200) return -1;
  char tempBuff[256]; memset(tempBuff, 0, sizeof tempBuff);

  va_list arg;
  int32_t done;
  va_start (arg, format);
  done = (int32_t)vsprintf(tempBuff,format, arg);
  va_end (arg);

  pushMsgOnSerial((uint8_t*)tempBuff, done);
  return done;
}

where pushMsgOnSerial() will be your board specific function for sending bytes on the serial port.


text:
Q: SQL Parse xml column data I have very little experience with SQL Server. Here is what I am trying to accomplish:
I have a table with many rows. Every row contains a column named "Config". The data stored in the Config column is of the xml type. The xml structure looks like this:
<root>
 <path1>
  <path2>
   <path3>true</path3>
  </path2>
 </path1>
</root>

I am trying to go through every row in the table and find the percentage of true to false values of <path3>.
I looked at some SQL documentation and tried to use the value() function I am having difficulties extracting the XML data from the column:
select Config.value('(/root/path1/path2/path3)[1]','nvarchar(max)') from [MyDB].[dbo].[MyTable]

Here is the result of my query:

I would like to query and extract data from the XML "Config" column of my table and aggregate that data into columns.

A: You need to specify namespaces in the query when xml is built with namespaces. For example
CREATE TABLE tbl (Config xml);
INSERT INTO tbl (Config)
VALUES ('<root xmlns="abc">
 <path1>
  <path2>
   <path3>true</path3>
  </path2>
 </path1>
</root>') ;

Then
with xmlnamespaces (DEFAULT 'abc')
select Config.value('(/root/path1/path2/path3)[1]','nvarchar(max)') path3Txt
from tbl;

or explicit specification
with xmlnamespaces ('abc' as x)
select Config.value('(/x:root/x:path1/x:path2/x:path3)[1]','nvarchar(max)') path3Txt
from tbl;

A: You would need to use CROSS APPLY. Check it out.

SQL

-- DDL and sample data population, start

    DECLARE @tbl TABLE (ID INT IDENTITY(1,1) PRIMARY KEY, [Config] XML);
    INSERT INTO  @tbl
    VALUES (N'<root>
        <path1>
            <path2>
                <path3>true</path3>
            </path2>
        </path1>
    </root>')
    , (N'<root>
        <path1>
            <path2>
                <path3>false</path3>
            </path2>
        </path1>
    </root>');
    -- DDL and sample data population, end

    ;WITH rs AS
    (
       SELECT ID
          , col.value('(./text())[1]','VARCHAR(20)') AS Result
        FROM @tbl tbl
          CROSS APPLY tbl.[Config].nodes('/root/path1/path2/path3') AS tab(col)
    )
    SELECT * FROM rs;