text:
Q: How to reduce combination of nested for and if loops in python I have two big dataframes and my aim to calculate geographical distance between each and every lat/long in first dataframe to all the lat/longs in second dataframe. for this I am using haversine function. I want reduce the time taken to run this loop.Is there any alternate ways to write this code more efficiently.
for i in range(0,len(df1)):
    BS = (df1['Latitude'][i],df1['Longitude'][i])
    for j in range(0,len(df0)):
        if (abs(df1['Latitude'][i]-df0['Cust_lat'][j])<=0.1 and abs(df1['Longitude'][i]-
              df0['Cust_long'][j])<=0.1):
            CPE = (df0['Cust_lat'][j],df0['Cust_long'][j])
            if(haversine(BS,CPE)<= radius):
                distance=haversine(BS,CPE)


text:
Q: Documents "checked out or locked" but checkout has never been enabled? My business partner has a horrible time opening documents.  She is not very technical and so her problems often have surprising solutions.  but this one has me baffled.
We will work together on a SharePoint-Online document, opened from the browser using the "Open in Word" option which is default.  However once a day or so, she will create a V2 document claiming "I couldn't edit the original because I got the error that the document was checked out or locked...".
I have never enabled the checkout option in that library - or ANY library in this site collection.  I just checked again this morning: "Version Settings - Require documents to be checked out = NO".
HOW is the managing to get this error?  It is only her having the issue.

A: Even if you don't set your library to require check-ou, you may still have checked-out documents in the following situtations:

*

*You manually check-out the document from the Library (select the document, choose "check-out").

*You open the document in Word and let it open (this leads to a not-visible check-out state, known as "short-term" check-out, as long as the document is opened somewhere, or if Word was unproperly closed).

*You upload a document in a library where you have required properties, and you don't fill-up these properties (this can also easily happen if you copy/paste or drag/drop a batch of files).

*You check-out the document from Word ("File" menu, "Info" section, "Manage document" button).

A: -- I know this comment is 6,5 years later, but I'm just making it in case others stumble upon this thread. --
I had the same situation and in my case this was caused by a Column setting combination of

*

*Default Value (value)

*Enforce unique values (slider)

Each document was automatically in conflict and Sharepoint checks out the document automatically as some sort of failsafe/workaround.
Hopefully this helps some.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate Random String with Specific Restrictions Tring to generate a random string but it needs to be formatted a specific way.
N = number
L = Capital Letter
must be NL-NN
needs hyphen as well
examples: 5K-22, 9L-19, 0R-66
every method I have tried has just generated a string but without the hyphen, I know it is probably something simple my brain just hurts thinking on it so I thought I'd see if one of yall could give me a hand.
Thanks

A: Try this:
function randomchar(a,b)
    return string.char(math.random(string.byte(a),string.byte(b)))
end

a=randomchar('0','9')
b=randomchar('A','Z')
c=randomchar('0','9')
d=randomchar('0','9')

print(a..b..'-'..c..d)


text:
Q: How to add single if statement in flask I am using Python 3.5 to develop a web app with Flask.
Having the following code:
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def main():
    return render_template('main.html', show_hidden=False)

app.run()

and the template main.html:

Hey!

    {% if show_hidden == True %}

Hidden text

    {% endif %}

Right now this seems an unuseful feature, but I'll find a way to determine whether the hidden text should be displayed.
When the above code runs, the hidden text is shown although show_hidden is set to False. Furthermore, when it is turned to True the hidden text is displayed twice. As I have followed the docs this code is supposed to be working. Could someone please point me out what am I missing?

A: The == True is redundant, you can just check whether {% if show_hidden %}
Change :
{% if show_hidden == True %}

To :
{% if show_hidden %}


text:
Q: Android listview not working as expected I have this code that will eventually be populated from a database but to get it working first I have used the below code
  ListView mListView = (ListView) getActivity().findViewById(R.id.listView);

        ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String,Object>>( );
        HashMap<String, Object> listItem;
        listItem = new HashMap<String, Object>();
        for (int i = 0;i<=10;i++) {
            listItem.put("item", "orderTitles" + i);
            listItem.put("subitem", "orderDescriptions" + i);
            items.add(listItem);
        }
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), items, R.layout.list_item_format, new String[]{"item", "subitem"}, new int[]{R.id.itemTitle, R.id.itemDescription});
        mListView.setAdapter(adapter);

The problem is that the output to the list is saying only OrderTitles10 and OrderDescriptions10 (listed 10 times) instead of counting incrementally. What am I doing wrong

A: change your code to this:
 ListView mListView = (ListView) getActivity().findViewById(R.id.listView);

        ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String,Object>>( );
        HashMap<String, Object> listItem;

        for (int i = 0;i<=10;i++) {
            listItem = new HashMap<String, Object>();
            listItem.put("item", "orderTitles" + i);
            listItem.put("subitem", "orderDescriptions" + i);
            items.add(listItem);
        }
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), items, R.layout.list_item_format, new String[]{"item", "subitem"}, new int[]{R.id.itemTitle, R.id.itemDescription});
        mListView.setAdapter(adapter);

A: Initialize listItem inside for loop to create and add new HashMap with both values in ArrayList :
    for (int i = 0;i<=10;i++) {
        listItem = new HashMap<String, Object>();
        listItem.put("item", "orderTitles" + i);
        listItem.put("subitem", "orderDescriptions" + i);
        items.add(listItem);
    }

A:
initialize listitem inside the loop and change the for loop condition like below

 for (int i = 0;i<10;i++) {
    listItem = new HashMap<String, Object>();
    listItem.put("item", "orderTitles" + i);
    listItem.put("subitem", "orderDescriptions" + i);
    items.add(listItem);
}


text:
Q: Is this calculus proof correct? Let
$$ f(x) = \int^{x}_{-2} (x + 2) g(t) \, dt.$$
The domain of $g$ and $f$ is $\mathbb{R}$. Assuming $g$ is a positive continuous function, show $f(x) \ge  {0}\ \forall x \in \mathbb{R}$.
My proof is:
Since $g$ is a continuous function, it is integrable on $\mathbb{R}$. So $ \forall x \in \mathbb{R} \ \exists\ c \in \mathbb{R}$ such that
$$\int ^{x}_{-2} (x + 2) g(t) \, dt = (x + 2) \int ^{x}_{-2} g(t) \, dt = (x+2) \cdot g(c) \cdot (x - (-2)) = (x+2)^2 g(c).$$
Since $g$ is a positive function, $g(c)$ is positive. Since $(x+2)^2$ is a non-negative function, their product is always $0$ or bigger.


text:
Q: spy on method call in componentDidMount I want to test some custom methods that get called in the componentDidMount life cycle method of a React component.
  componentDidMount() {
    getData().then(res => {
      console.log(res);
      this.setState({
        rate: res.data.bpi.USD.rate_float
      });
    });
  }

I am importing the getData method from api.js:
export const getData = () => {
  return axios
    .get("https://api.coindesk.com/v1/bpi/currentprice.json")
    .then(res => {
      return res;
    });
};

Testing it with Jest and Enyzme like this:
describe("App", () => {
  describe("Calls getData when componentDidMount", () => {
    const spy = jest.spyOn(App.prototype, "getData");
    const wrapper = mount(<App {...props} />);
    wrapper.instance().getData();
    expect(spy).toHaveBeenCalled(1);
  });
});

It fails: App › Calls getData when componentDidMount › encountered a declaration exception
And give me the following error:
TypeError: Cannot read property '_isMockFunction' of undefined

What are I am doing wrong?

A: getData is not App method, it cannot be spied on App class, it is not available on wrapper.instance() component instance.
Modules can be mocked with jest.mock. Proper unit testing requires to mock everything but tested unit. axios request can be mocked with:
import { getData } from '.../api';

jest.mock('.../api');

describe("App", () => {
  describe("Calls getData when componentDidMount", () => {
    getData.mockResolvedValue({ data: ... });
    const wrapper = mount(<App {...props} />);
    expect(getData).toHaveBeenCalled(1);
  });
});

Notice that shallow enables lifecycle hooks by default, it's expected that componentDidMount is called on component instantiation.
getData can be tested in similar way by mocking axios; this is shown in the manual.


text:
Q: Sql Paging result with one selected row on top A bit of context: I have a multi step form, in step1 the user must select a row in a table with pagination (filters + sorts), then he goes to step2 but at any moment he could come back to step1 and need to see the previously selected row.
NB: I dont want to keep the page number in frontend storage because if the table has changed, the selected id may not be on the same page any more
The test db:
CREATE TABLE [dbo].[Table_CTE](
    [Id] [int] NOT NULL,
    [FirstName] [nvarchar](50) NULL,
    [LastName] [nvarchar](50) NULL)

DECLARE @i int = 0
WHILE @i < 20
BEGIN
    SET @i = @i + 1
    insert into TABLE_CTE values (@i, CONCAT('FirstName', @i), CONCAT('LastName',  @i))
END

Sample of current query
DECLARE @PagingOffset int = 0;
DECLARE @PagingSize int = 5;
DECLARE @SelectedId int = 20;

WITH CTE_FILTERED AS (
    SELECT Id, FirstName, LastName
        --+ lot of complex subselect
    FROM TABLE_CTE
    WHERE  1 = 1
        AND FirstName LIKE '%1%'
)
SELECT
    --Cant explain why but looks faster than COUNT(*) OVER()
    (SELECT COUNT(*) FROM CTE_FILTERED) Total
    , CTE_FILTERED.*
FROM CTE_FILTERED
-- Could be ordered by anything
ORDER Id
OFFSET @PagingOffset ROWS FETCH NEXT @PagingSize ROWS ONLY;

Result
Total   Id  FirstName   LastName
11  1   FirstName1  LastName1
11  10  FirstName10 LastName10
11  11  FirstName11 LastName11
11  12  FirstName12 LastName12
11  13  FirstName13 LastName13

From here i see 3 solutions

*

*Query the row id, then query the PagedResult (-1 row) and concact them in backend

*Find a way to query the page number of the rowId selected then bring the user directly to this page

*Find a way to keep our selected id on top of all results no matter the paging (filters and sorts) => best scenario in my opinion

I just achieved the solution 3 but it looks really complex, maybe there is a better way to achieve it?
DECLARE @PagingOffset int = 0;
DECLARE @PagingSize int = 5;
DECLARE @SelectedId int = 20;

WITH CTE_FILTERED2 AS (
    SELECT Id, FirstName, LastName
        --+ lot of complex subselect
    FROM TABLE_CTE
    WHERE  1 = 1
        AND (Id = @SelectedId
            OR FirstName LIKE '%1%')
),
CTE_FILTERED_SELECTED2 AS (
    SELECT Id, FirstName, LastName
    FROM CTE_FILTERED2
    WHERE CTE_FILTERED2.Id = @SelectedId

    UNION ALL

    SELECT Id, FirstName, LastName
    FROM CTE_FILTERED2
    WHERE CTE_FILTERED2.Id != @SelectedId
    -- Could be ordered by anything
    ORDER BY Id
    -- forced to add an offset to be able to sort
    OFFSET @PagingOffset ROWS FETCH NEXT @PagingSize ROWS ONLY
)
SELECT (SELECT COUNT(*) FROM CTE_FILTERED_SELECTED2) Total
    , CTE_FILTERED_SELECTED2.*
FROM CTE_FILTERED_SELECTED2
-- forced to order by something to be able to use offset
ORDER BY (SELECT NULL)
OFFSET @PagingOffset ROWS FETCH NEXT @PagingSize ROWS ONLY;

Result
Total   Id  FirstName   LastName
12  20  FirstName20 LastName20
12  1   FirstName1  LastName1
12  10  FirstName10 LastName10
12  11  FirstName11 LastName11
12  12  FirstName12 LastName12

