text:
Q: I want to show tooltip on mouse hover of every coordinate in angular-highchart, it should show x and y axis value in tooltip or label chart = new Chart({
        chart: {
          type: "line",
          // height : 1000
          // height: 55 + '%',
          height: (9 / 16) * 100 + "%",
          // width: 1200,
        },
        title: {
          text: "",
        },
        credits: {
          enabled: false,
        },
        legend: {
          title: {
            text: "OrderNumber",
            style: {
              fontStyle: BOLD,
            },
          },
          layout: "vertical",
          align: "right",
          verticalAlign: "top",
          borderWidth: 1,
          floating: true,
          backgroundColor: WHITE,
        },
        xAxis: {
          startOnTick: true,
          endOnTick: true,
          title: {
            text: this.xLabel,
            style,
          },
          type: CTYPE,
          gridLineColor: BLACK,
          // min:
          //   this.chartData != undefined
          //     ? Math.log10(Math.ceil(Math.min(this.chartData.series) / 10) * 10)
          //     : this.xMin,
          max: this.xMax,
          gridLineWidth: 1,
          lineColor: BLACK,
          minorGridLineColor: BLACK,
          lineWidth: 1,
          tickLength: 20,
          tickInterval: 1,
          minorTickInterval: 0.1,
          minorGridLineWidth: 0.5,
          // animation: false,
          labels: {
            formatter: function () {
              var raise = require("superscript-text");
              let num = Math.log10(this.value as number).toPrecision(1);
              let base = "10";
              let final = base + raise(num.toString());
              return final;
            },
          },
        },
        yAxis: {
          startOnTick: true,
          endOnTick: true,
          title: {
            text: this.yLabel,
            style,
          },
          max: this.yMax,
          min: this.yMin,
          type: CTYPE,
          lineColor: BLACK,
          lineWidth: 1,
          gridLineColor: BLACK,
          minorGridLineColor: BLACK,
          gridLineWidth: 1,
          tickLength: 20,
          tickInterval: 1,
          minorTickInterval: 0.1,
          minorGridLineWidth: 0.5,
          labels: {
            formatter: function () {
              var raise = require("superscript-text");
              let num = Math.log10(this.value as number);
              let base = "10";
              let final = base + raise(num.toString());
              return final;
            },
          },
        },
        plotOptions: {
          series: {
            stickyTracking: false,
            marker: {
              enabled: false,
            },
            states: {
              hover: {
                enabled: false,
              },
              inactive: {
                opacity: 1,
              },
            },
            animation: false,
            visible: true,
          },
          line: {
            events: {
              legendItemClick: function (event) {
                this.selectedItemList.forEach((item) => {
                  if (event.target.options.id === item.product.index) {
                    item.product.toggleSlashEye = !item.product.toggleSlashEye;
                    let count = 0;
                    this.selectedItemList.forEach((item) => {
                      if (item.product.toggleSlashEye === false) count++;
                    });
                    if (count === this.selectedItemList.length) this.isSeriesVisible = true;
                    else this.isSeriesVisible = false;
                  }
                });
              }.bind(this),
            },
          },

          // animation: false,
        },
        tooltip: {
          enabled: true,
          followPointer: true,
          formatter: function () {
            return `<b>x = ${this.y}</b> y = <b>${this.x} </b>`;
          },
        },
        series: [],
      });

currnet code status - currently I am showing tooltip on series only.
expected - I want to show the tooltip on the locations where the yaxis and xaxis graph lines cross.


text:
Q: Replace long dash with a usual one in C# I have a string with multiple dashes, but it contains long dashes.
What method can I use to normalize dashes?
text = Regex.Replace(text, @"(\u2012|\u2013|\u2014|\u2015)", "-");

