text:
Q: scala lower bound type "with" another type? Here is the code
class Result[A] {
    def map[B](f: (Result[A] => Result[B]), xResult: Result[A]) = {
      xResult match {
        case Success(x)    => Success(f(xResult))
        case Failure(errs) => Failure(errs)
      }
    }

    def apply[B](fResult: Result[A], xResult: Result[B]) = {
      (fResult, xResult) match {
        case (Success(f), Success(x))        => Success((f, x))
        case (Failure(errs), Success(a))     => Failure(errs)
        case (Success(a), Failure(errs))     => Failure(errs)
        case (Failure(errs), Failure(errs2)) => Failure(List(errs, errs2))
      }
    }
  }

  case class Success[A](a: A) extends Result[A] {}

  case class Failure[A](a: A) extends Result[A] {}

  def createCustomerId(id: Int) = {
    if (id > 0)
      Success(id)
    else
      Failure("CustomerId must be positive")
  }

Here are the questions
1) result from type inference from method createCustomer is like this
Product with Serializable with Result[_ >: Int with String]

I dont have trouble with the "Product with Serializable" stuff, the thing im wondering is how to do something meaningfull with the result, and just out of curiosity how to initialize a type like that.
suppose i have another method as shown below
def createCustomer(customerId: Result[_ >: Int with String], email: Result[String]) = {
    how can i read/do something with "customerId" argument
  }

how to initialize a type like that
val x: Result[Int with String] = ???

notes:

*

*i know my Result class doesnt have any generic "getter"

*I know that perhaps things could be easier in method "createCustomerId" if when id > 0 i returned Success(id.ToString), but i really want to know whats going on with this lower type and how i could take advantage (if possible) in the future

A: The problem is that your type definition states that both Success and Failure take the same argument type. However, you actually want to put some other type of argument into Failure while still keeping covariance. Here is the simplest fix:
class Result[A] {

  def map[B](f: (Result[A] => Result[B]), xResult: Result[A]) = {
    xResult match {
      case Success(x) => Success(f(xResult))
      case Failure(errs) => Failure(errs)
    }
  }

  def apply[B](fResult: Result[A], xResult: Result[B]) = {
    (fResult, xResult) match {
      case (Success(f), Success(x)) => Success((f, x))
      case (Failure(errs), Success(a)) => Failure(errs)
      case (Success(a), Failure(errs)) => Failure(errs)
      case (Failure(errs), Failure(errs2)) => Failure(List(errs, errs2))
    }
  }
}

case class Success[A](a: A) extends Result[A] {}

case class Failure[A, B](a: B) extends Result[A] {}

object TestResult extends App {

  def createCustomerId(id: Int): Result[Int] = {
    if (id > 0)
      Success(id)
    else
      Failure("CustomerId must be positive")
  }

  println(createCustomerId(0))
  println(createCustomerId(1))
}

prints:
Failure(CustomerId must be positive)
Success(1)

If you don't annotate return type for createCustomerId with Result[Int] compiler will infer Result[_ <: Int] with Product with Serializable which is probably not ideal but not too bad.


text:
Q: Troubles removing ignore tags from Stack Overflow This may be a stupid question on my part and/or possibly a duplicate, but I'm having problems deleting ignored tags from Stack Overflow.
When I hover over them, I don't see any "X" to delete the tag nor does the description box popup like it used to. Also, the ignored tags are not ignoring any questions anymore.
If it helps, I have nearly 200 to 300 ignore tags selected atm.

A: It works fine for me.
Did you deactivate JavaScript?
Try to clear your cache and cookies eventually to begin with a fresh state.
Try also another browser to check if it is really a global problem or just on one browser.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to push array into Anypoint Monitoring custom metrics? I need to push an JSON array information into custom dashboard table.
[
 {
 api_name: "abc_api",
  owner: "avish"
},
{
api_name: "xyz_api",
owner: "avesh"
},
etc...
]

I need to push the info into a table with 2 column like API_NAME and API_OWNER.
Please let me know if this can be possible with 'anypoint custom metric' connector or do we have any option in mulesoft ?

A: Values for measurements have to be numerical. It doesn't seem that the data that you want to push is compatible with custom metrics.


text:
Q: Limit and derivative
The function $f:\Bbb R\to\Bbb R$ is differentiable and $\lim_{x\to\infty}f'(x)=1$. Which of the following is true?
A) $f$ is bounded
B) $f$ is increasing
C) $f$ is unbounded
D) $f'(x)$ is bounded

A: A. This suggests that $\displaystyle \lim_{x \to \infty} f(x) = x+K$, for some constant $K$, so not bounded, because it increases forever.
B. An increasing function is ALWAYS increasing. We have no evidence that states that this function is monotone.
C. If A is false, then C is true.
D. $f'(x)$ must exist for all $x \in \mathbb R$. It is also bounded to the right. (I just spent  5 minutes trying to prove it was bounded because I misread the question, please kill me.)
 However, we have no evidence to suggest that the function's derivative is bounded to the left, so the derivative is not necessarily bounded.
For studying purposes, consider $f(x)=e^{-x}+x$, which satisfies all the properties.
The answer is easily proven to be $\boxed{C}$, from above.
Remember that bounded over a set, in this case $\mathbb R$, means that for all $x \in \mathbb R$, $|f(x)| \leq M$, for some constant M.
For example, we can firmly assert that $\displaystyle \frac{1}{x^2+1}$ is bounded over the reals, where $M=1$.
We can also say that $x$ is bounded over the set $[-5,5]$, but we cannot say that it is bounded over the reals, because $f(x)=x$ grows arbitrarily at infinity.

A: Let $\epsilon > 0$. Then there exists a natural number $M$, such that $|f'(x)-1| < \epsilon$ whenever $x>M$. Chose $M<x<y$. By the mean value theorem there exists $c\in (x,y)$ such that $$f(x)+f'(c)(y-x)=f(y)$$ Hence, $$f(y)> (1-\epsilon)(y-M)+M$$ Since you have freedom in choosing $y>M$, $f(y)$ can be made as large as possible.


text:
Q: error while executing `VBoxManage` (vagrant/ virtualbox) I'm following the installation tutorial from Data Science at the Command Line which includes the following steps:
$ mkdir MyDataScienceToolbox

$ cd MyDataScienceToolbox

$ vagrant init data-science-toolbox/data-science-at-the-command-line

$ vagrant up

This works perfectly on one of my computer but not the other. Why?
Both computers are using Virtualbox version:4.3.12 and Windows 7.
This is the error message:
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'data-science-toolbox/data-science-at-the-command-line'...
There was an error while executing `VBoxManage`, a CLI used by Vagrant

for controlling VirtualBox. The command and stderr is shown below.
Command: ["import", "C:\\Users\\bernard\\.vagrant.d\\boxes\\data-science-toolbox-VAGRANTSLASH-data-science-at-the-command-line\\0.0.5\\virtualbox\\box.ovf", "--vsys", "0", "--vmname", "packer-virtualbox-iso_1410075150030_92186", "--vsys", "0", "--unit", "7", "--disk", "C:\\cygwin64\\home\\bernard\\VirtualBox VMs\\packer-virtualbox-iso_1410075150030_92186\\packer-virtualbox-iso-disk1.vmdk"]

Stderr: 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
Interpreting C:\Users\bernard\.vagrant.d\boxes\data-science-toolbox-VAGRANTSLASH-data-science-at-the-command-line\0.0.5\virtualbox\box.ovf...

OK.
0%...
Progress state: VBOX_E_FILE_ERROR
VBoxManage.exe: error: Appliance import failed
VBoxManage.exe: error: Could not create the clone medium 'C:\cygwin64\home\bernard\VirtualBox VMs\packer-virtualbox-iso_1410075150030_92186\packer-virtualbox-iso-disk1.vmdk'.
VBoxManage.exe: error: VMDK: cannot write allocated data block in 'C:\cygwin64\home\bernard\VirtualBox VMs\packer-virtualbox-iso_1410075150030_92186/packer-virtualbox-iso-disk1.vmdk' (VERR_DISK_FULL)
VBoxManage.exe: error: Details: code VBOX_E_FILE_ERROR (0x80bb0004), component Appliance, interface IAppliance
VBoxManage.exe: error: Context: "int __cdecl handleImportAppliance(struct HandlerArg *)" at line 779 of file VBoxManageAppliance.cpp

A: It looks like on the failing system your C: drive might not have enough free space. From the tail end of the error messages: "VERR_DISK_FULL".
Similar question on Super User: What causes the "Failed to create the hard disk storage" error when creating a new virtual machine?

A: You can use with sudo , I got rid of errors when executing with root access.
Example:
sudo vagrant up


text:
Q: WSL expected to be in the same environment but isn't I have Windows 10 (10.0.19043.1288), and I installed WSL2 using wsl --install ubuntu (20.04) from an elevated (admin) PowerShell.
I set the default WSL version to 2 and selected Ubuntu as the default distribution.
When starting using bash.exe (which is in c:\Windows\system32):
$ whoami && id && uname -a
root
uid=0(root) gid=0(root) groups=0(root)
Linux COMPUTERNAME 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

When starting with wsl.exe (which is in c:\Windows\system32):
$ whoami && id && uname -a
root
uid=0(root) gid=0(root) groups=0(root)
Linux COMPUTERNAME 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

When starting with ubuntu.exe (which is in c:\Program Files\Apps\Cannonical...):
$ whoami && id && uname -a
uid=1000(username) gid=1000(usernamegroups=1000(username),4(adm),20(dialout),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),117(netdev),1001(docker)
Linux COMPUTERNAME 5.10.102.1-microsoft-standard-WSL2 #1 SMP Wed Mar 2 00:30:59 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

The output of wsl.exe -l -v:
  NAME                   STATE           VERSION
* Ubuntu                 Running         2
  docker-desktop-data    Stopped         2
  docker-desktop         Stopped         2

Questions:

*

*Why do I have different environments? Ubuntu is selected as default.

*Why do I have a bash.exe and wsl.exe in the system32 directory?


text:
Q: PHP apply "double" even odd classes let´s say I´m creating divs in a loop:
 $i = 0;
 while ($i < 20) {
    echo '
x
';
 $i++;
  }

How can I apply classes in this rythm

x

x

x

x

x

x

x

…

(Double Zebra)
I´m always ending in somethin like:
$i%2 ? 'even':'odd';

which would give me
even
odd
even
odd

(Zebra striped)
thanks!

A: Just do :
 $i = 0;
 while ($i < 20) {
     $class = ($i%4 < 2) ? 'odd' : 'even';
     echo '
x
';
     $i++;
 }