EDIT Final solution
SELECT TOP (@PagingSize) Priority, Id, FirstName, LastName, Total
FROM
(
  SELECT Priority = 1, Id, FirstName, LastName, -1 Total
   FROM dbo.TABLE_CTE WHERE Id = @SelectedId
  UNION ALL
  SELECT Priority = 2, Id, FirstName, LastName, Total
   FROM
   (
    SELECT Id, FirstName, LastName, COUNT(*) OVER () + IIF(@SelectedId IS NULL, 0, 1) Total
      FROM dbo.TABLE_CTE
      WHERE FirstName LIKE '%1%'
      ORDER BY Id
    OFFSET @PagingOffset ROWS FETCH NEXT @PagingSize ROWS ONLY
   ) AS y
   WHERE Id != @SelectedId
) AS z
ORDER BY Priority;

Priority    Id  FirstName   LastName    Total
1   20  FirstName20 LastName20  -1
2   1   FirstName1  LastName1   12
2   10  FirstName10 LastName10  12
2   11  FirstName11 LastName11  12
2   12  FirstName12 LastName12  12

A: This seems a little simpler (but I didn't want to complicate it with retrieving counts). Basically you assign a priority to the selected row, and assign everything else a lower priority, then you can sort on that artificial column.
DECLARE @PagingOffset  int = 0,
        @PagingSize    int = 5,
        @SortId        bit = 1,
        @SortFirstName bit = 0,
        @SortLastName  bit = 0,
        @SelectedId    int = 20;

SELECT TOP (@PagingSize) Id, FirstName, LastName
FROM
(
  SELECT Priority = 1, Id, FirstName, LastName
   FROM dbo.TABLE_CTE WHERE Id = @SelectedId
  UNION ALL
  SELECT Priority = 2, Id, FirstName, LastName
   FROM
   (
    SELECT Id, FirstName, LastName
      FROM dbo.TABLE_CTE
      WHERE FirstName LIKE '%1%'
      -- AND Id <> @SelectedId
      ORDER BY
        CASE WHEN @SortId = 1        THEN Id END,
        CASE WHEN @SortFirstName = 1 THEN FirstName END,
        CASE WHEN @SortLastName = 1  THEN LastName END
        OFFSET @PagingOffset ROWS FETCH NEXT @PagingSize ROWS ONLY
   ) AS y
) AS z
ORDER BY Priority;

*

*Example db<>fiddle
The outer ordering matches what you wrote (SELECT NULL = don't care) but you could easily repeat the case expression on the outer:
ORDER BY Priority,
        CASE WHEN @SortId = 1        THEN Id END,
        CASE WHEN @SortFirstName = 1 THEN FirstName END,
        CASE WHEN @SortLastName = 1  THEN LastName END;

A: If you have aribtrary filters and arbitrary sorting, and want to guarantee your users always see the page with an arbitrary row in it...
DECLARE @PagingSize int = 5;
DECLARE @SelectedId int = 20;

WITH
  filtered_sorted_paged AS
(
  SELECT
    <anything>,
    (ROW_NUMBER() OVER (ORDER BY <anything>) - 1) / @PagingSize + 1  AS page_id
  FROM
    <anything>
  WHERE
    <anything>
),
  page_search AS
(
  SELECT
    *,
    MAX(CASE WHEN id = @SelectedId THEN page_id END) OVER ()  AS selected_page_id
  FROM
    filtered_sorted_paged
)
SELECT
  <stuff>
FROM
  page_search
WHERE
  page_id = selected_page_id

For large datasets repeating this for every user action seems expensive, but it appears to do what you ask...
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=f3e90f195bc4e3dbcd03b4e194d94d4e


text:
Q: (Windows)Can I get the program to be changed or be stopped while it is running? I am now writing a win32 program in C++.
I want to show my running process on the window, just like time is flowing.
For example, this code
int a=0;
for(int i=0;i<10;i++)
{
  a++;//The change in "a" can be seen on the window.
  Sleep(1*1000);
}

But I've found that if I want to show this process, like clicking a button and a changing number appears on the screen, then the program needs to be running all the time. At this point, I don't have a way to do anything else, like clicking on another button.
So I realized I needed an operation that could interrupt the current process. But I went through a lot of information and found that only the fork() function of the Linux system can meet my needs. But I'm using Windows now, so what other ways can I achieve this?
Sincerely look forward to your reply.

A: You want to create a timer with SetTimer. Then watch for the WM_TIMER messages and update the screen then. This is the standard way of achieving what you described.

A: Create a thread and use atomic.
std::atomic_int a_t(0);

auto do_a = [](std::atomic_int* pA)
{
for (int i = 0;i < 10;i++)
{
    (*pA)++;
    std::this_thread::sleep_for(1s);
}
};

thread t(do_a, &a_t);
t.join();
cout << a_t.load(memory_order::memory_order_relaxed);

Anytime you need get the value of a_t , just call  a_t.load(memory_order::memory_order_relaxed);
Hope this helps you


text:
Q: Set two items color at same time in android RecyclerView I need to change the colour of two recylerview items at same time,based on the selection of user.
for example :- We have 4 options available in recylerview.
case 1:- User clicks the right option than change the recylerview item colour to green
case 2:- User clicks the wrong option than change the recylerview item colour to red and correct option to green. and rest to remain white.
enter image description here
Reference from imageenter image description here
JSON Response for options:-
    "options": [
                    {
                        "options": "big trouble",
                        "answer_id": 73,
                        "option_image": "",
                        "is_correct":"0"

                    },
                    {
                        "options": "right ",
                        "answer_id": 74,
                        "option_image": "",
                        "is_correct":"0"
                    },
                    {
                        "options": "none",
                        "answer_id": 75,
                        "option_image": ""
,
                        "is_correct":"1"
                    },
                    {
                        "options": "no error",
                        "answer_id": 76,
                        "option_image": "",
                        "is_correct":"0"
                    }
                ]

Rest is the normal recylerview and adapter .

A:         holder.mCardItems.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(---)  //True Condition
                holder.itemView.setBackgroundColor(Color.parseColor("#00C853"));
            else if (---) // False Condition
                holder.itemView.setBackgroundColor(Color.parseColor("#F44336"));
            else    //Nurtal Condition
                holder.itemView.setBackgroundColor(Color.parseColor("#FFFFFF"));
        }
    });


text:
Q: In Semantic Web, are OWL EL, RL, QL all instances of DL? What is the difference? More inside I'm using the pellet reasoner on a number of ontologies and have run the info method on a list of IRIs (in this case URLs). The two metrics that interest me are the DL Expressivity and OWL Profile.
The OWL Profiles I'm getting range from "OWL 2," "OWL 2 DL," "OWL 2 EL," "OWL 2 QL," "OWL 2 RL." When is says "OWL 2," does that mean the ontology is OWL 2 full? Are all the other variations DL? I have found a spec describing the different profiles (table 10 especially) [as a new user I can't post more than one hyperlink; thought the upcoming one was more important of two], but so far I haven't been able to answer this question for myself.
As for the "DL Expressivity," the very name implies that all the Expressivity codes (Such as ALCH, ALCH(D)) are DL. I have found this highly academic catalogue, so to speak, of the codes and their technical meaning in terms of complexity, but I need to know how to tell, at least generally, whether an ontology is DL or Full by looking at the Expressivities. Any help or links explaining these things would be most appreciated.
If it helps, I should also give some context for what I'm trying to do with this stuff. I'm just building a table from the "pellet info" data that has the ontology ID number (from the url list), the expressivity and OWL Profile for each, and also says whether that ontology is full, DL, or Lite.

A: If whatever is telling you (Pellet?) than an ontology is "OWL2" when it could otherwise state one of the profiles such as EL, QL or RL, then perhaps the ontology it is reporting about includes constructs that sit outside the expressivity of each of the profiles, but is otherwise included in the OWL2 specification.
As I understand it, each of the profiles are based on different description logics (DLs) that are geared towards different purposes:

*

*OWL2 (DL) is based on the description logic SROIQ, and is geared towards ontologies with a high degree of expressivity in the language. Reasoning tasks can be relatively expensive in this language.

*OWL2-EL is based on EL++, which is geared towards scalable reasoning in the TBox (i.e., polynomial-time reasoning for most inference tasks such as classification).

*OWL2-QL is based on DL-Lite, which is geared towards scalable query answering in the ABox (when dealing with lots of instance data and a relatively simple TBox).

*OWL2-RL is based on Description Logic Programs (DLP), which has an expressivity that subsets that of OWL2 DL (the fragment that can be handled using logic programs).

