text:
Q: Convert CSV into JSON. How do I keep values with the same Index? I am using this database: https://cpj.org/data/killed/?status=Killed&motiveConfirmed%5B%5D=Confirmed&type%5B%5D=Journalist&localOrForeign%5B%5D=Foreign&start_year=1992&end_year=2019&group_by=year
I have preprocessed it into this csv (showing only 2 lines of 159):
year,combinedStatus,fullName,sortName,primaryNationality,secondaryNationality,tertiaryNationality,gender,photoUrl,photoCredit,type,lastStatus,typeOfDeath,status,employedAs,organizations,jobs,coverage,mediums,country,location,region,state,locality,province,localOrForeign,sourcesOfFire,motiveConfirmed,accountabilityCrossfire,accountabilityAssignment,impunityMurder,tortured,captive,threatened,charges,motive,lengthOfSentence,healthProblems,impCountry,entry,sentenceDate,sentence,locationImprisoned
1994,Confirmed,Abdelkader Hireche,,,,,Male,,,Journalist,,Murder,Killed,Staff,Algerian Television (ENTV),Broadcast Reporter,Politics,Television,Algeria,Algiers,,,Algiers,,Foreign,,Confirmed,,,Partial Impunity,No,No,No,,,,,,,,,
2014,Confirmed,Ahmed Hasan Ahmed,,,,,Male,,,Journalist,,Dangerous Assignment,Killed,Staff,Xinhua News Agency,"Camera Operator,Photographer","Human Rights,Politics,War",Internet,Syria,Damascus,,,Damascus,,Foreign,,Confirmed,,,,,,,,,,,,,,,

And I want to make this type of JSON out of it:
"Afghanistan": {"year": 2001, "fullName": "Volker Handloik", "gender": "Male", "typeOfDeath": "Crossfire", "employedAs": "Freelance", "organizations": "freelance reporter", "jobs": "Print Reporter", "coverage": "War", "mediums": "Print", "photoUrl": NaN}, "Somalia": {"year": 1994, "fullName": "Pierre Anceaux", "gender": "Male", "typeOfDeath": "Murder", "employedAs": "Freelance", "organizations": "freelance", "jobs": "Broadcast Reporter", "coverage": "Human Rights", "mediums": "Television", "photoUrl": NaN}

The problem is that Afghanistan (as you can see in the link) has had many journalist deaths. I want to list all these killings under the Index 'Afghanistan'. However, as I currently do it, only the last case (Volker Handloik) in the csv file shows up. How can I get it so every case shows up?
this is my code atm
import pandas as pd
import pprint as pp
import json

# list with stand-ins for empty cells
missing_values = ["n/a", "na", "unknown", "-", ""]

# set missing values to NaN
df = pd.read_csv("data_journalists.csv", na_values = missing_values, skipinitialspace = True, error_bad_lines=False)

# columns
columns_keep = ['year', 'fullName', 'gender', 'typeOfDeath', 'employedAs', 'organizations', 'jobs', 'coverage', 'mediums', 'country', 'photoUrl']

small_df = df[columns_keep]

with pd.option_context('display.max_rows', None, 'display.max_columns', None):  # more options can be specified also
    print(small_df)

# create dict with country-column as index
df_dict = small_df.set_index('country').T.to_dict('dict')

print(df_dict)

# make json file from the dict
with open('result.json', 'w') as fp:
    json.dump(df_dict, fp)

    # use pretty print to see if dict matches the json example in the exercise
 pp.pprint(df_dict)

I want to include all of these names (and more) in the JSON under the index Afghanistan

I think I will need a list of objects that is attached to the index of a country so that every country can show all the cases of journalists death instead of only 1 (each time being replaced by the next in the csv) I hope this is clear enough

A: I'll keep your code until the definition of small_df.
After that, we perform a groupby on the 'country' column and use pd.to_json on it:
country_series = small_df.groupby('country').apply(lambda r : r.drop(['country'], axis=1).to_json())

country_series is a pd.Series with the countries as index.
After that, we create a nested dictionary, so that we have a valid json object:
fullDict = {}
for ind, a in country_series.iteritems():
    b = json.loads(a)
    c = b['fullName']
    smallDict = {}
    for index, journalist in c.items():
        smallDict[journalist] = {}
        for i in b.keys():
            smallDict[journalist][i] = b[i][index]
    fullDict[ind] = (smallDict)

The nomenclature in my part of code is pretty bad, but I tried to write all the steps explicitly so that things should be clear.
Finally, we write the results to a file:
with open('result.json', 'w') as f:
    json.dump(fullDict, f)


text:
Q: How can I extract all the coefficients of a linear equation? I have a linear equation in two variables that I am simplifying using simplify from sympy and I want to extract all the coefficients of the equation. This is what I have for the coefficients of x and y
expr =(x - 4.48e10)**2 + (y+1.047e11)**2 - (x + 1.346e11)**2 - (y + 5.23e10)**2
smpl = simplify(expr)
smpl.as_expr()

x = smpl.coeff(x)
print(x)

y = smpl.coeff(y)
print(y)

How can I extract 7.88332*10^21 separately? I tried to use a = smpl.coeff(-1) but that prints out the absolute value of x and the last term. How can I fix this?

A: Here is your expression:
In [15]: smpl
Out[15]: -358800000000.0⋅x + 104800000000.0⋅y - 7.88332e+21

You want to get the constant term 7.88332e+21 separately from the rest of the expression. There are many different ways that you could do that depending on what other expressions you might want to handle.
When working interactively the simplest way to access parts of an expression is by using .args (possibly recursively) e.g.:
In [16]: smpl.args
Out[16]: (-7.88332e+21, 104800000000.0⋅y, -358800000000.0⋅x)

In [17]: smpl.args[0]
Out[17]: -7.88332000000000e+21

In [18]: smpl.args[2]
Out[18]: -358800000000.0⋅x

In [19]: smpl.args[2].args[0]
Out[19]: -358800000000.000

This makes it possible to find any subexpression manually but is a fragile approach to use in a program where the exact form of the expression might not be known ahead of time.
Other solutions really depend on defining what "class" of expressions you want to be able to handle and how exactly to specify which part of the expression is the part that you want. Assuming that your expression is always a polynomial with explicit numeric coefficients and your goal is to get the numeric constant then you can use .as_coeff_Add:
In [21]: smpl.as_coeff_Add()
Out[21]: (-7.88332e+21, -358800000000.0⋅x + 104800000000.0⋅y)

In [22]: smpl.as_coeff_Add()[0]
Out[22]: -7.88332000000000e+21

More generally any expression can be treated as a polynomial and plain numeric coefficients can be extracted from that:
In [25]: smpl.as_coefficients_dict()
Out[25]: defaultdict(int, {1: -7.88332e+21, x: -358800000000.0, y: 104800000000.0})

In [26]: smpl.as_coefficients_dict()[1]
Out[26]: -7.88332000000000e+21

In [31]: smpl.as_coefficients_dict()[x]
Out[31]: -358800000000.000

Another possibility that could work for non-polynomial expressions but depends on the syntactic form of the expression is to use pattern matching:
In [37]: a, b, c = symbols('a, b, c', cls=Wild, exclude=[x, y])

In [38]: smpl.match(a*x + b*y + c)
Out[38]: {a: -358800000000.0, b: 104800000000.0, c: -7.88332e+21}

In [39]: smpl.match(a*x + b*y + c)[c]
Out[39]: -7.88332000000000e+21

Unlike as_coeff_Add and as_coefficients_dict() this would also work if the term you wanted to exact was an expression rather than just a number.
Lastly a simple way to get all numbers out of an expression is using .atoms:
In [41]: smpl.atoms(Float)
Out[41]: {-7.88332e+21, -358800000000.0, 104800000000.0}

In [42]: list(smpl.atoms(Float))
Out[42]: [-358800000000.0, 104800000000.0, -7.88332e+21]

In [43]: list(smpl.atoms(Float))[-1]
Out[43]: -7.88332000000000e+21

redpajama_set_name: RedPajamaStackExchange


text:
Q: Replace column values? I recently got into SSIS and haven't been able to find what I am trying to achieve anywhere on the web.
I am trying to take some rows as input, and then replace one specific column's value with something else, and then return the rows with modified columns as output.
The problem is that I don't know which task to use.
I'm limited by SQL Server 2008.
How do I get started?

A: The way I would do this is with a Derived Column Transformation.  Take a look at this example (hitting the sample database, AdventureWorks2012):

As you can see on this screenshot, what I'm doing is taking the Name column from AdventureWorks2012.HumanResources.Department (this would work with your version of SQL Server/SSIS as well, I believe.  Although you would know pretty quickly if it doesn't) and using a conditional statement for my Expression:
Name == "Sales" ? "New Sales Name" : Name

What that is, is a short-hand conditional statement.  It takes the Boolean result of Name == "Sales".  If that's true (i.e. the Name is "Sales") then return "New Sales Name", or whatever string you'd want to substitute.  If that's false (the Name is not "Sales") then just return the Name as it originally was.


text:
Q: Bash command for automatically confirm option during installation Whenever you're installing a package, it usually prompts for y/n confirmation, is there a way to automate this?

A: You might try
yes | install-package.sh

A: on debian based distros you can run:
apt-get -y install <package_to_install>

to further automate it (in case of installing packages that asks some questions - for example mysql-server asks for db root password) run:
DEBIAN_FRONTEND=noninteractive apt-get -y install <package_to_install>

A: Try the -f switch. It probably depends on which package manager you have, so you should check the man-page for your package manager to confirm.


text:
Q: node-soap Signature not populating We are trying to set up node-soap using the WSSecurityCertificate as detailed here. We were expecting the signature to be generated, but it just says 'Signature'. The BinarySecurityToken looks to be generated correctly. Looking around online shows how we can sign something using openssl, but not really get the signature. And if we were to generate it, what do we sign? Our own key? Our own certificate? And this documentation doesn't list how to generate the signature. Any help on how to populate this signature or what we are doing wrong?
Code:
var options = {
        hasTimeStamp: true,
        mustUnderstand: true,
        additionalReferences: [
            'wsa:Action',
            'wsa:To',
        ],
        signerOptions: {
            prefix: 'ds',
            attrs: { Id: 'Signature' },
            existingPrefixes: {
                wsse: 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd',
            }
        }
    };
  var wsSecurity = new soap.WSSecurityCert(privateKey, publicKey, password, options)

What is output:
<ds:Signature Id="Signature" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

