text:
Q: Knowing when to stop with spatial point thinning -- is an approach with Clark-Evans test valid? I need a random sample of presence points from the species' area to use in distribution modeling. I have an excessive amount of spatially clustered presence records, so I use minimum nearest neighbor distance-based spatial thinning with R package spThin.
I created a list of thinned datasets based on a vector of minimum NND values ranging from 10 to 500 km with a step of 10 km. To check if the distribution of points in each thinned set can be considered random, I used Clark-Evans' two-sided test with Cumulative Distribution Function (cdf) edge correction and 99 replicates Monte-Carlo based p-value estimation (spatstat package). I get the following distribution of p-values:
As I see it, the random pattern "likeliood" distribution is sort of unimodal. Two main questions are the following:
1. Is this workflow acceptable? (I do not mean "flawless" -- there is likely no ideal solution for that problem, as usulal.)
2. If so, based on the graph, what distance is a reasonable choice for modeling?
As there is a lot of uncertainty in both occurrence data and range estimation, I thought I could arbitrarily choose one value from the peak region of the graph. However, it would be nice to preserve as many points as it is reasonable to.
Here is how the actual point distributions look. The three graphs are made with (upper to lower) minimum NND = 130, 180 and 280 km (on the graph, that is "first p > .05", "first p ~= 1" and "average between first and last p > .05", respectively).

I would appreciate any advice with the reasonable choice of NND value from the experienced statisticians.


text:
Q: Starting Apache on Docker container I am playing with Docker to build an image with Apache and PHP but there is an issue with automatic start of Apache. This is Dockerfile:
FROM ubuntu:16.04

RUN apt-get update

# Apache
RUN apt-get -y install apache2

# Apache config
RUN echo "ServerName localhost" >> /etc/apache2/apache2.conf
RUN apache2ctl configtest
RUN a2dissite 000-default
COPY otpuskatame_backend.conf /etc/apache2/sites-available
RUN a2ensite otpuskatame_backend
RUN a2dissite 000-default
RUN rm /etc/apache2/sites-available/000-default.conf

# PHP
RUN apt-get -y install php libapache2-mod-php php-mcrypt

# Load container
CMD service apache2 start

EXPOSE 80

The image was built successfully but when run it with following command it breaks:
sudo docker run -d -v /var/www/project/:/var/www:rw -p 80:80 --name=lamp1 lamp1

Status:
CONTAINER ID        IMAGE                   COMMAND                  CREATED             STATUS                     PORTS                  NAMES
1a3679275b1d        lamp1                   "/bin/sh -c 'servi..."   8 seconds ago       Exited (0) 6 seconds ago                          lamp1

Logs look OK:
 * Starting Apache httpd web server apache2

If I remove CMD line from Dockerfile and then log into container and run service apache2 start manually everything works fine. But how to start it automatically?

A: It is due to main service in docker getting killed and because of this docker is exiting. You need to run service in the foreground
Try adding this to Dockerfile and rebuild it
CMD /usr/sbin/apache2ctl -D FOREGROUND

For more details refer to the site below:
https://writing.pupius.co.uk/apache-and-php-on-docker-44faef716150

A: It is due to main service in docker getting killed and because of this docker is exiting, you can execute:
docker run -d -t -p 80:80 --name apache image bash -c "service apache2 start && sleep 60"

The container will live for 60 seconds.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find minimum of the sigma Is there any polynomial algorithm to finding x1,x2,...,xn for fixed  ai,j,pi,j and gi,j and (0 < i,j <= n) such that minimize sigma{pi,jci,j} where :
ai,j+xi-xj = ci,j (mod gi,j) , -1< ci,j < gi,j

A: x = a (mod b) is the same as: there is an integer q such that a + qb = x is integer, therefore, x = a (mod b) constraint is equivalent to x - bW = a, W >= 0, W is integral, i.e., your problem can be reformulated as a mixed-integer program, which is know to be NP-hard problem.


text:
Q: How to use std::vector.insert()? So, I'm trying to learn how to use std::vectors, but I have a problem:
std::vector<Box>entities;

entities.insert(1, Box(&world, b2Vec2(Camera.getCenter().x, Camera.getCenter().y), b2Vec2(25, 25), 0, sf::Color::Red, b2_dynamicBody, 1.0f, 0.3));

How come that doesn't work? It gives me the following error :
Error no instace of overloaded function "std::vector<_Ty, _alloc>::insert [with _Ty=Box, _Alloc=std::allocator<Box>] matches the argument list. Argument types are (int, Box). Object type is std::vector<Box, std::allocator<Box>>

What am I doing wrong?

A: The first parameter should be an iterator, not an index. You can get an iterator to position 1 by using entities.begin() + 1.
Note that position 1 is the location of the second element in the vector: vector indexing is zero-based.

A: The first parameter is wrong. You should specify an iterator, not an index.
entities.insert(entities.begin() + i, theItem);

where i is the position you want to insert at. Note that the vector must be at least of size i.