As far as I can tell, the catalogue you've linked to is up-to-date, but is a bit hard to use if you aren't familiar with logics and can identify the constructs covered by each language. The W3C OWL2 profiles page summarises the language expressivity of each of the profiles in OWL syntax. You could possibly refer to this to determine the intersecting expressivity of each of the OWL2 language profiles without having to interpret their semantics (in terms of DLs, which is hard to grasp unless you're comfortable with description logics, and in the case of OWL2-RL, description logic programs).
Lastly, note that the OWL1 'profiles' of Full, DL and Lite each correspond to yet other description logics:

*

*OWL1 DL corresponds to the description logic SHOIN.

*OWL1 Lite corresponds to the description logic SHIF.

*OWL1 Full corresponds to an undecidable logic that at least supersets SHOIN (though, I'm not quite sure what this is exactly! :-)

A: Full, DL, and Lite are three variants (flavors) of OWL, each constituting different compromises between expressivity and computational complexity. OWL Full has provides maximum expressiveness, syntactic freedom, but without computational guarantees. The semantics of OWL Full is a mixture of RDFS and OWL DL (RDF-based semantics). OWL DL is a restricted version of OWL Full. OWL DL provides very high expressiveness, computational completeness (all conclusions are guaranteed to be computable), and decidability (all computations can be finished in finite time). While OWL DL includes all OWL language constructors, they can be used only under certain restrictions. For example, OWL DL number restrictions may not be assigned to transitive properties. OWL Lite is a subset of OWL DL designed for easy implementation. OWL Lite has limited applicability, because it is suitable only for classification hierarchies and simple constraints. All three flavors are available in both OWL and OWL 2.
EL, QL, and RL are three OWL profiles, each of which provides a different balance between expressive power and reasoning complexity, thereby providing more options for different implementation scenarios. The EL profile was designed for handling ontologies with very large numbers of properties and/or classes, the QL profile is aimed at applications with a very large instance data volume and a priority for query answering, and the RL profile was designed for applications that require scalable reasoning with relatively high expressivity.
The DL Expressivity refers to the set of mathematical constructors available in the logical underpinning of OWL, i.e., the description logic (DL) that corresponds to the OWL flavor/profile or ontology you are talking about.
Very briefly, the ALC description logic supports atomic and complex concept negation, concept intersection, universal restrictions, and limited existential quantification. By extending ALC and transitivity roles (i.e., S) with
role hierarchies (H), inverse roles (I), functional properties (F), and datatypes (D), we get the SHIF(D) description logic, which roughly corresponds to OWL Lite. By adding nominals (O) and cardinality restrictions (N ) to SHIF(D), we obtain SHOIN (D), the description logic underlying OWL DL. Extending SHOIN(D) with complex role inclusion axioms, reflexive and irreflexive roles, asymmetric roles, disjoint roles, the universal role, self-constructs, negated role assertions, and qualified number restrictions yields to the very expressive yet decidable SROIQ(D) description logic, which largely corresponds to OWL 2 DL.
Although OWL Full and OWL DL support the same set of constructors, OWL Full does not have restrictions on the use of these constructors (e.g., no restrictions on the use of transitive properties), which makes OWL Full undecidable, while OWL DL is decidable.


text:
Q: Human-readable duration between two UNIX timestamps I'm trying to calculate the difference between two UNIX timestamps (i.e. seconds since 1970). I want to say e.g. "3 years, 4 months, 6 days, etc" but I don't know how to account for leap years and months of different durations. Surely this is a solved problem..?
This is different to other questions which want to express an approximate duration in one unit that has a fixed/homogeneous duration (e.g. 3 hours, or 7 weeks, etc.). Results for 1. Jan to 1. Feb would be "1 month" and results for 1. Feb to 1. Mar would also be "1 month" even though the number of days are different.
I want to express the complete duration precisely but in years/months/days/hours/minutes. Solutions in C++ would be appreciated!

A: Using this free, open-source C++11/14 date/time library, this problem can be solved very simply, with very high-level syntax.  It leverages the C++11 <chrono> library.
As relatively few people are familiar with how my date library works, I will go through how to do this in painstaking detail, piece by piece.  Then at the end I put it all together packaged up in a neat function.
To demonstrate it, I will assume some helpful using declarations to cut down on the verbosity:
#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;

And it also helps to have some example UNIX timestamps to work with.
auto t0 = sys_days{1970_y/7/28} + 8h + 0min + 0s;
auto t1 = sys_days{2016_y/4/2} + 2h + 34min + 43s;
std::cout << t0.time_since_epoch().count() << '\n';
std::cout << t1.time_since_epoch().count() << '\n';

This will print out:
18000000
1459564483

This indicates that 1970-07-28 08:00:00 UTC is 18000000 seconds after the epoch and 2016-04-02 02:34:43 UTC is 1459564483 seconds after the epoch.  This all neglects leap seconds.  That is consistent with the way UNIX timestamps work, and consistent with the operation of std::chrono::system_clock::now().
Next it is convenient to "coarsen" these timestamps with seconds precision down to timestamps with a precision of days (number of days since the epoch).  This is done with this code:
auto dp0 = floor<days>(t0);
auto dp1 = floor<days>(t1);

dp0 and dp1 have type std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<int, std::ratio<86400>>>, which is a whopping mouth-full!  Isn't auto nice!  There is a typedef called date:: sys_days that is a handy shortcut for the type of dp0 and dp1, so you don't ever have to type out the ugly form.
Next it is handy to convert dp0 and dp1 to {year, month, day} structures.  There is such a structure with the type date::year_month_day which will implicitly convert from sys_days:
year_month_day ymd0 = dp0;
year_month_day ymd1 = dp1;

This is a very simple structure with year(), month() and day() getters.
It is also handy to have the time since midnight for each of these UNIX timestamps.  That is easily obtained by subtracting the days-resolution time_point from seconds-resolution time_point:
auto time0 = t0 - dp0;
auto time1 = t1 - dp1;

time0 and time1 have type std::chrono::seconds and represent the seconds past the start of the day for t0 and t1.
To verify where we are, it is handy to output what we have so far:
std::cout << ymd0 << ' ' << make_time(time0) << '\n';
std::cout << ymd1 << ' ' << make_time(time1) << '\n';

which outputs:
1970-07-28 08:00:00
2016-04-02 02:34:43

So far so good.  We have two UNIX timestamps divided up into their human readable components (at least year, month and day).  The function make_time shown in the print statement above takes seconds and converts it into a {hours, minutes, seconds} structure.
Ok, but so far all we've done is take UNIX timestamps and convert them to field types.  Now for the difference part...
To take the human-readable difference we start with the big units and subtract them.  And then if the next smallest units are not subtractible (if the subtraction would produce a negative result), then the bigger-unit subtraction is too big by one.  Stay with me, code+example is clearer than human language:
auto dy = ymd1.year() - ymd0.year();
ymd0 += dy;
dp0 = ymd0;
t0 = dp0 + time0;
if (t0 > t1)
{
    --dy;
    ymd0 -= years{1};
    dp0 = ymd0;
    t0 = dp0 + time0;
}
std::cout << dy.count() << " years\n";
std::cout << ymd0 << ' ' << make_time(time0) << '\n';
std::cout << ymd1 << ' ' << make_time(time1) << '\n';

This outputs:
45 years
2015-07-28 08:00:00
2016-04-02 02:34:43

First we take the difference between the year fields of ymd1 and ymd0 and store this in the variable dy which has type date::years.  Then we add dy back to ymd0 and recompute the serial time_points dp0 and t0.  If it turns out that t0 > t1 then we have added one too many years (because the month/day of ymd0 occurs later in the year than that of ymd1).  So we subtract a year and recompute.
Now we have the difference in years, and we have reduced the problem to finding the difference in {months, days, hours, minutes, seconds} and this delta is guaranteed to be less than 1 year.
This is the basic formula for the whole problem!  Now we just need to rinse and repeat with the smaller units:
auto dm =  ymd1.year()/ymd1.month() - ymd0.year()/ymd0.month();
ymd0 += dm;
dp0 = ymd0;
t0 = dp0 + time0;
if (t0 > t1)
{
    --dm;
    ymd0 -= months{1};
    dp0 = ymd0;
    t0 = dp0 + time0;
}
std::cout << dm.count() << " months\n";
std::cout << ymd0 << ' ' << make_time(time0) << '\n';
std::cout << ymd1 << ' ' << make_time(time1) << '\n';

The first line of this example deserves extra attention because a lot is going on here.  We need to find the difference between ymd1 and ymd0 in units of months.  Just subtracting ymd0.month() from ymd1.month() only works if ymd1.month() >= ymd0.month().  But ymd1.year()/ymd1.month() creates a date::year_month type.  These types are "time points", but with a precision of a month.  One can subtract these types and get months as a result.
Now the same formula is followed:  Add the difference of months back to ymd0, recompute dp0 and t0, and discover if you've added one too many months.  If so, add one less month.  The above code outputs:
8 months
2016-03-28 08:00:00
2016-04-02 02:34:43

Now we're down to finding the difference of {days, hours, minutes, seconds} between two dates.
auto dd = dp1 - dp0;
dp0 += dd;
ymd0 = dp0;
t0 = dp0 + time0;
if (t0 > t1)
{
    --dd;
    dp0 -= days{1};
    ymd0 = dp0;
    t0 = dp0 + time0;
}
std::cout << dd.count() << " days\n";
std::cout << ymd0 << ' ' << make_time(time0) << '\n';
std::cout << ymd1 << ' ' << make_time(time1) << '\n';

Now the interesting thing about sys_dayss is that they are really good at day-oriented arithmetic.  So instead of dealing with field types like year_month_day or year_month, we work with sys_days at this level.  We just subtract dp1 - dp0 to get the difference in days.  Then we add that to dp0, and recreate ymd0 and t0.  Check if t0 > t1 and if so, we've added one too many days so we back off by one day.  This code outputs:
4 days
2016-04-01 08:00:00
2016-04-02 02:34:43

Now we are just down to finding the difference between two time stamps in terms of {hours, minutes, seconds}.  This is really simple, and where <chrono> shines.
auto delta_time = time1 - time0;
if (time0 > time1)
    delta_time += days{1};
auto dt = make_time(delta_time);
std::cout << dt.hours().count() << " hours\n";
std::cout << dt.minutes().count() << " minutes\n";
std::cout << dt.seconds().count() << " seconds\n";
t0 += delta_time;
dp0 = floor<days>(t0);
ymd0 = dp0;
time0 = t0 - dp0;
std::cout << ymd0 << ' ' << make_time(time0) << '\n';
std::cout << ymd1 << ' ' << make_time(time1) << '\n';

We can just subtract time0 from time1.  Both time1 and time0 have type std::chrono::seconds and their difference has the same type.  If it turns out that time0 > time1 (as in this example), we need to add a day.  Then we can add the difference back and recompute time0, dp0 and ymd0 to check out our work.  We should get the same timestamp as t1 now.  This code outputs:
18 hours
34 minutes
43 seconds
2016-04-02 02:34:43
2016-04-02 02:34:43

This is all a very long-winded explanation for this code:
#include "date.h"
#include <iostream>

struct ymdhms
{
    date::years          y;
    date::months         m;
    date::days           d;
    std::chrono::hours   h;
    std::chrono::minutes min;
    std::chrono::seconds s;
};

std::ostream&
operator<<(std::ostream& os, const ymdhms& x)
{
    os << x.y.count()   << " years "
       << x.m.count()   << " months "
       << x.d.count()   << " days "
       << x.h.count()   << " hours "
       << x.min.count() << " minutes "
       << x.s.count()   << " seconds";
    return os;
}

using second_point =
    std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>;

ymdhms
human_readable_difference(second_point t1, second_point t0)
{
    using namespace date;
    auto dp0 = floor<days>(t0);
    auto dp1 = floor<days>(t1);
    year_month_day ymd0 = dp0;
    year_month_day ymd1 = dp1;
    auto time0 = t0 - dp0;
    auto time1 = t1 - dp1;
    auto dy = ymd1.year() - ymd0.year();
    ymd0 += dy;
    dp0 = ymd0;
    t0 = dp0 + time0;
    if (t0 > t1)
    {
        --dy;
        ymd0 -= years{1};
        dp0 = ymd0;
        t0 = dp0 + time0;
    }
    auto dm =  ymd1.year()/ymd1.month() - ymd0.year()/ymd0.month();
    ymd0 += dm;
    dp0 = ymd0;
    t0 = dp0 + time0;
    if (t0 > t1)
    {
        --dm;
        ymd0 -= months{1};
        dp0 = ymd0;
        t0 = dp0 + time0;
    }
    auto dd = dp1 - dp0;
    dp0 += dd;
    t0 = dp0 + time0;
    if (t0 > t1)
    {
        --dd;
        dp0 -= days{1};
        t0 = dp0 + time0;
    }
    auto delta_time = time1 - time0;
    if (time0 > time1)
        delta_time += days{1};
    auto dt = make_time(delta_time);
    return {dy, dm, dd, dt.hours(), dt.minutes(), dt.seconds()};
}

Which can be exercised like this:
int
main()
{
    std::cout << human_readable_difference(second_point{1459564483s},
                                           second_point{18000000s}) << '\n';
}

and outputs:
45 years 8 months 4 days 18 hours 34 minutes 43 seconds

The algorithms behind all this are all public domain and neatly collected and explained here:
http://howardhinnant.github.io/date_algorithms.html
I would like to emphasize that this question is a good but complicated question because of the non-uniformity of units such as years and months.  The most effective way to deal with a question like this is to have low-level tools capable of abstracting away the complicated low-level arithmetic with higher-level syntax.
As an added verification, this:
std::cout << human_readable_difference(sys_days{feb/11/2000} + 9h + 21min + 6s,
                                       sys_days{jul/12/1900} + 15h + 24min + 7s) << '\n';

Outputs:
99 years 6 months 29 days 17 hours 56 minutes 59 seconds

which is identical to the output reported in another answer that reports what Wolfram Alpha outputs. As a bonus, the syntax here does not -- and can not -- suffer from endian ambiguity (m/d/y vs d/m/y). Admittedly this involved a little luck in that Wolfram's output is reported using the "America/New_York" timezone, and for these two timestamps the UTC offset is the same (so the timezone offset does not factor in).
If timezone actually does matter, an additional software layer on top of this is required.

A: For the older date, use the Leap Year formula to start counting the number of days from Unix start date, Jan1st 1970, to your first timestamp
(For leap seconds, dunno if you need to get that precise, hopefully will be out-of-scope?)
Leap year calculated by constraining date to after 1600AD and
the algorithm for the Gregorian Calendar from:
http://en.wikipedia.org/wiki/Leap_year of
if year modulo 400 is 0
       then is_leap_year
    else if year modulo 100 is 0
       then not_leap_year
    else if year modulo 4 is 0
      then is_leap_year
    else
      not_leap_year
If a year is a Leap Year, then there are 29days in Feb, else 28days
Now you know the month, day_of_month, year for the 1st variable
Next, another set of counts of days to the 2nd timestamp, using the Leap Year formula till you get to the 2nd timestamp.
typedef struct {
  int year;
  int month;
  int dayOfMonth;
} date_struct;

static int days_in_month[2][13] = {
  {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};

int isLeapYear(int year) {
  int value;
  value = year;

  //if year modulo 400 is 0
  //   then is_leap_year
  value = year % 400;
  if(value == 0) return 1;

  //else if year modulo 100 is 0
  //   then not_leap_year
  value = year % 100;
  if(value == 0) return 0;

  //else if year modulo 4 is 0
  //   then is_leap_year
  value = year % 4;
  if(value == 0) return 1;

  //else
  //   not_leap_year
  return 0;
}

date_struct addOneDay(date_struct ds, int isLeapYear){
  int daysInMonth;

  ds.dayOfMonth++;

  //If the month is February test for leap year and adjust daysInMonth
  if(ds.month == 2) {
    daysInMonth = days_in_month[isLeapYear][ds.month];
  } else {
    daysInMonth = days_in_month[0][ds.month];
  }

  if(ds.dayOfMonth > daysInMonth) {
    ds.month++;
    ds.dayOfMonth = 1;
    if(ds.month > 12) {
      ds.year += 1;
      ds.month = 1;
    }
  }
  return ds;
}

long daysBetween(date_struct date1, date_struct date2){
  long result = 0l;
  date_struct minDate = min(date1, date2);
  date_struct maxDate = max(date1, date2);

  date_struct countingDate;
  countingDate.year = minDate.year;
  countingDate.month = minDate.month;
  countingDate.dayOfMonth = minDate.dayOfMonth;

  int leapYear = isLeapYear(countingDate.year);
  int countingYear = countingDate.year;

  while(isLeftDateSmaller(countingDate,maxDate)) {
    countingDate = addOneDay(countingDate,leapYear);
    //if the year changes while counting, check to see if
    //it is a new year
    if(countingYear != countingDate.year) {
      countingYear = countingDate.year;
      leapYear = isLeapYear(countingDate.year);
    }

    result++;
  }

  return result;
}

(I wrote an open source program that gives the difference between two calendar dates, in C/C++. Its source code, some that I posed above, might help give you inspiration for your own solution, or maybe you can adapt some of it, too http://mrflash818.geophile.net/software/timediff/ )

A: Re: "surely this is a solved problem?"
This problem appears to be be solved, if Wolfram Alpha is correct.  It seems WA doesn't publicly provide their method, and their site deliberately makes screen-scraping difficult, but it has a method, which is available as an online "black box".
To see that black box in action, go to Wolfram Alpha, and eEnter two dates, separated by a "to", for example:
7/12/1900 to 2/11/2000

Outputs:

99 years 6 months 30 days

Times of day also:
7/12/1900 3:24:07pm  to 2/11/2000 9:21:06am

Outputs:

99 years 6 months 29 days 17 hours 56 minutes 59 seconds

Note that Wolfram assumes a default EST timezone.  Locations too, can be input, here's the same numeric range the latter example but in different locations and timezones:
7/12/1900 3:24:07pm in Boston to 2/11/2000 9:21:06am in Hong Kong

The output is different from the previous answer by 13 hours:

99 years 6 months 29 days 4 hours 56 minutes 59 seconds


text:
Q: I am stuck in my while loop with elapsed time of a timer as condition I am starting a timer and I want the method to wait until some time passed. I have searched in other similar questions but cannot find a clear answer.
Why is does the following code freeze the app?
elapsed time starts at 0 and intervall is 1000 (1sec)
private void timer2_Tick(object sender, EventArgs e)
    {
        elapsedtime2++;
    }

//this is inside my method
timer2.Start();
while (elapsedtime2 < 3)
    {

    }
timer2.Stop();

A: The easiest way to pause execution for a second is:
Thread.Sleep(1000);

If you're familiar with async/await, the async equivalent is:
await Task.Delay(1000);

A: You can use events to get the desired behaviour:
private int elapsedtime2 = 0;
private ManualResetEventSlim mre = new ManualResetEventSlim();

private void timer2_Tick(object sender, EventArgs e)
    {
        elapsedtime2++;
        if(elapsedtime2 >= 3)
        {
            mre.Set();
        }
    }

If your elapsed time variable has the expected value, you can set the event.
mre.Reset();
timer2.Start();
mre.Wait();
timer2.Stop();

Before you start the timer, you unset the event. After you started your timer, you wait until the event is set.


text:
Q: what input should be given while creating hyperbox for neural network?(Fuzzy Min Max Neural Network classification)) I am Currently Working on Project  "Fuzzy Min Max Neural Network Part 1: Classification"
By going through paper I understood the concept of project but not able to decide how to create Hyperbox for input pattern. And no informaton is Available on internet.
I am using Java Technology.
And I am Using PID datset.
link for the paper:
ftp://ftp.inf.ufrgs.br/pub/SIA/refer%EAncias/fuzzy%20min%20max%20classifier.pdf
I want to ask that while creating hyperbox all the parameters of input dataset should be used or work can be done with single parameter also and what should be the size of hyperbox   that we have give initally before creating hyperbox ( 0 < size of hyperbox <1) ?

A: PID data set is having 9 attributes. select 2 or more than 2 attributes and than apply your algorithm to create hyperbox.


text:
Q: CMake cross compilation with Poky I try to set up my cross-platform development environment with CMake.
I encounter the following error only when I try to compile with poky toolchain:
make[2]: * No rule to make '/opt/poky/1.3/sysroots/armv5te-poky-linux-gnueabi/usr/lib/libboost_thread.so', needed by 'test'. Stop
I tried to set up the CMake toolchain in two different methods and the result is the same.
Method1 (simple):
###################################################################################
# Cross compile using Poky prebuilt toolchains, you need to source the
# environment first:
#
# $ rm -fr build; mkdir build; cd build
# $ source /opt/poky/1.3/environment-setup-armv5te-poky-linux-gnueabi
# $ cmake -DCMAKE_TOOLCHAIN_FILE=Toolchains/arm-poky-linux-gnueabi-simple.cmake
# $ make
###################################################################################

SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_SYSTEM_VERSION 1)

SET(CMAKE_FIND_ROOT_PATH $ENV{OECORE_TARGET_SYSROOT})
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

Method2:
# this one is important
SET( CMAKE_SYSTEM_NAME Linux )

# this one not so much
SET( CMAKE_SYSTEM_VERSION 1 )

# specify the cross compiler
SET( CROSS_COMPILER_PATH /opt/poky/1.3/sysroots/x86_64-pokysdk-linux/usr/bin/armv5te-poky-linux-gnueabi )
SET( C_CROSS_COMPILER arm-poky-linux-gnueabi- )

FIND_PROGRAM( CCACHE ccache )
IF( CCACHE )
    SET( CMAKE_C_COMPILER "${CCACHE}" "${CROSS_COMPILER_PATH}/${C_CROSS_COMPILER}gcc" )
    SET( CMAKE_CXX_COMPILER "${CCACHE}" "${CROSS_COMPILER_PATH}/${C_CROSS_COMPILER}g++" )
ELSE( CCACHE )
    SET( CMAKE_C_COMPILER "${CROSS_COMPILER_PATH}/${C_CROSS_COMPILER}gcc" "" )
    SET( CMAKE_CXX_COMPILER "${CROSS_COMPILER_PATH}/${C_CROSS_COMPILER}g++" "" )
ENDIF(CCACHE)

SET( CMAKE_RANLIB "${CROSS_COMPILER_PATH}/${C_CROSS_COMPILER}ranlib" )
SET( CMAKE_AR "${CROSS_COMPILER_PATH}/${C_CROSS_COMPILER}ar" )

SET( CMAKE_COMPILER_IS_GNUCC 1 )
SET( CMAKE_COMPILER_IS_GNUCXX 1 )

INCLUDE_DIRECTORIES( BEFORE SYSTEM /opt/poky/1.3/sysroots/armv5te-poky-linux-gnueabi/usr/include )
LINK_DIRECTORIES( /opt/poky/1.3/sysroots/armv5te-poky-linux-gnueabi/usr/lib )

# where is the target environment
SET( CMAKE_FIND_ROOT_PATH /opt/poky/1.3/sysroots/armv5te-poky-linux-gnueabi/ )

#search for libraries and header files only in the target environment
SET( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY )
SET( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY )

# search for programs in the build host directories
SET( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER )

My CMake project is:
cmake_minimum_required( VERSION 2.8.9 )

project ( TEST )

set( BOOST_COMPONENTS thread )

find_package( Boost COMPONENTS ${BOOST_COMPONENTS} )

add_executable( test test.cpp )
target_link_libraries( test ${Boost_THREAD_LIBRARY} )

My cpp code used for tests:
#include <boost/thread/thread.hpp>
#include <iostream>

void hello()
{
    std::cout << "Hello!" << std::endl;
}

int main()
{
    boost::thread thrd( &hello );
    thrd.join();
    return 0;
}

Thank you by advance for your help

A: The solution to my problem:
Solution1:
###################################################################################
#
# Cross compile using Poky prebuilt toolchains, you need to source the
# environment first:
#
# $ rm -fr build; mkdir build; cd build
# $ source /opt/poky/1.3/environment-setup-armv5te-poky-linux-gnueabi
# $ cmake -DCMAKE_TOOLCHAIN_FILE=Toolchains/arm-poky-linux-gnueabi-simple.cmake
# $ make
#
###################################################################################

SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_SYSTEM_VERSION 1)

SET(CMAKE_FIND_ROOT_PATH /home/sylvain/Share/dev/Dev2M_CMakeCrossCompile/temp/boost $ENV{OECORE_TARGET_SYSROOT})
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

My CMake project:
cmake_minimum_required( VERSION 2.8.9 )

project ( TEST )

set( BOOST_COMPONENTS atomic system thread )

#Very useful to find the source of the problem
#set( Boost_DEBUG on )

#Set the version of gcc in my case that is the source of my problems otherwise the module defines the gcc version of my ubuntu PC
set( Boost_COMPILER "-gcc" )

set( BOOST_ROOT /home/sylvain/Share/dev/Dev2M_CMakeCrossCompile/temp/boost )

find_package( Boost COMPONENTS ${BOOST_COMPONENTS} true )

set( MY_BOOST_LIBRARIES
    ${Boost_ATOMIC_LIBRARY}
    ${Boost_SYSTEM_LIBRARY}
    ${Boost_THREAD_LIBRARY}
)

add_executable( test test.cpp )
target_link_libraries( test ${MY_BOOST_LIBRARIES} )

A: Boost is usually linked as follows:
FIND_PACKAGE( Boost COMPONENTS ${TheLibs} REQUIRED )
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})

