Quebra de Linha dentro da tag P não funciona

Question: Estou fazendo uma animação em JavaScript para que o texto tenha o efeito de estar sendo digitado. Estou usando uma única tag
 para o texto, e gostaria que quebrasse a linha nas tags
, mas elas estão sendo adicionadas como texto no HTML.
Segue código abaixo + Link do Codepen
Link: https://codepen.io/Sr-RIcci/pen/ExWdbBX

function typeWriter(elemento) {
  const textoArray = elemento.innerHTML.split('');
  elemento.innerHTML = "";
  textoArray.forEach((letra, i) => {
    setTimeout(() => elemento.innerHTML += letra, 75 * i);
  });
}

const titulo = document.querySelector('p');
typeWriter(titulo);
p::after {
  content: "|";
  margin-left: 5px;
  opacity: 1;
  animation: pisca 0.7s infinite;
}

@keyframes pisca {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

Olá mundo
 Olá Universo
 Olá Vida

Comment: Dennis, editei a minha resposta com um exemplo sem regex e sem split.
Answer: Isso ocorre porque o split() divide o
 também, o que você pode fazer é o uso de uma expressão regular, então ao invés de split() vocë pode usar String.prototype.match, veja como a array fica depois:

console.log("a b c d
 foo bar
 asd".match(/<\w+?>|./g))

A primeira parte da expressão é para pegar as tags <\w+?> e o . depois do pipe (|) é para pegar qualquer outro caractere (até espaços.
No entanto você poderia também fazer um for() bem elaborado para unir os caracteres quando for uma tag, navegando caractere por caractere, e nem precisa de split, exemplo (veja os comentários dentro do código):

const elemento = document.querySelector("p");
const texto = elemento.innerHTML;

let hasOpenTag = false;
let tmpTag;

//Limpa o campo
elemento.innerHTML = '';

for (let i = 0, j = texto.length; i < j; i++) {
    let letra = texto[i];

    /*
      Se o caractere for "<" então executa o continue;
      para que o setTimeout não seja executado e armazenará
      os próximos caracteres até encontrar o ">"
    */
    if (letra === '<') {
      tmpTag = letra;
      hasOpenTag = true;
      continue;
    }

    /*
      Se encontrar o ">" e antes dele teve um "<"
      então junta a tag toda na variável tmpTag e irá
      adicionar ao setTimeout
    */
    if (hasOpenTag && letra === '>') {
        letra = tmpTag + letra;
        hasOpenTag = false;
    }

    /*
      Se a variavel hasOpenTag for true irá armazenar
      todos próximos caracteres para formar a tag, até
      encontrar o ">" (da if anterior)
      adicionar ao setTimeout
    */
    if (hasOpenTag) {
       tmpTag += letra;
       continue;
    }

    setTimeout(() => elemento.innerHTML += letra, 75 * i);
}
p::after {
  content: "|";
  margin-left: 5px;
  opacity: 1;
  animation: pisca 0.7s infinite;
}

@keyframes pisca {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

Olá mundo
 Olá Universo
 Olá Vida

Answer: Onde usa a propriedade Element.innerHTML use a propriedade Node.innerText que representa o conteúdo textual "renderizado" de um nó e seus descendentes isso significa que as quebras de linha são convertidas e compreendidas como \n.

function typeWriter(elemento) {
  const textoArray = elemento.innerText.split('');
  elemento.innerText = "";
  textoArray.forEach((letra, i) => {
    setTimeout(() => elemento.innerText += letra, 75 * i);
  });
}

const titulo = document.querySelector('p');
typeWriter(titulo);
p::after {
  content: "|";
  margin-left: 5px;
  opacity: 1;
  animation: pisca 0.7s infinite;
}

@keyframes pisca {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

Olá mundo
 Olá Universo
 Olá Vida


Explanation to the what() call

Question: using namespace std;

struct MyException : public exception
{
  const char * what () const throw () // <--- This
  {
    return "C++ Exception";
  }
};

Please consider the marked line.
Can somebody explain me the syntax used in that statement
I think i should have narrowed down my query to  "const throw()"   part only...
Thanks all for the replies
Comment: Your title is very vague and poor. Please change it to describe the specific syntax you're asking about so that the title describes the question. You should also demonstrate that you have performed some basic research. Which book are you using?
Comment: @Tri_Core you should _edit_ the question so that it is clear what you are asking. You have added text saying "I think I should have narrowed down my query to const throw() part only" - don't add that text, just _do it_, i.e. narrow down your query.
Comment: Do you think i should delete this question?
Answer: It's a member function definition.

const char * is the return type, a pointer to a constant character, by convention the first character of a zero-terminated string array.
what is the function name
() is an empty parameter list, indicating that the function takes no arguments
const qualifies the function, so it can be called on a const object, and can't directly modify the object's members
throw () is an exception specification which prevents it from throwing any exceptions.

This overrides the virtual function declared in the exception base class, allowing you to get a text message describing the specific exception that was thrown:
try {
    // Throw a specific type
    throw MyException();
} catch (std::exception const & ex) {
    // Catch a generic type and extract the message
    std::cerr << ex.what() << '\n';  // prints "C++ Exception"
}

Comment: I must point that it does not actually prevent exceptions from being thrown. `throw()` variant (now deprecated) tells that no exceptions are expected to be thrown so compiler can simplify code omit exception handling parts. However if exception is thrown it may lead program into inconsistent state since no proper cleanup is performed.
Answer: what is a function that returns a const char *. It is also a function that never throws an exception.
Answer: The line is a member function declaration for the class MyException. It follows the exact same syntax as any other function declaration.
const char * - is the return type of the function.
what - is the name of the function.
() - the (empty) parameter list. The method takes no parameters.
const - declares this to be a const function (in general, this means it should not change the state of the object).
throw () - declares that the function throws no exceptions.
Answer: using namespace std;

struct MyException : public exception
{
  const char * what () const throw () // <--- This
  {
    return "C++ Exception";
  }
};

It isn't clear from your question which bit in particular you are unsure of, but I would guess it is the throw(), as this is not commonly used.
This is used to document the types of exceptions the method can throw, which enables the compiler to check that:

When you use the method ,You are catching everything thrown
Are not throwing something that you should not be

The rest of the line is fairly standard:
const char * what () const throw ()
what() : A function named what.
what() const: what() is a const function, so it can be used on const objects of type MyException
const char* what() const: what is a const function, which returns a pointer to const char

Explanation to the what() call


TypeError: Wrong number or type of arguments for overloaded function 'new_Date'

Question: I am new to python. I am getting an error when running below code. The issue seems to be with date. can someone help me to correct i please. I have tried changing the date format in the excel but it does not solve the issue. The excel have a list of several bonds. I want to generate the coupon dates of the different bonds
BondData = pd.read_excel (r'C:\Users\Avishen\Desktop\Python\BONDDATA.xlsx')
Data = pd.DataFrame(BondData)

def scheduledates():
    tenor = ql.Period(ql.Semiannual)
    day_count = ql.Thirty360
    calendar = ql.UnitedStates()
    businessConvention = ql.Unadjusted
    dateGeneration = ql.DateGeneration.Backward
    monthEnd = False

    # Dates in Bond Period
    return ql.Schedule (issueDate, maturityDate, tenor, calendar, businessConvention,
                            businessConvention , dateGeneration, monthEnd)

new_df["Dates"]= Data.apply(lambda x: scheduledates(),axis = 1)
new_df["ISIN"] = Data.ISIN
new_df

Error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-877415e9cf83> in <module>
     21                             businessConvention , dateGeneration, monthEnd)
     22
---> 23 new_df["Dates"]= Data.apply(lambda x: scheduledates(),axis = 1)
     24 new_df["ISIN"] = Data.ISIN
     25 new_df

~\anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
   7546             kwds=kwds,
   7547         )
-> 7548         return op.get_result()
   7549
   7550     def applymap(self, func) -> "DataFrame":

~\anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
    178             return self.apply_raw()
    179
--> 180         return self.apply_standard()
    181
    182     def apply_empty_result(self):

~\anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
    269
    270     def apply_standard(self):
--> 271         results, res_index = self.apply_series_generator()
    272
    273         # wrap results

~\anaconda3\lib\site-packages\pandas\core\apply.py in apply_series_generator(self)
    298                 for i, v in enumerate(series_gen):
    299                     # ignore SettingWithCopy here in case the user mutates
--> 300                     results[i] = self.f(v)
    301                     if isinstance(results[i], ABCSeries):
    302                         # If we have a view on v, we need to make a copy because

<ipython-input-4-877415e9cf83> in <lambda>(x)
     21                             businessConvention , dateGeneration, monthEnd)
     22
---> 23 new_df["Dates"]= Data.apply(lambda x: scheduledates(),axis = 1)
     24 new_df["ISIN"] = Data.ISIN
     25 new_df

<ipython-input-4-877415e9cf83> in scheduledates()
      8
      9 def scheduledates():
---> 10     issueDate = ql.Date(Data.issuedate)
     11     maturityDate = ql.Date(Data.maturitydate)
     12     tenor = ql.Period(ql.Semiannual)

~\anaconda3\lib\site-packages\QuantLib\QuantLib.py in __init__(self, *args)
    425
    426     def __init__(self, *args):
--> 427         _QuantLib.Date_swiginit(self, _QuantLib.new_Date(*args))
    428
    429     def weekdayNumber(self):

TypeError: Wrong number or type of arguments for overloaded function 'new_Date'.
  Possible C/C++ prototypes are:
    Date::Date()
    Date::Date(Day,Month,Year)
    Date::Date(Day,Month,Year,Hour,Minute,Second,Millisecond,Microsecond)
    Date::Date(Day,Month,Year,Hour,Minute,Second,Millisecond)
    Date::Date(Day,Month,Year,Hour,Minute,Second)
    Date::Date(BigInteger)
    Date::Date(std::string const &,std::string)

---------------------------------------------------------------------------

Data = pd.DataFrame(BondData)
Fields from Bond Data
    ISIN
    issuedate
    maturitydate
coupon
Tradeyield
    Bond_Price
    MarketPrice
    Nominal_Amount

Answer: From the traceback, the problem is the line:
issueDate = ql.Date(Data.issuedate)

(which for some reason is not in the code you pasted).  Coming from Excel, issuedate should be an integer and thus compatible with the ql.Date constructor, but it's possible that pandas is reading it as a string or some other type.  You should examine the data frame and check the type of the column.  If it's not what you expect, you'll have to figure out if there are data in that column that pandas can't interpret as integers, and either clean them up of force the conversion somehow before passing them to ql.Date.
Comment: Thanks @Luigi Ballabio.  Mange to solve it


password protect only the home page

Question: I'm trying to pwd protect only my home page with apache basic auth.
This seems to work on everything not just the hp
<LocationMatch "/">
  AuthType Basic
  AuthName "heelooo?"
  AuthUserFile /var/path/.htpasswd
  Require valid-user
 </LocationMatch>

Changing the regex to ^/$ or ^$ makes it not authenticate anything. Any tips? (its running a mod_ruby rails app)
Answer: It's always better to use Directory directive for setting authentication.
Location directives should not be used to control access to filesystem locations
<Directory /home-path>
AuthName Members
AuthType Basic
Require valid-user
AuthUserFile /auth-file-path/.htpasswd
</Directory>

Ruby-on-rails solution:
before_filter :authenticate

protected

def authenticate
  authenticate_or_request_with_http_basic do |username, password|
    username == "user" && password == "pass"
  end
end

Comment: hm, its all virtual (mod_ruby, rails) so I dont think I can specify a file like that since I don't have one. Well, tried it with the root dir without a / and its protecting everything instead of just the home page.
Comment: http://projects.oucs.ox.ac.uk/rails/howtos/apache/handout.pdf
Comment: maybe a last resort. I'd rather not polute my codebase with conditionals for basic authentication. Is this not doable with pure apache?
Comment: It can be done from apache level but you'd need to run ruby on rails via fastcgi. Please note that apache has a very poor (performance wise) implementation of basic authentication when AuthUserFile is used (on each request AuthUserFile is read), so probably coding it yourself would be much more easier and more efficient.
Comment: s/always/often/
Comment: according to apache docs always, but I can live with often ;)
Answer: I reran all my attempts and one decided to work.  I found that
    LocationMatch "^/$"
does in deed work. I must have been doing something wrong before.  basicauth can indeed work with mod_ruby - don't need to run as fastcgi.  Thanks for all the help.

password protect only the home page


$a=mx$ and $b=my$, $\gcd(x,y)=1$ and $p,q$ relatively prime to $a,b$. Is $\mu q=\tau q\pmod m$ for $\mu=p^{-1} \in Z_a$ and $\tau = p^{-1}\in Z_b$

Question: Let $a=mx$ and $b=my$ where $\gcd(x,y)=1$. Let $p,q$ be integers relatively prime to $a$ and $b$. Let $\mu$ be the integer which represents the class of the multiplicative inverse of $p$ in $\mathbb{Z}_a$ and, similarly, let $\tau$ be the multiplicative inverse of $p$ in $\mathbb{Z}_b$.
Is it always the case that $\mu q =\tau q$ (mod m).
Every example with specific numbers that I have worked out under these conditions this has been the case, but I'm not sure how to prove it in general.
Comment: I updated the question because I had a typo in the original statement of the qeustion. In particular, when I initially wrote this I asked whether $\mu p = \tau q$ (mod m). I meant to ask whether $\mu q = \tau q$ (mod m)
Answer: Yes it is. As $q$ is invertible $\mod{m}$, you are essentially asking if $\mu \equiv \tau \mod{m}$.
As $\mu p \equiv 1 \mod{a}$, $\mu p=ka +1=kmx+1$ for some $k \in \mathbb{Z}$, and so $\mu p \equiv 1 \mod{m}$.
A similar reasoning with $\tau$ gives us that $\tau p \equiv 1 \mod{m}$. We deduce that $\tau p \equiv \mu p \mod{m}$. Now, $p$ is invertible$\mod{m}$, and so this implies that $\mu \equiv \tau \mod{m}$.
Comment: That is a very nice proof Jonah, this helps a lot. Thanks!


how to install SSL certificate on Google cloud VM

Question: I have purchased a SSL certificate from Godaddy , i have .crt file , .pem file , csr file and private key file
i am having a google cloud VM with a ubuntu OS and hosted API on port 5111
i did attach SSL certificate in my code as mentioned https://timonweb.com/posts/running-expressjs-server-over-https/ in step 2
but still SSL is HTTPS endpoint is not working.
am i missing any steps , any guidance is appreciated here.
Comment: Define "not working". Why's your API running on 5111?
Comment: does need to run on port 443? not working means the API when open in browser says  connection refused
Comment: If you want to access it without typing a port number in the URL, yes.
Comment: ok even changing it to port 443 does not work. am i missing any basic steps . do we need to do anyhting else?
Comment: No clue. You haven't shared your config, you haven't answered what "not working" means exactly, etc.
Comment: what config information do you need?
Comment: Is there a reason you've *twice* now ignored the "define not working" question? **What error or other symptoms are you getting?**
Comment: Hi there. You defined **not working** as a `connection refused` right? Connection refused means that the port is not open. The good news is that the problem seems to be related with your app rather than a FW issue. The bads news is that you need to verify if your app is actually running and listening on the port. Can you please confirm that?
Answer: I was missing a step where we need to upload SSL certificate in App engine settings section and map it with domain


jQuery ajax form submission response not changing on resubmission

Question: Note: this is a jQuery coding exercise and I am not allowed to use plugins or other modules.
I have a jQuery form that gets submitted to a php page. This php page checks if the email is already taken or not. If not an account is created.
I am not going to include the php page to reduce complexity. The main focus is on jQuery.
Note: I am using the skeleton framework
HTML:

    <form id="myForm" action="validate_signup.php" method="post">

Sign Up

          <input class="u-full-width" type="email" placeholder="Email" id="email" name="email">
          Email not entered

          <input class="u-full-width" type="password" placeholder="Password" id="pword" name="pword">
          Password not entered

          <input class="u-full-width" type="text" placeholder="First Name" id="fname" name="fname">
          First Name not entered

          <input class="u-full-width" type="text" placeholder="Last Name" id="lname" name="lname">
          Last Name not entered

          <input class="button-primary" type="submit" value="Submit" name="signup">

    </form>

jQuery:
// jQuery form validation
$(document).ready(function(){

    // field mapping
    var form_fields = {
        'email' : 'email',
        'pword' : 'password',
        'fname' : 'first name',
        'lname' : 'last name'
    };

    // ajax data
    var ajaxData = {};

    // make sure form fields were entered
    $('#myForm').on('submit', function() {

        for (var field in form_fields) {
            if (!$('#' + field).val()) {
                $('#' + field).next().addClass('error_show');
            } else if ($('#' + field).val()) {
                $('#' + field).next().removeClass('error_show');
                ajaxData[field] = $('#' + field).val();
            }
        }

        // signup post field to indicate to php submission
        ajaxData['signup'] = 'Submit';

        // send data if it is all there
        if (Object.keys(ajaxData).length === 5) {
            var request = $.ajax({
                url         : 'validate_signup.php',
                method      : 'POST',
                data        : ajaxData,
                dataType    : 'html'
            });

            request.done(function(response) {
                $('#response')
                .append(response)
                .show('slow');
            });

        }

        return false;

    });

});

The main HTML line in question where the response gets printed is:

Example scenario:
If the user types in an email that is already taken

Email already in use, please use another.

Gets outputted. If the user modifies the entry and resubmits the form the following gets printed:

Email already in use, please use another.sign up complete

How can I solve this problem where I remove the old response data with the updated response?
Answer: When you call .append(), you are adding more content to the body of the element. Instead, you can call .html() to replace the body of the element.
You could change:
$('#response').append(response).show('slow');

To:
$('#response').html(response).show('slow');

But I think it would be better to call .hide() and .empty() just before making the ajax call.
$('#response').hide().empty();

That way the old response disappears as soon as the submit button is clicked, and it will animate slowly again when the ajax call returns.
Comment: Thanks! In addition to your solution how can I make it so that subsequent resubmissions get printed smoothly with `show('slow')` as the initial request does and the response doesn't just get spitted out.
Comment: If it's not too much to ask for.
Answer: Give your error-elements in html an id:

      <input class="u-full-width" type="email" placeholder="Email" id="email" name="email">
      Email not entered

with success and error function in the ajax call, you can display the received error:
var request = $.ajax({
                url         : 'validate_signup.php',
                method      : 'POST',
                data        : ajaxData,
                dataType    : 'html',
                success     : function(data) {
                     $('#requestError').html(data);
                },
                error       : function() {
                     $('#requestError').html("Error while AJAX");
                }
            });

I hope that could help you.


Module for animation when link is clicked

Question: If a user clicks ANY of the links on the drupal site I am setting up, I want to show animation before the transition to another node/page.
Is there a module for this? Or would jquery work/how would I insert this into drupal.
Here's a site that I created a long time ago, but in flash template:
http://jonesstuckey.com/
Click on ANY Link and you will see the animation.
I'm trying to apply all this flash/actionscript to my drupal site.Any suggestions
Comment: How do you want to "apply all this flash" to HTML? Flash can't animate anything that's outside Flash.
Comment: through javascript
Answer: You can override the click event on your links, as shown here.
The code from that question is:
<code>var goToURL = null;

$('a').click(function() {
   var goToURL = $(this).attr("href");
     $(el).delay(500 * i).animate({'left': '-300px'}, 1000, function() {window.location = gotoURL;});
     return false; // or e.preventDefault();
   }
});
</code>
Answer: I used the JQuery Loadinganimation module for a similar reason:

