text:
Q: Image not getting referenced from html in angular In my angular project, I am referencing an image(book.svg) in test.component.html file, which is not working at all. In the console, it references to localhost:4200:/assets/book.svg and hence it is unable to find it
We have kind a different structure of project, with libs and apps as shown.
Please let me know where the problem is and how to fix this.
Have used require() to make it work, but this fails the test cases so not looking for require().
<button mat-icon-button >

</button>

the code structure:

project
   ----------apps
       -------------xyz-frontend
           -------------src
               -------------assets
                     ----------book.svg
   ----------libs
       -------------shared
           -------------shared-ui
               -------------src
                    ----------lib
                        ----------test
                             ----------test.component.ts
                             ----------test.component.html
                    ----------assets
                        ----------book.svg

angular.json

"projects": {
    "xyz-frontend": {
      "root": "apps/xyz-frontend/",
      "sourceRoot": "apps/xyz-frontend/src",
      "projectType": "application",
      "prefix": "apps/xyz-frontend",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "index": "apps/xyz-frontend/src/index.html",
            "main": "apps/xyz-frontend/src/main.ts",
            "polyfills": "apps/xyz-frontend/src/polyfills.ts",
            "tsConfig": "apps/xyz-frontend/tsconfig.app.json",
            "assets": [
              "apps/xyz-frontend/src/favicon.ico"
            ],
            "styles": [
              "apps/xyz-frontend/src/styles.scss",
              "libs/shared/shared-styles/src/themes/a4a-theme.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "apps/xyz-frontend/src/environments/environment.ts",
                  "with": "apps/xyz-frontend/src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": false
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "xyz-frontend:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "xyz-frontend:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "xyz-frontend:build"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "apps/xyz-frontend/tsconfig.app.json",
              "apps/xyz-frontend/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "shared-assets": {
      "root": "libs/shared/shared-assets",
      "sourceRoot": "libs/shared/shared-assets/src",
      "projectType": "library"
    },
    "shared-ui": {
      "root": "libs/shared/shared-ui",
      "sourceRoot": "libs/shared/shared-ui/src",
      "projectType": "library",
      "prefix": "xyz",
      "architect": {
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "libs/shared/shared-ui/src/test.ts",
            "tsConfig": "libs/shared/shared-ui/tsconfig.spec.json",
            "karmaConfig": "libs/shared/shared-ui/karma.conf.js"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "libs/shared/shared-ui/tsconfig.lib.json",
              "libs/shared/shared-ui/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },

A: Normally, your import should look like:

How's your angular.json file assets part looks like?
In Angular 6+ it should be like:
...
"assets": [
  "src/favicon.ico",
  "src/assets",
  // ...
],
...


text:
Q: How to edit xml file using DOM in java (really different) I want to modify the following XML file :
<TVS>
  <Tv>
   <Detail>
   <Name>abcd</Name>
   <Model>yuio</Model>
   <InStock>20</InStock>
   <Price>6000</Price>
    <Description>nmk</Description>
   </Detail>
  </TV>
  <Tv>
    <Detail>
    <Name>bgtf</Name>
    <Model>wsxz</Model>
    <InStock>20</InStock>
    <Price>1000</Price>
    <Description>uhb</Description>
    </Detail>
  </TV>
</TVS>

the edited XML file should look like this:
<TV TotalValue="2354">
    <Detail Name="nmnm" Model="lkjh" InStock="12"/>
 </TV>

That means the attribute TotalValue should be generated and added to the  from
  this  formula :
TotalValue = Price * InStock and the Name and Model and InStock nodes   should be attributes for Detail
I have the following method for deleting elements :
private static void deleteElement(Document doc) {
    NodeList TV = doc.getElementsByTagName("Detail");
    Element emp = null;
    //loop for each
    for(int i=0; i<TV.getLength();i++){
        emp = (Element) TV.item(i);
        Node DescriptionNode = emp.getElementsByTagName("Description").item(0);
        emp.removeChild(DescriptionNode);
    }

}

I need help for writing editElement method which is the hardest part!

A: Detail.java
package com.sof.test;

public class Detail implements Comparable {

    private String Name;
    private String Model;
    private int InStock;
    private int price;

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getModel() {
        return Model;
    }

    public void setModel(String model) {
        Model = model;
    }

    public int getInStock() {
        return InStock;
    }

    public void setInStock(int inStock) {
        InStock = inStock;
    }
    @Override
    public int compareTo(Object o) {

         if((((Detail)o).getInStock())*(((Detail)o).getPrice())  > (this.getInStock())*(this.getPrice()))
         {

             return -1;
         }
        return 1;
    }

}

ReadXMLFile2.java
package com.sof.test;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXMLFile2 {
    List<Detail> arrayList = new ArrayList<Detail>();

    public static void main(String argv[]) {

        try {

            File fXmlFile = new File(
                    "D:\\StackOverFlow\\DomParserTest\\src\\tvs.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            ReadXMLFile2 readXMLFile = new ReadXMLFile2();
            doc = readXMLFile.readNodes(doc);
            Document document = dBuilder.newDocument();

            readXMLFile.saveXml(readXMLFile.editXml(document));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Document editXml(Document document) throws Exception {

        Element roote = document.createElement("TVS");
        Element tvelement = null;

        Collections.sort(arrayList);

        for (Detail detail : arrayList) {

            tvelement = document.createElement("TV");

            Attr attr = document.createAttribute("TotalValue");

            attr.setValue("" + detail.getPrice() * detail.getInStock());
            tvelement.setAttributeNode(attr);

            Element det = document.createElement("Detail");
            attr = document.createAttribute("Name");

            attr.setValue(detail.getName());
            det.setAttributeNode(attr);
            attr = document.createAttribute("Model");

            attr.setValue(detail.getModel());
            det.setAttributeNode(attr);
            attr = document.createAttribute("Instock");

            attr.setValue("" + detail.getInStock());
            det.setAttributeNode(attr);

            tvelement.appendChild(det);

            roote.appendChild(tvelement);

        }
        document.appendChild(roote);

        return document;
    }

    public Document readNodes(Document doc) {

        NodeList nList = doc.getElementsByTagName("Detail");

        Detail detail = null;
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;
                detail = new Detail();

                detail.setName(eElement.getElementsByTagName("Name").item(0)
                        .getTextContent());
                detail.setModel(eElement.getElementsByTagName("Model").item(0)
                        .getTextContent());
                detail.setInStock(Integer.parseInt(eElement
                        .getElementsByTagName("InStock").item(0)
                        .getTextContent()));
                detail.setPrice(Integer
                        .parseInt(eElement.getElementsByTagName("Price")
                                .item(0).getTextContent()));

            }

            arrayList.add(detail);
        }
        return doc;
    }

    public void saveXml(Document doc) throws Exception {
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("file.xml"));
        transformer.transform(source, result);
        System.out.println("File saved!");
    }

}

I updated the answer with sorting based on "TotalValue". If you get this Accept it as answer ...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Meaning - 'the sword and the purse'
Because it lacks the legitimacy and accountability that come with election and the power that
  derives from the sword and the purse, the Supreme Court's authority rests on public acceptance of its
  status as a nonpartisan arbiter of the law.

I hazard that "purse" refers to monetary influence and that 'sword' = might and main? But why 'sword'?
Source: P301, America on Trial, Alan Dershowitz

A: As Josh61 indicates in his comments beneath the OP's question, Congress (the legislative branch) is empowered under the U.S. Constitution to pass laws to raise revenue for the federal government. Article I, Section 8 of the Constitution reads in part:

The Congress shall have Power To lay and collect Taxes, Duties, Imposts and Excises, to pay the Debts and provide for the common Defence and general Welfare of the United States...

This authority has given rise to the metaphorical idea that Congress possesses "the power of the (federal) purse."
Article II, Section 2 of the Constitution reads in part:

The President shall be Commander in Chief of the Army and Navy of the United States, and of the Militia of the several States, when called into the actual Service of the United States...

Authority over  military affairs is sometimes termed "the power of the sword," and in the United States it resides (with some limitations) in the executive branch of the government, headed by the President.

A: One explanation is that the phrase is ultimately an allusion to Jesus sending out the Apostles in Luke 22:36, where he tells them to take their purse, and if they don't have a sword, to sell the cloak and buy one. Purse is, indeed, monetary influence, as "sword" is power of force.

A:
Because it lacks the legitimacy and accountability that come with election and the power that derives from the sword and the purse, the Supreme Court's authority rests on public acceptance of its status as a nonpartisan arbiter of the law.

*

*The Supreme Court justices are not elected, so they lack the legitimacy and accountability that come with election.

*And they do not have either military or economic power.
What does their authority stem from, if not #1 and #2?  Simply from a general acceptance by the public of their position as nonpartisan judges.
That is what the quote says.  The sword refers to physical might/force: military or police power.  The purse refers to economic power: influence from owning/controlling great wealth.


text:
Q: How to fix the enviroment variable GDAL_DATA path set? I have been work with gdal in python 2.7 in windows 10 and Pycharm, and I can't fix the GDAL_DATA path in the environment. Because that I got this message:

ERROR 4: Unable to open EPSG support file gcs.csv.  Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.

I try to use command line:
set GDAL_DATA='c:/Users/User/share/epsg_csv/'

And try to use the function inside the python code:
import os
os.environ["GDAL_DATA"] = 'c:/Users/User/share/epsg_csv/'

Any suggestion?

A: For some reason that I do not understand the GDAL_DATA variable (and for that matter also the PROJ_LIB variable) are not set at installation of the GDAL packages with Anaconda 4.6.
To set these variables I do the following at the start of the program before calling any of the geo modules.
import os
os.environ['GDAL_DATA'] = os.environ['CONDA_PREFIX'] + r'\Library\share\gdal'
os.environ['PROJ_LIB'] = os.environ['CONDA_PREFIX'] + r'\Library\share'

For information for my conda environment the CONDA_PREFIX is:
c:\Users\<user_name>\Ananconda3\envs\<my_env>

Hope this helps.


text:
Q: Three.js Image Pixel coordinate to World Coordinate Mapping I'm creating a 3D object in Three.js with 6 faces. Each face has a mesh which uses a THREE.PlaneGeometry(width and height both are 256). On the mesh I'm using a JPEG picture which is 256 by 256  for the texture. I'm trying to find a way to find the world coordinate of a pixel coordinate(for example 200,250 is the pixel coordinate) on the Object3D's PlaneGeometry corresponding to where that picture was used as texture.
Object hierarchy:-
Object3D-->face(object3d) (total 6 faces)-->Each face has a mesh(planegeometry) and uses a jpeg file as texture.
Picture1 pixel coordinate-->Used to create texture for Plane1-->World Coordinate corresponding to that pixel coordinate.
Can someone please help me.
Additional information:-
Thanks for the answer. I'm trying to compare 2 results.
Method 1:- One yaw/pitch is obtained by clicking on a specific point in the 3d object(e.g, center of a particular car headlight which is the front face) using a mouse and getting the point of intersection with the front face using raycasting.
Method 2:-The other yaw/pitch is obtained by taking the pixel coordinate of the same point(center of a particular car headlight) and calculating the world space coordinate for that pixel point. Pls note that pixel coordinate is taken from the JPEG file that was used as texture to create the PlaneGeometry for the mesh(which is a child of the front face).
Do you think the above comparison approach is supposed to produce the same results, assuming all other parameters are identical between the 2 approaches?

A: Well assuming your planes are PlaneGeometry(1,1) then the local coordinate X/Y/ZZ for a given pixel is pixelX / 256, pixelY / 256 and the Z is 0.5
so something like:
var localPoint = new THREE.Vector3(px/256,py/256,0.5)
var worldPoint = thePlaneObject.localToWorld(localPoint)


text:
Q: Finding $\cos ( 2 \sin^{-1}( \frac{5}{ 13} )) $ The following problem is from the $8$th edition of the book Calculus, by James Stewart. It is problem number $9$ in section $6.6$.
Problem:
Find an exact value for the expression:
$$ \cos{\left(  2 \sin^{-1}\left( \frac{5}{13} \right) \right)  } $$
Answer:
\begin{align*}
\cos{\left(  2 \sin^{-1}\left( \frac{5}{13} \right) \right)  } &=
 \sqrt{  1 - \sin^2{\left(  2 \sin^{-1}\left( \frac{5}{13} \right) \right)  } } \\
%
\cos{\left(  2 \sin^{-1}\left( \frac{5}{13} \right) \right)  } &=
 \sqrt{  1 - 2 \sin^2{\left(  \sin^{-1}\left( \frac{5}{13} \right) \right)  } \cos^2{\left(  \sin^{-1}\left( \frac{5}{13} \right) \right)  } } \\
%
\cos{\left(  2 \sin^{-1}\left( \frac{5}{13} \right) \right)  } &=
 \sqrt{  1 - 2 \left( \frac{25}{13^2} \right)  \cos^2{\left(  \sin^{-1}\left( \frac{5}{13} \right) \right)  } } \\
%
\cos{\left(  2 \sin^{-1}\left( \frac{5}{13} \right) \right)  } &=
 \sqrt{  1 - \left( \frac{50}{13^2} \right)  \cos^2{\left(  \sin^{-1}\left( \frac{5}{13} \right) \right)  } } \\
\end{align*}
\begin{align*}
\cos^2{\left(  \sin^{-1}\left( \frac{5}{13} \right) \right) } &=
 1 - \sin^2{\left(  \sin^{-1}\left( \frac{5}{13} \right) \right) } \\
\cos^2{\left(  \sin^{-1}\left( \frac{5}{13} \right) \right) } &= 1 - \frac{25}{169} = \frac{169 - 25}{169} \\
\cos^2{\left(  \sin^{-1}\left( \frac{5}{13} \right) \right) } &= \frac{144}{169} \\
\cos{\left(  2 \sin^{-1}\left( \frac{5}{13} \right) \right)  } &=
 \sqrt{  1 - \left( \frac{50}{13^2} \right)  \left(  \frac{144}{169} \right) } \\
\cos{\left(  2 \sin^{-1}\left( \frac{5}{13} \right) \right)  } &= \sqrt{  \frac{13^4 - 50(144)}{13^4}  } \\
\cos{\left(  2 \sin^{-1}\left( \frac{5}{13} \right) \right)  } &= \sqrt{  \frac{21361}{13^4}  } \\
\cos{\left(  2 \sin^{-1}\left( \frac{5}{13} \right) \right)  } &=  \frac{  \sqrt{ 21361 } } { 169 }
\end{align*}
The book's answer is $\frac{119}{169}$ and SciLab matches the book. Where did I go wrong?

A: Your mistake is when you squared $\sin2\theta$, it should be $4\sin^{2}\theta\cos^{2}\theta$ not $2\sin^{2}\theta\cos^{2}\theta$, but in case you want an easier method than going for a long method, here is one:
Just let $\displaystyle \theta=\sin^{-1}\left(\frac{5}{13}\right)$ so that we have $\sin \theta=\dfrac{5}{13}$ and now we know that $\displaystyle \cos 2\theta=1-2\sin^{2}\theta=1-2\left(\frac{5}{13}\right)^2=\frac{119}{169}.$

A: In the second line there is a mistake!
$$\sin^22\alpha=4\sin^2\alpha\cos^2\alpha.$$
Now, $$\cos2\arcsin\frac{5}{13}=\sqrt{1-4\left(\frac{5}{13}\right)^2\left(\frac{12}{13}\right)^2}=\frac{119}{169}.$$

A: Alternative solution:
Let $sin^{-1}(\frac{5}{13})=x$, then $\sin x=\frac{5}{13},\space \cos x=\frac{12}{13}$
$\cos 2x=1-2\sin^2x=1-2\times(\frac{5}{13})^2=\frac{119}{169}$


text:
Q: dijit tree seleted node icon change I am using dojo version 1.10.2 and claro theme.
I do not want folder icon for tree node, which I have achieved using getIconClass. Now I have requirement to highlight the selected node with closefolder(or any other image) in front of node and color of the node label 'red'.  I am able to change color of the node label, but not able to display the image in front of selected node. Please advice me to resolve the same.
the fiddle link is given below:
http://jsfiddle.net/pyz9Lcpv/1/
require([
"dojo/_base/window", "dojo/store/Memory",
"dijit/tree/ObjectStoreModel", "dijit/Tree",
"dojo/domReady!"

], function(win, Memory, ObjectStoreModel, Tree){
// Create test store, adding the getChildren() method required by ObjectStoreModel
var myStore = new Memory({
    data: [
        { id: 'world', name:'The earth', type:'planet', population: '6 billion'},
        { id: 'AF', name:'Africa', type:'continent', population:'900 million', area: '30,221,532 sq km',
                timezone: '-1 UTC to +4 UTC', parent: 'world'},
            { id: 'EG', name:'Egypt', type:'country', parent: 'AF' },
            { id: 'KE', name:'Kenya', type:'country', parent: 'AF' },
                { id: 'Nairobi', name:'Nairobi', type:'city', parent: 'KE' },
                { id: 'Mombasa', name:'Mombasa', type:'city', parent: 'KE' },
            { id: 'SD', name:'Sudan', type:'country', parent: 'AF' },
                { id: 'Khartoum', name:'Khartoum', type:'city', parent: 'SD' },
        { id: 'AS', name:'Asia', type:'continent', parent: 'world' },
            { id: 'CN', name:'China', type:'country', parent: 'AS' },
            { id: 'IN', name:'India', type:'country', parent: 'AS' },
            { id: 'RU', name:'Russia', type:'country', parent: 'AS' },
            { id: 'MN', name:'Mongolia', type:'country', parent: 'AS' },
        { id: 'OC', name:'Oceania', type:'continent', population:'21 million', parent: 'world'},
        { id: 'EU', name:'Europe', type:'continent', parent: 'world' },
            { id: 'DE', name:'Germany', type:'country', parent: 'EU' },
            { id: 'FR', name:'France', type:'country', parent: 'EU' },
            { id: 'ES', name:'Spain', type:'country', parent: 'EU' },
            { id: 'IT', name:'Italy', type:'country', parent: 'EU' },
        { id: 'NA', name:'North America', type:'continent', parent: 'world' },
        { id: 'SA', name:'South America', type:'continent', parent: 'world' }
    ],
    getChildren: function(object){
        return this.query({parent: object.id});
    }
});

// Create the model
var myModel = new ObjectStoreModel({
    store: myStore,
    query: {id: 'world'}
});

// Create the Tree.
var tree = new Tree({
    model: myModel,
    getIconClass:function(item, opened){
            console.log('tree getIconClass', item, opened);
            console.log('tree item type', item.type);
        },
    onClick: function(item, node) {
            node._iconClass= "dijitFolderClosed";
            node.iconNode.className = "dijitFolderClosed";
            console.log("node : " +node);

        }
});
tree.placeAt(contentHere);
tree.startup();

});

A: You should be able to change the icon via css, for example, this will change the icon on the selected tree node to a gradient:
.claro .dijitTreeRowSelected .dijitTreeExpando {
    background-image: url("http://archive.dojotoolkit.org/nightly/checkout/dijit/themes/claro/images/standardGradient.png");
    background-position: 0px 0px;
}

Here is the updated jsfiddle.
http://jsfiddle.net/pyz9Lcpv/4/


text:
Q: Thread local BigInteger variable in nested Parallel.For is not processed for aggregation with standard patterns? I tryed to refactor a nested sequential for loop into a nested Parallel.For loop.
But following the recommended parallel patterns and locks, the overall result was too low compared with the sequential result.
The problem was caused by a wrong or inconsistent use of BigInteger calculation methods.
For BigInteger you need to use ++-operator or BigInteger methods like BigInteger.Add().
My sources:

*

*How to: Write a Parallel.For Loop with Thread-Local Variables

*Threading in C# - Parallel Programming - The Parallel Class - For and ForEach
Please find sample code below:
    internal static class Program
    {
        static Object lockObj = new Object();
        static void Main()
        {
            //target result: 575
            NestedLoopAggregationTest();
            return;
        }

        private static void NestedLoopAggregationTest()
        {
            BigInteger totalSequential = 0;
            BigInteger totalRecomandedPattern = 0;
            BigInteger totalAntiPattern = 0;

            const int iEnd1 = 5;
            const int iEnd2 = 10;
            const int iEnd3 = 15;

            for (int iCn1 = 1; iCn1 <= iEnd1; iCn1++)
            {
                for (int iCn2 = 1; iCn2 <= iEnd2; iCn2++)
                {
                    for (int iCn3 = iCn2 - 1; iCn3 <= iEnd3; iCn3++)
                    {
                        totalSequential++;
                    }
                }
            }

            Parallel.For(1, iEnd1 + 1, (iCn1) =>
            {
                Parallel.For(1, iEnd2 + 1, (iCn2) =>
                {
                    Parallel.For<BigInteger>(iCn2 - 1, iEnd3 + 1, () => 0, (iCn3, state, subtotal) =>
                    {
                        //Solution:
                        //for BigInteger use ++-operator or BigInteger.Add()
                        subtotal = BigInteger.Add(subtotal, 1);
                        return subtotal;
                    },
                    (subtotal) =>
                    {
                        lock (lockObj)
                        {
                            totalRecomandedPattern = BigInteger.Add(totalRecomandedPattern, subtotal);
                        }
                    }
                     );
                });
            });

            MessageBox.Show(totalSequential.ToString() + Environment.NewLine + totalRecomandedPattern.ToString() +
        }
    }

A: Your current parallel implementation requires a lock every time subtotal is modified in the inner loop. This modified approach is faster than both your serial and parallel implementaions because it avoids a lock in the innermost loop:
Parallel.For(1, iEnd1 + 1, (iCn1) =>
{
    Parallel.For(1, iEnd2 + 1, (iCn2) =>
    {
        BigInteger subtotal = 0;
        for (var iCnt3 = iCn2 - 1; iCnt3 < iEnd3 + 1; iCnt3++)
        {
            //Solution:
            //for BigInteger use ++-operator or BigInteger.Add()
            subtotal = BigInteger.Add(subtotal, 1);
        }
        lock (lockObj)
        {
            totalRecomandedPatternModified = BigInteger.Add(totalRecomandedPatternModified, subtotal);
        }
    });
});

I increased each of the endpoints by a factor of 10 so the runtime is long enough to be measured on my hardware, then got the following average times:
Serial:   9ms
Parallel: 11ms
Modified: 2ms


text:
Q: using angularjs consecutive ng-include directive Why using consecutive angular ng-include does not work?
for example:

only show the content of partial1.html
but if I use:

Works fine, displays the content of both pages.
Thanks.

A: Add the ending tag for the divs:


text:
Q: Using lapply with Dates and the minus function I have a vector of dates and a vector of number-of-days.
dates <- seq(Sys.Date(), Sys.Date()+10, by='day')
number.of.days <- 1:4

I need to get a list with an entry for each number-of-days, where each entry in the list is the dates vector minus the corresponding number-of-days, ie.,
list(dates-1, dates-2, dates-3, dates-4)

The defintion of - (function (e1, e2)  .Primitive("-")) indicates that its first and second arguments are e1 and e2, respectively. So the following should work.
lapply(number.of.days, `-`, e1=dates)

But it raises an error.

Error in -.Date(X[[i]], ...) : can only subtract from "Date" objects

Furthermore, the following does work:
lapply(number.of.days, function(e1, e2) e1 - e2, e1=dates)

Is this a feature or a bug?

A: You can use:
lapply(number.of.days, `-.Date`, e1=dates)

Part of the problem is - is a primitive which doesn't do argument matching.  Notice how these are the same:
> `-`(e1=5, e2=3)
[1] 2
> `-`(e2=5, e1=3)
[1] 2

From R Language Definition:

This subsection applies to closures but not to primitive functions. The latter typically ignore tags and do positional matching, but their help pages should be consulted for exceptions, which include log, round, signif, rep and seq.int.

So in your case, you end up using dates as the second argument to - even though you attempt to specify it as the first.  By using the "Date" method for -, which is not a primitive, we can get it to work.
So technically, the behavior you are seeing is a feature, or perhaps a "documented inconsistency".  The part that could possibly considered a bug is that R will do a multiple dispatch to a "Date" method for - despite that method not supporting non-date arguments as the first argument:
> 1:4 - dates  # dispatches to `-.Date` despite first argument not being date
Error in `-.Date`(1:4, dates) : can only subtract from "Date" objects

A: You might be better off using POSIXt dates. They're a bit more flexible, for example if you wanted to add a week or year. The equivalent answer to @BrodieG using lubridate functionality to work with POSIXt:
dates <- ymd(seq(Sys.Date(), Sys.Date()+10, by='day'))
number.of.days <- 1:4

list(dates-1, dates-2, dates-3, dates-4)

lapply(number.of.days, `-.POSIXt`, e1=dates)

Also, how's the fishing in Philly? :)


text:
Q: Magento: Products missing old-prices, keeps lines from being straight In grid mode displaying the products, I would like the "Add to cart" buttons to line up. But beacause only som of my products have old-price, the once who lack it will display the button one line higher up. I have looked in prices.phtml without finding out where to edit.
td;dr: How to add a empty line in catalog if the old-price is empty?

A: Default themes have this CSS;
.products-grid .actions {
    bottom: 12px;
    position: absolute;
}

...which ensures the elements containing add to cart buttons line up.


text:
Q: How can I mount a partition on every reboot using Bash Script? I have a partition mounted with mount /mnt/filesys.bin /mnt/mymnt/
Each time I reboot, I need to remount. How can I keep this mounted after every reboot?

A: @pa4080 is totally right, but the really easy solution is (running as the superuser, so sudo su first):
mount /mnt/filesys.bin /mnt/mymnt/
grep mymnt /etc/mtab >>/etc/fstab

The first line mounts your device with whatever other options you need, the second will put it into /etc/fstab with the same options so that it gets mounted on every reboot.

A: From man fstab:

The file /etc/fstab contains descriptive information about the filesystems the system can mount. fstab is only read by programs, and not written; it is the duty of the system administrator to properly create and maintain this file.

To do what you want you just need to add an entry for this mount in /etc/fstab as follows:

*

*Open new terminal window Ctrl+Alt+T.

*Open the file /etc/fstab for edit with root privileges, using nano:
sudo nano /etc/fstab

*Go to the bottom of the file and add the following line - here I'm assuming it is an image file, so we need to use the loop option (reference):
/mnt/filesys.bin /mnt/mymnt/ auto nofail,defaults,loop 0 0

If you want to mount physical device (or partition), you can identify it by several different ways, for example by its UUID. To find the UUID use sudo blkid while the device is mounted (or use the GUI tool Disks). In this case the entry could look like:
/dev/disk/by-uuid/a58b40e4-eb9b-4720-835b-785a3be3ae33 /mnt/mymnt/ auto nosuid,nodev,nofail 0 0

or:
UUID=a58b40e4-eb9b-4720-835b-785a3be3ae33 /mnt/mymnt/ auto nosuid,nodev,nofail 0 0

Where a58b40e4-eb9b-4720-835b-785a3be3ae33 is the UUID of your device.

*Save the file: Ctrl+O, then exit from nano: Ctrl+X.

*Restart the system or type sudo mount -a to see the result.
Do not forgot to remove that entry if you remove the image file.


text:
Q: yocto recipe for an application that uses dlib and opencv I made a yocto recipe for dlib and also I added opencv package in local.conf.
Now I want to make a recipe for an application that uses dlib and opencv libraries. I tried the following recipe, but when I try to build it with bitbake application, it throws me some errors.
dlib recipe:
SUMMARY = "A toolkit for making real world machine learning and data analysis applications"
HOMEPAGE = "https://github.com/davisking/dlib"

LICENSE = "Boost-Software"
LIC_FILES_CHKSUM = "file://dlib/LICENSE.txt;md5=2c7a3fa82e66676005cd4ee2608fd7d2 \
                    file://dlib/external/pybind11/LICENSE;md5=beb87117af69fd10fbf9fb14c22a2e62 \
                    file://dlib/external/libpng/LICENSE;md5=243135ddedf702158f9170807cbcfb66 \
                    file://docs/docs/license.xml;md5=2e6ff4080dcb217d4d300b90e9aabb5b \
                    file://examples/LICENSE_FOR_EXAMPLE_PROGRAMS.txt;md5=57eee82829ed297e23d84de5f905afee \
                    file://examples/video_frames/license.txt;md5=127ee508b60a6be9dea8af3b441993dc \
                    file://python_examples/LICENSE_FOR_EXAMPLE_PROGRAMS.txt;md5=064f53ab40ea2b6a4bba1324149e4fde"

SRC_URI = "git://github.com/davisking/dlib.git;protocol=https"

PV = "1.0+git${SRCPV}"
SRCREV = "3b794540baeabbcd033b544230401967106d5483"

S = "${WORKDIR}/git"

do_compile() {
        cd ${S}
        cd dlib
        mkdir build
        cd build
        cmake ..
        sudo make install
}

FILES_${PN} += "/${base_prefix}"
inherit cmake

application recipe:
DESCRIPTION = "Simple application"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://application.cpp;md5=df22013877ba7d830e9993ae1d77d724"

SRC_URI = "file://application.cpp"

S = "${WORKDIR}"

do_compile() {
        ${CXX}  -std=c++11 -O3 -L${libdir}/libdlib.a -I${includedir}/dlib/ -lpthread -lX11  application.cpp ${LDFLAGS} `pkg-config --cflags --libs opencv` -o application
}

do_install() {
        install -d ${D}${bindir}
        install -m 0755 application ${D}${bindir}
}

some errors when I try bitbake application:
| application.cpp:(.text._ZN4dlib30entropy_decoder_model_kernel_5ILm257ENS_24entropy_decoder_kernel_2ELm200000ELm4EE6decodeERm[_ZN4dlib30entropy_decoder_model_kernel_5ILm257ENS_24entropy_decoder_kernel_2ELm200000ELm4EE6decodeERm]+0x1a8): undefined reference to `dlib::entropy_decoder_kernel_2::get_target(unsigned int)'
| application.cpp:(.text._ZN4dlib11pinv_helperINS_9matrix_opINS_8op_transINS_6matrixIdLl3ELl0ENS_33memory_manager_stateless_kernel_1IcEENS_16row_major_layoutEEEEEEEEEKNS3_INT_4typeEXsrSA_2NCEXsrSA_2NRENSA_16mem_manager_typeES6_EERKNS_10matrix_expISA_EEd[_ZN4dlib11pinv_helperINS_9matrix_opINS_8op_transINS_6matrixIdLl3ELl0ENS_33memory_manager_stateless_kernel_1IcEENS_16row_major_layoutEEEEEEEEEKNS3_INT_4typeEXsrSA_2NCEXsrSA_2NRENSA_16mem_manager_typeES6_EERKNS_10matrix_expISA_EEd]+0x4fc): undefined reference to `cblas_dgemm'
| application.cpp:(.text._ZN4dlib28get_serialized_frontal_facesB5cxx11Ev[_ZN4dlib28get_serialized_frontal_facesB5cxx11Ev]+0x8e9c): undefined reference to `dlib::base64::~base64()'

What can I do in order to slove this problem?

A: Change the dlib recipe to
SUMMARY = "A toolkit for making real world machine learning and data analysis applications"
HOMEPAGE = "https://github.com/davisking/dlib"

LICENSE = "Boost-Software"
LIC_FILES_CHKSUM = "file://dlib/LICENSE.txt;md5=2c7a3fa82e66676005cd4ee2608fd7d2 \
                    file://dlib/external/pybind11/LICENSE;md5=beb87117af69fd10fbf9fb14c22a2e62 \
                    file://dlib/external/libpng/LICENSE;md5=243135ddedf702158f9170807cbcfb66 \
                    file://docs/docs/license.xml;md5=2e6ff4080dcb217d4d300b90e9aabb5b \
                    file://examples/LICENSE_FOR_EXAMPLE_PROGRAMS.txt;md5=57eee82829ed297e23d84de5f905afee \
                    file://examples/video_frames/license.txt;md5=127ee508b60a6be9dea8af3b441993dc \
                    file://python_examples/LICENSE_FOR_EXAMPLE_PROGRAMS.txt;md5=064f53ab40ea2b6a4bba1324149e4fde"

SRC_URI = "git://github.com/davisking/dlib.git;protocol=https"

PV = "1.0+git${SRCPV}"
SRCREV = "3b794540baeabbcd033b544230401967106d5483"

S = "${WORKDIR}/git"

inherit cmake

EXTRA_OECMAKE += "-DDLIB_NO_GUI_SUPPORT=ON -DBUILD_SHARED_LIBS=ON"

Then in your application recipe
DESCRIPTION = "Simple application"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://application.cpp;md5=df22013877ba7d830e9993ae1d77d724"

inherit pkgconfig
DEPENDS += "dlib opencv"

SRC_URI = "file://application.cpp"

S = "${WORKDIR}"

do_compile() {
        ${CXX} ${CXXFLAGS} -std=c++11 -O3 -I${STAGING_INCDIR}/dlib -pthread application.cpp -o application ${LDFLAGS} `pkg-config --cflags --libs opencv` -lX11 -ldlib
}

do_install() {
        install -D -m 0755 application ${D}${bindir}/application
}

A: You might want to update the license in the recipe otherwise the example provided by Khem will return a warning. The Boost License is:
LICENSE = "BSL-1.0"
LIC_FILES_CHKSUM = "file://LICENSE.txt;md5=2c7a3fa82e66676005cd4ee2608fd7d2"


text:
Q: Reliable test for intersection of two Bezier curves Is there a test which reliably decides whether two Bezier curves intersect or not?
I don't need to know how many intersections there are or at what parameters they appear at. I just would like to know if there is some intersection or not. By "reliably" I mean that there should be no false positives or false negatives: for instance, checking if the bounding boxes overlap is not "sufficient" as they might overlap even if there is no curve intersection.
Alternatively, if it helps, I would be also interested in a weaker test: it would answer "yes" if the curves intersect (one or more times). If  the curves don't intersect this test's answer would be "yes" or "no", meaning that false positives would be allowed.
An example of what I'm after: according to Rational polynomial parametric/rational polynomial parametric curve intersection, "If the two wedges do not overlap, the curves cannot intersect more than once". This would answer my question, were it "more than zero" instead.

A: I'd test the convex hulls of the control points for overlap.

*

*If there is no overlap, then the answer is definitely "no" because the curves stay inside the convex hull.

*If there is overlap in such a way that the endpoints of the first curve are not inside the convex hull for the second curve, and vice versa, and the direct connections of the endpoints intersect, then the answer is "yes"

*Otherwise (i.e., there is overlap, but one curve might sneak around the other) the asnwer is "maybe" and we can recurse: Subdivide both of the curves (or just one? But which one?) and check each combination. This looks like it might become exponential but in most real life situations only one of the four sub-pairs should ba a "maybe" case again.

It may be advisable to stop recursion at a certain depth (and answer "yes"). Otherwise, touching curves might cause "stack overflow".
Also, if you limit yourself to a fixed number (three, say) of recursions, you can both be sure to bound the complexity while at the same time producing false positives at most (and presumably only in rare situations.
The heuristic is that after a few subdivisions, the subcurves are so little bent (i.e., the convex hulls are very "thin" compared to their lengths) that we may expect either a "no" or a clear "yes".

A: As far as I know, there is no certified and complete method that can determine arbitrary intersections without transformations and implicitization. However, the bounding box checks, including repeated subdivision of the curves to some application-dependent resolution, are excellent filters for curves in general position.
As you already noticed, a purely numerical method (including subdivision when you only use fixed-precision floating point arithmetics) will not be able to reliably handle degeneracies like (nearly) tangential intersections. The argument is the same as in the univariate case, just that the precision bounds are even worse in higher dimension.
For the bivariate solving, the main methods to analyze and intersect (pairs of) algebraic curves in monomial basis are RUR (rational univariate representation) by Fabrice Rouillier et al. and CAD (cylindrical algebraic decomposition).
The former involves some not-so-lightweight algebraic machinery like Gröbner bases, the latter can be done with GCD and resultant computations only. Note that I'm oh-so-slightly biased both as an author of a state-of-the-art variant of the latter method and as a coauthor of Fabrice. Obviously, algebraic curve analysis is a well-studied topic, and I refer to the small selection of a vast number of references that is mentioned in that paper.
I also met and worked with Chee Yap who's the author of the paper you mentioned, but didn't know this work. From a very, very quick glance, he needs a genericity assumption that ensures that sufficient refinement eventually reveals only ordinary intersections. In particular, the method does not seem to handle tangential intersections.
Any complete approach with both variants will require exact or bigfloat arithmetic, but that alone will not give you a complete algorithm unless you compute with a priori worst-case precision bounds. More elegant formulations use adaptive precision handling and combine symbolic and numeric computations. The crucial ingredients are, again, univariate polynomial root isolation as well as GCD, (sub-)resultants and/or Gröbner basis computations, depending on your favorite method.
I vaguely remember rumours about resultant computations in Bernstein basis, but IIRC, none of them has been investigated and developed to the point of a complete solver. From a theoretical point of view, there is some evidence and conjectures – but no proof! – that conversion to implicit form is not a bottleneck step (and that, indeed, the previously mentioned method might be asymptotically optimal). Again, the conjecture basically boils down to univariate root isolation complexity and precision demand bounds. In practice, the situation might be different; but I guess that the difference is negligible for the degenerate or "almost degenerate" situations that remain after some filter steps (essentially, intersection of convex hulls of control point polygons).
BTW, for implementations, have a look at the CGAL project; it features a library for 2D arrangements according to the exact geometric computation paradigm. (Again, I'm biased because... You know. Just one of many, many wheels here in all those developments.)

A: I think you're asking for something impossible, so you'll have to compromise somewhere.
I assume that you will implement the algorithm using floating point arithmetic, and that's one of the big sources of trouble. Two curves can be arbitrarily close without intersecting, so you have to define what you mean by "intersection" in floating point arithmetic. I suggest that a reasonable definition of an intersection is a pair of points, one lying on each curve, whose distance apart is less than some small number $\varepsilon$. And, of course, $\varepsilon$ will need to be an order of magitude (or two) bigger than the error $\delta$ involved in calculating points on the curve. Using double precision arithmetic, and assuming your curves are of unit size, $\delta$ will be around $10^{-14}$, so $\varepsilon$ will need to be around $10^{-12}$, say.
Depending on your application, it might make sense to use a much larger value for $\varepsilon$. For engineering or manufacturing, $10^{-7}$ is probably good enough, and for graphics $10^{-5}$ might suffice. Once you have chosen $\varepsilon$, you know when you can stop the various subdivision processes that compute intersections.
There is a pretty thorough analysis of intersection algorithms in Tom Sederberg's notes. But most of the techniques are based on bounding volume tests and subdivision, which you don't seem to like.
In this chapter of his notes, and in a paper in Computer-Aided Design
Volume 18, Issue 1, January–February 1986, Pages 58–63, Sederberg discusses intersection calculation by implicitization. This is much faster than subdivision-based techniques for curves of low degree (less that 5 or so). The idea is to obtain an implicit equation $F(x,y)=0$ for one of the curves. Then if the other curve has parametric equation $C(t)$, the intersection points are the roots of the polynomial equation $\phi(t) = F(C(t))=0$. In floating point arithmetic, $\phi(t)$ will never be zero, of course, so you still have to deal with the $\varepsilon$ problem I outlined above. And, in fact, in this scenario, the $\varepsilon$ problem is harder because the value of $\phi$ has no clear geometric meaning, so it's hard to decide how small a value indicates an "intersection".

A: If you are talking about quadratic bezier curves like from a TrueType font definition etc, then (except for the horizontal line case) you can solve for $x$ as a function of $y$ (something you'd already have code for, to rasterize the interior, etc.) and there are 2 cases (for simplicity, consider the full unbounded curves, for unbounded $t$):

*

*non-degenerate case: $x = Ay + B \pm\sqrt{Cy + D}$

*degenerate: $x = Ay^2 + By + C$
Set two of the above kinds of functions to be equal, and square away the square-roots, and you get a quartic formula that can be solved in closed form. (It seems you always get a quartic if one of the curves is non-degenerate, so there's no way to rotate or skew $x$ and $y$ to make it into something lower-order, unfortunately).
Be sure to back-test the answer because extending to unbounded $t$ introduces false positives. To back-test, chop the curve into sections that are monotonic in both $x$ and $y$ (something you'd do anyway for initial bounding-box tests. This also gives you a single square-root signum to work on at a time.) Then you get bounding boxes for the two sections you're working on and you can easily check whether your answer is within both boxes.
There is also the case where one of the "bezier curves" is a horizontal line, but if you happen to be using this for banded union/intersection operations the horizontal line case already falls away. Finally, as others have noted, floating-point arithmetic will have problems when the curves are "near intersection" so you have to accept some inaccuracy there. Oh and the quartic formula solver code is complicated and can easily end up with hard-to-find bugs.


text:
Q: IAnnotationTransformer Method Description in TestNG When implementing IAnnotationTransfer interface in TestNG, there is a parameter called annotation which is the annotation that would get read from the test class. Now, there are few methods that are straightforward whereas various methods of annotation that I am not able to understand (such as getAttributes). Can someone point me to example usages (descriptions) of these methods so that I can come to know how to use some of these methods.
Specifically, what getAttributes return?
I tried to use it (CustomAttribute[] cs = annotation.getAttributes();) but I am getting nothing in cs variable.
All the methods in the IAnnotation interface can be accessed below:
https://javadoc.io/doc/org.testng/testng/7.1.0/org/testng/annotations/ITestAnnotation.html

A: Below is a sample that shows how to work with CustomAttribute. The other methods are all self explanatory.
The test class that uses CustomAttribute would look like below:
import org.testng.Reporter;
import org.testng.annotations.CustomAttribute;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.Optional;

public class SampleTestClass {

    @Test(attributes = {
            @CustomAttribute(name = "functionality", values = {"login", "oauth"}),
            @CustomAttribute(name = "flavor", values = {"bvt", "regression"})
    })
    public void customAttributeEnabledTestMethod() {
        System.err.println("Printing the custom attributes from test method");
        CustomAttribute[] attributes = Optional
                .ofNullable(
                        Reporter.getCurrentTestResult().getMethod().getAttributes())
                .orElse(new CustomAttribute[]{});
        Arrays.stream(attributes).forEach(attribute -> {
            System.err.println("Attribute Name : " + attribute.name());
            System.err.println("Attribute values : " + Arrays.toString(attribute.values()));
        });
    }

    @Test
    public void plainTestMethod() {
        System.err.println("Hello world again");
    }
}

The custom annotation transformer that alters value for this:
import org.testng.IAnnotationTransformer;
import org.testng.annotations.CustomAttribute;
import org.testng.annotations.ITestAnnotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Optional;

public class DemoAnnotationTransformer implements IAnnotationTransformer {

    @Override
    public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {

        CustomAttribute[] attributes = annotation.getAttributes();
        //We need this filtering logic because there's currently a bug in TestNG 7.1.0
        //which causes the annotation transfomer to be invoked multiple times.
        //This should be resolved in TestNG v7.2.0
        //The defect to refer to : https://github.com/cbeust/testng/issues/2312
        Optional<CustomAttribute> found = Arrays.stream(attributes)
                .filter(each -> each.name().equalsIgnoreCase("supported-browsers"))
                .findAny();

        if (found.isPresent()) {
            return;
        }

        int size = attributes.length + 1;
        CustomAttribute[] copied = new CustomAttribute[size];
        System.arraycopy(attributes, 0, copied, 0, attributes.length);
        copied[attributes.length] = new CustomAttribute() {

            @Override
            public Class<? extends Annotation> annotationType() {
                return CustomAttribute.class;
            }

            @Override
            public String name() {
                return "supported-browsers";
            }

            @Override
            public String[] values() {
                return new String[]{"firefox", "chrome"};
            }
        };
        annotation.setAttributes(copied);
    }
}

Here's how the suite xml looks like :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="qn_62287783_suite" parallel="false" configfailurepolicy="continue">
    <listeners>
        <listener class-name="com.rationaleemotions.stackoverflow.qn62287783.DemoAnnotationTransformer"/>
    </listeners>
    <test name="qn_62287783_test" verbose="2">
        <classes>
            <class name="com.rationaleemotions.stackoverflow.qn62287783.SampleTestClass"/>
        </classes>
    </test>
</suite>

Here's how the output looks like:
Printing the custom attributes from test method
Attribute Name : functionality
Attribute values : [login, oauth]
Attribute Name : flavor
Attribute values : [bvt, regression]
Attribute Name : supported-browsers
Attribute values : [firefox, chrome]

Hello world again

PASSED: customAttributeEnabledTestMethod
PASSED: plainTestMethod

===============================================
    qn_62287783_test
    Tests run: 2, Failures: 0, Skips: 0
===============================================

===============================================
qn_62287783_suite
Total tests run: 2, Passes: 2, Failures: 0, Skips: 0
===============================================

Process finished with exit code 0


text:
Q: Copy array from certain position to another array in c I have array A and i want to copy this array from position x till y to another array in C language. Please help in creating it in c.
Using memcpy copies array from beginning only. I want to copy from particular position to another position.

A: int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int b[5];

memcpy( b, a + 5, 5 * sizeof( int ) );

Also you can do this using an ordinary for loop
for ( int i = 0; i < 5; i++ ) b[i] = a[i+5];

A: Since you are copying into another array, you can use memcpy():
memcpy(another_array, array + x, (y - x) * sizeof(*array));

If you were copying into the same array, you should use memmove() instead.
memmove(array + z, array + x, (y - x) * sizeof(*array));

For each, the first parameter denotes the destination, and the functions assume the destination has enough space to accept the complete copy.

A: memcpy only copies from the beginning of an array if that's what address you pass it. The name of an array a is synonymous with the address of the first element &a[0], so if you do memcpy(dest, src, size), then the copy will be from the start of the array src.
Pointer arithmetic can be used to start the copy from a point further along in your array. For example, to copy 10 elements starting from element 2 in array src, you can do this:
size_t size = 10 * sizeof (int);
int * dest = malloc(size);
memcpy(dest, src + 2, size);  // or equivalently, &src[2]

A: for(i=x, j=0; i<=y; i++, j++)
   AnotherArray[j]= A[i];

A: Copy arrays with memcpy
void * memcpy (void * destination, void * source, size_t size)

The memcpy function copies an certain amount of bytes from a source memory location and writes them to a destinaction location. (Documentation)
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int some_array[] = {10, 11, 12, 13, 14};

    int memory_amount = sizeof(some_array);
    int item_count = memory_amount / sizeof(some_array[0]);
    int *pointer = malloc(memory_amount);
    memcpy(pointer, &some_array, memory_amount);

    while (item_count--)
        printf("%d=%d\n", item_count, *(pointer + item_count));

    free(pointer);
    return 0;
}

Output
$ ./a.out
4=14
3=13
2=12
1=11
0=10


text:
Q: Calculate the display width of a string in C#? A Java version of this question was just answered, and, well, I don't know how to do this in .net.
So how do you calculate the display width of a string in C# / .net?

A: Graphics.MeasureString but its a bit crappy, as is explained and improved upon; here

A: An alternative for Windows Forms is the static TextRenderer.MeasureText method.
Although restricted to integer sizes, this (in tandem with TextRenderer.DrawText) renders more accurate and much higher quality ClearType text than the Graphics.MeasureString/DrawString duo.

A: You've got the same problem in this question as was present in the Java question - not enough information! It will differ between WinForms and WPF.
For WinForms: Graphics.MeasureString
For WPF I'm not sure, but I suspect it will depend on the exact way you're drawing the text...

A: You would use Graphics.MeasureString.
http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

A: In WPF you would use FormattedText.

A: Graphics.MeasureString([text to measure],[font being used to measure text]);
The resulting object will provide the following:

Other overloads of MeasureString also available.


text:
Q: re.sub - multi value and multi lines substitution Let's say we have file in.conf with text:
line1 = %var1%
line2 = %var2%
line3 = %var3%

And we have script, which must replace all %var(s)% in in.conf and generate new file - out.conf:
#!/usr/bin/env python

import re

infile = 'in.conf'
outfile = 'out.conf'

change_vars_list = ('%var1%', '%var2%', '%var3%')
change_values_list = ('newvalue1', 'newvalue2', 'newvalue3')

with open(infile, 'r') as inconf:
    lines = inconf.read()

    print('\nRaw lines:\n\n%s' % lines)
    print('\nVars to change:')
    print(change_vars_list)

    outdata = re.sub(r'%var1%', 'NEWVALUE', lines)
    print('\nNew data:\n\n%s\n' % outdata)

with open(outfile, 'w') as outconf:
    outconf.write(outdata)

While re.sub called for only %var1% - this works excellent:
$ ./replace.py

Raw lines:

line1 = %var1%
line2 = %var2%
line3 = %var3%

Vars to change:
('%var1%', '%var2%', '%var3%')

New data:

line1 = NEWVALUE
line2 = %var2%
line3 = %var3%

$ cat out.conf
line1 = NEWVALUE
line2 = %var2%
line3 = %var3%

But - how can I realize, that same script can replace all %var(s)% with given values from change_values_list and save them to new file out.conf?
So - out.conf must looks like:
line1 = newvalue1
line2 = newvalue2
line3 = newvalue3

A: Editing your initial code:
#!/usr/bin/env python

import re

infile = 'in.conf'
outfile = 'out.conf'

change_vars_list = (r'%var1%', r'%var2%', r'%var3%')
change_values_list = ('newvalue1', 'newvalue2', 'newvalue3')

with open(infile, 'r') as inconf:
    lines = inconf.read()

    print('\nRaw lines:\n\n%s' % lines)
    print('\nVars to change:')
    print(change_vars_list)

    outdata = lines
    for var, value in zip(change_vars_list, change_values_list):
        outdata = re.sub(var, value, outdata)

    print('\nNew data:\n\n%s\n' % outdata)

with open(outfile, 'w') as outconf:
    outconf.write(outdata)

Or, if it's always simple substitution, you can just use the replace string function:
for var, value in zip(change_vars_list, change_values_list):
    outdata = outdata.replace(var, value)

A: Don't sure this is best solution - but it works:
#!/usr/bin/env python

infile = 'in.conf'
outfile = 'out.conf'

change_vars_list = ('%var1%', '%var2%', '%var3%')
change_values_list = ('newvalue1', 'newvalue2', 'newvalue3')

with open(outfile, 'r+') as outconf:
    with open (infile, 'r') as inconf:
            for line, var, value in zip(inconf, change_vars_list, change_values_list):
                print('Var %s value %s' % (var, value))
                outconf.write(line.replace(var, value))

$ ./replace.py
Var %var1% value newvalue1
Var %var2% value newvalue2
Var %var3% value newvalue3

$ cat out.conf
line1 = newvalue1
line2 = newvalue2
line3 = newvalue3

But still hope for some other idea...

A: Try:
outdata = re.sub(r'%var[0-9]%', 'NEWVALUE', lines)

The first parameter of re.sub is a regular expression pattern. You'll find a useful cheatsheet and can test your patterns here.

A: Just solving the core issue, as you're handling the files just fine already:
template = 'line1 = %var1%\nline2 = %var2%\nline3 = %var3%'
change_vars_list = ('%var1%', '%var2%', '%var3%')
change_values_list = ('newvalue1', 'newvalue2', 'newvalue3')
changes = dict(zip(change_vars_list, change_values_list))
import re
print(re.sub('|'.join(changes),
             lambda match: changes[match.group()],
             template))

Prints:
line1 = newvalue1
line2 = newvalue2
line3 = newvalue3

Unless you have a good reason to specify change_vars_list and change_values_list separately, I'd write them like this:
template = 'line1 = %var1%\nline2 = %var2%\nline3 = %var3%'
changes = {'%var1%': 'newvalue1',
           '%var2%': 'newvalue2',
           '%var3%': 'newvalue3'}
import re
print(re.sub('|'.join(changes),
             lambda match: changes[match.group()],
             template))

Alternatively, if you don't insist on using regular expressions:
template = 'line1 = %var1%\nline2 = %var2%\nline3 = %var3%'
change_vars_list = ('%var1%', '%var2%', '%var3%')
change_values_list = ('newvalue1', 'newvalue2', 'newvalue3')
for var, value in zip(change_vars_list, change_values_list):
    template = template.replace(var, value)
print(template)

Or shorter again:
template = 'line1 = %var1%\nline2 = %var2%\nline3 = %var3%'
changes = (('%var1%', 'newvalue1'),
           ('%var2%', 'newvalue2'),
           ('%var3%', 'newvalue3'))
for var, value in changes:
    template = template.replace(var, value)
print(template)


text:
Q: How do I "import" an xml schema for xjb code generation I'm new to using xml, and having trouble figuring this out. I found a schema for the RSS spec online, and I can generate java classes from that self-contained schema using xjc without issues.
I want to add fields from simpledc.xsd because in RSS feeds, I'm seeing tags like dc:creator on <items>, and I'd like to set it up so code generation for that can work too. In my attempt, I added the xsd:include for the dc schema, and added a field to the item definition.
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <!-- My addition -->
    <xsd:include schemaLocation="simpledc.xsd" />

    <xsd:element name="rss" type="rss" />

    <xsd:complexType name="rss">
        <xsd:sequence>
            <xsd:element name="channel" type="channel" maxOccurs="1"
                minOccurs="1" />
...

    <xsd:complexType name="item">
        <xsd:sequence>
            <xsd:element name="title" type="xsd:string" maxOccurs="1" minOccurs="0">
                <xsd:annotation>
                    <xsd:documentation>
                        The title of the item.
                    </xsd:documentation>
                </xsd:annotation>
            </xsd:element>
            ...
            <!-- My addition -->
            <xsd:element name="creator" type="dc:creator" maxOccurs="1" minOccurs="0" />
        </xsd:sequence>
    </xsd:complexType>

Intellij provides the error:
Cannot resolve symbol 'dc:creator'

And xjc also provides a similar error:
$ xjc -p com.test.generated -d src/main/java/ src/main/resources/schemas/rss.xsd
parsing a schema...
[ERROR] s4s-att-invalid-value: Invalid attribute value for 'type' in element 'element'. Recorded reason: UndeclaredPrefix: Cannot resolve 'dc:creator' as a QName: the prefix 'dc' is not declared.
  line 391 of file:/<project>/src/main/resources/schemas/rss.xsd

How do I set this up properly so that I can add elements with the dc namespace in my xml schema, and have codegen work properly?

A: I figured out how to do this. I used an include where I should have used an import because I was referencing a different namespace. And then for the element from the different namespace, I need to use a ref to link to them:
<xsd:schema
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:dc="http://purl.org/dc/elements/1.1/">
    <xsd:import schemaLocation="dc.xsd" namespace="http://purl.org/dc/elements/1.1/"/>
...
    <xsd:complexType name="item">
        <xsd:sequence>
            ...
            <!-- My addition -->
            <xsd:element minOccurs="0" ref="dc:creator" />
        </xsd:sequence>
    </xsd:complexType>

I'm not sure what the intent of the simpledc.xsd provided by the dublin core website. Using dc.xsd seems to work for generating the schema.
Unfortunately, when you're trying to unmarshall xml according to this schema, it seems that the rss feed author needs to add xmlns fields at the top level <rss> element, and they mostly do not.


text:
Q: Why isn't jQuery Validate plug in working with one section of my MVC project? I am using jQuery Validate plugin on my MVC web app. In one section of the app, the plugin works perfectly. The fields in this section of the app do not have a [Required] field validator attached to any of the fields in the model.
Below is the code that I am trying to make work with the jQuery Validate plugin. It is not working. I have been troubleshooting this for hours, and I can't see the error where I'm going wrong! I tried removing the [Required] field validator in the model and it didn't fix the issue. I'd appreciate another set of eyes...
My MVC Model:
public class LoanApp
{
    [Required]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
}

The HTML with Razor Syntax
<form id="applicantPersonalInfo">

        @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2"})

             @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control"} })
             @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })

</form>

The jQuery Validate:
$('#applicantPersonalInfo').validate({
   rules: {
      FirstName: {
          required: true
      }
   },
   onfocusout: function (element) { $(element).valid(); },
   onkeyup: function (element) { $(element).valid(); }
});

I have been comparing the two sections for hours and I can't seem to find the issue with the code in this section. Really appreciate the help. Thanks!


text:
Q: Find Sqlpackage.exe on client machine to install DACPAC I'm developing a .Net-application that would deploy a dacpac on a client machine. For that purpose I would require SqlPackage.exe to deploy the dacpac.
I need a absolute path of SqlPackage.exe to make my application work irrespective of client's machine configuration.
Can you please help me to achieve this.
Thanks,
Yogesh

A: To find sqlpackage programmatically you can make use of the TaskModuleSqlUtility powershell library. Either run the Invoke-DacpacDeployment from the powershell script (sorry not C#) or make use of Get-SqlPackageOnTargetMachine function for sqlpackage.exe path.
Search for tests in github for samples.

A: You can install sqlpackage.exe in two ways:

*

*SSDT (SQL Server Data Tools): the location will be VS Install Directory\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\{SqlVersion}, VS install directory: C:\Program Files (x86)\Microsoft Visual Studio {VsVersion}.0

*SQL Server Management Studio (SSMS) and the Dac Framework MSI:  C:\Program Files (x86)\Microsoft SQL Server\{SqlVersion}\Dac\bin
SqlVersion is 140 for the SQL Server 2017, 130 for the SQL Server 2016 etc.
VsVersion is 14 for Visual Studio 2017
More details in this question.

A: you also can download from microsoft doc site
https://learn.microsoft.com/en-us/sql/tools/sqlpackage-download?view=sql-server-ver15&viewFallbackFrom=sql-server-ver17
and check your version of sql and get correct instructions


text:
Q: Accessing t-values in pmdarima pmdarima has this .pvalues() which described as Get the p-values associated with the t-values of the coefficients. Note that the coefficients are assumed to have a Student's T distribution. meanwhile it use z statistics not t statistics on it summary. How to access pmdarima t-values?
or should I did the t-test separately?


text:
Q: Is it possible to to declare variables within a condition? This is how I would do a while loop:
boolean more = true;
while (more)
{
  // do something
  if (someTest())
  {
    more = false;
  }
}

That's pretty standard. I'm curious to know if there's a way of doing something similar to the code below in Java: (I think I've seen something like it in C)
// The code below doesn't compile (obviously)
while (boolean more = true)
{
  // do something
  if (someTest())
  {
    more = false;
  }
}

I only ask this because currently I don't like the way I'm defining the variable used in the condition (in this case: "more") outside the scope of the loop, even though it's only relevant inside the loop. There's no point it being left hanging around after the loop has finished.

* * Update * *
An idea came to me following a visit to the Porcaline Chamber of Secrets:
for (boolean more=true; more; more=someTest())
{
  // do something
}

It's not perfect; It's abusing the for loop and I can't think of a way to execute the loop at least once, but it's close... Is there a way to make sure the loop is performed 1+ times?

A: To answer your question literally, you can do
for(boolean more = true; more; ) {
   more = !someTest();
}

but this is much the same as
while(!someTest());

If it must execute at least once you can do
do {

} while(!someTest());

A: For your specific case, you can reduce your code to this:
while (true) {
  if (someTest()) {
    break;
  }
}

In general, you could replace your outer-scope declaration with an inner-scope one, but you'd need to move the loop condition:
while (true) {
  boolean more=true;
  ...
  if (someTest()) {
    more = false;
  }
  ...
  if (!more) {
    break;
  }
}

Or even:
do {
  boolean more=true;
  ...
  if (someTest()) {
    more = false;
  }
  ...
  if (!more) {
    break;
  }
} while (true);

I'd opine that defining your condition outside the loop is clearer.

A: KidTempo, in the example you gave, I think that more would be re-initialized each time through the loop. Each time through the loop, the conditional is re-evaluated, so assuming that you are able to define a variable in a conditional, the variable would be re-initialized each time that conditional is re-evaluated. This would also apply to other types of conditionals, so I would say to avoid defining variables in a conditional.


text:
Q: Angular html template as string with style attribute renders with NO style attribute I am having a Util.ts which defines format function as shown below. The problem is on the small tag which has style property.
export const formatMessage = (message ) =>{
    return '' + message.name+" " +message.ts + '  ' + message.c;
  }

However when rendered small tag's style attribute is getting removed.

I am not sure why this behavior, The HTML string template returned by the formatMessage function is attached to the HTML using innerHTML of DIV as shown here.

Why is this style property getting removed (while class property stays) and how do I address the issue?

A: dom sanitizer stips the style from your html. it is done to prevent xss attacks. you can bypass security checks by doing this:
  constructor(private s: DomSanitizer) { }
...
  export const formatMessage = (message, sanitizer ) =>{
    return sanitizer.bypassSecurityTrustHtml('' + message.name+" " +message.ts + '  ' + message.c);
  }

and pass sanitizer to formatMessage


text:
Q: Get array of documents from array of ids in firestore using React I need to get back an array of documents using an array of user Ids from firestore in react. I want to call this as a function and pass in an array of ids into it, then return an array of objects with all the documents that have matching userIds.
The userIds array will look something like this
["2","3","4"]

The object I need returned in an array, and how it is structured as a collection in the database will look like this:
 {
    dateCreated: 1630348731918,
    docId: "ljAIJmthfwSLwU4FPdMW",
    emailAddress: "rreay724@gmail.com",
    followers: ["2","3"],
    following: ["2"],
    fullName: "Bobby R.",
    userId: "3",
    username: "bobby"
  }

Below is the code I currently have.
export const getFollowers = async (followerIds) => {
  if (followerIds.length > 0) {
    const result = await firebase
      .firestore()
      .collection("users")
      .where("userId", "in", followerIds)
      .get();

    const followers = result.docs.map((item) => ({
      ...item.data(),
      docId: item.id,
    }));
    return followers;
  }
};

I'm calling this inside useEffect, which looks like this in the full page:
export default function FollowerPopUp({ visible, closeWindow, followers }) {

  useEffect(() => {
    const response = getFollowers(followers);
    console.log(response);
  }, [followers]);

  return (
    <div
      className={`overflow-auto z-30 m-0 p-0 h-2/6 w-3/12  border rounded-xl bg-white text-left fixed ${visible}`}
    >

Followers

      <FollowerRow
        following={true}
        username={"kratos"}
        fullName={"Kratos God of War"}
      />

  );
}

And I'm actually now getting back a promise with the Promise Result and the array of objects I need. Now I just need to get that array into a variable to map through.
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(2)
0: {username: "kratos", following: Array(0), userId: "2", fullName: "Kratos the God of War", followers: Array(1), …}
1: {dateCreated: 1630347676459, userId: "3", following: Array(1), emailAddress: "cloud@ff7.com", username: "cloud", …}
length: 2

A: Fixed this on my own. My code looks like this and it now works and I'm able to pull back what I need.
Function to pull data from firestore:
export async function getFollowers(followerIds) {
  if (followerIds.length > 0) {
    const result = await firebase
      .firestore()
      .collection("users")
      .where("userId", "in", followerIds)
      .get();

    const followers = await Promise.all(
      await result.docs.map(async (item) => ({
        ...item.data(),
        docId: item.id,
      }))
    );
    return followers;
  }
}

Code in useEffect to return array of followers:
 useEffect(() => {
    const getFollowerList = async () => {
      const followerList = await getFollowers(followers);
      await setFollowersList(followerList);
    };
    getFollowerList();
  }, [followers]);


text:
Q: How to populate a hashmap with the keys in one set and the values in another set I am using the Property object and I have the following:
m_Properties.stringPropertyNames() //A set of Strings that I want to use as the key

m_Properties.values() //A set of Strings that I want to use as the value

I want to put them in this hashmap
 private static HashMap<String, String> newProperties = new HashMap<String, String>();

I am not sure as I would have to loop through both at the same time, but how would I do that?

A: Ugly ancient object....
for(String property : m_Properties.stringPropertyNames()) {
    newProperties.put(property, m_properties.getProperty(property));
}


text:
Q: update manager not updating every time i run update manager, i get a message saying
"The package system is broken
If you are using third party repositories then disable them, since they are a common source of problems.
Now run the following command in a terminal: apt-get install -f"
I run this command in a terminal, but nothing happens...this started happening since i installed a calender plugin for thunderbird. is this the cause?

A: Try this:
sudo apt-get purge thunderbird; sudo apt-get install thunderbird


text:
Q: Bad variant cast exception when converting a Javascript object to a JSAPIPtr I am initialising a Javascript object and passing it to a registered API function whose signature is as follows::
I checked that the variant object coming from Javascript is not empty....
JS file
Initialize function called when I press a button...
 function Initialize()
    {
        var Class=function(){this.member1_JS='Red'};
        BorderStyle.prototype.member2_JS='1';
        var obj=new Class();
        plugin().DoTheChanges(obj);

    }

=======================================================

A: It should be:
_jsObjPtr= objectFromJavaScript.convert_cast<FB::JSObjectPtr>();

Any object coming from javascript is a JSObjectPtr; if it's doing a convert_cast to JSAPIPtr it will try to find inside the JSObjectPtr a C++ JSAPI object that you have created (for example, a DicomAPI object) which won't actually work on most browsers because they hide it too deep to get back out.


text:
Q: How can I toggle a boolean number? Here is my code:
$num = 1; // it always is either 0 or 1

if ( $num == 1 ){
    $num = 0
} else {
    $num = 1;
}

As you see, my code toggles the number. It is really ugly to me. I guessed php should has a function to do so. But I didn't find anything similar after some searches. Anyway, can I do that more standard and better?
Currectly I'm coding for a great company. That's why I want to write clean and professional codes.

A: All Mothods below only use 1 line of code
Method 1) use ! operator
<?php

$num = 1;

$num = (int) !$num;   // method 1

Method 2) use array to return with num as index
<?php

  $num =1;

  $num = array(1,0)[$num];  //method 2

Method 3) use conditional operator
<?php

  $num =1;

  $num = (int) ($num < 1);  // if 1 return 0 else return 1 , method 3

Method 4) Hack using empty function
<?php

  $num = 1;

  $num = (int)empty($num);  // method 4

Oneline Demo

A: Here's a couple of fun ways, if number is 1 return 0 or 1
$num = 1;
function toggle1($num){
   if($num){
      return 0;
   }
   return 1;
}

without argument, just toggle away for flip flop action
function toggle2(){
    static $num = 1;
    $num = ($num?0:1);
    return $num;
}

with argument
function toggle3($num){
    return ($num?0:1);
}

like @B. Desai but cast to int
function toggle4($num){
    return (int) !$num;
}

straight up like the example but ternary
$num = 1;
$num = ($num?0:1);

A: You can simply use ! operator to toggle number between 0 and 1;
$num = 1; // it always is either 0 or 1
function toggleNumber($num)
{
  return !$num;
}
$num = intval(toggleNumber($num));
echo $num; //print 0
echo "<br>";
$num = intval(toggleNumber($num));
echo $num; // print 1

You can directly use $num = intval(!($num)); to toggle number. But function is good approach.

A: Simple subtraction.  Just subtract the current value from 1.  This will not perform as quickly as bitwise, but it will be easily comprehensible by other coders if you are working in a team.  The performance differences will be measurable in nanoseconds.  $num=1-$num is a single line expression that doesn't use a conditional statement.
$num=1;

echo $num=1-$num,"\n";  // 0
echo $num=1-$num,"\n";  // 1
echo $num=1-$num;       // 0

A: If you're coding for a great company, you don't want to use a number that will act as a boolean.
If you know for sure that your number will always be 0 or 1, then use a Boolean. Here are some reason:

*

*In a few days/monthes/years, you will have to run through this code again, and you will see a number, so maybe you'll forget about that 0/1 rule that you implicitly set.

*If somebody else read through your code, how is he going to know that this can only be 0/1 ?

*When you (or someone else) will write documentation about that, do you really want to put in: "This is a number that can be only 0 or 1" ?
If you happend to use a boolean, that toggle thing you ask is much more easy:
$value = TRUE; //TRUE is a PHP Constant

$value = !$value; //Toggled, $value is now equal to FALSE

if ($value) { } //instead of if ($num == 1)
if (!$value) { } //instead of if ($num == 0)

In the documentation, you can state that this is a boolean value, everybody understands there are only two possibilities: TRUE or FALSE.

A:
In one line you can do it
$num = 1;
echo ($num == 1) ? 0 : 1;

A: Your approach is correct and will work as well. Just you need to wrap it into a function. Another way is using ^ (Bitwise XOR) to do that functional and more clean:
function toggleNumber( $num ) {
    return $num ^= 1;
}

Online Demo

That function gets the number and does XOR with 1 on it. Then the number will be toggled.

A: Another way to do it would be:

$num = 1 - $num;


text:
Q: .NET Entity Framework Core database connection fail I have a simple API app using EFC to connect to database. Things work well in my localhost test with
In appsettings.json:
"ConnectionStrings": {
    "DevConnection": "Server=(local);Database=CentoWebDB;Trusted_Connection=True;MultipleActiveResultSets=True;"
}

In Startup.cs
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options =>
            {// avoid naming convention;
                var resolver = options.SerializerSettings.ContractResolver;
                if (resolver != null)
                    (resolver as DefaultContractResolver).NamingStrategy = null;
            });

        services.AddDbContext<CentoWebDBContext>(
            options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DevConnection"),
                    sqlServerOptions => sqlServerOptions.CommandTimeout(120)
                )   // set the timeout
        );

        services.AddCors();
    }

But when I was trying to make the api app accessible from remote by adding UseKestrel and UseUrls as below, it failed to  connect to the DB.
    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .UseUrls("http://10.10.10.10:5000", "http://localhost:5000")
            .UseStartup<Startup>();
}

Error message:

fail: Microsoft.AspNetCore.Server.Kestrel[13]
  Connection id "0HLRC8TEROPG9", Request id "0HLRC8TEROPG9:00000001": An unhandled exception was thrown by the application.
  System.ArgumentNullException: Value cannot be null.
  Parameter name: connectionString
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
  at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action1 sqlServerOptionsAction)
  at TSPfizer.CentoMiner.Web.Startup.<ConfigureServices>b__4_1(DbContextOptionsBuilder options) in C:\Users\shangl02\source\repos\TSolution\CentoMinerWebAPI\Startup.cs:line 43
  at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass1_02.b__0(IServiceProvider p, DbContextOptionsBuilder b)

Seems the connection string is null. don't understand what goes wrong. Did I miss something there?


text:
Q: JPA xml mapping not finding fields I have the following class:
package lt.vic.valdos.domain.valda;

public class Valda implements java.io.Serializable {
    private long id;
    private Long valdosKodas;

    public long getId() {
        return id;
    }

    public Long getValdosKodas() {
        return valdosKodas;
    }
}

and the following orm.xml:
<?xml version="1.0"?>
<entity-mappings
        xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/orm"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.eclipse.org/eclipselink/xsds/persistence/orm http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_2_1.xsd"
        version="2.1">
    <entity class="lt.vic.valdos.domain.valda.Valda">
        <table name="VALDOS" schema="VLD" />
        <attributes>
            <id name="id" />
            <basic name="id">
                <column name="vld_id" />
                <return-insert return-only="true" />
            </basic>
            <basic name="valdosKodas">
                <column name="valdos_kodas" />
            </basic>
        </attributes>
    </entity>
</entity-mappings>

When I deploy this in glassfish, i get the following error:
Exception [EclipseLink-7215] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Could not load the field named [id] on the class [class lt.vic.valdos.domain.valda.Valda]. Ensure there is a corresponding field with that name defined on the class.

The class is in a jar that is included into a web application as a maven dependency. The orm.xml is in /WEB-INF/classes/META-INF of the web application.
What am I doing wrong?

A: Figured this one out myself. For some reason EclipseLink requires a setter on a class. Once I add private setters everything seems fine. Why the setters are needed (mapping accessors should default to FIELD) remains a mystery but it is not that important for me. Adding  access="FIELD" to all entity attributes also fixes the problem without the setters.

A: You should be specifying the id as generated using the IDENTITY strategy:
<id name="id">
    <column name="vld_id"/>
    <generated-value strategy="IDENTITY"/>
</id>

This strategy will automatically read the database provided id back into the new object upon successful commit.  The EclipseLink returning statement functionality is only applicable to basic mappings because id is already covered by Identity ID generation.

A: I think you have to add the column description for the id column to your id element, instead of using an extra basic element. As in <id name="id"> <column name="vld_id" /> ... </id>, without an extra <basic name="id"> ....
From my own experience (some time ago now), it's probably easier to use annotations to define your mappings.


text:
Q: Creating or deleting associations with accepts_nested_attributes_for I have 2 models, Category and LineItemTypes
There are already plenty existing of both, it is now a requirement for them to be associated. Being many LineItemTypes for every Category.
I have added accepts_nested_attributes_for :line_item_types on Category
I've tried using a hidden_field on a form to create a list of existing associated LineItemTypes:
- form_for @category do |form|
  %ul#categorised
    - form.fields_for :line_item_types do |line_item_types|
      -categorised.each do |l|
        %li
          =l.description
          =line_item_types.hidden_field :category_id

  =form.submit

If I add an item to that list, I get errors saying that a LineItemType for that Category can't be found. I thought accepts_nested_attributes_for would add the association if it doesn't exist. Or is it only for 'creating' new records and modifying existing relationships, not creating new relationships.
a.update_attributes({:line_item_types_attributes => [{:id => 2767}, {:id => LineItemType.find(2).id}]})
ActiveRecord::RecordNotFound: Couldn't find LineItemType with ID=2 for Category with ID=1

Any ideas without having to write something to traverse the resulting form params and create the associations? Or an even easier way to achieving this?

A: I've come to the conclusion that accepts_nested_attributes_for works kinda like url_for... Where the presence of ID makes it assume the relationship exists. Rendering accepts_nested_attributes_for not suitable for what I want to do.
I've worked around this with a before filter:
def find_line_item_types
  params[:category][:line_item_types] = LineItemType.find(params[:category][:line_item_types].collect { |a| a[0].to_i }) if params[:category] and params[:category][:line_item_types]
end

A: no you should be able to create line_item_types from a Category instance without specifying the category_id in the line_item_types attributes!
You should check that you got the :inverse_of option in your has_many and belongs_to declarations.
# in Category
has_many :line_item_types, :inverse_of => :category

# In LineItemType
belongs_to :category, :inverse_of => :line_item_types

Tell me if that helps.

A: Well, I had the same issue, so I searched into the source and monkey patched accepts_nested_attributes_for to allow this behavior...
https://gist.github.com/2223565
It looks like a lot, but I actually just modified a few lines:
module ActiveRecord::NestedAttributes::ClassMethods
  def accepts_nested_attributes_for(*attr_names)
    # ...
    #options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
    options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only, :allow_existing)
    # ...
  end
end

And...
module ActiveRecord::NestedAttributes
  def assign_nested_attributes_for_collection_association(association_name, attributes_collection, assignment_opts = {})
    # ...
    #existing_records = if association.loaded?
    #  association.target
    #else
    #  attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
    #  attribute_ids.empty? ? [] : association.scoped.where(association.klass.primary_key => attribute_ids)
    #end

    existing_records = if options[:allow_existing] or not association.loaded?
      attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
      scope = options[:allow_existing] ? association.target_scope : association.scoped
      scope.where(association.klass.primary_key => attribute_ids)
    else
      association.target
    end
    # ...
  end
end


text:
Q: Angular - Save blob in local text file? I have a plain text variable which I want to store and save on a .txt file using Angular.
So far I have tried the following:
var data = new Blob([text], {type: 'text/plain'});
const url= window.URL.createObjectURL(data);
window.open(url);

Being text the variable with the plain text content. It seems to work but it opens de blob on a new browser tab, and I need it to be downloaded as whatever.txt.
How can I achieve this? Thanks!

A: The solution can be found here:
JavaScript blob filename without link
The steps are the following:

*

*Create a hidden <a> tag.

*Set its href attribute to the blob's URL.

*Set its download attribute to the filename.

*Click on the <a> tag.

A: This is working code from my application
const file = new window.Blob([data], { type: contentType });

const downloadAncher = document.createElement("a");
downloadAncher.style.display = "none";

const fileURL = URL.createObjectURL(file);
  downloadAncher.href = fileURL;
  downloadAncher.download = fileName;
  downloadAncher.click();


text:
Q: Correspondence of Schur Decomposition and Spectral Decomposition needs P.D? According to Wikipedia,

[...] the Schur decomposition extends the spectral decomposition. In particular, if $A$ is positive definite, the Schur decomposition of $A$, its spectral decomposition, and its singular value decomposition coincide.

Why is positive definiteness needed in order to make the Schur decomposition correspond to the Spectral decomposition, as opposed to the weaker condition of symmetry?
Thanks

A: The statement is about three decompositions: the Schur decomposition, the spectral decomposition, and the singular value decomposition. Positive definiteness is needed to make the spectral and singular value decompositions coincide, because the singular values are always nonnegative.
For a Hermitian matrix, the Schur and spectral decompositions coincide, with no hypotheses on the signs of the eigenvalues, and the singular values are the absolute values of the eigenvalues.


text:
Q: SpringBatch Jaxb2Marshaller: different name of class and xml attribute I try to read an xml file as input for spring batch:
Java Class:
package de.example.schema.processes.standardprocess;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Process", namespace = "http://schema.example.de/processes/process", propOrder = {
    "input"
})
public class Process implements Serializable
{

    @XmlElement(namespace = "http://schema.example.de/processes/process")
    protected ProcessInput input;

    public ProcessInput getInput() {
        return input;
    }

    public void setInput(ProcessInput value) {
        this.input = value;
    }

}

SpringBatch dev-job.xml:
<bean id="exampleReader" class="org.springframework.batch.item.xml.StaxEventItemReader" scope="step">
    <property name="fragmentRootElementName" value="input" />
    <property name="resource"
        value="file:#{jobParameters['dateiname']}" />
    <property name="unmarshaller" ref="jaxb2Marshaller" />
</bean>

<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
        <list>
            <value>de.example.schema.processes.standardprocess.Process</value>
            <value>de.example.schema.processes.standardprocess.ProcessInput</value>
            ...
        </list>
    </property>
</bean>

Input file:
<?xml version="1.0" encoding="UTF-8"?>
<process:process xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:process="http://schema.example.de/processes/process">
    <process:input>
        ...
    </process:input>
</process:process>

It fires the following exception:

[javax.xml.bind.UnmarshalException: unexpected element (uri:"http://schema.example.de/processes/process", local:"input"). Expected elements are <<{http://schema.example.de/processes/process}processInput>]
    at org.springframework.oxm.jaxb.JaxbUtils.convertJaxbException(JaxbUtils.java:92)
    at org.springframework.oxm.jaxb.AbstractJaxbMarshaller.convertJaxbException(AbstractJaxbMarshaller.java:143)
    at org.springframework.oxm.jaxb.Jaxb2Marshaller.unmarshal(Jaxb2Marshaller.java:428)

If I change  to  in xml it work's fine. Unfortunately I can change neither the xml nor the java class.
Is there a possibility to make Jaxb2Marshaller map the element 'input' to the class 'ProcessInput'?

A: I don't believe JAXB allows this.  JAXB is a binding API, so it doesn't provide much in the way of customization.  That being said, you can use XStream and provide aliases for what you need, allowing you to customize the mapping of XML to object however you want.  You can see an XStream example here: https://github.com/spring-projects/spring-batch/blob/master/spring-batch-samples/src/main/resources/jobs/iosample/xml.xml


text:
Q: Sysinternals' Portmon: Error 2 When I try to connect to local ports, Computer -> Connect local, using Portmon v. 3.02, I'm getting an error message, Error 2, in a small error dialog box:

I run the tool as an administrator (if not, I get error 6).
By the way this is a Windows 7 x64. On 32-bit, in Windows 7 x86, it works fine. How can I fix this problem?

A: Sysinternals' Portmon works only on 32-bit versions of Windows. It does not support 64-bit (probably its driver is not signed).
From the Portmon homepage:

*

*Runs on:

*

*Client: Windows XP (32-bit) and higher (32-bit).

*Server: Windows Server 2003 (32-bit) and higher (32-bit).

A: "Error 2" is "Cannot find the file specified", that is, cannot find a required DLL file.
Originally, you got this error when you tried to run Portmon from a network location: that broke the security trust, causing Portmon to be untrusted (or perhaps just messing up the search path somehow).
On my copy of Windows 7 64 bit, Microsoft Dependency Walker (depends.exe) tells me that PORTMSYS.SYS (the file created/loaded by Portmon.exe), has unresolved dependencies on ci.dll, clfs.sys, hal.dll and kdcom.dll.
Those are the
code integrity
common log file system
hardware abstraction layer
kernel debugger com

libraries, and they aren't actually missing: if they were, Windows wouldn't boot. However, I don't see a copy of those files in SysWow64. This suggests to me that the problem is not with portman.sys: the problem is with the win32 compatibility layer in Windows 7/64 bit: It doesn't support debug properly.
It is now 2018. There is no 64-bit version of Portmon. Serial ports are a legacy standard. The Windows 7 problem was fixed by the release of Windows 8.1. However, there is a faint chance that some Visual Studio utility or security update back-ported to Windows 7 will fix the problem. Perhaps someone who is familiar with SysWow and debugging will comment.

A: Instead of portmon for Windows x64, you can use an emulator of a pair of virtual COM ports and a simple program that will connect the physical port and one of the virtual ones, as well as perform the logging function.
To create a pair of virtual COM ports you can use:

*

*com0com (preferably version "com0com-2.2.2.0-x64-fre-signed", because it contains signed x64 driver)

*Virtual Serial Ports Emulator (VSPE), every time it starts on x64 it asks to purchase a driver, but it works even if you refuse.

Simple mapping and logging program can be found e.g. here or you can write it yourself, it is simple.
The sequence of actions is follows:

*

*Сreate a pair of virtual COM ports using emulator (for example, COM28 and COM29)

*Let the external device be connected to the computer COM1 port. In the program, whose exchange with external device we want to listen to, we set up a port COM28 (instead of СОМ1) for communication.

*In the mapping program, we set up that we want to bind and log ports COM1 and COM29 (don't forget to set the port baud rate).

A: In Windows Explorer, right click on portmon.exe --> select Properties --> click the Compatibility tab, and Run in Windows XP compatibility mode. It works fine like that in Windows 7 64-bit.

A: I haven't tried it yet, but this question mentions com0com. It creates two virtual serial ports and emulates a null modem cable between them. It claims to be able to run on 64 bit Windows. I'm not sure whether it comes with software that lets you just pipe input from a real port into one of the virtual ports. One of the FAQ's says that you can turn on logging.
I guess in the worst case, you could write your own small program that pipes data from a real port to one of the virtual ports and logs it all.
There's also this question on open-source alternatives that mentions a couple of projects.

A: I've used AccessPort
http://sudt.com/en/ap/download.htm and it works great. Very similar to Portmon

A: Don't start Portmon from a network drive/path or something else.
Copy on to the hard disk drive, e.g. on the desktop, restart and try again!

A: If you run Portmon in compatibility mode, it will work.
Check Make older programs run in this version of Windows.
It says:

To run the Program Compatibility troubleshooter:

*

*Open the Program Compatibility troubleshooter by clicking the Start button Picture of the Start button, and then clicking Control Panel. In the search box, type troubleshooter, and then click Troubleshooting. Under Programs, click Run programs made for previous versions of Windows.

*Follow the instructions in the troubleshooter.

The above is a public explanation from Microsoft for a common situation when running older applications in Windows.
But, I can say it briefly;

*

*Right click on portmon.exe

*Select menu about "troubleshooting compatibility problem" or something like that (I'm using a foreign version of Windows, so I don't see correct name of that menu in English.)

*Select automatic mode

*It will detect the problem and recommend Windows XP (SP2) mode

*Select it and execute Portmon again.

I hope it works!

A: Instead of Portmon you can also use the IO Ninja program with the "Serial Monitor" plugin.
It gives a little less information than Portmon, but in a more understandable form. The main thing is, just like a Portmon, it allows you to see the data that is transmitted between a third-party application and an external device via a serial port. The program works under modern versions of Windows (I tried it myself on Windows 10 x64). The aforementioned plugin "Serial Monitor" is paid (but has an evaluation period).
Note: the port that you want to monitor must first be connected to the "IO Ninja" program, and then opened in a third-party application whose exchange with an external device you want to track.

A: Just to test that the hardware is working, you could perhaps boot a Linux live CD and run the statserial and/or minicom program to verify that it works. The Knoppix distribution seems to contain both those programs.
Serial ports on Linux are named /dev/ttyS0 for COM1, /dev/ttyS1 for COM2, etc.


text:
Q: Retrieving index of vector using std::upper_bound, index out of bounds I am attempting to retrieve a vector's index based on it's value using std::upper_bound. For some reason though, the following code sets tmpKey equal to 2 vs my expected value of 1. Does anything stick out as being horribly wrong?
int main()
{
    float time = 30.0000000;
    std::vector<float> positionKeyTimes = { 0.000000000, 30.0000000 };

    auto it = std::upper_bound(positionKeyTimes.begin(), positionKeyTimes.end(), time);
    auto tmpKey = (size_t)(it - positionKeyTimes.begin());

    std::cout << tmpKey << "\n";

    std::cin.get();
}

A: std::upper_bound

Returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found.

There's no element greater than 30 in your vector, so the end iterator is returned.
To get your expected value you could use std::lower_bound instead, which

Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value, or last if no such element is found.

Remembering that

The range [first, last) must be partitioned with respect to the expression element < value or comp(element, value), i.e., all elements for which the expression is true must precede all elements for which the expression is false. A fully-sorted range meets this criterion.