add_executable(test test.cpp)
target_link_libraries( test ${Boost_LIBRARIES} )

For clarification:
The message "no rule to make" often means that the target file doesn't exist. Most of the times i check the file manually. If the file exists and you still get errors you can try to link manually by setting linker flags
e.g.:
SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -l${PATH_TO_LIBRARY}")

If it still doesn't work, then call make with the Verbose flag (usually VERBOSE=1) and look if the link step is executed correctly.

A general approach to link a external library is to add it as an own target. The advantage is that you can reuse it for multiple executables or libraries in the same Project. You wouldn't use that for boost, because they usually handle that for you.
add_library( libABCDEFG SHARED/STATIC IMPORTED )
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${PathToLibrary} )
TARGET_LINK_LIBRARIES(test libABCDEFG)

Another hint to CMake usage with Toolchains:
A Toolchain is only included on the first creation of the project (except you include it otherwise). If you change any settings inside of the toolchain you have to delete the CMake Cache and re-execute the first CMake call.


text:
Q: DIFxApp fails to copy catalog file specified in "CatalogFile.NTx86" in INF I want to make installer for driver.
I use Wix and DifxApp extension, but the driver is installed without certification.
It is failed to copy catalog file according to setupapi.log.
How to write WXS to install with certification?
Driver package is specified in WXS as below.
<DirectoryRef Id="APPLICATIONROOTDIRECTORY">
    <Component Id="MyDrver" Guid="MY-GUID">
        <Difxapp:Driver
            AddRemovePrograms="no"
            DeleteFiles="yes"
            ForceInstall="yes"
            Legacy="no"
            PlugAndPlayPrompt="no"
            Sequence="1"/>
        <File Id="MyDrver_INF" Name="MyDrver.inf" Source="Driver\MyDrver.inf" Vital="yes" KeyPath="yes" DiskId="1" Checksum="yes" />
        <File Id="MyDrver_CAT" Name="MyDrver.cat" Source="Driver\MyDriver_amd64.cat" Vital="yes" KeyPath="no"  DiskId="1" Checksum="yes" />
        <File Id="MyDrver_SYS" Name="MyDrver.sys" Source="Driver\MyDrver.sys" Vital="yes" KeyPath="no"  DiskId="1" Checksum="yes" />
    </Component>