JQuery loadinganimation module shows a loading layer on page loading events.
  These may be triggered by form submission, clicking a hyperlink or executing an AJAX call.
Hyperlinks may be excluded from trigger by adding a ".noLoadingAnimation" class.
  Further "javascript" and "#" hyperlinks are automatically excluded.
  Loading and animation may be aborted by pressing "ESC".
  Hope it helps!


Dreamweaver link to button CS6

Question: OK.. This might be a stupid question but I am a newbie on Dreamweaver. I know that right click -> make link option gives you an option to link a selected text to another page. I was trying to do the same with a button but right clicking a button is not giving the make link button. How do I make a button that when clicked would take me to another page?
I am trying to replicate a google homepage and this is the code I have thus far.

    <input name="textfield" type="text" id="textfield" value="" size="100" />

    <input name="Button 1" type="submit" id="Button 1" value="Google Search" />

     <input type="submit" name="button2" id="button2" value="I'am Feeling lucky" />

Answer: You mention DreamWeaver and I don't know if you want a solution using the GUI side only or if you can go into design view. My answer is about the design view.
Your input type is submit, you need to submit the contents of a form! Something like:
<form action="googleResultReplcationPage.aspx" method="get">

      <input name="textfield" type="text" id="textfield" value="" size="100" />

      <input name="Button 1" type="submit" id="Button 1" value="Google Search" />

      <input type="submit" name="button2" id="button2" value="I'am Feeling lucky" />

</form>

To do what you want, you'll need JavaScript and change the type to Button. this obviously only works if the user has JavaScript enabled.
<input type="button" value="Google Search" onClick="window.navigate('replicationGooglePage.aspx')">

As a work around you could do it using CSS (you will also need to create the hover)
some words

.button {
  display: block;
  width: 115px;
  height: 25px;
  background: #4E9CAF;
  padding: 10px;
  text-align: center;
  border-radius: 5px;
  color: white;
  font-weight: bold;
}

Source
Out of these 3 options, the first suggestion is IMO the best way.
As an aside, don't use           as it doesn't always work on every browser (some browsers used to only read the first), instead use a style/css and use Left or Padding or Margin (depending on your code/setup/design) - although you would be better off making your website centered!
<form action="googleResultReplcationPage.aspx" method="get">

      <input name="textfield" type="text" id="textfield" value="" size="100" />

      <input name="Button 1" type="submit" id="Button 1" value="Google Search" />
      <input type="submit" name="button2" id="button2" value="I'm Feeling lucky" style="margin-left:50px;" />

</form>

Dreamweaver link to button CS6


Iptables "if not" condition?

Question: I am trying to create a rule for iptables which logically does the following:
IF [destination != 192.168.0.1]
    forward port 80 requests to port 3128
else
    carry on like this never happened

How can it be done?
Comment: end solution `-A PREROUTING -i eth0 -d ! 192.168.0.1 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128` got me to my goal
Answer: You can negate any iptables condition with a !. Of course, if you are using bash, you need to use a \ as well to prevent some dirty syntax error given by the shell to you.
iptables -t nat -I PREROUTING \! -s 192.168.0.1 -p tcp --dport 80 -j DNAT --to your_outer_ip:3128