A: entities.insert(entities.begin(), /*other stuff as before*/ would insert at the beginning of your vector. (i.e. the zeroth element). Remember that vector indexing is zero-based.
entities.insert(1 + entities.begin(), /*other stuff as before*/ would insert at the second spot.

A: All overloaded versions of the method insert require that the first argument would be of type std::vector<Box>::const_iterator applied to your vector definition. This iterator specifies the position where a new element must be inserted.
However you are passing in an integer value 1 instead of the iterator
entities.insert(1,
               ^^^
                Box(&world, b2Vec2(Camera.getCenter().x, Camera.getCenter().y),
                    b2Vec2(25, 25), 0, sf::Color::Red, b2_dynamicBody, 1.0f, 0.3));

There is no implicit conversion from an object of type int to an object of type std::vector<Box>::const_iterator. So the compiler issues an error.
Maybe you mean the following
#include <vector>
#include <iterator>

//...

entities.insert( std::next( entities.begin() ),
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
                Box(&world, b2Vec2(Camera.getCenter().x, Camera.getCenter().y),
                    b2Vec2(25, 25), 0, sf::Color::Red, b2_dynamicBody, 1.0f, 0.3));

Or if your compiler does not support function std::next then you can jjust write
entities.insert( entities.begin() + 1,
                 ^^^^^^^^^^^^^^^^^^^^^
                Box(&world, b2Vec2(Camera.getCenter().x, Camera.getCenter().y),
                    b2Vec2(25, 25), 0, sf::Color::Red, b2_dynamicBody, 1.0f, 0.3));


text:
Q: How do I get a reference to a function from within the function?
Possible Duplicate:
In Perl, how can a subroutine get a coderef that points to itself?

Is there a way to get a reference to a function from within that function without using the name?
I've recently found myself repeatedly writing code that smells of an anti-pattern. Data::Dump supports filters but (as of version 1.16) they aren't applied recursively. To work around that I've been writing things like this:
sub filter {
    my ($context, $node) = @_;
    # ...
    return { dump => dumpf($something, \&filter) };
}

This works, but the \&filter reference is starting to bug me. It creates maintenance overhead if the function is renamed or copied elsewhere as a template for a new filter. I'd like to replace it with something like __SUB__ (if Perl had such a thing).

A: For named subroutines you can use caller to get the name and then take a reference to it:
sub foo {
    state $self = \&{(caller(0))[3]};
    #...
    # call $self->();
}

This doesn't work for anonymous subroutines, which get "names" like main::__ANON__.


text:
Q: Surface generated by normals to a surface - what does it mean? A problem asks me to do the following:

Find the equation of the surface generated by the normals to the surface $x + 2yz + xyz^2 = 0$ at all points on the Z axis.

I don't understand what this means!
Sure, we can compute the normal to the given surface at any point (a line, no doubt) - but how do normals generate another surface, of which the question demands the equation?
Please explain!


text:
Q: Why are Random Unknown Projects Being Created Under my Google Cloud Platform Organization? New projects are showing up under my Google Cloud Platform (GCP) organization:
gcloud projects list --format='table(name:label=NAME, projectId:label=PROJECT_ID)'

#=>

NAME              PROJECT_ID
. . .             . . .
My First Project  primeval-jet-xxxxxx
My First Project  thermal-imprint-xxxxxx
My First Project  hip-weaver-xxxxxx
. . .             . . .

where xxxxxx represent random alphanumeric characters.
I am not part of any GCP groups.  I am the owner of my organization, which should have just one project.
I've tried to add a billing account on GCP and it has failed multiple times because of suspicious activity on my account.
I have 2FA enabled and changed my password multiple times.  The problem still persists.
What should I do?


text:
Q: NumberFormatter not using the correct decimal separator for "fr_CH" locale I'm just wondering if I missed something or it is some kind of bug in the NumberFormatter
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
numberFormatter.locale = Locale(identifier: "fr_CH")
print(numberFormatter.decimalSeparator)
print(numberFormatter.string(from: 123.45))

The output is:
Optional(",")
123.45 CHF // I would expect `123,45 CHF`

So far, I've only found this problem for this particular region. Can anyone recreate this?

A: Change
print(numberFormatter.decimalSeparator)

To
print(numberFormatter.currencyDecimalSeparator)


text:
Q: Find longest substring in python I have an input string and a file composed of different strings, one per line. I am trying to find if there is a substring in the input string that matches an entire line in the file. Its working but because there are some lines in the file that happen to be substrings of other lines, I'm not always getting the correct result. So is there a way to find the longest substring that matches a line in the file? For example, say the file contained: car, red car. And my input was "I like my red car." Is there a way to return "red car" rather than just "car"?
Here's my code:
wordsDoc = open('Database.txt', 'r', encoding='latin-1')
words = wordsDoc.readlines()
for line in words:
    if line.strip().lower() in inputString.lower():
        matching.append(line)

A: You can use LCS algorithm.
Maybe this link can be useful: http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python


text:
Q: TensorFlowDNNClassifier class is deprecated but replacement does not seem to work? Using the following with TF .9.0rc0 on 60,000 (train) and 26,000 (test) on  or so records with 145 coded columns (1,0) trying to predict 1 or 0 for class identification..
classifier_TensorFlow = learn.TensorFlowDNNClassifier(hidden_units=[10, 20, 10],n_classes=2, steps=100)
classifier_TensorFlow.fit(X_train, y_train.ravel())

I get:
WARNING:tensorflow:TensorFlowDNNClassifier class is deprecated. Please consider using DNNClassifier as an alternative.
Out[34]:TensorFlowDNNClassifier(steps=100, batch_size=32)

And then good results quite fast:
score = metrics.accuracy_score(y_test,   classifier_TensorFlow.predict(X_test))
print('Accuracy: {0:f}'.format(score))
Accuracy: 0.923121

And:
print (metrics.confusion_matrix(y_test, X_pred_class))
[[23996   103]
[ 1992    15]]

But when I try to use the new suggested method:
classifier_TensorFlow = learn.DNNClassifier(hidden_units=[10, 20, 10],n_classes=2)

it hangs with no completion? it would not take the "steps" parameter? I get no error messages or output so not much to go on... Any ideas or hints? The documentation is a bit "light?"

A: I don't think it is a bug, from the source code of DNNClassifier, I can tell that its usage differs from TensorFlowDNNClassifier. The constructor of DNNClassifier doesn't have the steps param:
def __init__(self,
           hidden_units,
           feature_columns=None,
           model_dir=None,
           n_classes=2,
           weight_column_name=None,
           optimizer=None,
           activation_fn=nn.relu,
           dropout=None,
           config=None)

As you could see here. Instead the fit() method that DNNClassifier inherited from BaseEstimator now has the steps param, notice that the same happens with batch_size:
  def fit(self, x=None, y=None, input_fn=None, steps=None, batch_size=None,
          monitors=None):

For the "it hangs with no completion?", in the doc of the fit() method of BaseEstimator it is explained that if steps is None (as the value by default), the model will train forever.
I still don't get why I would like to train a model forever. My guesses are that creators think this way is better for the classifier if we want to have early stopping on validation data, but as I said is only my guess.
As you could see DNNClassifier doesn't give any feedback as the deprecated
TensorFlowDNNClassifier, it is supposed that the feedback can be setup with the 'config' param that is present in the constructor of DNNClassifier. So you should pass a RunConfig object as config, and in the params of this object you should set the verbose param, unfortunately I tried to set it so I can see the progress of the loss, but didn't get so lucky.
I recommend you to take a look at the latest post of Yuan Tang in his blog here, one of the creators of the skflow, aka tf learn.

A: I just had a similar issue @Ismael answer is correct. I just wanted to add to the information that now classifier.fit() has the steps parameter that this parameter behaves differently. It doesn't abort earlier. There is another parameter called max_steps. That behaves as the original steps parameter of TensorFlowDNNClassifier.
In short just use the max_steps parameter on fit() like this:
classifier = skflow.DNNClassifier(...)
classifier.fit(X_train, y_train, max_steps=3000)


text:
Q: How do you track templates calls in ColdFusion? How do you track template path in ColdFusion?
I.E.
I have the following folder and file structure

*

*index.cfm
<cfset ArrayAppend(request.Trace, '/')>
 <cfdump var=#request.trace#>

*foo

*

*index.cfm
<cfset ArrayAppend(request.Trace, '/foo/')>
<cfinclude template='../'>

*bar

*

*index.cfm
ArrayAppend(request.Trace,'/foo/bar/')>
<cfinclude template='../'>
When I call foo/bar/index.cfm,
request.Trace equals:

*

*'/foo/bar/'

*'/foo/'

*'/'

How could I do this without specifically declaring each folder name?

A: Have a look at:

*

*expandPath(".")

*getBaseTemplatePath()

*getCurrentTemplatePath()

*CGI.CF_TEMPLATE_PATH

*CGI.PATH_TRANSLATED

*CGI.SCRIPT_NAME
If you want the template stack trace, use this:
<cfset templateTrace = []>
<cfset tagTrace = createObject("java","java.lang.Exception").init().TagContext>
<cfloop array="#tagTrace#" index="tagInfo">
    <cfset templateTrace.add(tagInfo.Template)>
</cfloop>
<cfdump var="#templateTrace#">

This will output all templates passed up to this call.

A: Not ideal but this worked for me.
<cfset currentFile = GetCurrentTemplatePath()>
<cfset currentDir = GetDirectoryFromPath(currentFile)>
<cfset webroot = expandPath("/")>
<cfset m_Trace = Replace(currentDir, webroot , '\')>
<cfset ArrayAppend (request.Trace, m_Trace )>


text:
Q: PDO Overwrite params I've made a simple code to make multiple inserts on the database:
 <?php
if (isset($_POST['numb']) && isset($_POST['email1'])) {
  $error = false;
  $numb = $_POST['numb'];
  for ($i = 1; $i <= $numb; $i++) {
    if (!isset($_POST['email' . $i])) {
      $error = true;
    }
  }
  if ($error == false) {
    include 'config.php';
    try {
      $connection = new PDO($dsn, $user, $pass);
      $suc1 = true;
    } catch (PDOException $e) {
      echo $e->GetMessage();
      $suc1 = false;
    }
    if ($suc1 == true) {
      $sql = "INSERT INTO alunos(email, emailKey) VALUES ";
      for ($i = 1; $i <= $numb; $i++) {
        $BAMBAM[$i] = '(:email' . $i . ', :emailkey' . $i . ')';
        $FELIPEFRANCO[$i] = sha1(microtime() . $_POST['email'. $i]);
        if ($i != $numb) {
          $BAMBAM[$i] = $BAMBAM[$i] . ',';
        }
        $sql = $sql . $BAMBAM[$i];
      }
      $insert = $connection->prepare($sql);
      for ($i = 1; $i <= $numb; $i++) {
        $param1 = 'email' . $i;
        $value1 = $_POST['email' . $i];
        $param2 = 'emailkey' . $i;
        $value2 = $FELIPEFRANCO[$i];
        echo '<script>alert("' . $param1 . ' -> ' . $value1 . '")</script>';
        $insert->bindParam($param1, $value1, PDO::PARAM_STR);
        $insert->bindParam($param2, $value2, PDO::PARAM_STR);
      }
      try {
        $insert->execute();
        $suc2 = true;
      } catch (PDOException $e) {
        echo  $e->GetMessage();
        $suc2 = false;
      }
      echo $sql;
    } else {
      header('Location: addAlunosForm.php?error=internal');
    }
  } else {
    header('Location: addAlunosForm.php?error=fill');
  }
} else {
  header('Location: addAlunosForm.php?error=fill');
}
?>

There is a test script up there, and, in the alert, it says exactly thiis:
email1 -> 1@gmail.com
email2 -> 2@gmail.com
email3 -> 3@gmail.com
But in the databse, it inserts the 3rd value 3 times:
3
NULL
3@gmail.com
901d4043642394ca30ea83688d944987d266b698
NULL
NULL

4
NULL
3@gmail.com
901d4043642394ca30ea83688d944987d266b698
NULL
NULL

5
NULL
3@gmail.com
901d4043642394ca30ea83688d944987d266b698
NULL
NULL

Details:

*$numb is the number of inserts


text:
Q: How to assign the value to templateUrl object in directive I have custom directive..
<users stats="stats"></users>

In controller, I have assigned stats value like
$scope.stats = "10";

Then I have written custom directives and get a scope object(stats)
directive.scope = {stats:'='})
directive.transclude = true;

directive.templateUrl = "templates/partials/users_stats.html";
    directive.link = function(scope, element, attrs){
            attrs.noEmpl = scope.stats;
    }

Then i have noEmpl modal in users_stats.html file
{{noEmpl}}

Here value is not assigning
Here is the jsfiddle https://jsfiddle.net/mdingalla/p13d44xz/8/

A: how about
directive.templateUrl = "templates/partials/users_stats.html";
directive.link = function(scope, element, attrs){
        scope.noEmpl = scope.stats;
}

then in html
{{noEmpl}}

https://jsfiddle.net/mdingalla/p13d44xz/8/ - jsfiddle


text:
Q: Drop-Down Menu - Python GUI I'm trying to create a drop down menu in Python that allows me to select a set list of items(ex. mL, L, m^3) and in the same button as the drop down menu, display the chosen item in the list.  I've gotten this far but I'm stuck:
from Tkinter import *
import tkMessageBox
import Tkinter

Avol_units = Menubutton(root, text="Units", relief=RAISED)
Avol_units.grid(row=4, column=2)
Avol_units.menu = Menu(Avol_units, tearoff = 0)
Avol_units["menu"] = Avol_units.menu

LVar  = IntVar()
mLVar = IntVar()

Avol_units.menu.add_checkbutton(label="L",
                      variable=LVar)
Avol_units.menu.add_checkbutton(label="mL",
                      variable=mLVar)

A: This is all you need to implement. I have tested it and it works fine but you may have to edit some lines or correct indentations.
from tkinter import*
from tkinter import ttk
import random
import tkinter.messagebox

Avol_units = Menubutton(root, text="Units", relief=RAISED)

LVar  = IntVar()
mLVar = IntVar()

Avol_units =Label(ABC2,font=("arial",12,"bold"),text="Nationality:",padx=2,pady=2,fg="Cornsilk",bg="cadet blue")
        Avol_units .grid(row=7,column=0, sticky =W)
        Avol_units =ttk.Combobox(ABC2,textvariable= Nationality, state="readonly", font=("arial",12,'bold'),
                                width=18)
        Avol_units["value"]=('','British','Nigeria','Jordan','Palastine','morocco','France','Norway')
        Avol_units.current(0)
        Avol_units.grid(row=7,column=1,pady=3, padx=20)


text:
Q: Echo Query Without "q=/index.php"? Right now I'm using $_SERVER['QUERY_STRING'] to echo the query on the page and for it ended up looking like this:
q=/index.php&utm_domain=

I'm not sure why the q=/index.php part is appearing, but I just want it to display utm_domain=
I also tried
http_build_query($_GET)

but I have no idea why this is happening since I haven't seen it before.. how do i fix this so it displays only the query?

A: Seems like you've got some URL rewriting or similar that sets the q parameter to the original request.
You can easily filter out the q parameter when displaying the query string. For example
$query = http_build_query(array_filter($_GET, function($key) {
    return $key !== 'q';
}, ARRAY_FILTER_USE_KEY));


text:
Q: Closeable lazy-seq in Clojure I'm trying to create a lazy-seq which is also closeable. What would be the cleanest way to do that in Clojure?
Intended usage (but it's just one example, I can think of more usages for a closeable lazy sequance):
(with-open [lines (file-lines-seq file)]
   (consume (map do-stuff-to-line lines)))

Which in this case would be equivalent to:
(with-open [reader io/reader file]
    (consume (map do-stuff-to-line (line-seq file))))

A: Managed to get the intended usage with this wonderful piece of code:
(defn file-lines-seq [file]
  (let [reader (clojure.java.io/reader file)
        lines-seq (line-seq reader)]
    (reify
      Closeable
      (close [this] (.close reader))

      ISeq
      (first [this] (.first lines-seq))
      (next [this] (.next lines-seq))
      (more [this] (.more lines-seq))
      (cons [this var1] (.cons lines-seq var1))
      (count [this] (.count lines-seq))
      (empty [this] (.empty lines-seq))
      (equiv [this var1] (.equiv lines-seq var1))
      (seq [this] (.seq lines-seq))
)))

If there's a less ugly way to do this, please let me know.


text:
Q: Align a shape within a different shape and naming shapes using VBA (macros) PowerPoint I would like to align ( in this case center)a shape( round cornered rectangle) within sharp cornered rectangle in a slide i.e the center point of both shapes should be equal using VBA without using 'Selection'.I am thinking to reference them via names(Like, wherever these two shapes come as a bunch, macro should align them) but not sure how to start.
Excuse me for the layman's explanation. Any thoughts would really be helpful and push me to start.

A: You'll have to set up a loop to check each shape in the slide, finding if its Type is an AutoShape, then if its AutoShapeType is msoShapeRoundedRectangle or msoShapeRectangle. As each are found, you would store the name of each in a variable. If both are found then you would get the left, top, width and height measurements for each and set those values so the centers align.
Sub CenterShapes()
  Dim oSlide As Slide
  Dim oShape As Shape
  Dim bFoundRRect As Boolean, bFoundRect As Boolean
  Dim RRectName$, RectName$
  For Each oSlide In ActivePresentation.Slides
    For Each oShape In oSlide.Shapes
      If oShape.Type = msoAutoShape Then
        If oShape.AutoShapeType = msoShapeRoundedRectangle Then
          bFoundRRect = True
          RRectName$ = oShape.Name
        End If
        If oShape.AutoShapeType = msoShapeRectangle Then
          bFoundRect = True
          RectName$ = oShape.Name
        End If
      End If
    Next oShape
    If bFoundRRect = True And bFoundRect = True Then
      RRectVCenter = oSlide.Shapes(RRectName$).Top + (oSlide.Shapes(RRectName$).Height / 2)
      RRectHCenter = oSlide.Shapes(RRectName$).Left + (oSlide.Shapes(RRectName$).Width / 2)
      RectVCenter = oSlide.Shapes(RectName$).Top + (oSlide.Shapes(RectName$).Height / 2)
      RectHCenter = oSlide.Shapes(RectName$).Left + (oSlide.Shapes(RectName$).Width / 2)
      VDif = RRectVCenter - RectVCenter
      HDif = RRectHCenter - RectHCenter
      oSlide.Shapes(RectName$).Top = oSlide.Shapes(RectName$).Top + VDif
      oSlide.Shapes(RectName$).Left = oSlide.Shapes(RectName$).Left + HDif
    End If
  Next oSlide
End Sub

A: This example assumes you know, or determine with your code, the names of the shapes you want to align. Then it's a quick manner of setting up a ShapeRange and using the built-in alignment functions in PowerPoint.
Option Explicit

Sub AlignMe()
    Dim theseShapeNames As Variant
    theseShapeNames = Array("Rectangle 3", "Rectangle 4", "Rectangle 5")

    Dim thisSlide As Slide
    Dim theseShapes As ShapeRange
    Set thisSlide = ActivePresentation.Slides(1)
    Set theseShapes = thisSlide.Shapes.Range(theseShapeNames)
    theseShapes.Align msoAlignCenters, msoFalse
End Sub


text:
Q: The best way to get rid off common mode noise for remote measurement I measure DC pseudo-differentially over 1-2 m wires. In order to avoid any voltage drop in wires  the built in  ADC input buffers  are used, thus there almost no current flow.  I expect the wires to catch a lot of common mode noise from RF to 50 Hz power grid.
Most materials about common mode noise that I found, consider it in the context of power line that involve common-mode chokes. Howver, I am not sure if this is suitable for my measurement.
Another way is the vanilla common mode filter

But again, I am not sure if it would be good enough and provide adequate level of filtering.
Moreover, there might be more methods that I am not aware of.
What possibilities are there to suppress common mode noise, and what is the best method for a measurement application?
In addition, how much the application of a shielded twisted pair cable would help to ease the problem?

A: You have to take care of two kinds of interference:

*

*common mode interference caused by capacitive coupling

*differential mode interference caused by inductive coupling

Capacitive coupling is already handled well by shielding and by using a differential pair of signals because it affects bouth lines about the same.
For handling inductive coupling using a twisted pair is very important.
If wires are not twisted it is easy to induce quite a large voltage (acting like a AC voltage source in series of the signal source) caused by changing magnetic fields (possible sources are transformers, speakers, SWPS, cellphones... any AC currents).
Twisting the differential pair reduces the intereferences as every other twist adds a positive/negative intereference to the signal ideally canceling out at the end (see Image below).

*

*The upper part shows a non-twisted wire pair: interfernce by induction is large (proportinal to blua area).

*The lower part shows a twisted wire pair: interference by induction is small (or even zero) as positive (+) and negative (-) interferences cancel out (partially).

A: I highly recommend trying a shielded cable. Using unshielded cables picks up a lot of noise from AC power lines, especially in audio applications. (I once made an unshielded guitar cable from scratch in high school, and you could definitely hear the 60Hz hum of the mains AC)
Also, make sure that the shielded cable is grounded properly, as this will make a big difference in regards to noise.

A: Using a good, properly shielded twisted pair cable and avoiding ground loops can really make a difference. Take a look at this on how to break ground loops: Shielding, Grounding and Ground loops.


text:
Q: How to sync fonts across Macbooks? My old MacBook has many fonts that I need to sync to my new MacBook.  How do I figure out the ones that are missing, and sync them?

A: Introduction
The Fonts included with the macOS operating system have not changed a whole lot over the years. As new (and highly customisable) fonts are made available to download and add to your FontBook, it indeed becomes difficult to remember which ones you have installed yourself and which were installed by the last macOS update. Having faced this issue for several years now, I  believe that I have found and implemented the best solution implemented across my various mac devices.
The Concept
I have discovered that the following solution is both reliable and very easy to set up. It includes uploading the entire fonts folder on the mac to Dropbox. Already being a frequent user of the platform, I am a big believer in syncing my fonts this way because my Design projects live there permanently. The big advantage is that the work and fonts are all in one location (Dropbox) from where I can access them at any time without having to search the internet for that one awesome font I haven't installed locally on the end-device. If I share a project, I can also have instant access to include the fonts in the project files, making it super easy for the receiver of my work to continue.
The Setup
You can find these sorts of guides all over the internet but I have found this one to be the most reliable in terms of macOS changes.
Your Mac:

*

*Launch Terminal in Applications/Utilities/

*Run cd ~/Library to open your user Library.

*Run sudo mv Fonts ~/Dropbox to move your Fonts folder to your Dropbox.

*Enter your password when prompted.

*Run ln -s ~/Dropbox/Fonts to create a symbolic link in your User Library.

Target Mac:

*

*Launch Terminal in Applications/Utilities/

*Run cd ~/Library to open your user Library.

*Run sudo rm -r Fonts to delete your user fonts folder.

*Enter your password when prompted.

*Run ln -s ~/Dropbox/Fonts to create a symbolic link in your User Library.
Things to consider
While this setup works well for my own purposes, you may like to thing about using a different cloud storage provider such as Google Drive or Apple's iCloud, which may work even better on other Apple devices.
Let me know how you make out and whether you have any questions about this method in action. I am sure it would fit your needs and I'd be more than happy to follow up with you on this.
Follow-up Additions

*

*This method essentially removes all Fonts from the mac and migrates them to Dropbox, then a link to the location is created, allowing any of your linked devices (or through the web interface) to add new/delete old fonts to/from your "repository".

*After the initial synchronization between Dropbox and the mac, you are able to disconnect from it because the font files have been synced to the Dropbox folder in your file system, much like every other cloud storage solution has that offline component. You may make changes to any content, once you connect to the internet, it syncs up and any changes push to all devices.

*If you are a one-off solution, I'd recommend not going to all the trouble of creating the symbolic link etc, and simply copying all the fonts to a folder on Dropbox or any other physical/cloud storage medium, deleting all fonts in the Fonts folder on the target machine and pasting all of them into the (now empty) Fonts folder.

*If you wish to keep existing ones, I have honestly not looked into that in too much detail as it wasn't applicable to my situation at the time. Apps like Compare Folders work really well when locating differences. I would suggest you check the source mac's Font folder against the target mac's Fonts folder and view the differences. This would allow you to pick out those that are not in the target folder. It isn't all as complicated as it sounds.

A: The accepted answer worked for me, too, except that I don't use Dropbox but iCloud. These are instructions, providing that you don't have yet a folder called Fonts in your iCloud. I hope @ProGrammer won't mind if I copy instructions s/he got from mba.me:
Your Mac:

*

*Launch Terminal in Applications/Utilities/

*Run cd ~/Library to open your user Library.

*Run sudo mv Fonts Mobile\ Documents/com~apple~CloudDocs to move your Fonts folder to your iCloud.

*Enter your password when prompted.

*Run ln -s Mobile\ Documents/com~apple~CloudDocs/Fonts to create a symbolic link in your User Library.

Target Mac:

*

*Launch Terminal in Applications/Utilities/

*Run cd ~/Library to open your user Library.

*Run sudo rm -r Fonts to delete your user fonts folder.

*Enter your password when prompted.

*Run ln -s Mobile\ Documents/com~apple~CloudDocs/Fonts to create a symbolic link in your User Library.

I strongly recommend to back up your original fonts.
BTW until Big Sur, this technique worked with a subfolder - I didn't need to replace the Fonts folder with a link but just put fonts on iCloud and then made a symbolic link in the Library/Fonts folder called iCloud:

*

*cd ~/Library

*ln -s Mobile\ Documents/com\~apple\~CloudDocs/Fonts Fonts/iCloud
It was less invasive technique but it was getting unstable in Catalina and stopped with macOS 11.

A: If using the built in Font Book app is not enough for you, I would look at Adobe Creative Cloud to license fonts and typefaces or if you already have purchased or cleared licensing, Extensis has excellent tools to manage this for 2 machines or a small / large workgroup or enterprise.

*

*https://www.extensis.com/font-management-software

A: If this is a 'one-time' activity, then there are plenty of file-syncing applications: Chronosync, Resilio Sync, GoodSync, etc -- which can be used to ensure that either or both Macs end up with either or both sets of files in the target folders.
These apps can also be used to run continuously, to ensure that the files stay in sync.
Bear in mind that Font Book does create status files in the font folders, which may have machine-specific information - encodings.dir, fonts.dir, fonts.scale, fonts.list - and copying these to another Mac may cause unforeseen problems.
Third-party font management apps may allow you to store and enable fonts on network drives (licence permitting). Though all hell can break loose if the network connection isn't available.


text:
Q: .NET 5.0 application not getting environment variables from docker run I have tried almost every solution I could find on the internet, but nothing has worked.
In my .Net 5.0 application, I am trying to override values for 'IP' and 'Port' in my appsettings.json file using environment variables with the 'docker run' command on Linux.
This is my appsettings.json file:
{
    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "Default": "Information",
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "IPSettings": {
        "IP": "192.168.230.131",
        "Port": "10080"
    }
}

This is my Dockerfile (I have tried without using the 'ENV' lines as well):
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80
ENV IPSettings__IP='192.168.230.131'
ENV IPSettings__Port='10080'

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["HostServer.csproj", "."]
COPY ["QuicktronWrapper/QuicktronWrapper.csproj", "QuicktronWrapper/"]
RUN dotnet restore "./HostServer.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "HostServer.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "HostServer.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "HostServer.dll"]

I have also added environment variables to the configuration, like below:
    var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddEnvironmentVariables();

    IConfigurationRoot configuration = builder.Build();

I am certainly able to get these values from appsettings.json, because I can run the application without issues on Windows, by launching it from Visual Studio on IIS.
Now, when I try to build the docker image on Linux and run it, the values I provide in the 'docker run' command aren't being passed to my application.
The following are variants of the command I used, but none seem to be working:
docker run -it -p 4000:9999 --name HostServer hostserver \
-e "IPSettings:IP"="192.168.247.131" \
-e "IPSettings:Port"="10080"

docker run -e ASPNETCORE_IPSettings__IP="192.168.247.131" \
-e ASPNETCORE_IPSettings__Port="10080" \
-it -p 4000:9999 --name HostServer hostserver

docker run -e IPSettings__IP="192.168.247.131" \
-e IPSettings__Port="10080" \
-it -p 4000:9999 --name HostServer hostserver

I have been struggling to fix this for more than a couple of days now. What am I missing here?
Also, if I replace the values in apsettings.json with the values I need and then use the following command:
docker run -it -p 4000:9999 --name HostServer hostserver

it runs perfectly on Linux, which means the problem is definitely with the way I am passing the environment variables.

A: It looks fine.
Something of the form:
docker run -it -e IPSettings__IP="192.168.247.131" --entrypoint /bin/bash --name HostServer hostserver

should work -  at least, I have the equivalent on my terminal here.
Docker can be particular about parameter order. Try the specific order in the example I provided.


text:
Q: How Spring creates an implementation of CrudRepository interface+CustomRepositoryInterface? Hy,
I have the next code in Spring
    @Repository
     public interface UserRepository extends CrudRepository<User, String>,
         UserRepositoryExtension<RosterUser> {
      ...any custom spring JPA methods...

   }

Extension Interface:
    public interface UserRepositoryExtension <T> {
       public T put(T entity);
   }

Implementation of Extension interface
    public class UserRepositoryExtensionImpl implements
     UserRepositoryExtension<User> {
 @Autowired
EntityManager entityManager;

@Override
public User put(User user) {
    entityManager.....(any logic here)
}...

}
I knew that Spring was able to create an inplementation of the UserRepository+CrudRepository interface methods in inyection time but what I dont get is:

*

*how spring creates these implementations and combine them with my implementation of UserRepositoryExtensionImpl(what happens under the hood?)

*How Spring knows what entityManager to use in the implementation class of UserRepository+CrudRepository it creates in injection time? It takes the entityManager from the context or from the class UserRepositoryExtensionImpl where an entityManager is declared?
Thanks


text:
Q: How prove that $ x+y+z>4$ for $ a+b+c=4$ and $ ax+by+cz=xyz$? Given positive reals $ a,b,c,x,y,z$ such that $ a+b+c=4$ and $ ax+by+cz=xyz$.
How prove that $ x+y+z>4$?

A: Suppose there exist $a, b, c, x, y, z > 0$ such that
$$a+b+c=4,$$
$$ax+by+cz = xyz,$$
$$x+y+z \leq 4.$$
Observe that we have
$$axyz + bxyz + cxyz = 4xyz,$$
so that
$$axyz + bxyz + cxyz = 4ax + 4by + 4cz,$$
and hence
$$ax(yz-4) + by(xz-4) + cz(xy-4) = 0.$$
Since
$x+y+z \leq 4$
and
$a, b, c, x, y, z > 0,$
what follow are the inequalities
$$xy, yz, xz < 4,$$
whence
$$ax(yz-4) + by(xz - 4) + cz(xy-4) < 0;$$
a contradiction, qed.


text:
Q: Calculating conditional probability using VineCopula in R I have a dataframe X (with columns x1 and x2) and would like to calculate conditional probability, something like P(x1<0.5|x2<0.3), which can be calculated using BiCopCDF. My question is: how do I obtain the transformed values (i.e., u and v) from the original data (x1 and x2)?
How can I obtain the u and v values corresponding to x1=0.5 and x2=0.3, to further explain it using the aforementioned example. One option is to find a distribution that fits x1 and x2 the best and then calculate CDF, however, I am not sure how well any particular distribution would fit the data. Any suggestions or help would be greatly appreciated.
Below is the code I am using:
u <- pobs(X)[,1]
v <- pobs(X)[,2]

par_clay = BiCopEst(u,v,3)$par
cop_clay = BiCop(family = 3, par = par_clay) #family 3 for clayton copula

copula_cdf = BiCopCDF(u = u1, v = v1, cop_clay)
conditional_cdf = copula_cdf/ecdf(v1)


text:
Q: How to create a Matrix from an Array in R? I have a simple array, like:
x <- c(10,20,30,40,50,60,70,80,90,100)

I would like to create a matrix from this array, because those numbers are prices of two stocks.
stock A: 10 30 50 70 90
stock B: 20 40 60 80 100

How can I create two columns from this list of prices.
Thank you

A: I suspect the OP actually wants:
> matrix(x, ncol = 2, byrow = TRUE)
     [,1] [,2]
[1,]   10   20
[2,]   30   40
[3,]   50   60
[4,]   70   80
[5,]   90  100

or possibly
> split(x, rep(c("A","B"), length(x)/2))
$A
[1] 10 30 50 70 90

$B
[1]  20  40  60  80 100

which can be converted to a data frame easily enough...

A: Just push the vector into matrix
matrix(x, ncol = 2)

No need to specify the number of rows since that is implicit. See ?matrix


text:
Q: How to use opengl glfw3 render in a imgui window? I am learning OpenGL by glfw3 lib and I am using imgui to make a interesting application.
I want to make a little Engine or CAD tool.
Problem is I can not render what I want in a imgui window.
I searched google and found below links:

*

*https://gamedev.stackexchange.com/questions/150214/render-in-a-imgui-window

*https://gamedev.stackexchange.com/questions/140693/how-can-i-render-an-opengl-scene-into-an-imgui-window
I tried about two days and I have rendered a triangle in a imgui window.
However when I try to render content as this link(Tutorial and Code) shows me.
The box in imgui window won't spin!!!
I tried serial days and I am going to give up, I really need your help.
#define __abc__ is a value to test.
Xhader.h just is the header file in the tutorial, also .vs and .fs files.
the difference is tutorial uses glad.h and I use glew.h
#define __abc__
#define STB_IMAGE_IMPLEMENTATION
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <stb_image.h>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"

#include "Xhader.h"

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow* window);

GLFWwindow* Proinit();
void imguiSetup(GLFWwindow* window);

// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;

int main()
{
    GLFWwindow* window = Proinit();
    imguiSetup(window);

    int view3d_width = 100;
    int view3d_height = 200;

    // configure global opengl state
    // -----------------------------
    glEnable(GL_DEPTH_TEST);

    // build and compile our shader zprogram
    // ------------------------------------
    Xhader ourShader("shader/vs.txt", "shader/fs.txt");

    // set up vertex data (and buffer(s)) and configure vertex attributes
    // ------------------------------------------------------------------
    float vertices[] = {
            -0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
            0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
            0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
            0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
            -0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
            -0.5f, -0.5f, -0.5f, 0.0f, 0.0f,

            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
            0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
            0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
            0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
            -0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,

            -0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
            -0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
            -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
            -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
            -0.5f, 0.5f, 0.5f, 1.0f, 0.0f,

            0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
            0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
            0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
            0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
            0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
            0.5f, 0.5f, 0.5f, 1.0f, 0.0f,

            -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
            0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
            0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
            0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
            -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,

            -0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
            0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
            0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
            0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
            -0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
            -0.5f, 0.5f, -0.5f, 0.0f, 1.0f
    };

    GLuint VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    GLuint VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    //---------------------------------------    FBO    -----------------------------//
#ifdef __abc__
    unsigned int fbo;
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    GLuint TOF;
    glGenTextures(1, &TOF);
    glBindTexture(GL_TEXTURE_2D, TOF);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 400, 300, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#else
    ;
#endif

    // load and create a texture
    // -------------------------
    unsigned int texture1, texture2;
    // texture 1
    // ---------
    glGenTextures(1, &texture1);
    glBindTexture(GL_TEXTURE_2D, texture1);
    // set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load image, create texture and generate mipmaps
    int width, height, nrChannels;
    stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis.
    std::string s1 = "resources/textures/container.jpg";
    std::string s2 = "resources/textures/awesomeface.png";
    unsigned char* data = stbi_load(s1.c_str(), &width, &height, &nrChannels, 0);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);
    // texture 2
    // ---------
    glGenTextures(1, &texture2);
    glBindTexture(GL_TEXTURE_2D, texture2);
    // set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load image, create texture and generate mipmaps
    data = stbi_load(s2.c_str(), &width, &height, &nrChannels, 0);
    if (data)
    {
        // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);

    // tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
    // -------------------------------------------------------------------------------------------
    ourShader.use();
    ourShader.setInt("texture1", 0);
    ourShader.setInt("texture2", 1);

    // render loop
    // -----------
    while (!glfwWindowShouldClose(window))
    {

#ifdef __abc__
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, TOF, 0);
#endif
        if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) {
            std::cout << "FRAMEBUFFER SUCCESS" << std::endl;
            glViewport(0, 0, 400, 300);
            // render
            // ------
            glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // also clear the depth buffer now!
            // bind textures on corresponding texture units
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, texture1);
            glActiveTexture(GL_TEXTURE1);
            glBindTexture(GL_TEXTURE_2D, texture2);
            // activate shader
            ourShader.use();
            // create transformations
            glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first
            glm::mat4 view = glm::mat4(1.0f);
            glm::mat4 projection = glm::mat4(1.0f);
            float time = (float)glfwGetTime();
            std::cout << time << std::endl;
            model = glm::rotate(model,time , glm::vec3(0.5f, 1.0f, 0.0f));

            view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
            projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
            // retrieve the matrix uniform locations
            unsigned int modelLoc = glGetUniformLocation(ourShader.ID, "model");
            unsigned int viewLoc = glGetUniformLocation(ourShader.ID, "view");
            // pass them to the shaders (3 different ways)
            glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
            glUniformMatrix4fv(viewLoc, 1, GL_FALSE, &view[0][0]);
            // note: currently we set the projection matrix each frame,
            //but since the projection matrix rarely changes it's often best practice
            //to set it outside the main loop only once.
            ourShader.setMat4("projection", projection);
            // render box
            glBindVertexArray(VAO);
            glDrawArrays(GL_TRIANGLES, 0, 36);

#ifdef __abc__
            glBindFramebuffer(GL_FRAMEBUFFER, 0);
#endif
        }
        else {
            std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl;
        }
#ifdef __abc__
        // Start the Dear ImGui frame
        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();
        bool View_3D = true;
        if (View_3D) {
            ImGui::Begin("3D View", &View_3D);
            view3d_height = ImGui::GetWindowSize().x;
            view3d_width = ImGui::GetWindowSize().y;
            ImVec2 pos = ImGui::GetCursorScreenPos();
            ImGui::GetWindowDrawList()->AddImage(
                (void*)TOF,
                ImVec2(ImGui::GetCursorScreenPos()),
                ImVec2(ImGui::GetCursorScreenPos().x + ImGui::GetWindowSize().x - 15,
                    ImGui::GetCursorScreenPos().y + ImGui::GetWindowSize().y - 35),
                ImVec2(0, 1),
                ImVec2(1, 0)
            );
            ImGui::End();
        }

        // input
        // -----
        processInput(window);

        ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
        // render
        ImGui::Render();
        int display_w, display_h;
        glfwGetFramebufferSize(window, &display_w, &display_h);
        glViewport(0, 0, display_w, display_h);
        glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
#endif

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // optional: de-allocate all resources once they've outlived their purpose:
    // ------------------------------------------------------------------------
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);

    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}

// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow* window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}

GLFWwindow* Proinit() {
//glfwSetErrorCallback(glfw_error_callback);
    if (!glfwInit()) return (GLFWwindow*)1;
#ifdef __APPLE__
    // GL 3.2 + GLSL 150
    const char* glsl_version = "#version 150";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  // 3.2+ only
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);            // Required on Mac
#else
    const char* glsl_version = "#version 130";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  // 3.2+ only
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);            // 3.0+ only
#endif
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Shader3D", NULL, NULL);
    if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return (GLFWwindow*)-1; }
    glfwMakeContextCurrent(window);
    //glfwSwapInterval(1); // Enable vsync
    //glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
#if defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
    bool err = glewInit() != GLEW_OK;
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
    bool err = gladLoadGL() == 0;
#else
    bool err = false;
#endif
    if (err) { fprintf(stderr, "Failed to initialize OpenGL loader!\n"); return (GLFWwindow*)1; }

    return window;
}

void imguiSetup(GLFWwindow* window) {
    // Setup Dear ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls
    ImGui::StyleColorsDark();
    ImGui_ImplGlfw_InitForOpenGL(window, true);         //Setup Platform bindings
#ifdef __APPLE__
    ImGui_ImplOpenGL3_Init("#version 150");             //Setup Renderer bindings
#else
    ImGui_ImplOpenGL3_Init("#version 130");
#endif

}