A: Many possible solutions, one example:
$i%4 < 2 ? 'even':'odd'

edit: or using CSS3's nth-child selector:
<!DOCTYPE html>

        <title>...</title>

A

B

C

D

E

F

G

A: If more than 2 values (even/odd), I prefer to use an array like:
$classes = array('even', 'odd', 'odd', 'even');

for($i=0; $i<20; $i++){
    $clsIdx = $i % count($classes);
    echo "{$classes[$clsIdx]}
";
}

Demo: http://codepad.viper-7.com/vlCHdv
This allows for any values to repeat in any order.


text:
Q: How can i get "latitude" and "longitude" after integrating google maps in my Reactjs web app? i'm making a Reactjs app where i want to show google maps in  app... i want to implement the following
(1) my app will want permissions from user to get his current position and get the "latitude" and "longitude" and save them.
or
(2) user selects the marker on map and i want to get those latitude and longitude points.
first is more important. Please help me out. please thanks.
https://www.youtube.com/watch?v=4z4hxEHlsxc
i saw this video and this was helpful but he didn't teach about (1) problem.

A: Refer to my Codepen example here. You can get your first task done. For the second task, read the documentation. It's pretty straight forward. Links are below.
Markers documentation
Events documentation
Also, this library is very good at handling google maps. take a look.
class App extends React.Component {

  constructor(props) {
    super(props);

    this.map = null;
    this.marker = null;

    this.state = {
      currentLocation: {
        lat: 0.0,
        lng: 0.0
      }
    };
  }

  componentDidMount() {
    if (navigator && navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(pos => {
        const coords = pos.coords;
        this.setState({
          currentLocation: {
            lat: coords.latitude,
            lng: coords.longitude
          }
        });
        this.setPin(coords.latitude, coords.longitude)
      });

      this.map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
    }else{
      //TODO:
    }
  }

  setPin(lat, lng) {
    if(this.map) {
      this.map.setCenter({lat: lat, lng: lng});

      if(this.marker) {
        this.marker.setMap(null);
        this.marker = null;
      }

      this.marker = new google.maps.Marker({
        position: {lat: lat, lng: lng},
        map: this.map,
        title: 'Current Location'
      });

    }else{
      console.log("Map has not loaded yet")
    }
  }

  render() {
    return (

        {this.state.currentLocation.lat } / {this.state.currentLocation.lng}

    );
  }
}

ReactDOM.render(
    <App />,
  document.getElementById('main')
);

A: Use this library
https://www.npmjs.com/package/react-geocode
import Geocode from "react-geocode";

/// set Google Maps Geocoding API for purposes of quota management
Geocode.setApiKey("xxxxxxxxxxxx");
Geocode.setLangu`enter code here`age("en");

// Get address from latidude & longitude.
Geocode.fromLatLng("48.8583701", "2.2922926").then(
  response => {
    const address = response.results[0].formatted_address;
    console.log(address);
  },
  error => {
    console.error(error);
  }
);

// Get latidude & longitude from address.
Geocode.fromAddress("Eiffel Tower").then(
  response => {
    const { lat, lng } = response.results[0].geometry.location;
    console.log(lat, lng);
  },
  error => {
    console.error(error);
  }
);


text:
Q: SQL check or uniqueness in one column in multipe tables I have a 'unique' column, 'GID_New' that is in multiple tables. Is there a way to check if it's unique across all the tables in the QGIS project in SQL?
Can it be done in one SQL search without merging the tables into one and then running something like
SELECT A.GID_New, count(*), A.TableName
FROM "Water_Merged" as A
Group by A.GID_New

And then checking for a count >1
I would like to know which table the non-unique GID_New's are from as well.
The data is in a geopackage in QGIS so the code needs to work in QGIS SQL implementation.

A: You can use union all:
select gid_new, count(*) no_matches
from (
    select gid_new from table1
    union all select gid_new from table2
    union all select gid_new from table3
) t
group by gid
having count(*) > 1

If you want to know in which table duplicates exists, then one option is string concatenation. Assuming that your database uses string_agg(), that would look like:
select gid_new, count(*) no_matches, string_agg(which, ',') which_tables
from (
    select 'table1' which, gid_new from table1
    union all select 'table2', gid_new from table2
    union all select 'table3', gid_new from table3
) t
group by gid
having count(*) > 1


text:
Q: GoogleApiClient's enableAutoManage() needs a fragment activity but I have an activity I want to logout from google account which is integrated into my application. I have this function
   public void logoutFromGooglePlus(Activity a) {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestProfile()
                .build();
        GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(a.getBaseContext())
                .enableAutoManage(a /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API)
                .build();
        mGoogleApiClient.connect();
        if (mGoogleApiClient.isConnected()) {
            Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {

                        }
                    });
        } else {
            mGoogleApiClient.connect();   // It can send user to onConnected(), call logout again from there
        }
    }

As you can see I need to do it in an activity but here I have a problem enableAutoManage needs a fragmentActivity as input. But I have an activity. Can I  cast activity as fragmentActivity easily?or there is some other methods to do it?
thanks

A: I have met the same problem as you but it works when i changed from activity to AppCompatActivity.
Hope it helps.


text:
Q: Internet Explorer does not recognize iframe source I have a web application that if opened in Google Chrome or in Firefox works fine but in IE it does not work. The problem is when I try to change the src of an iframe. Here is the source of the iframe:
<iframe id="myFrame" name="I1" src="" style="border: thick inset #0000FF; width: 719px; height: 700px"></iframe>

The src, I change it when it loads the page (with the tag body onload)
This is the code that I have in the script to change the src:
<script type="text/javascript">

 function cargarImg() {
            var src1 = '<%= Request.QueryString["cobo"] %>';
            var src2 = '<%= Request.QueryString["carp"] %>';enter code here
            document.getElementById('myFrame').src = '////192.168.1.230/Pictures/TempFiles/' + src2 + '/cubo.swf';
        }
    </script>

Can someone tell me where the problem is? As I said, it works in Chrome or in Firefox but not in Internet explorer. Thank you

A: I believe your issue is with setting the src using the '////192.168.1.230/Pictures/TempFiles/' path it is going up a directory from where your current page is instead of to the root.  Try replacing the string with this http://192.168.1.230/Pictures/TempFiles/.


text:
Q: What do you call widely-pursued but exclusive careers where people are high-paid? (Superstars) I'm interested in finding writings on the subject of pursuing, "Superstar" or "wildest dreams" careers, but all my searches kept yielding writings about common careers and workplace settings that are merely described in superlative terms.
Please help me find a word or phrase that describes the most aspirational and exclusive of careers, such as famous musician, actor, influencer, creator, professional athlete, supermodel or other such careers to which many may aspire, but only a tiny fraction will achieve. As it's inherently somewhat subjective, please don't get lost in trying to define exactly which careers fit this definition.
The term should capture the make-or-break essence, in which the majority who don't achieve the high threshold for success will have to change careers. This is in contrast to something like a company executive, where most unsuccessful aspirants can comfortably remain on the business professional career path.

A: You used the word aspirational, which works pretty well.

of, relating to, or characterized by aspiration... associated with or suggestive of a high level of success and social status and therefore appealing to people who aspire to such status (Merriam-Webster)

Also useful could be high-reaching, which is defined by The Free Dictionary as

Reaching high or upward; hence, ambitious; aspiring.

Also, consider ambitious:

If a plan or idea is ambitious, it needs a great amount of skill and effort to be successful or be achieved (Cambridge)

And glamorous turns up many results online that are related to what you're looking for, although most definitions don't include this aspect:

attractive in an exciting and special way [Ex] a glamorous job (Cambridge)

Less specifically these are competitive careers:

relating to, characterized by, or based on competition (Merriam-Webster)

These are also known as win-or-bust careers, in addition to make-or-break, which you mentioned:

[of a plan] that will either completely succeed or completely fail (Word Hippo)

A: high-flyer (flier)

highflier
noun US (UK high-flyer, high-flier, highflyer) someone who
has a lot of ability and a strong wish to be successful and is
therefore expected to achieve a lot: Highfliers in the industry
typically earn 25 percent more than their colleagues.
https://dictionary.cambridge.org/dictionary/english/highflier

the elite

elite
noun [ C, + sing/pl verb ] UK  /iˈliːt/ US  /iˈliːt/
the richest, most powerful, best-educated, or best-trained group in a
society: the country's educated elite a member of the elite
https://dictionary.cambridge.org/dictionary/english/elite


text:
Q: Why does a stepup transformer increases voltage but reduces current? I know its a really basic question knowing the fact that you could just plug in the Voltage and Current into the proportionality formula. The thing is that I want a 'scientific/logical' explanation rather than the Maths.
And why don't a step-up transformer increases the current instead of the voltage?

A: if a step-up transformer could increase both current and voltage, it would be making free energy out of nothing. So... without maths... because a transformer conserves energy, if the voltage gets stepped up, the current gets stepped down.
Here is another way to think of this: an electrical transformer is just like the gearbox in your car. Voltage = torque and current = RPM. In first gear, the input shaft turns four times and the output shaft turns once, so the RPM is divided by four while the input torque is multiplied by four times at the output shaft. This is just like a step-up transformer, in which the input current is divided by four and the input voltage is multiplied by four.


text:
Q: how to access payment gateways in iphone application I need to access payment gateways (master or visa) in my iphone application. Any one can help me, how can i get it?

A: Obviously you will need to interact with your payment gateway using the exposed API. However, be aware that Apple will likely reject your application if you do so (they require using their in app store in most cases for payment processing). I recommend you read the guidelines.


text:
Q: tshark gives invalid capture filter error I'm trying to capture packets between two hosts using a python script. The function is as follows :
def wire_cap(IP1,IP2,op_fold,file_name,duration):  # invoke tshark to capture traffic during session
    batcmd='"c:\\Program Files\\Wireshark\\tshark.exe" -i 1 src ' + str(IP1) + ' or src '+ str(IP2) +' -a duration:'+str(duration)+' -P -w '+ op_fold+file_name+'.pcap'
    p = subprocess.Popen(batcmd, shell=True,stderr=subprocess.PIPE)
    while True:
        out = p.stderr.read(1)
        if out == '' and p.poll() != None:
            break
        if out != '':
            sys.stdout.write(out)
            sys.stdout.flush()
    thread.exit()

However, this gives the following error :
Capturing on 'Local Area Connection'
tshark: Invalid capture filter "src 172.28.3.87 or src 172.28.3.56 -a duration:40 -P -w C:\Python_Scripts\wire_capture.pcap" for interface 'Local Area Connection'!

