text:
Q: Normal $T\in B(H)$ has a nontrivial invariant subspace I am wondering if the following is true:

Every normal $T\in B(H)$ has a nontrivial invariant subspace if $\dim(H)>1$?

A: Let $ T \in B(\mathcal{H}) $ be a normal operator. Let $ \sigma(T) $ denote the spectrum of $ T $. We then have two cases to consider: (i) $ \sigma(T) $ is a singleton set, and (ii) $ \sigma(T) $ contains at least two points.

Case (i): Suppose that $ \sigma(T) = \{ \lambda \} $ for some $ \lambda \in \mathbb{C} $. Let $ \text{id}_{\lambda} $ and $ 1_{\lambda} $ denote, respectively, the identity function on $ \{ \lambda \} $ and the constant function on $ \{ \lambda \} $ with value $ 1 $. By the Continuous Functional Calculus, we can apply these two functions to $ T $. As $ \text{id}_{\lambda} = \lambda \cdot 1_{\lambda} $, we obtain $ T = \lambda I $, where $ I: \mathcal{H} \to \mathcal{H} $ is the identity operator. Clearly, $ I $ has non-trivial subspaces (this is only true if we assume that $ \dim(\mathcal{H}) > 1 $), so $ T $ has non-trivial subspaces as well.

Case (ii): Suppose that $ \sigma(T) $ contains two distinct points $ \lambda_{1} $ and $ \lambda_{2} $ (note that this is not possible if $ \dim(\mathcal{H}) = 1 $). Let $ U_{1} $ and $ U_{2} $ be disjoint open neighborhoods (contained in $ \sigma(T) $) of $ \lambda_{1} $ and $ \lambda_{2} $ respectively. If $ \mathbf{E} $ denotes the resolution of the identity corresponding to $ T $, then we have non-zero projection operators $ P_{1} := \mathbf{E}(U_{1}) $ and $ P_{2} := \mathbf{E}(U_{2}) $ satisfying the following two properties:

*

*$ P_{1} P_{2} = \mathbf{0}_{B(\mathcal{H})} = P_{2} P_{1} $ and

*$ T P_{1} = P_{1} T $ and $ T P_{2} = P_{2} T $, i.e., $ P_{1} $ and $ P_{2} $ commute with $ T $.
Property (1) says that $ P_{1} $ is not the identity operator; otherwise $ P_{1} P_{2} = P_{2} \neq \mathbf{0}_{B(\mathcal{H})} $, which is a contradiction. Next, Property (2) says
$$
T[{P_{1}}[\mathcal{H}]] = {P_{1}}[T[\mathcal{H}]] \subseteq {P_{1}}[\mathcal{H}],
$$
which shows that $ {P_{1}}[\mathcal{H}] $ is a non-trivial invariant subspace of $ T $.

Conclusion: Every normal operator $ T \in B(\mathcal{H}) $ has a non-trivial invariant subspace if $ \dim(\mathcal{H}) > 1 $.


text:
Q: Determinant of $U$, Determinant of $U^T$ Given an $n\times n$ matrix $U$ such that $U^TU = I_n$, the $n\times n$ identity matrix.
Then what are the possible values of the determinant of $U$?

A: I am writing the answer through an ordinary mobile. So please excuse me with the proper formatting. . . Determinant of the product $AB$ is equal to the product of the determinants of $A$ and $B$. Also determinant of the transpose is same as determinant of the matrix. So the answer is $\pm 1$