Comment: ok this should be what I need, I shall try this though just to note its the same IP just when a local server request is made the caching server interferes so I am trying to by pass the local address this way .
Comment: Your `!` is misplaced; that is the old syntax. This will throw a deprecation warning. The current syntax is, e.g. `! -s 192.168.0.1`
Comment: @MichaelHampton Thank you - I corrected - so goes it for old boys :-)
Comment: this is what I used to meet my needs and it worked perfectly so thank you! **-A PREROUTING -i eth0 -d ! 192.168.0.1 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128**

Iptables "if not" condition?


Laravel MethodNotAllowedHttpException when creating a library

Question: I'm getting a MethodNotAllowedHttpExceptions after trying to add a helper library to laravel 4. I've created a class within app/libraries/Time.php, I have added the 'libraries' folder to the composer.json file, under the classmap.
In my global.php file I've added: app_path().'/libraries' to the addDirectories array. Afterwards I did the ./composer.phar dump-autoload.
And under my loginController is where I'm trying to make use of the class. The class in full is below this.
app/libraries/Time.php
class Time {

// convert times to user submitted time
public function set($zone)
{
    // Get user timezone from map
    $timezone = $this->get($zone);

    // set default timezone
    date_default_timezone_set($timezone);
}

// maps the timezone the user gives
private function get($time)
{
    $zone = Array(
        'PST'  => 'America/Los_Angeles',
        'MST'  => 'America/Denver',
        'CST'  => 'America/Chicago',
        'EST'  => 'America/New_York',
        'HST'  => 'America/Adak',
        'AKST' => 'America/Anchorage'
    );

    return $zone[$time];
}
}

I'm curious as to how I can keep the httpexception from happening and where I might be going wrong in creating this library.
UPDATE: For people wondering, the loginController is a resource controller and I'm calling the class in store() like so: Time::store($zone); It's this one line that's causing the error.
Answer: I'm not sure if it's causing your problem but set isn't a static method in your class. Try this:
public static function set($zone)
{
    // Get user timezone from map
    $timezone = self::get($zone);

    // set default timezone
    date_default_timezone_set($timezone);
}

// maps the timezone the user gives
private static function get($time)
{
    $zone = Array(
        'PST'  => 'America/Los_Angeles',
        'MST'  => 'America/Denver',
        'CST'  => 'America/Chicago',
        'EST'  => 'America/New_York',
        'HST'  => 'America/Adak',
        'AKST' => 'America/Anchorage'
    );

    return $zone[$time];
}

Comment: You my friend are the man. That was it. I wasn't sure how to call get without using $this->get. But both those functions not being static is what caused it. This solved it.
Comment: No worries, glad it helped. You might want to look at putting stuff like this in a 'service provider'. There's a good article here: http://fideloper.com/create-facade-laravel-4
Comment: Thanks. I really appreciate the link. I'll take a look at it and possibly change it around to make it work. Right now though, deadlines :P
Answer: The error MethodNotAllowedHttpException is related to the HTTP method you are using in your route:
So if you have:
Route::get('posts', ...);

Laravel will not accept a POST to that route, you need to create a
Route::post('posts', ...);

You might also have an ambiguous route: a route wich was not supposed to be hit, is being hit instead of the other one. This could cause a route collision:
Route::get('{name}', ...);

Route::resource('posts', ...);

If you try to hit /posts it will hit your first get and not the resource.
Comment: @Antonio_Carlos_Ribeiro The route is a post. It's a Resource controller and it's being called in the loginController under the store() function. So it should be a post route. Also, the route works without this one line: Time::set($zone);
Comment: Edited to add another possibility.
Comment: So I did a ./artisan routes to check the routes under my app. I'm not seeing any collision but just incase, I uploaded my routes to pastebin here: http://laravel.io/bin/mJQ39. **POST portal/store** is the one that's causing the issue.


Executar URL de sistema diariamente através do agendador de tarefas do Windows

Question: Gostaria de agendar uma tarefa no Agendador de Tarefas do Windows. Consiste em, diariamente, em determinado horário, abrir o navegador e executar determinada URL (que executará algumas tarefas {inserts, updates..) de um software).
Já sei como agendar a tarefa. Preciso somente do script .bat que fará a ação de abrir o navegador e executar a URL. Alguém que possa me ajudar?
Answer: Partindo do ponto que já sabe como agendar a tarefa, então crie um arquivo em lote (*.bat) com a seguinte linha e agende sua execução:
<code>start https://br.stackoverflow.com
</code>
Isso fará o seu navegador padrão abrir a URL informada.
Outra alternativa é agendar uma tarefa solicitando a execução do navegador desejado e passando a URL como argumento.

Neste caso a tarefa está agendada para ser executada no Firefox, mesmo que o navegador padrão seja outro.


button for boolean field during node display

Question: I have a boolean field in my content type which takes values either 1 or 0. I want to provide a button instead of just displaying the value of field so that the user can click on it and toggle the value.
Is it possible to doing something like this ?
Answer: Maybe you should check out the Flag module. Out of the box this module will give you the boolean field, the ajax button on the node view, and rules integration.
The flag module integrates nicely with views. Here is some helpful documentation. http://drupal.org/documentation/modules/flag
You will no longer need the boolean field on your node though so, depending on existing content may require a migration.
It does have a very large user base too and it may save you some development.
Answer: If you want to submit a new value for the field on the actual toggle then you'll need to write a custom module with an ajax handler that saves that value for you.
If you just want to change the look of the field and can wait for the 'Save' button to be pressed to save the updated value you could probably do everything in CSS with maybe a bit of javascript if you want to make it look more slick.
Comment: I want to write an ajax handler...  Can you point me to any tutorials on how to code it?
Comment: Is it also possible to use rules and the button field to do something like this ?
Comment: Are you on Drupal 6 or 7?
Comment: I use Drupal 7.
Comment: Ignore what I said and go with @thepearson 's answer
Answer: The best answer to this is to Use the Button-Field module and use rules to create actions when the button is clicked. The module already has integration with rules.
Comment: Also note
[rules_link](https://www.drupal.org/project/rules_link) and
[rules_linkevent](https://www.drupal.org/project/rules_linkevent)
Answer: Fasttoggle may be what you want.

Speeds up common administration tasks like unpublishing or promoting nodes or blocking users through the use of AJAX callbacks. This saves lots of page loads. If JavaScript is not available, it degrades gracefully to a regular confirmation page.
Comment: I would gladly edit it, to provide relevant quote, but it seems linked module is for "common administration tasks", not for field values, and no part of it's description suggest it's relevant.
Comment: Yes, it looks like this is not for fields. Another one only for properties is [itoggle](https://www.drupal.org/project/itoggle)


how to use awk or sed command (OS level commands) in Sybase level

Question: I have one text file in host level Ex: /tmp/file.txt. So I have one script and I need to read the line by line from file.txt, so I used sed command. So I am using while loop in the script and I have logged in to DB level, how can I use sed command or similar to sed for accessing one line data from file.txt ?in database level
Ex: sed -n '5p' "/tmp/file.txt"   (or) awk 'NR==5' /tmp/file.txt
So this output I want to check in db level after isql command? Is it possible. Can any one suggest the alternate?
Answer: You are probably looking for the Sybase Adaptive Server's xp_cmdshell:

Description
Executes a native operating system command on the host
  system running Adaptive Server.
Syntax
xp_cmdshell command [, no_output]

For your commands that would be:
xp_cmdshell 'sed -n 5p /tmp/file.txt'

xp_cmdshell 'awk "NR==5" /tmp/file.txt'

Be careful with different quotation types when using quotes inside quotes.
Comment: I have tried that too. It is not working..                                                               1> xp_cmdshell command [ awk 'NR==5' /userids.txt,no_output]
2> go
Msg 102, Level 15, State 181:
Server '', Line 1:
Incorrect syntax near '[ awk 'NR==5' /userids.txt,no_outpu'.                                       Tried for sed also the same syntax error. i have tried exec xp_cmd shell also but no use
Comment: I bet you're supposed to replace 'command' with the actual command:  `xp_cmdshell awk 'NR==5' /userids.txt`
Comment: Exactly! That's only the **syntax**. In that kind of lines `[ ]` indicates that the `, no_output` is optional. The `command` is replaced with the actual command. See the linked manual: it has examples and everything.
Answer: Re: So this output I want to check in db level after isql command? Is it possible. Can any one suggest the alternate?
Are you saying:
1) want to process the output of a db level command using shell script syntax? Or,  2) Or take the output of a shell script and send it to be processed in the database?
If 1), there's a alternate to isql called sqsh.  You can do this with sqsh:
sqsh -SMYSERVER -Dmydb -Umylogin -w180
<mypassword>
select blah_column from blah_table
go |  sed 's/thingy/widget/g'

If 2), then have your shell script produce SQL commands for output and run that against the db using isql -i (or sqsh -i)
Note, if using awk in sqsh, be careful.  Sometimes it needs extra backslashes for the dollar signs


bootstrap timepicker with angularjs

Question: I need to use Bootstrap TimePicker with AngularJS. I am new to AngularJS.
I have edit option for end date. on edit timepicker is shown but not working in AngularJS.
HTML:

        End Time
         {{actDetailsData.endTime | date: 'shortTime'}}

                <input id="timepicker1" ng-model="actDetailsData.endTime" type="text" class="form-control input-small">

Controller:
angular.element(document).ready(function () {
        angular.element('#timepicker1').timepicker();
      });

Answer: you can use ui-bootstrap instead of bootstrap.
at first download ui bootstrap then add ui bootstrap script and css link to your project .then add ui.bootstrap to your module
angular.module('myModule', ['ui.bootstrap']);

and at the end add datepicker like this :
 <input type="text" class="form-control" uib-datepicker-popup="{{format}}"
 ng-model="dt" is-open="popup1.opened" min-date="minDate" max-date="maxDate"
 datepicker-options="dateOptions" date-disabled="disabled(date, mode)"
 ng-required="true" close-text="Close" alt-input-formats="altInputFormats" />

ui bootstrap datepicker in github
Comment: Thanks! It is really more exciting. but is there any similar way to use the uib-timepicker with input format.

bootstrap timepicker with angularjs


Add custom domain to API gateway without serverless-domain-manager

Question: I want to add a custom domain to the API Gateway using serverless framework but without "serverless-domain-manager" or any other plugin. I am looking for a more native way, maybe extending a resource in "serverless.yml"
All articles suggest that plugin, but it isn't the best for multi environment pipelines
https://www.serverless.com/blog/serverless-api-gateway-domain/
Answer: Doing it manually is not that complicated, here is the full explanation
Add a custom domain to all envs

Issue a certificate for the domain in the same region of serverless project, in my case us-east-2
Go to API Gateway > Custom domain names > Create, use Regional endpoint type if using HTTP APIs
In the created domain there is API Gateway domain name, you'll need to point a CNAME record to it
Finally go to API mappings and create the mappings, in my case main and prod with stage $default
Answer: API Gateway with a custom domain is configured to use TLS 1.2, and it supports some weak cipher. These weak ciphers are removed in TLS 1.3 which is only supported in CloudFront distributions at the moment.
Some security tools like AppScan raised these issues for me during the security testing of these APIs.
You can check the details here.
https://security.stackexchange.com/questions/254667/are-weak-cipher-suites-for-tls1-2-a-valid-concern
If security is concerned, I would suggest using a cloud front distribution in front of the API gateway.
https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-cloudfront-distribution/


Hdinsight Spark Session issue with Parquet