A: First, you should create a framebuffer and a texture like f_tex
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    f_tex = CreateTexture(512, 512, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, f_texture,
    GLuint depthrenderbuffer;
    glGenRenderbuffers(1, &depthrenderbuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 512, 512);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer);

and then, give the pointer of f_tex to drawList->AddImage()
    ImGui::Begin("Game Window");
    ImVec2 pos = ImGui::GetCursorScreenPos();
    ImDrawList* drawList = ImGui::GetWindowDrawList();
    auto app = SSEngine::App::main;
    uint f_tex = app->getFrameBuffer();
    drawList->AddImage((void*)f_tex,
        pos,
        ImVec2(pos.x + 512, pos.y + 512),
        ImVec2(0, 1),
        ImVec2(1, 0));
    ImGui::End();

example in my project:
https://i.stack.imgur.com/365De.png


text:
Q: Can you ask ruby to treat warnings as errors? Does ruby allow you to treat warnings as errors?
One reason I'd like to do this is to ensure that if heckle removing a line of code means that a warning occurs, I have the option of ensuring that the mutant get killed.

A: You can finally do that by overriding Warning.warn like
module Warning
  def warn(msg)
    raise msg
  end
end

This will turn the warning into an exception. This solution works at least since 2.4 branch.

A: There is unfortunately no real way of doing this, at least not on most versions of Ruby out there (variations may exist), short of monitoring the program output and aborting it when a warning appears on standard error.  Here's why:

*

*Ruby defines Kernel.warn, which you can redefine to do whatever you wish (including exiting), and which you'd expect (hope) to be used consistently by Ruby to report warnings (including internal e.g. parsing warning), but

*methods implemented natively (in C) inside Ruby will in turn directly invoke a native method called rb_warn from source/server.c, completely bypassing your redefinition of Kernel.warn (e.g. the "string literal in condition" warning, for example, issued when doing something like: do_something if 'string', is printed via the native rb_warn from source/parse.c)

*to make things even worse, there is an additional, rb_warning native method, which can be used by Ruby to log warnings if -w or -v is specified.

So, if you need to take action solely on warnings generated by your application code's calling Kernel.warn then simply redefine Kernel.warn.  Otherwise, you have exactly two options:

*

*alter source/error.c to exit in rb_warn and rb_warning (and rb_warn_m?), and rebuild Ruby

*monitor your program's standard error output for ': warning:', and abort it on match

A: You could also potentially use DTrace, and intercept the calls to rb_warn and rb_warning, though that's not going to produce exceptions you can rescue from somewhere.  Rather, it'll just put them somewhere you can easily log them.


text:
Q: How to set ngModel inside ngRepeat within Angular JS custom directive I am trying to create a directive where I am trying to generate forms dynamically, based on model. It seems somehow data-ng-model is not being set correctly in this scenario.
I am getting following output.
    <input type="{{ item.type }}" class="form-control" id="{{ item.id }}" data-ng-model="{{ item.model }}" placeholder="{{ item.label }}">

Whereas I am expecting following.
    <input type="text" class="form-control" id="role" data-ng-model="role.name" placeholder="Role Name">

One thing to note here is if I misspell or omit ng-model value it outputs correctly.
I've following code.
Template (cb-form-elements.html)
    <form class="form-horizontal" role="form" data-ng-submit="save()">

        {{ item.label }}

          <input type="{{ item.type }}" class="form-control" id="{{ item.id }}" placeholder="{{ item.label }}" data-ng-model="{{ item.model }}">

          <button type="submit" class="btn btn-default">Create Role</button>

    </form>

Directive
    angular.module('secondarySalesApp')
      .directive('cbFormElements', function () {
        return {
          templateUrl: '/views/partials/cb-form-elements.html',
          restrict: 'EA',
            require: '^ngModel',
            scope: {
              ngModel: '='
            }
        };
      });

Controller
    angular.module('secondarySalesApp')
      .controller('RoleCtrl', function ($scope, Restangular) {
        $scope.roles = Restangular.all('roles').getList().$object;

        $scope.cbFormConfig = [{
            "label": "Role Name",
            'id': "role",
            'type': 'text',
            'model': 'role.name'
        }];

        $scope.save = function(){
            $scope.roles.post($scope.role);
        }
      });

Declaration
    <data-cb-form-elements data-ng-model="cbFormConfig"></data-cb-form-elements>

The same thing works if I move it into page from directive.
Any help in this regard is appreciated.

A: The ng-model directive is not an interpolated directive; it will need a scope expression and not a string value.
Maybe this will help you: dynamic angular forms with febworms


text:
Q: From convergence in $L^2(\mathbb R^n)$ to convergence in $L_\text{loc}^2(\mathbb R^n)$
the question is about convergence in $L^2(\mathbb R^n)$  and $L^2_\text{loc}(\mathbb R^n)$ ... for details please look at the image i have attached above . Please let me know if there is something unclear to you . Thanks


text:
Q: why show only gridline in google map? I am developing Google map in my application but its not showing map only showing grid line ,Please anyone help me what is problem is that?
                                              And I am drawing text over bubbles,when more than 2 bubble lie same places,in that case text overlapping to each other.
                                                                          After changing API key Map will be showing but my second problem still remaining.I have to draw bubbles on Map and text (size of property on that bubble) suppose there are size of list 4 then 4 should be draw on bubble.I have been implemented these but there is no desire output is showing.
                                                                                When more than 2 property on same position and each have more than 2 list size then text on bubble overlapp to eachother sorry for my explanation I am using this code -
            drawable = this.getResources().getDrawable(R.drawable.bluedot);
            drawable1 = this.getResources().getDrawable(R.drawable.bluedot_large);

             overlay = new GoogleMapViewOverlay(drawable,mapView,activity);

//GoogleMapViewOverlay method is as:-
public GoogleMapViewOverlay(Drawable drawable, MapView mapView,
            Activity activity2)
    {
        //super(drawable);
        super(boundCenterBottom(drawable));
        setLastFocusedIndex(-1);
        populate();
        arrayList1  = new ArrayList<Applicationdataset>() ;
        items = new ArrayList<OverlayItem>();
        marker = drawable;
        mContext = mapView.getContext();
        mc = mapView.getController();
        this.activity = activity2;
        DB = new DatabaseHelper(activity2);
    }

//add item as
if(point != null)
                        {
                            if(arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
                            {
                                oi = overlay.createItem(i);
                                System.out.println("listing when 1 value is"+arrayList.get(i).getUnitstotal());
                                overlay.addItem(oi);
                            }
                            else if(!arrayList.get(i).getUnitstotal().equalsIgnoreCase("1"))
                            {
                                oi = overlay.createItem(i);
                                System.out.println("listing when more value is  "+ arrayList.get(i).getUnitstotal());
                                if(overlay!=null)
                                {
                                    overlay.addItem(oi);
                                    //overlay.draw(canvas, mapView, shadow);
                                }

                            }
                        }

//draw method for text draw over bubbles
                @Override
     public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when )
    {
        super.draw(canvas, mapView, false);

        arrayList1 = arrayList;
        for (int index = 0; index < items.size(); index++)
          {
            OverlayItem item = items.get(index);
            GeoPoint point = item.getPoint();
            Point ptScreenCoord = new Point();
            mapView.getProjection().toPixels(point, ptScreenCoord);
            //Paint
            Paint paint = new Paint();
            paint.setStyle(Style.STROKE);
            paint.setTextAlign(Paint.Align.CENTER);
            paint.setTypeface((Typeface.defaultFromStyle(Typeface.BOLD)));
            paint.setTextSize(20);
            paint.setColor(Color.WHITE);
            paint.setFilterBitmap(false);//true
            if(arrayList.get(index).getUnitstotal().equalsIgnoreCase("1"))
                canvas.drawText("", ptScreenCoord.x, ptScreenCoord.y-20,paint);
            else
            {

                  canvas.drawText(arrayList.get(index).getUnitstotal().toString(), ptScreenCoord.x, ptScreenCoord.y-40, paint);
            }

        }

        return true;
    }