That string isn't a valid capture filter (syntax error).
See the User's Guide for a description of the capture filter syntax.
0 packets captured

Initially, I thought the issue was with the interface, which is passed as '1', but after checking with Wireshark, there seems to be no problem with that. I verified with the official documentation too. Every option I passed looks fine.
I'm sure I'm missing out on something here. It would be really helpful to receive any directions suggesting that.

A: Your tshark command is:
c:\\Program Files\\Wireshark\\tshark.exe" -i 1 src 172.28.3.87 or src 172.28.3.56 -a duration:40 -P -w C:\Python_Scripts\wire_capture.pcap

That command mixes command-line flag arguments (the ones beginning with -) and capture-filter arguments.  Capture filter arguments must either come after all command-line flag arguments, i.e.
c:\\Program Files\\Wireshark\\tshark.exe" -i 1 -a duration:40 -P -w C:\Python_Scripts\wire_capture.pcap src 172.28.3.87 or src 172.28.3.56

or be part of a command-line flag argument, namely a -f argument:
c:\\Program Files\\Wireshark\\tshark.exe" -i 1 -f "src 172.28.3.87 or src 172.28.3.56" -a duration:40 -P -w C:\Python_Scripts\wire_capture.pcap

That's the standard convention for UN*X commands - and for Windows commands that use UN*X-style syntax (which usually means commands that originated on UN*X, as tshark did, or that are trying to maintain compatibility with UN*X commands).
So try
    batcmd='"c:\\Program Files\\Wireshark\\tshark.exe" -i 1 -a duration:'+str(duration)+' -P -w '+ op_fold+file_name+'.pcap src ' + str(IP1) + ' or src '+ str(IP2)


text:
Q: Depth buffering and polygon filling in Java I was a bit curious to see if I could write a simple engine in Java2D to render a 3D cube. My attempt has, to my surprise, been successful so far. The cube looks pretty good so far:

But, as you can see, I am seriously lacking depth testing. I am completely lost on how I could go about doing depth testing in Java2D though. From what I have found, you go about it by rendering each polygon to a bitmap then testing each pixel against every other pixel that is may conflict with. This is where I am lost.
I have the necessary depth values for each vertex of the polygons, but I don't have the depth values of each pixel. This is probably a side effect of letting Java2D fill each polygon for me using the fillPolygon(Polygon p) method.  So this leads me to believe I cannot do depth testing if I render my polygons using the fillPolygon(..) method. My first question is that: Can I do z-buffering while still being lazy and letting Java do my pixel drawing?
If not, then my next question is: how in the world do I go about rendering the polygons on my own? I mean, I know well enough how to store pixels in a bitmap then render them to an image. I am wondering how I can take the four vertices of each polygon and render them appropriately.

A: Given the triangle (or any polygon) you can surely compute the z value at any pixel location but I don't think you can tell the java function fillPolygon(Polygon p) to only draw the polygon pixels that pass the depth test unless your library has some function that also takes a stencil mask. If not, you need to code your own rasterizer. This old paper presents a remarkable yet simple rasterization algorithm that is suitable for today parallel hardware.

A: It all depends on what you would like to learn more about.

*

*If you want to implement Z-Buffering, you need to do the step of rasterizing, which is currently done by Java2D. A good starting point may be the scanline algorithm for the rendering.

*If you are more interested in hidden-surface removal and culling, you could start with backface culling


text:
Q: Creating a Custom Colored dbg! Macro In Rust I'd like to create a custom macro similar to the standard dbg! macro, but with the option to use colors via the colored crate. dbg! usually prints something with the format of
[path_to_file:line_number] "symbol name" = "symbol value"
//[src/gallery/image_slot.rs:231] "my_integer_value_of_12" = "12"

*

*How do I access the path/line number [path_to_file:line_number] so I can print it?

*How do I access the symbol name of a variable? (i.e. print my_var given my_var = 12)

A: *

*Use the file!, line!, and column! macros.

*Use the stringify! macro.