Question: Using HDinsight to run spark and a scala script.
I'm using the example scripts provided by the Azure plugin in intellij.
It provides me with the following code:
val conf = new SparkConf().setAppName("MyApp")
val sc = new SparkContext(conf)

Fair enough. And I can do things like:
val rdd = sc.textFile("wasb:///HdiSamples/HdiSamples/SensorSampleData/hvac/HVAC.csv")

and I can save files:
rdd1.saveAsTextFile("wasb:///HVACout2")

However, I am looking to load in a parquet file. The code I have found (elsewhere) for parquet files coming in is:
val df = spark.read.parquet("resources/Parquet/MyFile.parquet/")

Line above gives an error on this in HDinsight (when I submit the jar via intellij).
Why don't you use?:
val spark = SparkSession.builder
  .master("local[*]") // adjust accordingly
  .config("spark.sql.warehouse.dir", "E:/Exp/") //change accordingly
  .appName("MySparkSession") //change accordingly
  .getOrCreate()

When I put in spark session and get rid of spark context, HD insight breaks.
What am I doing wrong?
How using HdInsight do I go about creating either a spark session or context, that allows me to read in text files, parquet and all the rest? How do I get the best of both worlds
My understanding is SparkSession, is the better and more recent way. And what we should be using. So how do I get it running in HDInsight?
Thanks in advance
Answer: Turns out if I add
val spark = SparkSession.builder().appName("Spark SQL basic").getOrCreate()

After the spark context line and before the parquet, read part, it works.


bootstrap input field and dropdown button submit mail form

Question: I have the following problem. I have a form where I can choose from three options. The problem is that it does not send the selected option while the other sections Name, surname, etc. send. Below I am sending the code:
thank you in advance

                    <button class="btn btn-dropdown dropdown-toggle" type="button" id="service-type" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                      Choose

                    </button>

x1

x2

x3

php code:
<?php
$to = 'email@example.com';
$subject  = "Appointment Form";
$servicetype = stripslashes($_REQUEST['service-type']);
$msg = "";
$msg .= "Service Type: ".$servicetype."\r\n\n";  // add sender's sources to the message
$mail = @mail($to, $subject, $msg, "From:".$email);

if($mail) {
   header("Location:index.html");
} else {
   echo 'Message could not be sent!';
}

?>

I also added JS but it still does't work
Dropdown Select
    $( document.body ).on( 'click', '.dropdown-menu li', function( event ) {
      var $target = $( event.currentTarget );
      $target.closest( '.dropdown' )
         .find( '[data-bind="label"]' ).text( $target.text() )
            .end()
         .children( '.dropdown-toggle' ).dropdown( 'toggle' );
      return false;
   });

Comment: where is your `` tag?
Comment: I used dropwdown, so I think I don't need it?
Comment: If you want to use Bootstrap code for your dropdown list, you'll need to add some JavaScript to handle changes to the dropdown and a hidden form element to handle the 'service-type' value.

(The Bootstrap dropdown isn't made to be a drop-in replacement for a `select` element. You need to add some JavaScript to handle when a user selects something.)
Comment: @Jeffwa I added JS (check my edit post) but it still does't work
Comment: HTML Form elements do *not* get transmitted on submit if they do not have a `name` attribute. Also, `button`s do not get transmitted unless they are clicked.
Comment: @Jeffwa Do you know how to fix it?
Comment: @emix09, see my answer
Answer: HTML:

        <button class="btn btn-dropdown dropdown-toggle" type="button" id="service-type" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
            Rodzaj usługi

        </button>

x1

x2

x3

    <input type='hidden' name='service-type'>

JavaScript:
$(document.body).on('click', '.dropdown-menu li', function(event) {
    event.preventDefault();

    var $target = $(event.currentTarget);

    $target.parents('.dropdown').sibling('[name=service-type]').val($target.text());

});
Answer: you cant pass values to php without name attribute and form tag . you can directly set it with select tag
<form action="file.php" method=POST>
    <select name=option>
 <option value=0 selected>0</option>
 <option value=1> 1</option>
</select><input type=button value=submit>
</form>

Answer: Suppose the name of form is mail_form, and there is a hidden form element to hold the choice information with id service-type-holder and name service-type. Then the following code could be used with inline Javascript:
<form  name="mail_form" id="mail_form" action="" method="post">
<input type="hidden" name="service-type" id="service-type-holder">

        <button class="btn btn-dropdown dropdown-toggle" type="button" id="service-type" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
            Choose

        </button>

x1

x2

x3


How to write a numeric field in a VBA expression using MS Access 2016?

Question: I have a code line referencing a field as a Date format. I need to reference another field as numeric format.
This is my code for a date format field:
Private Sub cmbsearch_Click()
Dim varFilter As Variant, stdcard_id As String, txtname As String, txtrecord
As String, strTableName As String
strTableName = "tbl01"
    If IsNull(Me.stdcard_id) Then
        Me.stdcard_id.SetFocus: Exit Sub
    End If

varFilter = "[dateofbirth]= # "& Forms!frm_stid_name_record & "#"
....
End Sub

This is my code line for a numeric format field, but I don't know to write the code after the "=" symbol
varFilter = "[std_id]="

Comment: Your headline says MS Access but your tags say Excel-VBA. Please [edit] and clarify! If you use the wrong tags, it shows up in the wrong categories and you might not get an answer.
Answer: try
Dim stdid As Long

stdid = Val(Forms!frm_stid_name_record)

varFilter = "[std_id]=" & stdid & " "

Comment: I apologize for my mistake.
My code lines are from VBA Access 2016 cmd button.
I have a Form with three TextBoxes already declared in the previous post.
@Dy.Lee. In my code, I need to include 'Forms!frm_stid_name_record...'

'varFilter = "[std_id]=" & Forms!frm_stid_name_record & " "  '

A Compilation Error Type mistmatch occurs in: 'Forms!frm_stid_name_record'

I have been googling but not found any help to fix the Error.
Comment: @SebastianSalazar, If Forms!frm_stid_name_record is a character, you can convert it to a number and then complete the sql statement.
Comment: In my Db Forms!frm_stid_name_record is the Form name.
My tbl01 has three fields: 'std_id (Double)', 'stdname (string)', 'stdrecord (Double)'
For my cmd button in my Form I am trying to use two Functions:
'txtname = Nz(DLookup("[stdname]", strTableName, varFilter), "N/A")'
'txtrecord = Nz(DLookup("[txtrecord]", strTableName, varFilter), "N/A")'
Thererefore, I need to fix the Error to test above code lines.
I'm confused, since, I thought I was working with VBA code.


C++/SDL problem of double inclusion

Question: I'm getting this error from compilator:
1>Linking...
1>main.obj : error LNK2005: "int g_win_flags" (?g_win_flags@@3HA) already defined in init.obj
1>main.obj : error LNK2005: "struct SDL_Surface * g_screen" (?g_screen@@3PAUSDL_Surface@@A) already defined in init.obj
1>MSVCRTD.lib(cinitexe.obj) : warning LNK4098: defaultlib 'msvcrt.lib' conflicts with use of other libs; use /NODEFAULTLIB:library
1>.\Debug\Heroes are back!.exe : fatal error LNK1169: one or more multiply defined symbols found

It looks like that g_win_flags and g_screen are twice included, but I don't understand why.
Here is the source:
main.cpp
#include <iostream>
#include "dec.h"
#include "init.h"

int main(int argc, char *argv[]){

    init();
    return 0;
}

dec.h
#ifndef DEC_H
#define DEC_H

#include <SDL.h>
#include <iostream>

#pragma comment(lib, "SDL.lib")
#pragma comment(lib, "SDLmain.lib")

using namespace std;

int g_win_flags = SDL_HWSURFACE|SDL_DOUBLEBUF;

SDL_Surface *g_screen = NULL;

#endif

init.h
#ifndef INIT_H
#define INIT_H

bool init();

#endif

init.cpp
#include "dec.h"

bool init(){
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) == -1){
        cerr << "Unable to initialize SDL" << endl;
        return false;
    }
    g_screen = SDL_SetVideoMode(640, 480, 0, g_win_flags);

    return true;
}

Can someone help? Thanks in advance and have a nice day :)
Comment: You should not define variables in header files other than extern declarations.
Comment: FYI that isn't a compiler error, it's a linker error.
Answer: You define and initialize the variables in the header.
You should just declare them in the header (dec.h) without any initializers:
extern int g_win_flags;
extern SDL_Surface *g_screen;

Then define them once in one file - presumably dec.cpp - with the initializations.
As it was, you were defining them in every source file that included 'dec.h' and then running foul of the ODR - One Definition Rule.
Answer: in dec.h you want
extern int g_win_flags;

extern SDL_Surface *g_screen;

and then to define and initalise them in just dec.cpp
Update:
#include "dec.h"
int g_win_flags = SDL_HWSURFACE|SDL_DOUBLEBUF;

SDL_Surface *g_screen = NULL;