A: Most Probably you havent fetched google map api key, please fetch it according to the instructions on following link, and then try:
https://developers.google.com/maps/documentation/android/mapkey


text:
Q: Why Account.LastActivityDate is not visible on any of SF UI? While solving one of the trailhead challenge I came accross Account.LastActivityDate field. I was not able to view this field in Account field list and had to google about it.
I was able to solve the problem and understood the purpose of this field.
One thing I did not understand is why do they have field and then keep it hidden on all SF UI?
It can be accessed via API or SOQL.
Can any one provide more details about it?
Thank you.

A: Not every field needs to be visible to every user (in fact, less is often better). Account has an Activities Related List. If one looks at that related list, it's often immediately obvious what the LastActivityDate is.
From the Object Reference:

LastActivityDate
Type
string
Properties
Filter, Group, Nillable, Sort
Description
Value is one of the following, whichever is the most recent:
• Due date of the most recent event logged against the record.
• Due date of the most recently closed task associated with the record.

Edit
I can't give you a definitive answer as to why the field isn't available for selection for display from Setup -> Account -> Field. The primary reason I can think of would be that the field is actually related to Activities (Tasks & Events). Without a Task or Event to reference, it's meaningless and of no value or use. From a practical standpoint, the field is probably best used in the context of reports.
That having being said, it somehow sticks in my mind that the field may be indexed (uncertain of that's true and would want to verify it before stating it as a fact). If so, I'd expect it's real purpose to be that of a "helper" which is used to speed up queries conducted in the background by Salesforce as an aid in finding related records from Activities.


text:
Q: How to obtain the number of CPUs/cores in Linux from the command line? I have this script, but I do not know how to get the last element in the printout:
cat /proc/cpuinfo | awk '/^processor/{print $3}'

The last element should be the number of CPUs, minus 1.

A: grep -c ^processor /proc/cpuinfo

will count the number of lines starting with "processor" in /proc/cpuinfo
For systems with hyper-threading, you can use
grep ^cpu\\scores /proc/cpuinfo | uniq |  awk '{print $4}'

which should return (for example) 8 (whereas the command above would return 16)

A: Processing the contents of /proc/cpuinfo is needlessly baroque. Use nproc which is part of coreutils, so it should be available on most Linux installs.
Command nproc prints the number of processing units available to the current process, which may be less than the number of online processors.
To find the number of all installed cores/processors use nproc --all
On my 8-core machine:
$ nproc --all
8

A: If you want to do this so it works on linux and OS X, you can do:
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

A: It is very simple. Just use this command:
lscpu

A: You can use one of the following methods to determine the number of physical CPU cores.

*

*Count the number of unique core ids (roughly equivalent to grep -P '^core id\t' /proc/cpuinfo | sort -u | wc -l).
awk '/^core id\t/ {cores[$NF]++} END {print length(cores)}' /proc/cpuinfo

*Multiply the number of 'cores per socket' by the number of sockets.
lscpu | awk '/^Core\(s\) per socket:/ {cores=$NF}; /^Socket\(s\):/ {sockets=$NF}; END{print cores*sockets}'

*Count the number of unique logical CPU's as used by the Linux kernel. The -p option generates output for easy parsing and is compatible with earlier versions of lscpu.
lscpu -p | awk -F, '$0 !~ /^#/ {cores[$1]++} END {print length(cores)}'

Just to reiterate what others have said, there are a number of related properties.
To determine the number of processors available:
getconf _NPROCESSORS_ONLN
grep -cP '^processor\t' /proc/cpuinfo

To determine the number of processing units available (not necessarily the same as the number of cores). This is hyperthreading-aware.
nproc

I don't want to go too far down the rabbit-hole, but you can also determine the number of configured processors (as opposed to simply available/online processors) via getconf _NPROCESSORS_CONF. To determine total number of CPU's (offline and online) you'd want to parse the output of lscpu -ap.

A: lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
# lscpu

Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                8
On-line CPU(s) list:   0-7
Thread(s) per core:    1
Core(s) per socket:    4
CPU socket(s):         2
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 15
Stepping:              7
CPU MHz:               1866.669
BogoMIPS:              3732.83
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              4096K
NUMA node0 CPU(s):     0-7

See also https://unix.stackexchange.com/questions/468766/understanding-output-of-lscpu.

A: The above answers are applicable to most situations, but if you are in a docker container environment and your container is limited by CpusetCpus, then you can't actually get the real cpu cores through the above method.
In this case, you need do this to get the real cpu cores:
grep -c 'cpu[0-9]' /proc/stat

A: The most portable solution I have found is the getconf command:
getconf _NPROCESSORS_ONLN

This works on both Linux and Mac OS X. Another benefit of this over some of the other approaches is that getconf has been around for a long time. Some of the older Linux machines I have to do development on don't have the nproc or lscpu commands available, but they have getconf.
Editor's note: While the getconf utility is POSIX-mandated, the specific _NPROCESSORS_ONLN and _NPROCESSORS_CONF values are not.
That said, as stated, they work on Linux platforms as well as on macOS; on FreeBSD/PC-BSD, you must omit the leading _.

A: I also thought cat /proc/cpuinfo would give me the correct answer, however I recently saw that my ARM quad core Cortex A53 system only showed a single core. It seems that /proc/cpuinfo only shows the active cores, whereas:
cat /sys/devices/system/cpu/present
is a better measure of what's there.  You can also
cat /sys/devices/system/cpu/online
to see which cores are online, and
cat /sys/devices/system/cpu/offline
to see which cores are offline.  The online, offline, and present sysfs entries return the index of the CPUS, so a return value of 0 just means core 0, whereas a return value of 1-3 means cores 1,2, and 3.
See https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-devices-system-cpu

A: In case anybody was wondering, here is what the Python psutil.cpu_count(logical=False) call does on Linux in equivalent shell script:
cat /sys/devices/system/cpu/cpu[0-9]*/topology/core_cpus_list | sort -u | wc -l

And here's a slightly longer version that falls back to the information from the deprecated thread_siblings_list file if core_cpus_list isn't available (psutil has this fallback):
cat /sys/devices/system/cpu/cpu[0-9]*/topology/{core_cpus_list,thread_siblings_list} | sort -u | wc -l

A: The following should give you the number of "real" cores on both a hyperthreaded and non-hyperthreaded system. At least it worked in all my tests.
awk -F: '/^physical/ && !ID[$2] { P++; ID[$2]=1 }; /^cpu cores/ { CORES=$2 };  END { print CORES*P }' /proc/cpuinfo

A: Not my web page, but this command from http://www.ixbrian.com/blog/?p=64&cm_mc_uid=89402252817914508279022&cm_mc_sid_50200000=1450827902 works nicely for me on centos. It will show actual cpus even when hyperthreading is enabled.
cat /proc/cpuinfo | egrep "core id|physical id" | tr -d "\n" | sed s/physical/\\nphysical/g | grep -v ^$ | sort | uniq | wc -l

A: You can also use Python! To get the number of physical cores:
$ python -c "import psutil; print(psutil.cpu_count(logical=False))"
4

To get the number of hyperthreaded cores:
$ python -c "import psutil; print(psutil.cpu_count(logical=True))"
8

A: Here's the way I use for counting the number of physical cores that are online on Linux:
lscpu --online --parse=Core,Socket | grep --invert-match '^#' | sort --unique | wc --lines

or in short:
lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l

Example (1 socket):
> lscpu
...
CPU(s):                28
Thread(s) per core:    2
Core(s) per socket:    14
Socket(s):             1
....
> lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l
14

Example (2 sockets):
> lscpu
...
CPU(s):                56
Thread(s) per core:    2
Core(s) per socket:    14
Socket(s):             2
...
> lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l
28

Example (4 sockets):
> lscpu
...
CPU(s):                64
Thread(s) per core:    2
Core(s) per socket:    8
Socket(s):             4
...
> lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l
32

A: Preface:

*

*The problem with the /proc/cpuinfo-based answers is that they parse information that was meant for human consumption and thus lacks a stable format designed for machine parsing: the output format can differ across platforms and runtime conditions; using lscpu -p on Linux (and sysctl on macOS) bypasses that problem.

*getconf _NPROCESSORS_ONLN / getconf NPROCESSORS_ONLN doesn't distinguish between logical and physical CPUs.

Here's a sh (POSIX-compliant) snippet that works on Linux and macOS for determining the number of - online - logical or physical CPUs; see the comments for details.
Uses lscpu for Linux, and sysctl for macOS.
Terminology note: CPU refers to the smallest processing unit as seen by the OS. Non-hyper-threading cores each correspond to 1 CPU, whereas hyper-threading cores contain more  than 1 (typically: 2) - logical - CPU.
Linux uses the following taxonomy[1], starting with the smallest unit:
CPU < core < socket < book < node
with each level comprising 1 or more instances of the next lower level.
#!/bin/sh

# macOS:           Use `sysctl -n hw.*cpu_max`, which returns the values of
#                  interest directly.
#                  CAVEAT: Using the "_max" key suffixes means that the *maximum*
#                          available number of CPUs is reported, whereas the
#                          current power-management mode could make *fewer* CPUs
#                          available; dropping the "_max" suffix would report the
#                          number of *currently* available ones; see [1] below.
#
# Linux:           Parse output from `lscpu -p`, where each output line represents
#                  a distinct (logical) CPU.
#                  Note: Newer versions of `lscpu` support more flexible output
#                        formats, but we stick with the parseable legacy format
#                        generated by `-p` to support older distros, too.
#                        `-p` reports *online* CPUs only - i.e., on hot-pluggable
#                        systems, currently disabled (offline) CPUs are NOT
#                        reported.

# Number of LOGICAL CPUs (includes those reported by hyper-threading cores)
  # Linux: Simply count the number of (non-comment) output lines from `lscpu -p`,
  # which tells us the number of *logical* CPUs.
logicalCpuCount=$([ $(uname) = 'Darwin' ] &&
                       sysctl -n hw.logicalcpu_max ||
                       lscpu -p | egrep -v '^#' | wc -l)

# Number of PHYSICAL CPUs (cores).
  # Linux: The 2nd column contains the core ID, with each core ID having 1 or
  #        - in the case of hyperthreading - more logical CPUs.
  #        Counting the *unique* cores across lines tells us the
  #        number of *physical* CPUs (cores).
physicalCpuCount=$([ $(uname) = 'Darwin' ] &&
                       sysctl -n hw.physicalcpu_max ||
                       lscpu -p | egrep -v '^#' | sort -u -t, -k 2,4 | wc -l)

# Print the values.
cat <<EOF
# of logical CPUs:  $logicalCpuCount
# of physical CPUS: $physicalCpuCount
EOF

[1] macOS sysctl (3) documentation
Note that BSD-derived systems other than macOS - e.g., FreeBSD - only support the hw.ncpu key for sysctl, which are deprecated on macOS; I'm unclear on which of the new keys hw.npu corresponds to: hw.(logical|physical)cpu_[max].
Tip of the hat to @teambob for helping to correct the physical-CPU-count lscpu command.
Caveat: lscpu -p output does NOT include a "book" column (the man page mentions "books" as an entity between socket and node in the taxonomic hierarchy). If "books" are in play on a given Linux system (does anybody know when and how?), the physical-CPU-count command may under-report (this is based on the assumption that lscpu reports IDs that are non-unique across higher-level entities; e.g.: 2 different cores from 2 different sockets could have the same ID).

If you save the code above as, say, shell script cpus, make it executable with chmod +x cpus and place it in folder in your $PATH, you'll see output such as the following:
$ cpus
logical  4
physical 4

[1] Xaekai sheds light on what a book is: "a book is a module that houses a circuit board with CPU sockets, RAM sockets, IO connections along the edge, and a hook for cooling system integration. They are used in IBM mainframes. Further info: http://ewh.ieee.org/soc/cpmt/presentations/cpmt0810a.pdf"

A: For the total number of physical cores:
grep '^core id' /proc/cpuinfo |sort -u|wc -l

On multiple-socket machines (or always), multiply the above result by the number of sockets:
echo $(($(grep "^physical id" /proc/cpuinfo | awk '{print $4}' | sort -un | tail -1)+1))

@mklement0 has quite a nice answer below using lscpu. I have written a more succinct version in the comments

A: Using getconf is indeed the most portable way, however the variable has different names in BSD and Linux to getconf, so you have to test both, as this gist suggests:
https://gist.github.com/jj1bdx/5746298
(also includes a Solaris fix using ksh)
I personally use:
$ getconf _NPROCESSORS_ONLN 2>/dev/null || getconf NPROCESSORS_ONLN 2>/dev/null || echo 1

And if you want this in python you can just use the syscall getconf uses by importing the os module:
$ python -c 'import os; print os.sysconf(os.sysconf_names["SC_NPROCESSORS_ONLN"]);'

As for nproc, it's part of GNU Coreutils, so not available in BSD by default. It uses sysconf() as well after some other methods.

A: Crossplatform solution for Linux, MacOS, Windows:
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu || echo "$NUMBER_OF_PROCESSORS")