</DirectoryRef>

Catalog file is specified in INF as below.
CatalogFile.NTx86  = MyDriver_x86.cat
CatalogFile.NTIA64 = MyDriver_ia64.cat
CatalogFile.NTAMD64 = MyDriver_amd64.cat

A: The Name="MyDrver.cat" in the MyDrver_CAT File actually renames the file that you are installing to MyDrver.cat. Omitting the "Name" attribute will automatically name the file the same as the file defined in the Source attribute (MyDriver_amd64.cat).
I assume your driver is failing to install because the inf file defines the CAT file with a specific name that does not exist in your installation since you rename that file to something else.


text:
Q: pymongo remove with user defined parameters I'm trying to build a simple mongodb RESTful API. Client will send JSON data for document removal, which looks like this:
{
    "collectionName": "user",
    "data": {
        "field": "fname",
        "value": "Mike"
    },
    "options": {
        "multi": "false"
    }
}

I would like to pass options from this JSON to pymongo's .remove() function but it's not working. I've tried it like this:
opts = {u'multi': u'false'}
dataBase[collectionName].remove({"some":"condition"},multi=opts['multi'])

it removes all documents that match the given condition, but multi should be false.
What am I doing wrong?

A: PyMongo's remove() method doesn't support the "multi" option. The option will be added in the next release of PyMongo, version 2.7. Details are in ticket PYTHON-605.


text:
Q: Oracle SQL Developer - errors copying a view from one database to another I'm trying to copy a view from one database to another. I'm exporting the view using 'Quick DDL > save to worksheet' to generate the script. At the top of the script i get the message:
"-- Unable to render VIEW DDL for object <view name> with DBMS_METADATA attempting internal generator."

Both the databases are identical, the view I'm trying to copy existed in both databases but was dropped in error in one of them.
When I try to run the script on my second database i get the error
Error report:
SQL Error: ORA-00604: error occurred at recursive SQL level 1
ORA-00001: unique constraint (SYS.I_COL1) violated
00604. 00000 -  "error occurred at recursive SQL level %s"
*Cause:    An error occurred while processing a recursive SQL statement
           (a statement applying to internal dictionary tables).
*Action:   If the situation described in the next error on the stack
           can be corrected, do so; otherwise contact Oracle Support.

Has anyone any idea what I might be doing wrong?

A: The message

-- Unable to render VIEW DDL for object  with DBMS_METADATA attempting internal

gives the SQL Developer.
This is due to the fact that he can not use dbms_metadata.get_ddl.
If everything is fine with the privileges, most likely due to the type of error (on execute dbms_metadata.get_ddl):
 ORA-06502: PL/SQL: numeric or value error
 LPX-00210: expected '<' instead of 'n'
 ORA-06512: at "SYS.UTL_XML", line 0
 ORA-06512: at "SYS.DBMS_METADATA_INT", line 3296
 ORA-06512: at "SYS.DBMS_METADATA_INT", line 4148
 ORA-06512: at "SYS.DBMS_METADATA", line 458
 ORA-06512: at "SYS.DBMS_METADATA", line 615
 ORA-06512: at "SYS.DBMS_METADATA", line 1221
 ORA-06512: at line 1

Try to reload the XML API:
1. enable restricted database session
2. run:
(from $ORACLE_HOME/rdbms/admin):
catnomet.sql
rmxml.sql
to remove the xml subsystem and after that: catxml
utlcxml.sql
prvtcxml.plb
catmet.sql
to reload it.

A: In my case, the problem was because in the view there were two columns with the same name or alias, and since the COL $ table has a unique index with the object number, and the name of the column, two columns are not allowed with the same name


text:
Q: SharePoint 2007 crawler is not stopping I recently tried to start a full crawl after my colleague mentioned that some of the files are not visible in the search.
Normally the crawler start full crawl every week. so i manually tried to start a full crawl. but eventually i come up with error message saying "Could not access the search service configuration database".

While looking on the content source in search administration area (Shared Services Administration: SharedServices1 > Search Administration > Content sources)i found that its being crawling for about 333 hours that's about 14 days.

So, i though to stop the crawler and start again. but it didn't seems to be stopping from crawling.
Does anyone have any idea to solve this issue... thanks in advance.


text:
Q: How to install Eclipse Neon behind a proxy With Neon, Eclipse comes with an installer.
I could not find any configuration menu in the installer.
My java version is:
java -version
java version "1.8.0_72"
Java(TM) SE Runtime Environment (build 1.8.0_72-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.72-b15, mixed mode)

on an ubuntu 14.04 64 bits.
I tried to configure the proxy in the eclipse-inst.ini:
...
-Djava.net.useSystemProxies=true
-Dhttps.proxyPort=8888
-Dhttp.proxyPort=8888
-Dhttps.proxyHost=localproxy
-Dhttp.proxyHost=localproxy

as documented here https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html
but the installer hangs...

A: There are two options:

*

*Download a full package instead of using the installer. There's a link right on the downloads page, but here's where to get the packages.

*Switch the installer to Advanced Mode (use the menu button in the top-right corner of the installer window). In Advanced Mode there is a place to confiure proxy settings:

A: A simpler approach would be to set up proxy in your command line:
Linux:
bash $ export http_proxy=http://www-proxy.example.com:80
bash $ export https_proxy=http://www-proxy.example.com:80 # Replace with your proxy protocol, url and port.
bash $ cd <Folder where Eclipse installer is downloaded>
bash $ ./eclipse-inst

csh $ setenv http_proxy http://user:password@proxy.domain.com:port
csh $ setenv https_proxy http://user:password@proxy.domain.com:port
csh $ cd <Folder where Eclipse installer is downloaded>
csh $ ./eclipse-inst

Windows:
set HTTP_PROXY=http://user:password@proxy.domain.com:port
set HTTPS_PROXY=http://user:password@proxy.domain.com:port

and invoke the eclipse-inst tool from the same command line.

A: I could find a workaround, which is to copy a valid network configuration from a previous Eclipse Mars configuration.
cp <old_eclipse>/configuration/.settings/org.eclipse.core.net.prefs <neon_installer_path>/eclipse-installer/configuration/.settings
It works, but it really looks like a hack, any other clues?

A: Solution worked for me:
Windows:
set HTTP_PROXY=http://user:password@proxy.domain.com:port
set HTTPS_PROXY=http://user:password@proxy.domain.com:port
and invoke the eclipse-inst tool from the same command line.