A: $U^T\cdot U=I_n$ means your matrix is an orthogonal matrix (http://en.wikipedia.org/wiki/Orthogonal_matrix)
Hence it's determinant is $\pm 1$ :

proof :
$\det (U)²=\det (U)\det (U^T)$ because $\det (U)=\det(U^T)$
Therefore $\det (U)^2=\det(U^T\cdot U)=\det (I_n)=1$

redpajama_set_name: RedPajamaStackExchange


text:
Q: ARM ASM + array I need help to write ARM assembly language routines to initialize an array X of size N with a constant value V, using two different approaches: indices, pointers
I have no idea how to do this in asm.
Thanks
jj

A: The simplest (not fastest) way to implement your function in ARM assembly language:
 .global foo
@
@ call from C as void foo(uint32 *array, uint32 size, uint32 value);
@
@ standard calling convention:
@ Values passed in register R0=*array, R1=size, R2=value
@
foo:
  str r2,[r0],#4   @ Store the value and increment the pointer
  subs r1,r1,#1    @ decrement the count
  bne foo          @ branch until the count is 0
  bx lr            @ return to caller

A: Just like in C for example you can have a pointer that you basically destroy by changing it
*ptr;
...
ptr++;

And you can use an array with an offset
data[x];
...
x++;

Arm provides a couple of addressing modes for that one is a register with an immediate offset (which you can have zero as an offset)
ldr r0,[r1]

The offset of zero is implied
ldr r0,[r1,#0]

You dont have to type it if you dont want to the assembler will encode it that way though.
Then you modify r1 (in this case) to move through memory (through the array).
The other addressing mode is a register offset
ldr r0,[r1,r2]

Where you can have one of the two registers be the base of the array and the other the index that moves through it.
Look these up in the arm docs and figure out how to use them properly to complete your homework.
Register indirect addressing for load and store is extremely common in instruction sets, not just ARM.  Having an immediate offset to it is as well.  Two register is also common, perhaps not as common though.  These tie directly in to the pointer and array programming models in higher level languages.


text:
Q: Set TrustManager for Tomcat connector programmatically Weeks before my project uses 1.4.0.M3 version of Spring Boot, which uses tomcat-embedded-core-8.0.33.
Here I was able to create multi-connector with following code:
@Bean
EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    tomcat.addAdditionalTomcatConnectors(createStandardConnector());
    return tomcat;
}

private Connector createStandardConnector() {
    Connector connector = new Connector(Http11Nio2Protocol.class.getCanonicalName());
    connector.setPort(expiredCertPort);
    connector.setScheme("https");
    connector.setSecure(true);
    Http11Nio2Protocol protocolHandler = (Http11Nio2Protocol) connector.getProtocolHandler();

    protocolHandler.setSSLEnabled(true);
    protocolHandler.getEndpoint().setTrustManagerClassName(TimelessTrustManager.class.getCanonicalName());
    return connector;
}

The problem is that as of version 1.4.0.RELEASE Spring Boot uses 8.5.* Tomcat, where .getEndpoint() method is declared as protected.
How to programmatically install TrustManager for particular connector or protocol handler?

A: .setTrustManagerClassName(string)


text:
Q: Silverlight/RIA Services and ASP .NET MVC/WebAPI I did some research around but I have some doubts still about following topic...
I have Silverlight/RIA Services project that needs to have ASP.NET MVC look as well as WebAPI for some different clients.
So my question is following

Can we use somehow RIA Services with ASP.NET MVC 5?
And if not what is a painless way to represent all existing logic in ASP.NET MVC?

Thank you!

A: Ria services have nothing to do with look and feel.
A Silverlight app or a non plugin, which uses RIA services can be hosted in a web page created using ASP.Net.

Can we use somehow RIA Services with ASP.NET MVC 5?

Yes.
RIA services which could be used by an asp.net backend would not gain the benefit of RIA services because changes made in the backend end are not generated forward to an application such as a Silverlight plugin. It just becomes another way of accessing data.


text:
Q: What is the cleanest way of running multiple variable=function() and knowing when they are all complete I have multiple variables that need calculating before being saved as as JSON file, these are calculated with a function. However when running asynchronously they come up as undefined. I read up on promises and seems like this may be the way, but it seems a bit silly running 15 promises, so I thought I'd ask if there is a cleaner way of doing this. Here's a portion of the code

var sql = "Select a.Volume, a.LastPrice, a.buyers, a.id From (Select Volume, LastPrice, buyers, id FROM "+ marketname +" ORDER BY id DESC LIMIT 1440) a order by a.id asc";
          db.query(sql, function (err, result, fields) {
          if (err) throw err;
          result.forEach(function(element){
            results = result.length;
            tempArrayVol.push(element.Volume);
            tempArrayPrice.push(element.LastPrice);
            tempArrayBuyers.push(element.buyers);
            counter++;
            console.log(results + " " + counter);
          });

         var volumeaverage = (( tempArrayVol.reduce(function(acc, val) { return acc + val; }) )  / tempArrayVol.length);
         var buyersaverage = ((( tempArrayBuyers.reduce(function(acc, val) { return acc + val; }) ) / tempArrayBuyers.length ) * 100);

         var price24h    = change(prevDay, tempArrayPrice[tempArrayPrice.length -1]);
          //etc

So once all variables are defined, the JSON file should be written, should I chain promises or is there a better way?

A: Promises:
Promise.all([
  function1(),
  function2(),
  function3(),
]).then(([res1, res2, res3]) => doSomething(res1,res2,res3));

async/await:
async function() {
  const res1 = await func1();
  const res2 = await func2();
  const res3 = await func3();
  // do your thing
}


text:
Q: Why is the definition of prime numbers written to include 2 This question is often asked as "why is 2 a prime number" and the only answers I can find are "The definition of prime numbers is written in such a way that 2 is prime". Sometimes, if the question was "Why is 2 a prime number even though it's even" the answer will include some explanation that being even is not such a special property, it just means a number is divisible by two and of course two is divisible by two, that's the number itself and three is divisible by three and it's still prime and so on.
But there is something special about a number being even, and it 2 does have a special property that is not shared by any other prime number. It can be divided into equal subsets.
The answer I'm looking for will answer the question in the title and also answer: If we change the definition of a prime number, what effects does that have on mathematics theories, proofs, etc. Are certain claims that were useful and important under the old definition no longer true?
Specifically, What's the impact of changing the definition of prime to this: A prime is any integer that cannot be divided into smaller equal groups. N.B. this also changes the primeness of 1 but not any other number.

A: $2$ is considered a prime because most of the time that turns out to be convenient. $1$ is not considered a prime for the same reason.
That being said, $2$ is definitely the oddest prime.

A: You may wish to read the 2012 Journal of Integer Sequences article What is the Smallest Prime?, by Chris K. Caldwell and Yeng Xiong. The abstract starts with

What is the first prime? It seems that the number two should be the obvious answer, and today it is, but it was not always so. There were times when and mathematicians for whom the numbers one and three were acceptable answers.

Also, as already basically stated in the comments and other answers, the Introduction says

... whether or not a number (especially unity) is a prime is a matter of definition, so a matter of choice, context and tradition, not a matter of proof. Yet definitions are not made at random; these choices are bound by our usage of mathematics and, especially in this case, by our notation.

I enjoyed reading this article & found it educational. The only thing I have to add to this article & what's already been stated here is that I also believe it's generally good to question things instead of just accepting the status quo because "that's the way it is". During my years tutoring math at university, I had a philosophy of "there's no such thing as a stupid question, only a stupid answer". What I mean is that if the person has made a reasonable effort to resolve it on their own and the question is sincere, it's deserving of a reasonable answer.

A: We define things in such a way that they have some practical use, and help us make sense of the world around us. This is exactly how words and concepts are created, and also evolve. For example, we decided to give a name to a class of objects in the sky with similar behavior: 'planets'. These objects form what a philosopher might call a 'natural' class of objects. Having labels for them allows us to talk and think about those objects more easily, helping us with explanations, predictions, doing science, and again making sense of things in general.
But like I said, definitions can evolve: Pluto is no longer considered a 'planet', because after finding out more about our solar system we realized Pluto is in significant ways different from Neptune, Jupiter, Earth, etc. That is, by putting Pluto into different (though still related) class of 'dwarf-planets', we now look at it a little differently.
The same holds for mathematical definitions. For example, we could define 'huppelflup numbers' to be exactly those numbers that can be divided by 17 or by 631 ... but there just isn't much practical use to such a definition, and so we don't.
But the way we define prime numbers has lots of practical uses.  For example, with the current definition, we get the nice, clean, result that every number has a unique prime factorization. And it's not just applications within mathematics that matter: prime numbers have tremendous importance for real life as well.
Now, if we were to exclude $2$ as a prime, this would no longer be true.  And a bunch of other results would likewise have to be stated in a much more cumbersome way.
And by the way, this unique prime factorization theorem is exactly why mathematicians did exclude $1$ as a prime .. even though originally it was.
So yes, you're right that it is not as if definitions are fixed until the end of time.  And maybe at some point in the future we redefine the sets of primes again to also exclude $2$, because doing so will have some other advantages.
However, I wouldn't hold my breadth: the current definition is very nice.

A: An addendum to the other answers:
The number $2$ is actually so special that it often is exluded from consideration. The set of primes with $2$ excluded is often referred to as the set of odd primes.
Imprecisely: We are "lucky" enough that we can describe this set using other accepted terms and expressions, otherwise we might have come up with a new name for this set.
Examples:
"Law of quadratic reciprocity — Let p and q be distinct odd prime numbers" - from Wikipedia page on Quadratic Reciprocity
"If a, b, c is a non-trivial solution to $x^p + y^p = z^p , p$ odd prime, then $y^2 = x(x − ap)(x + bp)$ (Frey curve) will be an elliptic curve" - from Wikipedia page on Fermat's last theorem.
"Let the characteristic of K be different from 2." - from Wikipedia page on Quadratic forms.

A: Concepts which use prime numbers as objects for study and consideration are learned at a much earlier stage, in acquiring mathematical maturity, than sets.  I don't think you mean "group" in the way that word is used in mathematics, but even in the way you do use, it's less useful than the indivisibility definition.
Plainly, there are many primitive concepts for which the decomposition of numbers into products of indivisible factors is telling something about their properties.
And there is the principle that definitions of terms are considered good if the theorems which can be phrased and proven using those terms are as simply-stated as possible.

A: Can you clarify what definition of the prime number you are using? The one I know is

a natural number that is divisible only by itself and 1

Or a variation of it. Number 2 expressly satisfies the rule and does not require any "special" ruling to be included.


text:
Q: Can the day of the month be encoded similarily to other cyclical variables? I am working with time-series data in Python to see if variables like the time of day and the day of the month and the month of the year affect attendance at a gym. I have read up on encoding the time series data cyclicly using sine and cosine. I was wondering if you can do the same thing for the day of the month. The reason I ask is that, unlike the number of months in a year or the number of days in a week, the number of days in a month is variable (for example, February has 28, whereas March has 31). Is there any way to deal with that?
Here is a link describing what I mean by cyclic encoding: https://ianlondon.github.io/blog/encoding-cyclical-features-24hour-time/
Essentially, what this is saying is that you can't just convert the hour into a series of values like 1, 2, 3, ..., 24 when you are doing machine learning because that implies that the 24th hour is further away (from a euclidean geometric perspective) from the 1st hour than the 1st hour is from the 2nd hour, which is not true. Cyclical encoding (assigning sine and cosine values to each hour) allows you to represent the fact that the 24th hour and the 2nd hour are equidistant from the 1st hour.
My question is that I do not know if this cyclical conversion will work for days in a month, seeing as different months can have different numbers of days.

A: You can implement this by dividing each month into 2π radians; then in a 28-day month, a day is 0.2234 while in a 31-day month, a day is 0.2026.
This obviously introduces a skew where a shorter month will appear to take up as much time as a longer one; but it will satisfy your requirement. If you only use this metric for normalizing a single feature, that should be inconsequential, and let you achieve the stated goal.
If you have points in time with a finer granularity than a day, you obviously can and probably should normalize those into the same projection.


text:
Q: Where to fetchRecords in React - componentDidMount or onComponentDidUpdate or else where? I am attempting to get some records, from my redux store in a component. However, I am only trying to fetch records that belong to the currently logged-in user, which I get access to through my mapStateToProps function. -- ie, I am calling fetchRuns(userId)
I can't seem to figure out how or where to make this call. If I make the call in componentDidMount, userId is still null at this point. If I make the call in componentDidUpdate, I get an infinite loop, because my component updates when it returns. From my research, it sounds like I might need to keep track of another piece of state in componentDidUpdate that lets me know if I should make the call... I haven't been able to figure out how to do that.
My code
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { fetchRuns } from "../actions";
import RunCell from "./RunCell";

class Runs extends React.Component {
  componentDidUpdate() {
    // TODO: BUG - go to run , refresh, hit cancel, all other runs are missing
    this.props.fetchRuns(this.props.userId);
  }

  renderRuns() {
    //Show runs in reverse chronological order
    const sortedRuns = this.props.runs.sort(
      (a, b) => new Date(b.runDate) - new Date(a.runDate)
    );

    return sortedRuns.map((run) => {
      return <RunCell {...run} key={run.id} />;
    });
  }

  render() {
    if (this.props.runs) {
      return (

Your Training Log

              <Link className="ui button right" to="/runs/add">
                Add Run
              </Link>

{this.renderRuns()}

      );
    } else {
      return
Loading runs...
;
    }
  }
}

function mapStateToProps(state) {
  return { runs: Object.values(state.runs), userId: state.auth.userId };
}

export default connect(mapStateToProps, { fetchRuns })(Runs);

A: You are close to the solution, you just need to compare the new userId prop with the old one to prevent the infinite loop:
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { fetchRuns } from "../actions";
import RunCell from "./RunCell";

class Runs extends React.Component {
  componentDidUpdate(prevProps) {
    if(prevProps.userId !== this.props.userId){ // <=== In order to prevent infinite loop add this comparison
       this.props.fetchRuns(this.props.userId);
    }
  }

  componentDidMount() {
    if(this.props.userId){ // <=== fetch your data inside this methode
      this.props.fetchRuns(this.props.userId);
   }
  }

  renderRuns() {
    //Show runs in reverse chronological order
    const sortedRuns = this.props.runs.sort(
      (a, b) => new Date(b.runDate) - new Date(a.runDate)
    );

    return sortedRuns.map((run) => {
      return <RunCell {...run} key={run.id} />;
    });
  }

  render() {
    if (this.props.runs) {
      return (

Your Training Log

              <Link className="ui button right" to="/runs/add">
                Add Run
              </Link>

{this.renderRuns()}

      );
    } else {
      return
Loading runs...
;
    }
  }
}

function mapStateToProps(state) {
  return { runs: Object.values(state.runs), userId: state.auth.userId };
}

function mapDispatchToProps(dispatch) {
  return {
    fetchRuns: (userId) => dispatch(fetchRuns(userId))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Runs);


text:
Q: efficient method of downloading webpage info Before you stop reading and suggest HTML Agility (based on the title), I am already using this tool. The problem is this: I have have a webpage that lists a whole bunch of case numbers and has links to the individual case number page. My app already downloads this info and displays it in a datagridview. However in my app I also need information from the individual case number pages (the links).
The problem is I already know it's going to take forever to acquire using HTML agility. To get the case page, it takes about 2 minutes. Code wise I'm feeding HTML agility the HTML code, adding the cell values to an array and parsing out the array indexes I to display in my grid. This is a very large array parse for the number of components on the page.
Any ideas to acquire the main page and specific cells from the linked pages?

A: An example showing how you can use XPath in HmtlAgility

HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(yourHtml);
Example 1 : //The below example will get all div's with class as container foreach (HtmlNode node in
  doc.DocumentNode.SelectNodes("//div[@class='container']")) {
  Console.Writeline(node.InnerText); }
Example 2 : //The below example will get first div with class as container HtmlNode node in
  doc.DocumentNode.SelectNodes("//div[@class='container'][1]"))
Console.Writeline(node.InnerText);

You can use Xpath Queries to get the element(s) you want
for XPath syntax and more please use the link http://www.w3schools.com/xpath/xpath_syntax.asp


text:
Q: Manipulating the HttpSession in a JSF ViewHandlerWrapper doesn't work In a ViewHandlerWrapper-implementation I have following code:
public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException, FacesException {
    final String token = UUID.randomUUID().toString();

    HttpSession httpSession = (HttpSession) context.getExternalContext().getSession(true);
    httpSession.setAttribute("expectedToken", token);

    getWrapped().renderView(context, viewToRender);
}

As you can see, I want to add a UUID to the Session. Following the debugger I can see that the attribute stays on the Session until the entire request-response cycle of the servlet container is complete. However, at the next invocation the "expectedToken" attribute is null.
Before going "old school" (fetching the HttpSession) I tried to manipulate a value object on the session, which rendered the same result. The change was dismissed.
Is this not supposed to work (after all, the response is not committed when renderView is invoked)?

A: Try getting the session without recreation
HttpSession httpSession = (HttpSession) context.getExternalContext().getSession(false);

A: Rather use the JSF-provided ExternalContext#getSessionMap(). This is in turn transparently backed by the HTTP session.
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.getSessionMap().put("key", "value");

A hint for the future, whenever you need to haul the raw Servlet API from under the JSF hoods, ask yourself twice: Am I doing it the right way? Isn't there a JSF-ish way? In almost all cases there is. If in vain, just ask here :)


text:
Q: DataTables: Filter on custom data attribute I want to filter a DataTable by selecting a filter from a select-input.
<select class="form-control filter-table" data-column="language">
  <option selected>Alle Sprachen</option>
  <option value="GER">Deutsch</option>
  <option value="ENG">Englisch</option>
</select>

That's how my table is designed:

  Hello	  Englisch

  Hello	  German

Here's my event handler:
$('.filter-table').change(function (e) {
    var column = $(this).data('column');
    var filter = $(this).val();
});

I already searched quite a while but did not find an answer

A: I am assuming that you are using DataTables Jquery Plugin.
<select id="dropdown1" class="form-control filter-table" data-column="language">
<option selected>Alle Sprachen</option>
<option value="GER">Deutsch</option>
<option value="ENG">Englisch</option>
</select>

            Greeting
            Language

Hello	  Englisch

Hello	  German

Javascript:
$(document).ready(function() {
   var table =  $('#example').DataTable();

 $('#dropdown1').on('change', function () {
     if(this.value=="Alle Sprachen")
      {
      table.columns(1).search('').draw();
      }
      else
      {
      table.columns(1).search( this.value ).draw();
      }
   } );

});

Working Fiddle: https://jsfiddle.net/an5kbx0z/

A: If you happen to look for generic jQuery solution, you might check out this one:

 //populate options
 $('#lang').append([...$('#mytable tr td:nth-of-type(2)')].sort().reduce((options, option) => options+=`<option value="${$(option).text()}">${$(option).text()}</option>`,'<option value="All" selected>All</option>'));

  //grab table data
 const tableDataObj = {};
 tableDataObj.data = [...$('#mytable tbody tr')].map(row => {
  const rowObj = {};
  [...$(row).children('td')].forEach((cell, index) => rowObj[$(`#mytable thead th:eq(${index})`).text()] = $(cell).text());
  return rowObj;
 });
 tableDataObj.header = [];
 tableDataObj.data.map(row => Object.keys(row)).flat().forEach(entry => {
  if(tableDataObj.header.indexOf(entry) == -1) tableDataObj.header.push(entry);
 });

  //draw table upon selection
 $('#lang').on('change', function() {
  const filteredData = JSON.parse(JSON.stringify(tableDataObj));
  filteredData.data = filteredData.data.filter(entry => entry.Language == $(this).val() || $(this).val() == 'All');
  $('#mytable').html('

');
  $('#mytable').append('

'+filteredData.header.reduce((thead, th) => thead+=`<th>${th}</th>`,''));
  $('#mytable').append(`<tbody>${Object.values(filteredData.data).reduce((rows, row) => rows+='<tr>'+Object.values(row).reduce((tds, td) => tds += '<td>'+td+'</td>','')+'</tr>','')}</tbody>`);
 });
<!doctype html>

  <link rel="stylesheet" type="text/css" href="test.css">

   <select id="lang"></select>

      Greeting	Language

      Hello	English

      Hallo	Deutsch

      Selam	Turkce

      Salut	Francais

      Ciao	Italiano

It is not that elegant and scalable, however, delivers general idea.
If you were requesting for DataTables solution, I may recommend this plug-in. With it you don't need to use extra drop-downs - it is neat and simple, even though in its early release, fulfills your requirement perfectly. With that approach, you may get multiple select filters in addition to basic DataTables sorting, pagination/scrolling. Here is the DEMO.


text:
Q: How come the .NET framework 3.5 offline installer is 200 MBs larger than the .NET 4 offline installer? I have code/support an application built on .NET framework that has always run on .NET 2.  This year we are upgrading the application to use .NET 3.5 (or 4?).
In preparing for this change we noticed that that Offline Installer (required for our customer base) for .NET 3.5 is 200+ MBs bigger than the .NET 4 offline installer.
Here are my questions.
Why is the dotnet 3.5 installer so much bigger than the 4 offline installer?
Can we TARGET .NET 3.5 but distribute .NET 4.  In other words, is .NET 4 backwards compatible?  Assuming that .NET 4 was the only installed .NET could application still target earlier frameworks?
IF our application is compiled for x86 CPU (rather than Any CPU) do you still have to distribute the x64/x86 Client Profile or can we just distribute the x86 Client Profile?  In other words, can we distribute the x86 Client Profile even though it will be installed on x64 machines if our app is compiled for x86 target CPU?  Any risks or gotchas for doing this?
The issue is that if we upgrade our app to target .NET 4 there are a lot of application servers that we also have to upgrade which effects a number of other applications.  Any thoughts?
Seth

A: .NET 3.5 is fully backward compatible with .NET 3.0 and .NET 2.0 - it thus includes all of those two previous versions as well. .NET 4.0, on the other hand, starts from scratch, and can discard deprecated/unnecessary code. This also means that .NET 4.0 cannot necessarily run .NET 3.5 code unchanged - there's another SO answer on some of the breaking changes there.

A: It is because of the prerequisites.  The .NET 4.0 installer requires the target machine to be updated to

*

*XP SP3

*Vista SP1

*Server 2003 SP2

*Server 2008 or Win7

The 3.5 SP1 installer is much more lenient, it can even run on the original version of XP.  To make that work, it needs to include updates of many of the core Windows components.  A significant chunk of that 231 MB installer are not actually .NET components.
Also notable is that in .NET 4.0, the difference between the client profile and the full version has largely disappeared.  The full version is only 15% bigger, there isn't much point in targeting the client profile.


text:
Q: jQuery Mobile / Hammer.js working in iOS Safari, broken when launched from home screen This is less of a code question and more of a library support question. (I know, I know... SO is for code debugging!)
I am using Hammer.js within a jQuery Mobile web app. I have written some gesture handling code that enables users to pinch-to-zoom and swipe-to-scroll just one <div> in my project, while maintaining user-scalable=no viewport. After days of writing and debugging, it's working for me. It works and I have tested in Safari and Chrome on iOS 7, and in Safari on iOS 6. It's working on iPad and iPhone.
That is, until I "Save to Home Screen". Once I do this, and I launch from the icon on my home screen, my swipe-to-scroll functionality is lost. Pinch-to-zoom is still working.
Any idea what might cause working code in Safari to break once launched from inside a "Home Screen" icon web app ?
See for yourself at http://omdapp.devstage.co/ (open in mobile browser, and then use "Add to Home Screen" and try when launched from home screen)
Things I've tried:

*

*Adding "?v=1" to the JS includes

*Changing JS filenames altogether

*Clearing Safari history/cookies/data

*Debug to make sure no JS errors thrown

*Remove and re-add the Home Screen icon

Note: I do not have Mac OS, so I cannot test using Web Inspector.


text:
Q: I get this error: TypeError: Cannot read properties of undefined (reading 'members') whenever I execute command const levels = require('discord-xp')
const { MessageEmbed } = require('discord.js')
const client = require('../../index')

module.exports = {
  name: "edit",
  description: "Edits a users level or xp",
  usage: ".edit <user> [xp / level] [add / set / remove] <number>",
  developersOnly: true,

  run: async (message, args, client) => {
    const usage = ".edit <user> [xp / level] [add / set / remove] <number>"
    if (!args[0]) return message.channel.send(`> You need to state more arguments \`${usage}\``)
    if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
    if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
    const mentionedMember = message.mentions.members.first()
    if (!['xp', 'level'].includes(args[1])) return message.channel.send(`> You did not specify if you are changing level or xp: \`${usage}\``)
    if (args[1] === "xp") {
      if (!['add', 'set', 'remove'].includes(args[2])) return message.channel.send(`You did not state if you're adding, setting, or removing`)
      const value = Number(args[3]);
      let levelUser = await Levels.fetch(mentionedMember.user.id, message.guild.id)
      if (!levelUser) return message.channel.send('> That person isnt in the database yet.')
      if (args[2] === 'add') {
        if (!value) return message.channel.send('> That is not a valid number')
        try {
          await Levels.appendXp(mentionedMember.user.id, message.guild.id, value)
          message.channel.send(`> Added \`${value}\` xp to ${mentionedMember}`)
        } catch (err) {
          console.log(err)
        }
      } else if (args[2] === 'remove') {
        if (!value) return message.channel.send('> That is not a valid number')
        try {
          await Levels.subtractXp(mentionedMember.user.id, message.guild.id, value)
          message.channel.send(`> Removed \`${value}\` xp to ${mentionedMember}`)
        } catch (err) {
          console.log(err)
        }

      } else if (args[2] === 'set') {
        if (!value) return message.channel.send('> That is not a valid number')
        try {
          await Levels.setXp(mentionedMember.user.id, message.guild.id, value)
          message.channel.send(`> Set ${mentionedMember}'s xp to \`${value}\``)
        } catch (err) {
          console.log(err)
        }

      }
    } else if (args[1] === 'level') {
      if (!['add', 'set', 'remove'].includes(args[2])) return message.channel.send(`You did not state if you're adding, setting, or removing`)
      const value = Number(args[3]);
      let levelUser = await Levels.fetch(mentionedMember.user.id, message.guild.id)
      if (!levelUser) return message.channel.send('> That person isnt in the database yet.')
      if (args[2] === 'add') {
        if (!value) return message.channel.send('> That is not a valid number')
        try {
          await Levels.appendLevel(mentionedMember.user.id, message.guild.id, value)
          message.channel.send(`> Added \`${value}\` level(s) to ${mentionedMember}`)
        } catch (err) {
          console.log(err)
        }
      } else if (args[2] === 'remove') {
        if (!value) return message.channel.send('> That is not a valid number')
        try {
          await Levels.subtractLevel(mentionedMember.user.id, message.guild.id, value)
          message.channel.send(`> Removed \`${value}\` level(s) to ${mentionedMember}`)
        } catch (err) {
          console.log(err)
        }

      } else if (args[2] === 'set') {
        if (!value) return message.channel.send('> That is not a valid number')
        try {
          await Levels.setLevel(mentionedMember.user.id, message.guild.id, value)
          message.channel.send(`> Set ${mentionedMember}'s level to \`${value}\``)
        } catch (err) {
          console.log(err)
        }

      }
    }
  }
}

This is supposed to be a level and xp edit command for my bots leveling system
i tested it on my self first but it didnt seem to work and i dont think theres any errors in my code. It send this super long error:
TypeError: Cannot read properties of undefined (reading 'members')
    at Object.run (/home/runner/sung-jin-woo/commands/leveling/edit.js:13:46)
    at Client.<anonymous> (/home/runner/sung-jin-woo/events/guild/messageCreate.js:124:18)
    at Client.emit (node:events:402:35)
    at MessageCreateAction.handle (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/actions/MessageCreate.js:25:14)
    at Object.module.exports [as MESSAGE_CREATE] (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketManager.js:350:31)
    at WebSocketShard.onPacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:443:22)
    at WebSocketShard.onMessage (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:300:10)
    at WebSocket.onMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/event-target.js:199:18)
    at WebSocket.emit (node:events:390:28)
    at Receiver.receiverOnMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/websocket.js:1022:20)
    at Receiver.emit (node:events:390:28)
    at Receiver.dataMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:522:14)
    at Receiver.getData (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:440:17)
    at Receiver.startLoop (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:148:22)
    at Receiver._write (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:83:10) Promise {
  <rejected> TypeError: Cannot read properties of undefined (reading 'members')
      at Object.run (/home/runner/sung-jin-woo/commands/leveling/edit.js:13:46)
      at Client.<anonymous> (/home/runner/sung-jin-woo/events/guild/messageCreate.js:124:18)
      at Client.emit (node:events:402:35)
      at MessageCreateAction.handle (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/actions/MessageCreate.js:25:14)
      at Object.module.exports [as MESSAGE_CREATE] (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
      at WebSocketManager.handlePacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketManager.js:350:31)
      at WebSocketShard.onPacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:443:22)
      at WebSocketShard.onMessage (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:300:10)
      at WebSocket.onMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/event-target.js:199:18)
      at WebSocket.emit (node:events:390:28)
      at Receiver.receiverOnMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/websocket.js:1022:20)
      at Receiver.emit (node:events:390:28)
      at Receiver.dataMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:522:14)
      at Receiver.getData (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:440:17)
      at Receiver.startLoop (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:148:22)
      at Receiver._write (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:83:10)
}