If you go to the docs of the dbg! macro, you can click [src], which shows the implementation of dbg!, which is as follows:
macro_rules! dbg {
    () => {
        $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
    };
    ($val:expr $(,)?) => {
        // Use of `match` here is intentional because it affects the lifetimes
        // of temporaries - https://stackoverflow.com/a/48732525/1063961
        match $val {
            tmp => {
                $crate::eprintln!("[{}:{}] {} = {:#?}",
                    $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
                tmp
            }
        }
    };
    ($($val:expr),+ $(,)?) => {
        ($($crate::dbg!($val)),+,)
    };
}

Using that, we can easily create a similar colored_dbg! macro, with the colored crate as you suggested.
(I just picked random colors, for a simple example)
// colored = "2.0"
use colored::Colorize;

macro_rules! colored_dbg {
    () => {
        eprintln!("{}", format!("[{}:{}]", file!(), line!()).green());
    };
    ($val:expr $(,)?) => {
        match $val {
            tmp => {
                eprintln!("{} {} = {}",
                    format!("[{}:{}]", file!(), line!()).green(),
                    stringify!($val).red(),
                    format!("{:#?}", &tmp).blue(),
                );
                tmp
            }
        }
    };
    ($($val:expr),+ $(,)?) => {
        ($(colored_dbg!($val)),+,)
    };
}

You'd use it just like how you'd be able to use dbg!:
fn main() {
    let my_var = 12;
    colored_dbg!(&my_var);

    let v = vec!["foo", "bar", "baz"];
    let v = colored_dbg!(v);
}

Which outputs the following:


text:
Q: How do you use a value from a data frame as the for loop iterator in R? I'm trying to set a numeric value from a data frame as the iterator condition in a for loop in R and I cannot get it to work.
The idea of the script is this:

*

*Loop through the rows in a data frame

*For each row, loop through a chunk as many times as a value in the row dictates

For example, I have a data frame called events like the following:
Row     Event        Years
 1        1           10
 2        2           7

I would like to run the following loop to perform the script above:
for (i in 1:nrow(events)){
  for(j in 1:events[i,2]{
    print(paste('The event number is',i,'and the year number is',j))
  }
}

The outcome I'm looking for would look like this:
[1] "The event number is 1 and the year number is 1."
[1] "The event number is 1 and the year number is 2."
[1] "The event number is 1 and the year number is 3."
[1] "The event number is 1 and the year number is 4."
[1] "The event number is 1 and the year number is 5."
[1] "The event number is 1 and the year number is 6."
[1] "The event number is 1 and the year number is 7."
[1] "The event number is 1 and the year number is 8."
[1] "The event number is 1 and the year number is 9."
[1] "The event number is 1 and the year number is 10."
[1] "The event number is 2 and the year number is 1."
[1] "The event number is 2 and the year number is 2."
[1] "The event number is 2 and the year number is 4."
[1] "The event number is 2 and the year number is 5."
[1] "The event number is 2 and the year number is 6."
[1] "The event number is 2 and the year number is 7."

But the result I'm getting is:
[1] "The event number is 1 and the year number is 1."
[1] "The event number is 2 and the year number is 1."
[1] "The event number is 2 and the year number is 2."

For testing purposes, I've tried the following code which works the way I want it to...
for (i in 1:nrow(events)){
  for(j in 1:10){
    print(paste('The event number is',i,'and the year number is',j))
  }
}

...so I've tried every way I can to replicate the 10 value dynamically.
I'm new to R but I'm not new to programming; I've tried everything from how I'm calling the index, to the type of the value, to setting and getting dimensions using dim() to the others listed below:

*

*1:as.numeric(events[i,2]

*1:events$Years[i]

*1:as.integer(events[i,2])

*1:as.factor(events[i,2])
I think I'm treating the iterator as a single value (like an integer) instead of an R construct like a factor or a vector and that's where I'm missing something. I've also read about using the apply function for this type of problem but I'm not familiar with its use so I wanted to try and tackle the for loop first.
Does anyone know what I have wrong here? I've been pulling my hair out all day on this!
Thanks in advance for your help.

A: Try:
df <- read.table(header = TRUE, text = "Row     Event        Years
1        1           10
2        2           7")

Count <- do.call("c", lapply(df$Years, function(x) seq(1, x)))
df <- df[rep(df$Event, df$Years) ,]
df <- cbind(df, Count)

paste("The event number is", df$Event, "and the year number is", df$Count)

I think the for-loops are not a good idea, if you can vectorize.


text:
Q: Question of partial differential with change of variables. Show that the equation
$k\frac{\partial^2{\phi}}{\partial{x^2}}=\frac{\partial{\phi}}{\partial{t}}$, $(k>0)$
is transformed by the introduction of the new independent variables
$\xi=\frac{x}{2\sqrt{t}}, \zeta=t$
into
$k\frac{\partial^2{\varphi}}{\partial{\xi^2}}+2\xi\frac{\partial{\varphi}}{\partial{xi}}=4\zeta\frac{\partial{\varphi}}{\partial{\zeta}}$
Where $\varphi(\xi,\zeta)=\phi(x,t)$

Using chain Rule,
$\frac{\partial{\phi}}{\partial x}=\frac{\partial{\phi}}{\partial{\xi}}.\frac{\partial{\xi}}{\partial x}$
From above,
$x=\xi2\sqrt{t}$
$\frac{\partial x}{\partial{\xi}}=\frac{4t+\xi}{2\sqrt{2}} \rightarrow \frac{\partial{\xi}}{\partial x}=\frac{2\sqrt{2}}{4t+\xi}$
I just substitute in
$\frac{\partial{\phi}}{\partial x}=\frac{\partial{\phi}}{\partial{\xi}}.\frac{\partial{\xi}}{\partial x}$
$\frac{\partial{\phi}}{\partial x}=\frac{\partial{\phi}}{\partial{\xi}} [\frac{2\sqrt{2}}{4t+\xi}]$
Similarly, I can calculate for $\frac{\partial^2{\phi}}{\partial x^2}$, but I do not find where this can lead to the answer.

A: Using your change of variable and the chain rule on $\phi(x,t) = \psi(\xi(x,t), \zeta(t))$, we get
\begin{align}
\phi_{x} &= \psi_{\xi} \cdot \xi_{x} \\
&= \psi_{\xi} \cdot \frac{1}{2 \sqrt{t}} \\
\implies \phi_{xx} &= \psi_{\xi \xi} \cdot \frac{1}{4t} \\
\phi_{t} &= \psi_{\xi} \cdot \xi_{t} + \psi_{\zeta} \cdot \zeta_{t} \\
&= \psi_{\xi} \cdot \frac{-x}{4 t^{3/2}} + \psi_{\zeta} \cdot 1
\end{align}
and so our original PDE becomes
\begin{align}
\phi_{t} &= k \phi_{xx} \\
\implies \psi_{\xi} \cdot \frac{-x}{4 t^{3/2}} + \psi_{\zeta} \cdot 1 &= k \psi_{\xi \xi} \cdot \frac{1}{4t} \\
\implies 4t \psi_{\zeta} - \psi_{\xi} \cdot \frac{x}{\sqrt{t}} &= k \psi_{\xi \xi} \\
\implies 4 \zeta \psi_{\zeta} - 2\xi \psi_{\xi} &= k\psi_{\xi \xi} \\
\implies 4 \zeta \psi_{\zeta} &= 2\xi \psi_{\xi} + k\psi_{\xi \xi}
\end{align}


text:
Q: Kernel downgrade, UUID not found initramfs I have a freshly installed 18.04 box. Updates were installed and rebooted. It's running kernel 4.15.0-74 without an issue:
root@restore:~# uname -a
Linux restore 4.15.0-74-generic #84-Ubuntu SMP Thu Dec 19 08:06:28 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

But due to incompatibility with a third party vendor I had to downgrade the kernel to 4.15.0-72. So.. I installed the package and rebooted into that kernel.
However.. I'm thrown back to initramfs immediately, after which it tells me:
Gave up waiting for root file system device. Common problems:
  - Boot args (cat /proc/cmdline)
    - Check rootdelay= (did the system wait long enough?)
  - Missing moduiles (cat /proc/modules; ls /dev)
ALERT! UUID=2e897a65-bbcc-426d-a72e-8aca96121c80 does not exist. Dropping to a shell!

The UUID is correct:
root@restore:~# blkid /dev/sda2
/dev/sda2: UUID="2e897a65-bbcc-426d-a72e-8aca96121c80" TYPE="ext4" PARTUUID="22caffaa-6efd-406b-acba-dbd8a53c72d1"

I've added a rootdelay=60 to the grub config, ran update-grub again, no luck.
root@restore:~# cat /etc/default/grub
GRUB_DEFAULT=0
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="noresume rootdelay=60"
GRUB_CMDLINE_LINUX="netcfg/do_not_use_netplan=true"
GRUB_TERMINAL=console

I also regenerated the initrd and run update-grub again. No luck.
root@restore:~# update-initramfs -c -k 4.15.0-72-generic
update-initramfs: Generating /boot/initrd.img-4.15.0-72-generic

More verbose output can be found: https://pastebin.com/8PEwkh05
And contents of fstab as requested below:
root@restore:~# cat /etc/fstab
UUID=2e897a65-bbcc-426d-a72e-8aca96121c80 / ext4 defaults 0 0
/swap.img       none    swap    sw      0       0

Am I missing something blindingly obvious here?
Hardware is a QEMU VM. I'm able to reproduce this on each VM I build from the install ISO.

A: re: "I'm able to reproduce this on each VM I build from the install ISO."
Is this a standard Ubuntu .iso, or "something custom" .iso (which I suspect)?

In reviewing your log, I see...
/usr/share/initramfs-tools/scripts/local-premount/ORDER ignored: not executable
/usr/share/initramfs-tools/scripts/init-premount/ORDER ignored: not executable
/usr/share/initramfs-tools/scripts/panic/ORDER ignored: not executable
/usr/share/initramfs-tools/scripts/local-block/ORDER ignored: not executable
/usr/share/initramfs-tools/scripts/local-top/ORDER ignored: not executable
/usr/share/initramfs-tools/scripts/init-bottom/ORDER ignored: not executable
/usr/share/initramfs-tools/scripts/init-top/ORDER ignored: not executable
/usr/share/initramfs-tools/scripts/local-bottom/ORDER ignored: not executable

You might wish to review these.
Also, in your /etc/fstab, I see...
UUID=2e897a65-bbcc-426d-a72e-8aca96121c80 / ext4 defaults 0 0

and it should be...
UUID=2e897a65-bbcc-426d-a72e-8aca96121c80 / ext4 errors=remount-ro 0 1

And in /etc/default/grub, I see...
GRUB_CMDLINE_LINUX_DEFAULT="noresume rootdelay=60"
GRUB_CMDLINE_LINUX="netcfg/do_not_use_netplan=true"

why the need for these parameters?


text:
Q: Is there any value in including SQLite in VCS's Having an argument with my team. We are developing an application using SQLite and some want to add it to the repo (GIT) and some don't. Previously with RDBMS system there has been no perceived benefit of using VCS on the DB. However SQLite is a self contained file with no external dependencies so i assume, even though it is binary, that a commit of the project code + the SQLite  file will give an accurate snapshot of the state of play at that point.
I also assume that a branch and merge would work as well.
Has anyone actually done this and if so does it work?

A: You'd get more benefit from GIT's versioning facilities if you stored a dump of the SQLite database (i.e. commands required to create it) rather than the database file itself. That way you could look at the history of the dump file and see tables or data being added etc.

A: Generally speaking, it's preferable to include full set of dependencies in a VCS repository. This makes your life a whole lot simpler.
If you're after versioning DB schema, check out Wizardby.


text:
Q: How to make a distinction between  with & without href in BeautifulSoup? I'm crawling a website and the target is the ads ID's, I was crawling a tags, then ['href'], but some of a tags don't have href, and return an error.
How can I make a distinction between these two?
The code:
def id_finder(url):
    id_list = []
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    ads_ids = soup.find_all('a')
    for ID in ads_ids:
        link = ID['href']
        if link.find('/car-search/'):
            pass
        else:
            print(link)

def main():
    driver = webdriver.Chrome(r"./chromedriver")
    driver.get("https://iranpelak.com/car-search")
    driver.maximize_window()
    time.sleep(2)
    try:
        WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//button[@data-role='end']"))).click()
    except Exception as e:
        print(e)
        pass
    first_page_url = driver.current_url
    for page in range(1, 10000):
        if page == 1:
            id_finder(first_page_url)
        else:
            pass

The error I get:
return self.attrs[key]
KeyError: 'href'

I think it's because some a tags don't have href, but your opinions would be appreciated!

A: The exact answer to your question is that you can pass custom function (filter) to soup.find_all() method:
spam = """
a tag with href
a tag without href
"""

soup = BeautifulSoup(spam, 'html.parser')

# find all a tags
a_tags = soup.find_all('a')
for tag in a_tags:
    print(tag.text)

# find only a tags with href
a_tags = soup.find_all(lambda tag: tag.name == 'a' and tag.get('href'))
for tag in a_tags:
    print(tag.text)
    print(tag['href']) # or print(tag.get('href'))

output
a tag with href
a tag without href
a tag with href
some url

However, as mentioned in the comments it is possible to use tag.get() method or handle the KeyError exception
a_tags = soup.find_all('a')
for tag in a_tags:
    link = tag.get('href')
    if link:
        print(link)

a_tags = soup.find_all('a')
for tag in a_tags:
    try:
        link = tag['href']
        print(link)
    except KeyError:
        pass

output
some url
some url

A: You can add a try/except block to handle those tags which do not contain a href element, catching the KeyError that is thrown:
for ID in ads_ids:
    try:
        link = ID['href']
    except KeyError:
        # Handle cases here
    if link.find('/car-search/'):
        pass
    else:
        print(link)

If you don't need to handle anything here, you can simply use continue to skip to the next iteration in the loop.

A: You can condense this:
a_tags = soup.find_all('a')

for ID in ads_ids:
    link = ID['href']
    if link.find('/car-search/'):
        pass
    else:
        print(link)

into this:
print([i['href'] for i in soup.select('a[href]:not([href*="/car-search/"])')])

a[href] -> a tags only with href attribute;
:not([href*="/car-search/"]) -> hrefs not containing the string /car-search/
Combining them specifies a tags only with href attributes not containing the specified string.
This css selector list is applied via select() method, returning a list which can have the href attributes extracted, from each member, inside a list comprehension. The extracted list of hrefs are wrapped in a print() call.


text:
Q: How can I get equally spaced points in a ListLogLogPlot? I am using ParallelTable to generate couples {j,fun[j]} which then I plot with ListLogLogPlot, but because of the loglog scale all points pile up at the far right of the plot.
How can I get equally spaced points?

A: You can use PowerRange
ListPlot[
 Transpose[{#, #}] &@PowerRange[1, 10^6]
 , PlotTheme -> "Scientific"
 , FrameTicks -> Automatic
 , ScalingFunctions -> {"Log10", "Log10"}
 ]

Inevitably, if you Google that function, you get something else...


text:
Q: Drupal Can't access Drupal Admin Dashboard I tried many times installing drupal on kubuntu with xampp (including after reinstalling kubuntu) and can't access Drupal Admin Dashboard.
These are the commands after reinstalling kubuntu
go to :
/home/rebirth/Downloads: type:
-sudo tar xvfz drupal-7.34.tar.gz
-mv drupal-7.34 ../../../opt/lampp/htdocs
-cd ../../../..
-sudo cp /opt/lampp/htdocs/drupal-7.34/sites/default/default.settings.php /opt/lampp/htdocs/drupal-7.34/sites/default/settings.php
-cd /opt/lampp/htdocs/drupal-7.34/sites
-sudo chmod a+w default-sudo chmod a+w default/settings.php
Then I install drupal by typing the url localhost + : "/drupal-7.34/"
I install using root as a username and setting up a password, create the database etc..
When I finish the installation it shows drupal without the Drupal Admin Dashboard and I tried many times login in it doesn't work ...
Is there a file saving the password and username to be an administrator or do I Have to use the webbrowser as root?
Help much appreciated!

A: Uncomment line 340 on settings.php to reflect your domain name
e.g. for localhost
$cookie_domain = 'localhost';

Please note this works for drupal 7 and my php version is 5.6. and ubuntu 14.10 you should also have rights to read and write the settings.php
Type your link
eg. http://yourdomain/drupal/user/
enter correct credentials you should be able to login
Regards,


text:
Q: How come the determinant of a matrix have to be 0 to find the eigenvalue and vector? I need help understanding why if the determinant of a matrix is 0 then there exists a matrix such that multiplying it by a vector get 0 and how this relates to eigenvectors and eigenvalues. For example, why do you find the determinant, all I know is that if the determinant is 0, then there is no inverse. So I am very confused and dumb.

A: Suppose determinant of a square matrix $A$ is zero. In that case the characteristic equation $\det (A-\lambda I)=0$ clearly has the root $\lambda=0$. It follows that $0$ is an eigen value of $A$. The converse is similar. Hence we may conclude that:
A square matrix has $0$ as an eigen value if and only if its determinant is zero.


text:
Q: Timeout error when running e2e test in angular cli projet I started working with e2e test with protractor and jasmine in angular cli project
describe('my-web-client App', function() {
  let page: myWebClientPage;

  beforeEach((done) => {
    page = new myWebClientPage();
  });

  it('should show menubar', () => {
    page.navigateTo();
    expect( page.getAppMenubar().isPresent() ).toEqual(true); // getAppMenubar() return element(by.css('app-menubar'));
  });
});

But even with a simple test I received the following errors

A: You specify the done callback but never execute it and, according to jasmine documentation:

... spec will not start until the done function is called in the call
  to beforeEach above. And this spec will not complete until its done is
  called.

You can just omit it:
beforeEach(() => {
  page = new myWebClientPage();
});


text:
Q: UIVIew that will grow as I scroll down? so I want to make an app that will display 20 pictures on a longer than the screens length view. then after the user scrolls down all the way to the bottom and reaches the end, if he tries to scroll down more the view will get longer, and load another 20 pictures. Does anyone have any ideas of how to do something like that ? and advices or tips or a small tutorial would be greatly appreciates.
Thank you very much.

A: I think the UITableView is perfect for this. You can have two sections in your table. First will contain cells with the pictures. The second will contain a cell representing a button for loading more images. If user taps this cell you simply load more pictures and increase the number of cells in UITableViewDataSource method.


text:
Q: Como criar registros na tabela MYSQL de acordo com o valor da variável $nregistros PHP Tenho uma variável $nregistros que define o valor de registros a ser inserido na tabela "formularios".
Se o $nregistros for igual a 4 por exemplo, ele deve inserir 4 linhas da seguinte forma:
formularios
id|campo
6 | 1
7 | 2
8 | 3
9 | 4

o campo "id" é autoindex, e o campo "campo" deve iniciar em 1 e ir até o valor final da $nregistros, no caso aqui, 4
Como posso fazer isso?

A: Para esse feito, um simples for pode resolver.
Tente algo como :
<?php
    $nregistros = 4;
    for($n = 1; $n <= $nregistros; $n++) {
        echo "INSERT INTO formularios SET campo = $n; ";
    }
?>

No lugar do echo entraria sua query de inserção no banco.
Dessa forma, obtive a seguinte saída:
INSERT INTO formularios SET campo = 1; INSERT INTO formularios SET campo = 2; INSERT INTO formularios SET campo = 3; INSERT INTO formularios SET campo = 4;

Vale lembrar que caso o número que estiver na variável $nregistros
  for muito longo, haverá perda de performance, pelo fato da realização
  de múltiplos insert.


text:
Q: Fire event only when clicking on an element, and not on its children If I bind a click handler to the body element, when I click anything on the page the event is triggered. I can check the event.target on every click:
$("body").on("click", function(event) {
  if (event.target.tagName == "BODY") {
    ...
  }
});

but that seem a bit overkill. Is there a way to trigger the event only when clicking the blank area of the body itself?

A: You can use the eventPhase property of event. A value of 2 means that the event is currently triggering the target element:
$("body").on("click", function(event) {
    //Cancel if not at target
    if (event.eventPhase != 2) return;

    //Other Code Here
});

Fiddle Here: http://jsfiddle.net/o0yptmmp/

A: You can do it if you check on every click if the element clicked has a body parent. If the condition is false, you are clicking the body:
$("body").on("click", function(event) {
  if ($(this).parents('body').length == 0) {
     //Do something
  }
});

In my opinion it's not a good practice, but it depends on your code and project.

A: You should put an
event.stopPropagation()

on all children you want to not bubble up.
jQuery Docs: http://api.jquery.com/event.stoppropagation/.


text:
Q: How to add clickTag for  alternate/fallback in HTML5 Ads? I realize there's not quite any "standards" in place for creating HTML5 ads.
But is there a best practice for entering a clickTag on Ads that makes use of ?
I assume this implementation largely depends on the ad-server it's uploaded to, but how could the clickTag dynamically change if Javascript is disabled?
Could it change on the server-side (ex: replaced upon request via PHP) even though the page has an *.html extension instead of *.php?
So far I have this for the HTML of an Ad:

A: Ad-server that supports  should change the value on the server side before serving the ad (see their specs). If not, I believe the only option would be to hard code the link.

If you do it like above, the clickTag will be used if javascript is available and otherwise user will be sent to the hard coded url.


text:
Q: android - How to get rid of the very top bar image
So I want to get rid of the black area at the top and the gray "news" area should be the very top of the screen. What is this section called?
I tried this but it just crashed my app.
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.SeanLee_TheFootballGallery_2201" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="android:windowFullscreen">true</item>
    </style>
</resources>

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_core);

        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.gray_01, null)));

        populateCollection();

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, NewsFragment.newInstance(mCollection)).commit();
    }