text:
Q: Modifying content in file I run into a problem, which I cant solve.
Im making an app, where on the first page I need to choose one of two machines, there are 2 buttons on page and when one of them is clicked, i make POST to /mechineChoose where I pass id of selected machine. Then I need to change config.js file, where I have all params needed for rest of app.
const config = {
machineName: "Machine",
...

So in my code I need to change machineName, right now I use fs module to read and then write to file, but problem is that I cant change this name more than once. When I restart app, Im able to change the name, but when trying to choose second machine, nothing happens.
router.post("/machineChoose", async (req, res) => {
console.log(req.body.machineChoose);
if (req.body.machineChoose == 1) {
    machineX = "Machine1";

} else {
    machineX = "Machine2";
}
console.log(machineX);
fs.readFile('./config.js', 'utf-8', function (err,data){
    if (err){
        console.log(err);
    }
    var result = data.replace(config.machineName,machineX);
    fs.writeFileSync('./config.js', result, 'utf-8', function(err){
        if (err) return console.log(err);
    });
});
return res.send("")

})
Any idea how to solve it ?

A: After writing to the file, you need to reload the config-object as it will still hold the previous state in-memory and thus further calls to data.replace(...) will not replace anything, since it will still be called with "Machine".
I would do something like this (although you should consider using a real database):
router.post("/machineChoose", async (req, res) => {
    const chosenMachine = req.body.machineChoose == 1 ? "Machine1" : "Machine2";
    const config = await readConfig();
    config.machineName = chosenMachine;
    await writeConfig(config);
    res.status(204).end();
});

async function writeConfig(currentConfig) {
    try {
        await fs.promises.writeFile("./config.json", JSON.stringify(currentConfig));
    } catch (e) {
        console.log("Could not write config file", e)
        throw e;
    }
}

async function readConfig() {
    try {
        const rawConfig = await fs.promises.readFile("./config.json", {encoding: 'utf-8'});
        return JSON.parse(rawConfig);
    } catch (e) {
        console.log("Could not read config file", e)
        throw e;
    }
}


text:
Q: Microsoft SQL query to view I have this complex query that i want to turn into a view.
This query comes from https://snippets.cacher.io/snippet/3e84b01b7d52b4ca7807 and i want to save it in a view or even as a table if possible.
`
/*##=============================================*/
/*## QUERY BODY                                  */
/*##=============================================*/
/* #region QueryBody */

/* Testing variables !! Need to be commented for Production !! */
-- DECLARE @UserSIDs              AS NVARCHAR(10)  = 'Disabled';
-- DECLARE @CollectionID          AS NVARCHAR(10)  = 'SMS00001';
-- DECLARE @Locale                AS INT           = 2;
-- DECLARE @Categories            AS NVARCHAR(250) = 'Tools';
-- DECLARE @Compliant             AS INT           = 0;
-- DECLARE @Targeted              AS INT           = 1;
-- DECLARE @Superseded            AS INT           = 0;
-- DECLARE @ArticleID             AS NVARCHAR(10)  = '';
-- DECLARE @ExcludeArticleIDs     AS NVARCHAR(250) = '';

/* Variable declaration */
DECLARE @LCID                  AS INT = dbo.fn_LShortNameToLCID(@Locale);
DECLARE @HelperFunctionExists  AS INT = 0;

/* Perform cleanup */
IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL
    DROP TABLE #MaintenanceInfo;

/* Check for helper function */
IF OBJECT_ID('[dbo].[ufn_CM_GetNextMaintenanceWindow]') IS NOT NULL
    SET @HelperFunctionExists = 1;

/* Initialize HealthState descriptor table */
DECLARE @HealthState TABLE (
    BitMask     INT
    , StateName NVARCHAR(250)
)

/* Populate HealthState table */
INSERT INTO @HealthState (BitMask, StateName)
VALUES
    ('0',     'Healthy')
    , ('1',   'Unmanaged')
    , ('2',   'Inactive')
    , ('4',   'Health Evaluation Failed')
    , ('8',   'Pending Restart')
    , ('16',  'Update Scan Failed')
    , ('32',  'Update Scan Late')
    , ('64',  'No Maintenance Window')
    , ('128', 'Distant Maintenance Window')
    , ('256', 'Expired Maintenance Window')

/* Initialize ClientState descriptor table */
DECLARE @ClientState TABLE (
    BitMask     INT
    , StateName NVARCHAR(100)
)

/* Populate ClientState table */
INSERT INTO @ClientState (BitMask, StateName)
VALUES
    ('0', 'No Reboot')
    , ('1', 'Configuration Manager')
    , ('2', 'File Rename')
    , ('4', 'Windows Update')
    , ('8', 'Add or Remove Feature')

CREATE TABLE #MaintenanceInfo (
    ResourceID          INT
    , NextServiceWindow DATETIME
)

/* Get maintenance data */
IF @HelperFunctionExists = 1
    BEGIN
        WITH Maintenance_CTE AS (
            SELECT
                CollectionMembers.ResourceID
                , NextServiceWindow.Duration
                , NextServiceWindow.NextServiceWindow
                , RowNumber             = DENSE_RANK() OVER (PARTITION BY ResourceID ORDER BY NextServiceWindow.NextServiceWindow)
                , ServiceWindowType
                , ServiceWindow.Enabled
            FROM vSMS_ServiceWindow AS ServiceWindow
                JOIN fn_rbac_FullCollectionMembership(@UserSIDs) AS CollectionMembers ON CollectionMembers.CollectionID = ServiceWindow.SiteID
                JOIN fn_rbac_Collection(@UserSIDs) AS Collections ON Collections.CollectionID = CollectionMembers.CollectionID
                    AND Collections.CollectionType = 2                           -- Device Collections
                CROSS APPLY ufn_CM_GetNextMaintenanceWindow(ServiceWindow.Schedules, ServiceWindow.RecurrenceType) AS NextServiceWindow
            WHERE  NextServiceWindow.NextServiceWindow IS NOT NULL
                AND ServiceWindowType <> 5 -- OSD Service
        )

        /* Populate MaintenanceInfo table and remove duplicates */
        INSERT INTO #MaintenanceInfo(ResourceID, NextServiceWindow)
        SELECT
            ResourceID
            , NextServiceWindow
        FROM Maintenance_CTE
        WHERE RowNumber = 1
    END

/* Get update data */
;
WITH UpdateInfo_CTE
AS (
    SELECT
        ResourceID      = Systems.ResourceID
        , Missing       = COUNT(*)
    FROM fn_rbac_R_System(@UserSIDs) AS Systems
        JOIN fn_rbac_UpdateComplianceStatus(@UserSIDs) AS ComplianceStatus ON ComplianceStatus.ResourceID = Systems.ResourceID
            AND ComplianceStatus.Status = 2                                      -- Filter on 'Required' (0 = Unknown, 1 = NotRequired, 2 = Required, 3 = Installed)
        JOIN fn_rbac_ClientCollectionMembers(@UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = ComplianceStatus.ResourceID
        JOIN fn_rbac_UpdateInfo(@LCID, @UserSIDs) AS UpdateCIs ON UpdateCIs.CI_ID = ComplianceStatus.CI_ID
            AND UpdateCIs.IsSuperseded IN (@Superseded)
            AND UpdateCIs.CIType_ID IN (1, 8)                                    -- Filter on 1 Software Updates, 8 Software Update Bundle (v_CITypes)
            AND UpdateCIs.ArticleID NOT IN (                                     -- Filter on ArticleID csv list
                SELECT VALUE FROM STRING_SPLIT(@ExcludeArticleIDs, ',')
            )
            AND UpdateCIs.Title NOT LIKE (                                       -- Filter Preview updates
                '[1-9][0-9][0-9][0-9]-[0-9][0-9]_Preview_of_%'
            )
        JOIN fn_rbac_CICategoryInfo_All(@LCID, @UserSIDs) AS CICategory ON CICategory.CI_ID = ComplianceStatus.CI_ID
            AND CICategory.CategoryTypeName = 'UpdateClassification'
            AND CICategory.CategoryInstanceName IN (@Categories)                 -- Filter on Selected Update Classification Categories
        LEFT JOIN fn_rbac_CITargetedMachines(@UserSIDs) AS Targeted ON Targeted.ResourceID = ComplianceStatus.ResourceID
            AND Targeted.CI_ID = ComplianceStatus.CI_ID
    WHERE CollectionMembers.CollectionID = @CollectionID
        AND IIF(Targeted.ResourceID IS NULL, 0, 1) IN (@Targeted)                -- Filter on 'Targeted' or 'NotTargeted'
        AND IIF(UpdateCIs.ArticleID = @ArticleID, 1, 0) = IIF(@ArticleID <> '', 1, 0)
    GROUP BY
        Systems.ResourceID
)

/* Get device info */
SELECT
    Systems.ResourceID

    /* Set Health states. You can find the coresponding values in the HealthState table above */
    , HealthStates      = (
        IIF(CombinedResources.IsClient != 1, POWER(1, 1), 0)
        +
        IIF(
            ClientSummary.ClientStateDescription = 'Inactive/Pass'
            OR
            ClientSummary.ClientStateDescription = 'Inactive/Fail'
            OR
            ClientSummary.ClientStateDescription = 'Inactive/Unknown'
            , POWER(2, 1), 0)
        +
        IIF(
            ClientSummary.ClientStateDescription = 'Active/Fail'
            OR
            ClientSummary.ClientStateDescription = 'Inactive/Fail'
            , POWER(4, 1), 0
        )
        +
        IIF(CombinedResources.ClientState != 0, POWER(8, 1), 0)
        +
        IIF(UpdateScan.LastErrorCode != 0, POWER(16, 1), 0)
        +
        IIF(UpdateScan.LastScanTime < (SELECT DATEADD(dd, -14, CURRENT_TIMESTAMP)), POWER(32, 1), 0)
        +
        IIF(ISNULL(NextServiceWindow, 0) = 0 AND @HelperFunctionExists = 1, POWER(64, 1), 0)
        +
        IIF(NextServiceWindow > (SELECT DATEADD(dd, 30, CURRENT_TIMESTAMP)), POWER(128, 1), 0)
        +
        IIF(NextServiceWindow < (CURRENT_TIMESTAMP), POWER(256, 1), 0)
    )
    , Missing           = ISNULL(Missing, (IIF(CombinedResources.IsClient = 1, 0, NULL)))
    , Device            = (
            IIF(
                SystemNames.Resource_Names0 IS NOT NULL, UPPER(SystemNames.Resource_Names0)
                , IIF(Systems.Full_Domain_Name0 IS NOT NULL, Systems.Name0 + '.' + Systems.Full_Domain_Name0, Systems.Name0)
            )
    )
    , OperatingSystem   = (
        CASE
            WHEN OperatingSystem.Caption0 != '' THEN
                CONCAT(
                    REPLACE(OperatingSystem.Caption0, 'Microsoft ', ''),          -- Remove 'Microsoft ' from OperatingSystem
                    REPLACE(OperatingSystem.CSDVersion0, 'Service Pack ', ' SP')  -- Replace 'Service Pack ' with ' SP' in OperatingSystem
                )
            ELSE (

            /* Workaround for systems not in GS_OPERATING_SYSTEM table */
                CASE
                    WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.1%'    THEN 'Windows 7'
                    WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.2%'    THEN 'Windows 8'
                    WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.3%'    THEN 'Windows 8.1'
                    WHEN CombinedResources.DeviceOS LIKE '%Workstation 10.0%'   THEN 'Windows 10'
                    WHEN CombinedResources.DeviceOS LIKE '%Server 6.0'          THEN 'Windows Server 2008'
                    WHEN CombinedResources.DeviceOS LIKE '%Server 6.1'          THEN 'Windows Server 2008R2'
                    WHEN CombinedResources.DeviceOS LIKE '%Server 6.2'          THEN 'Windows Server 2012'
                    WHEN CombinedResources.DeviceOS LIKE '%Server 6.3'          THEN 'Windows Server 2012 R2'
                    WHEN Systems.Operating_System_Name_And0 LIKE '%Server 10%'  THEN (
                        CASE
                            WHEN CAST(REPLACE(Build01, '.', '') AS INTEGER) > 10017763 THEN 'Windows Server 2019'
                            ELSE 'Windows Server 2016'
                        END
                    )
                    ELSE Systems.Operating_System_Name_And0
                END
            )
        END
    )
    , LastBootTime      = (
        CONVERT(NVARCHAR(16), OperatingSystem.LastBootUpTime0, 120)
    )
    , PendingRestart    = (
        CASE
            WHEN CombinedResources.IsClient      = 0
                OR CombinedResources.ClientState = 0
            THEN NULL
            ELSE (
                STUFF(
                    REPLACE(
                        (
                            SELECT '#!' + LTRIM(RTRIM(StateName)) AS [data()]
                            FROM @ClientState
                            WHERE BitMask & CombinedResources.ClientState <> 0
                            FOR XML PATH('')
                        ),
                        ' #!',', '
                    ),
                    1, 2, ''
                )
            )
        END
    )
    , ClientState       = (
        CASE CombinedResources.IsClient
            WHEN 1 THEN ClientSummary.ClientStateDescription
            ELSE 'Unmanaged'
        END
    )
    , ClientVersion     = CombinedResources.ClientVersion
    , LastUpdateScan    = (
        CONVERT(NVARCHAR(16), UpdateScan.LastScanTime, 120)
    )
    , LastScanLocation  = NULLIF(UpdateScan.LastScanPackageLocation, '')
    , LastScanError     = NULLIF(UpdateScan.LastErrorCode, 0)
    , NextServiceWindow = IIF(CombinedResources.IsClient != 1, NULL, CONVERT(NVARCHAR(16), NextServiceWindow, 120))
FROM fn_rbac_R_System(@UserSIDs) AS Systems
    JOIN fn_rbac_CombinedDeviceResources(@UserSIDs) AS CombinedResources ON CombinedResources.MachineID = Systems.ResourceID
    LEFT JOIN fn_rbac_RA_System_ResourceNames(@UserSIDs) AS SystemNames ON SystemNames.ResourceID = Systems.ResourceID
    LEFT JOIN fn_rbac_GS_OPERATING_SYSTEM(@UserSIDs) AS OperatingSystem ON OperatingSystem.ResourceID = Systems.ResourceID
    LEFT JOIN fn_rbac_CH_ClientSummary(@UserSIDs) AS ClientSummary ON ClientSummary.ResourceID = Systems.ResourceID
    LEFT JOIN fn_rbac_UpdateScanStatus(@UserSIDs) AS UpdateScan ON UpdateScan.ResourceID = Systems.ResourceID
    LEFT JOIN #MaintenanceInfo AS Maintenance ON Maintenance.ResourceID = Systems.ResourceID
    LEFT JOIN UpdateInfo_CTE AS UpdateInfo ON UpdateInfo.ResourceID = Systems.ResourceID
    JOIN fn_rbac_FullCollectionMembership(@UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = Systems.ResourceID
WHERE CollectionMembers.CollectionID = @CollectionID
    AND (
        CASE                                                                     -- Compliant (0 = No, 1 = Yes, 2 = Unknown)
            WHEN Missing = 0 OR (Missing IS NULL AND Systems.Client0 = 1) THEN 1 -- Yes
            WHEN Missing > 0 AND Missing IS NOT NULL                      THEN 0 -- No
            ELSE 2                                                               -- Unknown
        END
    ) IN (@Compliant)

/* Perform cleanup */
IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL
    DROP TABLE #MaintenanceInfo;

/* #endregion */
/*##=============================================*/
/*## END QUERY BODY                              */
/*##=============================================*/

`
Is there an easy way to achieve this?
I have tried to look at the official Microsoft documentation but are still not able to convert the query to a view. https://learn.microsoft.com/en-us/sql/t-sql/statements/create-view-transact-sql?view=sql-server-ver16
As I am new to SQL language I am not sure where to start.

A: So I agree with Larnu, that this probably doesn't make a ton of sense. But there are cases where one might want to be able to run multiple batches of queries / procedural code from an object that's as consumable as a view. I've done this once in a case where I needed to maximize my options for performance tuning without losing the consumability of the object. So for the sake of when it does make sense, this is something you could do:

*

*Wrap your code in a stored procedure.

*Use OPENQUERY() to call your procedure.

*Wrap the OPENQUERY() call in a view.

Limitations with this methodology is it's rather static:

*

*You can't pass parameters to your stored procedure

*If you use temp tables in your stored procedure, then you need to use the WITH RESULT SETS clause to explicitly define the shape of your result set

*The procedure can only return one result set

*The SQL Server Engine puts a hard-coded cardinality estimate of 10,000 against OPENQUERY(). So in cases where your procedure returns a lot more rows (typically an order of magnitude or more) than 10,000, e.g. 1 million rows, then you may experience some performance issues with joining the wrapper view to other objects.

Example:
-- Step 1: Wrap the procedural code in a stored procedure
CREATE PROCEDURE dbo.RunSomeCode
AS
BEGIN

CREATE TABLE #Results (ID INT, SomeValue VARCHAR(100));

DECLARE @SomeVariable INT = 0;

WHILE (@SomeVariable < 5)
BEGIN
    SET @SomeVariable = @SomeVariable + 1;

    INSERT INTO #Results (ID, SomeValue)
    SELECT ID, SomeValue
    FROM SomeTable
    WHERE ID = @SomeVariable
END

SELECT ID, SomeValue
FROM #Results;

END
GO

-- Step 2 & 3: Wrap an OPENQUERY() call to the procedure in a view.
CREATE VIEW dbo.SomeView
AS

SELECT ID, SomeValue
FROM OPENQUERY
(
'
    LocalServerName,
    EXEC dbo.RunSomeCode
    WITH RESULT SETS
    ((
        ID INT,
        SomeValue VARCHAR(100)
    ))
'
);

Voila, you can now execute the procedure by SELECTing from the view:
SELECT ID, SomeValue
FROM dbo.SomeView;


text:
Q: Networks Security Group best practices Which are the best pratices to define Network Security Group in Azure?
All NICs need to have an NSG applied but is a best practice to create one for each NICs?
The best practice is to create one for enviroment (DEV, PROD, Staging)?

A: Microsoft works with the Center for Internet Security to develop the CIS Microsoft Azure Foundations Benchmark. This document includes a section on network security best practices. This is an excellent document to read and includes individual steps to secure your Azure environment. This is the Azure recommend document.
Each of the steps detailed by the document are part of the Azure Security Center and Azure Monitor.
The document is copyrighted, therefore I can only include a link to the CIS website:
Center for Internet Security

A: Truthfully it will be different on how your network or organization is laid out.  I would definitely not recommend one NSG per NIC.  NSG are built to be reusable so if you have a group of VMs who will need the same configuration it would be best to attach them all to the same NSG.
As for one NSG per environment I'd advice against this as well as it assumes the rules will be be the same for all your appliances and services. (I know subnets can also be part of this but again how is the organization setup and/or appetite for managing all of that).
If it helps think of NSG as your firewall policy on inbound/outbound ports (just allow/deny).  Would you assign the same restrictions on every machine or PaaS offerring?  Probably not. Would it be the same in every environment, possibly but not likely.
As for deployment and management I'd strongly recommend leveraging Azure Resource Manager (ARM) templates and associate that with a CI/CD pipeline and potentially set it up for nightly deployments.  This would protect against configuration drift on your network if users are manually configuring nsgs.


text:
Q: Understand the map function in Python - Index reassignment I am trying to understand how the map function works in Python with this usage :
I have
def permutate(table, block):
"""Permutate this block with the specified table"""
    return(map(lambda x: block[x], table))

ls_bits =    [0,1,0,0,1,1,1,0]
IP =         [2,3,1,4,7,0]

ls_bits= permutate (IP, ls_bits)
print (list(ls_bits))

>>>
[0, 0, 1, 1, 0, 0]

It does exactly what I want: it takes the value of i index in ls_bits (ls_bits[i]), and reassigns this value to the index of value IP[i] in ls_bits. For exemple, ls_bits[1] = 1, IP[1] = 3, so after the map function, ls_bits[3] = 1.
But I don't understand why (I found this method on the web) since I am not using any function in the "map method"
Thanks in advance for your help, I hope I was clear enough for you to understand my problem

A: A lambda expression is passed as a function to map. It is defined as a nested function to be able to reference the other function argument block. From the docs:

Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope [...]

The function map() is used to apply the callable (first argument) sequentially to the iterable (second argument). It builds a list of the callable's return values for each element contained in the iterable in return.
Altogether, it's a shorthand for
def permutate(table, block):
    """Permutate this block with the specified table"""
    def index(x):
        return block[x]
    ret = []
    for x in table:
        ret.append(index(x))
    return ret

For reference:

*

*http://docs.python.org/2/tutorial/controlflow.html#lambda-expressions

*http://docs.python.org/2/library/functions.html#map

A: map applies the function lambda x: block[x] to each of the elements of the iterable table and returns an array of the results

A: def permutate(IP, bits):
    return(map(lambda x: bits[x], IP))
    # To apply lambda function on IP list
    # x is any elem of IP list
    # return the index of elems in the IP list

    # bits[2] ---> 0. becuase index of 2 in the IP list is zero.
    # bits[3] ---> 0. becuase index of 3 in the IP list is zero.
    # bits[1] ---> 1. becuase index of 1 in the IP list is one.
    # bits[4] ---> 1. becuase index of 4 in the IP list is one.
    # bits[7] ---> 0. becuase index of 7 in the IP list is zero.
    # bits[0] ---> 0. becuase index of 0 in the IP list is zero.

    ### Visualization ###
    # elems of bits          --> 0   1   0   0   1   1   1   0
    # index of elems of btis --> 0   1   2   3   4   5   6   7

bits = [0,1,0,0,1,1,1,0]
IP   = [2,3,1,4,7,0]

print ('indexes of IP list :', list(permutate(IP, bits)))


text:
Q: Why Qt chart example does not delete dynamically allocated variables I have been checking the Qt BarChart example, I noticed that the dynamically allocated variables were not deleted at all, why? I try to copy the idea of this example, then use in a layout, and display the chart in a plainTextEditor. However, I want to delete these dynamically allocated variables once I display the chart, but I don't know when and where to delete them. I tried to delete them at the end of the function, but it won't show anything on the plainTextEditor. I don't want to define these dynamically allocated variables as a member variables and delete them in the Destructor.
Here are the example I get from the Qt Documentation
> #include <QtWidgets/QApplication>
> #include <QtWidgets/QMainWindow>
> #include <QtCharts/QChartView>
> #include <QtCharts/QBarSeries>
> #include <QtCharts/QBarSet>
> #include <QtCharts/QLegend>
> #include <QtCharts/QBarCategoryAxis>
>
> QT_CHARTS_USE_NAMESPACE
>
> int main(int argc, char *argv[]) {
>     QApplication a(argc, argv);
>
>     QBarSet *set0 = new QBarSet("Jane");
>     QBarSet *set1 = new QBarSet("John");
>     QBarSet *set2 = new QBarSet("Axel");
>     QBarSet *set3 = new QBarSet("Mary");
>     QBarSet *set4 = new QBarSet("Samantha");
>
>     *set0 << 1 << 2 << 3 << 4 << 5 << 6;
>     *set1 << 5 << 0 << 0 << 4 << 0 << 7;
>     *set2 << 3 << 5 << 8 << 13 << 8 << 5;
>     *set3 << 5 << 6 << 7 << 3 << 4 << 5;
>     *set4 << 9 << 7 << 5 << 3 << 1 << 2;
>
>     QBarSeries *series = new QBarSeries();
>     series->append(set0);
>     series->append(set1);
>     series->append(set2);
>     series->append(set3);
>     series->append(set4);
>
>
>     QChart *chart = new QChart();
>     chart->addSeries(series);
>     chart->setTitle("Simple barchart example");
>     chart->setAnimationOptions(QChart::SeriesAnimations);
>
>     QStringList categories;
>     categories << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun";
>     QBarCategoryAxis *axis = new QBarCategoryAxis();
>     axis->append(categories);
>     chart->createDefaultAxes();
>     chart->setAxisX(axis, series);
>
>     chart->legend()->setVisible(true);
>     chart->legend()->setAlignment(Qt::AlignBottom);
>
>     QChartView *chartView = new QChartView(chart);
>     chartView->setRenderHint(QPainter::Antialiasing);
>
>     QMainWindow window;
>     window.setCentralWidget(chartView);
>     window.resize(420, 300);
>     window.show();
>
>     return a.exec(); }

A: In Qt, certain functions are designated to take ownership, forming a parent/child relationship. And parents delete their children when they are destroyed.
With the example you've shown, series is the parent of set0 through set4 (from the calls to series->append). chart is the parent of axis and series (from chart->setAxisX). chartView is the parent of chart (from its construction: QChartView *chartView = new QChartView(chart)). And finally window is the parent of chartView (from window.setCentralWidget). And since window is not a pointer, but an actual QMainWindow object with automatic storage duration, it will be destroyed at the end of the scope, taking all of its descendants with it.


text:
Q: SELECT using file data won't work I have a query that returns nothing when it calls array data from files, but works fine if I declare the arrays inline.
Here's what's NOT working:
<?php

$firstnames = file("firstnames.txt");
$lastnames  = file("lastnames.txt");

for ($i = 0; $i < count($firstnames); $i++) {
    $stmt1 = $db->prepare("SELECT P_ID FROM personal WHERE personal.FirstName=:firstname AND personal.LastName=:lastname");

    $stmt1->bindParam(':firstname', $firstnames[$i], PDO::PARAM_STR);
    $stmt1->bindParam(':lastname', $lastnames[$i], PDO::PARAM_STR);

    $stmt1->execute();
    $row = $stmt1->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        foreach ($row as $key) {
            $PIDs[] = $key;
        }
    }
}