The expected output is something like 11-1111-11/11
The actual is almost the same, but some of the dashes are long ones. (I can't put in that dash because the stackoverflow does not recognize it.)

A: This works:
 private const string DashPattern = @"[\u2012\u2013\u2014\u2015]";
 private static Regex _dashRegex = new Regex(DashPattern);

 public static string RemoveLongDashes(string s)
 {
     return _dashRegex.Replace(s, "-");
 }

Your expression with the pipe characters (|) is not a valid regex expression.  If you want to replace all of the vowels, you use an expression like @"[aeiou]", i.e., the choices within a set of square brackets.

A: Here is some info on the em dash. You might be able to copy and paste the dash from this post into your code and use the string.replace
The em dash
Look in the following SO post for the answer:
replacing the em dash
Looks like the following code solved the issue for others:
String s = "asd – asd";
s = s.replaceAll("\\p{Pd}", "-");

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to explain to the browser to remember the Ajax request? There is a problem with the "back" button of the browser and my application.
The webapp uses ajax and standart requests. That all happens this way:

*

*I make GET request to list.jsp page - it's the first page you see in application if you check the temp link I provided below. Now we are on Page 1  (the whole page was reloaded)

*I make Ajax request (click on link - i.e. page number) to page 4. Only the parth of page was reloaded - everything is OK. Thus now we are on page 4

*I make Ajax request (click on link - i.e. page number) to page 5. Only the parth of page was reloaded - everything is OK. Thus now we are on page 5

*Now I press the browser "back" button (one step back to history) - nothing happened. The browser consoles does not show any changes.

*This step I press the browser "back" button again. It turns out that this step executed correctly. GET request happened.
What is going on? Why does the browser not remember changes that hapaned on step 3 ? How can I instruct the browser to make step back to history to the changes that was made by ajax request?
You can check it online by temp link. Just try to go throuh the pages. The pink square is current page indicator.

update 1:
This code initialized after loader finished loading recources.
$(function() {

    $(window).on('hashchange', refreshByHash);

    refreshByHash();

    function refreshByHash() {
        var hash = window.location.hash;
        console.log("hash = " + hash.substring(1));

        /* $.ajax({

               url : 'paginator.action?page=' + hash, // action
               type : 'GET', //type of posting the data
                dataType : 'html',
                async: true,
                success : function(htmlData) {
                    $('#paginator').html(htmlData);
                },
                error : function(xhr, ajaxOptions, thrownError) {
                    alert('An error occurred! ' + thrownError);
                },

            }); */

       }

 });

A: I would suggest you to put a hash parameter in the url, that way the browser would handle the history properly, and listen to hashchange events. In most cases you can store the page state directly there, so you don't have to implement your own history handling. I've put together a little MCVE:

$(function() {

  // setup some pagination bar
  for (var i = 1; i < 11; i++) {
    $('#pages').append(
        $('').text(i).attr('href','#'+i)
    );
    $('#pages').append($('').text('.'));
  }

  // load contents of page i
  function _uiPage(i) {
      // imitate some XHR
      setTimeout(function() {
          $('#page-content').text('This is page ' + i);
      }, 200);
  }

  // load contents of current page based on hash
  function refreshByHash() {
      var hash = window.location.hash;
      _uiPage(hash ? +hash.substring(1) : 1);
  }

  // refresh on hash change
  $(window).on('hashchange', refreshByHash);
  // initial state on page load
  refreshByHash();
});

Note: Chrome's back button will go back in the active iframe, so after you clicked on some of the pages, you can press the back button to test the behaviour, and the outer frame, StackOverflow itself will not change.

Also take a look at thoe question: How to manage browser "back" and "forward" buttons when creating a javascript widget

Edit1
$(function() {
  $(window).on('hashchange', refreshByHash);
  refreshByHash();

  function refreshByHash() {
    var hash = window.location.hash;
    // ----- strip the hashmark here -----
    hash = hash ? hash.substring(1) : '';
    console.log("hash = " + hash);

    $.ajax({
      url : 'paginator.action?page=' + hash, // action
      type : 'GET', //type of posting the data
      dataType : 'html',
      async: true,
      success : function(htmlData) {
        $('#paginator').html(htmlData);
      },
      error : function(xhr, ajaxOptions, thrownError) {
        alert('An error occurred! ' + thrownError);
      },
    });
  }
});

A: When user clicks on #idPage (btw, use classes instead, now you have multiple elements with the same ID and that's not good) since href attribute is empty, the browser will load # (and will go to the top of the page).
You should prevent default behavior when user clicks on links, e.g.
$('body').on('click', '#idPage', function(e) {
   // some code goes here
   e.preventDefault();
});

Hashtag (#) has effect on back/forward button. If you append hashtag and click "back", the browser will return you to the state before hashtag was applied.


text:
Q: Python Plot two subplots I have a set of 12 plots that I want to save as one. The first set is a 3x3 subplot of 9 segments and the 2nd part is a 2x2 subplot of 4 segments.
I've tried to add a subplot(121) between these two and I have tried to use figure(1) and figure(2), but both don't met me save the two images as one big image. Is there an easy way of doing this?
plt.subplot(331)
plt.imshow(getpoly(seg1),origin="lower")
plt.subplot(332)
plt.imshow(getpoly(seg2),origin="lower")
plt.subplot(333)
plt.imshow(getpoly(seg3),origin="lower")
plt.subplot(334)
plt.imshow(getpoly(seg4),origin="lower")
plt.subplot(335)
plt.imshow(getpoly(seg5),origin="lower")
plt.subplot(336)
plt.imshow(getpoly(seg6),origin="lower")
plt.subplot(337)
plt.imshow(getpoly(seg7),origin="lower")
plt.subplot(338)
plt.imshow(getpoly(seg8),origin="lower")
plt.subplot(339)
plt.imshow(getpoly(seg9),origin="lower")

plt.subplot(221)
plt.imshow(h1,origin="lower")
plt.colorbar()
plt.subplot(222)
plt.imshow(h2,origin="lower")
plt.colorbar()
plt.subplot(223)
plt.imshow(getpoly(h2),origin="lower")
plt.colorbar()
plt.subplot(224)
plt.imshow(h1-getpoly(h2),origin="lower")
plt.colorbar()

A: You would probably want to use gridspec with GridSpecFromSubplotSpec as shown here.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

gs = gridspec.GridSpec(1, 2)
gs0 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs[0])
gs1 = gridspec.GridSpecFromSubplotSpec(2, 2, subplot_spec=gs[1])

fig = plt.figure()

for i in range(9):
    ax = fig.add_subplot(gs0[i//3, i%3])
    ax.imshow(np.random.rand(4,4))
    ax.set_xticks([]); ax.set_yticks([])

for i in range(4):
    ax = fig.add_subplot(gs1[i//2, i%2])
    ax.imshow(np.random.rand(4,4))
    ax.set_xticks([]); ax.set_yticks([])

plt.show()


text:
Q: how to back to the first of text file i have a txt file which have some lines ...and my code is :
string line;
ifstream myfile("c:\\main.txt");

bool passport = true;

while(passport==true){

    int pos1=0;
    cout<<setw(20)<<"PassPort_Number : ";
    cin>>add.Id ;
    if (myfile.is_open())
    {
        while(!myfile.eof()){
            getline(myfile,line);
            pos1+=line.find(add.Id);
            cout<<pos1;
        }
    }

    if(pos1<0)
        passport=false;
    else {
        cout<<"PassPort Number tekrariye :d"<<endl;
    }
}

first time everything is ok but at the second time of running it doesn't enter to second while (while(!myfile.eof() ) ...
what's wrong with my code?
when it goes to the end of text file it doesn't back to the first of file at the next loop ... how can i back to the first of text file ?

A: Call:
myfile.seekg(0, ios::beg);

to set the file read pointer back to the beginning.


text:
Q: Where is bed data stored? In Minecraft, players use a bed to set their spawn point. If they die and the bed is gone, they are sent back to the world spawn. However, I was wondering where this data is stored and how that affects game play. If a player sleeps in a bed to set their spawn, destroys the bed, and immediately puts it back in the same place, does that destroy their spawn? If the data is stored with the bed block, it would. If the data is stored with the player data, it might not. But I haven't been able to find any information about immediate bed replacement anywhere.

A: The best way to try to figure out how this works is with some SCIENCE. To test this, I set my spawn in a bed in my test world. Then, I broke the bed, and placed it back in exactly the same position it was in when I set my spawn there (I used some wool to mark where the bed was and how it was oriented). When I used /kill, I respawned at the bed. However, if I break the bed, use /kill, and then replace it in the spot it was before, after having died, my spawn is no longer set.
The coordinates of the player's bed are stored in the Player.dat file. Upon respawning, the game checks to see if the bed is still there, and if there is a valid spawning space around it. If the bed is at those coordinates upon death, and there is a valid spawning space, the player will spawn there. Even if the bed had been broken. If the bed is missing or obstructed upon respawning, the bed coordinates are cleared.

A: Depending on game version, breaking and replacing a bed can reset a spawn, (currently doesn't reset). However, the data is stored in the world's metadata, not the blocks of the bed, as you still spawn next to the bed if it is in an unloaded chunk, and can you change spawn points with commands.

A: The bed data is stored with that instance of the bed block. So if you break it and then immediately replace it, you would still spawn at the world spawn as the newly placed bed would be a new instance of a bed block.


text:
Q: Unit testing nested function, third-party function mocking. Jest I have a third-party function, return from a parent function, I am able to test the parent function call, toHaveBeenCalled but the nested return statement is not being tested. Definitely it needs to be mocked as it's a third-party function. The function looks like below:
import * as _html2canvas from 'html2canvas';
// tslint:disable-next-line: no-any
const html2canvas: any = _html2canvas;

export const  downloadElement = (props: string, imageName: string): HTMLElement => {
const captureElement = document.querySelector(props);
const canvasBg = window.getComputedStyle(document.body, null).getPropertyValue('background-color');

const options = {
 scale: 0.8,
 backgroundColor: canvasBg,
 removeContainer: true,
 allowTaint: true
};

return html2canvas(captureElement, options)
   .then((canvas: HTMLCanvasElement) => {
     canvas.style.display = 'none';
     document.body.appendChild(canvas);
     return canvas;
   })
   .then((canvas: HTMLCanvasElement) => {
     const image = canvas
       .toDataURL('image/png')
       .replace('image/png', 'image/octet-stream');
     const a = document.createElement('a');
     a.setAttribute('download', `${imageName}.png`);
     a.setAttribute('href', image);
     a.click();
     canvas.remove();
   });
};

I am trying to cover: return html2canvas... till the end.
I tried-
jest.mock('html2canvas', () => {
    html2canvas: jest.fn();
})

and
jest.mock('html2canvas', () => () => ({
    then : jest.fn(() => ({
        then : jest.fn(() => ({
            toHaveBeenCalled : jest.fn().mockResolvedValue({})
        }))
    }))
}));

        const element = document.createElement('div');
        element.id = "test";
        document.body.appendChild(element);
        let de = downloadElement('test', 'testImage') as any;

        expect(de).toBeCalled();

I tried mockResolvedValue as well.
de = jest.fn().mockResolvedValue({});

Looks like I can't find the way to cover it. Any help appreciated.


text:
Q: Display Android Certificate I have a short question: What does this call return exactely?
context.getPackageManager().getPackageInfo(context.getPackageName(), GET_SIGNATURES).signatures[0].toByteArray();

I know it returns the first app certificate for the app which is the CERT.RSA in the META-INF folder, but what exately does it return? Just a byte-array which represents the whole certificate as the file or some other byte-array? I don't really know much about the structure of certificates and the data they contain so I really don't have any clue.
The best answer would be an instruction for openssl with that I get the returned value from the above code line.

A: I finally tested it myself on an android simulator and got the final answer. It's actually not hard to understand once I realized that PKCS7 is just a storage-form or rather a container for various signature-types.
Within the app
The call returns the first signature within the CERT.RSA file. It's a PKCS7 file which embeds the X.509-certificate and from what I've read it's always just one signature for android apps.
Signature sig = context.getPackageManager().getPackageInfo(context.getPackageName(), GET_SIGNATURES).signatures[0];

This Signature obtained from above can be directly used to generate a working X.509-certificate like this (taken from here):
 byte[] rawCert = sig.toByteArray();
 InputStream certStream = new ByteArrayInputStream(rawCert);

 CertificateFactory certFactory;
 X509Certificate x509Cert;
 try {
      certFactory = CertificateFactory.getInstance("X509");
      x509Cert = (X509Certificate) certFactory.generateCertificate(certStream);

      //do stuff with your certificate
 } catch(Exception ex) {
      //handle exception
 }

Anywhere else
If you have the certificate outside of your own android app and want the same byte-stream, that is provided by the function above you can do the same with a simple Java-program like this:
 FileInputStream is = new FileInputStream("CERT.RSA");
 CertificateFactory cf = CertificateFactory.getInstance("X.509");
 X509Certificate c = (X509Certificate) cf.generateCertificates(is).toArray()[0];
 byte[] rawCert = c.getEncoded();

This code first reads the file, creates the CertificateFactory and then the important step it to isolate the first certificate in the PKCS7-container. And then c.getEncoded() finally gives you the exact same representation as the method above.
openssl
And last but not least the openssl-command for it(taken from here):
 openssl pkcs7 -inform DER -in CERT.RSA -print_certs -text

It will give you a pretty overview of the information contained and at the end the
 -----BEGIN CERTIFICATE-----
 ...
 -----END CERTIFICATE-----

block. It contains the same data as above. If you parse the contents of this block and decode it with base64 it will give you the exact same byte array as in the upper two examples.

A: context.getPackageManager().getPackageInfo(context.getPackageName(), GET_SIGNATURES).signatures[0]

Would return the representation of the signing certificate associated with an application package. It would be an instance of a Signature class as defined here in the documentation. (The name 'Signature' is slightly misleading and even mentioned in the documentation itself).
context.getPackageManager().getPackageInfo(context.getPackageName(), GET_SIGNATURES).signatures[0].toByteArray();

Would return its byte Array representation. ie: The certificate file's byte array representation.
Adding to that, a certificate is nothing new than a text file, but the data is structured into a common format and encoded. X.509 is one of the most widely used formats. You can find it here. The RFC for a X.509 certificate is here. Certificates are structured such that they can be easily checked if altered by a 3rd party.
There isn't any openssl command which directly returns a byte[]. The closest which I could think of is the openssl command which you can use to get the textual representation of a certificate.
$ openssl x509 -in <your-certificate> -noout -text

A: The signatures member of PackageInfo is simply an array of all signatures read from the package file.
public Signature[] signatures;

The class android.content.pm.Signature stores a signature in the form
private final byte[] mSignature;

This is what toByteArray() does:
/**
 * @return the contents of this signature as a byte array.
 */
public byte[] toByteArray() {
    byte[] bytes = new byte[mSignature.length];
    System.arraycopy(mSignature, 0, bytes, 0, mSignature.length);
    return bytes;
}

So essentially this code simply provides you the byte array of a signature used to sign the package.
Assuming CERT.RSA is the RSA file in META-INF folder of the apk, you can get the package MD5, SHA1, and SHA256 signatures through:
keytool -printcert -file CERT.RSA


text:
Q: Horizontal rule in R Markdown / Bookdown causing errors Suddenly, I run into an error when knitting to PDF in Markdown/Bookdown.  Nothing about my system has changed.
The error is being caused by a 'horzontal rule' i.e. --- or *** anywhere in markdown, despite line spaces either side.
I include a simplistic exmaple of the offending --- that will not knit to PDF.
Incidentally, knitting to another format does not cause problems and knitting to PDF without a horizontal rule does not generate an error.  Also, swapped --- for *** to explore if this stapped the error.  It did not.
Can anyone offer any insight, please?
Using TinyTex and MikteX separately (not installed together).  Neither solve the problem.
Only just encountered this problem.  Files that previously knitted without issue now fail when they encounter  --- or ***.

## R Markdown

Some text, then I want horizontal rule

---

Some text after the horizonatal rule.

! Missing number, treated as zero.
<to be read again>
                   \protect
l.146 ...nter}\rule{0.5\linewidth}{\linethickness}
                                                  \end{center}

Error: Failed to compile K.tex. See https://yihui.name/tinytex/r/#debugging for debugging tips. See K.log for more info.
Execution halted

A: Update: this issue has been fixed in rmarkdown v2.1, and should disappear if you (re)install the latest version of rmarkdown from CRAN.

This is a known and fixed bug now in pandoc.
https://github.com/jgm/pandoc/issues/5801
it happened with newer version of TexLive.
This will be fixed in next pandoc version. You'll have to wait or use the nightly build.
you can also use a trick for now by adding this in the header of tex document.
\renewcommand{\linethickness}{0.05em}

With rmarkdown you can do
---
title: "Untitled"
output:
  pdf_document:
    keep_tex: true
    includes:
      in_header: header.tex
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{cat, engine.opts = list(file = "header.tex")}
\renewcommand{\linethickness}{0.05em}
```

lalalala

---

lilili

you can also write the header.tex file manually, or add it to your template.
This works for me.

A: So, a temporary solution, that worked for me, until a more permanent solution is found is:
\begin{center}\rule{3in}{0.4pt}\end{center}

Used this instead of --- or ***


text:
Q: Почему не работает тест в Rspec Почему не срабатывает тест?
   require 'rspec'
class Test
  attr_accessor :name
  def girl
    puts "Hello #{name}"
  end
end

describe "Hello" do
 it "Hello Mari" do
 name1=Test.new
 name1.name="Mari"
 name1.girl=="Hello Mari"
 end

end

A: Новичкам можно порекомендовать почаще обращаться к документации http://rspec.info
А не работает потому, что что тесты пишут немного иначе
name1 = Test.new
name1.name = 'Mari'
expect(name1.girl).to eq('Hello Mari')


text:
Q: How to create in C or C++ the contents value of Sig type object for digital signature in PDF? We are programmatically creating PDF using our in house lib (C++) by adding all the required objects so that PDF readers can render them properly.
Currently we are enhancing the lib to support digital signatures in PDF. Our users will use USB token or Windows certificates to sign the PDF.
On studying raw PDF file with digital signature, we were able to make sense of all the objects except for the contents of Sig type object.
18 0 obj
<<
/Type /Sig
/Filter /Adobe.PPKLite              --> signature handler for authenticating the fields contents
/SubFilter /adbe.pkcs7.sha1         --> submethod of the handler
/Contents <....>                    --> signature token
/ByteRange [ 0 101241 105931 7981
]                                   --> byte range for digest calc
/M (D:20210505094125+05'30')        --> timestamp
/Reason ()
/Location ()
/ContactInfo ()
>>
endobj

We have referred
https://www.adobe.com/devnet-docs/acrobatetk/tools/DigSigDC/Acrobat_DigitalSignatures_in_PDF.pdf
to understand what all constitutes the signature token.
We need direction on how to programmatically create the signature token for PDF using windows APIs. Currently we are not looking at 3rd party lib solutions.
Thanks in advance.
Update
We tried the following:

*

*Updated our in-house PDF lib to support incremental updates so that digital signing related objects can be added. We added something like this apart from the obj# 18 mentioned above:

16 0 obj                       --> new Acroform obj
<<
/Fields [ 17 0 R ]
/SigFlags 3
>>
endobj
2 0 obj                        --> Updating root to add AcroForm
<<
/Type /Catalog
/Pages 3 0 R
/AcroForm 16 0 R
>>
endobj
17 0 obj                       --> new obj for signature field
<<
/T (SignatureField1)
/Type /Annot
/Subtype /Widget
/FT /Sig
/F 4
/Rect [ 270 159 503 201 ]  --> field position. this will have image of sign
/P 5 0 R
/V 18 0 R
/AP <<
/N 19 0 R
>>
>>
endobj
5 0 obj                    --> updating existing page obj with Annots
<<
/Type /Page
/Parent 3 0 R
/MediaBox [ 0 0 595 841 ]
/Resources 4 0 R
/Contents 6 0 R
/Annots [ 17 0 R ]
>>
endobj
18 0 obj
<<
/Type /Sig
/Filter /Adobe.PPKLite
/SubFilter /adbe.pkcs7.sha1  --> we tried with adbe.pkcs7.detached as well
/Contents <>           --> updated contents using windows APIs
/ByteRange [ 0 100381 102645 7322
]                      --> updated ByteRange with right offsets and lengths
/M (D:20210610125837+05'30') --> sign verified time
/Reason ()
/Location ()
/ContactInfo ()
>>
endobj
19 0 obj                  --> new obj
<<
/Length 7
/BBox [ 0 0 233 42 ]
/Type /XObject
/Subtype /Form
/Resources <<
/XObject <<
/FRM 20 0 R
>>
>>
>>
stream
/FRM Do
endstream
endobj
20 0 obj                 --> new obj for image manipulation
<<
/Length 29
/Type /XObject
/Subtype /Form
/Resources <<
/XObject <<
/Im1 21 0 R
>>
>>
/BBox [ 0 0 233 42 ]
>>
stream
q 233 0 0 42 0 0 cm /Im1 Do Q
endstream
endobj
21 0 obj           --> image obj which contains sign info. Generated by us
<<
/Length 6166
/Type /XObject
/Subtype /Image
/Width 372
/Height 82
/ColorSpace /DeviceRGB
/BitsPerComponent 8
/Filter /DCTDecode
>>
stream
---------------------------------> image stream
endstream
endobj
xref               --> updated xref
0 1
0000000000 65535 f
2 1
0000099954 00000 n
5 1
0000100172 00000 n
16 6
0000099901 00000 n
0000100020 00000 n
0000100297 00000 n
0000102944 00000 n
0000103096 00000 n
0000103271 00000 n
trailer             --> updated trailer
<<
/Root 2 0 R
/Info 1 0 R
/Size 22
/ID [ <982AAACB948CE1AD9FDD976D177BF316> <982AAACB948CE1AD9FDD976D177BF316> ]
--> ID generated via windows API
/Prev 99491
>>
startxref
109605
%%EOF

*For contents data, we used the below API:

bool SignMessageBySubjectName (BytePtr pMessage, ULong pMessageSize, StrPtr pSubjectName, CRYPT_DATA_BLOB * pSignBlob)
{
        HCERTSTORE               store_handle   = NULL;
        PCCERT_CONTEXT           cert_context   = NULL;
        BYTE *                   signed_blob    = NULL;
        ULong                    signed_blob_size;
        ULong                    message_size;
        CRYPT_SIGN_MESSAGE_PARA  signature_params;
        BYTE *                   message;

    pSignBlob->cbData = 0;
    pSignBlob->pbData = NULL;

    message = (BYTE *) pMessage;

    message_size = (pMessageSize + 1) * sizeof(Char); //Size in bytes

        const BYTE * message_array[] = {message};
        DWORD        message_array_size[1];

    message_array_size[0] = message_size;

    store_handle = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL,
                                 CERT_SYSTEM_STORE_CURRENT_USER, L"MY");

    cert_context = CertFindCertificateInStore( store_handle, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, 0,
                                               CERT_FIND_SUBJECT_STR, pSubjectName, NULL);

    signature_params.cbSize = sizeof(CRYPT_SIGN_MESSAGE_PARA);
    signature_params.dwMsgEncodingType = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING;
    signature_params.pSigningCert = cert_context;
    signature_params.HashAlgorithm.pszObjId = szOID_RSA_SHA1RSA;
    signature_params.HashAlgorithm.Parameters.cbData = NULL;
    signature_params.cMsgCert = 1;
    signature_params.rgpMsgCert = &cert_context;
    signature_params.cAuthAttr = 0;
    signature_params.dwInnerContentType = 0;
    signature_params.cMsgCrl = 0;
    signature_params.cUnauthAttr = 0;
    signature_params.dwFlags = 0;
    signature_params.pvHashAuxInfo = NULL;
    signature_params.rgAuthAttr = NULL;

    //Get size of signed message
CryptSignMessage(&signature_params, TRUE, 1, message_array, message_array_size,NULL, &signed_blob_size);

signed_blob = (BYTE *) Malloc(signed_blob_size);

CryptSignMessage(&signature_params, TRUE, 1, message_array, message_array_size,  signed_blob, &signed_blob_size);

    pSignBlob->cbData = signed_blob_size;
    pSignBlob->pbData = signed_blob;

    CertFreeCertificateContext(cert_context);
    CertCloseStore(store_handle, CERT_CLOSE_STORE_FORCE_FLAG);

    return true;
}

While using CryptSignMessage() with detached parameter as TRUE, we get a around 850 length sign token which we convert to hex and add in the contents part. It'll approximately be around 1700 chars.

*In case of the image used in the Field newly added, we generated our own image and added it as a PDF obj.

*For the ID in trailer part, we generated the same using API from Bcrypt.lib (BCryptGenRandom()), converted its output to hex and updated the ID part.

*Listing out the steps we did:

*

*We generated 2 buffers. Both buffers are identical with respect to all the PDF objects required, the ID generated from BCryptGenRandom() and ByteRange array updated with actual values. buffer1 has contents data as 0s for a definite length acting as a placeholder. buffer2 has empty contents data (/Contents <>)

*buffer2 will be passed onto CryptSignMessage() to generate the sign token. This will be converted to hex.

*The hex sign token will be added to contents part of buffer1 replacing the 0s based on its length.

*buffer1 will be written to a PDF file.
When we did all these, and opened the PDF in readers, we got errors like

*

*Signature is invalid

*Document has been corrupted or altered since the signature was applied.

Error from a PDF Reader:

Detailed Error:

But with these errors too, the reader was able to identify the user, certificate, hash algorithm and signature algorithm used.

We think we need to somehow add timestamp data as part of the sign token so as to avoid this error. Or something else we would have missed.
PFA sample PDF here:https://drive.google.com/file/d/1Udog4AmGoq2ls3Tu3Wq5s2xU9LxaI3fH/view?usp=sharing
Kindly help us solve this issue. Thanks in advance.

A: We used a different set of APIs to make this work.
Pasting the code here:
bool SignatureHandler::SignMessageTest (BytePtr pMessage, ULong pMessageSize, StrPtr pSubjectName, CRYPT_DATA_BLOB * pSignBlob, LPSTR pOid, DWORD pFlag, DWORD pType)
{
        HCERTSTORE              store_handle  = NULL;
        PCCERT_CONTEXT          cert_context  = NULL;
        BYTE *                  signed_blob   = NULL;
        ULong                   signed_blob_size = 0;
        CRYPT_SIGN_MESSAGE_PARA signature_params;
        BYTE *                  message;
        BOOL                    rc;

        pSignBlob->cbData = 0;
        pSignBlob->pbData = NULL;

    store_handle = CertOpenStore (CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER, L"MY");

    cert_context = CertFindCertificateInStore (store_handle, (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING), 0, CERT_FIND_SUBJECT_STR, pSubjectName, NULL);

        HCRYPTPROV_OR_NCRYPT_KEY_HANDLE a         = 0;
        DWORD                           ks        = 0;
        BOOL                            bfr       = false;

        HCRYPTPROV_OR_NCRYPT_KEY_HANDLE PrivateKeys;
        CERT_BLOB                       CertsIncluded;
        CMSG_SIGNER_ENCODE_INFO         Signers;

        HCRYPTMSG                       hMsg;

    rc = CryptAcquireCertificatePrivateKey (cert_context, 0, 0, &a, &ks, &bfr);

        CMSG_SIGNER_ENCODE_INFO SignerEncodeInfo = {0};

    SignerEncodeInfo.cbSize = sizeof (CMSG_SIGNER_ENCODE_INFO);

    if (a)
        SignerEncodeInfo.hCryptProv = a;

    if (bfr)
        PrivateKeys = a;

    CERT_BLOB SignerCertBlob;

    SignerCertBlob.cbData = cert_context->cbCertEncoded;
    SignerCertBlob.pbData = cert_context->pbCertEncoded;
    CertsIncluded         = SignerCertBlob;

                    SignerEncodeInfo.cbSize    = sizeof (CMSG_SIGNER_ENCODE_INFO);
                    SignerEncodeInfo.pCertInfo = cert_context->pCertInfo;
                    SignerEncodeInfo.dwKeySpec = ks;
                    SignerEncodeInfo.HashAlgorithm.pszObjId          = pOid;
                    SignerEncodeInfo.HashAlgorithm.Parameters.cbData = NULL;
                    SignerEncodeInfo.pvHashAuxInfo = NULL;

                    Signers = SignerEncodeInfo;

                    CMSG_SIGNED_ENCODE_INFO SignedMsgEncodeInfo = {0};

                    SignedMsgEncodeInfo.cbSize        = sizeof (CMSG_SIGNED_ENCODE_INFO);
                    SignedMsgEncodeInfo.cSigners      = 1;
                    SignedMsgEncodeInfo.rgSigners     = &Signers;
                    SignedMsgEncodeInfo.cCertEncoded  = 1;
                    SignedMsgEncodeInfo.rgCertEncoded = &CertsIncluded;
                    SignedMsgEncodeInfo.rgCrlEncoded  = NULL;

                    signed_blob_size = 0;

                    signed_blob_size = CryptMsgCalculateEncodedLength ((PKCS_7_ASN_ENCODING | X509_ASN_ENCODING), pFlag, pType, &SignedMsgEncodeInfo, 0, pMessageSize);

                    if (signed_blob_size) {

                        signed_blob_size *= 2;

                        hMsg = CryptMsgOpenToEncode (CERTIFICATE_ENCODING_TYPE,
                                                     pFlag,
                                                     pType,
                                                     &SignedMsgEncodeInfo,
                                                     0,
                                                     NULL);

                        if (hMsg) {

                            signed_blob = (BYTE *)malloc (signed_blob_size);

                                BOOL CU = CryptMsgUpdate (hMsg, (BYTE *)pMessage, (DWORD)pMessageSize, true);

                            if (CU) {

                                if (CryptMsgGetParam (
                                        hMsg,               // Handle to the message
                                        CMSG_CONTENT_PARAM, // Parameter type
                                        0,                  // Index
                                        signed_blob,  // Pointer to the BLOB
                                        &signed_blob_size))    // Size of the BLOB
                                {

                                    signed_blob = (BYTE *)realloc (signed_blob, signed_blob_size);

                                    if (hMsg) {

                                        CryptMsgClose (hMsg);
                                        hMsg = 0;
                                    }
                                }
                            }
                            if (hMsg)
                                CryptMsgClose (hMsg);
                            hMsg = 0;
                        }
                    }

    CryptReleaseContext (a, 0);

    pSignBlob->cbData = signed_blob_size;
    pSignBlob->pbData = signed_blob;

    CertFreeCertificateContext (cert_context);
    CertCloseStore (store_handle, CERT_CLOSE_STORE_FORCE_FLAG);

    return true;
}

The oid, flag and type we used are szOID_RSA_SHA1RSA, CMSG_DETACHED_FLAG and CMSG_SIGNED respectively.
On converting pSignBlob->pbData to hex and adding it to /Contents, the PDF and signature became valid when opened in PDF readers.

A: Ok, the signature container is embedded correctly.
But there are issues with the signature container itself:

*

*Both in the SignedData.digestAlgorithms collection and in the SignerInfo.digestAlgorithm value you have used the OID of SHA1withRSA, but that is a full signature algorithm, not the mere digest algorithm SHA1 expected there.

*Then the SHA1 hash of the signed bytes is BB78A402F7A537A34D6892B83881266501A691A8 but the hash you signed is 90E28B8A0D8E48691DAFE2BA10A4761FFFDCCD3D. This might be because you hash buffer2 and

buffer2 has empty contents data (/Contents <>)

The hex string delimiters '<' and '>' also belong to the contents value and, therefore, must also be removed in buffer2.
Furthermore, your signature is very weak:

*

*It uses SHA1 as hash algorithm. SHA1 meanwhile has been recognized as too weak a hash algorithm for document signatures.

*It doesn't use signed attributes, neither the ESS signing certificate nor the algorithm identifier protection attribute. Many validation policies require such special attributes.


text:
Q: How to cope with 'readonly' and 'selected' attributes in WatiN 2.0 against IE9 I'm using WatiN for web testing, and am encountering issues caused by the fact that for the 'readonly' attribute of INPUT elements, WatiN is attempting to parse the value as a boolean, which as far as I can tell is incorrect, as the attribute should be written as follows:

<input readonly="readonly" />

When I try to access the TextField.Readonly property from WatiN at runtime, an error is thrown because WatiN attempts to parse 'readonly' as a boolean. I also encountered a similar issue with the 'selected' attribute of the <option> element.
I find it hard to believe that nobody else has encountered these basic scenarios using WatiN which makes me think I am missing something obvious. Is there a known way to work around these issues or is this a known issue with WatiN?

A: This issue has to do with IE9 showing a page in IE9mode differs greatly from how IE9 in IE8mode (and older versions of IE) behaves. These problems have been fixed in WatiN 2.1

A: The syntax of readonly="readonly" that you mention is definitely correct according to w3c school and it looks like you have indeed found a bug.
Looking at  /trunk/src/Core/TextField.cs in line 57 the code is
 public virtual bool ReadOnly
 {
   get
   {
     var value = GetAttributeValue("readOnly");
     return string.IsNullOrEmpty(value) ? false : bool.Parse(value);
   }
 }

so you should probably just change it to something like this, although I am not using the fancy ? and : syntax :-)
 public virtual bool ReadOnly
 {
   get
   {
     string value = GetAttributeValue("readOnly");
     if (value.ToLower() == "readonly")
     {
       return true;
     }
     else
     {
        return false;
     }
   }
 }


text:
Q: "The multi-part identifier could not be bound" for update statement from 'inner' set to 'update' set Error

'The multi-part identifier "ar_update.Id" could not be bound.'

as line denoted in sql script.
I also tried other columns for the errant join to try to prompt different errors and gives same error results.
Why/How to qualify the 'inner' processing set back to the 'update' set?
update ar_update
   set ar_update.[GLEntry_Amount] = ar_sum.[GLEntry_Amount_sum]
  from [dbo].[ASL_Result_VGO]  as ar_update

  join (select  ar.[Id]                        as [Id]
               ,ar.[Company Id]                as [Company Id]
               ,ar.[Schedule Name]             as [Schedule Name]
               ,ar.[Line No_]                  as [Line No_]
               ,ar.[Row No_]                   as [Row No_]
               ,ar.[Posting Date]              as [Posting Date]
               ,ar.[Business Centre Code]      as [Business Centre Code]
               ,ar.[Site Locations Code]       as [Site Locations Code]

               ,GLEntry_Amount_sum =
                    (select  sum(are.[GLEntry_Amount])
                     from    [dbo].[ASL_Result_VGO]  as are
                     where   are.[Company Id]           = ar.[Company Id]  and
                             are.[Schedule Name]        = ar.[Schedule Name]  and
                             are.[Posting Date]         = ar.[Posting Date]  and
                             are.[Business Centre Code] = ar.[Business Centre Code]  and
                             are.[Site Locations Code]  = ar.[Site Locations Code]  and
                             are.[Row No_] in ( select * from dbo.udf_range_expand_VGO(ar.[Totaling]) )
                    )

        from    [dbo].[ASL_Result_VGO]  as ar
        where   ar.[Id] = ar_update.[Id]    -- The multi-part identifier "ar_update.Id" could not be bound.

       )  ar_sum  on  ar_update.[Id] = ar_sum.[Id]

    where   ar_update.[Totaling Type] = 2  and   -- formulas
            len(trim(ar_update.[Totaling])) > 0  and
            charindex('..', ar_update.[Totaling]) > 0   -- P ranges

A: this happened because on where ar.[Id] = ar_update.[Id] because ar_update.[Id] is not a value it is a multivalued type, it's like you were comparing a list with an integer, try this
update ar_update
   set ar_update.[GLEntry_Amount] = ar_sum.[GLEntry_Amount_sum]
  from [dbo].[ASL_Result_VGO]  as ar_update

  join (select  ar.[Id]                        as [Id]
               ,ar.[Company Id]                as [Company Id]
               ,ar.[Schedule Name]             as [Schedule Name]
               ,ar.[Line No_]                  as [Line No_]
               ,ar.[Row No_]                   as [Row No_]
               ,ar.[Posting Date]              as [Posting Date]
               ,ar.[Business Centre Code]      as [Business Centre Code]
               ,ar.[Site Locations Code]       as [Site Locations Code]
               ,GLEntry_Amount_sum =     (select  sum(are.[GLEntry_Amount])
                     from    [dbo].[ASL_Result_VGO]  as are
                     where   are.[Company Id]           = ar.[Company Id]  and
                             are.[Schedule Name]        = ar.[Schedule Name]  and
                             are.[Posting Date]         = ar.[Posting Date]  and
                             are.[Business Centre Code] = ar.[Business Centre Code]  and
                             are.[Site Locations Code]  = ar.[Site Locations Code]  and
                             are.[Row No_] in ( select * from dbo.udf_range_expand_VGO(ar.[Totaling]) )
                    )

        from    [dbo].[ASL_Result_VGO]  as ar

       )  ar_sum  on  ar_update.[Id] = ar_sum.[Id]

    where   ar_update.[Totaling Type] = 2  and   -- formulas
            len(trim(ar_update.[Totaling])) > 0  and
            charindex('..', ar_update.[Totaling]) > 0


text:
Q: Excel VBA to add unique numbers to multiple accounts I cannot get to a satisfactory answer.  I need to add comments to a data input sheet. I have added a form  and I am able to populate my worksheet.  However, I wish to add a unique identifier (number) to each unique customer. Row a1 has customer A; row a2 has customer B; row a3 has customer A - I would like to number the rows 1, 1, 2 respectively in column b

A: Assuming that you have your customers in column A and your unique numbers in column B you could use the following formula for cell B2 and then copy it down:
=IFERROR(INDEX($B$1:B1,MATCH(A2,$A$1:A1,0)),MAX($B$1:B1)+1)

Cell B1 will be set to 1 or whichever the starting number should be.
The result would be something like this:

A: If by "add a unique identifier (number) to each unique customer" you mean that you are trying to generate a sequence number which is unique within each unique customer, (i.e. if column A contained A, B, A, C, C then you are after 1, 1, 2, 1, 2 in column B) then you can just use the formula
=COUNTIF(A$1:A1,A1)

in cell B1 and copy it down.


text:
Q: ssh-keyscan and mac: debug2: fd 3 setting O_NONBLOCK I'm sitting on a mac trying to add a host ip to the known hosts file before ssh'ing into the machine. Not very used to a mac so I don't know what's wrong, I get the following:
km@Karls-MacBook-Pro ~ $ ssh-keyscan -vv -t rsa x.x.x.x >> /Users/km/.ssh/known_hosts
debug2: fd 3 setting O_NONBLOCK

A: $ ssh-keyscan -vv -t rsa x.x.x.x >> /Users/km/.ssh/known_hosts
              ^^^
debug2: fd 3 setting O_NONBLOCK
^^^^^^

The "fd 3" message is a debug message. You're getting it because you requested verbose output. It doesn't indicate a problem.


text:
Q: is there any way to skip rows in pandas until csv says "Flight Table"? N11682,aircraft,C172,,Cessna,C172SP,airplane,airplane_single_engine_land,fixed_tricycle,Piston,false,false,false,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
Flights Table,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
Date,AircraftID,From,To,Route,TimeOut,TimeOff,TimeOn,TimeIn,OnDuty,OffDuty,TotalTime,PIC,SIC,Night,Solo,CrossCountry,Distance,DayTakeoffs,DayLandingsFullStop,NightTakeoffs,NightLandingsFullStop,AllLandings,ActualInstrument,SimulatedInstrument,HobbsStart,HobbsEnd,TachStart,TachEnd,Holds,Approach1,Approach2,Approach3,Approach4,Approach5,Approach6,DualGiven,DualReceived,SimulatedFlight,GroundTraining,InstructorName,InstructorComments,Person1,Person2,Person3,Person4,Person5,Person6,FlightReview,Checkride,IPC,PilotComments
2020-11-01,N172TG,KSFM,KSFM,,,,,,,,0.8,0.8,0.0,0.0,0.0,0.0,0.00,0,0,0,0,0,0.0,0.0,0.00,0.00,0.00,0.00,0,,,,,,,0.8,0.0,0.0,0.0,,,,,,,,,false,false,false
2020-11-01,N916BA,KSFM,KSFM,,,,,,,,0.5,0.5,0.0,0.0,0.0,0.0,0.00,0,0,0,0,0,0.0,0.0,0.00,0.00,0.00,0.00,0,,,,,,,0.5,0.0,0.0,0.0,,,,,,,,,false,false,false31,N172TG,KSFM,KSFM,KASH,,,,,,,1.7,1.7,0.0,0.0,0.0,1.7,0.00,0,0,0,0,0,0.0,0.0,0.00,0.00,0.00,0.00,0,,,,,,,1.7,0.0,0.0,0.0,,,,,,,,,false,false,false

Heres my CSV, although I want it to skip multiple rows prior to the string "Flight Table" is this possible? Ive used skiprows but I need a little more versatility

A: I would:

*

*Open the CSV file

*loop through it as an iterator

*if a line starts with your magic string, pass the remaining lines to pandas.read_csv
with open(mycsv, 'r') as fobj:
    for line in fobj:
        if line.startswith('Flights Table'):
            df = pandas.read_csv(fobj)

A: Use this link
count lines manually and use skiprows.
If lines keep changing - use readline till you find your string and count lines programmatically and feed to skiprows
skiprows : list-like, int or callable, optional
Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file.


text:
Q: Convergence in distribution of order statistic random variables with uniform distribution. I am trying to find the asymptotic distribution of an order statistic $X_{(1)}$ for iid RVs $X_1, ..., X_n \sim \mathrm{Unif}(0,1)$,
The distribution for $X_{(1)}$
$F_{X_{(1)}}(x) = 1 - \left(1 - {x}\right)^{n}, \quad y>0$.
why $X_{(1)}$ convergence in distribution to zero?
I think $F_{X_{(1)}}(x)$ go to $1$ as $n$ go to infinity.

A: $F_{X_1} (x)=0$ if $x \leq 0$. $F_{X_1} (x) \to 1$ for $ x> 0$. So the limiting CDF is exactly the CDF of the zero random variable.


text:
Q: Reduce two Scala methods, that only differ in one Object Type I have the following two methods, using objects from Apache Spark.
  def SVMModelScoring(sc: SparkContext, scoringDataset: String, modelFileName: String): RDD[(Double, Double)] = {
    val model = SVMModel.load(sc, modelFileName)

    val scoreAndLabels =
      MLUtils.loadLibSVMFile(sc, scoringDataset).randomSplit(Array(0.1), seed = 11L)(0).map { point =>
        val score = model.predict(point.features)
        (score, point.label)
      }
    return scoreAndLabels
  }

  def DecisionTreeScoring(sc: SparkContext, scoringDataset: String, modelFileName: String): RDD[(Double, Double)] = {
    val model = DecisionTreeModel.load(sc, modelFileName)

    val scoreAndLabels =
      MLUtils.loadLibSVMFile(sc, scoringDataset).randomSplit(Array(0.1), seed = 11L)(0).map { point =>
        val score = model.predict(point.features)
        (score, point.label)
      }
    return scoreAndLabels
  }

My previous attempts to merge these functions have resulted in errors surround model.predict.
Is there a way I can use model as a parameter that is weakly typed in Scala?

A: Disclaimer - I've never used Apache Spark.
It looks to me like the only difference between the two methods is the way the model is instantiated. It's unfortunate that the two model instances don't actually share a common trait that provides predict(...) but we can still make this work by pulling out the part that changes - the scorer:
def scoreWith(sc: SparkContext, scoringDataset: String)(scorer: (Vector)=>Double): RDD[(Double, Double)] = {
  MLUtils.loadLibSVMFile(sc, scoringDataset).randomSplit(Array(0.1), seed = 11L)(0).map { point =>
    val score = scorer(point.features)
    (score, point.label)
  }
}

Now we can get the previous functionality with:
def svmScorer(sc: SparkContext, scoringDataset:String, modelFileName:String) =
  scoreWith(sc: SparkContext, scoringDataset:String)(SVMModel.load(sc, modelFileName).predict)

def dtScorer(sc: SparkContext, scoringDataset:String, modelFileName:String) =
  scoreWith(sc: SparkContext, scoringDataset:String)(DecisionTreeModel.load(sc, modelFileName).predict)


text:
Q: remove permalink trailing slash I need to use the_permalink() in order to construct a simple link from each post . the link should be like
http://www.mysite.com/category/year/post-name?output=something..

I use ?output=something" >
the problem is that the trailing slash of the permalink is giving me an extar trailing slash that is breaking my link .
http://www.mysite.com/category/year/post-name/?output=something..

I know that I can construct the structure in another way , but I want to use the permalink (much easier) and i do not want to change the permalink structure sitewide ...
any way of getting rid of the trailing slash ??

A: You can use the trim command to do this, specifically, the rtrim to remove the character from the right side:
$url = rtrim(get_permalink(),'/');

Using a blanket substr -1 technique would cause problems if there isn't a trailing slash in the permalink. Also, the function the_permalink echoes the link, and get_permalink returns it as a string.

A: This post is old but, why not use WordPress build in function untrailingslashit? Added since 2.2.0
function untrailingslashit( $string ) {
    return rtrim( $string, '/\\' );
}

A: echo substr(the_permalink(), 0, -1);

A: We can add the following code in .httaccess file.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=301,L]

</IfModule>

Don't forgot to select the custom link from backend and remove the trailing slash from postname.


text:
Q: Why the OpenTK(C#) based rendering to texture showed nothing My project aims to render to texture based on OpenTK (Version 3.0.1.0, C#). Most codes were translated from this tutorial which using C++.
I just want to use an texture(int backfaceTex) in the default render frame (pass#1). The texture backfaceTex stores the rendering results in an offline frame buffer.   But when call the rendered buffer(pass#2), I can only see a black window right now. It seems that all elements of the backfaceTex  are zero. Why? There should be a colored cube on the screen.

The code is short and simple, all relevant data/shaders were also attached for reproducing this issue. The private function Display() is the real rendering part.(2-pass rendering)

I want to know which part of my implementation is wrong? Any ideas are welcome.


text:
Q: Create a new time from hours, minutes, seconds To make a long story short, the data I have access to is that I have Hours, Minutes, Seconds. I would like this to be converted to a time object (without a date). Is this possible in go?
Example:
Hours := 17
Minutes := 55
Seconds := 25.62

I would like to do something like
t := time.Parse(Hours, Minutes, Seconds) // hoping this reads 17:55:25.62

Everything I have found seems to require a date or a format that requires a date.
Any thoughts?

A:
I would like this to be converted to a time object (without a date). Is this possible in go?

Not using the standard library. The time package offers two main data types: Date, which describes a point in time; and Duration, which describes an interval of time. There is no standard library representation of a time without a date component.
If you're truly asking if it's possible to represent such a thing in Go, the answer can only be "of course it is" - for example:
type JustTime struct {
    Hour int
    Minute int
    Second float
}

would do the trick, but whether that's useful depends entirely on your particular use case.


text:
Q: Forward declaration include, on top of declaration include (ClassFwd.h + Class.h) In Effective C++ (3rd edition), Scott Meyers, in Item 31, suggests that classes should have, on top of their classic Declaration (.h) and Definition (.cpp) files, a Forward Declaration Include File (fwd.h), which class that do not need the full definition can use, instead of forward declaring themselves.
I somewhat see the case for it, but I really don't see this as a viable option... It seems very hard to maintain, rather overkill and hardly necessary.
I can, however, see its use for template forward declarations, which are rather heavy. But for simple classes? It seems to be that it's a pain to maintain and will create a whole lot of almost empty include files that serve a very small purpose... is it worth the hassle?
Here's a example:
// Class.h
class Class
{
    Class();
    ~Class();
};

// ClassFwd.h
class Class;

// Class.cpp
Class::Class()
{
}

Class::~Class()
{
}

My question:
What do you guys think? If this a good practice?
NOTE I am mostly interested in the arguments FOR this practice, to see if I missed something that would make me agree with Scott Meyers.

A: I used forward declaration header files for all my libraries. A library would typically have this structure:
lib/
  include/
    class headers + Fwd.h
src/
  source files + internal headers

The lib/include directory would contain all public classes headers along with one forward declarations header. This made the library light-weight on the include side. Any header outside of this library only includes the forward header (Fwd.h), while sources outside of this library includes the necessary complete headers. One can also provide a convenience header (Lib.h) that includes all the other headers, for use in source files.
Another thing to place in the forward declaration header is typedefs for shared_ptr, especially in the case of an inheritance hierarchy with factory classes that return pointers to implementations.
The above is useful for larger applications with lots of internal libraries. A refinement of the above for this case would be to place the public headers in lib/include/lib. This way clients of your library would have to include lib/.... Think of this as a namespace for your headers.
Good luck!

A: Placing a simple class Whatever; in its own header has no advantages and lots of disadvantages.
Especially in the case where accessing a header can be time consuming, one uses simple forward declarations to avoid accessing headers; putting them in their own headers would defeat the purpose...
With templated things, as you note, it's a different matter. E.g. check out <iosfwd> from the standard library.
Cheers & hth.

A: The practice allows the code user not to think about whether a class is regular or template. The user just #inludes "corresponding_fwd.h" file and has a class reference. One less annoyance for the user is A Good Thing. But if it's a small project or class' creator is the only class' user then it might be more annoyance. So, it depends.

A: If you have a large solution this is your only chance to handle the inherent dependencies:
struct A {
    B* m_pB;
};

struct B {
    A* m_pA;
};

Now A and B may reasonably be in different header files, maybe even different projects. Yet, their dependency is not some design defect but entirely logical and necessary. What do you do?

*

*First include a single Types.h forward-declarating header for eeach required project, i.e., the forward declaration does not have its own header file per class.

*Then include the Class.h of all required projects. These headers will require forward declarations to compile.

*Include the headers of the main project.

In a rather large solution (500k LOC) I've found this pattern to be very easily manageable. Otherwise, if you change a class declaration, where do you find all forward declarations that you may have made individually in any number of other header files?


text:
Q: CSRF Cookie error with Chrome browser that I cannot solve I'm using javascript with a Django api to submit a modal form.
I'm sending a CSRF cookie that works in other circumstances (like on other browsers or with other forms in Chrome), but when I submit a Django form, but it fails on chrome and I get the following error:
Error:
Forbidden (403) CSRF verification failed.
Request aborted.
Reason given for failure: CSRF token missing or incorrect.

I know for a fact that I'm sending the CSRF cookie, as I can see it in the inspect element.
csrfmiddlewaretoken=*sometoken*

How might I fix this and what other information do you need?


text:
Q: AlertFragments with android support v4 library I'm trying to create custom AlertDialog but I have one problem.
My alert dialog class below:
class AddNewDayAlert : DialogFragment
{
    public static AddNewDayAlert NewInstance(Bundle bundle)
    {
        AddNewDayAlert fragment = new AddNewDayAlert();
        fragment.Arguments = bundle;
        return fragment;
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Use this to return your custom view for this Fragment
        View view = inflater.Inflate(Resource.Layout.AddNewDayLayout, container, false);

        Button btn = view.FindViewById<Button>(Resource.Id.dialog_text);
        EditText txt = view.FindViewById<EditText>(Resource.Id.dialog_text);
        btn.Click += delegate
        {
            string day_name;
            if (txt.Text != "" && txt.Text != null)
            {
                day_name = txt.Text;
                Toast.MakeText(this.Activity, "Sėkmingai pridėta!!!", ToastLength.Long).Show();
                Dismiss();
            }

            else
                Toast.MakeText(this.Activity, "Pamiršote įvesti dienos pavadinimą!", ToastLength.Long).Show();
        };

        return view;
    }

}

and problem is here:
        Android.Support.V4.App.FragmentTransaction ft = FragmentManager.BeginTransaction();
        Fragment prev = FragmentManager.FindFragmentByTag("dialog");
        if (prev != null)
        {
            ft.Remove(prev);
        }
        ft.AddToBackStack(null);

        AddNewDayAlert fragmentas = AddNewDayAlert.NewInstance(null);
        fragmentas.Show(ft, "dialog");

In the last line I get an error because fragmentas.Show() is using Android.App.FragmentTransaction and I am using Android.Support.V4.App.FragmentTransaction.
If I try to use Android.App.FragmentTransaction I get error in first line:

Maybe there is way to convert? What should I do ?

A: You are conflicting two different FragmentTransaction classes. If you decide to use Support v4 Fragments, then you will want to use the Support v4 FragmentTransaction.
https://developer.android.com/reference/android/app/FragmentTransaction.html
https://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html
You will also need to ensure that you are using a AppCompatActivity(Which inherits FragmentActivity and has a reference to Android.Support.V4.App.FragmentManager) if you go down the v4 route. That way you will have access to SupportFragmentManager that is the same type.
EX:
[Activity(Label = "App7", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : AppCompatActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        // SetContentView (Resource.Layout.Main);

        Android.Support.V4.App.FragmentTransaction ft = SupportFragmentManager.BeginTransaction();

    }
}

A: Your AddNewDayAlert class should also inherit from V4 DialogFragment
class AddNewDayAlert : Android.Support.V4.App.DialogFragment


text:
Q: the unpaid number of days is not computed in the employee payslips in odoo 8 i created a salary rule called Unpaid leave and it depends on a python code
 like this:
result= worked_days.Unpaid and worked_days.Unpaid.number_of_days*(contract.wage/31) or 0
and the employee took 2 days unpaid leaves
i added the rule to the salay structure of the employee
then in the payslips i compute sheet and show the salary computation tab but the Unpaid leave show as zero inspite of the 2 days leave of that emplayee
is the unpaid number of days is zero?
and if not zero why it is not computed in the employee payslip?

A: The better solution is found from here and which is very described.
Here defined the payroll, rules, calculations, Unpaid deductions.


text:
Q: Loop with jquery on mvc In my project, The costumers can do discount to their products for a while. When That while finishs, Discount finishs. Every second or minute, The Program must control the discount finish dates. But If I want to do that, I have to reload the page again everytime. So How can i do that with js on mvc ?

A: You use ajax calls from your front end and JsonResult return types in your controllers. Here is a tutorial to get you going: http://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/


text:
Q: Open Access file with button click Is it possible to open my Microsoft Access file with just a button click event?
The tutorials I read online has to go through OpenFileDialog but I do not want that. I want to open the file directly with a click of a button.
File Location: C:\Users\User\Documents\MedicalRecord.accdb

A: You can use Process.Start(), it's the same thing as double-clicking your file directly.
 private void button1_Click(object sender, EventArgs e)
 {
     Process.Start(@"C:\Users\User\Documents\MedicalRecord.accdb");
 }

A: Yes, it is possible, instead of using open file dialog's file name, use the file location you want


text:
Q: Python --- Split DataFrame column names into multiple columns names based on dictionary having values in a list df = pd.DataFrame(
    {'animals': 'deer', 'devices': 'phone', 'movies': 'inseption'},
    index=[1]
)
col_map = OrderedDict(
    {
        'animals': ['aquatic_animals', 'land_animals'],
        'devices': ['Tech'],
        'movies': ['cinemas']
    }
)
df2 = df.rename(columns=col_map)

Output

Desired Output

A: data = [['beer', 10], ['whiskey', 40], ['vodka', 50]]
df = pd.DataFrame(data,columns=['a','b'])
print('Input df')
display(df)
col_map = {'a':['liquor'],'b':['percentage','%']}
col_map_fil = {}
for k,v in col_map.items():
    if len(v) > 1:
        for i in v:
            df[i] = df[k]
        df.pop(k)
    else:
        col_map_fil.update({k:v[0]})
df = df.rename(columns=col_map_fil)
print('Output df')
display(df)


text:
Q: Creating a CKAN Extension Error: No such command 'create' I'm Creating a CKAN EXTENSION base in their official documentation.

https://docs.ckan.org/en/2.9/theming/templates.html#creating-a-ckan-extension

When I'm in this step,

ckan -c /etc/ckan/default/ckan.ini create -t ckanext-example_theme

I got this error.
*

(default) root@ccgeo:/usr/lib/ckan/default/src# ckan -c
/etc/ckan/default/ckan.ini create -t ckanext-example_theme 2021-10-27
02:27:45,515 INFO  [ckan.cli] Using configuration file
/etc/ckan/default/ckan.ini 2021-10-27 02:27:45,515 INFO
[ckan.config.environment] Loading static files from public 2021-10-27
02:27:45,544 INFO  [ckan.config.environment] Loading templates from
/usr/lib/ckan/default/src/ckan/ckan/templates 2021-10-27 02:27:45,762
INFO  [ckan.config.environment] Loading templates from
/usr/lib/ckan/default/src/ckan/ckan/templates Usage: ckan [OPTIONS]
COMMAND [ARGS]... Error: No such command 'create'. (default)
root@ccgeo:/usr/lib/ckan/default/src#

*

*

A: There is an error in the docs, it should be
ckan generate extension as correct CLI command
or in your case:
ckan -c /etc/ckan/default/ckan.ini generate extension -o *location-to-put-generated-template*


text:
Q: How to convert float number to string without losing user-entered precision in C? Here's what I'm trying to do:

*

*I need to print the fractional part of a floating number which has to be input as a float during user input.

*The fractional part should be like: if float is 43.3423, the output should be 3423; and if number is 45.3400 output should be 3400.

*This can be done easily with a string input but I need a way to make this work with float without losing the extra zeros or without appending zeros to user's original input.

Here's what I already tried :-

*

*Take the fractional part by frac = num - (int)num  and then multiplying frac until we get zero as the remainder. But this fails for cases like 34.3400 — the last two zeros won't get included with this method.

*Convert the float number to a string by
char string[20];
sprintf(string, "%f", float_number);

The sprintf function puts the float number as a string but here also it doesn't automatically detect the user entered precision and fills the string with extra zeros at the end (6 total precision). So here also the information about the user's original entered precision is not obtained.
So, is there a way to get this done? The number must be taken as float number from user. Is there any way to get info about what's the user's entered precision? If it's not possible, an explanation would be very helpful.

A: I think I understand where you're coming from. E.g. in physics, it's a difference whether you write 42.5 or 42.500, the number of significant digits is implicitly given. 42.5 stands for any number x: 42.45 <= x < 42.55 and 42.500 for any x: 42.4995 <= x < 42.5005.
For larger numbers, you would use scientific notation: 1.0e6 would mean a number x with x: 950000 <= x < 1050000.
A floating point number uses this same format, but with binary digits (sometimes called bits ;)) instead of decimal digits. But there are two important differences:

*

*The number of digits (bits) used depends only on the data type of the floating point number. If your data type has e.g. 20 bits for the mantissa, every number stored in it will have these 20 bits. The mantissa is always stored without a part after the "decimal" (binary?) point, so you won't know how many significant bits there are.

*There's no direct mapping between bits and decimal digits. You will need roughly 3.5 bits to represent a decimal digit. So even if you knew a number of significant bits, you still wouldn't know how many significant decimal digits that would make.

To address your problem, you could store the number of significant digits yourself in something like this:
struct myNumber
{
    double value;
    int nsignificant;
};

Of course, you have to parse the input yourself to find out what to place in nsignificant. Also, use at least double here for the value, the very limited precision of float won't get you far. With this, you could use nsignificant to determine a proper format string for printing the number with the amount of digits you want.
This still has the problem mentioned above: you can't directly map decimal digits to bits, so there's never a guarantee your number can be stored with the precision you intend. In cases where an exact decimal representation is important, you'll want to use a different data type for that. C# provides one, but C doesn't. You'd have to implement it yourself. You could start with something like this:
struct myDecimal
{
    long mantissa;
    short exponent;
    short nsignificant;
}

In this struct, you could e.g. place 1.0e6 like this:
struct myDecimal x = {
    .mantissa = 1;
    .exponent = 6;
    .nsignificant = 2;
};

Of course, this would require you to write quite a lot of own code for parsing and formatting these numbers.

A: The only way is to create a struct with the original string value and/ or required precision for rounding

A:
which has to be input as a float during user input.
So, is there a way to get this done.

Almost.  The "trick" is to note the textual length of user input.  The below will remember the offset of the first non-whitespace character and the offset after the numeric input.
scanf(" %n%f%n", &n1, &input, &n2);

n2 - n1 gives code the length of user input to represent the float.  This method can get fooled if user input is in exponential notation,  hexadecimal FP notation, infinity, Not-a-number, excessive leading zeros, etc.  Yet works well with straight decimal input.
The idea is to print the number to a buffer with at least n2 - n1 precision and then determine how much of the fractional portion to print.
Recall that float typically has about 6-7 significant leading digits of significance, so attempting to input text like "123456789.0" will result in a float with the exact value of 123456792.0 and the output will be based on that value.
#include <float.h>
#include <math.h>

int scan_print_float(void) {
  float input;
  int n1, n2;
  int cnt = scanf(" %n%f%n", &n1, &input, &n2);
  if (cnt == 1) {
    int len = n2 - n1;
    char buf[len * 2 + 1];
    snprintf(buf, sizeof buf, "%.*f", len, input);
    char dp = '.';
    char *p = strchr(buf, dp);
    if (p) {
      int front_to_dp = p + 1 - buf;
      int prec = len - front_to_dp;
      if (prec >= 0) {
        return printf("<%.*s>\n", prec, p+1);
      }
    }
  }
  puts(".");
  return 0;
}

int main(void) {
  while (scan_print_float()) {
    fflush(stdout);
  }
  return EXIT_SUCCESS;
}

Input/Output
43.3423
<3423>
45.3400
<3400>
-45.3400
<3400>
0.00
<00>
1234.500000
<500000>
.
.

To robustly handle this and the various edge cases, code should read user input as text and not as a float.

Note: float can typically represent about 232       numbers exactly.
43.3423 is usually not one of them.  Instead it has an exactly value of 43.3423004150390625
43.3400 is usually not one of them.  Instead it has an exactly value of 43.340000152587890625


text:
Q: How to create an image from a 2-dimensional byte array? In my project after long process, i got a 2 dimensional byte array from the IR camera.
The byte array holds image in it...
How to convert that byte array to image in C#..
I know that by
MemoryStream ms = new MemoryStream(byteArray);
System.drawing.Image im = Image.FromStream(ms);

We can pass 1 dimensional array and convert it into image..
If i pass 2 dimensional array as a single dimensional array.. it shows error..
How to rectify it..???? or else how to convert 2 dimensional byte array to image...???
Thank you!!

A: If it's a rectangular array (i.e. a byte[,]) instead of a jagged array (byte[][]) then you may be able to do it pretty simply with some unsafe code.
Have a look at my parallel Mandelbrot set generation code - only the bottom bit is interesting, where it constructs a Bitmap from a palette and a block of data:
byte[] data = query.ToArray();

unsafe
{
    fixed (byte* ptr = data)
    {
        IntPtr scan0 = new IntPtr(ptr);
        Bitmap bitmap = new Bitmap(ImageWidth, ImageHeight, // Image size
                                   ImageWidth, // Scan size
                                   PixelFormat.Format8bppIndexed, scan0);
        ColorPalette palette = bitmap.Palette;
        palette.Entries[0] = Color.Black;
        for (int i=1; i < 256; i++)
        {
            palette.Entries[i] = Color.FromArgb((i*7)%256, (i*7)%256, 255);
        }
        bitmap.Palette = palette;
        // Stuff
    }
}

I don't know whether you can unpin the array after constructing the bitmap - if I were using this for production code I'd look at that more closely.

A: If you want the byte arrays to be processed inorder, you can do the following
byte[][] doubleArray = GetMyByteArray();
byte[] singleArray = doubleArray.SelectMany(x => x).ToArray();
MemoryStream ms = new MemoryStream(singleArray);
System.drawing.Image im = Image.FromStream(ms);

The SelectMany method essentially takes the arrays of arrays and returns the elements in order.  Starting with the first element of the first array, finishing that array and then moving onto the next.  This will continue until all elements are processed.


text:
Q: Question about pip using Python from Windows Store I have python installed through windows store and I can install programs using pip, but when I try to run said programs, they fail to execute in powershell.
How can I make sure that the necessary "scripts" folder is in my path? I never faced these problems when installing from executable.
For example, "pip install ntfy" runs successfully in Powershell.
The command "ntfy send test" fails telling me the term is not part of a cmdlet, function, etc. etc.
The 'ntfy' program is  located here /mnt/c/Users/vlouvet/AppData/Local/Packages/PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0/LocalCache/local-packages/Python37/Scripts/ntfy.exe
What is the recommended way of editing my path so that programs installed via pip are available across windows store updates of the Python language?

A: On Windows you can find the user base binary directory by running
python -m site --user-site

and replacing site-packages with Scripts.
For example, this could return
C:\Users\Username\AppData\Roaming\Python36\site-packages

so you would need to set your PATH to include
C:\Users\Username\AppData\Roaming\Python36\Scripts

You can set your user PATH permanently in the Control Panel. You may need to log out for the PATH changes to take effect.

A: In advance
I highly recommend you not to use python installed from the Windows Store, because you'll face such errors, and even more nasty ones.
The easy solution
Create a virtual environment on a more accessible folder, for example in C:\Users\<user>\python. To do so, do the following:

*

*Using PowerShell, go to your user folder, using cd(Note that usually PowerShell already starts inside your user folder. This is an important setting to have, and if not, you should change your powershell starting point to this folder for the future.);

*Now that you're in your user folder, type in the PowerShell mkdir python; cd python;

*Now, to create a virtual environment, type python -m venv venv;

*(You can verify that your virtual enviroment has been created by listing the folders, with the command ls);

*You have created a virtual environment. Now, you need to activate it. To activate, run the following: ./venv/Scripts/activate;

Now, you have fully created and activated a virtual environment for your current PowerShell session. You can now install any packages / programs using pip.
After that, the only thing that you need to do is to add C:\Users\<user>\python\venv\Scripts to your Path, and you're good to go.
Caveats
By adding this folder to your Path, you may be using an outdated python version in the future, since the Scripts folder inside your virtual environment also adds a python executable that will be enabled in the path.
The recommended solution
As I stated before, I do not recommend to have the Microsoft Store version of python installed on your machine. That said, you're probably using it for the conveniences of having the latest Python version installed as soon as they're released. To alleviate this need while also getting rid of your MS Store Python. I recommend you using Chocolatey to install python (and pretty much any other programs for development).
What is Chocolatey?
Chocolatey is a package manager for Windows, pretty much like apt-get for Ubuntu Linux or HomeBrew for MacOS. By using a package manager, you get rid of the hassle of always having to execute the (mostly annoying) install wizards on windows.
To install Chocolatey:

*

*Go to chocolatey.org/install and follow the install instructions;

*(Recommended: Take a look on their documentation later to see what Chocolatey is capable of);

*With Chocolatey installed, take a test drive and see if it is working properly by running choco -v in PowerShell;

*By having Chocolatey installed, you can now run choco install python -y. Let's break down this command:

*

*choco install -> The package installer of chocolatey

*python -> the name of the package you want to install

*-y -> This tells the installer to skip install verification by saying "Yes to All" scripts that will be executed in order to install a package.

*With python installed from chocolatey, you can also see that Python is already added to your path - This means that any python package or executable installed globally will be now available on your machine!

Hope I could help you!

A: The above answer is good but I managed to get it to work by doing the following.

*

*Find your installation under C:\Users\"your user"\AppData\Local\Packages it will be named something like PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0

*Open your windows settings in the start menu

*In search type Environment variables. Edit environment variables for your account should pop up. Click it

*In the top box find Path, click it

*On the right Click new and enter C:\Users\"your user"\AppData\Local\Packages\"python install directory name from 1. here"\LocalCache\local-packages\Python37\Scripts inside the little box under the last item in the list

*open a new cmd prompt and type the script you wanted it should work.


text:
Q: Numpy switch numbering from columns to rows I need to change the numbering scheme of a matrix. Say,
import numpy as np
a = np.arange(6).reshape(3,2)
array([[0, 1],
       [2, 3],
       [4, 5]])

And I want to switch it to
b = np.array([[0,3],[1,4],[2,5]])
array([[0, 3],
       [1, 4],
       [2, 5]])

So that basically I number the matrix through the rows first. I am sure there is a nice way to do this in numpy

A: >>> import numpy as np
>>> np.arange(6).reshape(3,2, order = 'F')
>>> array([[0, 3],
   [1, 4],
   [2, 5]])

From the doc:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html
Use order='F' to specify the Fortran traditional representation and order='C' (the default) to use the traditional C representation.

A: To create a view of the same data with the new shape, you can use a.T.reshape(3, 2, order='F'):
In [35]: a = np.arange(6).reshape(3,2)

In [36]: a
Out[36]:
array([[0, 1],
       [2, 3],
       [4, 5]])

In [37]: b = a.T.reshape(3, 2, order='F')

In [38]: b
Out[38]:
array([[0, 3],
       [1, 4],
       [2, 5]])

Verify a and b are views of the same data, by changing a and checking b:
In [39]: a[1, 0] = 99

In [40]: a
Out[40]:
array([[ 0,  1],
       [99,  3],
       [ 4,  5]])

In [41]: b
Out[41]:
array([[ 0,  3],
       [ 1,  4],
       [99,  5]])


text:
Q: XML format data to display in sql Table only with specific columns (no duplicates) The following XML variable should show a table having columns like:-
Identifier  |  ModelVariant  |  BomElement
declare @xmlData XML='<UICK>
<KEM count="2" change="created">
<Identifier>ZAP46817</Identifier>
<ChangeLevel>1</ChangeLevel>
<Editor>GGV</Editor>
<ReleaseDateTime>2017-06-12T05:40:40</ReleaseDateTime>
<EngineeringScope>2528R ''P''  RELEASE</EngineeringScope>
<Reason>NYLON HOSE E "P" RELEASE FOR NEW ZEALANDMATURITY CHANGE</Reason>
<Status>REFER PROJECT</Status>
<LegalRelevance>no</LegalRelevance>
<SpecialToolsRequirement>N</SpecialToolsRequirement>
<CircularTechnicalLetterAvailability>N</CircularTechnicalLetterAvailability>
<ExaustRelevance>N</ExaustRelevance>
<StopNoticeType>N</StopNoticeType>
<Request>
  <Organization>requester</Organization>
  <Person>VINOTHKUMA</Person>
  <Department>TP/ACI</Department>
  <DateTime>2017-06-02T00:00:00</DateTime>
</Request>
<Update>
  <Organization>main editor</Organization>
  <Person>VINOTHKUMA</Person>
  <Department>TP/ACI</Department>
  <DateTime>2017-06-02T00:00:00</DateTime>
</Update>
<Approval>
  <Organization>approver</Organization>
  <Person>RPRABHU</Person>
  <Department>TP/ACI</Department>
  <DateTime>2017-06-09T00:00:00</DateTime>
</Approval>
<Authorization>
  <Organization>authorizer</Organization>
  <Person>VJAJI</Person>
  <Department>TP/ACI</Department>
  <DateTime>2017-06-09T00:00:00</DateTime>
</Authorization>
<ProductDocumentationUpdate>
  <Organization>product documentation editor</Organization>
  <Person>VIGNEB</Person>
  <Department>TP/AIH</Department>
  <DateTime>2017-06-06T00:00:00</DateTime>
</ProductDocumentationUpdate>
<Further-1>
  <Organization>CONTROLLED BY       </Organization>
  <Person>SARAVANAN</Person>
  <Department>TP/AIH</Department>
</Further-1>
<ProjectIdentifier>DICVPVH-Y17</ProjectIdentifier>
<ProjectName>HDT PROJECT 2017  HDT VEHICLE SERIES 2017</ProjectName>
<ChangeRequestIdentifier>NO CR</ChangeRequestIdentifier>
<TechnicalData>no</TechnicalData>
<Distributor>FQ</Distributor>
<KemType>A</KemType>
<StopNoticeCauseCode>U</StopNoticeCauseCode>
<ChangeCategories>
  <Category>
    <Identifier>5</Identifier>
    <Name>MaturityLevelChange</Name>
  </Category>
</ChangeCategories>
<MATERIALMASTERS>
  <PART_MATERIALMASTER count="1" change="modified">
    <Identifier>A4004204731</Identifier>
    <ChangeLevel>3</ChangeLevel>
    <UnitOfQuantity>each</UnitOfQuantity>
    <EnglishName>ZB COMPRESSED AIR LINE/MB/2528R 6X25700 ABS/TEST CON</EnglishName>
    <SpanishName>ZB TUB.P.AIRE COMP / MB/2528R 6X2 5700WB ABS/TEST CON</SpanishName>
    <PortugueseName>ZB TBO.AR COMPRIM. / MB/2528R 6X2 5700WB ABS/TEST CON</PortugueseName>
    <FrenchName>ZB COND AIR COMPR / MB/2528R 6X2 5700WB ABS/TEST CON</FrenchName>
    <DrawingGeometryChangeLevel>1</DrawingGeometryChangeLevel>
    <SecurityRelevance>N</SecurityRelevance>
    <CertificationRelevance>N</CertificationRelevance>
    <PartsListElementType>assembly</PartsListElementType>
    <ReferenceDrawingType>06.04.2017</ReferenceDrawingType>
    <CADIdType>G</CADIdType>
    <FlashwareDocumentationRelevantPart>no</FlashwareDocumentationRelevantPart>
    <TheftRelevantPart>no</TheftRelevantPart>
    <ReleaseItemType>SERIE</ReleaseItemType>
    <ReleaseDesignChangeOrder>ZAP46817</ReleaseDesignChangeOrder>
    <LeadingDocumentationGroup>KH</LeadingDocumentationGroup>
    <SharedPartFlag>no</SharedPartFlag>
    <ChangeText>MATURITY CHANGE</ChangeText>
    <TermID>0500002680</TermID>
    <RSK>
      <RSK-NL>LUCHTDRUKLEIDING</RSK-NL>
      <RSK-PL>PRZEWOD SPREZ. POW.</RSK-PL>
      <RSK-DA>TRYKLUFTROER</RSK-DA>
      <RSK-FR>CONDUITE DAIR COMPRIME</RSK-FR>
      <RSK-HU>SURITETTLEVEGOVEZETEK</RSK-HU>
      <RSK-TR>BASINCLI HAVA HATTI</RSK-TR>
      <RSK-CS>POTRUBI TLAKOVZDUSNE</RSK-CS>
      <RSK-DE>DRUCKLUFTLTG.</RSK-DE>
      <RSK-SV>TRYCKLUFTSLEDNING</RSK-SV>
      <RSK-SK>VEDENIE VZDUCHU</RSK-SK>
      <RSK-EN>COMPRESSED AIR LINE</RSK-EN>
      <RSK-ES>TUBERIA</RSK-ES>
      <RSK-IT>TUBAZIONE PNEUMATICA</RSK-IT>
      <RSK-PT>TUBO DO AR COMPRIMIDO</RSK-PT>
      <RSK-BG>??????????? ?????.????.</RSK-BG>
      <RSK-RU>????????????</RSK-RU>
      <RSK-ZH>??????</RSK-ZH>
    </RSK>
  </PART_MATERIALMASTER>
  <PART_MATERIALMASTER count="2" change="modified">
    <Identifier>A4004209329</Identifier>
    <ChangeLevel>3</ChangeLevel>
    <UnitOfQuantity>each</UnitOfQuantity>
    <EnglishName>ZB COMPRESSED AIR LINE/ACC 6X2 5700W/G131/BS4/PTO/RHD</EnglishName>
    <SpanishName>ZB TUB.P.AIRE COMP / ACC 6X2 5700WB/BS4/PTO/RHD</SpanishName>
    <PortugueseName>ZB TUBO DO AR COMPRIMIDO / ACC 6X2 5700WB/BS4/PTO/RHD</PortugueseName>
    <FrenchName>ZB CONDUITE AIR COMPRIME / ACC 6X2 5700WB/BS4/PTO/RHD</FrenchName>
    <DrawingGeometryChangeLevel>1</DrawingGeometryChangeLevel>
    <SecurityRelevance>N</SecurityRelevance>
    <CertificationRelevance>N</CertificationRelevance>
    <PartsListElementType>assembly</PartsListElementType>
    <ReferenceDrawingType>07.04.2017</ReferenceDrawingType>
    <CADIdType>G</CADIdType>
    <FlashwareDocumentationRelevantPart>no</FlashwareDocumentationRelevantPart>
    <TheftRelevantPart>no</TheftRelevantPart>
    <ReleaseItemType>SERIE</ReleaseItemType>
    <ReleaseDesignChangeOrder>ZAP46817</ReleaseDesignChangeOrder>
    <LeadingDocumentationGroup>KH</LeadingDocumentationGroup>
    <SharedPartFlag>no</SharedPartFlag>
    <ChangeText>MATURITY CHANGE</ChangeText>
    <TermID>0500002680</TermID>
    <RSK>
      <RSK-NL>LUCHTDRUKLEIDING</RSK-NL>
      <RSK-PL>PRZEWOD SPREZ. POW.</RSK-PL>
      <RSK-DA>TRYKLUFTROER</RSK-DA>
      <RSK-FR>CONDUITE DAIR COMPRIME</RSK-FR>
      <RSK-HU>SURITETTLEVEGOVEZETEK</RSK-HU>
      <RSK-TR>BASINCLI HAVA HATTI</RSK-TR>
      <RSK-CS>POTRUBI TLAKOVZDUSNE</RSK-CS>
      <RSK-DE>DRUCKLUFTLTG.</RSK-DE>
      <RSK-SV>TRYCKLUFTSLEDNING</RSK-SV>
      <RSK-SK>VEDENIE VZDUCHU</RSK-SK>
      <RSK-EN>COMPRESSED AIR LINE</RSK-EN>
      <RSK-ES>TUBERIA</RSK-ES>
      <RSK-IT>TUBAZIONE PNEUMATICA</RSK-IT>
      <RSK-PT>TUBO DO AR COMPRIMIDO</RSK-PT>
      <RSK-BG>??????????? ?????.????.</RSK-BG>
      <RSK-RU>????????????</RSK-RU>
      <RSK-ZH>??????</RSK-ZH>
    </RSK>
  </PART_MATERIALMASTER>
</MATERIALMASTERS>
<BOMMASTERS>
  <LOWER_BOM_HEADER count="1" change="modified">
    <ParentBomElement>A4004204731</ParentBomElement>
    <BomPosition change="deleted">
      <BomElement>A4004291808</BomElement>
      <Position>000010</Position>
      <Quantity>1</Quantity>
      <UnitOfQuantity>each</UnitOfQuantity>
      <MaturityLevel>V</MaturityLevel>
      <Plant>FQ, D, FH, FR, U, UD, Z</Plant>
      <ReleaseDesignChangeOrder>ZAP718915</ReleaseDesignChangeOrder>
    </BomPosition>
    <BomPosition change="created">
      <BomElement>A4004291808</BomElement>
      <Position>000010</Position>
      <Quantity>1</Quantity>
      <UnitOfQuantity>each</UnitOfQuantity>
      <MaturityLevel>P</MaturityLevel>
      <Plant>FQ, FH</Plant>
      <ReleaseDesignChangeOrder>ZAP46817</ReleaseDesignChangeOrder>
    </BomPosition>
  </LOWER_BOM_HEADER>
  <LOWER_BOM_HEADER count="2" change="modified">
    <ParentBomElement>Z40086626</ParentBomElement>
    <BomPosition change="deleted">
      <BomElement>A4004209329</BomElement>
      <Position>000100</Position>
      <Quantity>1</Quantity>
      <UnitOfQuantity>each</UnitOfQuantity>
      <MaturityLevel>V</MaturityLevel>
      <Plant>FQ, FR, U, UM, DW, J, SR, TD, TY, Z, EK, ZV</Plant>
      <ReleaseDesignChangeOrder>ZAP31815</ReleaseDesignChangeOrder>
    </BomPosition>
    <BomPosition change="created">
      <BomElement>A4004209329</BomElement>
      <Position>000100</Position>
      <Quantity>1</Quantity>
      <UnitOfQuantity>each</UnitOfQuantity>
      <MaturityLevel>P</MaturityLevel>
      <Plant>FQ, FH</Plant>
      <ReleaseDesignChangeOrder>ZAP46817</ReleaseDesignChangeOrder>
    </BomPosition>
  </LOWER_BOM_HEADER>
  <LOWER_BOM_HEADER count="3" change="modified">
    <ParentBomElement>A4004209329</ParentBomElement>
    <BomPosition change="deleted">
      <BomElement>A4004296901</BomElement>
      <Position>000100</Position>
      <Quantity>1</Quantity>
      <UnitOfQuantity>each</UnitOfQuantity>
      <MaturityLevel>V</MaturityLevel>
      <Plant>FQ, FR, U, UM, DW, J, SR, TD, TY, Z, EK, ZV</Plant>
      <ReleaseDesignChangeOrder>ZAP31815</ReleaseDesignChangeOrder>
    </BomPosition>
    <BomPosition change="created">
      <BomElement>A4004296901</BomElement>
      <Position>000100</Position>
      <Quantity>1</Quantity>
      <UnitOfQuantity>each</UnitOfQuantity>
      <MaturityLevel>P</MaturityLevel>
      <Plant>FQ, FH</Plant>
      <ReleaseDesignChangeOrder>ZAP46817</ReleaseDesignChangeOrder>
    </BomPosition>
  </LOWER_BOM_HEADER>
  <LOWER_BOM_HEADER count="4" change="modified">
    <ParentBomElement>Z40086699</ParentBomElement>
    <BomPosition change="deleted">
      <BomElement>A4004204731</BomElement>
      <Position>000100</Position>
      <Quantity>1</Quantity>
      <UnitOfQuantity>each</UnitOfQuantity>
      <MaturityLevel>V</MaturityLevel>
      <Plant>FQ, D, FH, FR, U, UD, Z</Plant>
      <ReleaseDesignChangeOrder>ZAP718915</ReleaseDesignChangeOrder>
    </BomPosition>
    <BomPosition change="created">
      <BomElement>A4004204731</BomElement>
      <Position>000100</Position>
      <Quantity>1</Quantity>
      <UnitOfQuantity>each</UnitOfQuantity>
      <MaturityLevel>P</MaturityLevel>
      <Plant>FQ, FH</Plant>
      <ReleaseDesignChangeOrder>ZAP46817</ReleaseDesignChangeOrder>
    </BomPosition>
  </LOWER_BOM_HEADER>
  <UPPER_BOM_HEADER count="5" change="modified">
    <ModelVariant>F400216220D130390</ModelVariant>
    <BomPosition change="deleted">
      <Group>S429</Group>
      <Scope>SN42240</Scope>
      <Position>000280</Position>
      <BomElement>Z40086626</BomElement>
      <Quantity>1</Quantity>
      <MaturityLevel>T</MaturityLevel>
    </BomPosition>
    <BomPosition change="deleted">
      <Group>S429</Group>
      <Scope>SN42240</Scope>
      <Position>000300</Position>
      <BomElement>Z40086699</BomElement>
      <Quantity>1</Quantity>
      <MaturityLevel>T</MaturityLevel>
    </BomPosition>
    <BomPosition change="created">
      <Group>S429</Group>
      <Scope>SN42240</Scope>
      <Position>000280</Position>
      <BomElement>Z40086626</BomElement>
      <Quantity>1</Quantity>
      <MaturityLevel>P</MaturityLevel>
    </BomPosition>
    <BomPosition change="created">
      <Group>S429</Group>
      <Scope>SN42240</Scope>
      <Position>000300</Position>
      <BomElement>Z40086699</BomElement>
      <Quantity>1</Quantity>
      <MaturityLevel>P</MaturityLevel>
    </BomPosition>
  </UPPER_BOM_HEADER>
</BOMMASTERS>
</KEM>
</UICK>'

I'm using the below code to fetch data, but it is not showing properly.
It should show -> inside  tag one Identifier value, then multiple ModelVariant value inside UPPER_BOM_HEADER and BomElement value inside BomPosition node. Exactly, is should be as per the below URLs.
The parent node  contains one  now, it may contain more number of  node same like above details.

SELECT  doc.col.value('(/ UICK / KEM/Identifier/text())[1]','VARCHAR(100)') Identifier,doc.col.value('(/ UICK / KEM/BOMMASTERS / UPPER_BOM_HEADER/ModelVariant/text())[1]','VARCHAR(100)') ModelVariant,doc.col.value('(/ UICK / KEM/BOMMASTERS / UPPER_BOM_HEADER / BomPosition/BomElement/text())[1]','VARCHAR(100)') BomElement FROM @xmlData.nodes('/ UICK / KEM/*') doc(col)

A: Your question is quite unclear... Next time please try to reduce!!! your sample data to a needed minimum to see what you need and please provide the expected output.
My magic crystall ball tells me, that you might be looking for something like this:
SELECT  @xmlData.value('(/UICK/KEM/Identifier/text())[1]','NVARCHAR(100)') Identifier
       ,u_bom.value('(ModelVariant/text())[1]','VARCHAR(100)') ModelVariant
       ,bomP.value('(BomElement/text())[1]','VARCHAR(100)') BomElement
FROM @xmlData.nodes('/UICK/KEM/BOMMASTERS/UPPER_BOM_HEADER') A(u_bom)
CROSS APPLY u_bom.nodes('BomPosition') AS B(bomP)

UPDATE: For multiple <KEM>
(hint Please avoid chameleon questions!)
Try it like this:
SELECT  kem.value('(Identifier/text())[1]','NVARCHAR(100)') Identifier
       ,u_bom.value('(ModelVariant/text())[1]','VARCHAR(100)') ModelVariant
       ,bomP.value('(BomElement/text())[1]','VARCHAR(100)') BomElement
FROM @xmlData.nodes('/UICK/KEM') AS A(kem)
CROSS APPLY kem.nodes('BOMMASTERS/UPPER_BOM_HEADER') B(u_bom)
CROSS APPLY u_bom.nodes('BomPosition') AS C(bomP)


text:
Q: Divisibility of determinants and matrix rows I have stumbled upon an exercise that is giving me nighmares. I've found that it is quite common in older exercise books, but I haven't even heard about it in class or seen it in any lecture in all my years in college, even if it seems to be a basic and simple problem. Naturally, as it happens, these promblem books don't have a solution for it (They just skip it in the solution pages). Here it is:

Given the matrix A=$ \left( \begin{array}{ccc}
a_{11} & a_{12} & ... &  a_{1n} \\
a_{21} & a_{22} & ... &  a_{2n} \\
\vdots & \vdots & \ddots & \vdots & \\
a_{n1} & a_{n2} & ... &  a_{nn} \end{array} \right)
\in M_{n}(N) / (a_{11}, ..., a_{1n})$ are single-digit natural positive numbers, prove that the determinant of the matrix A is divisible by the GCD of the numbers formed by the rows of the matrix.

I have tried applying determinant proprieties, solving the actual determinant and juggling with everything I know, but I just have no idea about how to do this. It is very unlikely that they ask us something like this at all, but I am very cusious and I want to know how can this be explained.
Edit: Since this is confusing to write, here is another exercise I found using this:

The numbers 20604, 53227, 25755, 20927 and 78421 are all divisible by 17. Prove that the determinant $\left| \begin{array}{ccc}
2&0&6&0&4 \\
5&3&2&2&7 \\
2&5&7&5&5 \\
2&0&9&2&7 \\
7&8&4&2&1 \end{array} \right|.$ is also divisible by 17

It's the same concept and it can be seen more clearly.

A: Here is the desired proof, for a $3\times 3$ matrix for simplicity.

*

*Add $10$ times the second column to the third column.  This doesn't change the determinant.

*Add $100$ times the first column to the third column.  This too doesn't change the determinant.  Now the third column contains values that are the rows of the original matrix.

*The gcd of those original rows divides each element of the last column of the matrix; hence by taking the Laplace expansion on that column, that gcd must divide the determinant.

A: This seems to be claiming that the matrix
$$
A = \begin{bmatrix}
1 & 4 \\
2 & 3
\end{bmatrix}
$$
whose determinant is $-5$, has a determinant that is divisible by both the number $14$ and the number $23$. Or maybe the notation $a_{i1} \ldots a_{in}$ means a product, in which case it's claiming that the determinant is divisible by both $4$ and $6$. In either case, both are false.


text:
Q: 'zsh: command not found: ng' in Visual Studio Code's integrated terminal on Mac Catalina Newer Macs (Catalina OS in my case) now have the default Z Shell aka zsh. Using a Mac zsh terminal window, I've successfully installed Angular 11.0.5 globally and created a project. I'm using nvm 0.32.2 and node 10.23.0.
However, on opening Visual Studio Code and navigating to my project within VS Code's integrated terminal, I get this error message using any ng command, such as trying to generate a component:
zsh: command not found: ng
Does anyone know how to properly set up Visual Studio Code's integrated terminal to properly identify ng commands using zsh?
I've found one possible work around here https://stackoverflow.com/a/58584109/6647188 but it uses third party tools which I'd like to avoid if possible. Is there no other known way to resolve this?

A: Here is the settings that worked for me
  "terminal.integrated.defaultProfile.osx": "zsh",
  "terminal.integrated.profiles.osx": {
    "tmux": {
      "icon": "terminal-tmux",
      "path": "tmux"
    },
    "zsh": {
      "path": "/bin/zsh"
    }
  },

A: *

*From the menu navigate to: Settings -> Features -> Terminal

*Click in "Edit in settings.json"

*Add this line(key value) to the object:
"terminal.integrated.shell.osx": "/bin/zsh"

*Close and relaunch Visual Code.

A: If this line does not work for you:
"terminal.integrated.shell.osx": "/bin/zsh"

Then try replacing "zsh" with "bash", like so:
"terminal.integrated.shell.osx": "/bin/bash"

A: try this. worked for me
alias ng="/Users/<user_name>/.npm-global/bin/ng"

https://stackoverflow.com/a/48415572

A: For the latest version of vscode at 1.62 nothing worked until I tried setting the default profile using the instructions in their docs here: https://code.visualstudio.com/docs/editor/integrated-terminal#_terminal-profiles
Not settings or commands needed just a few clicks on the IDE.

A: New suggested way by vscode:
This is deprecated, the new recommended way to configure your default shell is by creating a terminal profile
in `#terminal.integrated.profiles.osx#` and setting its profile name as the default
in `#terminal.integrated.defaultProfile.osx#`.

This will currently take priority over the new profiles settings but that will change in the future.