The general rule of thumb is "nothing in a header file should take up any space in the output of the compiler". (There are exceptions to this obviously)
In practice this means extern variable declarations are fine, as are function declarations, but not definitions.
Answer: You have included files into two different source files (init.cpp and main.cpp) that define instantiated variables.
You need a way to be sure they are 'externed' in all but one source file.
Comment: See Jonathan's answer below - that's what I meant to say (but didn't)
Answer: Well, I tried to do what you've told me guys, but compilator is complaining:
1>.\heroes are back!\dec.cpp(2) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>.\heroes are back!\dec.cpp(4) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>.\heroes are back!\dec.cpp(4) : error C2040: 'g_screen' : 'int' differs in levels of indirection from 'SDL_Surface *'

Here is the dec.h
#ifndef DEC_H
#define DEC_H

#include <SDL.h>
#include <iostream>

#pragma comment(lib, "SDL.lib")
#pragma comment(lib, "SDLmain.lib")

using namespace std;

extern int g_win_flags;

extern SDL_Surface *g_screen;

#endif

dec.cpp
#include "dec.h"
g_win_flags = SDL_HWSURFACE|SDL_DOUBLEBUF;

g_screen = NULL;

What is wrong in this code? Sorry for asking dumb questions, but I'm only learning C++ :)
Comment: You didn't specify types in the dec.cpp file, which is what it's telling you. You need to have `extern (type) (name);` in the header and `(type) (name) = (value);` in the code.

C++/SDL problem of double inclusion


How do I load specific data from local storage to a new page using JS ES6 and jQuery?

Question: I am developing a simple webapp for a fictional detective using Javascript ES6 and jQuery.
The main page (index.html) shows default cases that are stored in localStorage. For this, I made a script file (cases.js) containing a defaultCaseList object literal, and an index.js script-file containing a function to load and display the cases, and it works fine.
Every case on the main page has an "OPEN" button which is supposed to display that specific case on another page (single-case-page.html) when pressed on. Now, this is where I got stuck. How do I load data for that specific case from local storage into another html page when pressing on the "open" button? Which functions and script-files do I need for this? How do I set up the HTML in the singe-case-page for this?
This is the code for the function that loads and displays default cases on the main page:
`$(document).ready(() => {
getCaseList();
});

function getCaseList() {
window.caseList = JSON.parse(localStorage.getItem("caseList"));
$("#main-container").empty();
console.log(caseList);

for (let key in window.caseList) {
    var cases = caseList[key];
    $("#main-container").append(`

${cases.title}

Kategori: ${cases.kategori}

Etterforsker: ${cases.etterforsker}

            Open

    `);
}
}`

This is the code from the script-file containing a default case list:
`var defaultCaseList = [
{
    id: 1,
    title: "Operasjon RICO",
    kategori: "Organisert brottslighet",
    etterforsker: "Beck",
    imageUrl: "../images/case-file-pic.jpg"
},
{
    id: 2,
    title: "Operasjon Blåval",
    kategori: "Organisert brottslighet",
    etterforsker: "Wallander",
    imageUrl: "../images/case-file-pic.jpg"
},
{
    id: 3,
    title: "Elena",
    kategori: "Spionasje",
    etterforsker: "Veum",
    imageUrl: "../images/case-file-pic.jpg"
},
{
    id: 4,
    title: "Anonymous angriper infrastruktur ",
    kategori: "Cyber-trusler, Rikets sikkerhet",
    etterforsker: "Inspector Gadget",
    imageUrl: "../images/case-file-pic.jpg"
},
{
    id: 5,
    title: "Test Titel 5",
    kategori: "Test kategori 5",
    etterforsker: "John McLane",
    imageUrl: "../images/case-file-pic.jpg"
},
{
    id: 6,
    title: "Test Titel 6",
    kategori: "Test kategori 6",
    etterforsker: "James Bond",
    imageUrl: "../images/case-file-pic.jpg"
},
{
    id: 7,
    title: "Test Titel 7",
    kategori: "Test kategori 7",
    etterforsker: "Lincoln Rhymes",
    imageUrl: "../images/case-file-pic.jpg"
},
{
    id: 8,
    title: "Test Titel 8",
    kategori: "Test kategori 8",
    etterforsker: "Rick Ross",
    imageUrl: "../images/case-file-pic.jpg"
},
{
    id: 9,
    title: "Test Titel 9",
    kategori: "Test kategori 9",
    etterforsker: "Sherlock Holmes",
    imageUrl: "../images/case-file-pic.jpg"
},
{
    id: 10,
    title: "Test Titel 10",
    kategori: "Test kategori 10",
    etterforsker: "Barnaby Jones",
    imageUrl: "../images/case-file-pic.jpg"
}
];

if (!localStorage.getItem("caseList")) {
localStorage.setItem("caseList", JSON.stringify(defaultCaseList));
}`

Answer: So assuming that both your HTML pages share the same domain, they share the same localStorage and have access to your defaults. Knowing that, all you need to pass along, is the ID for the item you clicked on.
Something like this:
http://origin.com/single-case-page.html?id=1234
You can pluck out the query string parameter using jQuery like so: jquery get querystring from URL
Then you can just filter through your list of cases for the id you want:
const id = getQueryStringId(); // You'll need to write this function. also don't forget to convert to Number
const cases = JSON.parse(localStorage.getItem("caseList"));
const case = cases.find(c => c.id === id);


Variance of marginals of truncated bivariate normal distribution

Question: I have a truncated bivariate normal distribution
$$f(x,y)=\begin{cases}\frac{1}{2\pi \sigma_{1}\sigma_{2}\sqrt{1-\rho^{2}}}\exp\left(-\frac{z}{2(1-\rho^{2})}\right) &, |x| \leq a\\0 &, |x| > a\end{cases}$$
, where $$z=\frac{x^2}{\sigma_{1}^2}+\frac{y^2}{\sigma_{2}^2}-\frac{2\rho xy}{\sigma_{1}\sigma_{2}}$$
moreover, in case $f(x,y)$ would be not truncated, it would be normalized.
Is there a simple way to calculate variance of marginal distributions ?
I know that if the distribution is not truncated, variance of marginal distributions are $\sigma_{1}^2$ and $\sigma_{2}^2$, but what if the distribution is truncated ?
Comment: Is $f(x,y) a pdf? Or is the integral = 1?
Comment: @wolfies You are right. $f(x,y)$ would be normalized only if not truncated. I corrected about viarance and standard deviation.
Comment: $f(x,y)$ is a normalized pdf, so integral=1
Comment: $f(x,y)$ is plainly not normalised, as the normalising constant must depend on $a$ - and you do not even have a normalising constant. Also, you are confusing variance with standard deviation.
Answer: It depends what one means by simple ...
Given  $\mu = (0,0)$,  $\quad \Sigma =\left(
\begin{array}{cc}
 \sigma _1^2 & \rho  \sigma _1 \sigma _2 \\
 \rho  \sigma _1 \sigma _2 & \sigma _2^2 \\
\end{array}
\right) \quad $ and $\quad a>0$.
Unconditional model
Let $(X,Y) \sim N( \mu, \Sigma)$ with pdf $f(x,y)$ and cdf $F(x,y)$:

Normalising constant
Let $c = P(-a<X<a) = F(a,\infty)-F(-a,\infty) =2 \big[ F(a,\infty) -\frac12 \big] = \text{Erf}\left(\frac{a}{\sqrt{2} \sigma _1}\right)$
where Erf denotes the error function. Or, automating it:

Doubly Truncated model
Let $\big(X \big| -a<X<a,Y\big)$ have pdf $g(x,y)$. Then:

Then, the variance-covariance matrix for $(X,Y)$ when $X$ is truncated above at $a$ and below at $-a$ is given by:

where I am using the Varcov function from the mathStatica package for Mathematica to automate the nitty gritties.

The top left element denotes $\text{Var}(X)$ for the conditional model $g$ and yields a closed-form solution. An interesting feature is that the conditional variance of $X$ does not depend on $\rho$ - this appears to be because the truncation is symmetrical around the mean 0.
The bottom right entry (with the integral sign) denotes $\text{Var}(Y)$ for conditional model $g$: since the software is unable to find a closed-form solution, the integration does not appear to be 'easy'.
The off-diagonal elements denote $\text{Cov}(X,Y)$ for conditional model $g$.

Hope this helps.
Comment: Thank you. Indeed, this helps a lot. I was mainly interested in $Var(Y)$, and now i understand calculation is not so easy as i wish. Thank you again!


Using probability to detect exam cheating (identical wrong answers)

Question: Hypothetical:  What's the probability that two people taking a test with 10 questions get the identical wrong answers?  (Let's say there are 4 choices per problem)
Should we first break this down into asking "What are the odds of getting the same questions wrong?"
Also, would it be easier to first use the number incorrect as a constant?  ie:   What's the probability that two people taking a test with 10 questions get THREE identical wrong answers? (and the other 7 correct)
Comment: Are these people guessing each answer at random?
Comment: If all students wrongly answer that the Earth is flat, it may not be a case of cheating but of bad teaching ...
Comment: One of my undergrad professors gave us a final paper instead of an exam. And he said that in the event that all the papers handed will have the same answers he is going to assume this is a highly improbable-but not impossible sort of event.
Answer: As it has been mentioned already, the problem is ill-posed and the answer can be any number from $0$ to $1$ depending on the situation. I am writing it just to state it explicitly. The extreme points are
Great Inquisitor (year 13..): Here are 4 cosmology questions. Your verdict will depend on what answers you choose (close to $1$)
Teacher (any year you want): Last time you were caught cheating. If you both submit the same wrong answer again, I'll raise the question about expelling you both from the school!
(close to $0$)
"Close to" rather than "=" because the assumption that human intelligence is greater than human stubbornness is dubious. :-)
The intermediate points are like:
What nation invented the compass?
1) Americans
2) Chinese
3) Babylonians
4) Klingonese
Comment: Nice example. Any reasonable person should give one of two answers, so all wrong answers should be identical.
Comment: What's interesting is that most multiple choice quizzes are just like that, except when the teacher takes special effort to hide the right answer or does a nasty thing of the kind $\sqrt 7$ is closest to a) 2.6456 b) 2.6457 c) 2.6458 d) 2.6459 (to which any normal person should just respond "and who would care remembering it with this precision or seeing one of them as any different from the other three?") :-)
Answer: Whether one person gets a question wrong or right, the other has to get the same answer. If the answer was wrong, the second person needs to get the same answer to fit the condition that they get the same wrong answers. If the answer was right, the second person needs to get it right as well; otherwise, he would have answered a question wrong that the first person answered right.
Using this logic, the probability of the condition holding for a one-question test is $\frac{1}{4}$. So, for x amount of questions, the probability would be $\frac{1}{4^x}$. And we can generalize this result further by declaring the number of choices for each question to be y. Then the probability of the condition holding is $\frac{1}{y^x}$.
Comment: What a perfect example of restating the premise!  I was barking up the wrong tree until you cleared the mist and restated the question as, "What are the odds they select all the same answers"  This is a much simple probability problem.  Thanks!
Answer: The accepted answer here is wrong.  You cannot simply multiply probabilities of A and B to find the probability of A AND B unless these events are independent and uncorrelated, which is not generally true for test questions.  Looking at test results will generally show that all answers are not chosen with equal likelihood.  Even if that weren't true, any two questions on an exam could be highly correlated -- they might both depend on the same information or assumptions.  Also, any two students answering otherwise uncorrelated questions might be highly correlated -- especially identical twins living in a bubble.  In short, you can't answer the question without detailed information about the test and the students.
The accepted answer is right for the question only if you assume the students chose completely at random, a very unrealistic assumption.
I hope people will stop and take a moment to think about this more.  The title of this is "Using probability to detect cheating".  There are probably teachers falsely accusing students of cheating based on their confidence in the credibility of math.stackexchange, and this wrong answer.  It is possible using naive approaches to detect cheating in very extreme cases, but otherwise it requires very sophisticated techniques.  This isn't it.
Comment: To understand my point, answer this.  What if 90% of the test-takers choose the first multiple choice answer for question 1.  How can this choice have a 1/4 probability as I the accepted answer says?  Isn't it 9/10 probability?  And if 100% of people who chose that answer, also choose the first answer for the second question, that combination has at least a 9/10 probability, not 1/4 * 1/4.
Comment: Answers are uncorrelated.  If you study randomness, AAAAA is just as probable as ABCDE or ACBED.


Change the Mandatory field based on selection in webform

Question: I have Webform with a radio button type field named as "preferred contact method", for selecting email or phone.
When user select the email I want to set the email field as mandatory or if user select the phone I want to set phone field as mandatory.
How to handle this in Webform Drupal 7.
Comment: You just take a try for webform_conditional module https://www.drupal.org/project/webform_conditional
Answer: That is an interesting thing to have, but i don't think Webform support such a functionality. However they are some other way to achieve the same result.
Using Webform Conditional module. you can have two sets of  hidden questions, and only one set of question could be visible base on user selected choice.
If user click on phone the first set of question will be display to user where the phone is a mandatory and email optional.
If user click on email the second set of question will be display to user where you can have email as mandatory and phone as optional.
You can ready more about alternative ways here .
Answer: You can add '#states' for the field in hook_form_alter() . Check this question How to make a form required with states?


how to solve this equation $z=yb\cot(bx/2)$?