?>

But if I replace the the first two lines above with this, it works:
$firstnames = array("Michaela","Noeleen","Anton","Gerard","Gerard","Billy");
$lastnames = array("Daly","O'Brien","Vidal","Boyle","Espital","Mason");

I can output the $firstnames and $lastnames file contents to screen, so the file data is available to the query within the script. Any ideas what might be wrong?
File data is as follows, firstnames.txt :
Philip
Anne
Derek
Fíona
Katelyn
Margaret

Last names same format. No commas.


text:
Q: [yarn]Note that the development build is not optimized localhost:3000 shows blank page.
and some erros happen on console.
# yarn --version
1.22.19

#yarn start
Compiled successfully!

You can now view studyqa in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://172.18.0.2:3000

Note that the development build is not optimized.
To create a production build, use yarn build.

I tried to do "yarn start" after yarn build and yarn cache clean.
However, same messege
"
Note that the development build is not optimized.
To create a production build, use yarn build.
"
What should I do next?


text:
Q: Android is not receiving information sent via UDP I am trying to obtain information with the usage of UDP protocol on my Android device. I have to consider two cases - connection via access point, and router.
Sadly, in case of access point, I am loosing 95% of data - even though the sending process works properly (I can easily receive that information on my laptop). Somehow Android just can not cope with high traffic sent from one source.
Such problem does not exist when the connection works via router, because then the data is broadcasted from multiple sources, and it works reliably.
I would really appreciate any information about the cause of such behavior.