A: Count "core id" per "physical id" method using awk with fall-back on "processor" count if "core id" are not available (like raspberry)
echo $(awk '{ if ($0~/^physical id/) { p=$NF }; if ($0~/^core id/) { cores[p$NF]=p$NF }; if ($0~/processor/) { cpu++ } } END { for (key in cores) { n++ } } END { if (n) {print n} else {print cpu} }' /proc/cpuinfo)

A: cat /proc/cpuinfo | grep processor

This worked fine.  When I tried the first answer I got 3 CPU's as the output.  I know that I have 4 CPUs on the system so I just did a grep for processor and the output looked like this:
[root@theservername ~]# cat /proc/cpuinfo | grep processor
processor       : 0
processor       : 1
processor       : 2
processor       : 3

A: If it's okay that you can use Python, then numexpr module has a function for this:
In [5]: import numexpr as ne

In [6]: ne.detect_number_of_cores()
Out[6]: 8

also this:
In [7]: ne.ncores
Out[7]: 8

To query this information from the command prompt use:
# runs whatever valid Python code given as a string with `-c` option
$ python -c "import numexpr as ne; print(ne.ncores)"
8

Or simply it is possible to get this info from multiprocessing.cpu_count() function
$ python -c "import multiprocessing; print(multiprocessing.cpu_count())"

Or even more simply use os.cpu_count()
$ python -c "import os; print(os.cpu_count())"

A: If you just want to count physical cores, this command did it for me.
lscpu -e | tail -n +2 | tr -s " " | cut -d " " -f 4 | sort | uniq | wc -w

Pretty basic, but seems to count actual physical cores, ignoring the logical count

A: Use below query to get core details
[oracle@orahost](TESTDB)$ grep -c ^processor /proc/cpuinfo
8

A: Fravadona's answer is awesome and correct, but it requires the presence of lscpu. Since it is not present on the system where I need the number of physical cores, I tried to come up with one that relies only on proc/cpuinfo
cat /proc/cpuinfo | grep -B2 'core id' | sed 's/siblings.*/'/ | tr -d '[:space:]' | sed 's/--/\n/'g | sort -u | wc -l
It works perfectly, but unfortunately it isn't as robust as Fravadona's, since it will break if

*

*the name or order of the fields inside /proc/cpuinfo changes

*grep replaces the line separator it inserts (currently --) by some other string.

BUT, other than that, it works flawlessly :)
Here is a quick explanation of everything that is happening
grep -B2 'core id'

get only the lines we are interested (i.e "core id" and the 2 preceding lines)
sed 's/siblings.*/'/

remove the "siblings..." line
tr -d '[:space:]'

replace spacing chars
sed 's/--/\n/'g

replace the '--' char, which was inserted by grep, by a line break
sort -u

group by "physical id,core id"
wc -l

count the number of lines
Being a total noobie, I was very pleased with myself when this worked. I never thought I would be able to join the required lines together to group by "physical id" and "core id". It is kind of hacky, but works.
If any guru knows a way to simplify this mess, please let me know.

A: Most answers in this thread pertain to logical cores.
Using BaSH on Ubuntu 18.x, I find this works well to determine number of physical CPUs:
numcpu="$(lscpu | grep -i 'socket(s)' | awk '{print $(2)}')"

It should work on most Linux distros.

A: One more answer among the numerous previous ones. It is possible to use the cgroups when they are available. The cpuset sub-system provides the list of actives cpus. This can be listed in the top most cgroup of the hierarchy in /sys/fs/cgroup. For example:
$ cat /sys/fs/cgroup/cpuset/cpuset.effective_cpus
0-3

Then, a parsing of the latter would be necessary to get the number of active CPUs. The content of this file is a comma separated list of CPU sets.
Here is an example using tr to break the list into single expressions and using sed to translate the intervals into arithmetic operations passed to expr:
#!/bin/sh

# For test purposes, the CPU sets are passed as parameters
#cpuset=`cat /sys/fs/cgroup/cpuset/cpuset.effective_cpus`
cpuset=$1

ncpu=0
for e in `echo $cpuset | tr ',' ' '`
do
  case $e in

    # CPU interval ==> Make an arithmetic operation
    *-*) op=`echo $e | sed -E 's/([0-9]+)-([0-9]+)/\2 - \1 + 1/'`;;

    # Single CPU number
    *) op=1;;

  esac

  ncpu=`expr $ncpu + $op`

done

echo $ncpu

Here are some examples of executions with several flavors of CPU sets:
$ for cpuset in "0" "0,3" "0-3" "0-3,67" "0-3,67,70-75" "0,1-3,67,70-75"
> do
>   ncpu.sh $cpuset
> done
1
2
4
5
11
11

A:  dmidecode  | grep -i cpu | grep Version

gives me

Version: Intel(R) Xeon(R) CPU E5-2667 v4 @ 3.20GHz
Version: Intel(R) Xeon(R) CPU E5-2667 v4 @ 3.20GHz

