text:
Q: Running cron job manually and immediately with PHP I just wanted to run all my cronjob manually and immediately, following command works well in command line terminal but not working with shell_exec
crontab -l | grep -v '^#' | cut -f 6- -d ' ' | while read CMD; do eval $CMD; done

Can anyone please help me how can I merge this with php, I tried as following but not working:
shell_exec('crontab -l | grep -v "^#" | cut -f 6- -d " " | while read CMD; do eval $CMD; done');

One more thing, I just wants to trigger without bothering about output and waiting.
I have also tried creating shell script: cron.sh and tried: shell_exec('sh cron.sh');
Still no success

A:
I just wanted to run all my cronjob manually and immediately ... I just wants to trigger without bothering about output and waiting.

So why not just leave cron to do what cron does, which is to run jobs when they need to be run and (as far as you're concerned as a User) "without bothering about output and waiting"?
The cron utility is a scheduler, which means that the things that it runs want to be run periodically.
Why do you feel the need to run any of them "immediately"?
Is there any danger in running any of these processes more than once at the same time (the risk you run by trying to do cron's job for it)?
The cron utility runs in the security context of the root user.
PHP does not.
So, in order to get PHP to be able to do [all] the things that cron does, you'd have to give it access to root-level privileges (through sudo).  This is a Bad Idea(TM) unless you very tightly control what your "elevated PHP" is allowed to do and that's just making a maintenance headache for yourself, because such configuration will break whenever you added a new cron job.

A: Are you using this php script whit apache ? In this case you should check if apache has the rights  to exec those crontabs.
Maybe $CMD is not being well parsed, php and bash use the same syntax for the variables... Who is interpreting this?
Also I would recommend you to use the exec function instead, so you can debug a little more with the output and return code.
Good luck!


text:
Q: GOOGLE APP SCRIPT - LinearOptimizationService - Minimization of absolute deltas - Problem Infeasible I am currently setting up an optimization problem that has as objective to define some parameters minimizing the distance from some target parameters, given some fixed constraints
Hi already set up the problem in Excel Solver and works fine, but when I am translating in LinearOptimization services i get infeasible as result of the optimization.
Unfortunately I am not being able to understand if I set up the math for the absolute difference minimization or I simply did some mistakes in translating the model in Google Linear Optimization Services language. I am not being able to explore the details of the model I set up.
Here is the problem statement
i= 1, 2, 3
Variables
Xi
Di
Parameters
target_i
coeff_i
targetvalue
I want to define Xi such that
minimize sum(abs(Di))
Di = target_i-Xi
with the following contraints
Xi is between 0 and 1
sum(Xi)=1
Sum(Xi*coeff_i)=targetvalue
to decline it in Linear Optimization Service i used the equivalent problem:
minimize sum(Di)
with the following contraints
Di >= target_i-Xi
Di <= -(target_i-Xi)
Xi is between 0 and 1
sum(Xi)=1
Sum(Xi*coeff_i)=targetvalue
Here is the the script I wrote to implement it
// test data
  var TargetFrequency=2
  var ActualVolumesByBand=[50,100,1200]
  var AvgDropByBand=[5,15,25]
  var TargetDistribution=[0.25,0.5,0.25]
  var Weight=[2,1,2]
  var NumberOfPeriods=52

  var tolerance=0.0001
  var nBands=ActualVolumesByBand.length
  var engine = LinearOptimizationService.createEngine();

// adds a variable for each distribution band

 for (var i=0; i<nBands; i++)

  {
   engine.addVariable('distance'+i, 0, 10000)
   engine.addVariable('FinalDistribution'+i, 0, 1)
  }

 // set objective coefficients using weight and distance

   for (var i=0; i<nBands; i++)
  {
   engine.setObjectiveCoefficient('distance'+i, Weight[i])
  }

// set problem
  engine.setMinimization()

////Start Setting COntraints

  // define support arrays
  var LowerBound0=new Array
  for (var i=0;i<nBands;i++ )
  {
    LowerBound0[i]=0
  }
  Logger.log(LowerBound0)
  var UpperBound1000=new Array
  for (var i=0;i<nBands;i++ )
  {
    UpperBound1000[i]=10000
  }
  Logger.log(UpperBound1000)

  var C12VariblesArray= []
  for (var i=0;i<nBands;i++ )
  {
    C12VariblesArray[i]=['distance'+i, 'FinalDistribution'+i]
  }

  Logger.log(C12VariblesArray)

  var C1Coefficients=[]
  for (var i=0;i<nBands;i++ )
  {
    C1Coefficients[i]=[1, 1]
  }
  Logger.log(C1Coefficients)

/// Adding fist constraint for absolute value minimization

engine.addConstraints(TargetDistribution, UpperBound1000 ,C12VariblesArray ,C1Coefficients )
//

    var C2Coefficients=[]
  for (var i=0;i<nBands;i++ )
  {
    C2Coefficients[i]=[-1,1]
  }
  Logger.log(C2Coefficients)

// Adding second constraint for absolute value minimization

engine.addConstraints(TargetDistribution, UpperBound1000,C12VariblesArray ,C2Coefficients )

// adding constraint for integrity of distribution

  var C34VariblesArray= []
  for (var i=0;i<nBands;i++ )
  {
    C34VariblesArray[i]='FinalDistribution'+i
  }

  Logger.log(C34VariblesArray)

  var C3Coefficients = []
  for (var i=0;i<nBands;i++ )
  {
    c=1
  }

  Logger.log(C3Coefficients)

  var c3=engine.addConstraint(1, 1)

  for (var i=0;i<nBands;i++ ){
    c3.setCoefficient('FinalDistribution'+i,1 )
  }

// adding constraint for target frequency

// calculate total volume

var TotalVolume=0

  for (var i=0;i<nBands;i++ )
{
    TotalVolume=TotalVolume+ActualVolumesByBand[i]
}

    var C4Coefficients = []
  for (var i=0;i<nBands;i++ )
  {
    C4Coefficients[i]=TotalVolume/NumberOfPeriods/AvgDropByBand[i]
  }

  Logger.log(C4Coefficients)

  var c4=engine.addConstraint(TargetFrequency,TargetFrequency)
  for (var i=0;i<nBands;i++ ){
    c4.setCoefficient('FinalDistribution'+i,C4Coefficients[i] )
  }

  ////Finish setting COntraints

// start solving

var solution = engine.solve();
if (!solution.isValid()) {
  Logger.log('No solution ' + solution.getStatus());
} else {
   for (var i=0;i<nBands;i++ )
  {
    Logger.log('Value of band '+i+': ' + solution.getVariableValue('FinalDistribution'+i));
  }
}

Could you help me understand where is the mistake?

A: I did not look at the source code, but I saw a problem in your description. You write:
minimize sum(Di)
with the following contraints
Di >= target_i-Xi
Di <= -(target_i-Xi)

This looks incorrect. The math is usually derived as:
min sum(i, |target(i)-X(i)|)

<=>

min sum(i, d(i))
-d(i) <= target(i)-X(i) <= d(i)

<=>

min sum(i, d(i))
d(i) >= target(i)-X(i)
d(i) >= -(target(i)-X(i))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Image not picking up CSS class I've saved down my HTML / CSS files on my desktop (all working as expected). When I upload to host (Site Ground) once of my CSS rules seems not to be working.
Class painting4 should be strinking one of my images "images/painting8.jpg" but it doesn't appear to be working (The image appears in full size and when I view source code the class is not picked up.
Any ideas where I'm going wrong?

/************** Navigation Styles **************/

nav li {
  list-style: none;
  display: inline;
  padding: 10px 30px;
  border-right: solid 1px rgba(255, 255, 255, 0.5);
  color: rgba(255, 255, 255, 0.5);
  text-align: center;
  margin: 0 auto;
  font-size: 1.3em;
}

nav img {
  display: inline;
  float: left;
  padding: 6px;
  margin-left: 16px;
  margin-top: 6px;
  Margin-bottom: 6px;
}

* {
  font-family: arial;
}

.logo {
  width: 40px;
}

nav ul {
  padding: 0;
}

.last_of_nav {
  border-right: none;
  padding-right: none;
  margin-right: 70px;
}

#nav {
  text-align: center;
  background-color: black;
}

#wrapper a:hover {
  background-color: CadetBlue;
  width: 100%;
}

/********************** Element Selectors ************************/

body {
  margin: 0;
  background-color: white;
}

nav {
  background-color: #4682b4;
  padding: 1px;
  margin: 0 auto;
  width: 100%;
  text-align: center;
}

nav ul li a {
  padding: 15px 45px;
  width: 100%;
}

a {
  text-decoration: none;
}

#graduation-logo {
  width: 40px;
  height: 40px;
  margin-left: 10px;
  padding: 0;
  margin-top: 5px;
}

.year {
  color: CadetBlue;
}

/******** pseudo selectors *********/

nav a:visited {
  text-decoration: none;
  color: rgba(255, 255, 255, 0.5);
}

nav li a:hover {
  color: white;
}

nav li a:active {
  color: white;
  background-color: CadetBlue;
}

nav a:link {
  text-decoration: none;
  color: rgba(255, 255, 255, 0.5);
}

* {
  box-sizing: border-box;
}

nav img:hover {
  background-color: CadetBlue;
}

nav li a:hover,
a.selected {
  color: white !important;
  background-color: CadetBlue;
}

/****** Home Page ******/

.profile_picture {
  border-radius: 40%;
  float: ;
  margin-left: 35%;
  margin-right: 35%;
  margin-bottom: 5%;
  width: 30%
}

.secondary-cv-content-wrapper div {
  display: inline;
}

/****** Main body ******/

.main-content {
  background-color: white;
  width: 50%;
  margin-left: 10%;
  margin-right: 0;
  float: left;
}

.main-content-home {
  width: 50%;
  margin-left: 25%;
  margin-right: 25%;
}