so like can someone help me?
(if you need any more info about code say it in comment ill reply with the info there)

A: Whenever you see this error, check the line 'reading members'(in your case). That simply means you are doing a key access where keyname is 'members' and object inside which this key 'members' is present is undefined. For example X.members where X is undefined.So check in your code why this 'X'(imaginary name given for the sake of answer could be any name that you only know) is undefined or what could make that 'X' undefined. And after finding that you should put a check before doing the access i.e something like below to avoid these run time errors:
if(X) then X.members

OR
X?.members

Looking at your code the error is coming from here :
const mentionedMember = message.mentions.members.first()

Keep this line in correct place i.e all your access to mentionedMember should occur after this line and then change above line to :
const mentionedMember = message.mentions?.members.first() provided members has first() method. If you are not sure then you can do like this also const mentionedMember = message.?mentions?.members?.first()
There is one more way which is not cleaner but it's fine:
let mentionedMember;
if(message && message.mentions && message.mentions.members) {
 mentionedMember = message.mentions.members.first()
}

A: In this line code:
 if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
 if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
 const mentionedMember = message.mentions.members.first()

Try to arrange this like:
 const mentionedMember = message.mentions.members.first()
 if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
 if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)

In line:
if (!mentionedMember) return message.channel.send('> Mention a valid user / member.'); you already calling the mentionedMember which is its not readable.
Let me know if the error still there after you rearrange your code