What we expected (X'd out end to err on safety):
<ds:Signature Id="SIG-262E3B6052F7XXXXXXXXXXXXXXXXXXXX" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

If we remove the attrs line above, it becomes like below, so I am pretty sure this is needed:
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">


text:
Q: How to multiple two input fields values and display it in third field as output using visualforce/apex i have written vf and apex as below code mentioned and i am unable to gt the output:-

vf

<script>
function checkAllOrNone(allOrNoneCheckbox) {
    var container = allOrNoneCheckbox;
    while (container.tagName != "TABLE") {
        container = container.parentNode;
    }
    var inputs = container.getElementsByTagName("input");
    var checked = allOrNoneCheckbox.checked;
    for (var i = 0; i < inputs.length; i++) {
        var input = inputs.item(i);
        if (input.type == "checkbox") {
            if (input != allOrNoneCheckbox) {
                input.checked = checked;
            }
        }
    }
}
</script>
<apex:form id="frm">
    <apex:pageBlock >
        <apex:pageBlockButtons location="top">
            <apex:commandButton value="Search" action="{!searchprts}" reRender="product-table" />
        </apex:pageBlockButtons>
        <apex:pageBlockSection id="product-table" columns="1">
            <apex:pageBlockSectionItem >
                <apex:outputLabel value="Name" />
                <apex:inputText value="{!name}" />
            </apex:pageBlockSectionItem>
            <apex:pageBlockTable value="{!Products}" var="c">
                <apex:column >
                    <apex:facet name="header">
                        <apex:inputCheckbox id="chkbox" onclick="checkAllOrNone(this)"/>
                    </apex:facet>
                    <apex:inputCheckbox />
                </apex:column>
                <apex:column >
                    <apex:facet name="header">Name</apex:facet>
                    {!c.Name}
                </apex:column>
                <apex:column >
                    <apex:facet name="header" >amt</apex:facet>
                    <apex:outputText id="id1" value="{!c.amt__c}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">Qnty</apex:facet>
                    <apex:inputField id="id2" value="{!c.q__c}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">Total </apex:facet>
                    <apex:outputText id="id3" value="{!ttl }"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>

apex
public with sharing class Ctrl_ContactSearch
{
    public List<Product2> Products { get; set; }
    public String name { get; set; }
    public decimal total = 0;

    public Ctrl_ContactSearch()
    {
        total = 0;
        Products = new List<Product2>();
    }

    public PageReference searchprts()
    {
        Products = [select Id,Name,amt__c,q__c from Product2 where Name = :name];

    }
    public void ttl() {
       ttl = amt__c*q__c ;
    }
}

Also i would like to store the output in other fields of custom object.

A: Visualforce can't find the property ttl because you do not have a getter method available. You would need to change
public void ttl()

to
public void getttl()

or store the value in an instance variable with synthesized getters and setters (you already have one called total that you aren't using):
public Decimal ttl { get; set; }


text:
Q: How do I put to span next to each other on twitter bootstrap mobile view Hey im trying to achieve this look:
Problem is I can never put 2 spans next to each other they always stack up and im trying to not have that happen as you can see in the picture. Any Twitter Bootstrap CSS genius have an idea?
And just to be a bit more specific this is only for mobile view meaning that I am using the bootstrap class "visible-phone" on my container class.

A: From Bootstrap 3 Documentation
http://getbootstrap.com/css/#grid
Don't want your columns to simply stack in smaller devices? Use the extra small and medium device grid classes by adding .col-xs-* .col-md-* to your columns. See the example below for a better idea of how it all works.


text:
Q: Parse Cloud Code response is null after calling a function with callback I have a cloud code from which I call an external function.
The cloud code response is null but the console displays the response
my cloud code ;
Parse.Cloud.define("testccadd", async request => {
    try {
        var ccaddrequest = {
            conversationId: '123456789',
            email: 'email@email.com',
        };
        externalFunction (ccaddrequest, function (err, result) {
            console.log(result);
            return result;
        }) ;
    } catch (e) {
        console.log("Error");
    }
});

console.log (result); shows the values from the external function, but the return result; returns null
how can I get the external function response as response of my cloud code function ?

A: The problem is that your externalFunction uses a callback to return its result. That is an asynchronous event, meaning that it happens after your cloud functions has been processed.
The cloud function will execute var ccaddrequest... and then call externalFunction but it won't "wait" for externalFunction to call the callback function if it contains asynchronous commands.
So you need to wrap the externalFunction in a Promise (see how to promisify callbacks) and then await the result of it.
Plus you need to return the result of the Promise, so in your code you need to add
Parse.Cloud.define("testccadd", async request => {
    try {
        var ccaddrequest = {
            conversationId: '123456789',
            email: 'email@email.com',
        };
        var result = await externalFunctionPromise(...);
        return result;
    } catch (e) {
        console.log("Error");
    }
});


text:
Q: pytest fixture injection when decorator adds argument I'm trying to decorate test functions and return a wrapper that expects a fixture, but, it appears that pytest ignores the wrapper and looks to the wrapped function to determine which fixtures are needed.
contrived example:
def decorator(func):
    @functools.wraps(func)
    def _wrapper(some_fixture, *args, **kwargs):
        expected_results = some_fixture.load_results_for_case(func)
        observed_results = func(*args, **kwargs)
        assert expected_results == observed_results
    return _wrapper

@decorator
def test_some_feature():
    # some fancy code generating complex dataset
    return complex_dataset


text:
Q: How to save a layered pdf in R (via Sweave?) I've searched SO, Googled, read ?pdf, and come up dry as to the possibility of saving a plot as a pdf with layers that can be swtiched on and off in the pdf viewer margins. An example of what I'm talking about are the USGS quad topo-maps, which can be downloaded as pdfs with multiple layers, such as this (zipped pdf).
The following sentence in the pdf() help file sounds ominous, but I also wanted to check that I'm not misinterpreting it:
 The R graphics model does not distinguish graphics objects at the level
 of the driver interface.

I used to be able to save layered pdf's in Illustrator, but no longer have this program at my disposal. Perhaps someone can think of a workaround from within R? The data I'm using to map are large, but here's a toy example:
pdf("2objects.pdf")
plot(NULL, type = "n",xlim = c(0,1),ylim = c(0,1))
rect(0,.7,.7,0,border = "blue",lwd=2)
rect(.3,1,1,.3,border = "red",lty=2,lwd=2)
dev.off()

It looks like this (it's a png, but the above will give a pdf)

I'd like to be able to have the red and blue boxes as layers with visibility that can be switched on and off from within the pdf viewer.
Many thanks!
Edit: found thread in R-help (re: @mnel), and it looks to not be possible. I will still leave this question open, in case someone has come up with a nifty R-tastic workaround.
Edit (Sept 5th, 2012): I tried doing this via Sweave, and achieved partial success using the workaround posted here. This method produces a single pdf with 'layers' that can be switched on and off using hyperlinked text below the images. It uses 'animation' trickery to do so. While it is still not my ultimate desired outcome, it has the advantage of not depending on particular pdf viewers. I will still wait to see if someone posts a way to do layers, aka OCGs in a Sweave document, which I could then automate.
Edit (Sept 13, 2012): I posted my progress so far as an answer, using the code mentioned above. I was able to get it working in a more complex real world situation with no alterations to the code with overlays of different administrative and statistical boundaries within the US. In this case, I just named the different map overlays layer-0.pdf, layer-1.pdf, etc, and it worked without error. I still hope something better pops up here eventually.
Thanks all for you comments

A: I'm able to achieve this via ggplot.
library(ggplot2)
df <- data.frame(x = c(1,10), y = c(20,40), class = 1:2)
layered_plot <- ggplot(df, aes(xmin = x, xmax = x + 1, ymin = y, ymax = y + 2, fill = class)) +
geom_rect() +
opts(legend.position = "none")
# Now save this as pdf
ggsave(layered_plot, file="p1.pdf")

(This is just the png version for illustration but when I open the pdf in Illustrator, I can turn off the individual layers as needed).

A: Looks like the (tex) animation answer is the best I can come up with now. The following .Rnw file will create a pdf with a figure in the middle, and 2 text hyperlinks below it, which toggle visibility of the red and blue boxes independently. I found the Tex code that makes this work here. I've not looked at @Aaron's ocgtools suggestion yet, but will get there. Thanks all for your suggestions!
\documentclass{article}
%----------------------------------------------------------------%\
\usepackage[OT1]{fontenc}
\usepackage{Sweave}
\usepackage{animate}
\usepackage{hyperref}
\usepackage[margin=0.4in]{geometry}
%----------------------------------------------------------------%

\makeatletter
% command to create a toggle link
\newcommand{\ShowHideLayer}[3]{%
  % #1: anim No. (zero-based),
  % #2: layer No. (zero-based),
  % #3: link text
  \leavevmode%
  \pdfstartlink user {
    /Subtype /Link
    /Border [\@pdfborder]%
    /A <<
      /S/JavaScript
      /JS (
        \if at anim@useocg%
          if(a#1.fr[#2].state==true){
            a#1.fr[#2].state=false;
          }else{
            a#1.fr[#2].state=true;
          }
        \else
          if (a#1.fr[#2].display==display.visible){
            a#1.fr[#2].display=display.hidden;
          }else{
            a#1.fr[#2].display=display.visible;
          }
          this.dirty=false;
        \fi
      )
    >>
  }#3%
  \pdfendlink%
}

% command to create a link to show/hide all layers
\newcommand{\ShowHideAll}[2]{%
  % #1: anim No. (zero-based),
  % #2: link text
  \leavevmode%
  \pdfstartlink user {
    /Subtype /Link
    /Border [\@pdfborder]%
    /A <<
      /S/JavaScript
      /JS (
        var countvisible=0;
        for(var i in a#1.fr){
          \if at anim@useocg
            if(a#1.fr[i].state==true){countvisible++;}
          \else
            if (a#1.fr[i].display==display.visible){countvisible++;}
          \fi
        }
        if(countvisible){
          for(var i in a#1.fr){
            \if at anim@useocg
              a#1.fr[i].state=false;
            \else
              a#1.fr[i].display=display.hidden;
              this.dirty=false;
            \fi
          }
        }
        else{
          for(var i in a#1.fr){
            \if at anim@useocg
              a#1.fr[i].state=true;
            \else
              a#1.fr[i].display=display.visible;
              this.dirty=false;
            \fi
          }
        }
      )
    >>
  }#2%
  \pdfendlink%
}
\makeatother

\begin{document}

% heres the R-making of the plots, saved to working directory,
% which should be the folder containing this .Rnw file
% 3 versions of the same plot, one for each layer
<<echo = FALSE, hide = TRUE>>=
pdf("layer-0.pdf")
plot(NULL, type = "n", xlim = c(0, 1), ylim = c(0, 1), xlab = "", ylab = "")
dev.off()

pdf("layer-1.pdf")
plot(NULL, type = "n", xlim = c(0, 1), ylim = c(0, 1), axes = FALSE, xlab = "", ylab = "")
rect(0, .7, .7, 0, border = "blue", lwd = 2)
dev.off()

pdf("layer-2.pdf")
plot(NULL, type = "n", xlim = c(0, 1), ylim = c(0, 1), axes = FALSE, xlab = "", ylab = "")
rect(.3, 1, 1, .3, border = "red", lty = 2, lwd = 2)
dev.off()
@

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{center}
  %animated layer-set No. 0
  %                                          v-- frame rate ignored
  \animategraphics[width=1\linewidth,step]{1}{layer-}{0}{2}

  \ShowHideLayer{0}{1}{toggle red box}\\
  \ShowHideLayer{0}{2}{toggle blue box}\\
\end{center}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{document}


text:
Q: jqGrid Does Not Show The Returned JSON Data I use jqGrid in ASP.NET page.  In .aspx page, I have -

In .js file, I have -
var CASortInfo = {
    sortname: $('#MyTable').jqGrid('getGridParam', 'sortname'),
    sortorder: $('#MyTable').jqGrid('getGridParam', 'sortorder'),
    page: $('#MyTable').jqGrid('getGridParam', 'page'),
    rows: $('#MyTable').jqGrid('getGridParam', 'rows')
};

    $("#MyTable").jqGrid({
        url: "../Services/My.asmx/ReadMyTable",
        datatype: 'json',
        mtype: 'POST',
        prmNames: {
            search: "isSearch",
            nd: null,
            rows: "PageSize",
            page: "PageNumber",
            sort: "sortField",
            order: "sortOrder"
        },
        postData: { ID: $('#hfID').val() },
        ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
        serializeGridData: function (postData) {
            return JSON.stringify(postData);
        },
        colNames: ["", "My", "Date Created", "Notes", "Action"],
        colModel: [
            { name: "MyID", index: "MyID", resizable: false, hidden: true },
            { name: "MyName", index: "MyName", resizable: false, width: 250 },
            { name: "CreatedOn", index: "CreatedOn", resizable: false },
            { name: "Notes", index: "Notes", resizable: false },
            { name: "Buttons", formatter: ActionButtons, width: 70 }
        ],
        sortname: "CreatedOn",
        sortorder: "asc",
        ignoreCase: true,
        autowidth: true,
        shrinkToFit: true,
        height: "auto",
        pager: "#divMyTablePager",
        toppager: true,
        rowNum: 20,
        rowList: [5, 10, 20, 50],
        viewrecords: true,
        gridview: true,
        rownumbers: false,
        hoverrows: true,
        multiselect: false,
        jsonReader: {
            root: function (obj) { return obj.d.rows; },
            page: function (obj) { return obj.d.page; },
            total: function (obj) { return obj.d.total; },
            records: function (obj) { return obj.d.records; },
            repeatitems: false,
            id: "0"
        },
        beforeRequest: function () {
            CASortInfo = {
                sortname: $('#MyTable').jqGrid('getGridParam', 'sortname'),
                sortorder: $('#MyTable').jqGrid('getGridParam', 'sortorder'),
                page: $('#MyTable').jqGrid('getGridParam', 'page'),
                rows: $('#MyTable').jqGrid('getGridParam', 'rows')
            };
        },
        gridComplete: function () {

            $('#MyTable').jqGrid('setGridParam', {
                sortname: CASortInfo.sortname,
                sortorder: CASortInfo.sortorder,
                page: CASortInfo.page,
                rows: CASortInfo.rows
            });

                $("#divMyTable").show();
                $("#MyTable").setGridWidth($("#divMyTable").width());
        }
    });

I can see the responded JSon data as -
{"d":{"__type":"Core.DTO.JQGridModel","total":"1","page":"1","records":"1","rows":[{"MyID":"627d6ca3-5bbc-4aa8-9e53-76afe4869ae2","MyName":"This\u0027s a test.","CreatedOn":"\/Date(1394135983350)\/","Notes":"Yes","isActive":null}]}}

I can see breakpoint is hit in gridComplete.  What needs to be done to show the data grid with data?
Thanks,

A: Just found out that I messed up the case in divMyTable.   After it is corrected, it is working.  Thanks


text:
Q: I'm using Rails 5, but Rails is still requiring a database.yml file I'm using Rails 5 and I access my credentials by using RAILS_ENV=production EDITOR=vim rails credentials:edit. However, when I run rails c -e production, it gives me this error:
/usr/local/rvm/gems/ruby-2.5.8/gems/railties-5.2.4/lib/rails/application/configuration.rb:185:in `database_configuration': Cannot load database configuration:
Could not load database configuration. No such file - ["config/database.yml"] (RuntimeError)
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activerecord-5.2.4/lib/active_record/railtie.rb:133:in `block (2 levels) in <class:Railtie>'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:71:in `instance_eval'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:71:in `block in execute_hook'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:62:in `with_execution_control'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:67:in `execute_hook'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:52:in `block in run_load_hooks'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:51:in `each'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:51:in `run_load_hooks'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activerecord-5.2.4/lib/active_record/base.rb:328:in `<module:ActiveRecord>'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activerecord-5.2.4/lib/active_record/base.rb:27:in `<top (required)>'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `block in require_with_bootsnap_lfi'

Why is this file being required? How do I ignore it? Just for kicks, I set up a config/database.yml file that looks like this:
default: &default
  adapter: postgresql
  encoding: unicode
  pool: 200
  port: 25060
production:
  <<: *default
  host: <%= Rails.application.credentials.production[:host] %>
  username: <%= Rails.application.credentials.production[:username] %>
  password: <%= Rails.application.credentials.production[:password] %>
  database: <%= Rails.application.credentials.production[:database] %>
development:
  <<: *default
  host: <%= Rails.application.credentials.development[:host] %>
  username: <%= Rails.application.credentials.development[:username] %>
  password: <%= Rails.application.credentials.development[:password] %>
  database: <%= Rails.application.credentials.development[:database] %>

However, when I run rails c -e production, I still get this error:
(erb):14:in `<main>': Cannot load database configuration:
undefined method `[]' for nil:NilClass (NoMethodError)
        from /usr/local/rvm/rubies/ruby-2.5.8/lib/ruby/2.5.0/erb.rb:876:in `eval'
        from /usr/local/rvm/rubies/ruby-2.5.8/lib/ruby/2.5.0/erb.rb:876:in `result'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/railties-5.2.4/lib/rails/application/configuration.rb:172:in `database_configuration'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activerecord-5.2.4/lib/active_record/railtie.rb:133:in `block (2 levels) in <class:Railtie>'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:71:in `instance_eval'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:71:in `block in execute_hook'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:62:in `with_execution_control'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:67:in `execute_hook'
        from /usr/local/rvm/gems/ruby-2.5.8/gems/activesupport-5.2.4/lib/active_support/lazy_load_hooks.rb:52:in `block in run_load_hooks'

I can access the development instance just fine, but not production. Not quite sure why this file is required if Rails 5 is supposedly moving away from it.


text:
Q: Is there a way to compare incidences of 2 diseases in the same cohort? I would like to compare incidences of 2 diseases in the same cohort for the past 10 years.
Eg. I want to see whether there's an association between incidence of heart disease and incidence of influenza in the same cohort of people for the past 10 years.
Is this doable? What statistical method should I use? Thank you

A: Suppose you have table:
        ND  noHD
Flu     10    5
noFlu    5   10

Perhaps suggestive of association, but not significant.
Not enough data.
TBL = rbind(c(10,5), c(5,10))
fi        Fisher's Exact Test for Count Data

data:  TBL
p-value = 0.1431
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
  0.7054268 23.9214257
sample estimates:
odds ratio
  3.805039

However, if you have table:
        ND   noHD
Flu     102    53
noFlu    49   105

Roughly the same proportions as in the former example,
but with about ten times the number of subjects. Highly
significant.
TBL2 = rbind(c(102,53), c(49,105))
fisher.test(TBL2, alt="two")

        Fisher's Exact Test for Count Data

data:  TBL2
p-value = 2.445e-09
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
 2.498319 6.820386
sample estimates:
odds ratio
  4.103514


text:
Q: kafka-connect-jdbc does not fetch consecutive timestamp from source I use kafka-connect-jdbc-4.0.0.jar and postgresql-9.4-1206-jdbc41.jar
configuration of connector of kafka connect
{
  "connector.class": "io.confluent.connect.jdbc.JdbcSourceConnector",
  "mode": "timestamp",
  "timestamp.column.name": "updated_at",
  "topic.prefix": "streaming.data.v2",
  "connection.password": "password",
  "connection.user": "user",
  "schema.pattern": "test",
  "query": "select * from view_source",
  "connection.url": "jdbc:postgresql://host:5432/test?currentSchema=test"
}

I have configured two connectors one source and another sink using the jdbc driver, against a postgresql database ("PostgreSQL 9.6.9")
everything works correctly
I have doubts in how the connector collects the source data, looking at the log I see that between the execution of the queries there is a time difference of 21 seconds
11/1/2019 9:20:18[2019-01-11 08:20:18,985] DEBUG Checking for next block of results from TimestampIncrementingTableQuerier{name='null', query='select * from view_source', topicPrefix='streaming.data.v2', timestampColumn='updated_at', incrementingColumn='null'} (io.confluent.connect.jdbc.source.JdbcSourceTask)
11/1/2019 9:20:18[2019-01-11 08:20:18,985] DEBUG TimestampIncrementingTableQuerier{name='null', query='select * from view_source', topicPrefix='streaming.data.v2', timestampColumn='updated_at', incrementingColumn='null'} prepared SQL query: select * from view_source WHERE "updated_at" > ? AND "updated_at" < ? ORDER BY "updated_at" ASC (io.confluent.connect.jdbc.source.TimestampIncrementingTableQuerier)
11/1/2019 9:20:18[2019-01-11 08:20:18,985] DEBUG executing query select CURRENT_TIMESTAMP; to get current time from database (io.confluent.connect.jdbc.util.JdbcUtils)
11/1/2019 9:20:18[2019-01-11 08:20:18,985] DEBUG Executing prepared statement with timestamp value = 2019-01-11 08:17:07.000 end time = 2019-01-11 08:20:18.985 (io.confluent.connect.jdbc.source.TimestampIncrementingTableQuerier)
11/1/2019 9:20:19[2019-01-11 08:20:19,070] DEBUG Resetting querier TimestampIncrementingTableQuerier{name='null', query='select * from view_source', topicPrefix='streaming.data.v2', timestampColumn='updated_at', incrementingColumn='null'} (io.confluent.connect.jdbc.source.JdbcSourceTask)

11/1/2019 9:20:49[2019-01-11 08:20:49,499] DEBUG Checking for next block of results from TimestampIncrementingTableQuerier{name='null', query='select * from view_source', topicPrefix='streaming.data.v2', timestampColumn='updated_at', incrementingColumn='null'} (io.confluent.connect.jdbc.source.JdbcSourceTask)
11/1/2019 9:20:49[2019-01-11 08:20:49,500] DEBUG TimestampIncrementingTableQuerier{name='null', query='select * from view_source', topicPrefix='streaming.data.v2', timestampColumn='updated_at', incrementingColumn='null'} prepared SQL query: select * from view_source WHERE "updated_at" > ? AND "updated_at" < ? ORDER BY "updated_at" ASC (io.confluent.connect.jdbc.source.TimestampIncrementingTableQuerier)
11/1/2019 9:20:49[2019-01-11 08:20:49,500] DEBUG executing query select CURRENT_TIMESTAMP; to get current time from database (io.confluent.connect.jdbc.util.JdbcUtils)
11/1/2019 9:20:49[2019-01-11 08:20:49,500] DEBUG Executing prepared statement with timestamp value = 2019-01-11 08:20:39.000 end time = 2019-01-11 08:20:49.500 (io.confluent.connect.jdbc.source.TimestampIncrementingTableQuerier)

the first query collects data between 08: 17: 07.000 and 08: 20: 18.985, but the second gathers data between 08: 20: 39.000 and 08: 20: 49.500 .. between both there are 21 seconds of difference in which there may be records ...
11/1/2019 9:20:18[2019-01-11 08:20:18,985] DEBUG Executing prepared statement with timestamp value = 2019-01-11 08:17:07.000 end time = 2019-01-11 08:20:18.985
11/1/2019 9:20:49[2019-01-11 08:20:49,500] DEBUG Executing prepared statement with timestamp value = 2019-01-11 08:20:39.000 end time = 2019-01-11 08:20:49.500

I assume that one of the data is the last record obtained and the other value the timestamp of the moment
I can not find an explanation about this
Is the normal operation of the connector?
Should you assume that you are not always going to collect all the information?

A: The JDBC connector is not guaranteed to retrieve every message. For that, you need log-based Change Data Capture. For Postgres that is provided by Debezium and Kafka Connect.
You can read more about this here.
Disclaimer: I work for Confluent, and wrote the above blog
Edit: This is now a recording available of the above blog too from ApacheCon 2020:  https://rmoff.dev/no-more-silos


text:
Q: HH:MM:SS:Msec to HH:MM:SS in stored procedure I have a stored procedure which update a table based on such calculation and the calculation is done as column name (Calendatedate) - (Current System Date Time) and update this information to a column (TimeSpent) and display the value in  Hh:Mm:SS:Msec format.
The query is working fine but I want to update it in such a way so that the time spent should be only HH:MM:SS format. Please help me that how I remove that Msec from the time spent.
CREATE procedure St_Proc_UpdateTimeSpent
@timeEntryID int,
@status int output
as begin
set nocount on;
declare @Date dateTime;
set @Date=GETDATE();
    update Production set TimeSpent=(SELECT CONVERT(VARCHAR(20),DateAdd(SS,Datediff(ss,CalendarDate, @Date)%(60*60*24),0),114)),
    IsTaskCompleted=1
    where productionTimeEntryID=@timeEntryID
    set @status=1;
    return @status;
end

A: You can just use style 108 instead of 114 in the CONVERT function to get only the hh:mm:ss:
CREATE PROCEDURE dbo.St_Proc_UpdateTimeSpent
     @timeEntryID int,
     @status int output
AS BEGIN
   SET NOCOUNT ON;

   DECLARE @Date DATETIME;
   SET @Date = GETDATE();

   UPDATE dbo.Production
   SET TimeSpent = CONVERT(VARCHAR(20), DATEADD(SS, DATEDIFF(ss, CalendarDate, @Date)%(60*60*24),0), 108),
       IsTaskCompleted = 1
   WHERE
       productionTimeEntryID = @timeEntryID

   SET @status = 1;

   RETURN @status;
END

See the excellent MSDN documentation on CAST and CONVERT for a comprehensive list of all supported styles when converting DATETIME to VARCHAR (and back)
BTW: SQL Server 2008 also introduced a TIME datatype which would probably be a better fit than a VARCHAR to store your TimeSpent values ... check it out!


text:
Q: How to not send a referrer from a link in html I think I saw someday a way to create a link  without sending the page that the user was in originally. Is that possible? Or do we need to use a redirector to hide the location of the previous site?
EDIT: If you have an idea for a server-side option to anonymise the link you're welcome.

A: Check out this section on Wiki on referrer hiding.

Most major browsers do not send the referrer header when they are instructed to redirect using the "Refresh" HTTP header. However, this method of redirection is discouraged by the W3C.

A: Example

http://www.w3.org/TR/html5/links.html#link-type-noreferrer
The noreferrer keyword may be used with a and area elements. This keyword does not create a hyperlink, but annotates any other hyperlinks created by the element (the implied hyperlink, if no other keywords create one).
It indicates that no referrer information is to be leaked when following the link.
If a user agent follows a link defined by an a or area element that has the noreferrer keyword, the user agent must not include a Referer (sic) HTTP header (or equivalent for other protocols) in the request.

A: There is no way to do this.
In fact this param is controlled on the client side. Depending on the browser, some just never send referer or fakes.
You should not be able to do it in any way.
But here is 2 tips:

*

*Use a redirector page

*Offer to the user a copy/paste function and then, open a new window to let him able to paste and go.

A: I recommend to using a service like https://anon.click/
Also in HTML5 there is the rel="noreferrer" which could be used.

A: I use a combination of multiple answers I see here.
<a href='data:text/html;charset=utf-8,<meta http-equiv="refresh" content="0;url=http://www.google.com/">Open Link' rel=noreferrer target=_blank>A link without referer

I tested with Firefox, Chrome, iOS Safari, and Samsung Android default browser. And it works.
Even if a browser sends a referrer, it will not be the website since the page address is "data:...". That's why it is much safer than creating a page that does this.

A: Depending on what your circumstances are you could use something like anonym.to - if you trust these services.
From your tag I assume you do not want to use (or have access to) server-side tools like PHP. In that case this will be tricky. I don't know whether this is even possible at all with just HTML/Javascript.


text:
Q: SBJson displays null I am trying to parse some json data with SBJson to show the current temperature. The example code from this tutorial works perfect: Tutorial: Fetch and parse JSON
When I change the code to my json feed i get a null. I am kind of new to JSON but followed every tutorial and documentation I found. The json source i used: JSON Source
My code with sbjson:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;

NSArray* currentw = [(NSDictionary*)[responseString JSONValue] objectForKey:@"current_weather"];

//choose a random loan
NSDictionary* weathernow = [currentw objectAtIndex:0];

//fetch the data
NSNumber* tempc = [weathernow objectForKey:@"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:@"weatherCode"];

NSLog(@"%@ %@", tempc, weatherCode);

and of course I have already implemented the other sbjson code.

A: There is no current_weather key in the JSON data you posted. The structure is:
{ "data": { "current_condition": [ { ..., "temp_C": "7", ... } ], ... } }

Here's a visual representation:

Therefore, to get to temp_C, you'd need to first obtain the top-level data property:
NSDictionary* json = (NSDictionary*)[responseString JSONValue];
NSDictionary* data = [json objectForKey:@"data"];

then, from that, obtain the current_location property:
NSArray* current_condition = [data objectForKey:@"current_condition"];

and finally, from the current_location array, get the element you're interested in:
NSDictionary* weathernow = [current_condition objectAtIndex:0];

Also note that temp_C and weatherCode are strings, not numbers. To transform them to numbers, instead of:
NSNumber* tempc = [weathernow objectForKey:@"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:@"weatherCode"];

you could use something like:
int tempc = [[weathernow objectForKey:@"temp_C"] intValue];
int weatherCode = [[weathernow objectForKey:@"weatherCode"] intValue];

(or floatValue / doubleValue if the value is not supposed to be an int, but rather a float or a double)
You would then use %d (or %f for float / double) as a format string:
NSLog(@"%d %d", tempc, weatherCode);

A: Use NSJSONSerialization instead of JSONValue.
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary* jsonDict = [NSJSONSerialization
                                      JSONObjectWithData:data
                                      options:kNilOptions
                                      error:&error];
 NSLog(@"jsonDict:%@",jsonDict);

In your link, there is no current_weather key.
NSString* tempc = [[[[jsonDict objectForKey:@"data"] objectForKey:@"current_condition"] objectAtIndex:0] objectForKey:@"temp_C"];

A: Provided link returns json without current_weather parameter. There is only current_condition parameter, please review this.


text:
Q: Non-negativity of an integer Describe all non negative integers using only the constant symbols $0,1$, operations $+,\cdot$ and relation $=$ on $\mathbb Z$.
In the reals, a similar description is simple, we just say $x\geq 0\iff \exists y: y\cdot y = x$.
In the integers, however, that doesn't work. There's no $\sqrt{2}\in\mathbb Z$, for instance.
We could say
$$x\geq 0 \iff x=0\lor x=1\lor x=1+1\lor\ldots $$
but that's not satisfactory since it's not finite.
I always seem to be stuck defining it via itself, provided the expression is finite. What am I missing?
It would also be sufficient to describe negative integers.

A: As per orangeskid's reference. Lagrange's theorem does the trick.


text:
Q: Get result of command line request and open file I use following function :
std::string exec(const char* cmd) {
    std::array<char, 128> buffer;
    std::string result;
    std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }
    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
        result += buffer.data();
    }
    return result;
}

std::string filepath = exec("locate filename.txt");

It returns a std::string and I convert it using .c_str() in :
std::ifstream file(filepath.c_str(), ios::in);
But after I try :
if(file)
{
    ...
}
else
{
    std::cerr << "File missing : " + filepath << std::endl;
}

And I get :
File missing : /path/to/file

A: Unix command locate outputs newline ('\n') character after each file name, so you need to strip this character from the output of locate command before using it as file name.  You could probably use method pop_back of class string for this.
Also note, that locate may output several file names and file names may contain newline characters inside.


text:
Q: Windows 10 How to remove the shared folder icon Can't seem to figure out how to remove these little annoying icons that show on the two HDDs I've shared over LAN. Any ideas?
Changing the HDD icon will only do that, and the two people will stay there. I can't find a way to change icons for the groups that I'm sharing it with either, as I was hoping if I just changed the icon to the part of the HDD that is missing it will look okay, or an .ico that's transparent.
The image link below shows what I mean.
Icons on the HDD:

Was hoping I could change these icons to get around it:

A: Open Regedit and make a string at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Icons
The string should be named "28".
Enter its value as any blank Icon file. Maybe shell32.dll,-50
Rebuild the icon cache and restart the pc or just Explorer.


text:
Q: Priority of assign statements in i3 configuration I want to assign a specific app to a workspace in i3. That app is ranger and I want to launch it via alacritty
I've already chosen to launch alacritty in ws_term workspace and I want to launch ranger in ws_fm.
Running xprop returns two classes for ranger -> "Ranger", "Alacritty"
In my i3/config file I have the following directives (in this exact order):
assign [class="Alacritty"] $ws_term
...
assign [instance="Ranger"] $ws_fm

The problem is that even though I'm explicitly specifying Ranger as last, it always picks the "Alacritty" class and places the app in the wrong workspace. Same issue if I use title= or class= instead of instance.
How can I set the priority in the assign statements in case there are multiple matches for an app?

A: This is described in the userguide:

Assignments are processed by i3 in the order in which they appear in
the config file. The first one which matches the window wins and later
assignments are not considered.

The ranger assignment must be before the alacritty assignment.


text:
Q: Creating a column that repeats adjacent values in R data.frame I want to create a column y that mirrors the value of another column x and sets the adjacent values to the non-NAs.
Let's say I've got a data.frame df:
df = data.frame('index' = 1:10, 'x' = c(NA, NA, 1, NA, NA, NA, 2, NA, NA, NA))

> df
   index  x
1      1 NA
2      2 NA
3      3  1
4      4 NA
5      5 NA
6      6 NA
7      7  2
8      8 NA
9      9 NA
10    10 NA

Now I want to create the column df$y which forms some 'context' around the non-NAs in df$x. Specifically, value of these df$x (here: 1 and 2) applies to the their index PLUS one before and one after their index, so that:
> df
   index  x  y
1      1 NA NA
2      2 NA  1
3      3  1  1
4      4 NA  1
5      5 NA NA
6      6 NA  2
7      7  2  2
8      8 NA  2
9      9 NA NA
10    10 NA NA

I've tried to do this by finding the relevant starting and ending indices of the "context" around the 1 and the 2 with:
temp_list = sapply(df$index, function(i){
  if(!is.na(df$x[i])){
      target_index_start = i - 1
      target_index_end = i + 1
    mini_context_iter = df$x[target_index_start:target_index_end]
  } else {
    NULL
  }
})

... and this returns a nice list.
The problem is that this does not seem to handle the indices that are outside of the -1:+1 context. A related question is this SO post but it stops before creating the new column.
Any ideas how I could address this more precisely?

A: library(tidyverse)
df%>%mutate(y=coalesce(x,lead(x),lag(x)))
   index  x  y
1      1 NA NA
2      2 NA  1
3      3  1  1
4      4 NA  1
5      5 NA NA
6      6 NA  2
7      7  2  2
8      8 NA  2
9      9 NA NA
10    10 NA NA


text:
Q: How can I put repeated jQuery code into a subroutine or function? I am a jQuery newbie and I have created my first functioning program with it. It contains a series of hyperlinks on an image, and when you click on a word (the hyperlink), it invokes some jQuery that changes the look of the page, and calls an Ajax routine that performs a search and displays its results.
My problem is that I have a number of different hyperlinks, all of which do essentially the same thing, with only a simple character string that is different in the jQuery that processes it.
I am sure there is a good way to create a chunk of code once that can be executed passing the character string as a parameter, but I cannot yet figure out how to do this. Can someone suggest the cleanest way to do this?
Some of my code follows, but PLEASE IGNORE THE ## NOTATION as this is in ColdFusion which converts it to a single # before it hits the browser.
$( "##Shoulders" ).click(function() {
    $("##div1").animate({ height:0 }, 500).css('overflow', 'visible').empty();
    $("##div2").animate({ height:0 }, 500).css('overflow', 'visible').empty();
    $('##div3spacer').ScrollTo();
    $("##div3").load("ThreeSearchExercise.cfm?A=Shoulders", function () {
        $('.js-lazyYT').lazyYT();
        });
    });

$( "##Arms" ).click(function() {
    $("##div1").animate({ height:0 }, 500).css('overflow', 'visible').empty();
    $("##div2").animate({ height:0 }, 500).css('overflow', 'visible').empty();
    $('##div3spacer').ScrollTo();
    $("##div3").load("ThreeSearchExercise.cfm?A=Arms", function () {
        $('.js-lazyYT').lazyYT();
        });
    });

A: The only thing that changes is A parameter. So you can do this
function clickHandler() {
    $("##div1,##div2").animate({ height: 0 }, 500).css('overflow','visible').empty();
    $('##div3spacer').ScrollTo();
    $("##div3").load("ThreeSearchExercise.cfm?A=" + this.id, function() {
       $('.js-lazyYT').lazyYT();
    });
}

And bind like this
$('##Shoulders, #Arms').click(clickHandler);

A: You are defining anonymous functions inside each click() call. Use a single named function instead.
function handleClick() {
    function() {
        $("##div1").animate({ height:0 }, 500).css('overflow', 'visible').empty();
        $("##div2").animate({ height:0 }, 500).css('overflow', 'visible').empty();
        $('##div3spacer').ScrollTo();
        $("##div3").load("ThreeSearchExercise.cfm?A=Arms", function () {
            $('.js-lazyYT').lazyYT();
        });
    }
}

$( "##Shoulders" ).click(handleClick);
$( "##Arms" ).click(handleClick);


text:
Q: Show that the variety of semilinear Heyting/Brouwerian algebras is not generated by any single finite Heyting/Brouwerian chain Show that the variety of semilinear Heyting/Brouwerian algebras is not generated by any single finite Heyting/Brouwerian chain where a Brouwerian algebra is a Heyting algebra which does not include a bottom element and semilinear means that it is a subdirect product of chains.
I was hoping if we assume a single finite chain can generate the variety then we would get a contradiction considering an infinite algebra but I haven't been able to make this work.

A: Assuming that Brouwerian algebras are the same as Heyting algebras but without the $0$ element in the signature (so that, in the infinite case, they might not have a $0$ element at all), and checking the details of the proof of a well-known characterization of congruences on Heyting algebras, I came to the conclusion that the proof doesn't have any reference to the $0$ element, and so the same characterization holds for congruences on Brouwerian algebras.
So, if $\mathbf B$ is a Brouwerian algebra, and $\theta \subseteq B^2$, then $\theta$ is a congruence of $\mathbf B$ iff for some filter $F$ of $\mathbf B$,
$$\theta = \{(a,b)\in B^2 : (a\to b) \wedge (b\to a) \in F\}.$$
This allows us to use the same argument for Heyting or Brouwerian algebras.
So let $\mathbf A$ be a Heyting algebra or a Brouwerian algebra.
Then $\mathbf A$ is subdirectly irreducible iff its congruence lattice has precisely one atom $\mu$ (sometimes called the monolith), which is below every congruence except the identity.
Given the above characterization of congruences, this happens precisely if there is a co-atom $u$ in the lattice reduct of that algebra, so that
$$\mu = \{u,1\}^2 \cup \{(a,a):a\in A\}.$$
Now, consider a Heyting or Browerian algebra $\mathbf A$ whose lattice reduct is an infinite chain with an element $u$ such that $u \prec 1$.
Then $\mathbf A$ is subdirectly irreducible, so it can't be a subdirect product of finite algebras.


text:
Q: How to see real ram usage for each program in windows 7 when i press ctrl-alt-del and open Task manager I see that Memory is  used  at 80% (Performance tab), but if I add all the memory usage values for each program from the Processes tabs there's no way it adds up to 80% ! How can I see the real memory usage for each app?
PS: I found that view... select columns let's me show more data. So I checked all memory columns and the only one that could reach that 80% value is "Peak working set". There the values are much higher and I see a huge 2.5 GB usage from "svchost". But svchost is some kind of library, how can I see what program makes it use so much?
Here's a screenshot to see what I mean:

Total RAM is 8 GB and usage is always at 6 GB +
PPS:
closing virtualbox freed a lot of RAM, down to 50%, but why doesn't the virtualbox real ram usage show up in task manager?

A: The svchost.exe is a container to start Windows services. Windows 7 has a bug, which causes a large memory usage of the WindowsUpdate service. Microsoft fixed it in several Windows Update Client updates. Install the latest one from December 2015 to fix the memory usage.
For a detailed memory usage overview, always use RAMMap.


text:
Q: rails link_to image_tag put I need to change the following link to use a put method, but I cannot figure out where to add it!
= link_to image_tag('/images/icons/button-reject.png', :title => 'reject request'), user_request_deny_path(:user_id => req.user_id, :id => req.id)

A: Try:
= link_to image_tag('/images/icons/button-reject.png', :title => 'reject request'), user_request_deny_path(:user_id => req.user_id, :id => req.id), :method => :put

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Options
method: symbol of HTTP verb - This modifier will dynamically create an HTML form and immediately submit the form for processing using the HTTP verb specified. Useful for having links perform a POST operation in dangerous actions like deleting a record (which search bots can follow while spidering your site). Supported verbs are :post, :delete, :patch, and :put. Note that if the user has JavaScript disabled, the request will fall back to using GET. If href: '#' is used and the user has JavaScript disabled clicking the link will have no effect. If you are relying on the POST behavior, you should check for it in your controller's action by using the request object's methods for post?, delete?, patch?, or put?.

A: link_to(
  image_tag('/images/icons/button-reject.png', :title => 'reject request'),
  user_request_deny_path(:user_id => req.user_id, :id => req.id),
  :method => :put
)


text:
Q: How to determine nav-items to get full required width automatically I'm working with Bootstrap 3 and I'm trying to make a header navbar. Here is my code:

        <button class="navbar-toggler custom-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                     Home

                     Courses

                     E-learning products

                     Articles

                     Events

And the result looks like this:

As you can see the menu nav-item E-learning Products does not have enough space to place correctly in the place of nav-item.
However the other nav-items has extra space (as I mentioned out in the image).
So I need to make sure that every nav-item has enough required space based on the length of  links of nav-items.
And here comes the CSS code of this navbar:
/* Navbar */

        .has-navbar{
            margin-top:-10px;
            width:100%;
            height:30px;
        }

        .navbar{
            background-color: #fff !important;
            height:100%;
        }

        .nav-item{
            height:30px;
            width:130px !important;
        }

        .nav-item a{
            font-size:13px;
            font-weight: bold;
        }

        .first-item{
            margin-right:-50px !important;
        }

So here I tried setting width:130px !important; for .nav-item and it didn't work out well. I also tried width:100%; and this is the result:

So how can I properly place each nav-item menu link properly in their required space so the menu links does NOT have extra space AND not enough space?

A: So what you can do is set its width to max-content, which will be the maximum width that the content contained within can be.
Before(with width: 130px !important;):

After(with width: max-content;):

.nav-item{
   height:30px;
   //width:130px !important;
   width: max-content;
}

Note: If you think it's too short, you could set a min-width value to whatever you like.


text:
Q: Reading and parsing raw data from JSON file I am using QzTray to print receipt through my nodejs app. I have to create a json array that looks like this
[
    '\x1B'+'\x40',
    '\x1B'+'\x61'+'\x31',
    'Beverly Hills, CA  90210'+'\x0A',
    '\x0A',
    'www.qz.io'+'\x0A',
    '\x0A',
    '\x0A',
    'May 18, 2016 10:30 AM'+'\x0A',
    '\x0A',
    '\x0A',
    '\x0A',
    'Transaction # 123456 Register: 3'+'\x0A',
    '\x0A',
    '\x0A',
    '\x0A',
    '\x1B'+'\x61'+'\x30',
    'Baklava (Qty 4)       9.00'+'\x1B'+'\x74'+'\x13'+'\xAA',
    '\x0A',
    'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+'\x0A',
    '\x1B'+'\x45'+'\x0D',
    'Here\'s some bold text!',
    '\x0A',
    '\x1B'+'\x45'+'\x0A',
    '\x1D'+'\x21'+'\x11',
    'Here\'s large text!',
    '\x0A',
    '\x1D'+'\x21'+'\x00',
    '\x1B'+'\x61'+'\x32',
    '\x1B'+'\x21'+'\x30',
    'DRINK ME',
    '\x1B'+'\x21'+'\x0A'+'\x1B'+'\x45'+'\x0A',
    '\x0A'+'\x0A',
    '\x1B'+'\x61'+'\x30',
    '------------------------------------------'+'\x0A',
    '\x1B'+'\x4D'+'\x31',
    'EAT ME'+'\x0A',
    '\x1B'+'\x4D'+'\x30',
    '------------------------------------------'+'\x0A',
    'normal text',
    '\x1B'+'\x61'+'\x30',
    '\x0A'+'\x0A'+'\x0A'+'\x0A'+'\x0A'+'\x0A'+'\x0A',
    '\x1B'+'\x69',
    '\x10'+'\x14'+'\x01'+'\x00'+'\x05',
  ]

The problem is that when I try to parse this file using JSON.parse() , I always get the error
Uncaught SyntaxError: Unexpected token ' in JSON at position 7
    at JSON.parse (<anonymous>)
    at print (electronAPI_1.0.js:41)
    at HTMLInputElement.onclick (index.html:15)

Here is the code I use if it can help
var jsonConfig1 = JSON.parse(fs.readFileSync('couponConfig1.json', 'utf8'));

A: Your JSON contains single quotes, rather than double quotes, which will throw an error.

You are also using ANSI escape codes, versus UTF-16 codes. UTF-16 codes are what JSON use, therefore producing an error when your Javascript attempts to read the JSON.

It's also possible you were using UTF-8 escape codes, which share 127 identical characters to ANSI. In that case, you could use http://www.fileformat.info/info/unicode/ to convert your commands to UTF-16.


text:
Q: django insert table with form inputs manually I need to have form input data as values sent to my table field. Problem is I can't do that the usual way, because the form is tied to another model. But I also need to populate this model with same form.
payment = SitePayment.objects.create(
                    user=request.user,
                    charge=charge.id,
                    site=psite,
                    # address=form.address,
                    # zipcode=form.zipcode,
                    # city=form.city,
                    # country=form.country,
                )

This was to me the simpler and logical way to go about it, but it doesn't work. Is there a way to have form inputs inserted into this model when manually inserting a table?
I can provide more code, but I thought it would be really messy for you to understand, so I'm trying this way.

A: I found the solution, which was incredibly simple and I now feel incredibly stupid. I'm new to django/python, though, so please no anger.
payment = SitePayment.objects.create(
                    user=request.user,
                    charge=charge.id,
                    site=psite,
                    address=form.cleaned_data['address'],
                    zipcode=form.cleaned_data['zipcode'],
                    city=form.cleaned_data['city'],
                    country=form.cleaned_data['country'],
                )

It should of course be "form.cleaned_data" and not just "form."


text:
Q: A problem related to diagonalizable matrix If $A$ is a diagonalizable matrix in $M_n(\mathbb R)$ such that $A^k=I_n$ for some positive integer $k\geq 1$, then show that $A^2=I_n$.
Here $A$ satisfies $(x^k-1)=(x-1)(x^{k-1}+x^{k-2}+\cdots+1)$. So minimal polynomial must divide it, if minimal polynomial is $(x-1)$ then result holds. but i can't further proceed. Please someone help.Thanks in advance.

A: They key fact is that you have stated $A$ is diagonalisable over the real numbers.  So we have
$$A=P\pmatrix{\lambda_1\cr &\ddots\cr &&\lambda_n\cr}P^{-1}$$
and hence
$$A^k=P\pmatrix{\lambda_1^k\cr &\ddots\cr &&\lambda_n^k\cr}P^{-1}\ .$$
Since this is the identity we have $\lambda_j^k=1$; but $\lambda_j$ is real and so $\lambda_j=\pm1$ for every $j$.  Hence
$$A^2=P\pmatrix{\lambda_1^2\cr &\ddots\cr &&\lambda_n^2\cr}P^{-1}=I\ .$$

If the matrix is only diagonalisable over $\Bbb C$ the result need not be true.  For example, if
$$A=\pmatrix{0&1\cr-1&0\cr}$$
then $A^4=I$ but $A^2\ne I$.


text:
Q: Music player for Linux which remembers the playback position I'm looking for a music player for my Ubuntu Karmic desktop. I need the following features:

*

*supports multiple playlists

*remembers the playback position (file and time) for each playlist

*preferably, remembers playback position even when the process is killed

*lets the user adjust playback speed, without changing the pitch

I don't care if it's a GUI or command-line player or it uses a client-server model.
I've tried Rhythmbox, which doesn't have features 2., 3. and 4.
Which player would you recommend?

A: SMPlayer seems to meet most or all of your requirements (and more).
SMPlayer - Free Media Player for Windows and Linux with Youtube support - Official Site
http://smplayer.sourceforge.net/

*

*supports multiple playlists YES

*remembers the playback position(file and time) for each playlist YES

*preferably, remembers playback position even when the process is killed NOT SURE

*lets the user adjust playback speed, without changing the pitch YES

A: Since I couldn't find such a player, I implemented one for my own use as a Python script, which supports playing .m3u files, and calls mplayer with the proper -ss value to resume playback where it left off last time. Get it from http://raw.github.com/pts/mplaylist/master/mplaylist (project page: http://github.com/pts/mplaylist).

A: Just use mpv
for me on ubuntu
sudo apt install mpv
then
mpv --save-position-on-quit *
This save all position for all file by obtaining md5
My alias( in .bashrc):
alias mpvsp='mpv --save-position-on-quit --osd-level 3 --osd-align-y bottom --osd-align-x right --osd-color 0/1/1  --osd-font-size 30'

NOT support:
3. preferably, remembers playback position even when the process is killed


text:
Q: Implementation of custom list view ive been messing around in android and have made my first screen. Its nothing much, has some values and a button on it. When i click the button i am trying to laod a new page with a custom list view
for this purpose i am using some code i found on here at Custom ListView Android in one of the responses.
It lists the code for the class that builds and it also lists the xml which defines a row i assume?
What i am stuck with is, when i click the button on my interface, how do i get that list view shown in the example above to display as the next page? Is it simply just calling
Intent intent = new Intent("com.testproj.MYLIST");...
or do i need to build an interface of some sort then add it? I am really struggling to break the mould of traditional thought process from Java and its killing me.
Thanks

A: Assuming you are using the code described in the link that you have referenced, you only have to do the following:
Intent intent = new Intent(InitialActivity.this, YourListViewActivity.class);
startActivity(intent);

By the way, don't forget to reference YourListViewActivity in your manifest file.
<activity android:name="Package.YourListViewActivity">
</activity>

A: I suppose your list view is a ListActivity. See here to learn how to start an activity in Android: http://developer.android.com/guide/topics/fundamentals/activities.html#StartingAnActivity
I would also recommend to read the rest of the basic stuff on the developers site cited above.


text:
Q: Application context invalid in maven test Upon running 'mvn test' I get the following error(s):

java.lang.IllegalStateException: Failed to load ApplicationContext ...
  Caused by: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 14 in XML document from class path resource [applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'.

I've pasted my app context @ http://pastebin.com/24fKpgGr. Line 14, which is highlighted, seems fine; anyone see what is possibly wrong?
Thanks.

A: You missed t in http:
xmlns:xsi="htp://www.w3.org/2001/XMLSchema-instance"


text:
Q: Is there any way to clear out cache of S3 using Laravel? I am using a JSON file from the s3 which is uploaded after certain changes are made in the system. Due to the cache, I'm not getting the updated JSON even though is it deleted before the new one gets uploaded.

A: Laravel itself doesn't have anything for that but the AWS PHP SDK does.
You basically want to invalidate the file (createInvalidation) so that the next time a request is made for that file, CloudFront will fetch a fresh copy rather than serving a cached copy. Alternatively you can use file versioning so that you don't have to invalidate files.


text:
Q: Covariance matrix always positive semidefinite? I actually was perusing here right now to see if anything could explain a result I have been getting - of a covariance matrix which has a negative eigenvalue, yet the correlation matrix does not - but got a big surprise when I see all these statements that covariance matrices are always positive semidefinite.
I have certainly not been getting this result. I get LOTS of negative eigenvalues when using the covariance matrix of things that are pairwise at least rather correlated. For instance, the correlation between various exponentially weighted averages of random walks with different time constants. I only need to get into the 30s of them with time constants increasing in a geometric sequence with a factor of 1.04 (in other words, 1, 1.04, 1.04^2) and BAM. Negative eigenvalues. Very SMALL negative eigenvalues, like 10^-6, but negative. And it's not matlab calculating eigenvalues and eigenvectors wrong either, I try premultiplying and postmultiplying the matrix with an eigenvector for a negative eigenvalue and the result is a negative number. And don't even get me started on covariance matrices derived from actual observations rather than abstract functions, so that the "observed" covariance and correlation, which is the covariance divided by the square root of the corresponding variances of the 2 variables it's a covariance between, is not the underlying covariance or correlation of the actual random variable. In other words, say you have a particle moving around, and it has some mean square change in its position after a given amount of time. When the value which is observed over a period of time is used as the actual value - for instance, the mean square amount it moved in a millisecond, averaged over a period of a second - then just by luck it may not be the real mean square change in position after a millisecond, maybe it moved a little more or less than usual over that second. Negative eigenvalues are just frigging everywhere. So what is the deal then? Is it all numerical subtraction error? If I did it all with enough precision, would matlab find it to be positive definite always, when there is nothing linearly dependent (eigenvalues can be 0, but not negative)?

A: I think the anomalies are caused by rounding errors, which actually occur more frequently than people expect. For instance, try the following in Matlab:

x=rand(2,1); A=x*x'; min(eig(A))

About one in five times, you will get a small-sized (in the order of $10^{-17}$ to $10^{-16}$) but negative eigenvalue. And we are only talking about a $2\times2$ covariance matrix.


text:
Q: Same word giving true and false for same query in Postgresql I'm having a same data in 2 different table columns. When I comparing it returns False.
select (case when 'Gurgaon / Delhi – NCR' = 'Gurgaon / Delhi - NCR' then true else false end)

But when copy and compare the same column text it returns True
select (case when 'Gurgaon / Delhi – NCR' = 'Gurgaon / Delhi – NCR' then true else false end)

How those word differs and how can I find and resolve this?
UPDATE
In table one column stored as \96 and I changed to -. Is that causing the problem?

A: If what you want is to replace a character by another in a string, you can use the REPLACE() function.
This function is described in the documentation: https://www.postgresql.org/docs/current/functions-string.html
For example: SELECT REPLACE('Gurgaon / Delhi – NCR', '–', '-')
After that you could have a match between your two strings if it is that you still want.
Hope this helps.


text:
Q: Ubuntu Server 18.04 apt-get Fails My Ubuntu Server 18.04 system, while it continues to work, has become unable to apply any updates.  I'm not aware of any system change that I made that could be the culprit.
What can I do to fix this?  I've tried autoremove, purge, etc.
Here is typical output but any apt command produces a similar error:
# apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be REMOVED:
  linux-image-4.15.0-22-generic
The following packages will be upgraded:
  libcephfs2 librados2 ssh-import-id
3 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.
Need to get 0 B/3,065 kB of archives.
After this operation, 8,281 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 149817 files and directories currently installed.)
Removing linux-image-4.15.0-22-generic (4.15.0-22.24) ...
/etc/kernel/postrm.d/initramfs-tools:
update-initramfs: Deleting /boot/initrd.img-4.15.0-22-generic
/etc/kernel/postrm.d/x-grub-legacy-ec2:
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... found: /boot/grub/default
Testing for an existing GRUB menu.lst file ...

Could not find /boot/grub/menu.lst file. Would you like /boot/grub/menu.lst generated for you? (y/N) /usr/sbin/update-grub-legacy-ec2: line 1101: read:
read error: 0: Bad file descriptor
run-parts: /etc/kernel/postrm.d/x-grub-legacy-ec2 exited with return code 1
dpkg: error processing package linux-image-4.15.0-22-generic (--remove):
 installed linux-image-4.15.0-22-generic package post-removal script
subprocess returned error exit status 1
Errors were encountered while processing:
 linux-image-4.15.0-22-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

Thanks to all for the responses.  Followed suggestions below.  Can't seem to clean it up via apt / dpkg.  Here is output:
# sudo update-grub
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-4.15.0-22-generic
Found initrd image: /boot/initrd.img-4.15.0-22-generic
Found linux image: /boot/vmlinuz-4.15.0-20-generic
Found initrd image: /boot/initrd.img-4.15.0-20-generic
done

# sudo dpkg --purge linux-image-4.15.0-22-generic
dpkg: dependency problems prevent removal of linux-image-4.15.0-22-generic:
 linux-image-generic depends on linux-image-4.15.0-22-generic.
 linux-modules-extra-4.15.0-22-generic depends on linux-image-4.15.0-22-generic | linux-image-unsigned-4.15.0-22-generic; however:
  Package linux-image-4.15.0-22-generic is to be removed.
  Package linux-image-unsigned-4.15.0-22-generic is not installed.

dpkg: error processing package linux-image-4.15.0-22-generic (--purge):

dependency problems - not removing
    Errors were encountered while processing:
     linux-image-4.15.0-22-generic

A: I am still unclear on why I experienced this issue, but it seems a missing grub /boot/grub/menu.lst file was causing apt / dpkg updates to fail.  So I created an empty file.
sudo touch /boot/grub/menu.lst
sudo update-grub2

All good.  Then proceed with updating the system:
sudo apt update
sudo apt upgrade
sudo apt autoremove --purge

Along the way, there will be a warning that the current menu.lst file is different than the package maintainer's version.  Select the option to install the package maintainer's version, and then the rest of the update and cleanup completes successfully.  Will see how the next kernel upgrade goes, but problem is solved for now.
Thank you to all who contributed suggestions and help!

A: I know this should be a comment but I don't have enough reputation.
But I want to let you know I had a similar problem yesterday.
If this answer doesn't work for you, you can contact @videonauth . He's the super nice guy who helped me with this issue.
 I will copypaste from his answer the part that will hopefully help you:

First remove the removable packages after having run an update to get
  the proper package archives updated:
sudo apt update
sudo apt autoremove --purge

This should remove all removable packages so far except the one which
  managed to get messed up which we can then remove then by installing
  it and then removing it properly:
cd /var/cache/apt/archives
sudo dpkg -i linux-modules-4.15.0-22-generic_4.15.0-22.24_amd64.deb
sudo dpkg -r linux-modules-4.15.0-22-generic_4.15.0-22.24_amd64.deb

(Note from Oussema: ^This command was used based on the fact that my system's architecture is amd64. You can see yours using the command uname -a
"i386", "i486", "i586" and "i686" and "athlon" all mean 32 bit.
"x86_64" means 64 bit (Opteron or Athlon-64). "i686-64" means 32-bit
operation with 64-bit address space (Intel 686 with the new memory
mechanism). )

Now cleaning up the archives by running:
sudo apt clean

And now we can reinstall the packages properly after having run an
  complete update process:
sudo apt update
sudo apt dist-upgrade

with the following line:
sudo apt install --reinstall linux-generic


text:
Q: Сonflict onBlur event with events on other elements I have an input with an onBLur event and a button located in another part of the application
how to avoid conflict onBLur and clicking on this button, because by clicking on this button I also get a trigger
onBLur events


text:
Q: Making the CSS popup stick to the top of the div Guys take a look at the attached image. Kinda difficult to explain so attaching image.

What I'm looking for is, when you hover over the flag icon, a pop-up appears. It's a simple CSS popup. Basically, there's a wrap containing the icon and the popup. The popup is absolutely positioned. The wrap is relatively positioned. The popup has top:0. So it starts from the top of the wrap div. What i want is, the popup should stick to the top of the wrap div (from the triangle). And the popup's height is unknown, it depends on the content.

% Special Offer

£5 Voucher: Buy 10 VCHR get 10 SIMs free

.bjper_iconwrap {
  position: relative;
}
.bjoffersbigpop {
  background: #d1005c;
  padding: 20px;
  color: #fff;
  min-height: 200px;
  position: absolute;
  top: 0px;
  left: -47px;
  width: 300px;
  z-index: 100;
}

A: If you want the bottom to start at the top instead of using top:0 use bottom:100%; and then margin-top minus the size of the arrow:
.bjoffersbigpop {
  background: #d1005c;
  padding: 20px;
  color: #fff;
  min-height: 200px;
  position: absolute;
  bottom:100%;         /*remove top and replace with bottom*/
  margin-top:-20px;    /*minus the size of your arrow - optional*/
  left: -47px;
  width: 300px;
  z-index: 100;
}

A: I think you can put the popup inside the flag:

% Special Offer

£5 Voucher: Buy 10 VCHR get 10 SIMs free

And have it positioned by bottom instead of top:
.bjoffersbigpop {
  background: #d1005c;
  padding: 20px;
  color: #fff;
  min-height: 200px;
  position: absolute;
  bottom: 100%;
  left: -47px;
  width: 300px;
  z-index: 100;
}

A: you can use jquery
$(document).ready(function(){
  var height= $('.bjoffersbigpop').height();
  $('.bjoffersbigpop').css('top', - height + 'px');
})


text:
Q: Poisson distribution question, solving for time until event occurs. I've got this lengthy question that I'm really struggling with, I'd appreciate all help i can get.

"The number of customers Y arriving at a walk-in shop in the first t minutes after it opens doors [i.e time interval (0,t)] on any particular day follows a poisson distribution with mean $\lambda t$.
[the parameter $\lambda$ is the rate of arrivals per unit time and $t$ is the length of time period, so $\lambda t$ represents the mean of number of customers arriving in the interval of length $t$.
a) Let the random variable $T$ denote the time (in minutes) until the arrival of the first customer. Determine the probability density function of $T$.
[Hint: if $T>a$, then no customers have arrived in the time period (0,a).]
b) Let the random variable $U$ be the time until the arrival of the second customer. Show that $U$ has a gamma distribution with $\alpha = 2$ and $\beta=1/\lambda$
c) Let the random variable $W$ be the time until the arrival of the $k$th customer. Show that $W$ has a gamma distribution with $\alpha=k$ and $\beta=1/\lambda$.

I'm assuming that for part a, i need to solve $P(Y \le 1)=P(Y=0)+P(Y=1)$ for
$P(Y=y)=$ $(\lambda t)^y e^{-\lambda t} \over y!$
and then solve for $t$ from there, but i'm not really sure.
as for part b and c, I'm not really sure, as they both seem to depend on the solving the first part.
I know it's a lengthy question, and it'd take some time to get it solved.
All the help is appreciated.
Cheers

A: As part $a)$ was addressed in the comments and $b)$ is a special case of $c)$ which you can verify after seeing the general idea, I only present hints for $c)$.
Again, note that if $T_j$ is the time until the $j$-th customer arrives, then $T_j >t $ if and only if $N_t < j$. Thus, $P(T_j >t)=P(N_t \leq j-1)$. Writing as before, we have $F_{T_j}(t)=1-P(N_t \leq j-1)$. But this is equal to
$$1-e^{-\lambda t}\left(1+\lambda t+\frac1{2!}(\lambda t)^2+\dotsc +\frac1{(j-1)!}(\lambda t)^{j-1}\right).$$
Differentiate, with respect to $t$, the above expression to get $f_{T_j}(t)=\frac{\lambda^j}{(j-1)!}t^{j-1}e^{-\lambda t}$ and recognize this is the PDF of r.v. with Gamma distribution,
$\frac{1}{\Gamma(\alpha)\beta^\alpha} t^{\alpha-1}e^{- t/\beta}$, where $\alpha=j$, and $\beta=1/\lambda$, QED.


text:
Q: Change the total value on changing the selection to find total I am trying to get the total amount for the a variety of tickets that are available. from the select box, the user can chose the number of tickets he wants. in the end, the total amount is getting displayed. My issue is, on changing the selection of number of tickets, it is getting added to the previous total. i want to deduct it, and then add the correct amount. i have this running code.
This is the html i have.
<form>

     OAP

     <select class="venet-stock" data-price="20">
        <option value="1">
           1
        </option>
        <option value="2">
           2
        </option>
        <option value="3">
           3
        </option>
        <option value="4">
           4
        </option>
        <option value="5">
           5
        </option>
        <option value="6">
           6
        </option>
     </select>

        £20

      General

     <select class="venet-stock" data-price="35">
        <option value="1">
           1
        </option>
        <option value="2">
           2
        </option>
        <option value="3">
           3
        </option>
        <option value="4">
           4
        </option>
        <option value="5">
           5
        </option>
        <option value="6">
           6
        </option>
     </select>

        £35

             Concession

         <select class="venet-stock" data-price="50">
        <option value="1">
           1
        </option>
        <option value="2">
           2
        </option>
        <option value="3">
           3
        </option>
        <option value="4">
           4
        </option>
        <option value="5">
           5
        </option>
        <option value="6">
           6
        </option>
     </select>

        £50

     Total

            £50

This is my Jquery code.
var price_total = 0;
jQuery( '.venet-stock' ).change(function() {
    price = jQuery(this).attr('data-price');
    guest = jQuery( this ).val();
    price_total += guest*price;
    jQuery( '#price-total').text( price_total );
});

Thanks in advance.

A: Working Fiddle https://jsfiddle.net/t3vs4dgx/
HTML Code. Add only a Zero option to every dropdown.
<form>

      OAP

      <select class="venet-stock" data-price="20">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
      </select>

£20

      General

      <select class="venet-stock" data-price="35">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
      </select>

£35

      Concession

      <select class="venet-stock" data-price="50">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
      </select>

£50

      Total

£0

</form>

JS Code. Going through all selections when one is changed and add price_total for this run
$( '.venet-stock' ).change(function() {
    var price_total = 0;
    $( '.venet-stock' ).each(function(i,e){
      price = $(e).attr('data-price');
      guest = $(e).val();
      price_total += guest*price;
    });
    jQuery( '#price-total').text( price_total );
});


text:
Q: Prevent input cursor from going to end of input after value replace on keyup I'm using the function found here for formatting an input. It works, the only problem is that when adding text to the input, the caret automatically goes to the end of the input, and doesn't allow adding anything to any other place of the input that is not the end.
How can I prevent the cursor/cursor from going to the end of the input on keyup?
function format(input, format, sep) {
    var output = "";
    var idx = 0;
    for (var i = 0; i < format.length && idx < input.length; i++) {
        output += input.substr(idx, format[i]);
        if (idx + format[i] < input.length) output += sep;
        idx += format[i];
    }
    output += input.substr(idx);
    return output;
}

$('.phoneinput').keypress( function(e){
    var phoneLength = $(this).val();
    phoneLength = phoneLength.replace(/[^\d]/g,'').length;
    if (phoneLength == 10) {
        e.preventDefault();
    }
});

$('.phoneinput').keyup(function(e) {
    var phoneNumber = $(this).val().replace(/-/g, "");
    if (phoneNumber.length <= 10) {
        phoneNumber = format(phoneNumber, [2, 4], "-");
    }
    $(this).val(phoneNumber);
});


text:
Q: Show default language content if no translation for post I have a multilingual Wordpress site with plugin Polylang and the problem is that when I'm seeing site in other language the posts are not showing if there is no translation for the post.
$latest_blog_posts = new WP_Query( array( 'posts_per_page' => 15 ) );
            if ( $latest_blog_posts->have_posts() ) : while (
$latest_blog_posts->have_posts() ) : $latest_blog_posts->the_post(); ?>

I'm using above code to call for the posts, but for now I have posts only in default language (Only posts not pages or categories or any other thing) and everythings OK when I'm seeing site in default language, but when I switch to another one - no posts are shown as there are no translations in other language.
Can anyone help me with this issue. I want to show default language posts if there is no translation.

A: I found the solution and its very simple :) just added 'lang' => '' in array
$latest_blog_posts = new WP_Query( array( 'posts_per_page' => 15, 'lang' => '' ) );
            if ( $latest_blog_posts->have_posts() ) : while (
$latest_blog_posts->have_posts() ) : $latest_blog_posts->the_post(); ?>

A: Polylang has a function to get default language: pll_default_language()
In case: show all posts with default language, try to use this code:
$latest_blog_posts = new WP_Query( array( 'posts_per_page' => 15 ) );
if (!$latest_blog_posts->have_posts()) {
    $latest_blog_posts = new WP_Query( array(
        'posts_per_page' => 15,
        'lang' => pll_default_language()
    ));
}
if ( $latest_blog_posts->have_posts() ) :
   while ($latest_blog_posts->have_posts() ) : $latest_blog_posts->the_post(); ?>
...


text:
Q: If statement in ModelBuilder to check if field exists I'm trying to create the following in ModelBuilder:
Set input feature class
  if field1 exists
    execute the processes in branch1
  else
    add field1
    execute the processes in branch2
    merge branch

While I have no problem with the processes in the two branches, the IF check at the start doesn't seem to be working the way I want it to work. I am using this code in the Calculate Value code block
def ifFieldExists(Input_FC, SUMMARY):
  import arcpy
  fields = arcpy.ListFields(Input_FC)
  for f in fields:
    if f ==" SUMMARY":
      return "true"
    else:
      return "false"

and expression
ifFieldExists(r"%Input_FC%", "%SUMMARY%")

This is the precondition for branch1, so if it returns true, the field exists so branch1 executes. The other branch's precondition returns the reverse. When I run it on an input that does contain the field, the precondition returns false instead of true, so the wrong branch executes.

A: There are a number of logic errors and possible improvements/simplifications here:

*

*ListFields returns a list of Field objects, not strings corresponding to the field names, so you should check the field object's name property instead of directly equating the field object to the desired field name.

*You've hardcoded the string " SUMMARY" (note the leading space) instead of using the function parameter SUMMARY (I would also rename that to field or fieldName for clarity).

*You're looping through the list of fields but return either true or false on the first iteration. This means that if the first field in the list is not the one your looking for, you will always return false, even if the correct field exists further down the list. If you do use this type of logic you would need to let the loop continue and only return false after the loop has completed without first returning true (omit the else statement and un-indent the return "false" statement so that it is outside of the loop).

*ListFields accepts a wildcard argument, allowing you to limit which fields are returned. You could then check whether the length of the returned list is greater than 0 and return true if so, or false if not.

*You don't need the import arcpy statement, it is always available from the ModelBuilder environment.

So to sum up, try something like the below instead of what you have currently:
def ifFieldExists(inputFC, fieldName):
  fields = arcpy.ListFields(inputFC, fieldName)
  return "true" if len(fields) > 0 else "false"


text:
Q: How to lower the height of the bars with ChartJS? I would like the height of the left bars made with the ChartJS library to be equivalent to the right ones...

With stackOverflow topics I found this method (decrease the size of the parent container) but the bars overflow (they are not in absolute position).

Code I tried :
<div class="content competencesHeight" style="height: 100px !important;">
   <canvas class="skills"
      data-dataset3="{{ baseSkillsAndScores.managerLevels[i]* 20|json_encode }}"
      data-dataset4="{{ baseSkillsAndScores.minimalLevels[i] * 20|json_decode }}"
      data-label1="{{ 'legends.average_manager_evaluation'|trans({}, 'dashboard') }}"
      data-label2="{{ 'legends.average_expected_levels'|trans({}, 'dashboard') }}"
                                >
      </canvas>

 </div>

Thank you!!!


text:
Q: Set cart shipping total amount issue after Woocommerce update After the update my custom shipping amount rules are not working. Before the update I was using the following code to update shipping amount.
add_action('woocommerce_calculate_totals', 'mysite_box_discount');
function mysite_box_discount($cart )
{
  $cart->shipping_total=100;
  return $cart;
}

After the update the structure of $cart array has changed and the above code has stopped working. Now the data coming in form of a protected array. I found that $cart->get_shipping_total(); can fetch me shipping amount.
I also found following function to update shipping amount.
$cart->set_shipping_total($amount);

So I used it in the following way, but its not working.
add_action('woocommerce_calculate_totals', 'mysite_box_discount');
function mysite_box_discount($cart )
{
  $cart->set_shipping_total(100);
  return $cart;
}

Can anyone help me and tell how can I use this function or if there is some other way to do it.
Thank you.

A: You can use instead woocommerce_package_rates filter hook to set the cost of your shipping methods, which will be similar to your old code:
add_filter('woocommerce_package_rates', 'custom_shipping_costs', 10, 2 );
function custom_shipping_costs( $rates, $package ){
    // Loop through shipping methods rates
    foreach ( $rates as $rate_key => $rate ){
        // Targeting all shipping methods except "Free shipping"
        if ( 'free_shipping' !== $rate->method_id ) {
            $has_taxes = false;
            $taxes = [];

            $rates[$rate_key]->cost = 100; // Set to 100
            // Taxes rate cost (if enabled)
            foreach ($rates[$rate_key]->taxes as $key => $tax){
                if( $tax > 0 ){
                    $has_taxes = true;
                    $taxes[$key] = 0; // Set to 0 (zero)
                }
            }
            if( $has_taxes )
                $rates[$rate_key]->taxes = $taxes;
        }
    }
    return $rates;
}

Code goes in function.php file of your active child theme (or active theme). Tested and work.

You might need to refresh shipping cached data: disable, save and enable, save related shipping methods for the current shipping zone, in Woocommerce shipping settings.

In this hook if you need to loop through cart items (to make some calculations for example), you will use inside the function code:
foreach( $package['contents'] as $cart_item_key => $cart_item ) {
     $product = $cart_item['data']; // Get the WC_Product instance Object

     // your code
}


text:
Q: What would cause this SQL Server deadlock? I have a node.js script that is attempting to geocode records in a table.  The script selects 100 records at a time that do not have lat/log data, geocodes them using a third party api and writes the results to the lat/long column for the corresponding record.  This script has been causing deadlock errors in the database like the one below:

Transaction (Process ID 69) was deadlocked on lock resources with
another process and has been chosen as the deadlock victim. Rerun the
transaction.

I setup SQL Server Profiler to run a trace and track deadlock data and was able to get one of the deadlock graphs but I can't quite figure out why deadlock is occuring.  The two statements are both updates against different records in the same table.  I checked the Isolation Level and it is Read Committed.  While I haven't dealt with a lot database deadlocks, I didn't think these types of transactions would cause a deadlock.  I've included the XML below in case it is helpful:
<deadlock-list>
 <deadlock victim="process25211037848">
  <process-list>
   <process id="process25211037848" taskpriority="0" logused="0" waitresource="PAGE: 8:1:34878 " waittime="2422" ownerId="3315762" transactionname="UPDATE" lasttranstarted="2021-05-23T23:46:32.920" XDES="0x24d9e44d900" lockMode="U" schedulerid="4" kpid="7440" status="suspended" spid="65" sbid="0" ecid="4" priority="0" trancount="0" lastbatchstarted="2021-05-23T23:46:32.923" lastbatchcompleted="2021-05-23T23:46:32.380" lastattention="1900-01-01T00:00:00.380" clientapp="Node.js" hostname="PNS157" hostpid="6536" isolationlevel="read committed (2)" xactid="3315762" currentdb="8" currentdbname="DW_Staging" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128056">
    <executionStack>
     <frame procname="adhoc" line="1" stmtstart="100" stmtend="250" sqlhandle="0x02000000259d222f04b5eda0f2e0ab46a16fa9ba5cc2d8310000000000000000000000000000000000000000">
unknown     </frame>
     <frame procname="adhoc" line="1" stmtend="236" sqlhandle="0x02000000a6f84a131709260f562f587021ed884c3ed1e86a0000000000000000000000000000000000000000">
unknown     </frame>
    </executionStack>
    <inputbuf>
UPDATE Members SET MbrLat = 28.03195, MbrLong = -81.09178 WHERE MemberUID = 'ID456'    </inputbuf>
   </process>
   <process id="process24eae1b64e8" taskpriority="0" logused="0" waitresource="PAGE: 8:1:36694 " waittime="2422" ownerId="3315758" transactionname="UPDATE" lasttranstarted="2021-05-23T23:46:32.920" XDES="0x25206e8b900" lockMode="U" schedulerid="3" kpid="7784" status="suspended" spid="79" sbid="0" ecid="2" priority="0" trancount="0" lastbatchstarted="2021-05-23T23:46:32.920" lastbatchcompleted="2021-05-23T23:46:32.480" lastattention="1900-01-01T00:00:00.480" clientapp="Node.js" hostname="PNS157" hostpid="6536" isolationlevel="read committed (2)" xactid="3315758" currentdb="8" currentdbname="DW_Staging" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128056">
    <executionStack>
     <frame procname="adhoc" line="1" stmtstart="100" stmtend="250" sqlhandle="0x02000000d48bf12084e55043f1f9c7969865359e9737b71a0000000000000000000000000000000000000000">
unknown     </frame>
     <frame procname="adhoc" line="1" stmtend="244" sqlhandle="0x02000000424e371e647b248bf01785555348ca7d05f180650000000000000000000000000000000000000000">
unknown     </frame>
    </executionStack>
    <inputbuf>
UPDATE Members SET MbrLat = 25.9510963, MbrLong = -81.1176539 WHERE MemberUID = 'ID123'    </inputbuf>
   </process>
  </process-list>
  <resource-list>
   <pagelock fileid="1" pageid="34878" dbid="8" subresource="FULL" objectname="DW_Staging.dbo.Members" id="lock24ed7f99880" mode="U" associatedObjectId="72057594044678144">
    <owner-list>
     <owner id="process24eae1b64e8" mode="U"/>
    </owner-list>
    <waiter-list>
     <waiter id="process25211037848" mode="U" requestType="wait"/>
    </waiter-list>
   </pagelock>
   <pagelock fileid="1" pageid="36694" dbid="8" subresource="FULL" objectname="DW_Staging.dbo.Members" id="lock24e383d5f00" mode="U" associatedObjectId="72057594044678144">
    <owner-list>
     <owner id="process25211037848" mode="U"/>
    </owner-list>
    <waiter-list>
     <waiter id="process24eae1b64e8" mode="U" requestType="wait"/>
    </waiter-list>
   </pagelock>
  </resource-list>
 </deadlock>
</deadlock-list>

Can anyone see why this deadlock would be occurring?  Any suggestions for how I might get around these deadlock errors or what I should do to debug the issue?
UPDATES - in response to the questions below:

*

*I don't have an index on MemberUID

*The execution plan can be found here.

A: Because you have no suitable index on the table, you get a full table scan.
The table scan is going parallel, which means that access is happening out-of-order. You could solve this by using OPTION(MAXDOP 1), but that is just a band-aid.
Your best bet is to create an index to serve this query, the idea being that the query only needs to do a point lookup on the exact rows it needs.
Without knowing other queries you have, I can only suggest based on this one
CREATE NONCLUSTERED INDEX IX_Members_MemberUID ON Members (MemberUID) INCLUDE (MbrLat, MbrLong);

Given that the column is called MemberUID it is probably the primary key, in which case you should almost certainly make this a CLUSTERED index
CREATE UNIQUE CLUSTERED INDEX CX_Members_MemberUID ON Members (MemberUID);

Or better
--  DROP CONSTRAINT the old primary key then ...

ALTER TABLE Members
    ADD CONSTRAINT PRIMARY KEY CLUSTERED (MemberUID);