.main-content-wrapper-home {
  background-color: rgba(211, 211, 211, 0.4);
  height: auto;
  width: 100%;
  padding-bottom: 30px;
}

.intro {
  width: 90%;
  text-align: justify;
  margin: 1px auto;
  line-height: 30px;
  font-size: 1em;
}

.main-content-wrapper h1 {
  font-family: arial;
  padding: 5px;
}

.main-content-wrapper {
  background-color: rgba(211, 211, 211, 0.4);
  height: auto;
  width: 100%;
  padding-bottom: 30px;
  margin-bottom: 40px;
}

.main-content-wrapper h1,
.main-content-wrapper-home h1 {
  font-size: 40px;
  text-align: center;
  margin-top: 35px;
  padding-top: 10px;
}

.contact {
  text-align: center;
}

.contact_list {
  list-style: none;
  margin: 10px 10px;
  padding: 0;
  text-align: center;
}

.main-cv-content h4 {
  text-align: center;
}

.secondary-cv-content {
  width: 25%;
  margin-right: 10%;
  margin-left: 5%;
  float: right;
  margin-top: 35px;
}

.secondary-cv-content-wrapper {
  padding: 10px;
  background-color: white;
  padding-left: 30px;
  border: solid 2px rgba(211, 211, 211, 0.7);
}

.secondary-cv-content-wrapper h2,
.third-content-wrapper h2,
.fourth-content-wrapper h2,
.year,
h1,
.portfolio-first-content h2,
.painting2box h2 {
  color: #4682b4;
  text-align: center;
}

.secondary-cv-content-wrapper ul {}

.third-content {
  float: right;
  width: 25%;
  margin-right: 10%;
  margin-top: 35px;
}

.third-content-wrapper {
  border: solid 2px rgba(211, 211, 211, 0.7);
  padding: 10px 30px;
}

.third-content-wrapper a {
  display: inline;
}

.third-content-wrapper img {
  margin: 0px 0px;
  width: 50%;
  float: left;
  height: 140px;
  display: inline;
}

.third-content-wrapper h1 {
  margin: 0px 0px;
  width: 50%;
  float: left;
  height: 140px;
}

.fourth-content-wrapper {
  border: solid 2px rgba(211, 211, 211, 0.7);
  padding: 10px 30px;
  padding-bottom: 30px;
  text-align: center;
}

.fourth-content {
  float: right;
  width: 25%;
  margin-right: 10%;
  margin-top: 35px;
}

.secondary-cv-content-wrapper p {
  background-color: grey;
}

.portfolio-first-content {
  width: 60%;
  margin: 30px 20%;
}

.portfolio-first-content #main-painting2 {
  width: 100%;
  margin-bottom: 10px 10%;
}

.second-row-images img {
  width: 50%;
  float: left;
  margin: 10px 0;
  height: 430px;
}

#main-painting3 {
  width: 50%;
  float: left;
}

.main-painting4 {
  width: 50%;
  float: left;
}

/***** line Height ******/

p {
  line-height: 140%;
}

.painting2box {
  width: 15%;
  margin: 0 2.5%;
  display: inline-block;
}

/* Main footer */

.main-footer {
  border-top: solid 2px rgba(211, 211, 211, 0.7);
  margin-top: 50px;
  background-color: none;
  text-align: center;
  padding: 3px;
  clear: both;
  font-size: 1em;
  width: 100%;
  margin-top: 100px;
  position: relative;
}

.main-cv-content {
  padding: 15px;
  line-height: 140%;
}

.secondary-content {}

/****** Media Queries *****/

@media (max-width:950px) {
  .profile_picture {
    width: 50%;
    float: none;
    position: center
  }
  .main-content img {
    margin: 10px 25%;
  }
}

@media (max-width:500px) {
  .profile_picture {
    width: 60%;
    float: none;
    box-sizing: border-box;
  }
  .main-content {
    padding: 10%
  }
  .main-content {
    width: 80%;
  }
}

 Paintings


text:
Q: Ram and cpu estimates for virtual Private server I want to transfer my website from a shared hosting to VPS. Since on a shared hosting I can not see the RAM(or CPU) usage stats, and I never used VPS or dedicated servers, so, I am not sure, what parameters to choose. My website has
1) about 350-400 thousand pageviews a month
2)~ 30 GB bandwith a month.
3) It is a usual php/mysql website. Queries are very simple. There are no joins or other  complicated queries. The main page, that is viewed the most(perhaps > 95%) contains one simple query, SELECT id, name FROM posts WHERE name = "something". Table has ~ 150 K rows, and name column is indexed. That main page's(with most views) content is a simple text.
4) There are about 5-12 external css/js files to load.
Here, is the VPS params that Iam thinking to take(based on the price)
256MB RAM
256MB VSwap
1 CPU Core Access
20 GB SSD - [this one is all right]

Will this be about right? I know that it is very broad question, but if you can gimme some rough estimates, it will be enough.
Thanks


text:
Q: Javascript - get strings inside a string var str = '

            ...

text

            ...

';

I got a long string stored in var str, I need to extract the the strings inside div part="1". Can you help me please?

A: you could create a DOM element and set its innerHTML to your string.
Then you can iterate through the childNodes and read the attributes you want ;)
example
var str = "<your>";

var node = document.createElement("div");
node.innerHTML = str;

for(var i = 0; i < node.childNodes.length; i++){
   console.log(node.childNodes[i].getAttribute("part"));
}

A: If you're using a library like JQuery, this is trivially easy without having to go through the horrors of parsing HTML with regex.
Simply load the string into a JQuery object; then you'll be able to query it using selectors. It's as simple as this:
var so = $(str).find('.so');

to get the class='so' elememnt.
If you want to get all the text in part='1', then it would be this:
var part1 = $(str).find('[part=1]').text();