A: add this to your manifest  :
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

A: Please explain this a bit:-
You want to get rid of it from all the screens or in a specific screens.


text:
Q: Loading com AngularJS Tenho um objeto que indica que a página está sendo carregada. Porém, não está funcionando da forma correta, segue código:
HTML:

 //Quando carregando for TRUE mostra o spinner

 //Quando for false, mostra o conteúdo.

JS:
$scope.carregando = true;

$scope.acabou = function() {
    $timeout(function(){
        $scope.carregando = false;
    }, 3000);
}

$scope.acabou();

Percebam que caregando inicia como TRUE para que logo apareça o spinner, depois de 3 segundos seu status é alterado para FALSE, fazendo com que assim desapareça o spinner e apareça o conteúdo. Em partes esta funcionando. O que está errado é que quando a página começa a carregar, os dois aparecem juntos (durante alguns milésimos de segundo), não respeitando o ng-if, conforme imagem abaixo:

Outra dúvida, como eu poderia fazer para sumir o spinner e mostrar o conteúdo somente quando a página estiver totalmente carregada?

A: Amigo,
Aparentemente você não inseriu o $timeout no seu controller. ele precisa ser injetado para que você possa utiliza-lo dentro do seu controller, tal como o $scope é.
Fiz um PLUNKER com praticamente o mesmo código que você fez, mas injetando o $timeout no controller.

Em relação à sua outra pergunta, se você sumir com o body, você não vai conseguir mostrar spinner. Englobe seu Content em uma div e faça o spinner desacoplado. Segue exemplo abaixo:

 meu spinner

 // mostrar se for true
      // Progame sua página dentro deste DIV

Deixo aqui a documentação do $TIMEOUT para leitura.
Espero ter ajudado.

A: Acredito que o problema seja teus scripts sendo carregados dentro da tag .
Quando o html é renderizado no browser, os scripts dentro da tag  contendo o angular e o teu controller ainda não foram carregados, logo o ng-if ainda não foi interpretado. Quando o script for interpretado, aí tudo vai acontecer corretamente. Esses milésimos de segundo que você está percebendo, é o tempo que o browser demora para executar teus scripts.
Para forçar teus scripts a executaram antes do  ser carregado, você precisa colocar eles dentro da tag  no seu html. Ex:

 //Quando carregando for TRUE mostra o spinner

 //Quando for false, mostra o conteúdo.


text:
Q: How to extract string after a marker? I'm working on a project to perform a query into a set of files where the query criteria are inputted by a user.
Essentially, if the user inputs:
/T"some text"
The query will look for any file that contains "some text."
If a user inputs:
/T"some text" /T"some other text"
The query will look for a file that contains both or at least one such criteria.
I have a couple of ideas about how to perform the query itself, but my question is how can I extract the text after the /T and in-between the quotes. I plan on putting the extracted string into some data structure.
I saw some examples of using IndexOf and such, but they would essentially look for the first instance of /T and extract everything else after that. Is there a method that would allow a bounded way of getting this information, whether it is some class or implementation of regex?

A: var input = "/T\"some text\" /T\"some other text\"";
var criterias = input.Split(new[] { "/T\"", "\"" }, StringSplitOptions.None)
                     .Where(x => !string.IsNullOrWhiteSpace(x))
                     .ToList();


text:
Q: Foreign Keys to tables where primary key is not clustered index I'm focusing on SQL Server here, but I think this is a database agnostic question, really.
I have a table whereby a Guid is logically the primary key.  However, uniqueidentifiers apparently make terrible clustered indexes, so I'm planning on creating a dummy key as an identity column and making that the clustered index for the table.
When it comes to foreign keys referencing this table however, should the foreign keys reference the clustered index or the primary key?  I'm thinking it should be the primary key still, right?  And that's because the clustered index doesn't technically HAVE to be unique, whereas the primary key does...?
Also, just to double check, if I make another column the clustered index, that doesn't mean I need to add a non-clustered index to my primary key column, does it?  In other words, does my column automatically have an index on it just by being the primary key?

A: Taken from the MSDN article on FOREIGN KEY Constraints

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY
  KEY constraint in another table; it can also be defined to reference
  the columns of a UNIQUE constraint in another table.

I think it is perfectly fine to define a UNIQUE CLUSTERED INDEX on an IDENTITY column and define the PRIMARY KEY on different columns, often with a NONCLUSTERED INDEX but you don't have to specify an index.


text:
Q: Render Individual Form Element in Symfony 2 I'm having trouble rendering individual form fields in a twig template from a Symfony 2 form. In the example below, I'm simply trying to render the first_name form field.
Also, form_errors never renders anything.
Here is my Form object:
namespace ABC\WebsiteBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class LoanApplication extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder->add('first_name', 'text', array('required' => true));
  }

  public function getName()
  {
    return 'LoanApplication';
  }

  public function getDefaultOptions(array $options)
  {
    return array(
        //'data_class'      => 'Acme\TaskBundle\Entity\Task',
        'csrf_protection' => true,
        'csrf_field_name' => '_token',
        // a unique key to help generate the secret token
        'intention'       => 'loan_application',
    );
  }
}

Here is the controller:
namespace ABC\WebsiteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use JML\WebsiteBundle\Form\LoanApplication;
use JML\WebsiteBundle\QuickBase as QuickBase;

class ApplyController extends Controller
{
  public function indexAction()
  {
    $form = $this->createForm(new LoanApplication());
    return $this->render('ABCWebsiteBundle:Apply:index.html.twig', array(
            'form' => $form->createView(),
        ));

    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        if ($form->isValid()) {
            // perform some action, such as saving the task to the database

            //return $this->redirect($this->generateUrl('task_success'));
        }
    }
  }
}

And the twig:
<form action="{{ path('apply') }}" method="post" {{ form_enctype(form) }}>