Question: how to solve this equation $z=yb\cot(bx/2)$?
$b$ is unknown, the $x,y,z$ are known numbers, and $x\ne0,b>0$, we want to have the solution for $b$. Until now I have no idea about this.
Comment: I do not think that you could obtain explicit solutions. Only numerical methods could be used. If you want, give me values for $x,y,z$ and I shall try to show you how to proceed.
Comment: @ClaudeLeibovici thankyou, for example, x=1,y=1,z=1.
Comment: With $u=(bx)/2$ and $v=(zx)/(2y)$ your equation can be written as $u=v\tan{u}$. To get a rough idea you can plot $y=u$ and $y=v\tan{u}$. Their intersections are the solutions.
Comment: @Urgje how did you derive that?
Comment: @Darksonn  $\begin{eqnarray*}
z &=&yb\cot \frac{bx}{2} \\
\frac{zx}{2y} &=&\frac{bx}{2}\cot \frac{bx}{2} \\
\frac{bx}{2} &=&u,\;\frac{zx}{2y}=v \\
u &=&v\tan u
\end{eqnarray*}$
Answer: You have to solve $$f(b)=y~ b\ cot\Big(\frac {b~x}{2}\Big)-z=0$$ where $x,y,z$ are given constants. I suppose you noticed that $f(b)=f(-b)$; so we can just focus on positive solutions. You also know that there are discontinuities if $b x = 2 n \pi$; so we shall just try for the first solution, assuming there is one between $b=0$ and $b=\frac{2 \pi}{x}$.
A simple and classical procedure for solving nonlinear equations $f(b)=0$ is Newton, provided a "reasonable" starting value $b_0$. From this point, Newton scheme is $$b_{n+1}=b_n-\frac{f(b_n)}{f'(b_n)}$$ For your problem, after some simplifications, $$f'(b)=\frac{y (b x-\sin (b x))}{\cos (b x)-1}$$ Fot he case you gave ($x=y=z=1$), we can notice (by simple inspection) that $f(0)=1$ and $f(\pi)=-1$. So, there is a root between $0$ and $\pi$ and we shall start with $b_0=\frac{\pi}{2}$. The successive  iterates of Newton method are then : $b_1=2.57080$, $b_2=2.34796$, $b_3=2.33121$,$b_4=2.33112$ which is the solution for six significant figures.


Linq To Entity string to int conversion in order by

Question: There is a table in our database the stores year and month, each being a char. The existing Linq to Entity query looks like this:
from mc in repository.table.AsQueryable()
orderby mc.Year descending, mc.Month descending
select mc).FirstOrDefault()

The issue with this is that it is ordering by string and not int, leading to the incorrect row being returned from the query.  I have tried to convert the year and month to int and datetime, both throwing an error saying:
"LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method, and this method cannot be translated into a store expression."
(from mc in repository.table.AsQueryable()
 orderby mc.Year descending, Convert.ToDateTime(mc.Month) descending
 select mc).FirstOrDefault()

OR
"LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression."
(from mc in repository.table.AsQueryable()
 orderby mc.Year descending, Convert.ToInt32(mc.Month) descending
 select mc).FirstOrDefault();

As you can see, I cannot cast the month and year into INTs first because it is using the data from the table, not external data.
PS: I do not have the authority to change the tables to make the two columns INTs.
Anyone know how to approach this?
Comment: Check this [SO question](http://stackoverflow.com/questions/5971521/linq-to-entities-does-not-recognize-the-method-double-parsesystem-string-met)
Answer: I would recommend that you take a look at the SqlFunctions class, most notably about the DatePart method, which can be used with Entity Framework (with no exceptions), and will convert strings into the dates for you to be properly ordered by.
Answer: As @IronMan84 noticed solution below works only if you have .edmx file.

Add the following xml to your .edmx file. (Just do a 'Find in Files' in Visual Studio </Schema> and place it before this node):
<Function Name="IntParse" ReturnType="Edm.Int32">
  <Parameter Name="stringvalue" Type="Edm.String" />
  <DefiningExpression>
    cast(stringvalue as Edm.Int32)
  </DefiningExpression>
</Function>
Add the following static function to your auto-generated Entity Framework class file:
public partial class YourObjectContext
{
    [EdmFunction("YourModel", "IntParse")]
    public static double IntParse(string val)
    {
        return int.Parse(val);
    }
}
You are ready to go, just add the new function to your LINQ Query:
from mc in repository.table.AsQueryable()
orderby YourObjectContext.IntParse(mc.Year) descending, YourObjectContext.IntParse(mc.Month) descending
select mc).FirstOrDefault()
Comment: -1. This answer assumes that he is using an .edmx file, which is not always generated when one is using EF. Code-First, for example, doesn't generate one.
Comment: @IronMan84 It says `PS: I do not have the authority to change the tables to make the two columns INTs.` so I suggested it's about Database first.
Answer: Did you tried:
(from mc in repository.table.AsQueryable() orderby ((int)mc.Year) descending, ((int)mc.Month) descending select mc).FirstOrDefault();


Price Range in Drupal

Question: I am using ubercart where I enter different price ranges.
In the left sidebar, I want to display different price ranges like:
<code>less than 20$
21-40$
41-65$
more than 65$
</code>
So that whenever I click on one of these items all products in that price range will show up.
Does anyone have any ideas about how to do this?
Thanks.
Answer: use facetapi or faceted_search module i think it helpful..
Answer: You could go with the Search API Range module form where you can filter product by the price range ..

Price Range in Drupal


How can I automatically send email from Thunderbird with Excel VBA?

Question: What I want to do is send an email from a Thunderbird account automatically. The user shouldn't even have to hit the Send button of the email.
I've tried using CDO, but the problem with it is that you have to input the username and password of the account you are sending from. This macro will be used from several different accounts, so inputting each username and password isn't feasible. I could use CDO if there was someway of retrieving the username, password, and smtp server from Thunderbird, but I feel like the code I already have should be able to accomplish this without CDO (hopefully).
Here is really the only code I see (and it's everywhere) in regards to accomplishing this.
Sub Thunderbird()

Dim thund As String
Dim email As String
Dim cc As String
Dim bcc As String
Dim subj As String
Dim body As String

email = "firstname.lastname@example.com"
cc = "email@example.com"
bcc = "firstname.lastname@example.com"
subj = "Subject"
body = "body text"

thund = "C:\Program Files (x86)\Mozilla Thunderbird\thunderbird.exe"
thund = thund & " -compose " & Chr$(34) & "mailto:" & email & "?"
thund = thund & "cc=" & Chr$(34) & cc & "?"
thund = thund & "bcc=" & Chr$(34) & bcc & "?"
thund = thund & "subject=" & Chr$(34) & subj & Chr$(34)
thund = thund & "body=" & Chr$(34) & body

Call Shell(thund, vbNormalFocus)
SendKeys "^+{ENTER}", True

End Sub

As of right now, the fields cc, bcc, subj, and body are all recognized correctly. The problem is they all get added to the end of the first field. For instance, with the way the code is right now, cc will get put in the cc field, but bcc, subj, and body all get appended to cc in the cc field of Thunderbird.
If I comment cc out, then bcc is put in the correct field, but subj and body get appended to bcc in the bcc field of Thunderbird.
If I comment cc and bcc out, then subj gets put in the correct field, but body gets appended to subj in the subject field of Thunderbird.
So basically I need to add the correct code at the end of each of these lines. I've tried both "?" and Chr$(34) to no avail.
Lastly, SendKeys "^+{ENTER}", True isn't working at all. This might be because of all the parameters not being put in the correct field of Thunderbird, but not sure since I can't get that working. Email from Thunderbird displays, but this code isn't sending the email like it's supposed to.
SOLUTION (as provided by @zedfoxus)
Sub Thunderbird()

Dim thund As String
Dim email As String
Dim cc As String
Dim bcc As String
Dim subj As String
Dim body As String

email = "email@example.com"
cc = "email@example.com"
bcc = "firstname.lastname@example.com"
subj = "Subject"
body = "body text"

thund = "C:\Program Files (x86)\Mozilla Thunderbird\thunderbird.exe" & _
        " -compose " & """" & _
        "to='" & email & "'," & _
        "cc='" & cc & "'," & _
        "bcc='" & bcc & "'," & _
        "subject='" & subj & "'," & _
        "body='" & body & "'" & """"

Call Shell(thund, vbNormalFocus)
Application.Wait (Now + TimeValue("0:00:03"))
SendKeys "^{ENTER}", True

End Sub

Comment: [Excel Macro sending through Thunderbird](https://stackoverflow.com/questions/31283948/excel-macro-sending-through-thunderbird/31284639#31284639)
Answer: You were pretty close. Try this:
Public Sub SendEmail()
    Dim thund As String
    Dim email As String
    Dim cc As String
    Dim bcc As String
    Dim subj As String
    Dim body As String

    email = "firstname.lastname@example.com"
    cc = "email@example.com"
    bcc = "email@example.com"
    subj = "Testing"
    body = "Testing"

    thund = "C:\Program Files (x86)\Mozilla Thunderbird\thunderbird.exe " & _
            "-compose " & """" & _
            "to='" & email & "'," & _
            "cc='" & cc & "'," & _
            "bcc='" & bcc & "'," & _
            "subject='" & subj & "'," & _
            "body='" & body & "'" & """"

    Call Shell(thund, vbNormalFocus)
    SendKeys "^+{ENTER}", True

End Sub

Notice the example from http://kb.mozillazine.org/Command_line_arguments_(Thunderbird).

thunderbird -compose "firstname.lastname@example.com,email@example.com',email@example.com',subject='dinner',body='How about dinner tonight?',attachment='C:\temp\info.doc,C:\temp\food.doc'"

The example indicates that after -compose we should use type our information in double-quotes. Each parameter is separated by comma. Nomenclature is parameter='value[,value]' [,parameter='value[,value]]....
Comment: Thanks! Unfortunately, the SendKeys bit still doesn't work. The email displays correctly, but SendKeys doesn't send the email. It actually just minimizes the window.
Comment: What version of Windows do you have? What version of Excel do you have? I have Office 365 ProPlus and SendKeys are working perfectly with Thunderbird on Windows 7.
Comment: Try `Application.SendKeys "%fl", True` instead of `SendKeys "^+{ENTER}", True`. If that doesn't work, try `SendKeys "^+~", True`
Comment: I'm running Windows 8.1 on Office 2010. After messing around with the 2 options you provided, plus the original, I found out `SendKeys` was sending the key before the window was displayed. I added this before all 3 options and it worked `Application.Wait (Now + TimeValue("0:00:03"))`. Right now though, the emails aren't being sent. They sit in the Outbox folder of Thunderbird. Even with Thunderbird open, this still occurs. I have to go to the Outbox folder and maually send them. Any idea why? I don't see any simple fixes online.
Comment: Try sending `SendKeys "^~", True` or `SendKeys "^{ENTER}", True` or `SendKeys "%fd", True`. They all are CTRL+ENTER - that means Send Now. CTRL+SHIFT+ENTER sends the email later and that's what you are doing by sending `^` (CTRL), `+` (SHIFT) + `{ENTER}`
Comment: Ah. Thank you! I wasn't aware I was simply sending the wrong key combo. I'll update my thread to show the full solution. FYI, in your code `"-compose "` needs to be `" -compose "`. Needs a space before `-compose`, at least it does for me in order to work. Thanks again!
Comment: Notice the line prior to `"-compose "`. That line has a space at the end and therefore I don't need a space before `-compose`. The way I have written that piece of code is my own guideline (sort of) where `"-compose "`, `"to="`, `"cc="` line up to my liking
Comment: My apologies. I completely overlooked that. I agree with you. That way is better.


RepositoryItemLookupEdit new value disappears before being processed

Question: I have a LookupEdit in the grid that needs to be able to accept new values.  When I enter the new value and press "Enter" or "Tab", it saves normally via the ProcessNewValue event, however when I enter a value and click elsewhere in the grid, on another cell or just in white space, the value vanishes completely.  By implementing several other events and setting breakpoints all I figured out was that the value disappears before the "CloseUp" event fires.  Validating, EditValueChanged, EditValueChanging, ProcessNewValue, Closed, Leave, and even GetNotInListValue never even get called because of the empty value.
Can anyone think of some setting I haven't found yet, or any other reason why this value would disappear...And how I might stop it from happening?
Found a valid Workaround
I implemented the following 3 events, in sequence, to solve this issue.  I still have no idea what caused it, or how to go about preventing it.  This is a Workaround, not a solution, and should be treated as such.  I end up having to manually call the ProcessNewValue method, as well as forcing the value to equal the text field, and the text field back into the value later on.  Not the smoothest of operations, but it does work.
private void repPatchNum1_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
    {
        string surfaceSoftware = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "SurfaceSoftware");
        if (string.Compare(surfaceSoftware, SOFTWARE_CHECK, true) == 0)
        {
            string version = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "Version");
            if (version.ToLower().Contains(VERSION_CHECK))
            {//now we are certain we are in the right place
                LookUpEdit editor = sender as LookUpEdit;
                if (!((RPickListCollection)((BindingSource)editor.Properties.DataSource).DataSource).OfType<RPickList>().Any(a => a.RValue.Equals(e.NewValue)))
                {
                    repPatchNum1_ProcessNewValue(sender, new DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs(e.NewValue));
                    vwSurfaceSoftware.SetRowCellValue(vwSurfaceSoftware.FocusedRowHandle, colPatchNum, e.NewValue);
                }
            }
        }
    }

    private void repPatchNum1_CloseUp(object sender, DevExpress.XtraEditors.Controls.CloseUpEventArgs e)
    {
        string surfaceSoftware = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "SurfaceSoftware");
        if (string.Compare(surfaceSoftware, SOFTWARE_CHECK, true) == 0)
        {
            string version = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "Version");
            if (version.ToLower().Contains(VERSION_CHECK))
            {//now we are certain we are in the right place
                LookUpEdit editor = sender as LookUpEdit;
                if (!((RPickListCollection)((BindingSource)editor.Properties.DataSource).DataSource).OfType<RPickList>().Any(a => a.RValue.Equals(e.Value)))
                {
                    e.Value = ((LookUpEdit)sender).Text;
                }
            }
        }
    }

    private void repPatchNum1_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
    {
        string surfaceSoftware = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "SurfaceSoftware");
        if (string.Compare(surfaceSoftware, SOFTWARE_CHECK, true) == 0)
        {
            string version = vwSurfaceSoftware.GetRowCellDisplayText(vwSurfaceSoftware.FocusedRowHandle, "Version");
            if (version.ToLower().Contains(VERSION_CHECK))
            {//now we are certain we are in the right place
                LookUpEdit editor = sender as LookUpEdit;
                string patch = vwSurfaceSoftware.GetRowCellValue(vwSurfaceSoftware.FocusedRowHandle, colPatchNum).ToString();
                if (String.IsNullOrEmpty(editor.Text) && !String.IsNullOrEmpty(patch))
                {
                    editor.Text = vwSurfaceSoftware.GetRowCellValue(vwSurfaceSoftware.FocusedRowHandle, colPatchNum).ToString();
                    vwSurfaceSoftware.UpdateCurrentRow();
                }
            }
        }
    }