Similar results can be achieved with Prototype library, or others. Without any library, you can still do the same thing using the DOM, but it'll be much harder work.
Just to clarify why it's a bad idea to do this sort of thing in regex:
Yes, it can be done. It is possible to scan a block of HTML code with regex and find things within the string.
However, the issue is that HTML is too variable -- it is defined as a non-regular language (bear in mind that the 'reg' in 'regex' is for 'regular').
If you know that your HTML structure is always going to look the same, it's relatively easy. However if it's ever going to be possible that the incoming HTML might contain elements or attributes other than the exact ones you're expecting, suddenly writing the regex becomes extremely difficult, because regex is designed for searching in predictable strings. When you factor in the possibility of being given invalid HTML code to parse, the difficulty factor increases even more.
With a lot of effort and good understanding of the more esoteric parts of regex, it can be done, with a reasonable degree of reliability. But it's never going to be perfect -- there's always going to be the possibility of your regex not working if it's fed with something it doesn't expect.
By contrast, parsing it with the DOM is much much simpler -- as demonstrated, with the right libraries, it can be a single line of code (and very easy to read, unlike the horrific regex you'd need to write). It'll also be much more efficient to run, and gives you the ability to do other search operations on the same chunk of HTML, without having to re-parse it all again.


text:
Q: Extracting information from input elements in an xml format Here is an example of the input text tags in xml,
<Root>
  <Items>
    <Content>
      <ContentControl>
        <Grid>
          <Image Tag="And" ToolTip="And"/>
          <TextBox Tag="Num1">12</TextBox>
          <TextBox Tag="Num2">15</TextBox>
        </Grid>
      </ContentControl>
    </Content>
    <Content>
      <ContentControl>
        <Grid>
          <Image Tag="Button Pressed" ToolTip="Button Pressed"/>
          <ComboBox IsDropDownOpen="False" Text="4" Tag="Num2">
            <ComboBoxItem>0</ComboBoxItem>
            <ComboBoxItem>1</ComboBoxItem>
            <ComboBoxItem>2</ComboBoxItem>
            <ComboBoxItem IsSelected="True">4</ComboBoxItem>
          </ComboBox>
        </Grid>
      </ContentControl>
    </Content>
  </Items>
</Root>

I need to read the inputs entered into the text boxes and combo boxes individually using C#.
How can I determine which input element is which from reading the tags attached to them ?and how do I extract the data from the textbox and combobox inputs respectively, once I have determined the input data I want to extract?
For example, from the text box tagged 'Num1', I want to extract the value 12 and from the combo box from the selected item I want to extract the value 4.

A: I am not sure I understand the ultimate goal you're trying to achieve.
Anyway, this demonstrates how to achieve what mentioned in "For example" section of this question. This use XDocument and XPath query to select value 12 from the text box tagged 'Num1' and value 4 from combo box selected item :
var doc = XDocument.Load("path_to_xml_file.xml");
var textBoxValue
    = (string) doc.
                XPathSelectElement("/Root/Items/Content/ContentControl/Grid/TextBox[@Tag='Num1']");
var comboBoxValue
    = (string)doc
                .XPathSelectElement("/Root/Items/Content/ContentControl/Grid/ComboBox[@Tag='Num2']/ComboBoxItem[@IsSelected='True']");

UPDATE :
in case you have default namespace declared somewhere in the XML, the XML element where default namespace declared and all it's descendants considered in default namespace. But in the other side, all elements in XPath query having no prefix considered has no namespace.
So to bridge that difference, you need to

*

*add prefix declaration pointing to default namespace url

*add that prefix to an XmlNamespaceManager

*use that prefix when selecting elements in default namespace

*and pass the XmlNamespaceManager as second parameter of XPathSelectElement method

For example, assuming that default namespace declared from <Root> element  :
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("ns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
var textBoxValue
    = (string)doc.
                XPathSelectElement(
                    "/ns:Root/ns:Items/ns:Content/ns:ContentControl/ns:Grid/ns:TextBox[@Tag='Num1']"
                    , namespaceManager);


text:
Q: VBA Disable alert/dialog box when ... (Application.DisplayAlerts = False does not work)
Hi, solution to my problem with this warning dialog box is not Application.DisplayAlerts = False/true
and can not find correct way to disable this alert. Can you help me please
(all options are set correctly?  i tried also enabled macros)

A: As @R3uK said, you need to chose Enable all macros instead of Disable all macros with notification which throws you that notification. And when you have macros disabled then application.DisplayAlerts = false isnt executed and then not working.


text:
Q: Python code for Duplication matrices I was looking for a resource/code/script in python for forming duplication matrices but surprisingly it still evades me. The wiki page gives a pseudo-code for generating this 'unique' duplication matrix of size $N^2 \times N(N+1)/2$ for a symmetric matrix of size $N$.
Basically, I want matrix $D$ such that for an symmetric matrix $A \in \mathbb{R}^{N \times N}$,
$$D \: \text{vech}(A) = \text{vec}(A)$$
where vec and vech denote vectorization and half-vectorization, respectively.
Here is what I could manage from the wiki page
import numpy as np
def duplication_matrix(N):
    # source: https://en.wikipedia.org/wiki/Duplication_and_elimination_matrices
    N_bar = int(N * (N + 1) / 2.)
    # duplication matrix initialization
    D = np.zeros((N ** 2, N_bar))

    for ii in range(N):
        for jj in range(N):
            if jj <= ii:
                u_ij = np.zeros((N_bar, 1))
                tmp_idx = int(jj * N + ii + 1. - ((jj + 1.) * jj) / 2.) - 1
                u_ij[tmp_idx] = 1.
                T_ij = np.zeros((N, N))
                T_ij[ii, jj] = 1.
                T_ij[jj, ii] = 1.

                tmp = u_ij.dot(vectorize(T_ij).reshape((N ** 2, 1)).transpose())
                D += tmp.transpose()

    return D

You might find the indexing a bit difference corresponding to variable tmp_idx compared to what is given on the wiki page but it is done just to account for the indexing in python which starts from $0$.
Problem is that it apparently worked for $N=2$. I tried it with $N = 4$ but it didn't yield the right result. Before I dive into creating something by myself, I wanted to know if someone has already done it as it is surprising to me that this is not readily available.
Edit: I was trying to do something proper from this post but there were inconsistencies with the notation. So, I have created a hackey answer that solves my problem. But I will still appreciate a proper answer!

A: This is a hackey way of doing this, but basically, I created a list of all alphabets (as I needed something unique to keep track of entries) and created a chararray of size $N \times N$. Then just by comparing the entries of the vectorized and half-vectorized entities, I can create the duplication matrix, $D$. Here it goes:
import numpy as np
def duplication_matrix_char(N):
    N_bar = int(N * (N + 1) / 2.)

    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
           'v', 'w', 'x', 'y', 'z']
    idx = np.triu_indices(N)

    # duplication matrix initialization
    D = np.zeros((N ** 2, N_bar))
    D_char = np.chararray((N, N))

    for ii in range(N_bar):
        D_char[idx[0][ii], idx[1][ii]] = letters[ii]
        D_char[idx[1][ii], idx[0][ii]] = letters[ii]

    # vectorizing D_char
    for kk in range(N):
        vecD_char[kk * N: (kk + 1) * N] = D_char[:, kk].reshape((N, 1))

    # half vectorize D_char
    vechD_char = np.chararray((N_bar, 1))
    idx_l = np.tril_indices(N)
    for mm in range(N_bar):
        vech[mm, 0] = D_char[idx_l[0][mm], idx_l[1][mm]]

    for jj in range(N ** 2):
        idx = np.where(vechD_char == vecD_char[jj])
        D[jj, idx[0]] = 1.

    return D

As there are $26$ alphabets, you can create till $N = 6$. You can easily extend this for any $N$ as long as you have $N(N+1)/2$ unique letters!

A: I worked on this years ago and came up with the following
Julia function
function duplication(n)
   i = collect(1:n*n)
   J = zeros(Int, n,n)
   z = 1
   for x = 1:n
     for y = x:n
       J[x,y] = J[y,x] = z  # duplication occurs here
       z += 1
     end
   end
   # pass 3 vectors {i-index, j-index, value} to sparse()
   return sparse(i, vec(J), 1)
end

I also wrote a function based on the Wikipedia pseudo-code
function wiki_duplication(n)
   p = div(n*(n+1),2)
   A,D,u = zeros(Int,n,n), zeros(Int,n*n,p), zeros(Int,p,1)
   for i = 1:n
      for j = 1:i
         # use "." syntax to avoid reallocating the matrices
         A .= 0
         u .= 0
         ndx = i + (j-1)*n + div(j-j*j,2)
         A[i,j] = A[j,i] = u[ndx] = 1
         D += vec(A)*u'
      end
   end
   return D
end

This also works but is orders of magnitude slower than the first function.
Translating them into Python/NumPy shouldn't be terribly difficult.


text:
Q: Was Nagini Technically an Inferius When She Possessed Bathilda Bagshot's Body? J.K. Rowling writes in Tales of Beedle the Bard that Inferi are simply  corpses reanimated by Dark Magic and she describes them as "ghastly puppets" that are not sentient.
Nagini was a Horcrux, which is Dark Magic. She occupied and ambulated Bathilda Bagshot's corpse. Does this in any way make Nagini either partially or fully an Inferius, or was she just the magical component or catalyst for the reanimation of Bathilda's body? Or was Voldemort the one controlling Bathilda's corpse instead of Nagini?
In this instance I'm actually confused whether either Bathilda or Nagini was technically an Inferius — were they?

A: No - Bathilda's corpse was "animated" by Nagini in it, not magic.
An Inferius is a corpse reanimated by magic. Bathilda's corpse was not animated by magic, it was animated by Nagini being inside it. The corpse only seems to be moving because Nagini was moving it, and it was incapable of doing anything that she couldn't do, like cast spells or speak English. "Bathilda" was able to speak, but only in Parseltongue. It's fairly clear from its behavior that Nagini is in control of the actions the Bathilda-corpse takes. She lures Harry away to converse in Parseltongue without him knowing, is told by the Dark Lord to keep Harry from leaving, then bursts out of the corpse to obey his command.

"Then she closed her eyes and several things happened at once: Harry's scar prickled painfully; the Horcrux twitched so that the front of his sweater actually moved; the dark, fetid room dissolved momentarily. He felt a leap of joy and spoke in a high, cold voice: hold him!"
"And in the instant that he looked away, his eyes raking the tangled mess for a sword hilt, a ruby, she moved weirdly: he saw it out of the corner of his eye; panic made him turn and horror paralysed him as he saw the old body collapsing and the great snake pouring from the place where her neck had been." - Harry Potter and the Deathly Hallows, Chapter 17 (Bathilda's Secret)

She's able to contact the Dark Lord, tell him Harry was there, and obey his command to her.

"She didn't want to talk in front of you, because it was Parseltongue, all Parseltongue, and I didn't realise, but of course, I could understand her. Once we were up in the room, the snake sent a message to You-Know-Who, I heard it happen inside my head, I felt him get excited, he said to keep me there … and then …" - Harry Potter and the Deathly Hallows, Chapter 17 (Bathilda's Secret)

For comparison, Professor Snape defines an Inferius as a corpse reanimated by a Dark wizard's spells. Bathilda's corpse was used as a puppet, but was not reanimated by spells.

"The Inferius is a corpse that has been reanimated by a Dark wizard's spells. It is not alive, it is merely used like a puppet to do the wizard's bidding." - Harry Potter and the Half-Blood Prince, Chapter 21 (The Unknowable Room)

Once reanimated, Inferi can "function" on their own. However, Bathilda's corpse collapsed to the floor, inactive, once Nagini came out of it.
Therefore, it seems most logical from the evidence that Nagini just wore Bathilda's corpse as a disguise, like an outer shell to conceal herself, rather than the corpse being an Inferius or itself reanimated.

A: I'm going to Yet Again have to steal TGnat's excellent comment since he declined to post it as an answer.
Nagini was NOT dead at the time, so she/it was definitely NOT an Inferi.

Bathilda's status is unclear - I don't think she was a reanimated corpse; the DH text seems to support the notion that it was NOT a reanimated dead body but merely a skin/puppet which Nagini was inside of:

panic made him turn and horror paralyzed him and he saw the old body collapsing and the great snake pouring from the place where he neck had been
...
"Bathilda must've been dead a while. The snake was . . . was inside her. You-Know-Who put it there in Godric's Hollow, to wait. [Harry to Hermione, after the escape]
...
He remembered the snake coming out of Bathilda's neck; Hermione did not need to know the details.
" . . . she changed, changed into the snake, and attacked."

A: Nagini I believe is old Hindustani for the snake queen or something. Kipling uses the word in both male and female form in Rikki tikki tavi. Nag and Nagini were cobras and the antagonists of the garden against whom the mongoose hero struggled. I'm not sure how the Bagshot/nagini puppet thing works exactly but I'm pretty sure Nagini is alive and not inferi as killing the snake is discussed at length and Neville does the dead at the battle of Hogwarts (10 points for Gryfindor). The snake/historian  whispers only to harry because only harry speaks parsletongue and is unable to discern the difference between it and human-speak. Hermione would have noticed..that bit is clever..

A: No, it was not an Inferi.
The body of the woman Harry and Hermione has seen was merely an illusion that looked like Bathilda.  Harry was misled and did not recognize this – that was the whole point of the illusion.  The actual body of Bathilda was not involved at all, and is likely lying in a grave undisturbed.
See my answer for How come Nagini had magical powers? where I argue that the snake Horcrux creates such an illusion, just like how the diary and locket Horcruxes had created convincing illusions before that.
Update 2018-09-26: Apparently the Fantastic Beasts film series will elaborate on Nagini and his imitating Bathilda Bagshot, with an explanation possibly contradicting the above.  The recent question "Was Nagini the only snake which could become human?" "Recently launched trailer of Fantastic Beast 2: Crimes of Grindelwald has proved that being Animagus (I don't have proper word) was Nagini's inherent quality, not something assisted by Voldemort when she had became Bathilda Bagshot" called my attention to this.  The answer "Not an Animagus. A Maledictus. Big difference. - J. K. Rowling on Twitter" contains words directly from J. K. Rowling.

A: I'd like to think Voldemort killed Bathilda, created polyjuice potion using her hair and left a large pot for Nagini to drink whenever she thought Harry would enter or saw him from the window. Then the effects wore off and she attacked them.


text:
Q: An application launched from script has no icon I use an application (Simplify3D for example) which is a binary launched by bash script.
The GUI is created by the binary, while the .desktop file points to the script.
For this reason I do have an icon on the Desktop launcher and in the lens, but do not have an icon in the Unity Launcher - just a grey box with a question mark.
How can I make the icon visible in the launcher too?
The .desktop file contents is
[Desktop Entry]
Type=Application
Version=0.9.4
Name=Simplify3D
Comment=Simplify3D Software
Icon=/opt/Simplify3D/icon.png
Exec=/opt/Simplify3D/LaunchScript.sh
Terminal=false
Path=/opt/Simplify3D
StartupWMClass=Simplify3D // That line fixed it

A: In these "indirect" cases, you have to tell the desktop file what application it is connected to:
Add a line to your .desktop file, like:
StartupWMClass=[your_application] (the binary file in this case)

also pointed out here.


text:
Q: Lotus Notes XPinC DateTime format issue I am working on a XPage application which will work on both web and client. There is an action which will adjust the date object to 20 days and store it again in the current document. I got an issue, that the code is working perfectly on web and win-xp OS XPinC. I found that there is an issue with win-7 XPinC. And compare with two different win7 machine for the same document. But working on PC but not in another. Finally concluded with that the issues is due to the current machines datetime settings. But I cannot go and check/change all the pc's datetime format. Please advice how can I handle this.
Thanks in advance.

A: This has been doing my head in for several days.
Xpages works great in my browser, but the date/time is all screwed up when viewed in LN.
The solution is to go into "File" -> "Preferences" and then "Regional Settings".
Change "Content Language" from "English" to "English (United Kingdom)".
A pet hate of mine is that most computers default to the crazy US way of displaying the date, i.e. month/day/year when the rest of the world uses day/month/year.


text:
Q: Map applications I have no clue why the following piece of code is giving null pointer exception.Please help!
This is the MapActivity.class.
    package com.dutt.rishabh.locator;

    import android.Manifest;
    import android.content.pm.PackageManager;
    import android.graphics.Color;
    import android.location.Address;

    import android.location.Geocoder;

    import android.net.http.AndroidHttpClient;

    import android.support.v4.app.ActivityCompat;
    import android.support.v4.app.FragmentActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    EditText start, finish;
    Button bsearch, btype;
    String source, destiny,url;
    List<LatLng> lines=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        start = (EditText) findViewById(R.id.start);
        finish = (EditText) findViewById(R.id.finish);
        bsearch = (Button) findViewById(R.id.bsearch);
        btype = (Button) findViewById(R.id.btype);
        start.setText(R.string.source);
        finish.setText(R.string.destiny);
        source = start.getText().toString();
        destiny = finish.getText().toString();
        Geocoder geocoder=new Geocoder(this);
        List<Address> x=null;
        List<Address> y=null;
        try {
            x=geocoder.getFromLocationName(source,1);
            y=geocoder.getFromLocationName(destiny,1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Address origin,destination;
        origin=x.get(0);
        destination=y.get(0);
        url="http://maps.googleapis.com/maps/api/directions/json?origin="
                + origin.getLatitude() + "," + origin.getLongitude() +"&destination="
                + destination.getLatitude() + "," + destination.getLongitude() + "&sensor=false";
        changeMapType();
        JSONObject result = null;
        try {
            result = new JSONObject(fetchData());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONArray routes = null;
        try {
            routes = result.getJSONArray("routes");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            long distanceForSegment = routes.getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getInt("value");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONArray steps = null;
        try {
            steps = routes.getJSONObject(0).getJSONArray("legs")
                    .getJSONObject(0).getJSONArray("steps");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        lines = new ArrayList<LatLng>();

        for(int i=0; i < steps.length(); i++) {
            String polyline = null;
            try {
                polyline = steps.getJSONObject(i).getJSONObject("polyline").getString("points");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            for(LatLng p : decodePolyline(polyline)) {
                lines.add(p);
            }
        }

    }
    private List<LatLng> decodePolyline(String encoded) {

        List<LatLng> poly = new ArrayList<LatLng>();

        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((double) lat / 1E5, (double) lng / 1E5);
            poly.add(p);
        }

        return poly;
    }
    public String fetchData(){
        HttpResponse response = null;
        HttpGet request;
        AndroidHttpClient client = AndroidHttpClient.newInstance("somename");

        request = new HttpGet(url);
        try {
            response = client.execute(request);
        } catch (IOException e) {
            e.printStackTrace();
        }

        InputStream source = null;
        try {
            source = response.getEntity().getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String returnValue = buildStringIOutils(source);

        return returnValue;

    }

    private String buildStringIOutils(InputStream is) {
        try {
            return IOUtils.toString(is, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void changeMapType() {
        btype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mMap.getMapType() == mMap.MAP_TYPE_NORMAL) {
                    mMap.setMapType(mMap.MAP_TYPE_HYBRID);
                } else {
                    mMap.setMapType(mMap.MAP_TYPE_NORMAL);
                }
            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng bangalore = new LatLng(12.9716, 77.5946);
        mMap.addMarker(new MarkerOptions().position(bangalore).title("Marker in Bangalore"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(bangalore));
        mMap.setBuildingsEnabled(true);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mMap.setMyLocationEnabled(true);
        Polyline polylineToAdd = mMap.addPolyline(new PolylineOptions().addAll(lines).width(3).color(Color.RED));

    }

}

The following is the logcat error.
07-23 13:43:36.300 11999-11999/com.dutt.rishabh.locator E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.dutt.rishabh.locator, PID: 11999
                                                                          java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dutt.rishabh.locator/com.dutt.rishabh.locator.MapsActivity}: java.lang.NullPointerException
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
                                                                              at android.app.ActivityThread.access$900(ActivityThread.java:151)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                              at android.os.Looper.loop(Looper.java:193)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5345)
                                                                              at java.lang.reflect.Method.invokeNative(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:515)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
                                                                              at dalvik.system.NativeStart.main(Native Method)
                                                                           Caused by: java.lang.NullPointerException
                                                                              at com.dutt.rishabh.locator.MapsActivity.onCreate(MapsActivity.java:75)
                                                                              at android.app.Activity.performCreate(Activity.java:5343)
                                                                              at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
                                                                              at android.app.ActivityThread.access$900(ActivityThread.java:151)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                              at android.os.Looper.loop(Looper.java:193)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5345)
                                                                              at java.lang.reflect.Method.invokeNative(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:515)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
                                                                              at dalvik.system.NativeStart.main(Native Method)

I have no clue why it is giving a null pointer exception.Please help.Thank you!


text:
Q: When is the linuxProfile Property needed in Azure Resource Manager? I am currently writing an ARM (Azure Resource Manager) template that creates a Kubernetes cluster. Therefore I am using the templates of existing clusters to compare if I am missing anything. This way I discovered that one of my existing Kubernetes clusters (created in the portal) has the linuxProfile property (as shown below) while the other does not. Now I can not seem to figure out for what exactly I need this user. I can create and use a new cluster with or without this property.
Does anyone know when I need this user and if there are any security vulnerabilities if I do not use it (maybe because of missing ssh)?
The documentation does not help with this, as it only says that this is the administrator for Linux VMs. But it does not specify which VMs are meant (maybe the Kubernetes Nodes? Where would I need a user for them)?
The Kubernetes ARM Quickstart guide also has this property but does not explain it in more depth.
...
"properties": {
...
                "linuxProfile": {
                    "adminUsername": "azureuser",
                    "ssh": {
                        "publicKeys": [
                            {
                                "keyData": "ssh key"
                            }
                        ]
                    }
                }
}
...

A: Most time, you don't need to add this property. It's used to set the user and the SSH Public Keypair when you want to SSH into the nodes to take a check or do something you want. Here is an example. At this time, you need to deploy the extension to add the SSH Key. So you don't need to add the property, if you need, deploy the extension, it also works.


text:
Q: Where does the Guest Session store its configuration files In my computer I have my account (cyrex) and the guest session. If my user cyrex stores its files in /home/cyrex where does the guest session store its files?. For example, if I wanted to set the guest in a way so that when it loads it has a specific Wallpaper, Launcher icon size and any other customization I would want to do with it.

A: In /tmp/guest-[xxxxxx], where the x's are a string of letters and numbers. That folder contains all the normal home folders for a user.
The guest account is managed by lightdm through /usr/sbin/guest-account, which is a shell script. After setting up the guest account, the script will run a preferences script if it exists: /etc/guest-session/prefs.sh
A convenience set of scripts to make this process easier, along with some explanation of how to use them, can be found at CustomizeGuestSession.
The basic settings you can change are:
Firefox preference settings
Disabling the login-sound
gettexted strings
Set a Folder for storing files permanently
Show an Info dialog at startup
Set an Icon on the desktop
Set the guest account language and keyboard

I haven't tested everything, but after using it a few times things seems to work well and seem easy to modify. I figured changing the language had the most potential for bugs, but I set the guest language to Chinese and it worked great.
Some things need to be added, such as changing the background.
There are two main files prefs.sh, which runs as root and then calls auto.sh, which runs as the guest user, as it finishes.
Features can be added to either file as appropriate. To change the wallpaper I added the following line to auto.sh.
gsettings set org.gnome.desktop.background picture-uri "file:///usr/share/backgrounds/Leftover_by_Sagar_jain.jpg"

Launcher icon size was a little trickier since it is a relocatable schema and DConf Editor says it has No schema, but the command is:
gesettings set org.compiz.unityshell:/org/compiz/profiles/unity/plugins/unityshell/ icon-size 32

Thanks to @dobey for an explanation of using relocatable schemas.
The original scripts were posted on the Ubuntu Forums by Gunnar Hjalmarsson.

A: I just rewrote the tutorial Customize Guest Session. The main approach in the new tutorial - making use of a special purpose user account - is a more convenient way to customize the guest session feature.


text:
Q: Need help fixing 'ArrayIndexOutOfBoundsException' As described in the title i get ArrayIndexOutOfBoundsException when i start my Tomcat 7 with NetBeans 8.2.
I've tried troubleshooting with those two threads without any success:
ArrayOutOfBoundsException: asm.ClassReader.readClass(Unknown Source)
Failed to load ApplicationContext caused by ArrayIndexOutOfBoundsException in ClassReader
The exception seems to be caused by org.springframework.asm.ClassReader.readClass
or DienststellenController.class
Caused by: java.lang.ArrayIndexOutOfBoundsException: 52264
at org.springframework.asm.ClassReader.readClass(Unknown Source)
at org.springframework.asm.ClassReader.accept(Unknown Source)
at org.springframework.asm.ClassReader.accept(Unknown Source)

[Path\DienststellenController.class]; nested exception is
java.lang.ArrayIndexOutOfBoundsException: 52264

When i run my project with those four lines commented out, it works like a charm without any exceptions:
@RequestMapping(value = "/query", method = RequestMethod.GET)
public ModelAndView queryGet(HttpServletRequest request) {
    logger.debug("Received request to show a input form page");
    List<Person> personListe = personDao.getPersonalStamm();
    //List<String> ls = new ArrayList<>();
    Dienststelle d = (Dienststelle) request.getSession().getAttribute("dienststelle");
        if (d == null) {
        d = new Dienststelle();
    }
    ModelAndView mv = new ModelAndView("phonebook/dienststelle/query", "dienststelle", d);
    //personListe.forEach((p) -> {
    //    ls.add(p.getAnzeige());
    //});
    mv.addObject("person", personListe);
    return mv;
}

Controller
@RequestMapping(value = "/query", method = RequestMethod.GET)
public ModelAndView queryGet(HttpServletRequest request) {
    logger.debug("Received request to show a input form page");
    List<Person> personListe = personDao.getPersonalStamm();
    List<String> ls = new ArrayList<>();
    Dienststelle d = (Dienststelle) request.getSession().getAttribute("dienststelle");
        if (d == null) {
        d = new Dienststelle();
    }
    ModelAndView mv = new ModelAndView("phonebook/dienststelle/query", "dienststelle", d);
    personListe.forEach((p) -> {
        ls.add(p.getAnzeige());
    });
    mv.addObject("person", ls);
    return mv;
}

Method from dao class
@Override
public List<Person> getPersonalStamm() {
    String sql = "SELECT * FROM personalDB.personalstamm";
    RowMapper<Person> rm = ParameterizedBeanPropertyRowMapper.newInstance(Person.class);
    List<Person> personen = (List<Person>) getJdbcTemplate().query(sql, rm);
    return personen;
}

jsp page

        Vorgesetzter

            <form:select path="verantwortlich" maxlength="11" >
                <form:option value="0" label="-"/>
                <form:options items='${person}' itemValue='name' itemLabel='name' />
            </form:select>


text:
Q: If a table is partitioned by a single column should that column be included in index definitions? Elaborate:
CREATE TABLE TEST(
  school_year DATE,
  B VARCHAR2(12),
  C VARCHAR2(15),
  D NUMBER
)

And the table is already partitioned on column school_year.  Should column school_year be part of the index definition?  The most frequently executed query would be:
WHERE school_year = TO_DATE('06/30/2014', 'MM/dd/yyyy')
and B = '020100001000'
and D = 3

Should the index be:
CREATE INDEX IDX_SAMPLE (SCHOOL_YEAR, B, D)

or
CREATE INDEX IDX_SAMPLE (B, D)


text:
Q: KnpDoctrineBehaviors, how to use Sluggable with Translatable I use KnpDoctrineBehaviors (Sluggable,Translatable, etc ). Field that I use for slug, I have only in  MyClassTranslations. So when I add Sluggable for my translations class, I have for each i18n entry different slug. How to solve this? Thank you!

A: You can override the getter for title in your entity, and just call the translate method from KnpDoctrineBehaviors on your entity. It will try to get the title translation in your current locale, or fallback to default locale translation.
<?php

namespace AppBundle\Entity;

use Knp\DoctrineBehaviors\Model as ORMBehaviors;
use AppBundle\Entity\AppTrait\TranslatableEntity;

class SomeEntity
{
    use ORMBehaviors\Translatable\Translatable;
    use ORMBehaviors\Sluggable\Sluggable;

    public function getSluggableFields()
    {
        return ['title'];
    }

    public function getTitle()
    {
        return $this->translate(null,true)->getTitle();
    }

This implies that the slug might be updated often if you update the title with different locale, you might want to avoid this, and just use english title for slug generation:
    public function getTitle()
    {
        return $this->translate('en')->getTitle();
    }


text:
Q: inline assembly in lldb expression evaluation? I try to use inline assembly in LLDB's expression and it does not seem to work. As a toy example I run on ARM:
(lldb) expr  __asm__ __volatile__("mov r0, 4");
(lldb) register read
General Purpose Registers:
        r0 = 0x00000003

In reality I need to access the special CP15 c13 Software Thread ID registers and could not find other way of doing it within LLDB - so an idea here will be appreciated. I thought of using
expr  __asm__ __volatile__("MRC p15, 0, r0, c13, c0, 3");

It runs, but has no effect on the content of r0.
Thanks a lot!

A: An expression that writes to a register won't actually change register state.  Before running an expression, lldb saves the register state away, and then it runs your expression, then restores the register state when it is done.  In almost all cases, you don't want whatever change was made to the registers in order to run some complex expression to get inherited by the program as it continues, or it will just crash.
If you need to change register state explicitly, then you have to use register read.
I know that wasn't the point of your exercise, this comment is more to explain why that approach didn't work.


text:
Q: Latex - Image displaying text instead of image Here is my code:
\begin{center}
\includegraphics[scale=0.5]{image_135.png}
\end{center}

Here is what shows up:

I'm not sure if it is important, but I use Overleaf as an editor.

A: Change the compile mode from fast to normal:


text:
Q: How can I search for restaurants using filters with google maps android api? I'm trying to make an app that finds the users location and then searches for for example nearby restaurants. I have a method to find the users location the only thing that is left is to find the restaurants nearby the user. How can I do this? Plz Help!

A: I don't know about any native android soultions but you can make a Get request to this Google Places API webservice
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=8.5586,76.8814&radius=500&types=food&sensor=false&key=[Your_KEY]

And parse the Json to get the restaurants nearby

location        -  Latitude,Longitude of the place
radius          -  Required radius to search your request
key             - Your API Key
types           - Types of places to search

Things to do to parse the results

*

*Get an Api key and create a sample request in the browser, You will get a big json result something like this

*Goto websites like this which can generate POJO classes for your Json the best configuration is given below:

*Download files and extract it and add them to your source code,You will get some errors at first because you may not have the annotation libraries in your build.gradle

*Add these lines in your app's build.gradle:
dependencies{
           compile 'com.google.code.gson:gson:2.3.1'
           compile 'javax.annotation:javax.annotation-api:1.2-b01'
    }

*Sync gradle files,And In the code where you get the json String ,deserialize it with Gson like:

YourGooglePlacesClass object=new Gson().fromJson(jsonString,YourGooglePlacesClass.class)

A: You can check out the PlacePicker API that's native uses the Google Places API for Android. For samples, Google provided it in their googlesamples github repo, you can check those out!


text:
Q: Javascript making a statement dynamic I have an variable idx2 which is equal 10 and want to uses it in dynamic situation with an object:   "abc.abc10.test();"  i want to replace 10 with "idx2"  so it should look like  "abc.abcidx2.test()" to make the statement  dynamic and not hard coded.   I am not sure how to word the question to search for it in javascript and how correctly to code it.

A: suppose your object is
var obj = {
  "A_idx2": { test: function(){ console.log( 1 ); } } },
  "A_idx4": { test: function(){ console.log( 413 ); } },
  "A_idx5": { test: function(){ console.log( 551 ); } },
}
var a = "idx2";
obj[ "A_" + a ].test(); //outputs 1
a = "idx4";
obj[ "A_" + a ].test(); //outputs 413

hope this helps.

A: I suspect what you're after is bracket notation:
abc.abc[idx2].test();

A: call it using
window[Dynamic funtion name](arg1, arg2,...);

A: In JavaScript:
object.field      and
object['field']

are two ways of accessing the same thing.
So instead of using:
abc.abc10

you can use
abc['abc10']

so what you want is
abc['abc' + idx2]

for example:
abc['abc' + idx2].test();

A: Use eval function to run string as a statement.
var dynamical = "idx2";

var statement = "abc.abc" + dynamical + ".test()"

eval(statement);


text:
Q: HashSet with Custom Type I would like to know why HashSet behaves strangely with custome type objects.In below code for String always it gives different results but for Human same type of result which is sorted.Is there something wrong in my
equals or hashCode or compareTo ?

Please hlep me to understand.Thanks in Advance.
Bean :
public class Human implements Comparable<Human>
{
    private int id;
    private String name;
    private int age;
    // setters and getters
    public Human(int id,String name,int age)
    {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public int hashCode()
    {
        return id;
    }
    @Override
    public boolean equals(Object object)
    {
        if(object != null && object instanceof Human)
        {
            if(this.id == ((Human)object).getId())
            {
                return true;
            }
        }
        return false;
    }

    @Override
    public String toString()
    {
        String s = "id:"+this.id+":name:"+this.name+":age:"+age;
        return s;
    }

    @Override
    public int compareTo(Human human) {
        if(this.id > human.getId())
            return 1;
        else if(this.id < human.getId())
            return -1;
        else
            return 0;
    }
   }

Code :
System.out.println("HashSet");
Set<String> set1 = new HashSet<String>();
set1.add("3");
set1.add("1");
set1.add("2");
set1.add("4");

Iterator<String> iter1 = set1.iterator();
while(iter1.hasNext())
{
    System.out.println(iter1.next());
}

System.out.println("HashSet with Custom Objects");

Set<Human> set11 = new HashSet<Human>();
set11.add(new Human(1, "joe", 26));
set11.add(new Human(3, "leo", 109));
set11.add(new Human(2, "king", 18));
set11.add(new Human(0, "vkgentle", 10));

Iterator<Human> iter11 = set11.iterator();
while(iter11.hasNext())
{
    System.out.println(iter11.next().toString());
}

Output :
HashSet
3
2
1
4
HashSet with Custom Objects
id:0:name:vkgentle:age:10
id:1:name:joe:age:26
id:2:name:king:age:18
id:3:name:leo:age:109

A: There's nothing broken. The reason you're getting sorted results is because your custom hashCode method doesn't have a very random hash distribution.
The HashSet class is backed by an array of "buckets". When you add something to the HashSet it uses your hashCode method to figure out which bucket to use. I think it works something like this:
bucketIndex = object.hashCode() % arrayLength;

Since your hashCode() is just the ID, you end up with the Humans added to the buckets in order. If you mess with your hash function a bit in order to make it more randomly-distributed then you should get a more random ordering in the HashSet.

A:
always it gives different results but for Human same type of result which is sorted.Is there something wrong in my

order in HashSet is not guaranteed, if you want ordered to be maintained respecting your compareTo() then use TreeSet

A: The hashcode method of a string is a bit more complex that your simple return id;
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#hashCode%28%29
  s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

So that is why the order might seam strange on a string.
Now why is it ordered in the case of your custom object is because of the inner working of hashset. The important thing to remember is that : "It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time." But yet it still has to order them in some way to be able to find them fast. This order is based on the hashcode result modulo (%) the actual capacity of the hashset.
Your 3 method might be right for your need, but you should know that if two object are equals() and you add them both in your HashSet the second one will overwrite the first one. This is the your choice if the equality should be only on the id or on more field.


text:
Q: Convert 1.5 Vdc circuit work with 5 Vdc I'm starting out with resistors and would really use some good guidance here. I've researched a lot but still the knowledge is quite dark in my mind and there's things I don't finish understanding.
For instance, I'm working on a project now which consist in converting a set of lights so that they'll work with a USB connector instead of a battery.
The set works with a single AA battery. So the input voltage is 1.5vdc. I've measured the resistance of the lights and the circuit and, unless I measured very wrongly, its resistance is of 178 kohms.
So using a Voltage Divider Calculator I get that if I need to input 5v and the 1.5v and the 178 kohms resistance and I get 76 kohms.
Now, I'm sure I'm doing something wrong. My idea is to get a resistor to bring down the USB 5v to the 1.5v the circuit needs and, when researching, I was pointed toward the Voltage Divider formula as the way to do this but I'm confused as to how it works.
I was playing around with another set of lights that use 3 x AA batteries and found it only had a 200 ohm resistor that connected the positive side to the light series. However, I wasn't able to measure the resistance of the light series itself. Still, both sets I'm talking about have just 10 white leds, so I'm imagining their load to be about the same.
This second set I'm also planning on converting to 5vdc but first I need to understand how to go about doing it; that is, how I can calculate what I would need in order to get a circuit that takes 1.5vdc and another that takes 4.5vdc and make each work with 5vdc. If anyone could point me out in the right direction and/or clarify certain concepts that I fear I've got wrong, I would appreciate it greatly!

Thanks for all your responses! And I really an VERY sorry that my question (and in fact all my knowledge on electronics) is very much all over the place! I am, as I said, starting out; I'm a very excited amateur that wants very much to learn but hasn't learned anything formally. So please bear with me!
After a couple of the comments, I went back and (yes, I forgot to say there was a circuit on one of the streams of lights) found a capacitor in the circuit, which I'm assuming is used in order to allow the stream to be powered by the single AA battery (1.5 v).
Now, the second stream only has a resistor after the 3 x AAs. As the number of LEDs there was the same as in the first stream and they were both warm white, I went under the assumption that both worked with about 3.5 vdc and a current that a AA can provide. So I tested the stream and found that, yes, it works with 3.5 vdc. So my target voltage is that. And I believe the current out of a 5v USB output will be OK if the original power source was a (or 3) AA battery(ies).
I may be wrong, though, and would very much like your help. But I've since read a couple of things (here and elsewhere) that may be of use to me. What is seemingly the easiest solution, although I don't know if it'll work:

trying to power with 3.5V and how much current you need. If all you want is just to get replacement for pair of AA batteries, just put two 1N4001 diodes in series.

Will that work, do you think?

A: The question rambles too much for a single clear answer, but look up something called a voltage regulator or linear regulator.  These take a high and possibly varying voltage in, and produce a lower and steady voltage out.
There are voltage regulators available with fixed output voltages.  I haven't looked whether any are available with fixed 1.5 V output, but that would be easiest if you can find it.
In this case, you're starting with a reasonably steady 5 V from USB.  It can vary, but so can a "1.5 V" battery.  A simple voltage divider driving a emitter follower would probably work well enough as a crude voltage regulator.
Here is what I'm talking about:

This is not a good approach in general because the output voltage is a direct function of the input voltage.  In this case it's probably good enough since the USB voltage is close to 5 V.  In effect, this circuit uses the USB voltage as the reference that the output voltage is derived from.
More general voltage regulators contain their own independent references.

A: The string you have must have a boost converter to operate white LEDs from a single cell. As such the resistance you measured won't be representative of anything because it will be very nonlinear. You might want to take a fresh battery and connect your multimeter in series to measure the current draw (be sure to change it back to volts after you are done). I'll assume here that the current is well under 100mA (if it's more you could use an LM317M or LM317 rather than an LM317L with the same resistor chain)
Here is a circuit that will do what you want (the LM317L is available in TO-92):

To get 1.5V out, R1 can be 240 ohms and R2 can be 51 ohms. The capacitors are not critical- you could use 100uF/10V electrolytics for both.
A (somewhat) more modern part that works similarly is the LM1117 but it's a bit more fussy about the capacitors, being a semi-low dropout regulator. Read the datasheet recommendations carefully if you use such a device.
These parts are mature "jellybean" devices that designers often reach for because they are cheap, multi-sourced and stocked in vast volumes, and work fine. They also include thermal shutdown and current limiting so they are relatively foolproof (if you short or overload the output you won't likely destroy the part).

There are much more modern parts such as the TPS69xx series which will output a fixed 1.5V at (perhaps) 50mA in your case due to thermal limits, but they again are fussy about capacitors and are somewhat more difficult to breadboard (SOT-23-5 package) and have little power dissipation capability. You could use a 100n capacitor on the input and 10uF ceramic in series with 1 ohm on the output. All in all, though, I think the LM317 is more appropriate.

A: What kind of LED do I need?. Refer to my examples at end.
Due to your lack of understand of LED equivalent circuits and actual circuit being applied, consider this to evaluate your problem better then define the requirements better,then and only then an answer is possible.
All LED's have Zener like voltages and incremental resistance ESR) at rated current. If a fixed R (as done in stripleds) this is added to the circuit model in terms of Effective Series Resistance (ESR) discussed below, ( and all over this site).
If there is a DC to DC supply included in circuit with some kind of CC regulation, then you need to define Input V range and effect on current.

*

*Each 5mm  white/blue LED is equiv to 3.1V (nom) with 15 ohm ESR typ.

*Each HB Red/Yellow LED is equiv to 2.1V (nom) with ESR from 7 to 12 ohm

*These ESR values reduce as Pd of package and chip rating increases

*Since DMM's measure Reaistance with constant current in uA ranges with a low voltage limit often below the Vf or forward conducting voltage, it does not illuminate and Z is very high. This explains why your diode resistance is high.

*Once an LED becomes brighter , we say the diode is saturated at some threshold Vth, then rises in voltage due to the ESR of each diode type to reach the rated Vf at rated current

*5 mm LED current which is often rated at 20mA for 5mm due to 65mW limit at some temp due to thermal insulation of epoxy and junction temperature rise of 600'C per watt or 0.6['C/mW]* 65[mW] = 40'C rise in junction temp. above ambient.

A complete solution to your question is not possible , since you need to learn more about diode characteristics to define the problem better. This answer however assumes you are just beginning to read datasheets and you will note there is a wide variation and tolerance on Vf@If due to quality colour and chip size.
After you understand your application, then you can define a Voltage source with current limiting, R drop value, or a variable LDO voltage source, or a constant current sink to a array of LEDs, or in high power cases more advanced solutions.


text:
Q: If $p\circ \phi = p$ then $\phi$ is a deck transformation? I'm trying to solve the following question:

True or False:
Let $p:\tilde{X}\to X$ be a covering map with $\tilde{X}$ path connected and $\phi: \tilde{X}\to\tilde{X}$ a continuous transformation such that $p\circ\phi=p$. Then $\phi$ is a deck transformation.

To prove this is true, I just have to prove that $\phi$ is a homeomorphism. To prove this is false, I have to find a counterexample.
I am almost sure this is false, but I cannot find a counterexample. Some help?


text:
Q: Multiple dll reference failure on nuget reinstall I am getting multiple The referenced component <packagename> cannot be found when i do a nuget reinstall for my project. There are no build errors and i have to manually delete the erroneous references from the project to fix this 'annoyance'. Does anyone know why Im this is happening? (see screenshot).
I am using visual studio 2017 and .NET 4.6.1 and netstandard2.0 is installed. The project type is class library and If i look in the bin folder, it seems there is an additional xml file for each erroneous reference.

A: It seems it was part of a known issue with VS2017 and netstandard2.0. After stumbling across this github release note page and installing this package, it solved my issue. NETStandard.Library.NETFramework, link to nuget - https://www.nuget.org/packages/NETStandard.Library.NETFramework/
https://github.com/dotnet/core/blob/master/release-notes/2.0/2.0.0-preview2-known-issues.md#netstandard-20-and-the-net-framework


text:
Q: HumaneJs notifications bound to DIV I am using HumaneJs http://wavded.github.com/humane-js/ to display notifications. Everything is working well except that I cant seem to specify a DIV where my notifications should appear. The discussion in this link https://github.com/wavded/humane-js/pull/32 seems to indicate that it is possible but I am not able to get it to work
Here is my HTML code
<button id="1">Display default notification</button>

    <button id="2">Display notification inside div</button>

and here is the Javascript
/*display notification in default position*/
$("#1").click(function() {
  humane.log("Default notification");
});

/*display notification inside div*/
$("#2").click(function() {
    var custom = humane.create({container: $("#container")[0]});
    custom.log("Notification inside div");
});

I have also setup a fiddle to demonstrate the issue
http://jsfiddle.net/ZvCvJ/
Clicking on the button seems to display the notification in the default position(top-right) every time and I am not able to display the notification inside the DIV. Any help would be appreciated.

A: The reason it is displaying in the corner is because you are using the default libnotify
Add baseCls: "humane-bigbox" and it should fix it.
http://jsfiddle.net/ThdLC/

A: The CSS of the individual themes in Humane don't look like they take the 'container' into account.
Another notification plugin that explicitly supports this 'container restricted' notification is Noty.
http://needim.github.io/noty/#custom-container


text:
Q: Convert XML String API response to a key-value Object C# I am receiving a XML strings from and API, and would like to convert these to C# objects key-value in order to handle these values also apply some asserts.
The messages are of the form string format:
<?xml version="1.0" encoding="UTF-8"?>
<ReportData>
   <ProjectName>Test Data</ProjectName>
   <Unit>Unit 1</Unit>
   <ReportLabel.Cost>394</ReportLabel.Cost>
</ReportData>

After i get the string API response i am trying to deserialize the XMl like this where responseAPI is the xml above:
XmlDocument doc = new XmlDocument();

            using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(responseAPI), XmlDictionaryReaderQuotas.Max))
            {
                XElement xml = XElement.Load(reader);
                doc.LoadXml(xml.ToString());
            }

At this point i have and xml but i can not get a key-value object.
i am trying
var jsonText = JsonConvert.SerializeXmlNode(doc);

or
serializer = new XmlSerializer(typeof(Object));
using (TextReader reader = new StringReader(responseAPI))
{
  var result = (Object)serializer.Deserialize(reader);
}

or
var response = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseAPI);

I am new to with this kind of response in XML and am not sure the way to performing this.  It is not as easy as JSON format.

A: You can use System.Xml.Linq for this task.
Here is one way to create a dictionary from the XML:
static void Main(string[] args)
{
    // or use other overload of the Load() method if the XML is not comes from a file stream, uri etc...
    var xmldoc = System.Xml.Linq.XDocument.Load("YOUR FILE PATH");

    Dictionary<string, string> XMLKeyval = new Dictionary<string, string>();
    foreach (var name in xmldoc.Descendants("ReportData").Elements()
                        .Select(x => new { Name = x.Name, Value = x.Value }).Distinct())
    {
        XMLKeyval.Add(name.Name.LocalName, name.Value);
    }

    // Output
    foreach (KeyValuePair<string, string> itm in XMLKeyval)
    {
        Console.WriteLine(itm.Key + ": " + itm.Value);
    }

    Console.ReadLine();
}

A: You can not directly convert xml to a dict of key value pair, Instead we need to iterate through each node in xml and add it as a key value pair to a dict object.
please refer Converting an XML-document to a dictionary


text:
Q: What does this condition do in ternary? Javascript Ternary Condition
I have javascript with this condition, what is this?
var y = (typeof x !== undefined) ? x || 0 : 1;

A: This (typeof x !== undefined) ? x || 0 : 1; is going to return always true because the typeof operator will return a string.
That condition should compare a string as follow:
(typeof x !== 'undefined') ? x || 0 : 1;

var x;
var str = typeof x !== 'undefined' ? x || 0 : 1;

console.log(str);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Conditional (ternary) Operator explanation:
                         +--- When condition is true
                         |
                         |        +--- When condition is false
                         |        |
                         |        |
                         v        v
typeof x !== 'undefined' ? x || 0 : 1;
  ^    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |                             |
  |                             +---- The condition should be:
  |                                   (x === undefined ? 1 : x || 0)
  |
  +--- Checks for the type of x

Code refactored

var x = 4;
var str = x === undefined ? 1 : x || 0;
console.log(str);// should return 4

var y;
str = y === undefined ? 1 : y || 0;
console.log(str);// should return 1

y = null;
str = y === undefined ? 1 : y || 0;
console.log(str);// should return 0

y = 5;
str = y === undefined ? 1 : y || 0;
console.log(str);// should return 5

y = 5-"5";
str = y === undefined ? 1 : y || 0;
console.log(str); // should return 0
.as-console-wrapper { max-height: 100% !important; top: 0; }

Docs

*

*Conditional (ternary) Operator

*typeof

A: First, there is an error with the condition:
(typeof x !== undefined)

because you are comparing a type against a value.
typeof always returns a string, while undefined is a value. So, whatever type x is, it will be returned as as string. Even if it's value is undefined, "undefined" (notice the quotes?) will be returned as its type and since the string "undefined" has a typeof === "string", the condition will actually branch into the true section, even when x actually is undefined.
So, it needs to be: (typeof x !== "undefined").
Or, you could test the value of x against the value undefined:
(x !== undefined)

But, you can't mix and match values and types.

Now, assuming we correct that, the next part (the true branch):
x || 0

Simply returns x, as long as it is not "falsy" (that is, any value that would convert to the Boolean false). 0, false, NaN, undefined, "" or null are all falsy. So, if x is not falsy, x is returned. If x is falsy, then 0 is returned. This is a way to provide a default return value in case the first value doesn't exist. But, the logic is a bit off here, because if the code has entered the true branch, it's because x is not undefined, which means it's "truthy". And, if it's truthy, then we can safely just return x. So, it really should just be:
x

Finally, the last part (the false branch)
1

Is what will be returned if the original condition is false. In this case, if x is undefined.
So, the code has flaws in it and really should be:
(typeof x  !== "undefined") ? x : 1

EXTRA CREDIT:
In reality, any expression you place into the condition of an if statement is going to be converted to a Boolean for the if to do its job. If all you need to know is if x is not a "falsy" value, then all you need to do is write:
x ? x : 1;

The x will be converted to a Boolean.
If it's true (truthy), then x is returned.
If it's false (falsy), then 1 is returned.
Examples:

function testX(x){
  return x ? x : 1;
}

// Truthy:
console.log(testX(10));           // 10
console.log(testX({}));           // {}
console.log(testX(true));         // true
console.log(testX("something"));  // "something"

// Falsy:
console.log(testX(""));     // 1
console.log(testX());       // 1
console.log(testX(4-"Z"));  // 1 because 4-"Z" == NaN
console.log(testX(false));  // 1
console.log(testX(0));      // 1
console.log(testX(null));   // 1

A: The condition
(typeof x !== undefined)

asks if x is not of type undefined. Or, if x is defined. This will include any value or even null.
...? x || 0

If so, the expression evaluates to this. Which is the value of x in most cases or 0 if x is anything evaluated to be boolean false, e.g., null, false, etc.
... : 1;

Otherwise (i.e. case when x is undefined), evaluates to 1.
Typing in Javascript is complicated (in my opinion), sometimes it is not easy to remember what it is when you're comparing mixed type stuff, see https://dorey.github.io/JavaScript-Equality-Table/ for a summary matrix.

A: Admitting that you have a left-hand operand, it does the same thing as :
var y;
if(typeof x !== undefined) {
    if(x)
        y = x;
    else
        y = 0;
}
else
    y = 1;


text:
Q: VBS - Ignoring the \ special character properties I'm struggling to call a command line correctly in VBS due to the \ escape character.
The string output I'm looking to write to the command line is,
batch_name=\"myBatch\"

Which gets passed to a .exe file. Unfortunately, due to the way the \ character works I can only write,
batch_name=\myBatch\
batch_name=\""myBatch\""

I can't get \" in the output! An altered version of my code is below,
BATCH_NAME = "myBatch"

outputString = "batch_name=\" & BATCH_NAME & "\"

I've tried lots of methods - Concatenating the string with Chr(34), using multiple double quotes, even trying to replace() "" with ", nothing seems to work.
Any ideas?

A: I gave it a shot and
outputString = "batch_name=\""" & BATCH_NAME & "\"""

worked for me giving the result batch_name=\"myBatch\"
Does it work for you? How you execute this command in the shell?

A: You can do the following;
outputString = "batch_name=" & chr(92) & chr(34) & BATCH_NAME & chr(92) & chr(34)


text:
Q: Jasmine. Module is undefined even when angular-mocks used I use Grunt and grunt-contrib-jasmine to start jasmine tests.
My config in Gruntfile:
jasmine : {
            src : ['src/main/webapp/app/js/controllers/*.js'],
            options: {
                specs: 'src/main/webapp/specs/*spec.js',
                vendor: '/src/main/webapp/app/lib/angular.min.js',
                helpers: '/src/main/webapp/specs/helpers/angular-mocks.js'
            }
        }

But after grunt:jasmine i get error 'ReferenceError: Can't find variable: module
How can I fix it?

A: It's my fail with path to files.
This is solution. Module is not undefined, but I get another error ))
jasmine : {
            src : ['src/main/webapp/app/js/controllers/*.js'],
            options: {
                specs: 'src/main/webapp/specs/*spec.js',
                vendor: 'src/main/webapp/app/lib/angular.min.js',
                helpers: 'src/main/webapp/specs/helpers/angular-mocks.js'
            }
        }


text:
Q: How Can I send local video stream to server?
I am able to createOffer in local and send sdp to server.Also, got server answer and got sdp.
Now, How Can I send my local video stream to server? I don't want server video.

private void startStreamingVideo() {
    //creating local mediastream
    MediaStream mediaStream = factory.createLocalMediaStream("ARDAMS");
    mediaStream.addTrack(localAudioTrack);
    mediaStream.addTrack(localVideoTrack);
    localPeerConnection.addStream(mediaStream);

    MediaConstraints sdpMediaConstraints = new MediaConstraints();
    sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "false"));
    sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));

    localPeerConnection.createOffer(new SimpleSdpObserver() {
        @Override
        public void onCreateSuccess(SessionDescription sessionDescription) {
            Log.d(TAG, "onCreateSuccess: ");
            localPeerConnection.setLocalDescription(new SimpleSdpObserver(), sessionDescription);
            //remotePeerConnection.setRemoteDescription(new SimpleSdpObserver(), sessionDescription);

            callApiOffer(new Example(sessionDescription.description,sessionDescription.type.name().toLowerCase()));
        }
    }, sdpMediaConstraints);
}

private void callApiOffer(Example example){
        Utils.getInstance().getRetrofitInstance1().postRequest(example).enqueue(new Callback<ResponseExample>() {

            @Override
            public void onResponse(Call<ResponseExample> call, Response<ResponseExample> response) {
                ResponseExample body = response.body();
                if (body != null) {
                    Log.e(TAG, body.getType());
                    Log.e(TAG, body.getSdp());
                    // Here, I got server sdp and type="answer"
                    SessionDescription sessionDescription = new SessionDescription(Type.ANSWER, body.getSdp());
                    localPeerConnection.setRemoteDescription(new SimpleSdpObserver(), sessionDescription);
                    //doAnswer();
                }
            }

            @Override
            public void onFailure(Call<ResponseExample> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

Backend server is in Python aiortc
I am getting "onIceConnectionChange: FAILED"
  Need I add to -> addIceCandidate ??

A: You have to add peerconnection observer and in onIceCandidate method to send icecandidate. On receiving side you can add icecandidate.


text:
Q: MySQL hashed column password+script bash I'd a little problem.
I'd created a MySQL table with the password column encrypted with SHA1.
mysql> CREATE TABLE IF NOT EXISTS user_encrypted (
    username varchar(50) COLLATE utf8_unicode_ci NOT NULL PRIMARY KEY DEFAULT 'username',
    hashed_password varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'password',
    user_mail varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL DEFAULT 'your@email.com',
    user_phone varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL DEFAULT '+33 1 23 45 67 89',
    user_online tinyint(1) NOT NULL DEFAULT '0',
    user_enable tinyint(1) NOT NULL DEFAULT '1',
    user_max_connection tinyint(1) NOT NULL DEFAULT '2',
    user_start_date date NOT NULL DEFAULT '2015-05-01',
    user_end_date date NOT NULL DEFAULT '0000-00-00',
    KEY  hashed_password (hashed_password)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Result
Query OK, 0 rows affected (0.01 sec)

I'd a script, which call the MySQL table :
#!/bin/bash
. /etc/openvpn/script/config.sh

#New Encrypted_password
#username=$(mysql -h$HOST -P$PORT -u$USER -p$PASS $DB -sN -e "select username from user_encrypted where username = '$username' AND hashed_password = '$password' AND user_enable=1 AND user_max_connection=2 AND user_start_date != user_end_date AND TO_DAYS(now()) >= TO_DAYS(user_start_date) AND (TO_DAYS(now()) <= TO_DAYS(user_end_date) OR user_end_date='0000-00-00')")

##Check user
[ "$username" != '' ] && [ "$username" = "$username" ] && echo "user : $username" && echo 'authentication ok.' && exit 0 || echo 'authentication failed.'; exit 1

The problem is, when I use the script, and OpenVPn ask me for user / password, I use Test  and Test1234, but, the system refuse the password.
It seems the 'non-encrypted" password can't be translated to encrypted password for checking if the password for the table is the same as i entered in the client OpenVPN.
I don't know how to do, in my script bash for the password I enter is "converted" to encrypted password for checking with the database...
Rhank you

A: Your bash script doesn't hash the password. Hence, you're comparing the password with a hash of the password.
You say it's a SHA1 hash, which conveniently exists as a built-in function in MySQL. Changing
where username = '$username' AND hashed_password = '$password' ...

into
where username = '$username' AND hashed_password = SHA1('$password') ...

should fix your immediate problem.
I want to bring up two other problems with your code -- these are unfortunately pretty common mistakes:

*

*It appears you are not using a salt for the password hash. You should -- it would make it significantly harder for attackers to figure out your password from the hash. Please read this.

*Your login script is vulnerable to SQL injection. What if an attacker puts a string like admin'; SELECT * FROM user_encrypted WHERE 0 AND ' (or something to that effect) as a username? Please read this.


text:
Q: How to send encrypted emails with SES I'm trying to send emails to clients but securely as the contents will contain phone numbers and email addresses.
I want to use SES but I need to encrypt the contents of the email while it's in transit.
Apparently, S/MIME is an option. As per this documentation:
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/security.html
I've looked on how to use it, but tutorials are just installing certificates in Outlook etc. This really isn't my area of expertise.
How do I go about ensuring the contents of my email is secure when sending it to clients programatically. Once it reaches the inbox of the client and they can read it, I don't really care what happens to it. If there are better solutions, let me know but it's got to be using SES.
Any help?

A: S/MIME is for end-to-end public key encryption of the message. SES supports the HTTPS or TLS protocols for encryption of messages in transit. All programatic calls would normally use those protocols.


text:
Q: Payment Card Industry DSS - Storing card holder data in systems not connected to internet Background
Though I've looked through some posts on stack-overflow that partially cover this point I'm yet to find one that provides a comprehensive question/answer.
As a developer of POS systems the PCI DSS has two components I'm interested in:

*

*PA DSS (Payment Application) which regards the software I develop

*PCI DSS (Merchants) which regards all my clients that use the software

The PA DSS seems to put the point most bluntly:
"9.1 The payment application must be developed such that the database server and web server are not required to be on the same server, nor is the database server required to be in the DMZ with the web server"
Testing Procedures:
9.1.a To verify that the payment application stores cardholder data in the internal network, and never in the DMZ, obtain evidence that the payment application does not require data storage in the DMZ, and will allow use of a DMZ to separate the Internet from systems storing cardholder data (e.g., payment application must not require that the database server and web server be on the same server, or in the DMZ with the web server).
9.1.b If customers could store cardholder data on a server connected to the Internet, examine PA-DSS Implementation Guide prepared by vendor to verify customers and resellers/integrators are told not to store cardholder data on Internet-accessible systems (e.g., web server and database server must not be on same server).
And from the merchant's PCI DSS:
1.3.5 Restrict outbound traffic from the cardholder data environment to the Internet such that outbound traffic can only access IP addresses within the DMZ.
Question
My question is quite simple - can the database and application server be logically different (on different virtualised OS) or must they be physically different (on different physical/dedicated servers)?
Also, I'm a bit concerned about having to place a database server with no connection to the Internet whatsoever. How am I supposed to administer this server remotely?
Or is it okay to access the database server via the application server - though surely that defeats the purpose?

A: No simple answer, sadly.
The SSC has released a new supplement on virtualisation which has some relevant information: https://www.pcisecuritystandards.org/documents/Virtualization_InfoSupp_v2.pdf
While mixing guest OSs of different functions on the same hypervisor is not prohibited, you will need to show that you've thought about the extra risk that this brings.
They will also have to be logically separated with network traffic from one VM to the other going through a firewall of some sort to protect the different OSs and applications. Being on the same physical host is not an excuse for skipping controls like firewalling so you may have to be creative about how you meet these requirements.


text:
Q: Interesting/Paradoxical Math Problems for High School Students I am creating a math course for high school students (not necessarily advanced) about interesting/paradoxical math problems (think Monty Hall and Hilbert's Hotel). What are some other interesting math problems that are accessible to average high school students? So no calculus or higher required (unless the necessary machinery can be taught within 30 minutes). Thanks!

A: Zeno's paradox could be fun. I had a lively discussion with some high school students about whether $0.999999... = 1$, and we enjoyed looking at pictures such as this one:

While this topic comes up against the idea of a limit and infinite series, it doesn't have to be presented with that language.


text:
Q: Spring boot - How to create a CSV file and send as attachment at runtime Im trying to create a CSV file to send as attachment in mail.
I need to create the CSV file at runtime without storing in disc.
I read that we cannot send as attachment without storing in any physical location. Is it so!
I'm new to this, if anybody could provide some inputs to get started with this.


text:
Q: Keras Efficientnet B0 use input values between 0 and 255 I am using a EfficientNet B0 from keras application.
tf.keras.applications.EfficientNetB0(include_top=True,weights=None,input_tensor=None, input_shape=(224, 224, 6), pooling=None,classes=5,classifier_activation="softmax")

Keras thereby normalizes the input to (0,1). I found the following line in the keras code:
x = layers.Rescaling(1. / 255.)(x)

Now I do not want to to rescale the input. As input I want to use the original image, because I work with a coral edgetpu board. This board only works fast with int8.
I just want to remove the line above.
I could copy the code from keras in my project.
But then it doesn't work anymore when I use a different version of Tensorflow.
Does anyone have an idea?
I am using Tensorflow 2.4