text:
Q: Network shared folder access across nodes in azure service fabric cluster I have a service fabric cluster on Azure with 5 nodes. For testing, I have not configured any firewalls. I need to share a folder from one node such that it can be accessible by Network Service account from other node.
Though I set share permissions to network service, I always get access denied. However the local user account on the other node is able to access the shared folder


text:
Q: R * not meaningful for factors ERROR I have the following data.frame and I want to perform some calculations on the 2nd column.
> test
  code age
1  101  15
2  102  25
3  103  16
4  104  u1
5  105  u1
6  106  u2
7  107  27
8  108  27

As you can see, the 2nd column does not include only numbers. I omitted these cases:
> new<-subset(test,code<104 | code>106)
> new
  code age
1  101  15
2  102  25
3  103  16
7  107  27
8  108  27

But when I try to do a calculation in a new column this is what I get:
> new["MY_NEW_COLUMN"] <- NA
> new
  code age MY_NEW_COLUMN
1  101  15            NA
2  102  25            NA
3  103  16            NA
7  107  27            NA
8  108  27            NA
> new$MY_NEW_COLUMN <-new[,2] * 5
Warning message:
In Ops.factor(new[, 2], 5) : * not meaningful for factors

Why does that happen? Any suggestions?

A: new[,2] is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5


text:
Q: How is the time complexity of building k-d tree O(nlog^2n) when O(nlog(n)) median search is used? The time complexity of building a k-d tree using O(nlogn) meidan search is given as O(nlog^2n) in wikipedia. Can anybody explain how it is O(nlog^2n)?

A: When constructing a kdtree with a median search you get a balanced binary tree. A balanced binary tree has height O(log(n)). You search for the median(s) at every layer of this tree when constructing it. So if this search takes O(n * log(n)), you get: log(n) * n * log(n) = n * log(n)^2.


text:
Q: Python dict from mobypos.txt file I have a file from the Moby Project that pairs words with one or more letters indicating their part of speech. For example:
hemoglobin\N
hemogram\N
hemoid\A
hemolysin\N
hemolysis\N
hemolytic\A
hemophile\NA
hemophiliac\N

Hemoglobin is a noun, hemoid is an adjective, and hemophile can be used as a noun or an adjective.
I have created a dict from this file that pairs a word with the letters indicating its part of speech using the following code:
mm = open("mobypos.txt").readlines()
pairs = []
for x in mm:
    pairs.append(x.split("\\"))
posdict = dict(pairs)

This works successfully. What I want to do is generate lists called nouns, verbs, adjectives, etc that contain all the words of this part of speech. What is the fastest way to do this, given that len(posdict.keys()) returns 233340

A: You can use a generator expression to get an iterator of relative words :
nouns = (w for w,type in posdict.iteritems() if type=='N')

But note that since iterators are one shot iterables , when you just want to iterate over them and don't want to get the specific items or use some functions like len its better to use them, which are very optimized in terms of memory use. but if you want to use them a lot of times you better to use a list comprehension.
nouns = [w for w,type in posdict.iteritems() if type=='N']

A: You can use list comprehension
nouns = [word, type in posdict.iteritems() if 'N' in type]

adjs = [word, type in posdict.iteritems() if 'A' in type]

verbs = [word, type in posdict.iteritems() if 'V' in type]

The use of the in operator in the if clause will place words with multiple types accordingly.


text:
Q: Why does (x IS NULL != y IS NULL) require extra brackets in MySQL? I have a MySQL table whose fields come in groups, the rule being that only one group is in use per row, and all (and only) that group's fields are non-null.
To be explicit, let's look at some of these fields
x_encrypted
x_hashed
y_encrypted
y_hashed

I have a trigger which signals failure if you insert a bad record. One of the checks is this
IF (x_encrypted IS NULL != x_hashed IS NULL) ... error

i.e. either x is both encrypted and hashed, or it is not present.
This triggers an error in the case that both x_encrypted IS NULL AND x_hashed IS NULL. The fix is to rewrite it like this, with extra brackets:
IF ((x_encrypted IS NULL) != (x_hashed IS NULL)) ... error

Why are these extra brackets needed? I can't see how this would be syntactically ambiguous. I'm concerned that there's a gotcha lying in wait for me, I have similar NULL-related checks elsewhere that I no longer trust.

A: According to documentation, IS and != have same precedence. Also:

For operators that occur at the same precedence level within an expression, evaluation proceeds left to right, with the exception that assignments evaluate right to left.

That means, that this expression:
x_encrypted IS NULL != x_hashed IS NULL

will be evaluated as:
((x_encrypted IS NULL) != x_hashed) IS NULL

So that, you have to use explicit parenthesis to override default order of evaluation.