As to the original question: Please post an answer if you know why this might be happening or how to prevent it.
Thanks all :-)
Comment: Did you ask your question in DevExpress support center? https://www.devexpress.com/Support/Center/
Comment: Not yet, while I know they are the experts at DevExpress, I tend to trust the community here more :-)
Answer: I think I found a simpler workaround, tested on DevExpress 13.
When user presses Tab/Enter, event sequence is ProcessNewValue -> CloseUp
However if user finishes lookup by clicking somewhere else, events are reversed: CloseUp -> ProcessNewValue and entered value is lost. We can use PopupCloseMode.Immediate (specifies that the dropdown window was closed because an end-user clicked outside the editor) to detect this case, manually take entered value from editor, set it to event Value field and manually call ProcessNewValue. No need for other events.
private void myLookUp_CloseUp( object sender, CloseUpEventArgs e )
{
    var lookUpEdit = sender as LookUpEdit;
    if( lookUpEdit != null )
    {
        var enteredLookUpText = lookUpEdit.Text;
        if( e.CloseMode == PopupCloseMode.Immediate )
        {
            e.Value = enteredLookUpText;
            myLookUp_ProcessNewValue( sender, new ProcessNewValueEventArgs( enteredLookUpText ) );
        }
    }
    // Rest of event handler
}

Comment: Wow.  Talk about a dead question.  I'm not even employed by this company anymore...and I *suspect* that this is something newer to devX which wasn't available at the time.  that being said, THANK YOU.  unanswered questions always bug me :-)  I'll definitely keep it in mind if I ever come across this problem again!!!

Also, if anyone else happens to find out that this is a valid answer...Let me know and I'll mark it as such!!


How to get VMware guest MAC address from the console?

Question: I am trying to get the MAC address of a VMware guest from the command line in ESXi 6.
The vSphere client shows the MAC address of the network adapters, which are configured as "automatic".
The command
vim-cmd vmsvc/get.config <id>

shows me many of the details of that particular guest, but not the MAC addresses of the network cards.
Is there a command that I can run from the VMware shell that displays the MAC address of a VMWare guest?
Comment: This command `vim-cmd vmsvc/get.config ` gives back "False MAC addresses"!
Answer: vim-cmd vmsvc/device.getdevices <id> will show you details about the virtual devices of the VM, including the MAC adresses.
Comment: This may gives the mac at the moment of the VM creation but not the current mac address.
Comment: No, it doesn't. I just checked with a VM where I changed the MAC address a couple of weeks ago. The command shows it's current MAC address.
Comment: Maybe it needs something to be installed in the VM?
Answer: vim-cmd hostsvc/net/info | grep "mac ="
Comment: This shows the mac addresses of the host, not of the guests.
Answer: I know this is an old thread, but thought I'd share a one-liner to get all of them (I was trying to locate an unknown VM)...
for VID in `vim-cmd vmsvc/getallvms | awk '{print $1}'`; do echo ${VID} `vim-cmd vmsvc/device.getdevices ${VID} | grep macAddress` ; done

From there, you can use the VID with the macAddress you're looking for to run this to identify the actual VM:
vim-cmd vmsvc/get.config 2 | grep "name"


Grabbing text between slashes in Excel