A: I have solved this issue - the access point did not detect any device in his network, even though there were few android devices connected. I had to write a pinging service, that keeps the constant outbound traffic.


text:
Q: What is the difference between DDE & WCF & WMI & WFP? As I mentioned in the question, What is the difference between DDE & WCF & WMI & WFP? and when should I use eachone. I searched alot in google but I didn't get the point.
Is there any intersection or common functions between them?

A: DDE is an old model used for Inter-Process Communication in Windows.
WCF is a .NET framework for building network applications.
WMI is a extension to the Windows Driver Model which allows getting notifications or information about hardware.


text:
Q: Where to start in PHP for a script that rearranges tab delimited data This would be one of my first PHP projects.
Where to start in PHP for a script that rearranges tab delimited data.
I have a tab delimited data text file that needs to be rearranged periodically. Some entire columns would have to move to different parts of the text file, and some headers of columns need to be renamed as well. Basically my tab delimited data file is being converted to match another tab delimited data set to fit a system. (Actually the file is an Amazon.com SELLER CENTRAL Order Reports tab delimited text file that is in a different format from tab delimited text files downloaded from Amazon.com's own MARKETPLACE Order Reports)
I hope someone can give me some direction as to where I would start writing code or how to make this script work...

A: You can read in the TSV file using PHP's fgetcsv(), using "\t" as the delimiter.
This gives you an array of columns that you can manipulate as you require. Once done, you can then write the array as a line in a new file using fputcsv()
Edit: As an example, the process would go something like

*

*Open file handles (using fopen()) to your existing data file (source) and the new destination file

*Read in the source file line-by-line using fgetcsv()

*Create a new array of columns using the values returned by fgetcsv() in the order required

*Write the new array to the new file using fputcsv()

*Once done, close both file handles

A: Parse the data using fgetcsv() and use array_multisort(). If you need an example, there's one available on the multisort manual page.

A: Surely you have to know here

*

*To match the TAB inside php you use the string: "\t"

*Next you will need the explode function to obtain the array from one row of the file

*next you'll need foreach cycling among the array elements to analyse the data

*of course the Arrays in PHP will always help you

*and at the end when you'll need produce the final TAB delimited file you'll need the implode
Of course take a look at string and array functions in PHP.


text:
Q: Are there any programming languages that don't descend from C? I mean descend as in languages who's original compiler/interpreter was written in C or in a language that descends from C.
If you don't count assembly, the only thing that comes to my mind is B. Are there any others?

A: Don't forget Algol, which has been called a vast improvement over most of its imitators, including C.
Both COBOL and FORTRAN came long before C. I've seen a COBOL compiler written in RPG.
It's not unusual for a language's first compiler to be written in that language. The first compilation can be done by hand, and the first thing compiled with the hand-compiled compiler is the very same source code that was just hand-compiled. And the first thing compiled with that first machine-compiled compiler is the same source file yet again. If the hand-built compiler and the self-compiled compiler produce exactly the same output from this same source file, you know the compiler works "well enough", and the hand-compiled compiler can be thrown away.
Notice that the hand-built compiler doesn't need to produce efficient code or produce it efficiently. In fact, it doesn't even need to compile any feature of the language that the compiler itself doesn't use. That makes it feasible to bootstrap even "large" languages this way.
Forth might be considered to have been written this way. There is only a tiny part of the Forth runtime that needs to be written in Assembler, and everything else can be written in Forth itself.

A: In addition to Lisp, Smalltalk, Forth, COBOL, and FORTRAN mentioned by others, there's Pascal, Modula, Fortran, PL/I, BASIC, Snobol, and APL, to name some of the more popular languages that were neither descended from nor implemented in C. Early languages were implemented or bootstrapped in assembler.
Here's a small family tree of programming languages.
Also see Wikipedia: early programming languages and Establishing fundamental paradigms.

A: Lisp and Smalltalk are good examples of such languages who were not descended from C. There was also a programming language named BCPL before C which isn't in use nowadays.


text:
Q: OAuth authentication with VB.NET I'm trying to follow this example to access Twitter Stream API (userstream), so I need to do some modifications and this is my final code:
        'We need to define some details about the request. This includes a unique oauth_nonce parameter which must be generated per request, and a timestamp
        Dim oauth_version As String = "1.0"
        Dim oauth_signature_method As String = "HMAC-SHA1"
        Dim oauth_nonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
        Dim TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
        Dim oauth_timestamp As Integer = Convert.ToInt64(TimeSpan.TotalSeconds).ToString()

        'The next step is to generate an encrypted oAuth signature which Twitter will use to validate the request.
        'To do this, all of the request data is concatenated into a particular format as follows
        Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" & _
                         "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}"

        Dim baseString As String = String.Format(baseFormat, _
                        oauth_consumer_key, _
                        oauth_nonce, _
                        oauth_signature_method, _
                        oauth_timestamp, _
                        oauth_token, _
                        oauth_version)

        'baseString = String.Concat("GET&", Uri.EscapeDataString(stream_url), "&", Uri.EscapeDataString(baseString))
        'baseString = String.Concat(Uri.EscapeDataString(stream_url), "&", Uri.EscapeDataString(baseString))
        baseString = Uri.EscapeDataString(stream_url)

        'Using this base string, we then encrypt the data using a composite of the secret keys and the HMAC-SHA1 algorithm.
        Dim compositeKey As String = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))
        Dim oauth_signature As String

        Dim hasher As HMACSHA1 = New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
        Using hasher
            oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
        End Using

        'The oAuth signature is then used to generate the Authentication header.
        'This requires concatenating the public keys and the token generated above into the following format
        Dim headerFormat As String = "OAuth oauth_nonce=""{0}"", oauth_signature_method=""{1}"", " & _
                                       "oauth_timestamp=""{2}"", oauth_consumer_key=""{3}"", " & _
                                       "oauth_token=""{4}"", oauth_signature=""{5}"", " & _
                                       "oauth_version=""{6}"""
        Dim authHeader As String = String.Format(headerFormat, _
                                                Uri.EscapeDataString(oauth_nonce), _
                                                Uri.EscapeDataString(oauth_signature_method), _
                                                Uri.EscapeDataString(oauth_timestamp), _
                                                Uri.EscapeDataString(oauth_consumer_key), _
                                                Uri.EscapeDataString(oauth_token), _
                                                Uri.EscapeDataString(oauth_signature), _
                                                Uri.EscapeDataString(oauth_version))

        'We are now ready to send the request, which is the easy part.
        'Note, we must also disable the Expect: 100-Continue header using the ServicePointManager.
        'Without this code, .NET sends the header by default, which is not supported by Twitter
        Dim req As WebRequest
        Dim res As HttpWebResponse
        Dim streamReader As StreamReader
        Dim wait As Integer = 250
        Dim jsonRes As String = ""
        Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")

        ServicePointManager.Expect100Continue = False
        req = WebRequest.Create(stream_url)
        req.Headers.Add("Authorization", authHeader)

        res = DirectCast(req.GetResponse(), HttpWebResponse)
        streamReader = New StreamReader(res.GetResponseStream(), encode)
        While True
            jsonRes = streamReader.ReadLine()

            'Success
            wait = 250
        End While

        'Abort is needed or responseStream.Close() will hang
        req.Abort()
        streamReader.Close()
        streamReader = Nothing
        res.Close()
        res = Nothing

In this line: res = DirectCast(req.GetResponse(), HttpWebResponse) I get a 401 - Unauthorized, I guess the problem might be in the line where I prepare the OAuth signature, the original used POST and I will need GET, so I changed it and tried these 3 alternatives:
        'baseString = String.Concat("GET&", Uri.EscapeDataString(stream_url), "&", Uri.EscapeDataString(baseString))
        'baseString = String.Concat(Uri.EscapeDataString(stream_url), "&", Uri.EscapeDataString(baseString))
        baseString = Uri.EscapeDataString(stream_url)

Can you help me getting Twitter OAuth working in VB.NET?
For the moment, Twitterizer is not an option as it only works with Visual Studio 2010, and TwitterVB2.dll only works with REST API, not streaming API, I don't know if there are other
third party libraries but at this point I would prefer to solve in my own code (too many unmaintaned and incomplete libraries out there).
Thank you

A: Solved, actually the signature was generating ok so the error was somewhere in the method procesing the request, here is my final code, as I mentioned it is based in this C# one:
    Dim resource_url As String
    resource_url = "https://userstream.twitter.com/2/user.json"

    '==========================
    'OBTENCION DEL TOKEN Y SIGNATURE OAUTH

    Dim oauth_version As String = "1.0"
    Dim oauth_signature_method As String = "HMAC-SHA1"
    Dim oauth_nonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))

    Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
    Dim oauth_timestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()

    Dim oauth_signature As String = GeneraOAuthSignature(resource_url, _
                                                          oauth_nonce, _
                                                          oauth_signature_method, _
                                                          oauth_timestamp, _
                                                          oauth_version)
    '==========================
    'FORMATEO DEL ENCABEZADO OAUTH
    Dim headerFormat As String = "OAuth oauth_nonce=""{0}"", oauth_signature_method=""{1}"", oauth_timestamp=""{2}"", oauth_consumer_key=""{3}"", oauth_token=""{4}"", oauth_signature=""{5}"", oauth_version=""{6}"""

    Dim authHeader As String = String.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_consumer_key), _
                Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version))

    '==========================
    'LLAMADA HTTP
    ServicePointManager.Expect100Continue = False

    Dim req As WebRequest
    Dim res As HttpWebResponse
    Dim streamReader As StreamReader
    Dim contenidoRespuesta As String = ""
    Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")

    req = WebRequest.Create(resource_url)
    req.Timeout = -1
    req.Headers.Add("Authorization", authHeader)

    res = DirectCast(req.GetResponse(), HttpWebResponse)

    '==========================
    'PROCESAR RESPUESTA
    streamReader = New StreamReader(res.GetResponseStream(), encode)
    While True
        contenidoRespuesta = streamReader.ReadLine()

    End While

    '==========================
    'CIERRE DE STREAMS Y COMUNICACIONES
    'Abort is needed or streamReader.Close() will hang
    req.Abort()
    streamReader.Close()
    streamReader = Nothing
    res.Close()
    res = Nothing

Where:
Function GeneraOAuthSignature(ByVal stream_url As String, _
                              ByVal oauth_nonce As String, _
                              ByVal oauth_signature_method As String, _
                              ByVal oauth_timestamp As String, _
                              ByVal oauth_version As String) As String
    'The next step is to generate an encrypted oAuth signature which Twitter will use to validate the request.
    'To do this, all of the request data is concatenated into a particular format as follows
    Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" & _
                     "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}"

    Dim baseString As String = String.Format(baseFormat, _
                    oauth_consumer_key, _
                    oauth_nonce, _
                    oauth_signature_method, _
                    oauth_timestamp, _
                    oauth_token, _
                    oauth_version)

    baseString = String.Concat("GET&", Uri.EscapeDataString(stream_url), "&", Uri.EscapeDataString(baseString))

    'Using this base string, we then encrypt the data using a composite of the secret keys and the HMAC-SHA1 algorithm.
    Dim compositeKey As String = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))
    Dim oauth_signature As String

    Dim hasher As HMACSHA1 = New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
    Using hasher
        oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
    End Using

    Return oauth_signature
End Function