{{ dump(form_errors(form)) }} // always empty

    {{ form_label(form.first_name) }} // this renders
    {{ form_widget(form.first_name) }} //empty
    {{ form_row(form.first_name) }}  //empty

  <input type="submit" formnovalidate/>
</form>


text:
Q: What's the current status of cryptography export restrictions? Let's say I want to add some basic encryption capabilities to my application (without making it the application's primary purpose) - for example, using public-key cryptography to encrypt/sign private messages in a video game. Should I be worried about export restrictions (mainly in the US)? Is there a limit to how "strong" the encryption can be?

A: According to this article:

On June 25, 2010, the Department of Commerce's Bureau of Industry and Security (BIS) published a notice in the Federal Register implementing substantial and far-reaching amendments to controls of encryption software and hardware under the U.S. Export Administration Regulations (EAR).  These changes were originally announced in early May, and mark the first step in the Obama Administration's efforts toward reform of U.S. export controls intended to expand access for U.S. exporters to foreign markets.
...
Decontrolling Ancillary Cryptography Products
This amendment to the regulations incorporates changes adopted in December at meetings of the Wassenaar Arrangement.  Previously, exporters were permitted to self-classify most ancillary cryptography items (i.e., items, such as video games, that use encryption but where the encryption is ancillary to the item's main purpose) as ECCN 5D002.  Such items could then be exported immediately using License Exception ENC.  Certain other ancillary cryptography items were classified under ECCN 5D992, and were eligible for export to most destinations other than Cuba, Iran, North Korea, Sudan, and Syria.
The new regulations effectively decontrol ancillary cryptography products.  Specifically, the regulations add a note to Category 5 of the Commerce Control List stating that such items will no longer be controlled on the basis of their cryptographic functionality.  Rather, ancillary cryptography items will be controlled under whatever other ECCN is applicable to the item.  In many cases, such items will likely be classified as EAR99.

(emphasis added)
So, it looks like video games are off the hook as far as US is concerned.


text:
Q: pandas.DataFrame slicing accoring to another DataFrame How can I create df3 according to df1 and df2?
df1 = pd.DataFrame([[1,2,3],[10,20,30],[100,200,300]], index=['a','b','c'],columns=['A','B','C'])
df2 = pd.DataFrame([['A','C'],['B','A'],['C','B']],index=['a','b','c'],columns=[0,1])
df3 = pd.DataFrame([[1,3],[20,10],[300,200]], index=['a','b','c'],columns=[0,1])

Here is my code,
df1.apply(lambda x: x.loc[df2.loc[x.name,:]], axis=1)

This is df1

This is df2

This is df3

A: Seems like you can do with lookup after stack with df2
s=df2.stack()
s
Out[321]:
a  0    A
   1    C
b  0    B
   1    A
c  0    C
   1    B
dtype: object
pd.Series(df1.lookup(s.index.get_level_values(0),s),index=s.index).unstack()
Out[322]:
     0    1
a    1    3
b   20   10
c  300  200

Or with apply
df2.apply(lambda x : df1.loc[x.name,x].values,axis=1)
Out[327]:
     0    1
a    1    3
b   20   10
c  300  200

A: use lookup
In [993]: pd.DataFrame({k: df1.lookup(df2.index, df2[c]) for k, c in enumerate(df2)},
                       index=df1.index)
Out[993]:
     0    1
a    1    3
b   20   10
c  300  200

Or
In [973]: df2.apply(lambda x: pd.Series(df1.loc[x.name, y] for y in x), axis=1)
Out[973]:
     0    1
a    1    3
b   20   10
c  300  200


text:
Q: How to send contact form info from a website as mobile SMS? My client has a website but doesn't check emails often. He has a lot of web enquiries through the online contact form. He carries a mobile phone though. How to send contact form details that's submitted through the website to his mobile phone as SMS?

A: The quickest and cheapest way is to determine the email address for that person's phone. Almost every cell phone has an email address you can send to which will show up as SMS on the device. This should help you find the email address for each carrier: http://www.makeuseof.com/tag/email-to-sms/
If you want to send an actual SMS instead of an email, you could try a service like Twilio which makes sending and receiving SMS from your apps easy via a REST API. [Full disclosure: I work at Twilio, but I was a long-time satisfied customer before starting here.]


text:
Q: If $\int_0^\infty |f(x)|^2dx<\infty$ then $F(z)=\int_0^\infty f(t)e^{itz}dt$ is well-defined and continuous Suppose $f$ is a complex valued function defined on $(0,\infty)$ such that $\int_0^\infty |f(x)|^2dx<\infty$.  Then for $z\in \Bbb C$ with $\text{Im}(z)>0$, define $F(z)=\int_0^\infty f(t)e^{itz}dt$. I am trying to show that $F$ is continuous, but I can't even see why that the integral is well-defined. How can we show that $F$ is well-defined?

A: Use the Cauchy-Schwarz inequality (integral form) :
$$\left\lvert \int_0^\infty f(t) \overline{g(t)} \,\mathrm{d}t\right\rvert^2 \leq \left( \int_0^\infty \lvert f(t) \rvert^2 \,\mathrm{d}t\right)\left( \int_0^\infty  \lvert g(t) \rvert^2 \,\mathrm{d}t\right)
$$

A: $\newcommand{\Im}{\operatorname{Im}}\newcommand{\Re}{\operatorname{Re}}$
If $f\in L^2(0,\infty)$, then since $x^2$ is convex on $[k,k+1]$, Jensen's Inequality says
$$
\begin{align}
\|f\|_{L^1(k,k+1)}
&\le\|f\|_{L^2(k,k+1)}\tag{1a}\\
&\le\|f\|_{L^2(0,\infty)}\tag{1b}
\end{align}
$$
Furthermore,
$$
\left\|t^ne^{-t\Im(z)}\right\|_{L^\infty(k,k+1)}\le (k+1)^ne^{-k\Im(z)}\tag2
$$
Thus,
$$
\begin{align}
\left\|f(t)\,t^ne^{-t\Im(z)}\right\|_{L^1(0,\infty)}
&\le\sum_{k=0}^\infty\left\|f(t)\,t^ne^{-t\Im(z)}\right\|_{L^1(k,k+1)}\tag{3a}\\
&\le\sum_{k=0}^\infty\|f\|_{L^1(k,k+1)}\left\|t^ne^{-t\Im(z)}\right\|_{L^\infty(k,k+1)}\tag{3b}\\
&\le\sum_{k=0}^\infty\|f\|_{L^2(0,\infty)}(k+1)^ne^{-k\Im(z)}\tag{3c}\\
&\le\|f\|_{L^2(0,\infty)}e^{2\Im(z)}\int_0^\infty x^ne^{-x\Im(z)}\mathrm{d}x\tag{3d}\\[3pt]
&=\|f\|_{L^2(0,\infty)}\frac{e^{2\Im(z)}n!}{\Im(z)^{n+1}}\tag{3e}
\end{align}
$$
Explanation:
$\text{(3a)}$: Minkowski's Inequality
$\text{(3b)}$: Hölder's Inequality
$\text{(3c)}$: apply $(1)$ and $(2)$
$\text{(3d)}$: $(k+1)^ne^{-k\Im(z)}\le e^{2\Im(z)}\int_{k+1}^{k+2}x^ne^{-x\Im(z)}\mathrm{d}x$
$\text{(3e)}$: evaluate integral
Therefore,
$$
\begin{align}
\left|\,\frac{\mathrm{d}^n}{\mathrm{d}z^n}F(z)\,\right|
&=\left|\int_0^\infty f(t)\,t^ne^{-t\Im(z)}e^{it\Re(z)}\,\mathrm{d}t\right|\tag{4a}\\
&\le\|f\|_{L^2(0,\infty)}\frac{e^{2\Im(z)}n!}{\Im(z)^{n+1}}\tag{4b}
\end{align}
$$
which says that for $\Im(z)\gt0$, $F(z)$ is not only well-defined, but also $C^\infty$.


text:
Q: Instant repaint and validate I have to force my program to validate and repaint my gui (or part of it) the moment it adds a new component to it. There must be absolutley nothing done until the component is painted on the screen, then the code can continue.
I'm creating a layered JPanel structure. A series of JPanels that each continas a series of JPanels that each contains a series of JPanels.
As I create 3rd level JPanels, I need to take data from 1st level JPanels which aren't drawn yet. That causes them to return wrong data and mess up the whole setup.
1st level JPanels only get painted after the master for loop (one which goes trough 1st level JPanels) is completed.
How can I force my program to draw it as soon as it's created and added to its parent?
Everything here is done inside EDT, I checked. Repaint and validate didn't work at all.
EDIT:
Okay, I used Robins solution.
However, is there a way to force instant GUI updates, as soon as the line in the code gets executed (oposed to aiting for loop to finins and similar stuff). It would be so much easier to debug some thing if that would be possible. Even if insta-update means pausing all the other threads.

A:
As I create 3rd level JPanels, I need to take data from 1st level
  JPanels which aren't drawn yet. That causes them to return wrong data
  and mess up the whole setup.

I would first suggest to change this setup to something more safe. Having to rely on paint order of your UI elements sounds like a good source for nasty problems.

1st level JPanels only get painted after the master for loop (one
  which goes trough 1st level JPanels) is completed.
How can I force my program to draw it as soon as it's created and
  added to its parent? Everything here is done inside EDT, I checked.
  Repaint and validate didn't work at all.

It does not work because you are blocking the EDT. Calling repaint and/or validate does not actually triggers a repaint. Instead, it schedules one. You could attempt to break up your master loop in several separate Runnables which you each schedule on the EDT. That might allow the scheduled Runnable by the repaint call to slip in between. However, there is no guarantee for that.

A: You should have a GUI data model that contains the information you want to put on the panels.
You would generate the information, then create your GUI components.


text:
Q: How to call two alternating functions in a loop every 5 minutes in JavaScript? Acknowledging that the setTimeout() method is asynchronous and therefore starting with this:
for (var i = 1; i <= 3; i++) {
  (function(i) {
    setTimeout(function() {
      console.log(i + " second(s) elapsed");
    }, i * 1000);
  })(i);
}

I'd like to replace console.log() with something to the effect of

*

*window.open("https://www.twitter.com","_self") or document.getElementById("myFirstID").click();

*and window.open("https://www.facebook.com","_self") or document.getElementById("mySecondID").click();,
called alternatingly, each with a delay of, say, 5 minutes, but need some help replacing it without breaking it :-) Therefore I ask.

This was one early (but unsuccessful) attempt:
i=0;
while(i < 100)
{
    setTimeout(function(){ window.open("https://www.bbc.com","_self") }, 3000);
    setTimeout(function(){ window.open("https://www.cnn.com","_self") }, 3000);
  i++
}

tldr;
also thought of using a switch() statement

See also:
How to make setTimeout in while loop execute sequentially in JavaScript?
JavaScript closure inside loops – simple practical example
Calling two methods alternately after every 5 minutes.

A: You can have two functions that call each other with a timeout, like so. You can also keep track of the timer, in case you want to stop it when an event occurs, or after a certain duration.

function toggleCalls () {
  var timer = {timeout: null};
  function callA () {
    console.log("A Called");
    timer.timeout = setTimeout(callB, 1000);
  }
  function callB () {
    console.log("B Called");
    timer.timeout = setTimeout(callA, 1000);
  }
  callA();
  return timer;
}

var timer = toggleCalls();

setTimeout(function () {
  clearTimeout(timer.timeout);
  console.log("stopped");
}, 5000);

A: If you want to go in a loop you can put the urls in an array and loop over them, calling setTimeout() for the next one each time:

let urls = [
    "https://www.bbc.com",
    "https://www.cnn.com",
    "https://www.npr.org"
]
function openURLs(urls, i=0){
    setTimeout(function(){
         console.log(urls[i]) // or whatever you want to call here
         openURLs(urls, (i+1) % urls.length)
        }, 1000)
}
openURLs(urls)

Further notes:
Remainder % (aka "modulo")
alert(1 % 3); // 1
alert(2 % 3); // 2
alert(3 % 3); // 0

alert(4 % 3); // 1

A: Try to use Interval function.
  setInterval (()=> {
     // TODO inserte code here
    }, 300*1000);


text:
Q: Powershell Store Variables into Variable does not work I need some help with Powershell, i hope somebody can help.
I want to store multiple Variables into one single variable.
Here is my code:
$Content = @"
$Var1 = "1"
$Var2 = "2"
$Var3 = "3"
"@

echo $Content

And thats my output:
echo $Content
 = "1"
 = "2"
 = "3"

It should look like this:
$Var1 = "1", etc...

But every variable gets removed. I don't know why. Could somebody please explain this? Do i need to store them into something like an object?
Thanks in advance!

A: The quickest fix for your situation is to switch to a single-quoted here-string.
$Content = @'
$Var1 = "1"
$Var2 = "2"
$Var3 = "3"
'@

In general, double quotes around a string instruct PowerShell to interpolate. Single quotes around a string tells PowerShell to treat the content as a literal string. This also applies to here-strings (@""@ and @''@).
# Double Quotes

$string = "my string"
"$string"
my string

@"
$string
"@
my string

# Single Quotes

'$string'
$string

@'
$string
'@
$string

When interpolation happens, variables are expanded and evaluated. A variable is identified starting with the $ character until an illegal character for a variable name is read. Notice in the example below, how the variable interpolation stops at the ..
"$string.length"
my string.length

You can use escape characters or other operators to control interpolation within double quoted strings. The subexpression operator $() allows an expression to be evaluated before it is converted into a string.
"$($string.length)"
9

The backtick character is the PowerShell escape character. It can be used to escape $ when you don't want it to be treated as a variable.
"`$string"
$string

Mixing quotes can create certain gotchas. If you surround your string with single quotes, everything inside will be a literal string regardless of using escape characters or subexpressions.
'"$($string.length)"'
"$($string.length)"

'"`$string"'
"`$string"

Surrounding your string with double quotes with inside single quotes will just treat the inside single quotes literally because the outer quotes determine how the string will be interpreted.
"'$string'"
'my string'

Using multiple single quote pairs or double quote pairs requires special treatment. In this unique situation for double quotes, you can use the backtick escape or a two " to print a single ".
"""$string"""
"my string"

"`"$string`""
"my string"

For multiple single quotes, you must use two ' because a backtick will be treated literally and not tell PowerShell to escape anything.
'''$string'''
'$string'

Please reference About_Quoting_Rules for official documentation.


text:
Q: Why c++ char array size is increase by one I declare C++ array as follows. Array size is 5 and number of characters are 5. But i have error: initializer-string for array of chars is too long When i change array size to 6 or empty, then no error. Why is that?
#include <iostream>
using namespace std;
int main()
{
   char name[5] = "ABCDE";
   cout<<name;
   return 0;
}

A: Because there's a null character at the end, so the size should be 6.
See string literal:

The null character ('\0', L'\0', char16_t(), etc) is always appended
  to the string literal: thus, a string literal "Hello" is a const char[6]
  holding the characters 'H', 'e', 'l', 'l', 'o', and '\0'.

And when initialize character arrays,

If the number of initializer clauses exceeds the number of members and bases (since C++17) to initialize, the program is ill-formed (compiler error)

So compile failed.
And you don't need to specify the size at all, just char name[] = "ABCDE"; will help you to avoid such kind of troubles.

String literals can be used to initialize character arrays. If an array is initialized like char str[] = "foo";, str will contain a copy of the string "foo".

A: strings in C are null-terminated.
What it means?
It means that they need an extra character to store the null character to indicate the end of the string.
Imagine a function parsing the "ABCDEF", how it knows when the string ended and don't invade other parts of the memory?
A: It knows just because the null character '\0'
So that's the reason you need to declare it with 1 extra character in mind.
To exemplify, imagine the piece of code:
#include <stdio.h>

int main() {
        char name[5] = "ABCDE";
        char test[] = "ANYTHING";
        printf("Hello, %s\n", name);
}

What you think it's gonna print? "ABCDE", right?
Actual output:

Hello, ABCDEANYTHING

It happens because printf tries to find the end of the string (the first null character) but only find it when it's already iterating over the test variable in a improper memory access.
It's a "good scenario", in the worst case your program will crash with a buffer overflow and could leave area for security exploitation.

A: The compiler implicitly terminates string literals with the null \0 termination character. So, every string literal you declare actually has an extra \0 character to the end.
char name[6] = "ABCDE";   // <-- Actually [ABCDE\0]
char name[] = "ABCDE";   // <-- Compiler figures it out


text:
Q: Non-integral powers of a matrix Question
Given a square complex matrix $A$, what ways are there to define and compute $A^p$ for non-integral scalar exponents $p\in\mathbb R$, and for what matrices do they work?
My thoughts
Integral exponents
Defining $A^k$ for $k\in\mathbb N$ is easy in terms of repeated multiplication, and works for every matrix. This includes $A^0=I$. Using $A^{-1}$ as the inverse, $A^{-k}=\left(A^{-1}\right)^k$ is easy to define, but requires the matrix to be invertible. So much for integral exponents.
Rational definition
I guess for a rational exponent, one could define
$$A^{\frac pq}=B\quad:\Leftrightarrow\quad A^p=B^q$$
This will allow for more than one solution, and I'm not sure if the computations I'll describe below will find all solutions satisfying the above equation. So I'm not sure whether that's a reasonable definition. For non-rational exponents, a limit using a convergent series of rational exponents might work.
Diagonalizable computation
If $A$ is diagonalizable, then one has $A=W\,D\,W^{-1}$ for some diagonal matrix $D$. One can simply raise all the diagonal elements to the $p$-th power, obtaining a matrix which will satisfy the above equation. For each diagonal element, I'd define $\lambda^p=e^{(p\ln\lambda)}$, and since $\ln\lambda$ is only defined up to $2\pi i\mathbb Z$, this allows for multiple possible solutions. If one requires $-\pi<\operatorname{Im}(\ln\lambda)\le\pi$, then the solution should be well defined, and I guess this definition even has a name, although I don't know it.
Non-diagonalizable computation
If $A$ is not diagonalizable, then there is still a Jordan normal form, so instead of raising diagonal elements to a fractional power, one could attempt to do the same with Jordan blocks. Unless I made a mistake, this appears to be possible. At least for my example of a $3\times3$ Jordan block, I was able to obtain a $k$-th root.
$$
\begin{pmatrix}
\lambda^{\frac1k} & \tfrac1k\lambda^{\frac1k-1} & \tfrac{1-k}{2k^2}\lambda^{\frac1k-2} & \\
0 & \lambda^{\frac1k} & \tfrac1k\lambda^{\frac1k-1} \\
0 & 0 & \lambda^{\frac1k}
\end{pmatrix}^k
=
\begin{pmatrix}
\lambda & 1 & 0 \\
0 & \lambda & 1 \\
0 & 0 & \lambda
\end{pmatrix}
$$
If the eigenvalue $\lambda$ of this block is zero, then the root as computed above would be the zero matrix, which doesn't result in a Jordan block. But otherwise it should work.
Conclusion
Edited since this question was first asked.
So it seems that every invertible matrix can be raised to every rational power, as long as uniqueness is not a strong requirement. A non-invertible matrix apparently can be raised to non-negative powers as long as all Jordan blocks for eigenvalue zero have size one.
Is this true? If not, where is my mistake? If it is, is there a good reference for this?

A: As @tom pointed out in a comment, the power of a matrix can be defined in terms of logarithm of a matrix and matrix exponential, using
$$A^p:=\exp\left(p\ln A\right)$$
Using the principal logarithm (this is the name for that choice described in the question without giving a name), the above even yields unique results.
The matrix exponential is defined for every matrix, the matrix logarithm only for invertible matrices.
The case of singular matrices mentioned in the question is therefore not covered by this definition.

A: You are correct that your proposed definition for rational exponents can run into issues of uniqueness. Consider just the problem of trying to find the square root of a matrix. If $I$ is the 2x2 identity, then any matrix of the form
\begin{pmatrix}
  \pm1 & a \\
  0 & \mp1 \\
\end{pmatrix}
satisfies $A^2=I$. Now, there is a case where you can define a unique square root. In particular, your matrix must be positive definite [1]
For a more general discussion, see this

A: I came to the need/wish to extend $A^n$ to $A^z$ from a geometrical perspective (where $n$ is an integer number and $z$ real one), so I hope this can help, by providing a geometrical meaning for "real powers of a matrix".
this is the geometrical setup
The hyperboloid shown on the image comes from the Pells's equation:
$$x^2 - 2y^2 = 1$$
The "vertical planes" shown there (only 3 shown, for $n=-1,0,1$) are identified by their $z$ coordinate and placed at $n$ (integer) values only.
That was the starting point: extending integer values $n$ to all real values $z$, will mean considering a continuous set of "vertical planes": that will involve powers of matrices, as $n$ will show up as a matrix exponent, in the following.
I assume each $z=n$ vertical plane "hosts" the coordinate system $(x_n, y_n)$, just like as these coordinate systems "lived" on those planes.
With this setup, the matrix
\begin{pmatrix}
  3 & 4 \\
  2 & 3 \\
\end{pmatrix}
is a representation for this coordinate transform:
$$(x_n, y_n) = \begin{pmatrix}
  3 & 4 \\
  2 & 3 \\
\end{pmatrix}^n (x_0, y_0)$$
which also includes "jumping" from plane $z=0$ to plane $z=n$.
BTW: the Pells's equation above is invariant to this coordinate transform.
Noticeably, the same matrix was used by ancient Greeks "to generate the next integer solution" (to Pells's equation), as $(x, y)_{(0)}=(1,0)$ was known to be  "a trivial solution":
$$(x, y)_{(n+1)} = \begin{pmatrix}
  3 & 4 \\
  2 & 3 \\
\end{pmatrix} (x, y)_{(n)}$$
or
$$(x, y)_{(n+1)} = \begin{pmatrix}
  3 & 4 \\
  2 & 3 \\
\end{pmatrix}^n (x, y)_{(0)} = \begin{pmatrix}
  3 & 4 \\
  2 & 3 \\
\end{pmatrix}^n (1, 0)$$
where
$$\begin{pmatrix}
  3 & 4 \\
  2 & 3 \\
\end{pmatrix}^n$$
means "apply transform $n$ times" and
$$\begin{pmatrix}
  3 & 4 \\
  2 & 3 \\
\end{pmatrix}^{(-1)}$$
means "apply inverse transform once".
But, considering that matrix as a coordinate transform, we see point $(1,0)$ on plane $n=0$ "jumping FWD" to plane $n=1$ and "rotating CW" to point $(3,2)$, when applying the "forward transform", while we see that same point $(1,0)$ "jumping BWD" to plane $n=-1$ and "rotating CCW" to point $(3,-2)$, when applying the "inverse transform".
Due to the recursivity of the "next solution generator":
$$(x, y)_{(n+1)} = \begin{pmatrix}
  3 & 4 \\
  2 & 3 \\
\end{pmatrix} (x, y)_{(n)}$$
that kind of "jump and rotate" applies to all "integer solutions" to Pells's equation: indeed, as a coordinate transform, all the points in the plane "rotate to" other points.
That would also suggest that "all points on the paraboloids 'rotate' in 3D":

*

*$(1,0,0)$ gets transformed to $(3,2,1)$

*$(1,0,0)$ gets inverse-transformed to $(3,-2,-1)$
Having put the "vertical planes" in between "helps visualizing the motion": it's a discrete motion ($n$ steps by $1$, not by a $dz$): could it be "extended" so it's continuous?
With the geometrical interpretation above, "extending" this "motion" to be "continuous" means "extending integer powers of matrices to real powers".
Would you agree?
Cheers,
.k.


text:
Q: No encuentra clase en bean definido en el ServletContext Estoy usando para mi proyecto (maven 3.3.9, spring 4+, hibernate4+, tiles 3, postgres 9+, jdk 8, wildfly 10), y estoy recibiendo el siguiente mensaje de error:

Cannot find class [org.springframework.orm.hibernat4.LocalSessionFactoryBean] for bean with name 'sessionFactory' defined in ServletContext

¿Alguien sabe por qué recibo ese error y cómo puedo solucionarlo?

Aquí está mi pom:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cl.legal</groupId>
    <artifactId>opciondefensa</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Opcion Defensa Maven App</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>4.2.0.RELEASE</spring.version>
        <jstl.version>1.2</jstl.version>
        <tiles.version>3.0.1</tiles.version>
        <hibernate.version>4.1.7.Final</hibernate.version>
        <log4j.version>1.2.17</log4j.version>
        <slf4j.version>1.6.1</slf4j.version>
        <logback.version>0.9.26</logback.version>
        <postgresql.version>9.4.1208</postgresql.version>
        <joda.version>2.2</joda.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>${joda.version}</version>
        </dependency>

        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!-- Apache Commons Upload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>

        <!-- Amazon -->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.10.75</version>
        </dependency>

        <!-- Apache Commons Upload -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.4.1</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-base</artifactId>
            <version>2.4.4</version>
        </dependency>

        <!--  postgres  Connector-->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>${postgresql.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-extras</artifactId>
            <version>${tiles.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>2.1</version>
        </dependency>

        <!-- Log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
            <exclusions>
               <exclusion>
                  <groupId>commons-logging</groupId>
                  <artifactId>commons-logging</artifactId>
               </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
            <exclusions>
               <exclusion>
                  <groupId>commons-logging</groupId>
                  <artifactId>commons-logging</artifactId>
               </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
            <exclusions>
               <exclusion>
                  <groupId>commons-logging</groupId>
                  <artifactId>commons-logging</artifactId>
               </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
            <exclusions>
               <exclusion>
                  <groupId>commons-logging</groupId>
                  <artifactId>commons-logging</artifactId>
               </exclusion>
            </exclusions>
        </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

    <!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

    <!-- optional -->

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-c3p0</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>opciondefensa</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
<!--            <plugin> -->
<!--                 <groupId>org.wildfly.plugins</groupId> -->
<!--                 <artifactId>wildfly-maven-plugin</artifactId> -->
<!--                 <version>1.1.0.Alpha5</version> -->
<!--             </plugin> -->
        </plugins>
    </build>
</project>

Éste es mi spring-servlet.xml:
<!-- Configures the @Controller programming model -->
<!--     <mvc:annotation-driven /> -->
<!--     <context:annotation-config /> -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- Specifying base package of the Components like Controller, Service,
        DAO -->
    <context:component-scan base-package="cl.opciondefensa.controller" />
    <context:component-scan base-package="cl.opciondefensa.service" />
    <context:component-scan base-package="cl.opciondefensa.dao" />
    <context:component-scan base-package="cl.opciondefensa.util" />
    <context:component-scan base-package="cl.opciondefensa.entity" />

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="50000000" />
    </bean>

    <!-- View Resolver -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" />

    <!-- Tiles configuration -->
    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles-definitions.xml</value>
            </list>
        </property>
    </bean>

<!-- Getting Database properties -->
<!--     <context:property-placeholder location="classpath:application.properties" /> -->
    <context:property-placeholder location="classpath:application.properties" />

<!--    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> -->
<!--        <property name="driverClass" value="${database.driverClassName}" /> -->
<!--         <property name="jdbcUrl" value="${database.url}" /> -->
<!--         <property name="user" value="${database.username}" /> -->
<!--         <property name="password" value="${database.password}" /> -->
<!--         <property name="acquireIncrement" value="${connection.acquireIncrement}" /> -->
<!--         <property name="minPoolSize" value="${connection.minPoolSize}" /> -->
<!--         <property name="maxPoolSize" value="${connection.maxPoolSize}" /> -->
<!--         <property name="maxIdleTime" value="${connection.maxIdleTime}" /> -->
<!--    </bean> -->
    <!-- DataSource -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="org.postgresql.Driver" />
        <property name="jdbcUrl" value="${database.url}" />
        <property name="user" value="${database.username}" />
        <property name="password" value="${database.password}" />
        <property name="acquireIncrement" value="${connection.acquireIncrement}" />
        <property name="minPoolSize" value="${connection.minPoolSize}" />
        <property name="maxPoolSize" value="${connection.maxPoolSize}" />
        <property name="maxIdleTime" value="${connection.maxIdleTime}" />
    </bean>

    <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernat4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="cl.opciondefensa.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.connection.characterEncoding">${hibernate.connection.characterEncoding}</prop>
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
                <prop key="hibernate.cache.use_structured_entries">${hibernate.cache.use_structured_entries}</prop>
                <prop key="hibernate.cache.generate_statistics">${hibernate.cache.generate_statistics}</prop>
                <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
            </props>
        </property>
    </bean>

<!-- Specifying the Resource location to load JS, CSS, Images etc -->
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <!-- Transaction -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

Y mi WEB.XML :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

  <display-name>OpcionDefensa</display-name>
  <welcome-file-list>
    <welcome-file></welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

Finalmente, application.properties para spring-servlet.xml en sessionFactory:
database.driverClassName=org.postgresql.Driver
database.url=jdbc:postgresql://localhost:5432/opciondefensa
database.username=postgres
database.password=postgres

connection.acquireIncrement=2
connection.minPoolSize=20
connection.maxPoolSize=50
connection.maxIdleTime=600
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.hbm2ddl.auto=create
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.connection.characterEncoding=utf8
hibernate.cache.use_query_cache=false
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_structured_entries=true
hibernate.cache.generate_statistics=false

El InicioController :
@Controller
public class InicioController {
@RequestMapping(value="/", method = RequestMethod.GET)
public ModelAndView home() {
    ModelAndView mav = new ModelAndView("home");
    String url="";
    url = "home";
    mav.setViewName(url);
    return mav;
}

}

A: Creo que en el web.xml te falta unir el servlet con su spring-servlet.xml, ¿no?
Te faltaría esto en el web.xml:
<servlet>
   <servlet-name>spring</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/classes/spring-servlet.xml</param-value>
    </init-param>
<load-on-startup>1</load-on-startup>

La ruta la he puesto al azar, comprueba que tu archivo está en esa ruta o cambia la ruta.
Así estarías configurando el servlet. Si lo que quieres es un contexto para toda la aplicación y no solo para el servlet tendrías que cambiar el nombre del fichero por applicationContext.xml.


text:
Q: Query for Searching in MySQL I have 3 tables
members (id, name, email)
members_kids (id, member_id, kids_name, kids_age)
member_kids_activity_preferences (id, kid_id, activity_id)

I have an array of activities (4, 10, 12, 14)
What I need to do is select distinct email addresses from members WHOSE kids have a preference for 4,10,12,14 from the member_kids_activity_preferences table. How do i do it using 1 query ?
Jason

A: Quick shot:
SELECT DISTINCT email FROM members m
    JOIN members_kids k ON m.id = k.member_id
    JOIN member_kids_activity_preferences p ON k.id = p.kid_id
  WHERE p.activity_id IN (4,10,12,14)

A: SELECT m.name,m.email
FROM members m
   JOIN members_kids k
      ON m.id = k.member_id
   JOIN member_kids_activity_preferences ap
      ON k.id = ap.kid_id
WHERE ap.id IN (4, 10, 12, 14)
GROUP BY m.name,m.email

A: SELECT DISTINCT
  m.email
FROM
  members AS m
INNER JOIN
  members_kids AS mk
ON
  m.id = mk.member_id
INNER JOIN
  member_kids_activity_preferences AS mkap
ON
  mk.id = mkap.kid_id
WHERE
  mkap.activity_id IN (4,10,12,14)