Question: I have an excel sheet and was trying to figure out if there was a way to grab text b/w slashes.
For example:
[In cell B9]
R:\FINANCE-Asia\Q1Report.html
I want to pull out:  FINANCE-ASIA and place it into cell C9.
Anybody know what the formula for this would be?
Answer: This is by no means a 'clean' method of going about it; and would only apply to finding the first set of text.
=LEFT(RIGHT(B9, LEN(B9)-FIND("\",B9)),FIND("\",B9, FIND("\",B9)+1)-FIND("\",B9)-1)
Slightly cleaner form:
=MID(B9, FIND("\",B9)+1, FIND("\",B9, FIND("\",B9)+1)-FIND("\",B9)-1)
Answer: Even cleaner form:
<code>=TEXTAFTER(TEXTBEFORE(B9, "\", 2), "\", 1)
</code>
It'll give you the text before the 2nd backslash and after the 1st backslash.

Grabbing text between slashes in Excel


Using Node Limit, Show Role How Many Nodes They Can Still Add

Question: Using Node Limit and have limited roles to be able to add 3, 8 or 20 nodes of one content type depending on what they register with.
I wondered if it's possible to show how many of their limit they have left and then show it on their user page.
So if they have created 3 nodes, they have 5 left (if they had the 8 role allowance).
Comment: by saying "Show Role" , you mean the limitation is for a group or a person? I mean if A who is listed in role X adds a node is it affecting person B who also is a member of role X?
Answer: I checked the node_limit module and you need to create an api to be able to get the remaining limit for a particular role or user.

The number of limit and limit id are stored on node_limit table.
Your limit id and role id are stored on node_limit_role table.

What you need to do next is count the number of nodes the role or user has created.
Now you need to alter the user profile to print the remaining limit. See the api that you can use here.


Background com duas cores

Question: Gostaria de criar um background com duas cores em ângulo de 45 graus, mas sem transição. Fiz desta forma:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<gradient
    android:type="linear"
    android:startColor="#000"
    android:endColor="#FFF"
    android:angle="45"/>

</shape>

O problema é que fica com uma transição, tipo assim:

Eu gostaria de algo sem essa "transição":
Comment: vc quer essa "linha" com 45º graus exatamente ou quer que essa linha vá de uma diagonal a outra?
Answer: Em XML não sei se é possível.
Em Java, uma forma possível, é criar uma Shape e construir uma ShapeDrawable com ela.
DoisTriangulosDrawable.java
public class DoisTriangulosDrawable extends ShapeDrawable {

    public DoisTriangulosDrawable(){
        super();
        setShape(new DoisTriangulosShape());
    }

    private class DoisTriangulosShape extends Shape {

        @Override
        public void draw(Canvas canvas, Paint paint) {

            Path path = new Path();
            path.setFillType(Path.FillType.INVERSE_EVEN_ODD);
            Path path1 = new Path();
            path1.setFillType(Path.FillType.INVERSE_EVEN_ODD);

            paint.setStrokeWidth(0);
            paint.setStyle(Paint.Style.FILL);
            paint.setAntiAlias(true);

            paint.setColor(Color.BLACK);

            Point a = new Point(0, 0);
            Point b = new Point(0, (int) getHeight());
            Point c = new Point((int)getWidth(), (int)getHeight());

            path.moveTo(a.x, a.y);
            path.lineTo(b.x, b.y);
            path.lineTo(c.x, c.y);
            path.close();
            canvas.drawPath(path, paint);

            paint.setColor(Color.RED);

            Point a1 = new Point(0, 0);
            Point b1 = new Point((int)getWidth(),0);
            Point c1 = new Point((int)getWidth(), (int)getHeight());

            path1.moveTo(a1.x, a1.y);
            path1.lineTo(b1.x, b1.y);
            path1.lineTo(c1.x, c1.y);
            path1.close();
            canvas.drawPath(path1, paint);

        }
    }
}

Para utilizar, por exemplo, como background de um RelativeLayout:
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);

ShapeDrawable background = new DoisTriangulosDrawable();
layout.setBackground(background);//Requer API16 ou superior

Background com duas cores


Scaling step in Baum-Welch algorithm

Question: I am implementing the Baum-Welch Algorithm for training a Hidden Markov Process, to basically better understand the training process.
I have implemented the iterative procedures described in Rabiner's classic paper. My Implementation is in Wolfram Mathematica. The problem I am facing is the scaling step, if the sequence is 100 observations long then the probabilities easily cross the bounds of $10^{-30}$.
My question is can anyone explain or provide a link where the calculation of scaled forward and backward matrices is described?
For the forward procedure the code is as follows:
 ForwardProcedure[TM_, EM_, P_, N_, M_, Seq_] :=
 Module[{DP, i, j, DPPart},
  DP = ConstantArray[0, {N, M}];
  DP[[1, All]] = Table[P[[i]]*EM[[i, Part[Seq, 1]]], {i, 1, N}];
  DP = Table[
    If[j == 1, P[[i]]*EM[[i, Part[Seq, 1]]], 0]
    , {i, 1, N}, {j, 1, Length@Seq}];
  For[j = 2, j <= Length@Seq, j++,
   DPPart = DP[[All, j - 1]];
   For[i = 1, i <= N, i++,
    DP[[i, j]] = Dot[DPPart, TM[[All, i]]]*EM[[i, Part[Seq, j]]];
    ];
   ];
  DP
  ]

Essentially DP[[i, j]] = Dot[DPPart, TM[[All, i]]]*EM[[i, Part[Seq, j]]]; This line is the update. Which simply takes the needed columns from Transition (TM), The alpha (DP) matrices and multiplies with the associated Emission value.
How can I have a scaling factor independent of i, when not all the t-s of the row of the DP matrix are filled?
Comment: Asking us to debug your code is off topic here. Fwiw though If I remember correctly HMMs have the alpha and beta sequences of distributions, but you don't always want to use them exactly like that because joint probabilities are always too small for any non trivial time series
Comment: I'm not asking to debug it. I just put it here for reference, if anyone ever wanted to see how it is actually implemented. This code works correctly, However does not scale the parameters. You are right there are alpha and beta sequences this code calculates alpha, and the reason you gave is precisely why we need scaling I was asking if someone can actually explain the scaling procedure, because I'm stuck at some point in Rabiner's paper.
Comment: okey dokey close vote retracted. I've worked through this same problem before so I'll check back in later when I'm in front of my computer (cell phone now).
Answer: Background and Notation
Let $x_1, \ldots, x_T$ be the observations, and $z_1, \ldots, z_T$ be the hidden states. The forward-backward recursions are written in terms of $\alpha(z_n)$ and $\beta(z_n)$.
$\alpha(z_n) = p(x_1,\ldots,x_n,z_n)$ is the joint distribution of all the heretofore observed data and the most recent state. As $n$ gets large, this gets very small. This is just because of simple properties of probabilities. Probabilities of subsets get smaller. This is axiomatic.
$\beta(z_n) = p(x_{n+1},\ldots,x_T|z_n)$ is the probability of all the future data given the current state. This gets small as $n$ goes down, for the same reasons as above.
Forward Algorithm
You can see that both of these things become very small, and hence cause numerical issues, whenever you have a non-tiny dataset. So instead of using the forward recursion
$$
\alpha(z_n) = p(x_n|z_n) \sum_{z_{n-1}}\alpha(z_{n-1})p(z_n|z_{n-1})
$$
use the filtering recursion:
$$
p(z_n|x_1,\ldots,x_n) = \frac{p(x_n|z_n)\sum_{z_{n-1}} p(z_n|z_{n-1})p(z_{n-1}|x_1,\ldots,x_{n-1})}{p(x_n|x_1,\ldots,x_{n-1})}.
$$
You can get this algebraically by dividing both sides of the first recursion by $p(x_1,\ldots,x_n)$. But I would program it by keeping track of the filtering distributions, not the $\alpha$ quantities. You also don't need to worry about the normalizing constant usually--the last step you can normalize your probability vector if your state space isn't too large.
I am more familiar with the non-HMM state space model literature, and the filtering recursions are probably the most common set of recursions. I have found a few results on the internet where HMM people call this procedure "scaling." So it's nice to find this connection and figure out what all this $\alpha$ stuff is.
Backward Algorithm
Next, the traditional HMM backward algorithm is stated as
$$
\beta(z_n) = \sum_{z_{n+1}}\beta(z_{n+1})p(x_{n+1}|z_{n+1})p(z_{n+1}|z_n).
$$
This one is trickier though. I have found a few websites that say to divide both sides by $p(x_1,\ldots,x_n)$ again, and I have also found resources that say to divide both sides by $p(x_{t+1},\ldots,x_T|x_1,\ldots,x_t)$. I'm still working this out, though. Also, I suspect there's another connection between this and the backward recursions in other areas of state space model literature (for marginal and joint smoothing distributions). I'll keep you posted.
Edit:
It turns out if you multiply both sides of the HMM backward equation above by $p(x_1, \ldots, x_n,z_n)/p(x_1,\ldots,x_T)$ you get the backward equation for the marginal smoothing distribution, which are more common in non-HMM state space models.
$$
p(z_n|x_1,\ldots,x_T) = p(z_n|x_1,\ldots,x_n) \sum_{z_{n+1}}\frac{p(z_{n+1}|z_n)}{p(z_{n+1}|x_1,\ldots,x_n)}p(z_{n+1}|x_1,\ldots,x_T).
$$
I don't know if this is standard for using Baum-Welch, but it's pretty standard with other state space models. Cool.
Edit 2:
https://www.springer.com/us/book/9780387402642 define on page 63 the normalized backward function as
$$
\hat{\beta}(z_n) = \beta(z_n)\frac{p(x_{1:n})}{p(x_{1:T})} = \frac{p(z_n \mid x_{1:T}) }{p(z_n \mid x_{1:n})},
$$
which, as they mention on page 65, has the interpretation of the ratio of two marginal smoothing distributions.
Answer: I'm not an expert in HMM, but happened to go through the same process of learning and implementing HMM while encountering the same normalization issues. Below is the answer based on my understanding.
- Forward algorithm:
The forward algorithm calculates $\alpha_t(j) \equiv P(z_t = j | x_{1:t})$, i.e., the probability that the hidden state $z_t$ at time $t$ is $j$, given the observed data points up to time $t$.
In vector form:
$\alpha_1 \propto \phi_t \odot \pi$
$\alpha_t \propto \phi_t \odot (A^T \alpha_{t-1})$, for $t=2,\dots,T$
Where $\phi_t(j) \equiv P(x_t | z_t = j)$ is the local evidence, $\pi$ the prior distribution over states, and $A$ the transition matrix whose entry $A[i, j]$ corresponds to the transition probability from state i to state j, i.e., $A[i, j] = P(z_{t+1} = j | z_{t} = i)$.
Since the above $\alpha_t$'s are not normalized, let's write a (Python) procedure to normalize a vector:
def normalize(v):
    norm = np.sum(v)
    v = v/norm
    return (v, norm)

With the normalization procedure defined above, we can normalize the $\alpha_t$'s:
$\hat{\alpha}_t, \text{norm}_t$ = normalize($\alpha$), for $t=1,\dots,T$
- Backward algorithm:
The backward algorithm calculates $\beta_t(j) \equiv P(x_{t+1:T} | z_t = j)$, i.e., the likelihood of future evidence given that the hidden state $z_t$ at time $t$ is $j$.
In vector form:
$\beta_T = 1_{\mathbf{K}}$
$\beta_{t} = A (\phi_{t+1} \odot \beta_{t+1})$, for $t = T-1, \dots, 1$
Where $K$ is the number of hidden states.
Note that $\beta_t(j)$ is not a probability distribution over states, hence $\sum_j \beta_t(j) \neq 1$.
The catch here is that we can normalize $\beta_t$ with the normalization factor we previously use to normalize $\alpha_t$, $\text{norm}_t$ calculated above.
$\hat{\beta}_t = \beta_t / \text{norm}_t$, for $t=1,\dots,T$
The rationale is described in the next bullet.
- Forward-Backward:
In this step, we calculate $\gamma_t(j) \equiv P(z_t=j | x_{1:T})$, i.e., the smoothed marginal given the fully observed sequence of data points.
One can show that $\gamma_t(j) \propto \alpha_t(j) \beta_t(j)$. In vector form:
$\gamma_t \propto \alpha_t \odot \beta_t \propto \hat{\alpha}_t \odot \hat{\beta}_t$, for $t=1,\dots,T$
Since $\hat{\alpha}_t$ carries the normalization factors: $\text{norm}_1, \text{norm}_2, \dots, \text{norm}_t$,
and $\hat{\beta}_t$ carries the normalization factors $\text{norm}_T, \text{norm}_{T-1}, \dots, \text{norm}_{t+1}$,
therefore for all the $\gamma_t$'s, they all have the same factor: $\prod_{t=1}^T \text{norm}_t$.

Scaling step in Baum-Welch algorithm


after Disabled Bitnami banner, Apache not running, Httpd could not be started

Question: I went to restart Apache after disabling the banner with
sudo /opt/bitnami/apps/wordpress/bnconfig --disable_banner 1

now Apache won't restart
~$ sudo /opt/bitnami/ctlscript.sh status
php-fpm already running
apache not running
mysql already running

I tried
~$ sudo /opt/bitnami/ctlscript.sh start apache
Syntax OK
/opt/bitnami/apache2/scripts/ctl.sh : httpd could not be started

Monitored apache
for error log -  cat /opt/bitnami/apache2/logs/error_log
you can find it here in this link
https://drive.google.com/file/d/1f2Xt0bwcMEhKcXkILLMf_kdBl0JoSZUr/view?usp=sharing
for httpd-app.conf file here copy of it in below link
https://drive.google.com/file/d/1l2zEPzIU0uBHdEyFQEZ22eEPS9fMnBTO/view?usp=sharing
Answer: When looking at (error) log files the most recent ones are at the bottom and those are usually the most relevant when an application fails to start.
That shows that the problem is not the banner but something else:

[Fri Jul 20 23:52:07.232239 2018] [ssl:emerg] [pid 2058:tid 140169115285248] AH0                                                                                2565: Certificate and private key localhost:443:0 from /opt/bitnami/apache2/conf                                                                                /server.crt and /opt/bitnami/apache2/conf/server.key do not match
  AH00016: Configuration Failed

Your problem is in the SSL configuration and the private key server.key does not belong to the certificate server.crt. You will need to fix that by using the correct files.
You can inspect TLS certificate files with openssl  and the modulus must match:
$ openssl x509 -noout -text -in server.crt
$ openssl rsa -noout -text -in server.key

$ openssl x509 -noout -modulus -in server.crt
$ openssl rsa -noout -modulus -in server.key

Comment: I installed new SSL certificate now issue solved
thank you a lot for you help
Comment: Please do not add a comment or an Answer to say "Thank you". - If you want to say "thank you," [vote up](http://serverfault.com/help/privileges/vote-up) that person's answer, or simply pay it forward by providing a great answer to someone else's question. - See [this FAQ page](http://serverfault.com/help/someone-answers) with regards to the etiquette on ServerFault and related sites. - (If this is an Answer to a Question you yourself asked then you additionally have the option to accept it as the correct answer.)


What is the purpose of separate validation/testing subsets in k-fold cross validation?

Question: So it turns out I have misunderstood what k-fold CV actually does. I had originally thought that (e.g.) 5-fold CV splits the whole dataset into 5 subsets, then on each iteration the model is trained with 4 and tested with the held-out subset.
But various documentation (https://scikit-learn.org/stable/modules/cross_validation.html) says an additional subset is left out of this procedure, and that the model is trained, validated, and tested? So why is testing the model using the held-out subsets alone not sufficient?
And how does this overcome the problems associated with just using train_test_split, given that you still have to define a subset of the data for testing the final model?
Answer: The main reason is that you usually want to make modeling decisions based on the cross-validation results (e.g. what model to choose, what hyperparameter settings for models etc.) and/or use the out-of-fold results to do stacking. Doing either of the two things has the potential to result in some degree of overfitting to the left-out-validation parts of each fold. In contrast a test set that you only ever use once avoids that.
Comment: k-fold CV on the training set gets used to make modeling decisions and we accept that they way we do it may lead to use getting a biased estimate of model performance. A split into training (within which you'd do CV) and test set gets you an unbiased estimate of performance (if you only assess it once) on the test set. Of course, if you reserve only, say, 20% of the data as a test set, it may turn out that the performance estimate form the CV is still in a sense better, because it uses 80% of the data (i.e. is lower variance). This is an example of a bias-variance trade-off.
Comment: Excellent, thanks for your reply - so how does k-fold CV overcome the bias involved with using train_test_split, if you have to define a separate testing subset anyway?