text:
Q: When should I stop playing this dice game? The rules are as follows:
You start with \$1 and roll a six-sided die. If you roll anything but a 1, you double your money (so \$2 for the first roll, $4 for the second, and so on). If you roll a 1, you lose all your money. What is the optimal number of times you should roll the die to make the most money?
My initial theory:
The probability of rolling 2-6 consecutively $n$ times is $(\frac{5}{6})^n$; and the probability of rolling a 1 is just $\frac{1}{6}$. So, the expected value is going to be:
$$
E = (\frac{5}{6})^n2^n-\frac{1}{6}2^n \\
=2^n(\frac{5}{6}^n-\frac{1}{6})
$$
Now, if I solve for $n_{L}$ where $E=0$:
$$
0=2^{n_{L}}(\frac{5}{6}^{n_{L}}-\frac{1}{6}) \\
\frac{1}{6}=\frac{5}{6}^{n_{L}} \\
n_{L}=log_{5/6}\frac{1}{6}\\
\approx9.8
$$
Which means I should roll around 9 times to maximize my profit (or maybe 10 if I'm feeling lucky).
However, I tried running a quick simulation and got $n_{L}=5.01 \pm 0.05$ after 10,000 games.
Where did I go wrong? Thank you!
For reference:

import random
import numpy as np

def dice():
    return random.randint(1,6)

ns=np.array([])
for i in range(10000):
    n=0
    while dice() != 1:
        n+=1
    ns=np.append(ns,[n])
print(np.average(ns))
print(np.std(ns)/100)

Output

5.0093
0.05511008393207182

Edit:
Here's a more accurate simulation that reflects Ross Millikan's answer for my own reference.
import random
import numpy as np

def dice():
    return random.randint(1,6)

trials=np.array([[]])
for i in range(30):
    moneys=np.array([])
    for j in range(100):
        money=1
        numrolls=0
        while numrolls <= i:
            numrolls+=1
            if dice() != 1:
                money=2*money
            else:
                money=0
                break
        moneys = np.append(moneys,[money])
    print("i: "+str(i))
    trial = np.array([i,np.average(moneys)])
    print("money: "+str(np.average(moneys)))
    trials = np.append(trials,trial)

Output
i: 0
money: 1.74
i: 1
money: 2.48
i: 2
money: 4.88
i: 3
money: 6.56
i: 4
money: 14.08
i: 5
money: 28.8
i: 6
money: 32.0
i: 7
money: 40.96
i: 8
money: 81.92
i: 9
money: 112.64
i: 10
money: 245.76
i: 11
money: 737.28
i: 12
money: 1146.88
i: 13
money: 327.68
i: 14
money: 2293.76
i: 15
money: 3276.8
i: 16
money: 6553.6
i: 17
money: 13107.2
i: 18
money: 26214.4
i: 19
money: 52428.8
i: 20
money: 20971.52
i: 21
money: 0.0
i: 22
money: 83886.08
i: 23
money: 335544.32
i: 24
money: 335544.32
i: 25
money: 671088.64
i: 26
money: 1342177.28
i: 27
money: 8053063.68
i: 28
money: 0.0
i: 29
money: 0.0

A: Your calculation is incorrect because $2^{n}\cdot \left(\frac 56 \right)^n$ is the expected profit of rolling $n$ times and quitting.  You should not subtract the $\frac 162^{n}$ because the loss of that is already reflected.
Planning to roll $n+1$ times is always better than planning to roll $n$ times.  If you plan to roll $n$ times your expected return is $2^{n}\cdot \left(\frac 56 \right)^n=\left(\frac 53 \right)^n$.  Each additional roll increases your expected return by a factor $\frac 53$ so you should never quit.  The mathematical problem with this is that the expected value does not converge, so it is not defined.  The psychological problem with this is that eventually you will roll a $1$ and get nothing.  This is a variant on the Saint Petersburg paradox.
Simulation is a poor approach for problems like this.  If you only try $10000$ or even $10^{100}$ times you will miss the rare event that you avoid rolling $1$ for an enormous time and win huge (assuming you stop).

A: Your code is calculating the average number of rolls where you successfully cash out but it doesn't account for the fact that the prize doubles at each step. The expected value does and so taking more risks for the much larger reward is optimal at each step.


text:
Q: Save map in raster format from QGIS using compression Is there a method to save a map in raster format from QGIS using compression?
For exemple from "Export map" in ArcGIS there are many options to compress the images depending on the file type (tiff, jpg, etc.).
I need to export/save a raster from a vector data (shape), and specifically I need to export an atlas.

A: I would not normally jump in when a question has effectively been answered in the comments but it seems some confusion has crept in.
If you want to export your raster as is but with compression there are lots of ways of doing it but Project->Save as Image is NOT one of them.  This takes a georeferenced snapshot of the current data view, which can be useful but is not what you want (based on the question title).  It will save as JPEG, which is a compressed format, but there is no control over the level of compression.  Likewise you can save a map from the composer as a JPEG, but, apart from resolution, there is no control over the compression level.
To compress a raster, you can tell QGIS to use compression in almost any of dialogs generating raster outputs. The "Save as" option mentioned in Chris W's comment is one such.  Right-click on the raster layer to get a pop-up menu.  The Save as dialog looks as follows:

You can find similar creation options in many raster-related dialog boxes (e.g. Raster->Conversion->Translate which would be another route to do this same thing).  Have a look here for some of the other creation options you can specify.  Note, QGIS should detect the current extent and resolution etc of your raster automatically, so you can just leave those options alone (unless you want to also change the file size by down-sampling the data of course).
Even where you don't have a handy button for a function like compression, if you see a little yellow pencil icon next to the box showing the GDAL commandline, then you can edit the command and (where GDAL allows it) add creation options with the -co flag.  Below is an example of editing the GDAL commandline to include compression for Raster->Projection->Warp. You will need to look up the documentation on what these are in each case but for look here for gdalwarp.  There are loads of other options besides the -co flag and getting to know the GDAL commands will make QGIS dialogs even more powerful because editing the commandline in this way gives you a lot of extra functionality and control beyond the standard default options available in the dialog box.


text:
Q: How do you record from two USB microphones using PyAudio? My application requires recording from two microphones at different locations simultaneously, and then doing FFT on the two streams of data to obtain a result. I was not able to find how to do this using PyAudio. Here is a code for recording from one source:
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 2

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

stream.stop_stream()
stream.close()
p.terminate()

Do I have to create two streams? And even if I code it right, are there hardware (sound card) limitations for this that I need to look into? Thanks

A: When using two independent audio devices, they will each have their own clock, and will drift from each other over time.
If you need to record from multiple microphones, you'll want to attach them to the same audio interface.  (Or, synchronize the two audio interfaces via their word clock, or by physically modifying them if no word clock I/O is available.)

A: to record from 2 Mics at once, you'll need to use a threaded based solution
simply assign each mic to his own thread, and you can work parallel
please note that stream starting time will differ, without a sampler it will be hard to sync them on the MS level.


text:
Q: Deploy Angular App with Spring Boot (on AWS) I have an angular app running on localhost at port 4200 and spring boot on port 808.
I want to deploy the Angular & Spring Boot Applications, but for me it is not clear what best practices are. I wanted to deploy the Angular application in AWS S3 and package the Spring application in a Docker container. Then I wanted to configure a proxy in Angular.
Now I have read an article that says that this method is not suitable for production.
Why is it not suitable for production and what are the better alternatives?
Many Thanks!

A: I think you are almost there. You are quite right. You can deploy the frontend angular app dist folder to S3 as a static website, then deploying your backend spring-boot app on docker is perfect. This can run on elastic beanstalk, ec2, ECS, and now even lambda.
You will need environment variables for the backend and frontend code, so they know how to communicate with each other, i.e., https://my_S3_URL_angular_site.com/ for your S3 bucket and https://my_EC2_URL_springboot_server.com/, but you do not need to use any proxies.


text:
Q: MutationObserver on nodelist I have some html with four section:

Inside of this section there is a div.button class, when the user clicks on it, the section gets expanded, covering the entire page (all the element inside become visible), and receives the class 'is-expanded'
Now i set a MutationObserver on those nodes (with class 'section'):
utilities.js
class Observer{
  constructor(targetClass,buttonHandler){
    this.targetClass = targetClass;
  }
  initObserver(){
    let self = this;
    const observer = new MutationObserver(function(mutations){
        mutations.forEach(function(mutation){
          if(mutation.target.classList.contains(self.targetClass)){
          let menuButton = Array.from(mutation.target.children).find(function(el){
            return el.classList.contains('menu-heading')
          })
          self.buttonHandler.disable(menuButton)
          console.log(menuButton)
      }
      else if(!mutation.target.classList.contains(self.targetClass)){
        let menuButton = Array.from(mutation.target.children).find(function(el){
          return el.classList.contains('menu-heading')
        })
        self.buttonHandler.enable(menuButton)

      }
        })
      }
      return observer
  }
}

main.js
    const observer = new utilities.Observer(expandedClass).initObserver()
const sections = Array.from(document.querySelectorAll('.section'));

document.addEventListener('DOMContentLoaded',function(){
  sections.forEach(function(section){
    observer.observe(section,{attributes:true})
  })
})

I'm new to mutation observe api, could be this a good use of it? even in terms of performance (instead of use addEventListener on click etc)
thanks
EDIT
I update the code, for now what i want is that if section has the class expanded, the children button (with class .menu-heading) get the css style pointerEvents set to none, to auto if not has the target class. the enable function from buttonhandler class do the job


text:
Q: How to reduce the time of STOP-THE-WORLD in Java GC We know that in Java a full GC can hang the JVM, which can also be called STOP-THE-WORLD. In many applications, hanging the JVM too long will cause a lot of problems. I want to know how to reduce the time of STOP-THE-WORLD in GC? What are the potential drawbacks caused by reducing the time of STOP-THE-WORLD? (not considering the JVM without stop-the-world behavior)

A: There are many approaches

*

*Create less garbage. A memory profiler will help.

*Use less heap.  A profiler can help reduce memory used.

*Use off heap memory instead.  There are number of libraries to store data off heap. e.g. Chronicle.

*Use more memory and GCs will happen less often, possibly be less serious when they do.  If you are using less than 32 GB of heap, this might be a quick win.

*Use a fully concurrent collector like Azul's Zing. It doesn't have a STW collector.

I would start with the memory profiler to reduce garbage and heap usage, and tune the GC.

A: If your objects live long time you can try to use DirectBuffers from New I/O package. Their creation and reclamation is more expensive than the creation and reclamation of heap-based non-direct buffers because direct buffers are managed using OS-specific native code. This added management cost makes direct buffers a poor choice for single-use or infrequently used cases.
Direct buffers are also outside the scope of Java's garbage collector.


text:
Q: android videoview error 1, -2147483648 I am getting error while playing video from asset folder and raw folder.
MediaPlayer error (1, -2147483648)
VideoView error 1, -2147483648.
I tried from asset folder as.
private String SrcPath = "file:///android_asset/aaa.mp4"; //also tried aaaa.mp3
VideoView vv = (VideoView)findViewById(R.id.videoView1);
vv.setVideoPath(SrcPath);
MediaController controller = new MediaController(this);
controller.setAnchorView(vv);
vv.setMediaController(controller);
vv.requestFocus();
vv.start();

and for raw folder i used URI as :
Uri video = Uri.parse("android.resource://com.usecontentprovider/raw/aaa.mp4");
vv.setVideoURI(video);

I got the same error message in both cases.

A: You can use software like avinaptic2 to get the video encoding information and make sure it matches the supported media formats in android.
A common problem I find is that videos are encoded with the wrong profiling. H.264 videos need to be encoded with Baseline level 3 or under to be played without errors or artifacts in Android.

A: I  found the solution as I am able to play video on virtual device.
I replaced the line
Uri video = Uri.parse("android.resource://com.usecontentprovider/raw/aaa.mp4");

with
Uri video = Uri.parse("android.resource://com.usecontentprovider/raw/"+R.raw.aaa);

And its working

A: Using R.raw works fine but in some cases I still get the same error. Fortunately I found the solution to my problem: I had to call videoView.start() inside onPrepare().
You can check the correct answer here:
Android: 'Can't play this video'; MediaPlayer & VideoView Error 1 -38


text:
Q: Why im not getting the response back from this factory function in angularJS I got this angular factory:
var productApp = angular.module('productApp', ['ngRoute', 'LocalStorageModule', 'angularSlideables', 'ui.bootstrap']);

productApp.factory('productFactory', function($http, localStorageService, $q) {
    var factory = {};

    factory.getProductById = function(prod_id) {
        if(prod_id !== '') {
            $http({
                url: 'rest/message/getProductById/' + prod_id,
                method: 'GET'
            }).success(function(data, status) {
                return data;
            }).error(function(data, status){
                // do nothing
            });
        }else {
            alert("There was an error while passing the ID. Please refresh the page and try again");
        }
    }

    return factory;
});

Injecting the factory in a controller and calling to the "getProductById" function:

productApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, productFactory, prodId) {
  console.log("this is the prod id " + prodId);
  // search product in the database
  $scope.prod = productFactory.getProductById(prodId);
  console.log($scope.prod);
  $scope.ok = function () {
      console.log($scope.prodData);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

Now, don't know what's wrong with it... the function RETURNS the data because i did a console.log(data) and saw all the response, but in the controller if i inspect the $scope.prod, it's undefined. It's not returning the data back from the function.
(Just in case you guys ask, the "prodId" in the controller parameter is fine, and retrieving that from another controller)
How can i solve this? :(
Thanks in advance.

A: Here's what I do.  I'm using $resournce instead of $http, but it should be enough to get you going.  You may even want to use the $resource since it has the built in fns.
My factory:
.factory('WorkOrder', function($resource){

    // $resource Usage: $resource(url[, paramDefaults][, actions]);
    return $resource('/controller/get/:id.json', {}, {
        /*
         * By default, the following actions are returned; modify or add as needed
         * { 'get':    {method:'GET'},
         *   'save':   {method:'POST'},
         *   'query':  {method:'GET', isArray:true},
         *   'delete': {method:'DELETE'} };
         */
    });

})

My controller:
    // get the work order data using the work order id from the tag attribute
var getWO = function() {

    WorkOrder.get({woId:$attrs.id},

        // success callback
        function(response) {
            // Assign the work order data to the scope
            $scope.WorkOrder            = response.WorkOrder;
        },

        // fail callback
        function(response) {
            // whatever...
        }
    );
};
getWO();

I put my success and fail fns in my controller because that's where I most likely know how I want to respond to success or failed calls.  I also assign the function to a variable and then call it right after in case I want to include the fn call inside a $timeout or call it elsewhere.
Hope this answers your question.

A: The pattern I have used to solve this problem is to pass in the success & error callback functions to the factory... like this:
var productApp = angular.module('productApp', ['ngRoute', 'LocalStorageModule', 'angularSlideables', 'ui.bootstrap']);

productApp.factory('productFactory', function($http, localStorageService, $q) {
    var factory = {};

    factory.getProductById = function(prod_id, successCallback, errorCallback) {
        if(prod_id !== '') {
            $http({
                url: 'rest/message/getProductById/' + prod_id,
                method: 'GET'
            })
            .success(successCallback)
            .error(errroCallback);
        } else {
            alert("There was an error while passing the ID. Please refresh the page and try again");
        }
    }

    return factory;
});

and then:
productApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, productFactory, prodId) {
  console.log("this is the prod id " + prodId);
  // search product in the database
  productFactory.getProductById(prodId, function successCallback(data) {
         $scope.prod = data;
      }, function errorCallback(data, status) {
         alert("An error occurred retrieving product. Please refresh the page & try again.");
      });
  console.log($scope.prod);

  $scope.ok = function () {
      console.log($scope.prodData);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

By doing it this way instead, you have access to the scope in the controller & can do whatever you need to with the returned data.


text:
Q: Difference between rect_size and rect_min_size in godots control nodes I am trying to understand the control nodes in Godot and i have one incredibly annoying problem. I do not entirely understand the relationship between the rect_size and rect_min_size. When i try to organize my ui elements they keep changing their values and thereby moving to places i do not want them to be.
What is the relationship between these two variables and how can i solve the problem that they keep changing?

A: rect_min_size is the minimum size that the control's rect can be sized. In other words, the control should never get smaller than rect_min_size.
rect_size is the actual size of the control's rect.
I recommend looking into Containers and a control's size flags. HBoxContainer and VBoxContainer's are great tools for laying out a responsive UI.
Another tip: When you are frequently changing the UI with multiple levels deep of Controls use find_node() rather than get_node(). This way you don't have to keep updating the paths after moving around the Control nodes.
Example:
onready var status_label: Label = find_node('status_label') as Label

Hope this helps.


text:
Q: Why I'm getting null or index out of bound? In this case animators contains 3 items.
But let' say I don't know how many items there is. Could be 3 or 30.
I can get the "medea_m_arrebola" index fine but how do I get the rest indexs ?
I tried on this line also 2 and now 1 : But getting exception IndexOutOfRangeException: Index was outside the bounds of the array.
soldiers_indexs = new int[1];

And if not using this line I'm getting null on the line :
soldiers_indexs[i] = i;

How can I get the rest items indexs ?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OpenningScene : MonoBehaviour
{
    [Header("Animators")]
    public Animator[] animators;
    [Space(5)]
    [Header("Movement Settings")]
    public Transform target;
    public float movingSpeed = 1f;
    public bool slowDown = false;
    [Space(5)]
    [Header("Rotation Settings")]
    public float rotationSpeed;
    public DepthOfField dephOfField;
    public float waitingAnimation;
    public float startConversation;

    private Vector3 targetCenter;
    private bool startWaitingAnim = true;
    private bool endRot = false;
    private int medea_m_arrebola_index;
    private int[] soldiers_indexs;

    // Use this for initialization
    void Start()
    {
        targetCenter = target.GetComponent<Renderer>().bounds.center;
        soldiers_indexs = new int[1];
        for (int i = 0; i < animators.Length; i++)
        {
            animators[i].SetFloat("Walking Speed", movingSpeed);

            if(animators[i].name == "medea_m_arrebola")
            {
                medea_m_arrebola_index = i;
            }
            else
            {
                soldiers_indexs[i] = i;
            }
        }
    }

A: Because C# is not Javascript.
Your code with soldiers_indexs[i] = i; would work perfectly in Javascript, even if the end result is hard to understand. However, an array in C-type languages is a defined data structure with lower and upper bounds. C# does not allow you to do things that appear to make no sense.
As it's not clear from your code what you are attempting to do, I can't advise a forward path. However, it is clear that using the index variable i to refer to a place on an array that you are not iterating is a mistake.
Generally, in C#, we use more general-purpose data structures such as a List<T>. In addition, I do not recommend for loops. A foreach loop nearly always makes more sense, and is always easier to read.


text:
Q: Does the sequence $x_{n+1}=x_n+x_n^2$ converge to $0$ whenever $-1\lt x_0\lt0$? My question concerns using the fixed-point iteration to find the fixed point of the function $f(x)=x+x^2=x(1+x)$ (this function has a single fixed point at $0$).
The problem
Given some fixed $x_0$, define the sequence $x_n$ by
$$\begin{align*}
x_{n+1}=x_n+x_n^2&&\text{for all $n\geq0$.}
\end{align*}$$
Does this sequence converge to $0$ for all $x_0$ in the range $-1\lt x_0\lt0$? After some computational numerical exploration, I think the answer might be yes but I'm not so sure how to prove this.
Some notes
The sequence trivially converges to $0$ when $x_0=-1$ or $x_0=0$. It's also fairly easy to prove that it does not converge to $0$ whenever $x_0$ lies outside this range (i.e., $x_0\lt-1$ or $x_0\gt0$).
I've already proved that for any $x_0$ in this range, all successive $x_n$s remain in this range (i.e., $-1\lt x_n\lt0$ for all $n\geq0$) and that the sequence increases / gets closer to $0$ (i.e., $x_{n+1}\gt x_n$), but is there any way to prove it actually converges to $0$?
Some examples
If, for example, $-\frac{1}{2}\lt x_n\lt-\frac{1}{4}$, we'll have $-\frac{3}{8}\lt x_{n+1}\lt-\frac{1}{8}$ and $-\frac{21}{64}\lt x_{n+2}\lt-\frac{5}{64}$, etc. So it seems as though the range of possible values gets closer to $0$. But, how would one prove this?

A: You can use the monotone convergence theorem. It tells us that a sequence $\{x_n\}_{n=1}^\infty\subseteq \mathbb R$ converges if it is bounded and decreasing. For you sequence we have $|x_{n+1}| = |x_n| |1+x_n| \leq 1$ since $x_0 \in (-1,0)$.  And likewise we have $x_{n+1} = x_n(1+x_n) \leq x_n$ as $1+x_n \in (0,1)$.
(You can use induction to prove both these claims.)
Now you have shown that $\lim_{n\to\infty} x_n=x$ exists. From this we see that
$$
x = \lim_{n\to\infty} x_{n+1} = \lim_{n\to\infty} x_n(1+x_n) = x(1+x).
$$
Hence $x$ satisfies $x = x^2+x$ so $x=0$.

A: The answer to your question (regarding convergence to $0$) is indeed affirmative and for a reason that is not too difficult to ascertain. For simplicity let us introduce the quadratic polynomial function:
\begin{align*}
f \colon \mathbb{R} &\to \mathbb{R} \\
f(x)&=x^2+x
\end{align*}
and let us note that $f[(-1, 0)] \subseteq (-1, 0)$, in other words the interval $(-1, 0)$ is stable under $f$. To prove this latter claim it suffices to notice that $x^2+x+1=\left(x+\frac{1}{2}\right)^2+\frac{3}{4} \geqslant \frac{3}{4}>0$ for any $x \in \mathbb{R}$ (and thus in particular $x^2+x>-1$ always) and respectively that given $x \in (-1, 0)$ we have $x+1>0$ yet $x<0$ which means that $x^2+x=x(x+1)<0$.
The immediate conclusion that we draw from this is that for any fixed $t \in (-1, 0)$, the unique recursive sequence $x \in \mathbb{R}^{\mathbb{N}}$ defined by $x_0=t$ and $x_{n+1}=f(x_n)$ for any $n \in \mathbb{N}$ has the property that actually $x \in (-1, 0)^{\mathbb{N}}$ and is thus a bounded sequence. Furthermore, since $x_{n+1}=x_n+x_n^2 \geqslant x_n$ takes place for every $n \in \mathbb{N}$ we gather that $x$ is increasing (one can actually make the more precise observation that since $x_n \neq 0$ for all $n \in \mathbb{N}$ under the stated conditions, the inequality mentioned above is actually strict, rendering $x$ into a strictly increasing sequence, however that is not essential for the study of convergence).
According to one of the theorems of Weierstrass, any upper-bounded increasing sequence of real numbers is convergent, which applies in particular to $x$. Since $x$ is defined recursively with respect to the continuous function $f$, it follows with necessity that $\displaystyle\lim_{n \to \infty} x_n$ must be a fixed point for $f$. However it is obvious that there is just one such fixed point - the unique solution to the equation $f(u)=u \Leftrightarrow u^2=0$ - which is $0$.


text:
Q: How to create and run ASM Dll in VS 2017 (WPF aplication)? I want to create an ASM DLL in Visual studio 2017 to use it (invoke the function write in asm) in existing c# project. The DLL will be using 64-bit code.
It will be very helpful if someone describes how to create this kind of DLL file and wrap it into a c# project to invoke a function.


text:
Q: FInd Out if User Switched off Document and Data From iCloud Account Once again stuck in iCloud :(. I am using Core Data + iCloud and in my app i want to know if user switched off Document and Data from his account.
Thanks

A: There is no built-in support for detecting this change, only for detecting if the user has logged out. One common approach is to write a sentinel file to iCloud, separately from Core Data, and then monitor that file to see if it disappears. Details vary but it's usually something like:

*

*Write the file using NSFileManager iCloud calls, and store the file name in user defaults. Each device using the account will have a different file, so including a UUID in the file name is a good idea. You only write this file, you never change it.

*Use either NSFilePresenter or NSMetadataQuery to get notified of changes to that file-- like, if it disappears.
If the file disappears, take immediate steps to unload the entire Core Data stack, including every managed object, because they don't have a persistent store backing them up any more.
One sample implementation is in Black Pixel's version of the Core Data "Recipes" demo app. You might need to tweak it to get it to work right in your code.

A: There are two cases:

*

*The app is not running, or in the background when the account status changes.

The solution here is to store / compare the identity token using NSUserDefaults (or some other storage local to the app). Grab the identity token from NSFileManager and compare it to the cached value each time the app finishes launching or comes back to the foreground.
id token = [[NSFileManager defaultManager] ubiquityIdentityToken];

*

*The app is running when the account changes.

This requires a file presenter to "something" inside the container. The best solution is to use a file that is not synced.
Implement -accommodatePresentedItemDeletionWithCompletionHandler: to spawn a thread (dispatch_async works great) and do your cleanup work.


text:
Q: How to read from a text file in MySQL using delimiter I know you can use the LOAD DATA command in MySQL to load data from a file into a database table, but that's using the default delimiters of whitespace.
I'm loading text from a file that contains words as well as punctuation. I need to load the words in the database but ignore any punctuation. In a language like C#, I would just specify a regular expression that only grabs alphanumeric characters and ignores other symbols.
Is there a way to do this in MySQL commands as well?

A: I think you would need to enclose your strings in quotes in the file and specify the
ENCLOSED BY '"'

optional parameter. For example your data would be
"xxx","Some text, and some more!", ...

I don't know of another way to do it in MySQL.
See the ENCLOSED BY section of this documentation: http://dev.mysql.com/doc/refman/5.1/en/load-data.html


text: Q: Shouldn't The Term Room-Temperature Superconductivity be Scrapped? There have been headlines claiming that the long-sought Room-Temperature Superconductivity has finally been achieved, and it is technically correct. But when this notion was first conjectured, there was no reason to expect that pressure would be relevant. So basically extremely-low temperature is being replaced by extremely-high pressure so isn't Room-Temperature Superconductivity intentionally misleading. Shouldn't we call it High Pressure Superconductivity. It seems very deceitful, because STP-Superconductivity has never been discovered, there is no proof that is it possible and STP-Superconductivity is was Room-Temperature Superconductivity was originally meant by. Right?


text:
Q: How can i add double ScrollView in XML? I am currently trying to add a double ScrollView inside my XML.
I am using two different views in my layout - a list and categories.
When a user clicks on a category - the list of videos will become visible and the categories will become invisible.
Currently, the category buttons are scroll-able and when I click a category button, the list of videos does become visible. However, the issue is that the list of videos do not scroll.
Here is my layout code:
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/tools"
        android:orientation="vertical"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <!--this is parent layout where I call ListView-->
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/parent01"
            android:descendantFocusability="beforeDescendants"
            android:fitsSystemWindows="true"
            android:focusableInTouchMode="true"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:orientation="vertical"
            android:weightSum="1">

        <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            <ListView
                    android:id="@+id/listview"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="5dp"
                    android:divider="@android:color/transparent"
                    android:dividerHeight="1dp"></ListView>

            <ProgressBar
                    android:id="@+id/nextProgress"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_gravity="center"
                    android:visibility="gone"
                    style="@android:style/Widget.DeviceDefault.Light.ProgressBar.Small"/>
        </RelativeLayout>
    </LinearLayout>

    <!--This is the categories layout-->
    <ScrollView
            android:layout_width="wrap_content"
            android:orientation="vertical"
            android:id="@+id/ll_buttons"
            android:layout_marginTop="60dp"
            android:layout_height="wrap_content">

        <LinearLayout
                android:layout_width="match_parent"
                android:orientation="horizontal"
                android:layout_height="200dp">

            <Button
                    android:layout_weight="0.5"
                    android:id="@+id/button1"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/rec_img"/>

            <Button
                    android:layout_weight="0.5"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/rec_img"
                    android:id="@+id/button2"/>
        </LinearLayout>

        <LinearLayout
                android:layout_width="match_parent"
                android:orientation="horizontal"
                android:layout_height="200dp">

            <Button
                    android:layout_weight="0.5"
                    android:id="@+id/button3"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/rec_img"/>

            <Button
                    android:layout_weight="0.5"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/rec_img"
                    android:id="@+id/button4"/>
        </LinearLayout>
    </ScrollView>
</RelativeLayout>

A: use nested scroll views
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

</android.support.v4.widget.NestedScrollView>

A: for nested scrolling better to use NestedScrollView

NestedScrollView as the name suggests is used when there is a need for a scrolling view inside another scrolling view.

ScrollView vs NestedScrollView

another thing use RecyclerView insted of Listview

RecyclerView vs. ListView
sample layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

 <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">

        // add here all your controlls

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

and dont forgot to set setNestedScrollingEnabled() property in RecyclerView like below code

If this property is set to true the view will be permitted to initiate nested scrolling operations with a compatible parent view in the current hierarchy. If this view does not implement nested scrolling this will have no effect. Disabling nested scrolling while a nested scroll is in progress has the effect of stopping the nested scroll.

mRecyclerView.setNestedScrollingEnabled(false);


text:
Q: 100% Disk Usage all the time - laptop keeps freezing whenever it spikes up I was wondering if anyone can help me? I'm very tempted to "restore to factory settings" and just completely restart everything...Will this work?
I have literally tried everything. From changing the power plan to deactivatingt some services. Nothing worked. I don't know if it is my actual hard drives fault? Or something I downloaded.
I also, started up Malwarebytes and it found nothing. Windows Defender came up with nothing as well. I Really want to just restore my laptop to factory settings.
My Disk Drive also spikes up to 100% whenever I come out of sleep mode. Currently I'm only able to use my laptop for about 5 minutes before the regular 5% Disk Space goes up to 100%.

A: One of the potential causes may be some type of malware that could be eating up your computer resources but it does not have to be the case, many badly designed drivers and programs can cause such behaviour as well.
To be absolutely sure the issue is caused or is not caused by malware I would advise to scan with few more programs such as SpyBot Search & Destroy and SUPERAntiMalware, I can only post two links in single answer but just type the names into Google and their websites should appear, they are both freeware programs.
If all these programs find nothing/do not fix the problem, download external Live CD/Rescue ISOs such as Kaspersky Rescue CD or Bitdefender Rescue CD, scans performed by those programs will take reasonably longer in comparison to anti-malware programs but they will be much more detailed and trustworthy.
You will find those programs are inside of ISO files - you will need program such as ISOtoUSB to burn them onto the USB and boot from BIOS level (alternatively you can burn them onto a CD but I do not recommend that).
Of course if you do not have enough time, restoring to factory settings should work as Windows will be restored from back-up partition in original, untouched state. Be sure to back-up your files such as photos and documents before performing it though as Windows may not copy all the files you would like to retain.


text:
Q: Python Tensorflow and OpenCV on Apple Silicon M1 I try to use OpenCV and Tensorflow with Python on Apple silicon M1.
I'm able to use Tensorflow, but install OpenCV in my environment fails
pip3 install opencv-python
Even build opencv-python by my own locally fails on numpy
git clone https://github.com/skvark/opencv-python.git
cd opencv-python
ENABLE_CONTRIB=0
ENABLE_HEADLESS=1
pip wheel . --verbose

with

ERROR: Command errored out with exit status 1:
/Users/hannes/git/city-simulator/tensorflow_venv2/bin/python3
/Users/hannes/git/city-simulator/tensorflow_venv2/lib/python3.8/site-packages/pip install --ignore-installed --no-user --prefix
/private/var/folders/np/7ckckk8s5fd169kvnnfhjkk40000gr/T/pip-build-env-3zg4n104/overlay
--no-warn-script-location -v --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel scikit-build cmake pip 'numpy==1.13.3; python_version=='"'"'3.6'"'"' and platform_machine !=
'"'"'aarch64'"'"'' 'numpy==1.19.3; python_version>='"'"'3.6'"'"' and
sys_platform == '"'"'linux'"'"' and platform_machine ==
'"'"'aarch64'"'"'' 'numpy==1.14.5; python_version=='"'"'3.7'"'"' and
platform_machine != '"'"'aarch64'"'"'' 'numpy==1.17.3;
python_version=='"'"'3.8'"'"' and platform_machine !=
'"'"'aarch64'"'"'' 'numpy==1.19.3; python_version>='"'"'3.9'"'"' and
platform_machine != '"'"'aarch64'"'"'' Check the logs for full command
output.

Even build numpy by my own fails
git clone git@github.com:numpy/numpy.git
cd numpy
OPENBLAS="$(brew --prefix openblas)" MACOSX_DEPLOYMENT_TARGET=11.1 python3 -m pip install cython --no-use-pep517
OPENBLAS="$(brew --prefix openblas)" MACOSX_DEPLOYMENT_TARGET=11.1 python3 -m pip install numpy --no-use-pep517
OPENBLAS="$(brew --prefix openblas)" MACOSX_DEPLOYMENT_TARGET=11.1 python3 -m pip install pandas --no-use-pep517
OPENBLAS="$(brew --prefix openblas)" MACOSX_DEPLOYMENT_TARGET=11.1 python3 -m pip install pybind11 --no-use-pep517
OPENBLAS="$(brew --prefix openblas)" MACOSX_DEPLOYMENT_TARGET=11.1 python3 -m pip install scipy --no-use-pep517
brew install libjpeg zlib
python3 -m pip install pillow
python3 -m pip install matplotlib
OPENBLAS="$(brew --prefix openblas)" MACOSX_DEPLOYMENT_TARGET=11.1 python3 -m pip install scikit-learn --no-use-pep517
OPENBLAS="$(brew --prefix openblas)" MACOSX_DEPLOYMENT_TARGET=11.1 python3 -m pip install statsmodels --no-use-pep517
cd ../opencv-python
pip wheel . --verbose
pip install numpy --no-index --find-links file:///Users/hannes/git/city-simulator/numpy/numpy

all without errors, bun on last I see this
Looking in links: file:///Users/hannes/git/city-simulator/numpy/numpy
Requirement already satisfied: numpy in /Users/hannes/git/city-simulator/tensorflow_venv2/lib/python3.8/site-packages (1.18.5)

and pip wheel . --verbose still runs into same error

A: I made it work with conda !
cd ~/Downloads
wget https://github.com/conda-forge/miniforge/releases/download/4.9.2-7/Mambaforge-4.9.2-7-MacOSX-arm64.sh
chmod +x Mambaforge-4.9.2-7-MacOSX-arm64.sh
./Mambaforge-4.9.2-7-MacOSX-arm64.sh
which python
file $(which python)
wget https://raw.githubusercontent.com/mwidjaja1/DSOnMacARM/main/environment.yml
conda env create --file=/Users/hannes/Downloads/environment.yml --name=condaVenv
conda activate condaVenv
pip3 install --upgrade --force --no-dependencies \
  https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_$(uname -m).whl \
  https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_$(uname -m).whl
python -c 'import tensorflow as tf; print(tf.__version__)'
conda install opencv
python -c 'import tensorflow as tf; import cv2; print(cv2.__version__); print(tf.__version__)'

shows now
4.5.1
2.4.0-rc0

ATTENTION during copy&paste this command !
When you copy it, you will see

Please remove \ after paste


text:
Q: Two way binding for Formik Field and custom component in React I am trying to pass my own functional component as a component attribute to a Formik Field in React. The problem is I don't know how to bind the Formik Field's value with the value in my custom component. Here's what I tried:
Form.js
// other Formik Form code...
<Field
    className="form-control"
    name="NetWeight"
    component={IntegerComponent}
></Field>
//...

IntegerComponent.js
function IntegerComponent({ field, className }) {
    const onChangeHandler = event => {
      const returnVal = (event.target.validity.valid) ? event.target.value : inputValue;
      setInputValue(returnVal);
    };

    return <input
      type="text"
      pattern="[0-9]*"
      className={className}
      onChange={onChangeHandler}
      value={inputValue}
    />
}

I want to bind Formik's field.value which I am destructuring from the props, to my NumberComponent's input's value. I tried doing field.value = returnVal but it didn't work as well. I know I can use onBlur and onChange handlers for above purpose than creating my functional component but the way my project is built, if I can make this work, it will help reducing a lot of redundant code. Any thoughts or suggestions?


text:
Q: Python - Open All Text Files in All Subdirectories Unless Text File Is In Specified Directory I have a directory (named "Top") that contains ten subdirectories (named "1", "2", ... "10"), and each of those subdirectories contains a large number of text files. I would like to be able to open all of the files in subdirectories 2-10 without opening the files in the subdirectory 1. (Then I will open files in subdirectories 1 and 3-10 without opening the files in the subdirectory 2, and so forth). Right now, I am attempting to read the files in subdirectories 2-10 without reading the files in subdirectory 1 by using the following code:
import os, fnmatch

def findfiles (path, filter):
    for root, dirs, files in os.walk(path):
        for file in fnmatch.filter(files, filter):
            yield os.path.join(root, file)

for textfile in findfiles(r'C:\\Top', '*.txt'):
    if textfile in findfiles(r'C:\\Top\\1', '*.txt'):
        pass
    else:
        filename = os.path.basename(textfile)
        print filename

The trouble is, the if statement here ("if textfile in findfiles [...]") does not allow me to exclude the files in subdirectory 1 from the textfile list. Do any of you happen to know how I might modify my code so as to only print the filenames of those files in subdirectories 2-10? I would be most grateful for any advice you can lend on this question.
EDIT:
In case others might find it helpful, I wanted to post the code I ultimately ended up using to solve this problem:
import os, fnmatch, glob

for file in glob.glob('C:\\Text\\Digital Humanities\\Packages and Tools\\Stanford Packages\\training-the-ner-tagger\\fixed\*\*'):
    if not file.startswith('C:\\Text\\Digital Humanities\\Packages and Tools\\Stanford Packages\\training-the-ner-tagger\\fixed\\1\\'):
        print file

A: Change your loop to this:
for textfile in findfiles(r'C:\\Top', '*.txt'):
    if not textfile.startswith(r'C:\\Top\\1'):
        filename = os.path.basename(textfile)
        print filename

A: The problem is as simple as that you are using extra \s in your constants.  Write instead:
for textfile in findfiles(r'C:\Top', '*.txt'):
    if textfile in findfiles(r'C:\Top\1', '*.txt'):
        pass
    else:
        filename = os.path.basename(textfile)
        print filename

The \\ would be correct if you hadn't used raw (r'') strings.
If the performance of this code is too bad, try:
exclude= findfiles(r'C:\Top\1', '*.txt')
for textfile in findfiles(r'C:\Top', '*.txt'):
    if textfile in exclude:
        pass
    else:
        filename = os.path.basename(textfile)
        print filename


text:
Q: Wildfly: how to resolve VFS URL to physical URL? How to resolve Wildfly vfs URL to physical URL? e.g.
vfs:/C:/wildfly-20.0.1.Final/bin/content/foo.ear/myejb.jar/

The java code must not have dependency on Wildfly or other libraries.


text:
Q: strace doesn't output as expected for 'ls' When I use strace with ls and save it using `-o' option, it's going to show output like the below:
➜  test strace -o st.out ls
st.out  test
➜  test

But my question is, how did this happen?
Because when you run strace, it's going to show system calls, but how will it be saved before the end of exited with 0?


text:
Q: AssemblyScript array access causing Memory Out of Bounds I am trying to access elements of an Array<u32> in AssemblyScript.
I initialize and fill my arrays as follows:
let totalSize: u32 = 512;

let leaderPtsX: u32[];
let leaderPtsY: u32[];
let leaderPtsType: u32[];

export function createPoints(): void {
  leaderPtsX = new Array<u32>();
  leaderPtsY = new Array<u32>();
  leaderPtsType = new Array<u32>();
  for (let i: u32 = 0; i < VP_COUNT; i++) {
    let x = <u32>(Math.random() * totalSize);
    let y = <u32>(Math.random() * totalSize);
    leaderPtsType.push(Math.random() > 0.5 ? 0xffffffff : 0xff00ff00);
    leaderPtsX.push(x);
    leaderPtsY.push(y);
  }
}

I have a function which needs to access the aforementioned arrays as so:
function getClosestNeighbourType(x: u32, y: u32): u32 {
  let minDistance = 5000;
  let minDistanceType = -1;
  for (let i = 0; i < VP_COUNT; i++) {
    let dist =
      Math.abs(x - unchecked(leaderPtsX[i])) +
      Math.abs(y - unchecked(leaderPtsY[i]));
    if (dist < minDistance) {
      minDistance = <u32>dist;
      minDistanceType = unchecked(leaderPtsType[i]);
    }
  }
  return <u32>minDistanceType;
}

But on compiling and running this in the browser i get the following console error:
array.ts:104 Uncaught RuntimeError: memory access out of bounds
    at ~lib/array/Array<u32>#__unchecked_get (wasm-function[29]:0x1b4a)
    at assembly/index/getClosestNeighbourType (wasm-function[30]:0x1b84)

I have tried lots of different methods and gone through a lot of documentation but no dice.
Any help or links appreciated.
Thanks!


text:
Q: post keeps data entity framework asp mvc In Httppost action method :
I have the following code:
    [ValidateAntiForgeryToken]
    [HttpPost]
    public async Task<ActionResult> StudentDetails(string id, string type)
    {
            Student model1 = await db.Student.Where(s => s.StudentGuid.ToString() == id).SingleOrDefaultAsync();

            model1.Type=type;//I didn't submit it yet to DB

            Student model2 = await db.Student.Where(s => s.StudentGuid.ToString() == id).SingleOrDefaultAsync();

            //at this point model2.Type took the same value of type without even setting it
    }

why model2 took the same values of model1 though I get model2 directly from database ??!!

A: It's because you're not loading it from the database really. The database context (db) has already retrieved that item from the database with the first call.
When you make the second call to get the entity, you're actually retrieving the instance that the context has previously created in memory, consequently, it includes the change you made to 'Type'.
If you want to get a 'clean' copy of the instance then I imagine there is a way to do it. Google something like 'get clean instance entity framework' and read through a few of the responses.
Edit: I would also strongly suggest reading up a little on EF as it seems like you have fundamental misconceptions about how it works.


text:
Q: C# converting to send a message from client to server i am currently trying to realize a communication between server and client.
I am already able to connect and disconnect to the server.
No i try to send actual data. Here is my problem ...
I created a method (in unity-c#) to send a message:
    public void SendServerMessage(message mes)
{
    if (connectedToServer)
    {
        try
        {
            // convert message into a byte array, wrap the message with framing
            Debug.Log("1");
            byte[] messageObject = ConversionTools.convertObjectToBytes(mes);
            Debug.Log("2");
            byte[] readyMessage = ConversionTools.wrapMessage(messageObject);
            Debug.Log("3");

            // send completed message
            cSock.Send(readyMessage);
        }
        catch
        {
            Debug.Log("There was an error sending server message " + mes.messageText);
        }
    }
}

--> I get the Debug.Log("1"); output but then i get the error message from the catch-block.
Here is the function :
        public static byte[] convertObjectToBytes(object o)
    {
        //used when sending our custom classes
        MemoryStream memStream = new MemoryStream();
        BinaryFormatter binForm = new BinaryFormatter();
        binForm.Serialize(memStream, o);
        return memStream.ToArray();
    }

message is a class i created that looks like this:
    [Serializable]
public class message
{
    //used to communicate between Server and Client
    public string messageText;
    private List<scObject> scObjects = new List<scObject>();
    public int messageID;
    [...]

It is able to manipulate the object by adding strings etc.
I really hope you guys can help me with this issue :(
I actually created this with the help of a tutorial and in the tutorial from 2012 the code works. I googled and tried a lot but i dont know how to fix it.