Which is correct socket count - looking up the E5-2667 tells me each socket has 8 cores, so multiply and end up with 16 cores across 2 sockets.
Where lscpu give me 20 CPUs - which is totally incorrect - not sure why. (same goes for cat /proc/cpu - ends up with 20.

A: Quicker, without fork
This works with almost all shell.
ncore=0
while read line ;do
    [ "$line" ] && [ -z "${line%processor*}" ] && ncore=$((ncore+1))
  done </proc/cpuinfo
echo $ncore
4

In order to stay compatible with shell, dash,  busybox and others, I've used ncore=$((ncore+1)) instead of ((ncore++)).
bash version
ncore=0
while read -a line ;do
    [ "$line" = "processor" ] && ((ncore++))
  done </proc/cpuinfo
echo $ncore
4

A: Python 3 also provide a few simple ways to get it:
$ python3 -c "import os; print(os.cpu_count());"

4
$ python3 -c "import multiprocessing; print(multiprocessing.cpu_count())"

4

A: Summary:
to get physical CPUs do this:
grep 'core id' /proc/cpuinfo | sort -u

to get physical and logical CPUs do this:
grep -c ^processor /proc/cpuinfo

/proc << this is the golden source of any info you need about processes and
/proc/cpuinfo << is the golden source of any CPU information.

A: Considering your specific sample code snippet that prints information on available CPU cores e.g.
$ cat /proc/cpuinfo | awk '/^processor/{print $3}'

Two approaches
Derive total value based on the highest cpu core id value
Taking an an advantage of the fact that CPU cores have a sequential number attached to them and stored under a processor field. Because of the fact that the information about each individual CPU core stores in proc file is in a list ordered by processor field ascending, you can simply grab the last entry of that sequence and observe the numerical value in the processor field e.g.
$ cat /proc/cpuinfo | awk '/^processor/{print $3}' | tail -n 1

NOTE: Since /proc/cpuinfo holds a number of entries corresponding to the cpus count, a processor field initial value is 0, don't forget to increment the value of the last cpu core by 1.

$ last_cpu_core_id=$(/proc/cpuinfo | awk '/^processor/{print $3}' | tail -n 1)
$ echo $((last_cpu_core_id + 1))

Count number of lines from the output
This approach contrasts with the first one in that, we are not really concerned about a particular value of cpu core id, we just counting output lines. When it comes to counting, the process normally starts from 1 which simplifies our solution.
Using grep
$ cat /proc/cpuinfo | grep processor | wc -l

Alternatively, we shouldn't necessarily remember the processor field per se, but taking an advantage of the fact that each entry describing individual cpu core details is delimited by a newline e.g.
cat /proc/cpuinfo | grep -v '^\w' | wc -l

using awk
cat /proc/cpuinfo | awk '($1 == "processor") {count++ } END { print count }'


text:
Q: How do I get the character pressed in a textarea This is really weird.
I have a textarea.
I listen to the keyup and keypress events.
When I press "(", keypress is fired with e.keyCode == e.which == 40
When I press the arrow down key, keyup is fired with e.keyCode == e.which == 40
Why is this so strange?

A: keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
Char code for "(" is 40 (keypress event) and key code for down arrow is also 40 (keyup).
Try:
String.fromCharCode(40); // "("

A: Traditionally, the arrow keys overlapped ASCII codes, but were represented to the programmer as a two-byte sequence so you were aware that a special key has been pressed.  With the advent of Unicode this is no longer a clean solution.
Browsers have implemented different ways of representing special key input to the Javascript runtime. The details are explained here.
I usually use the 'keydown' event when detecting arrow keys, as this event has the correct keycode attached and will fire with a different keycode(the one for 9) when the user is typing a left parenthesis.  This may not work in cases where you want to allow the user to repeat the keyed event by holding down the arrow key.


text:
Q: How to simulate JavaScript yield? One of the new mechanisms available in JavaScript 1.7 is yield, useful for generators and iterators.
This is currently supported in Mozilla browsers only (that I'm aware of). What are some of the ways to simulate this behavior in browsers where it is not available?

A: Similar to Pointy's answer, but with a hasNext method:
MyList.prototype.iterator = function() { //MyList is the class you want to add an iterator to

    var index=0;
    var thisRef = this;

    return {
        hasNext: function() {
            return index < thisRef._internalList.length;
        },

        next: function() {
            return thisRef._internalList[index++];
        }
    };
};

The hasNext method let's you loop like:
var iter = myList.iterator() //myList is a populated instance of MyList
while (iter.hasNext())
{
    var current = iter.next();
    //do something with current
}

A: For a non-trivial generator function, you will want to use some sort of tool to translate your code to an ES3 equivalent so that it can run in any modern browser. I recommend trying out Traceur, which can roughly be described as an ES6-to-ES3 source translator. Because generators are a language feature destined for ES6, Traceur will be able to translate them for you.
Traceur provides a demo page where you can type ES6 code and see the ES3 generated on the fly. If you enter something as simple as:
// Note that this declaration includes an asterisk, as specified by current ES6
// proposals. As of version 16, Firefox's built-in support for generator
// functions does not allow the asterisk.
function* foo() {
  var n = 0;
  if (n < 10) {
    n++;
    yield n;
  }
}

for (var n of foo()) {
  console.log(n);
}

you will see that the equivalent ES3 code is non-trivial, and it requires traceur.runtime to be included so that the code runs correctly in a browser. The runtime is defined in http://traceur-compiler.googlecode.com/git/src/runtime/runtime.js, which is currently 14K (unminified). This is a non-trivial amount of code, though likely much of it can be optimized away using the Closure Compiler.
Note there is also a bug filed to provide an option to inline the required functions from the traceur.runtime namespace, which would eliminate the need to include runtime.js altogether: https://code.google.com/p/traceur-compiler/issues/detail?id=119.

A: Without some sort of compiler or preprocessor… No.
The closest you can come is something like this:
function doStuff() {
    var result = { };
    function firstStuf() { ...; result.next = secondStuff; return 42; };
    function secondStuf() { ...; result.next = thirdStuff; return 16; };
    function thirdStuf() { ...; result.next = null; return 7; };
    result.next = firstStuff;
    return result;
}

But, well… That's pretty crappy, and really isn't much of a substitute.

A: I have started a little project that tries to do this with some callback trickery. Since it's impossible to create real coroutines in "standard" JavaScript, this doesn't come without a few caveats, e.g:

*

*it's impossible to make this follow the iterator protocol (stuff like .next() etc.),

*it's impossible to iterate through several generators at once,

*you have to watch out not to let the wrong objects leave the generator's scope (e.g. by calling yield in a timeout – since this is "plain" JavaScript, there's no syntax restriction that prevents you from doing this),

*exceptions in the generator are a little tricky,

*and last not least, it's very experimental (just started this a few days ago).

On the bright side, you have yield! :)
The Fibonacci example from the MDC page would look like this:
var fibonacci = Generator(function () {
  var fn1 = 1;
  var fn2 = 1;
  while (1){
    var current = fn2;
    fn2 = fn1;
    fn1 = fn1 + current;
    this.yield(current);
  }
});

console.log(fibonacci.take(10).toArray());

Output:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

The project is on BitBucket at https://bitbucket.org/balpha/lyfe.

A: Well you could always write an outer function that initializes variables in a closure and then returns an object that does whatever work you want.
function fakeGenerator(x) {
  var i = 0;
  return {
    next: function() {
      return i < x ? (i += 1) : x;
    }
  };
}

Now you can write:
var gen = fakeGenerator(10);

and then call gen.next() over and over again.  It'd be tricky to simulate the "finally" behavior of the "close()" method on real generators, but you might be able to get somewhere close.


text:
Q: Función allow="autoplay" no trabaja Tengo un reproductor html5 de una radio online, la idea es que reproduzca de forma automática apenas cargue la web. Probé varios atributos y no funcionan.
Este es el código:

hosting radio ,streaming hosting tv

Agradezco la ayuda, muchas gracias.

A: somos los creadores del player, en usastreams.com, el player en chrome, por su nueva politica, solo trabaja en automatico cuando el asuario le da play un par de veces. en los demas navegadores no hay problema.


text:
Q: MySql.Data.MySqlClient.MySqlException: Visual Studio C# I am really new to coding and I need to resolve an update problem in my project.
I wanted to update data (connected to the database) within datagridview, but it doesn't work and I do get the information about the problem below, but I can't resolve it.
I would really appreciate it if someone has an idea t resolve the issue. Thanks a lot.

MySql.Data.MySqlClient.MySqlException: "You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'Abflug=4, Abflugort='2021-11-23
00:00:00', Ankunft='Aachen-Merzbrück Airport', ' at line 1"

Here is my code:
private void btn_Buchungsuebersicht_update_Click(object sender, EventArgs e)
{
    for (int item = 0; item <= dataGridView_Buchungen.Rows.Count - 1; item++)
    {
        MySqlCommand cmd2 = new MySqlCommand("Update ReserBu set IDKunde=@IDKunde; Abflug=@Abflug, Abflugort=@Abflugort, Ankunft=@Ankunft, Zielort=@Zielort, PAX=@PAX, Catering=@Catering, Flugzeitgesamt=@Flugzeitgesamt, Strecke=@Strecke, Gesamtkosten=@Gesamtkosten, BuFreigegeben=@BuFreigegeben, BuStorno=@BuStorno, Stornierungsgrund=@Stornierungsgrund where IDReserBu=@IDReserBu", conn);
        cmd2.Parameters.AddWithValue("@IDKunde", dataGridView_Buchungen.Rows[item].Cells[0].Value);
        cmd2.Parameters.AddWithValue("@Abflug", dataGridView_Buchungen.Rows[item].Cells[1].Value);
        cmd2.Parameters.AddWithValue("@Abflugort", dataGridView_Buchungen.Rows[item].Cells[2].Value);
        cmd2.Parameters.AddWithValue("@Ankunft", dataGridView_Buchungen.Rows[item].Cells[3].Value);
        cmd2.Parameters.AddWithValue("@Zielort", dataGridView_Buchungen.Rows[item].Cells[4].Value);
        cmd2.Parameters.AddWithValue("@PAX", dataGridView_Buchungen.Rows[item].Cells[5].Value);
        cmd2.Parameters.AddWithValue("@Catering", dataGridView_Buchungen.Rows[item].Cells[6].Value);
        cmd2.Parameters.AddWithValue("@Flugzeitgesamt", dataGridView_Buchungen.Rows[item].Cells[7].Value);
        cmd2.Parameters.AddWithValue("@Strecke", dataGridView_Buchungen.Rows[item].Cells[8].Value);
        cmd2.Parameters.AddWithValue("@Gesamtkosten", dataGridView_Buchungen.Rows[item].Cells[9].Value);
        cmd2.Parameters.AddWithValue("@BuFreigegeben", dataGridView_Buchungen.Rows[item].Cells[10].Value);
        cmd2.Parameters.AddWithValue("@BuStorno", dataGridView_Buchungen.Rows[item].Cells[11].Value);
        cmd2.Parameters.AddWithValue("@Stornierungsgrund", dataGridView_Buchungen.Rows[item].Cells[12].Value);

        conn.Open();
        cmd2.ExecuteNonQuery();
        conn.Close();
    }
    MessageBox.Show("Aenderungen erfolgreich durchgefuehrt");
}


text:
Q: Integrate paypal payment method on magento I'm trying to integrate paypal payment method on a Magento site.  Where can I get the following info.
Paypal Api
Third party permission api username
Thanks for your help.

A: First go to paypal and create a developer account using link
https://developer.paypal.com/developer/accounts/
and go to this link to integrate sandbox
https://www.paypal.com/in/selfhelp/article/how-do-i-integrate-paypal-payments-standard-with-magento-2.0-ts2104


text:
Q: Unity Clock Missing I recently installed ubuntu 12.10 and it seems as though my clock is missing. I also don't see any options for date/time in the system settings panel.

Am I missing something? Again this is with Unity.

A: Open a terminal window (Ctrl+Alt+T), then run the following:
killall unity-panel-service

This command should reset the panel, and hopefully reactivate the clock indicator.

A: This could be one of two things, either the clock isn't installed, or a setting has been flipped to turn it off.
First make sure the clock is installed by making sure indicator-datetime is installed:

Then log out and back in. If it's already installed and it's still not showing up, try the options here:

*

*How to make the date appear next to the time indicator in Gnome Classic?
If that still doesn't work update your question with the results, thanks!

A: As per the comments above I've fixed this issue on my brand new 14.04 LTS installation by running.
$ pkill -f indicator-datetime-service

The clock came straight back.

A: sudo apt-get install indicator-datetime

and logout/login.

A: Worked for me:
sudo apt-get install indicator-datetime
sudo dpkg-reconfigure --frontend noninteractive tzdata
sudo killall unity-panel-service

Reference: https://askubuntu.com/a/357280/25184


text:
Q: How to prove this two variable limit doesn't exist? $\lim_{(x,y) \to (0,0)} \frac{x^2}{x^2-y}$
I set $x = r\cos\theta$, $y=r\sin\theta$, when $(x,y) \to (0,0)$, $r\to0$ and I got $\lim_{r \to 0} \frac{\cos^2\theta}{\cos^2\theta-\sin\theta/r}$ which is undefined.
Is it enough to prove this ?

A: Let $f(x,y)=\frac{x^2}{x^2-y}$. Observe that $f(x,0)=1$ and $f(0,y)=0$. Therefore the limit does not exist.

A: Yes, your approach is enough. Perhaps that it would be better to add that $\theta\notin\pi\mathbb Z$; otherwise, the limit exists.

A: Note that

*

*for $x=0 \implies \frac{x^2}{x^2-y}=0$

*for $x=t \quad y=t^2-t^3 \quad t\to 0^+\implies \frac{x^2}{x^2-y}=\frac{t^2}{t^2-t^2+t^3}=\frac1t\to\infty$