text:
Q: Unable to switch frames to get text I need to get text from a div tag that's below an iframe tag. This is the code I'm using:
  try:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='vjs-container-iframe']/a")))
  except Exception as e:
    print(e)
  try:
    driver.switch_to.iframe('vjs-container-iframe')
    description0=driver.find_element_by_id('jobDescriptionText').getText()
    driver.switch_to.default_content()
    counts=counts+1
    break
  except Exception as e:
    print(e)

I'm getting this error for the first half of the code:
Message:
The rest is just blank
And this error for the second half:
SwitchTo' object has no attribute 'iframe

A: It is not iframe instead it is frame.
driver.switch_to.frame(driver.find_element(By.XPATH, ""))

you can try with any unique locator, in place of xpath, that is it could be id, class name, css selector etc.
or
driver.switch_to.frame('vjs-container-iframe')

Also, .getText() is for Java, in Python we have .text
description0 = driver.find_element_by_id('jobDescriptionText').text

also, I see you are using break, not sure if you are in loop, if not then it won't do anything.

A: Two problems

*

*it should be

description0 = driver.find_element_by_id('jobDescriptionText').text

instead of
description0=driver.find_element_by_id('jobDescriptionText').getText()

*It should be

driver.switch_to.frame('vjs-container-iframe')


text:
Q: Date filter not working Long story short, I'm trying to display a date that came from json.
This is what I tried:
{{ item.CreateDate | date }}
{{ item.CreateDate | date : 'MM/dd/yyyy' }}

This is what I get: /Date(1413010800000)/
I want to get 10/14/2014
What am I doing wrong? Thanks

A: Try
{{ item.CreateDate | msDate | date : 'MM/dd/yyyy' }}

And the filter
app.filter('msDate', function () {
  return function (item) {
    return new Date(parseInt(item.substr(6)));
  };
});

Thanks @Brocco.

redpajama_set_name: RedPajamaStackExchange


text:
Q: App detailed-Http Logs in Azure App Service for Linux I hosted a web API on azure app service using a docker image (linux)
And for production purpose I need all http requests to be logged.
I tried " Diagnostic settings (preview)" and I selected "Archive to a storage account"
, But when I checked my logs I found all http request data except request & response body and header.
So, is there a way to log this details for debugging purpose.
Thanks in advance.

A: You won't get the response body and header values in the AppServiceHTTPLogs. You can find the description of the log over at https://learn.microsoft.com/en-us/azure/azure-monitor/reference/tables/appservicehttplogs.
The feature; however, is still in preview though so that means you can submit feedback asking to include the body and header values.


text:
Q: Parametrization of surfaces for vector integration I'm having some trouble calculating vector fields through surfaces. After attempting a few and being dissapointed with a wrong answer multiple times I figured I must be doing something wrong in the process. I think its the parametrization I'm struggling with.
Oftentimes there's a surface I can easily parametrize in Cartesian coordinates (sometimes partially) which can also be written using cylindrical or spherical coordinates. It's this part that gives me trouble, I don't really how to combine a change of coordinates and a parametrization.
I looked around at a few examples online and tried applying what I learnt there without much positive result, here's one of the attempts:

Integrate the function $\vec F(x,y,z) = (2x,-3y,z)$ through the surface $\Sigma$ defined as the part of the cylinder $x^2+y^2=1$ between $z=0$ and $z=x+2$.
Parametrization $\vec\phi$:
  $x = \cos\theta$
  $y = \sin\theta$
  $z = z$
  $\frac{\partial\phi}{\partial z}\times\frac{\partial\phi}{\partial\theta}=(-\cos\theta,-\sin\theta,0)$
Apply the formula: $\iint_\Sigma\vec F(x,y,z) .d\vec\sigma = \iint_K\vec F(\vec\phi(z,\theta)).(\frac{\partial\vec\phi}{\partial z}\times\frac{\partial\vec\phi}{\partial\theta}(z,\theta))$
Which gives $\int_0^{2\pi}d\theta\int_0^{\cos\theta+2}(2\cos\theta,-3\sin\theta,z).(-\cos\theta,-\sin\theta,0)dz$

Solving this integral doesn't give me the correct result, so I must've made an error along the way but I just can't find it.
Again, this is just an example, it's this type of integrating that's giving me a hard time.
Here's the further solution:

$\int_0^{2\pi}d\theta\int_0^{\cos\theta+2}(-2\cos^2\theta+3\sin^2\theta)dz$
  $=\int_0^{2\pi}(-2\cos^3\theta+3\sin^2\theta\cos\theta-4\cos^2\theta+6\sin^2\theta)d\theta$
  $= 0 + 0 + (-4\pi) + 6\pi = 2\pi$

The correct answer according to my textbook is $-2\pi$


text:
Q: Ruby: Avoid long nested module when reference to constant I have a class that define a constant in my rails app. For example:
module A
 module B
   class C
     CONSTANT = "constant"
   end
 end
end

And then, in another module, I want to get this constant:
module Test
  class Main
    def get_constant
       const = A::B::C::CONSTANT
    end
  end
end

This is too long and verbose. I tried some ways for not using prefix A::B::C. for example:
module Test
  class Main
    include A::B
    def get_constant
       const = C::CONSTANT
    end
  end
end

But in all cases, I always meet error because my rails app cannot find this constant. Please tell me how

A: In the second class/module, you can create a reference to the constant from the first:
class One
  OneConst = 1
end

class Two
  TwoConst = One::OneConst
  def self.two_const
    TwoConst
  end
  def two_const
    TwoConst
  end
end

puts Two.two_const
puts Two.new.two_const


text:
Q: How to get project URL within the application? I need to obtain my project URL so that I create a link to another section of my site when say for example new content is added I can append this location onto it.
Is there a way I can obtain this address

http://localhost:56672/ or http://mywebsite.azurewebsites.net/

A: If you are creating links manually you should just use a relative URL instead of absolute. So instead of:
http://mywebsite.azurewebsites.net/some/link/here

Use this:
/some/link/here

The browser will automatically fill in the hostname.
If you are linking to an action method, then you should be using Url.Action or Html.ActionLink.


text:
Q: How to replace my factory in my unit test without constructor dependency injection? Usnig xUnit and Moq.
EDIT1: This approach is going to be used in a library and I want to have parameterless constructor. I do not want my application project to know about dependencies of my library
EDIT2: I just read, that this is form of property DI. I think to stick to it, if noone have any better ideas.
I am using factory pattern in my solution. For testing purposes I want to replace my factory with its mock. Below will be simplified example. In my service class constructor I am creating instance of my factory:
public class ObjectService : IObjectService
    {
        public ObjectService()
        {
            Factory = new ObjectFactory();
        }

        public IObjectFactory Factory { get; set; }

        public IObjectModel GetObject(string firstName)
        {
            return Factory.GetObject(firstName);
        }
    }

So in unit tests I can replace instance of the factory with mock:
public class ObjectServiceTests
    {
        private readonly ObjectService _serv;
        private readonly Mock<IObjectFactory> _factoryMock;
        private readonly Mock<ISomeService> _someServMock;
        private readonly string _someFirstName = "SomeFirstName";

        public ObjectServiceTests()
        {
            _someServMock = new Mock<ISomeService>();
            _someServMock.SetupGet(s => s.SecondName).Returns("Cos");

            _factoryMock = new Mock<IObjectFactory>();
            _factoryMock.Setup(f => f.GetObject(_someFirstName))
                .Returns(new ObjectModel(_someFirstName, _someServMock.Object));

            _serv = new ObjectService();
        }

        [Fact]
        public void GetObject_Called_ReturnsObject()
        {
            _serv.Factory = _factoryMock.Object;

            IObjectModel newObj = _serv.GetObject(_someFirstName);

            Assert.Equal(_someFirstName + ", Cos", newObj.FullName);
        }
    }

I am wondering, is my approach with using public IObjectFactory Factory { get; set; } property correct? Because currently I have no any other idea how to do it. I will be happy for any suggestions how to replace my factory in tested method in other way.


text:
Q: Get standard error of exponentiated coefficient in cox regression When I run coxph, R supplies me with the coefficients, exponentiated coefficient, and standard error. The standard error is for the regression coefficient, $\beta$. How can I get the standard error of the exponentiaed regression coefficient, $exp(\beta)$?
R code:
library("survival")
data("lung") #From the survival package
res.cox <- coxph(Surv(time, status) ~ sex, data = lung)
summary(res.cox)

Which gives me (sorry for the horrible formatting):

Call:
    coxph(formula = Surv(time, status) ~ sex, data = lung)
n= 228, number of events= 165
coef exp(coef) se(coef)      z Pr(>|z|)
  sex -0.5310    0.5880   0.1672 -3.176  0.00149 **

se(coef) is giving me the standard error of "sex". I would like the standard error of exp("sex").
I can find the variance using the delta method, but can R give me the results without doing the calculations myself?

A: You can do it manually by calculating $se(sex) \cdot \exp(sex)=0.1672 \cdot 0.5880=.0983136$ since the derivative of $\exp{}$ is $\exp{}$ itself, or like this using svycontrast() in the survey package:
library("survival")
library("survey")
data("lung") #From the survival package
res.cox <- coxph(Surv(time, status) ~ sex, data = lung)
summary(res.cox)
svycontrast(res.cox, quote(exp(sex)))

which yields
         nlcon     SE
contrast 0.588 0.0983


text:
Q: I Want to Read .word format Document body and To display the content of body in VF Page as a String I Have uploaded a .word file in Document Object.Now I want to get that content(body) of that file and I want to dislay whole content in Visual Force Page.
Document doc = [Select d.body from Document d where d.name='docname';
Blob b = doc.body;
String Str = b.toString();

//This Giving an Error Encoding UTC8.

//Then Modified to like below but it's not giving correct data.
//It's giving like    @5ywnnn7*96w**.

Document doc = [Select d.body from Document d where d.name='docname';
Blob b = doc.body;
String Str = EncodingUtil.base64Encode(b);

Thanks In Advance.


text:
Q: 3D visualization of complex geometries in a GUI I would like to develop a small cross-platform for  (structured) mesh  generation software (similar to Gmesh) and possibly 3D pre/post processing (like Salome).
In order to make things easier I'd like to use already made libraries, to better focus on the development of what I need.
I need
1. geometrical modelling capabilities
2. GUI
3. 3D visualization.
I have been looking around but the whole workflow results a bit blurry.
I think pyGTK and GLADE are good choices for me ( because of the community and the very open license with respect to pyQt).
The modelling part could be handled by Open Cascade ( preferably pythonOCC) but for the visulization in a pyGTK widget I don't know what to do.
I was thinking to use openGL (PyGtkGLExt) but I understood that OpenGL is too low-level.
FreeCAD (http://goo.gl/V4FCW) uses Coin3D (I could use pyvy maybe) for this reason but a software like Gmesh uses directly OpenGL.
On top of that I saw that for scientific visualization, VTK would be probably better, but I don't understand  whether  it is based on OpenGL or not. In my opinion OpenGL is nice because it is supported by graphic card drivers making the whole software faster.
I should be able to render geometries built by pythonOCC into a pyGTK widget but what kind of libraries would be better to use? OpenGL alone (maybe to complex to program?)
Coin3D (or similar) to speed up the use of OpenGL?
VTK alone? VTK in combination with OpenGL?
Other combination and/or libraries?
Have you experience in this kind of software?
Do you have suggestion about it? Do you know tutorials where the combined used of these libraries is explained?


text:
Q: to_csv() writes values with additional fractions I am using to_csv() method to write my data frame into a .csv file. I have a variable called emotion which refers to a data frame, and I am using to_csv() like this;
 emotion.to_csv(file_name,encoding='utf-8', index = False)
 # file_name holds a string of a full path of the file which is intended to create

There are over 15.000 rows of data in this data frame, and when I open to check the .csv file which is created by to_csv method, most of the rows look fine. But there are few exceptions. You can see a chunk of rows from the .csv file below;

2.8641,0.2737,38.18,73,97,291664
  3.1672,0.2688,38.21,73,97,291667
  3.4115,0.2786,38.11,73,97,291672
  3.3675,0.2737,38.18,73,97,291675
  3.1719999999999997,0.2737,38.02,73,97,291678
  2.7761,0.2737,38.15,73,97,291682
  2.39,0.2688,38.18,73,97,291685
  2.0674,0.2835,38.11,73,97,291688

As I pointed out above with the bold font on the dataframe values, 3.1719999999999997 has an additional fractions. In the original data, it should be something like 3.171. Could you help me to overcome this problem? Thanks in advance.

A: See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html
to_csv has this nice float_format keyword argument that you can set.
emotion.to_csv(file_name, encoding='utf-8', index=False, float_format="%.3f")

A: This is probably a cast made by pandas when extracting the values from your csv.
If you want to limit the numbers of digits displayed by the dataframe you can use:
 pd.options.display.float_format = '${:,.3f}'.format

This will limit the numbers of digits to 3.


text:
Q: Tratamento de Erros Paramiko (Python) Olá,
Estou montando um script onde o usuario irá se autenticar em um equipamento, se tudo der certo o código continua senão ele mostra uma mensagem de erro. Estou usando a biblioteca Paramiko para fazer a sessão com o equipamento, a conexão está ok e ele retorna a mensagem que eu desejo quando a conexão falha, porém aparece outro erro logo em seguida.
MEU CÓDIGO:
username = raw_input("Username:")
password = getpass.getpass("Password: ")

remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    remote_conn_pre.connect('1.111.111.111', username=username, password=password)
except paramiko.ssh_exception.AuthenticationException:
    print ("Erro de login.")

ERRO EM SEGUIDA:
  File "run.py", line 67, in <module>
    remote_conn_pre.connect(ip, username=username, password=password)
  File "C:\Python27\lib\site-packages\paramiko\client.py", line 380, in connect
    look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
  File "C:\Python27\lib\site-packages\paramiko\client.py", line 603, in _auth
    raise saved_exception
paramiko.ssh_exception.AuthenticationException: Authentication failed.

Acredito que não estou sabendo usar o paramiko.ssh_exception.AuthenticationException direito, alguém pode me ajudar?
E mais uma dúvida, tem como eu fazer caso ele dê erro, ele retornar para o usuário digitar o username/password novamente?
Desculpe, sou meio novo em programação e Python, por isso as dúvidas.
Muito obrigado!

A: Você não esta tratando a exceção de forma correta.
No bloco try except adicione a tratativa da exceção de autentificação
try:
    remote_conn_pre.connect('1.111.111.111', username=username, password=password)
except AuthenticationException:
    print ("Erro de login.")

ou
try:
    remote_conn_pre.connect('1.111.111.111', username=username, password=password)
except paramiko.AuthenticationException as err:
    print ("Erro de login: " + str(err)))

Leia a documentação da biblioteca, no casso do metodo connect do client ele da raise nas exceções de BadHostKeyException , AuthenticationException, SSHException e socket.error
http://docs.paramiko.org/en/stable/api/client.htm


text:
Q: Tic Tac Toe Java GUI setting up playing field I am currently working on coding a simple version of Tic Tac Toe in Java GUI. I am having a problem with setting up the playing field. A button represents a square which a player can press to either get "X" or "O".
 //Playing field class

 import java.awt.*;
 import java.awt.BorderLayout;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 import java.awt.Color;
 class TicTacToeFrame extends JFrame {
     private JFrame game = new JFrame("Tic Tac Toe");
     private JPanel pane1, pane2, pane3;
     Button button = new Button();
     public TicTacToeFrame() {
         game.setSize(300, 300);
         game.setVisible(true);
         game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         pane1 = new JPanel();
         pane2 = new JPanel();
         pane3 = new JPanel();

         add(pane1, BorderLayout.NORTH);
         add(pane2, BorderLayout.CENTER);
         add(pane3, BorderLayout.SOUTH);

         pane1.setBackground(Color.white);
         pane2.setBackground(Color.white);
         pane3.setBackground(Color.white);

         placeButton();
     }
     public void placeButton() {
         for (int i = 1; i < 10; i++) {
             if (i < 4) {
                 pane1.add(button.getButton());
             }
             else if (3 < i && i < 7) {
                 pane2.add(button.getButton());
             }
             else if (6 < i && i < 10) {
                 pane3.add(button.getButton());
             }
         }
     }
 }

 //Button class

 import javax.swing.JButton;
 import java.awt.event.ActionListener;
 public class Button {
     private JButton button;
     private int number = 0;
     private String player;
     public Button() {
         button = new JButton();
     }
     public String getPlayer() {
         return player;
     }
     public JButton getButton() {
         return button;
     }
     public void changePlayer() {
         for (int i = 1; i < 10; i++) {
              if (number % 2 == 0) {
                  player = "X";
              }
              else {
                  player = "O";
              }
              number++;
         }
     }
 }

When I run the program in a main I receive the frame, however, the buttons which are supposed to represent squares are not placed. Help?

A: Why do you wrap a JFrame (game) inside a class that already extends JFrame?
I'd do it in this way:
public TicTacToeFrame() {
    super("Tic Tac Toe");
    //I prefer to call pack() method in this case..
    //setSize(300, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    pane1 = new JPanel();
    pane2 = new JPanel();
    pane3 = new JPanel();

    add(pane1, BorderLayout.NORTH);
    add(pane2, BorderLayout.CENTER);
    add(pane3, BorderLayout.SOUTH);

    pane1.setBackground(Color.white);
    pane2.setBackground(Color.white);
    pane3.setBackground(Color.white);

    placeButton();
    //call setVisible after you added all the buttons
    setVisible(true);
    pack();
}

There is a mistake also in placeButton method (as noticed by Hovercraft Full Of Eels):
public void placeButton() {
    for (int i = 1; i < 10; i++) {
        //You should create the button all the time
        Button button = new Button();
        if (i < 4) {
            pane1.add(button.getButton());
        }
        else if (3 < i && i < 7) {
            pane2.add(button.getButton());
        }
        else if (6 < i && i < 10) {
            pane3.add(button.getButton());
        }
    }
}


text:
Q: List Manipulation on Array with subscript elements I am trying to write a function which operates on an array with subscripted elements.
As an example i have the array a={$1_3$,$2_2$,$4_1$}, which means i have 3 amounts of value 1, 2 amounts of value 2 and 1 amount of value 4. If the subscripted amount reaches 0, then the element has to be dropped from the array.
Now i need a function
edit[a_,lower_,raise_]:=...

with lower_ being an array of elements which shall be decreased by 1 and raise_ being the array of elements which should be increased by 1. These two arrays have to contain the value and not the position of the element which should be changed.
So if i would call the function with
edit[{Subscript[1, 3], Subscript[2, 2], Subscript[4, 1]}, {1, 1, 4}, {2, 5}]

the output should be
{Subscript[1, 1],Subscript[2, 3], Subscript[5, 1]}

because

*

*the value 1 has to be decreased 2 times, leaving it with the amount 1

*the value 4 has to be decreased once, thus the amount reaches 0 and it has to be dropped

*the value 2 has to be increased once, increasing the amount to a total of 3

*the value 5 has to be increased once, and since its not in the list yet, it has to be added

I want to use subscript because it makes it easy to read and seems to behave like a normal 2 dimensional array, but i am open to good alternatives.

A: Here is an approach using Association for Version 10+.
edit[a_, lower_, raise_] := Subscript @@@ Normal@DeleteCases[#, 0] &@
         Merge[{#, #2, #3}, Total] &[<|Rule @@@ a|>, -Counts[lower], Counts[raise]]

Use:
edit[{Subscript[1, 3], Subscript[2, 2], Subscript[4, 1]}, {1, 1, 4}, {2, 5}]

$\left\{1_1,2_3,5_1\right\}$

A: You can do it with "classic" functions Tally and GatherBy
edit[a_, lower_, raise_] :=
 DeleteCases[#, _[_, 0]] &[
  Subscript[#[[1, 1]], Total@#[[All, 2]]] & /@ GatherBy[#, First] &@
   Join[a, Subscript @@@ (-Tally[-lower]), Subscript @@@ Tally@raise]]

edit[{Subscript[1, 3], Subscript[2, 2], Subscript[4, 1]}, {1, 1, 4}, {2, 5}]
(* {Subscript[1, 1], Subscript[2, 3], Subscript[5, 1]} *)

A: lst = {Subscript[1, 3], Subscript[2, 2], Subscript[4, 1]};

$\left\{1_3,2_2,4_1\right\}$

ClearAll[foo, editFX];
foo = Flatten[GatherBy[Join[#1, Subscript @@@ Tally[#2] ], First] /.
     {Subscript[x_, a_], Subscript[x_, b_]} :>
                  (Subscript[x, a + #3 b] /. Subscript[_, 0] :> Sequence[])] &;
editFX[lst_, arg1 : {___}, arg2 : {___}] := With[{t = foo[lst, arg1, -1]}, foo[t, arg2, 1]];

editFX[lst, {1, 1, 4}, {2, 5}]

$\left\{1_1,2_3,5_1\right\}$

Or
ClearAll[editFX2];
editFX2 = Fold[foo[#1, First@#2, Last@#2] &, #, {{#2, -1}, {#3, 1}}] &;
editFX2[lst, {1, 1, 4}, {2, 5}]

$\left\{1_1,2_3,5_1\right\}$


text:
Q: Flutter: How to get rid of the first touch delay? I have a little issue with Flutter.
I did a clean install and everything works smoothly.
Nonetheless, there is a delay of half a second between my touch and the action of a button (or menu hamburger).
This delay exists only for the first touch action.
After the first touch / click, any further touch action is without delay.
This problem exists on the emulator but also on a real device.
Could you explain to me why (and how to fix it)?

A: Thanks to @RandalSchwartz the problem is now solved.
Flutter applications are slower in development mode (with the hot reload).
This cause the app to have a delay with the first touch action (on a button or hamburger menu for example).
This also cause the app to have a long splash screen in development mode (around 3 seconds)
Therefore the solution is pretty simple if you want to get rid of all the waiting times, just launch you app in release mode with the following command:
"flutter run --release"


text:
Q: A question on the zeros involving the equation containing exponential factor I recently encounter a puzzle that: how to show that for any constant $c_1,c_2,c_3,c_4 \in \mathbb{R}$ the equation
$$c_1 e^t+c_2e^{-t}+c_3 e^{\alpha t}+c_4 e^{-\alpha t}=0$$
has at most only one zero in the interval $(0,1)$, where $\alpha $ is a fixed positive absolute constant.
If any expert here has some heuristic please give a guide. Thanks in advance.

A: Here is a plot of the function
$$f(c_1,c_2,c_3,c_4,\alpha,t)=c_1 e^t + c_2 e^{-t} +c_3 e^{\alpha t}+c_4 e^{-\alpha t}$$
as a function of $t$ for $c_1=1$, $c_2=1.93$, $c_3=-2.75$, $c_4=-0.09$, $\alpha=0.075$, with two zeros in the interval $0<t<1$:

So I would conclude the statement about there being at most 1 zero is false.


text:
Q: Attempted proof of the first part of the Fundamental Theorem of Calculus So I was trying to prove the first part of the Fundamental Theorem of Calculus in a different way using the Riemann sum definition of the definite integral, rather than the way it was presented in my high school calculus class (squeeze theorem, mean value theorem). There's one step in my proof that I'm not confident is legit, and I'm unsure if the proof breaks down.
The theorem says that $\displaystyle F(x) = \int \limits_a ^x f(t) dt \rightarrow \frac{dF(x)}{dx} = f(x)$.
Using the definition of the derivative, $ dF(x)/dx $ equals
$ \displaystyle \lim \limits_{h \rightarrow 0} \frac{F(x+h)-F(x)}{h} = \lim\limits_{h \rightarrow 0}\frac{\int\limits_a^{x+h} f(t) dt - \int\limits_{a}^xf(t) dt}{h} = \lim \limits_{h \rightarrow 0} \frac{1}{h} \int \limits_x ^{x+h} f(t)dt $.
In my attempt I replaced the definite integral with its Riemann Sum definition with regular partitions, so the latter equals
$ \displaystyle \lim \limits_{h\rightarrow 0} \hspace{2mm} \frac{1}{h} \lim \limits_{n \rightarrow \infty} \sum \limits_{i = 1}^n(\frac{x+h - x}{n}) \hspace{2mm}f(x+(\frac{x+h-x}{n})i)$ =
$\displaystyle \lim \limits_{h\rightarrow 0} \hspace{2mm}  \lim \limits_{n \rightarrow \infty} \sum \limits_{i = 1}^n\frac{1}{n} f(x+\frac{h}{n}i)] = $
(At this step, I'm not sure if switching the order of the limits is allowed; does my proof break down?) :
$ \displaystyle \lim \limits_{n \rightarrow \infty}\hspace{2mm}\lim \limits_{h \rightarrow 0}\sum \limits_{i = 1}^n\frac{1}{n} f(x+\frac{h}{n}i)]=$
$\displaystyle \lim \limits_{n \rightarrow \infty}\hspace{2mm}\sum \limits_{i = 1}^n\frac{1}{n} f(x)=$
$f(x).$
If the limit switching step (or any other) is incorrect, could you explain to me why? Thanks.


text:
Q: How can I get the memory address of a Flutter / Dart variable? Is this possible? I would like to print the current memory address of a variable in Dart but I don't know if this is possible. I want to write a code to show all memory address in a liked list structure.
Advice are welcome.

A: There is no way to print the memory address of a variable in Dart.
Even if you could print the memory address, there is nothing meaningful that you could do with it.
If you want to identify objects, you could use identityHashCode.

A: It's not possible to access raw memory of Dart objects. Dart is a garbage collected language which means that Dart objects are not guaranteed to live at a particular memory address as the garbage collector can (and certainly will) move these objects to different memory locations during a garbage collection. Within the Dart virtual machine Dart objects are almost exclusively accessed and passed around via handles and not raw pointers for this very reason.


text:
Q: Get Sum of the Count column i want to display on top of the page total no of critical items and below the list. This is my query
SELECT  vs.vessel_name, vs.CallSign ,COUNT(IF(m.AvailableQuant <= m.MinQuant,1, NULL)) AS 'Critical'
FROM tbl_vesselmaster vs
INNER JOIN comp_login cl ON vs.co_id = cl.id
INNER JOIN m_shipinv m ON vs.id = m.ShipId
WHERE vs.co_id=123
GROUP BY vs.id, vs.vessel_name ;

this is the output
vessel_name  CallSign  Critical_Items
-----------  --------  ----------------
Sima Sadaf   (NULL)                   4
sdare        3q1                      1

I want to display on top of the page the total no of critical items i.e 5 items are critical
how do i get the sum?

A: Below query will return you the sum of critical items :
SELECT  SUM(IF(m.AvailableQuant <= m.MinQuant,1, 0)) as total FROM tbl_vesselmaster vs
    INNER JOIN comp_login cl ON vs.co_id = cl.id
    INNER JOIN m_shipinv m ON vs.id = m.ShipId
    WHERE vs.co_id=123;

A: SELECT  COUNT(IF(m.AvailableQuant <= m.MinQuant,1, NULL)) AS 'Critical'
FROM tbl_vesselmaster vs
INNER JOIN comp_login cl ON vs.co_id = cl.id
INNER JOIN m_shipinv m ON vs.id = m.ShipId
WHERE vs.co_id=123

should give you all critical item

A: I hope You just want total in your existing query..
select sum(Critical) as Total from(
SELECT  vs.vessel_name, vs.CallSign ,COUNT(IF(m.AvailableQuant <= m.MinQuant,1, NULL)) AS Critical
FROM tbl_vesselmaster vs
INNER JOIN comp_login cl ON vs.co_id = cl.id
INNER JOIN m_shipinv m ON vs.id = m.ShipId
WHERE vs.co_id=123
GROUP BY vs.id, vs.vessel_name )alias;

A: Did you try something like this ?
select sum(d.Critical) from (SELECT  vs.vessel_name, vs.CallSign ,COUNT(IF(m.AvailableQuant <= m.MinQuant,1, NULL)) AS 'Critical'
FROM tbl_vesselmaster vs
INNER JOIN comp_login cl ON vs.co_id = cl.id
INNER JOIN m_shipinv m ON vs.id = m.ShipId
WHERE vs.co_id=123
GROUP BY vs.id, vs.vessel_name )d

A: You get an extra total line by using WITH ROLLUP. Then make sure to get this first and display null for the call sign:
SELECT
  vessel_name,
  case when vessel_name is not null then CallSign end as CallSign,
  Critical
FROM
(
  SELECT
    vs.vessel_name,
    vs.CallSign,
    SUM(m.AvailableQuant <= m.MinQuant) AS Critical
  FROM tbl_vesselmaster vs
  INNER JOIN comp_login cl ON vs.co_id = cl.id
  INNER JOIN m_shipinv m ON vs.id = m.ShipId
  WHERE vs.co_id=123
  GROUP BY vs.id WITH ROLLUP
) AS vessels
ORDER BY (vessel_name IS NOT NULL), vessel_name;


text:
Q: Azure Load Balancer to balance the load between multiple ports but in same VM (Backend Pool) I have having a hard time find a solution for this.
I have an Azure Internal Load Balancer (level 4). And I have ONLY one Virtual Machine act as the backend pool for the said Load Balancer.
And fun part starts here, I have multiple Docker containers running on that Virtual Machine. Running Nginx Web servers on ports 8080 and 8081.
And now I want to balance the load between these two ports.  Literally what I want is something like below in the photo:

So according to the photo, the request comes from abc.xyz.com and it should hit the Load Balancer, and then it should route the traffic to the only VM running multiple docker containers in multiple ports.
How can I achieve this behavior?
I have already setup A frontend configuration with private ip, a rule, backend pool

A: As per this article(https://learn.microsoft.com/en-us/azure/container-instances/container-instances-virtual-network-concepts#unsupported-networking-scenarios), placing an Azure Load Balancer in front of container instances in a networked container group is not supported and similarly it is not possible to route the traffic on containers to their specific ports running on a single Virtual Machine. The above solution works on VM level not on container level.
The only workaround for this scenario would be to use Azure Application gateway as Microservice architecture is supported on App gateway. To probe on different ports, you need to configure multiple HTTP settings. Reference:
https://learn.microsoft.com/en-us/azure/application-gateway/application-gateway-faq#can-one-backend-pool-serve-many-applications-on-different-ports
Azure Application Gateway is a web traffic load balancer that enables you to manage traffic to your web applications. And you can create an internal application gateway. To do that you can create an Application Gateway with both public and private frontend IP address and do not create any listeners for the public frontend IP address. Application Gateway will not listen to any traffic on the public IP address if no listeners are created for it.
Reference: https://learn.microsoft.com/en-us/azure/application-gateway/configuration-front-end-ip ,
https://learn.microsoft.com/en-us/azure/application-gateway/application-gateway-faq#how-do-i-use-application-gateway-v2-with-only-private-frontend-ip-address


text:
Q: Doctrine is not retrieving new columns I'm using the default find() method to get data, every thing was ok until I've added a new property to the entity : the same code is not retrieving the new column, I don't see it in the generated SQL query !
I've added other properties with different types and the problem remains : new properties aren't visible in the SQL query !
This is the result of doctrine:schema:validate :
Mapping
-------
 [OK] The mapping files are correct.

Database
--------
 [ERROR] The database schema is not in sync with the current mapping file.

So it seems the schema is not ok, how can I find the problem ?
UPDATE 1
I have another project with no database error. I've updated an existing entity :
bin/console make:entity

Then updated the schema :
bin/console doctrine:schema:update --force

But the new column is not retrieved !
UPDATE 2
I've generated a new entity with the same properties and Doctrine returns all the columns. I've made a diff between the two entities and the two repositories : they are identical !
I've cleared Doctrine's cache  :
 php bin/console doctrine:cache:clear-metadata
 php bin/console doctrine:cache:clear-query
 php bin/console doctrine:cache:clear-result

...but the problem persists

A: It was a Doctrine cache issue, here is a part on my doctrine.yaml :
    orm:
        metadata_cache_driver: apcu
        result_cache_driver: apcu
        query_cache_driver: apcu

I've tried to clear the cache php -r "apcu_clear_cache();" : no effect ! So I've changed the cache :
    orm:
        metadata_cache_driver: array
        result_cache_driver: array
        query_cache_driver: array

And now it works fine :)


text:
Q: how to retain the div contents after page refresh I am creating a dynamic div using Jquery and I am trying to cache it so that, I will get it back after the page refresh, please help on how to achieve this,
pasting the code below

I am trying to draw a div in the page using button click, after the click div is drawn in the page, when its refreshed using an F5 click, the div disappears, is there any way to retain the div contents using caching mechanisms?
this is been a showstopper for my whole functionality!
Thanks in advance,
Shajo

A: You may be misunderstanding the way jCache works. The cache effectively gets wiped out whenever you (re)load the page, because the browser will spin up a new JavaScript execution environment. This browser behavior makes sense, because it prevents JS on different websites from being able to interact with one another, creating a big security vulnerability. If you play around with the jCache demo, you can test this behavior by populating the demo cache, reloading the page, and noticing that the cache is emtpy.
As for your particular application, you'll need to (re)design it such that a reload is not necessary. This is really the whole point of Ajax. I seriously doubt this is a show stopper for you. In the worst case, you should be able to regenerate the dynamic div when the user reloads the page. If you need to remember some state in order to regenerate the div, cookies may work for you.

A: The best bet would be to keep track of the div content server side. That way everytime the user updates the content of the div, an AJAX call can be made updating the server side representation of the div.
When the page loads for the first time your server can prepopulate the div. It then appears as if the page retains the content of the div after a reload.
This type of functionality is used in numerous sites now so I'm sure it can work for your scenario. Look at this site (SO). When you vote you are essentially changing something on the browser, the color of the voting arrow. If you refresh after the color does not revert, it somehow remembers that you voted. Thats because when you click the vote arrow an AJAX call is made and the fact that you voted is recorded on the server.

A: try using a cookie http://plugins.jquery.com/project/cookie

A: To retain the web page content even after page load, you should use CacheStorage interface of javascript.
This interface can be exploited to make your website work offline too.
For details visit:
https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage


text:
Q: how to move inside an array trasformed into an as.data.frame? I have written the following code to declare an array as data frame:
b=as.data.frame(array(0,dim=c(NF,29,1,T+1),
dimnames=list(NULL,c(…..varnames))))

Now, I am not able to move inside the array.. for instance, if I need to show all the matrices in the following array position [,,1,1], what I need to write?
I have tried code like:
b$[].1.1
b$,1.1
b[,,1,1]"

but, of course, it does not work.
Thank you very much for your help!

A: from ?as.data.frame :

Arrays can be converted to data frames. One-dimensional arrays are
  treated like vectors and two-dimensional arrays like matrices. Arrays
  with more than two dimensions are converted to matrices by
  'flattening' all dimensions after the first and creating suitable
  column labels.

array1 <- array(1:8,dim = c(2,2,2),dimnames = split(paste0(rep(letters[1:2],each=3),1:3),1:3))
# , , 3 = a3
#
#     2
# 1    a2 b2
#   a1  1  3
#   b1  2  4
#
# , , 3 = b3
#
#     2
# 1    a2 b2
#   a1  5  7
#   b1  6  8
#

df1    <- as.data.frame(array1)
#    a2.a3 b2.a3 a2.b3 b2.b3
# a1     1     3     5     7
# b1     2     4     6     8

df1$b2.a3
# [1] 3 4

A: I need to create the a data frame, starting from an array which dimension is (2,3,1,3):
0   0   0   0   0   0   0   0   0
0   0   0   0   0   0   0   0   0

Hence, the output that I need is:
debt loan stock debt loan stock debt loan stock
  0    0    0    0    0     0     0    0    0
  0    0    0    0    0     0     0    0    0

Is next code correct?
b=array(0, dim=c(3,3,1,4), dimnames=list(NULL,c("debt","loan","stock")))
output=as.data.frame(b)


text:
Q: how to fill down when empty cells in access db db access table

kindly i need help to fill down with previous string PS: i am a beginner

A: Your Date field seems to be of data type Text. If so, change that to DateTime.
Then you can run a loop to update the records having no date value:
Dim Records     As DAO.Recordset

Dim Sql         As String
Dim LastDate    As Date

Sql = "Select * From YourTable Order By [Surevey ID]"
Set Records = CurrentDb.OpenRecordset(Sql)

If Records.RecordCount > 0 Then
    LastDate = Date ' Adjust if needed.
    Records.MoveFirst
    While Not Records.EOF
        If IsNull(Records!Date.Value) Then
            Records.Edit
                Records!Date.Value = LastDate
            Records.Update
        Else
            LastDate = Records!Date.Value
        End If
        Records.MoveNext
    Wend
End If
Records.Close


text:
Q: Send Everything! -- Favicons (Node.js) Recently while experimenting with Node, I moved from Safari to Chrome (Which seems to want to download everything under the sun) to compare load-speed to see how well it was doing on other browsers.
Chrome requests literally every file I denote in HTML for Chrome, Android, and Favicon files. Desktop Chrome obviously only uses one or possibly up to three files. It doesn't have a functional use for any Android icons (To the best of my knowledge), yet it requests them anyway.
Basically, it requests all of these (Interestingly it doesn't request the manifest file):
<link rel="icon" href="/favicon.ico" type="image/x-icon" />

<link rel="icon" type="image/png" sizes="512x512"  href="/android-chrome-512x512.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/android-chrome-192x192.png">

<link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="144x144"  href="/android-icon-144x144.png">
<link rel="icon" type="image/png" sizes="96x96"  href="/android-icon-96x96.png">
<link rel="icon" type="image/png" sizes="72x72"  href="/android-icon-72x72.png">
<link rel="icon" type="image/png" sizes="48x48"  href="/android-icon-48x48.png">
<link rel="icon" type="image/png" sizes="36x36"  href="/android-icon-36x36.png">

<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">

Finding this, I compared speed: A browser that only requests what it needs, vs. a browser that wants to request everything. The time-to-finish resulted in around 5-10x difference (That 512x512 can kill you -- even if it's preloaded on the server).
To compare, I also use the following:
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="192x192" href="/apple-touch-icon-precomposed.png">

<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#FFF">

Safari seems to pick and choose which to listen to based on what it'll use.
For the sake of completion:
<link rel="manifest" href="/manifest.json">

<meta name="msapplication-config" content="/browserconfig.xml">
<meta name="msapplication-TileColor" content="#FFF">
<meta name="theme-color" content="#FFF">

<meta name="apple-mobile-web-app-title" content="App">
<meta name="application-name" content="App">

To the question:
Is it possible to send all the file data in a JSON request to a client-side JS script and feed the browser the favicon files it wants instead of having <link> identifiers?
Alternatively, is it possible to load all of these files and embed them into the HTML instead of waiting for a request and sending the file as a response?

*

*I realize there are other things one could spend time trying to optimize.

*I also realize setting cache rules simplify this scenario greatly... later. I want to know if it's possible to deliver a speedy first-response.
Essentially, are there any ways to reduce time-to-finish caused by overzealous favicon requests?

A: Your Android icon should be defined in the manifest.json file. The Apple icons are handled differently because they use rel="apple-touch-icon" but all the others have the generic rel="icon" which you should only have just once.
Refer to Google's instructions how to properly set up the Android quick icons.


text:
Q: Riemannian distance topological requirements to become a metric I was reading the proof of the --well known-- theorem that if $(M, g)$ is a Riemannian manifold, then, one defines the Riemannian distance $d$ on $M$, as
$$  M \times M \ni (a, b) \longmapsto d(a, b) = \inf \left\{ L(c) \bigm| c \textrm{ is a $C^1$ piecewise curve that joins } a, b \right\}$$
where $L(c) = \int_I \sqrt{g(c(t))\cdot(c'(t), c'(t))} \; \textrm d t$. The theorem states that $d$ is indeed a metric compatible with the natural topology of $M$. My question is about the proof found in [1, VII.6] and [2, V.3.1]
at the point where it asserts that " $a \neq b$ implies $d(a,b) > 0$. "
It mentions that
(*) $a \neq b$ implies that we can find a local chart $(U, \varphi)$ and a closed ball $B$ in $\varphi(U)$ centered at $\varphi(a)$, of radius $r > 0$ such that any curve joining $a$ and $b$ should intersect the sphere $\varphi^{-1}(\partial B)$.
I cannot find any proof to this fact, unless i put the constraint of regularity in the manifold (so it turns to a $T_3$ space). Ok, i can understand that in the case that $M$ is locally compact manifold, or even paracompact, then Hausdorff property is sufficient, but even then, this fact, needs a proof based on the local topological properties of $M$.
My question is: Can we prove (*) without further constraints?
My references to this question are:
[1] S. Lang, "Introduction to Differential manifolds"
[2] W. Boothby, "Introduction to Differential manifolds and Riemannian Geometry"


text:
Q: Why does $\omega$ have the same cardinality in every (transitive) model of ZF? As in the title: Why does $\omega$ have the same cardinality in every (transitive) model of ZF? I've been thinking about this for some time now.
Can someone show me how to show this by showing me a proof? Thanks a lot.

A: Suppose $X$ and $Y$ are transitive models of set theory. Then the elements of $X$ and $Y$ are sets, and the set membership relations $\in^X$ and $\in^Y$ are the normal set membership relation $\in$.
Hence we can build up the following sequence of results, using the assumption of transitivity:

*

*$\emptyset^X$ (the unique element $z$ of $X$ such that $X \models (\forall y) [y \not \in z]$) and $\emptyset^Y$ are both the real empty set, $\emptyset$.

*So $1^X = \{\emptyset^X\}$ and $1^Y$ are both $1 = \{ \emptyset\}$.

*Similarly, for each finite ordinal $n$, $n^X = n^Y = n$.

*Moreover, for any $z \in X$, if $X$ satisfies the sentence "z is a finite ordinal", then $z$ really is a finite ordinal. The same holds for $Y$.

*Thus $\omega^X = \omega = \omega^Y$. So not only do $\omega^X$ and $\omega^Y$ have the same cardinality, they are literally the same set.

A: If a model is transitive then its ordinals are real ordinals. In particular it means that any finite ordinal in the model is actually finite, and therefore $\omega$ is the real $\omega$.
It is important to note, however, that there is a possibility that countable sets are not countable in the model; and that it is possible for non-transitive (and non-well founded) models to exist in which there is an uncountable number of finite ordinals, of course as Carl points out, internally the finite ordinals are always a countable set. It is only when we look at the model from an external point of view we can tell it has an uncountable number of finite sets.

The important point to notice is that we often assume that there is an "absolute" universe in which we do mathematics, and this universe is a model of ZFC. While this model is not a set, when we talk about models of ZFC we talk about set models. Now there is an internal and external issues to discuss. It is always the case with set models that there is an element of the set-model which the set model "sees" as having a very big cardinality, but the universe sees as having a "small" cardinality.
For example, if $M$ is a countable transitive model then the real numbers of $M$ is a countable set, but not internally.
For non-transitive models the natural numbers could be uncountable as well, externally, at least. However for a transitive model this is impossible.


text:
Q: How to send imageview with intent? the below is the image adapter. I assigned setOnClickListener when I click it , I start a new intent to a new activity, but I want to send this image in this adapter to another activity and set it an image view. my problem is I didnt know how to transfer viewholder.image to bitmap and send it through intent. how to that
    View row = convertView;
  final  ViewHolder holder;

    if (row == null) {
        LayoutInflater inflater = LayoutInflater.from(mcontext);
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.imageTitle = (TextView) row.findViewById(R.id.text);
        holder.imageView = (ImageView) row.findViewById(R.id.imageView);
        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }
    Listitem item = getItem(position);
    System.out.println("item.getUrl() ");
    System.out.println(item.getUrl());

    holder.imageTitle.setText(item.getId());
    Picasso.
            with(mcontext).
            load(item.getUrl())
            .placeholder(R.drawable.logo)
            .fit()
            .into(holder.imageView);

    holder.imageView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Log.d("OnImageButton", "Clicked");
            Intent intnt  =new Intent(mcontext, SingleViewActivity.class);
            Bitmap imageID=holder.imageView; // error here
            intnt.putExtra("ImageId", imageID);
            mcontext.startActivity(intnt)  ;

            Toast.makeText(mcontext, "intent",
                    Toast.LENGTH_LONG).show();
        }
    });

    return row;
}

static class ViewHolder {
    TextView imageTitle;
    ImageView imageView;
}

A: Don't sent the Bitmap. Send the url and use Picasso to retrieve it. The library keeps the Bitmap cached on the disk, so it will not download it again, and loading it from the disk cache will not take long


text:
Q: Using ruby-prof to get runtime difference between "1+1" and "1x2" Attempting to profile the difference in runtime between "1+1" and "1x2" using Ruby and the gem ruby-prof.
Install the gem and hacked together some code that appears to work, but does not give me the answer I'm looking for, that being the difference in runtime.
Is this possible, and if so, what code would give me this answer.

This code appears to work, but does not allow me to see a runtime difference.

require 'ruby-prof'

result = RubyProf.profile do
1+1
end
printer = RubyProf::GraphPrinter.new(result)

result = RubyProf.profile do
1x2
end
printer = RubyProf::GraphPrinter.new(result)

Which returns this in IRB

irb(main):001:0> require 'ruby-prof'
=> true
irb(main):002:0>
irb(main):003:0* result = RubyProf.profile do
irb(main):004:1* 1+1
irb(main):005:1> end
=> #<RubyProf::Result:0x11050c8>
irb(main):006:0> printer = RubyProf::GraphPrinter.new(result)
=> #<RubyProf::GraphPrinter:0x1332c18 @result=#<RubyProf::Result:0x11050c8>, @ou
tput=nil, @options={}, @thread_times={6793716=>0.01}>
irb(main):007:0>
irb(main):008:0* result = RubyProf.profile do
irb(main):009:1* 1x2
irb(main):010:1> end
SyntaxError: (irb):9: syntax error, unexpected tIDENTIFIER, expecting keyword_en
d
        from C:/Ruby193/bin/irb:12:in `<main>'
irb(main):011:0> printer = RubyProf::GraphPrinter.new(result)
=> #<RubyProf::GraphPrinter:0x1124310 @result=#<RubyProf::Result:0x11050c8>, @ou
tput=nil, @options={}, @thread_times={6793716=>0.01}>
irb(main):012:0>

A: 1x2 means nothing in ruby. Use 1*2 instead.
EDIT: You must run the code more times as it is too fast to measure.
require 'ruby-prof'

prof1 = RubyProf.profile do
  10_000_000.times {1+1}
end

prof2 = RubyProf.profile do
  10_000_000.times {1*2}
end

RubyProf::GraphPrinter.new(prof1).print
RubyProf::GraphPrinter.new(prof2).print

Anyway I think the best way to do it is with Benchmark:
require 'benchmark'

Benchmark.bm do |x|
  x.report("1+1") {15_000_000.times {1+1}}
  x.report("1*2") {15_000_000.times {1*2}}
end

It gives me:
         user     system      total        real
1+1  2.386000   0.000000   2.386000 (  2.392529)
1*2  2.403000   0.000000   2.403000 (  2.413323)

Multiplication is just a bit slower. But the difference is too small to mean anything.

A: Multiplication is done with * not with x. This is why you get the syntax error on your second example.

A: You want to use 1 * 2, not 1x2...
If any case, you won't get any noticeable difference. You will be measuring the time it takes Ruby to make a method call, as the operation itself will take negligible time compared to that.

A: Ruby prof only seems to give you time in 100th of seconds. These operations are faster than that and thus both operations will give you the same result.
require 'ruby-prof'
result = RubyProf.profile do
  1 + 1
end
printer = RubyProf::GraphPrinter.new(result)
printer.print(STDOUT)
result = RubyProf.profile do
  1 * 2
end
printer = RubyProf::GraphPrinter.new(result)
printer.print(STDOUT)

Gives :
Thread ID: 70218521201980
Total Time: 0.01

  %total   %self     total      self      wait     child            calls   Name
--------------------------------------------------------------------------------
 100.00% 100.00%      0.00      0.00      0.00      0.00                1     Global#[No method]

Thread ID: 70218521201980
Total Time: 0.01

  %total   %self     total      self      wait     child            calls   Name
--------------------------------------------------------------------------------
 100.00% 100.00%      0.00      0.00      0.00      0.00                1     Global#[No method]

Which is the same time. Perhaps using the built in Time you could get a better result.
This gives the time in milliseconds :
  start = Time.now
  1 + 1
  puts (Time.now - start) * 1000

  start = Time.now
  1 * 2
  puts (Time.now - start) * 1000

They both average out to be the same. ie 1000th of a millisecond


text:
Q: Python3 não reconhece o 0 como int? A questão diz que eu preciso receber entradas do usuário até que uma linha em branco seja digitada. Após o usuário terminar a entrada, eu preciso verificar nessa entrada se existem números válidos e imprimi-los no término do programa.
Seguem um exemplo de entrada dado na questão:
1000
abacaxi
uva
15.19
-1
+1.45
123.456-
12.34+

E a saída esperada:
Lista de Números Válidos Lidos = ['1000', '15.19', '-1', '+1.45']

Ou seja, palavras e números que terminam com "-" e "+" não são considerados válidos, mas os números que iniciam com "-" e "+" devem ser considerados. Até aí, sem problema.
Usei a seguinte lógica: para cada item que o usuário inseriu, eu verifico se o último caractere é inteiro. Se for, entra para uma nova lista chamada numerosValidos. Se não for, como é o caso das strings e dos números que terminam com sinal, o programa não faz nada. Segue o código:
def encontraValidos(lista):
    numerosValidos = []
    if len(lista) == 0:
        print("Lista de Números Válidos Lidos = {}".format(lista))
    else:
        for item in lista:
            try:
                if int(item[-1]):
                    numerosValidos.append(item)
                else:
                    pass
            except ValueError:
                pass

    return numerosValidos

E recebo a saída:
Lista de Números Válidos Lidos = ['15.19', '-1', '+1.45']

Entretanto, como foi dito no exemplo da questão, a entrada "1000" deveria aparecer nessa lista. Debugando o código, percebi que o "1000" não entra no if int(item[-1]), mas não consigo entender o por quê.
Alguma ajuda?

A: Porque zero é considerado falso.
Fazer apenas if x executará o que chamamos de truth value testing e nesse teste foi definido que o valor numérico zero será considerado falso¹. Assim, if int('0') será o mesmo que if 0, não executando o bloco dentro do condicional.

*

*Como escrever a condição "if not A" de uma forma mais explícita?
Segue a mesma ideia que a linguagem C utiliza (e talvez muitas outras), que nem possuía o tipo booleano e utilizada 0 e 1 para o serviço, sendo 0 o equivalente a falso e 1 a verdadeiro.
Aliado a isso, a sua verificação é falha. Não é suficiente apenas verificar se o último caractere é um número pois nesse caso a string petunias42 ou 12uva45 seriam considerados valores numéricos válidos.
A melhor forma de tratar isso é tentando gerar uma instância de float a partir da entrada. Se não for um número válido será lançada a exceção ValueError:
palavras = ['1000', 'abacaxi', 'uva', '15.19', '-1', '+1.45', '123.456-', '12.34+']
numeros = []

for palavra in palavras:
    try:
        float(palavra)
    except ValueError:
        continue

    numeros.append(palavra)

print(numeros)

*

*Como verificar se o valor de variável string é numero?

(1): A PEP 285 que prevê a adição do tipo booleano no Python não só indica que 0 é considerado falso como sugere que o booleano seja implementado como um subtipo de int.

This PEP proposes the introduction of a new built-in type, bool, with two constants, False and True. The bool type would be a straightforward subtype (in C) of the int type, and the values False and True would behave like 0 and 1 in most respects (for example, False==0 and True==1 would be true) except repr() and str().

Isso pode ser confirmado dentro da linguagem fazendo:
>>> print(isinstance(True, int))
True

>>> print(isinstance(False, int))
True

>>> print(issubclass(bool, int))
True


text:
Q: Login system in PHP wont work correctly for some reason my login script in php keeps returning invalid results, I'm using PHPMYADMIN to handle the database and mysqli to connect however whenever I submit the data though a HTML form the values always return false even if the correct username and password combo is working.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$con = mysql_connect("localhost","cnathanielwcol","","login");
if(! $con){die('Connection Failed'.mysql_error());}

$result = mysqli_query("SELECT * FROM login");
$row = mysql_fetch_array($result);
var_dump($row);

if ($row["username"]==$username) {
  echo "Correct Username
";
} else {
  echo "Wrong Username
";
}

if ($row["password"]==$password) {
  echo "Correct Password
";
} else {
  echo "Wrong Password
";
}

echo "

Username Submited Via HTML: " . $username . "";
echo "
Password Submited Via HTML: " . $password . "";
?>

A: Change
$con = mysql_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");

With
$con = mysqli_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");

Your are trying to fetch the data with mysqli and your database connection is established by mysql
your full code:
$username = $_POST["username"];
$password = $_POST["password"];
$con = mysqli_connect("localhost","cnathanielwcol","","login") or die('connection is not establised'.mysqli_error($con));

$result = mysqli_query($con,"SELECT * FROM login WHERE username='$username' AND password='$password'");
$rowCheck=mysqli_num_rows($result);
if ($rowCheck>0) {
    // fetch all data
    //start session
    echo "you are logged in ";
}
else{
    echo 'username or password did not match';
}

Use hash password.your code is not safe.

A: Firstly, you need to select a single row, not all the rows in your table, you'd do that by specifying a WHERE clause, currently, you are trying to compare an array of values to a string which should be throwing an error if error reporting is enabled.
Secondly, you are mixing to different APIs, mysql_* is not mysqli_*.
Thirdly, it doesn't seems as though you are hashing your passwords, please, do so.
Fourthly, make use of prepared statements, it seems as though you are still learning so it would be best to start using them now.
Reading Material
OWASP's Password Storage Cheat Sheet
OWASP's PHP Security Cheat Sheet

A: MySQL is deprecated from new version of PHP use
$con = mysqli_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");

A: Could you use mysqli_* please? You might be having a problem with your html form maybe


text:
Q: Delphi Classes: Property vs Get/Set methods So I'm kinda new to OO programming. Delphi has properties which are intended to be a "more elegant" way to acess class data than getters/setters (read it here usage of property vs getters/setters in business classes).
When should I use the fields directly and when should I use getters/setters inside the property? I'm gessing only when the data needs to be manipulated, but I'm not sure.
Edit:
Is it wrong to omit a setter that does nothing but return the value of the field  itself?
  property Field :integer read FField write FField;

A: In addition to @NGLN answer there is another use case for property getter/setter.
Accessing class instances through interface is only possible via instance methods. If you have to access property in such case you have to implement getter/setter methods.
type
  IField = interface
    function GetField: integer;
    procedure SetField(value: integer);
    property Field: integer read GetField write SetField;
  end;

  TField = class(TInterfacedObject, IField)
  protected
    FField: integer;
    function GetField: integer;
    procedure SetField(value: integer);
  public
    property Field: integer read GetField write SetField;
  end;

var
  f: IField;
  x, n: integer;
...
  f := TField.Create;
  f.Field := 5;
  f.SetField(6);
  n := f.Field;
  x := f.GetField;

Of course, depending whether you need only read or write access to that property you can omit setter or getter in your interface declaration.
Keep in mind that accessing instance through interface gives all interface implemented methods public visibility. That is why in above example you can call f.GetField despite it being declared protected (or even private).

A: What is unacceptable is to do this
TMyClass = class
private
public
  Fubar :integer;
end;

the remainder of your examples are fine.  I would be happy to receive code from you that reads like this
TMyClass = class
private
  FFu : integer;
public
  property Fu :integer read FFu write FFu;
end;

because I can confidently change it to
TMyClass = class
private
  FFu : integer;
  procedure SetFu(Value : Integer);
  function GetBar() : string;
public
  property Fu :integer read FFu write SetFu;
  property Bar : String read GetBar;
end;

without breaking existing code.
I have a personal dislike of setters that do nothing
procedure TMyClass.SetFu(Value : Integer);
begin
  FFu := Value;
end;

But in truth it is harmless.
Does that help?
This would be a valid reason or incentive for using a setter
procedure TMyClass.SetFu(Value : Integer);
begin
  if FFu <> Value then begin
    FFu := Value;
    if Assigned(FAfterFooChanged) then
      FAfterFooChanged(FFu);
  end;
end;

not 'manipulation' as such ...

A: Why properties?
For starters, a quick summary from the documentation on properties:

A property, like a field, defines an attribute of an object. But while a field is merely a storage location whose contents can be examined and changed, a property associates specific actions with reading or modifying its data. Properties provide control over access to an object's attributes, and they allow attributes to be computed.

Why not only setter and getter?
Separation of storage and access can indeed be achieved by the use of just getters and setters, and leave the property be. That is true, but the question you link to originates from a language difference: Delphi does have properties, and the answers there already explain why to use them. The two most obvious reasons are (1) cleaner code and (2) assignment capability. I think this answer deals with it quite extensive already.
Furthermore, without the use of properties, getters and setters are always needed, where with properties they are not. Assume a setter implementation, but no getter: a property can directly read the field.
Class completion
When you just declare a property's name and its type, Delphi's class completion defaults to reading a private field and a private setter which sets the private field. Mind that this is just the default configuration, which you again can modify to your needs. When you fully specify the property declaration, class completion will comply and add a private field, a getter and/or setter as required for your declaration.
Properties without getter and setter

Is it wrong to omit a setter that does nothing but return the value of the field itself?

When a property has no getter nor setter and it just reads and writes the field, then you could conclude that there is no difference beside being consistent. But that is not the case. The field and the property have distinct names, and therefore possibly distinct meaning. Meaning that you can give. See Using properties instead of fields in class methods of the same unit is a bad practice?.
When to use a getter or setter?

... I'm gessing only when the data needs to be manipulated ...

Well, that is partly true. Manipulation is one of the many reasons. Consider a Price property of type String, and its private field FPrice:

*

*Limitation: When the price needs to be equal or higher than zero,

*Delegation: When FPrice is part of another field, or when it otherwise is beyond the responsibility of this class,

*Verification: When the price may only have two decimals behind the comma,

*Interpretation: When the price is entered in thousands, but should be stored in cents,

*Effect: When the price has consequences for another field, for example rate or margin,

*Activation: When an edit to the price requires immediate action, for example updating the GUI,

*Conversion: When the price is entered in dollars but should be stored in yen,

*Cancelation: When the price does not make sense, for example when it is entered in scientific notation.

Note that a Price property is quite rudimentary. Leaving its setter or getter for future implementation is very well possible. But imagine more advanced properties which cannot do without setter or getter:

*

*A field that needs to be created before consulting:
function TMyObject.GetBarelyUsed: TRare;
begin
  if FBarelyUsed = nil then
    FBarelyUsed := TRare.Create(Self);
  Result := FBarelyUsed;
end;

*An item can be selected, but the item itself does not know what to do. Instead the owner does. Notice the complete absence of the private field in this case:
procedure TItem.SetSelected(Value: Boolean);
begin
  if Value <> Selected then
  begin
    if Value then
      Owner.Selection.Add(Self)
    else
      Owner.Selection.Remove(Self);
  end;
end;

*An image control, specialized in viewing your own image format. Assignment of the FileName property involves: checking the correct file extension, checking file existance, storing the file name in the private field, loading the file, adjusting the pictures' dimensions, or else undoing the previous assignment:
procedure TAwDxfImage.SetFileName(const Value: TFileName);
begin
  if FFileName <> Value then
    if SameText(ExtractFileExt(Value), '.' + SDxf) and
      FileExists(Value) then
    begin
      FFileName := Value;
      FGraphic.LoadFromFile(FFileName);
      FGraphic.SetBounds(Width, Height);
    end
    else
    begin
      FFileName := '';
      FGraphic.Clear;
    end;
end;

Source: NLDelphi


text:
Q: How to install windows from a .iso file My system is running on windows 10 on 500GB SATA. I've windows xp installation files (setup.exe etc) that i m trying to install on another 128GB SSD drive. I don't have a USB. Can someone please guide what are possible options?

A: What I finally did was to download .iso image file for windows 10 using torrent. Luckily I found the best WIN10 (activated and updateable). I bought a blank DVD (8.5gb) from a local store and using Imgburn utility, I burned .iso file to DVD and finally installed Windows 10.
Hope it helps.


text:
Q: Possible to fade out div border? I know you can fade out a
 with jQuery, but I was wondering if it's possible to fade out a border for a
?
So I've got my
:

And I'd just like to some how make that border fade out after 5 seconds.

update
Anyone still wanting to do this can do this with CSS3 transitions.
Just be sure to check it's within your supported browsers capability: http://caniuse.com/#search=transition
example
div {
    border: 4px solid red;
    -webkit-transition: border-color .25s ease;
       -moz-transition: border-color .25s ease;
        -ms-transition: border-color .25s ease;
         -o-transition: border-color .25s ease;
            transition: border-color .25s ease;
}

div:hover {
    border-color: none;
}

A: A real fade out animation would require us to use the alpha channel.
AFAIK jQuery UI's use of rgba() is very buggy, so we can use the step property to change the opacity of the border like this:
setTimeout(function(){

    var div = $('.confession');
    $({alpha:1}).animate({alpha:0}, {
        duration: 1000,
        step: function(){
            div.css('border-color','rgba(0,0,0,'+this.alpha+')');
        }
    });

}, 5000);

I used a black border so you can notice the effect, but you can change it to whatever color you want, for example rgba(221,221,221,'+this.alpha+')'); for #DDD
Working example: http://jsfiddle.net/victmo/2Xazx/
Cheers!
BTW, no plugins needed for this approach...

A: i like my way more... >.> No plugins needed.
http://jsfiddle.net/MJD5B/2

    text

.fakeBorder
{
    position:absolute;
    height:100%;
    width:100%;
    left:0px;
    top:0px;
    border:3px solid #DDD;
    margin:-3px;
}

A: I'm afraid there isn't a clean 100% working way of doing so.

*

*You could animate the border-width, but that won't be "fading out".

*You could animate the border-color, but that would require an extra library on top of jQuery, plus it will break if you change the background.

*You can fake the border by placing 2 divs on top of each other with a small space, and fade the outer one out, but that isn't really a border and if you'd want something fancy such as a dashed or dotted border, it won't be that simple.

If you don't plan on having something more fancy than a simple solid border, I suggest using jQuery to generate the 2 divs solution, and then fade out the outer (border) div. Like Joey's answer above me.

A: You need to use jQuery UI for that (color animation):
$(".confession").animate({
   borderLeftColor: "white",
   borderTopColor: "white",
   borderRightColor: "white",
   borderBottomColor: "white",
}, 3000);

(it's not working with borderColor and as for "transparent" it fades to white anyway)
http://jsfiddle.net/Jacek_FH/kxCht/3/
plugin with the similar (same?) capability:
http://docs.jquery.com/Release:jQuery_1.2/Effects#Color_Animations

A: The solution below should meet all of your posted criteria:
Wait 5000 ms (5 sec), then animate a fade out of the border that lasts 500 ms (.5 sec).
$(".confession").delay(5000).animate({borderWidth: "0"}, 500);

Working example: http://jsfiddle.net/ECRLW/
Since the above solution seems to be unable to animate the borderWidth fade with some browsers, the only other way I would know how to accomplish what you want with jQuery would be to use setTimeout():
function shrinkBorder(){
    var e = $(".confession");
    var eBorderWidth = e.css("border-width");
    if(eBorderWidth != "0px"){
        e.css("border-width",(eBorderWidth.split("px")[0]-1));
        setTimeout(shrinkBorder, 50);
    }
}

setTimeout(shrinkBorder, 5000);

Working example: http://jsfiddle.net/mmfMG/


text:
Q: How to add a lap timer in XNA? I've got a 2D racing game that I'm developing. Here's a screenshot of the game in XNA;http://oi41.tinypic.com/vxhy5y.jpg . I want to know how to create a lap timer. So for instance, "if car1blue/car2red collides with chequered flag start timer, and if they collide a second time, stop timer." Will this work in theory? If it does work in theory, how do I do it in XNA?
If you want, I could provide the code I've done so far.
Thank you very much!
EDIT;
Is it possible if you could show me what code goes where?

A: Without knowing how you have put it all together, can you not just store a DateTime somewhere of the time they passed the line, so when it starts you do:
public MyGame
{
    DateTime lastLapTimestamp = DateTime.Now;
    TimeSpan lastLapTime = new TimeSpan();
    // other stuff

    public void Update(TimeSpan elapsedTime)
    {
        if(HasCompletedLap)
        {
            var currentLapTimestamp = DateTime.Now;
            lastLapTime = currentLapTimestamp - lastLapTimestamp;
            lastLapTimestamp = currentLaptimeStamp;
        }
        // Other stuff
    }
}

Then just display your lastLapTime wherever you want to see how long it took to go around.

A: As requested here is the implementation that would be required in your example empty XNA project, again I am ONLY answering the question you pose above about the lap time:
/*
    NEW MEMBERS FOR YOU TO IMAGINE YOU HAVE SOME MEANINGFUL RACING GAME
*/
private Vector2 yourPosition;
private Texture2D yourCar;
private Texture2D yourTrack;
private Rectangle yourStartingLine;

private DateTime currentLapTimestamp = DateTime.Now();
private TimeSpan currentLapTime = new TimeSpan();

public Game1()
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";
}

protected override void Initialize()
{
    // Put your starting line somewhere
    yourStartingLine = new Rectangle(100,100,10,100)

    base.Initialize();
}

protected override void LoadContent()
{
    yourCar = Content.Load<Texture2D>("YourCarAssetName")
    yourTrack = Content.Load<Texture2D>("YourTrackAssetName")
}

protected override void UnloadContent()
{
    // TODO: Unload any non ContentManager content here
}

protected override void Update(GameTime gameTime)
{
    // Check your keyboard input
    UpdatePosition(Keyboard.GetState());
    if(HasPassedStartingLine())
    { UpdateLapTime(); }
    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    DrawTrack();
    DrawCar();
    DrawLapTime();
    base.Draw(gameTime);
}

/*
    NEW METHODS FOR YOU TO PRETEND DO STUFF
*/

private void UpdateLapTime()
{
    var newTimestamp = DateTime.Now;
    currentLapTime = newTimestamp - currentLapTimestamp;
}

private bool HasPassedStartingLine()
{
    // Work out if you have passed the starting line
    // and make sure you dont register it again until
    // they have passed the finish line
}

private void UpdatePosition(KeyboardState keyboardState)
{
    // Assumes you work out how to handle your players
    // controls to move the position of the car
}

private void DrawTrack()
{
    // Your rendering logic for the track
}

private void DrawCar()
{
    // Your rendering logic for the car
}

private void DrawLapTime()
{
    // your rendering logic for the lap time
}


text:
Q: How to set a page to display sub-categories and not products? How to set a page to display sub-categories and not products?

A: To hide products from a category page, set the category's Display Mode to Static block only.
To list all subcategories, include the following bit of code in your catalog/category/view.phtml:

<?php foreach ($this->getCurrentCategory()->getChildrenCategories() as $_subcat): ?>

<a href="<?php echo $_subcat->getUrl() ?>"><?php echo Mage::helper('catalog/output')->categoryAttribute($_subcat, $_subcat->getName(), 'name') ?>

<?php endforeach ?>

You may want to add checks for whether the subcategories are active, if there are any at all, and perhaps a flag of some sort to make the whole thing more flexible with a simple Custom Layout Update.


text:
Q: I know a GUID is nearly unique. But is it acceptable practice to assume it is unique? So I completely understand the mathematical unlikeliness of creating two GUID values with the same number.  But is it acceptable practice to assume they are unique?
For example I am working with a system for dealing with medical files.  When I began to layout the database structure the manager (Not very technically knowledgeable, but likes to think he is and delegates things that would be better left for the more technically minded to decide) says he wants to use GUID's to separate different medical records instead of INT because it is "More unique".  I explained how an INT is always going to be unique because it is sequential.  I suggested we use BigINT if it will make him feel more comfortable since there are more numbers in that then if the population of the planet increased to the point people would only fit standing next to one another across the planet, but he is insisting on using GUIDs.
My feeling is although it is NEARLY IMPOSSIBLE for there to be a mix up, when dealing with medical records, why take the chance?  What is the advantage of using a GUID vs an INT in this scenario?

A:
But is it acceptable practice to assume it is unique?

Yes. That is the entire purpose of UUID, to be used as a reliable unique identifier without centralized coordination. (A GUID is Microsoft's variation of a UUID.)
Only you (or your appropriate management) can make the final judgement for your particular project.
But if you truly begin to appreciate the enormity of the numerical range of 12x bits (which is actually incomprehensible to the human mind), then you know you can remove the usage of a properly generated UUID from your list of worries.
By "properly generated" I mean things like using the date-time Versions, or for lower number of values use the random (Version 4) if backed by a cryptographically-strong random number generator. Nearly every modern operating system today includes a UUID generation library. Or you can use the OSSP UUID project. Improperly-generated would include roll-your-own implementations you may see bandied about the inter webs.
As for the suggestion to use a database's auto-incrementing serial/sequence number, every database person I know with years of real-world experience has been burned by those. I've never heard of or read of anyone ever having a collision with properly-generated UUIDs. I'm not saying sequences are necessarily bad or don't have their place, I'm just saying that all I can do is laugh when I hear people turn away from a UUID because of some beyond-astrononomically incomprehensibly minute possibility of a UUID collision and choose a sequence instead.

when dealing with medical records, why take the chance?

Your medical system is far far more likely to fail because of faulty data-entry or other human error with handling records. But do you post 3 clerks on duty to independently triple-enter the same data to reduce that chance of error? No. And that risk is incomprehensibly mathematically more likely to happen than a UUID problem. Yet every medical facility I know of accepts that enormous risk without even thinking about it.

What is the advantage of using a GUID vs an INT

The advantages include:

*

*No need to manage your sequences.Examples include: Resetting for development, test, and production environments. Or when restoring a backup. Or fixing the sequence after faults in the system's serial generation library (my own experience).

*Avoid users' intuited assumptions being confused about missing numbers in the sequence. I've had that conversation far too often.

*Federating data between distributed systems.This is the biggest advantage, each system can act independently yet easily share data back and forth with other systems. Without UUIDs, the administrative overhead and the risk of error are bothersome at first and only grow over time.

Downsides include:

*

*Larger memory and storage usage.Serial numbers are usually 32-bit integers, sometimes 64-bit. A good database with native support for UUID as a data type will use 128 bits.

*Less readable by humans.One workaround is to just read several of the first or last digits for casual work.

*Possibly less efficient indexing, with very large number of entries.

A: using an incrementing integer ID ensures only uniqueness within its own domain/type, an advantage of UUIDs/GUIDs is that they uniquely identify the owning thing in the entire universe.
So if you have multiple objects, say MedicalRecord, ID = 5, VaccinationForm, ID = 5 then you need to specify both the type ("medicalRecord" or "vaccinationForm" with the ID value of 5) whereas with a GUID you only need to store a single quanta of information to uniquely identify it.
It can be argued that using GUIDs is a waste of space as they are 16 bytes long (a 128-bit value).
If your system is self-contained and not interfacing with others you might want to use SQL Server's "sequence" concept, where instead of each table storing its own identity sequence, the sequence is maintained for all tables, making it a Locally-Unique ID value. You can use any size integer too.
See here: https://msdn.microsoft.com/en-us/library/ff878091.aspx


text:
Q: Coalesce and Case-When with To_Date not working as expected (Postgres bug?) I'm using Postgres 9.1. The following query does not work as expected. Coalesce should return the first non-null value. However, this query returns null (1?) instead of the date (2).
select COALESCE(
    TO_DATE('','yyyymmdd'), --(1)
    TO_DATE('20130201','yyyymmdd') --(2)
    );

--(1) this evaluates independently to null
--(2) this evaluates independently to the date,
--    and therefore is the first non-null value

What am I doing wrong? Any workaround?
Edit: This may have nothing to do with Coalesce at all. I tried some experiments with Case When constructs; it turns out, Postgres has this big ugly bug where it treats TO_DATE('','yyyymmdd') as not null, even though selecting it returns null.
[PS: Strike-out above to avoid misleading. Postgres doesn't have a bug, but rather does not treat empty strings as null. See answer.]

A: SELECT TO_DATE('','yyyymmdd');

doesn't evaluates to NULL since you passing an empty string instead of NULL as an argument to TO_DATE()
This will successfully evaluate to NULL
SELECT TO_DATE(NULL,'yyyymmdd');

If you expect an empty string and want to treat it as a NULL you can use NULLIF()
SELECT TO_DATE(NULLIF(dt, ''),'yyyymmdd')
  FROM
(
  SELECT CAST('' AS VARCHAR(32)) dt
) q

That being said your sample code that evaluates (1) as NULL
SELECT COALESCE(
    TO_DATE(NULLIF('', ''),'yyyymmdd'),       --(1)
    TO_DATE(NULLIF('20130201',''),'yyyymmdd') --(2)
);

and returns

|                        COALESCE |
-----------------------------------
| February, 01 2013 00:00:00+0000 |

Here is SQLFiddle demo


text:
Q: WebAPI 2: is a void response faster then IHttpActionResult? I was building a method today in my WebAPI2. and came to the question if i should make my method a void or keep it as IHttpActionResult?
As advantage i see that IHttpActionResult can return any response code. What is the advantage of the void approach? is it faster or is the only difference that it always response 200 (or is it 204?).
Does somebody know which one is faster? or if it has any other major difference than the ones that i have named? (this includes the fact that void can't respond anything and IHttpActionResult can.......)

A: @Felipe Oriani, you where totaly true.. I was curious so i did the test.
See this amazing output.

*

*Void Avg response time is 2.075 ms

*IHttpActionResult Avg response time is 1.651 ms!

So that is a difference of 0.424 ms
This was with the following webAPI code
[Route("test/void")]
public void GetFirst()
{
    StringBuilder stringbuilder = new StringBuilder();
    for (int i = 0; i < 20; i++)
    {
        stringbuilder.Append("something");
    }
    //Thread.Sleep(1000);
}

[Route("test/IHttpActionResult")]
public IHttpActionResult GetSecond()
{
    StringBuilder stringbuilder = new StringBuilder();
    for (int i = 0; i < 20; i++)
    {
        stringbuilder.Append("something");
    }
    //Thread.Sleep(1000);
    return Ok();
}

Also i tried giving the webAPI more work on each request.. to see if the difference stays the same, or if for an longer action it's a real improvement to use IHttpActionResult instead of void?
I set the iteration to 200000 and uncommented the Thread.Sleep(1000) in the WebAPI code
Now the results:

*

*Void Avg response time is 11.64 ms

*IHttpActionResult Avg response time is 11.11 ms

So that is a difference of 0.53 ms
To which i can conclude and confirm, that what you say is true. And IHttpActionREsult is indeed faster then void. Only the difference is to minor to really notice something. But if your looking for the minor mini optimalisations? this is one of them!
The image below for the result!

A: Every message from an asp.net web api application return an http status code. An exception is expensive, so, if you pass this to the web api, the framework should know how to lead with this and change to a http message result.
There is no extremelly difference. A void action method in web api will return something diferent from 200 - OK if the code throw an exceptionActually I think it's even more expensive than a method with a type in result because the asp.net framework need to get the exception and change it to a http message as I said before.
If you specify an http message in your action method, you know what exactly you are responding to the client (I mean, the http status code as least). I enjoy working with HttpResponseMessage and create responses with the specific http status code.


text:
Q: std::function with noexcept in C++17 In C++17 noexcept has been added to the type system:
void r1( void (*f)() noexcept ) { f(); }
void foo() { throw 1; }

int main()
{
    r1(foo);
}

The latest versions of GCC and Clang in C++17 mode reject the call r1(foo), because void (*)() cannot be implicitly converted to void (*)() noexcept.
But with std::function instead:
#include <functional>

void r2( std::function<void() noexcept> f ) { f(); }
void foo() { throw 1; }

int main()
{
    r2(foo);
}

Clang accepts the program, apparently ignoring the noexcept specifier; and g++ gives a strange error regarding std::function<void() noexcept>.
What is the correct behaviour for this second program in C++17?

A: std::function's definition hasn't changed in the current working draft:
template<class T>
class function; // not defined

template<class R, class... ArgTypes>
class function<R(ArgTypes...)> {
    /* ... */
};

Since void() noexcept doesn't match the partial specialization, std::function<void() noexcept> is an incomplete type. Both Clang and GCC trunk diagnose this accordingly.


text:
Q: Material-UI Slider Component: How to show values/marks in a different order? By default the Material-UI slider shows marks/values in ascending order from min to max
For example, a slider with following config:
const marks = [
  {
    value: 1,
    label: '1'
  },
  {
    value: 2,
    label: '2'
  },
  {
    value: 3,
    label: '3'
  },
  {
    value: 4,
    label: '4'
  },
  {
    value: 5,
    label: '5'
  }
]

<Slider defaultValue={1} step={1} valueLabelDisplay="auto" onChange={handleChange} className={classes.slider} min={1} max={5} marks={marks} />

will render the slider like this: 1->2->3->4->5
I want to change the order in which the values/marks are displayed, something like this: 2->1->5->4->3 (Or any order in general, but other than the default 1 to 5)
Any help will be greatly appreciated, thanks!

A: With array manipulation you can do that like this maybe:

const arr = [1,2,3,4,5];
const arr1 = arr.splice(2).reverse(); // arr1 = [2,1] arr = [3,4,5]
const arr2 = arr.reverse(); //[5,4,3]
const result = arr1.concat(arr2); // [2,1,5,4,3];


text:
Q: C# Scaling GDI positions but not font size or line thickness I need to do a lot of drawing on a grid with spacing of 12.5 pixels X and 20 pixels Y (the PICA scale). The font needs to be a specific size and the lines need to still be one pixel thick. Currently I'm saving these values in floats and multiplying them (for example, text starting on row 3, column 6 is drawn as coords 2f*cx,5f*cy). I'd like to avoid all this unnecessary multiplication by using a scale transform, but unfortunately those affect the font size and line thickness as well. Is there a way to avoid this? Or would the compiler be silently doing this for me as the cx/cy values are constants?

A: ...also, Microsoft has left a little "hack" for us if you don't want lines to be scaled. Set the width of the line to 0px, and it will always be drawn a single pixel thick.

A: The compiler should reduce the constant portion of expressions to a single constant, but there will still have to be a multiply at runtime since the value of your float is not known at compile time.  So, (1 + 2 + c) * 6 * f can be reduced to n * f by the compiler if c is a constant.
Your best bet to prevent scaling of your text is probably to set up a scaling transform, draw all your non-text graphics that you don't care about maintaining minimum line widths, then draw your text without using the transform.  You can use the transform to locate where the text should start to save yourself having to calculate that independently - a function like LPtoDP (logical point to device point) should do the trick.
Another other way to approach this is to render the text in the transform, but apply a reverse scaling to the text size itself.  So, if the transform scales down 5%, you scale the font size up by 5%.  This will not give exact results, but might be close enough for visuals.


text:
Q: getting info after submitting form so Im new to php(almost never wrote php code before) I created a website with wordpress and created a form with FormMaker, when Im done submitting the form i want to be able to hook and read the data from the form then parse it into a CRM system
the form isn't contact form 7 and i cant seem to find the action hook to process the data after the form is submitted

A: Make sure form is creating using contact form 7 plugin.
If yes then use below code.
Hope its working for you.
function dorzki_send_lead_to_powerlink( $cf7 ) {

    //check if it is the right form
  if ($cf7->id()==11869)     // get form_id from forms list.
  {

    $submit = WPCF7_Submission::get_instance();
    $data   = $submit->get_posted_data();

    if ( ! empty( $data ) ) {

        $api_key = '402253f3-a260-40a7-85d2-dff0d6fae770';
        $api_url = 'https://api.powerlink.co.il/api/record/lead';

        $lead_data = [
            'firstname'      => $data[ 'your-name' ],
            'telephone1'     => $data[ 'your-phone' ],
            'emailaddress1'  => $data[ 'your-mail' ],
            'description'    => $data[ 'your-message' ],
            'leadsourcecode' => 4, // Internet
            'statuscode'     => 2, // First Contact
        ];

        $lead_data = json_encode( $lead_data );

        $response = wp_remote_post( $api_url, [
            'headers' => [
                'Content-Type'   => 'application/json',
                'tokenid'        => $api_key,
                'Content-Length' => strlen( $lead_data ),
            ],
            'body'    => $lead_data,
        ] );

        return ( ! is_wp_error( $response ) );

      }
    }
    return false;

}

add_action( 'wpcf7_before_send_mail', 'dorzki_send_lead_to_powerlink' );


text:
Q: mongodb 3.2 document validation disallow extra fields we started using MongoDb and we would like to take advantage of the document validation introduced in 3.2.
We would like to disallow extra properties which are not declared in the schema. For example if the schema says :
"group1.a": {
  "$type": "int"
},
"group1.b": {
  "$type": "int"
}

I would like the following document to fail:
{
   "group1": {
      "a": 1,
      "b": 2,
      "c": 3
   }
}

Does anybody have an idea on how to implement this ?
Thanks

A: According to some research like here validation only check listed fields in validation schema for existence and rules.
If field is not on the list - then it is not under validation.
As this was introduced with 3.2 then you could open a Jira ticket for this functionality here


text:
Q: UIView with custom shape I want to have a UIElement (any of UIView, UIButton, UILabel etc.) with custom shape lets say a triangle.
How do you suggest to achieve it.
Thanks in advance.

A: Here is a sample of a UIView subclass (triangle):
@implementation TriangleView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextBeginPath(ctx);

    CGContextMoveToPoint   (ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect));  // top left
    CGContextAddLineToPoint(ctx, CGRectGetMidX(rect), CGRectGetMinY(rect));  // mid right
    CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect));  // bottom left

    CGContextClosePath(ctx);

    CGContextSetRGBFillColor(ctx, 241/255.0, 241/255.0, 241/255.0, 1);
    CGContextFillPath(ctx);

}

@end


text:
Q: Need free ssl certificate because google chrome doesn't support webcam without https The new version of google chrome doesn't allow using webcam without https :

getUserMedia() no longer works on insecure origins. To use this
  feature, you should consider switching your application to a secure
  origin, such as HTTPS. See https://goo.gl/rStTGz for more details.

So I need a free ssl certificate (or cheap ssl certificate) for my web application. Openssl doesn't suit me because browsers display warning message when the ssl certificate is self-signed.
An idea ?
Thank you in advance.

A: use https://letsencrypt.org/ to get a free valid ssl certificate recognized by your mobile phone and by your web browser

A: I use cloudflare.com Origin Certificate. It is pretty good.


text:
Q: typecasting Eigen::VectorXd to std::vector Their are many links to go the other way round but I am unable to find to get a std::vector from a Eigen::Matrix or Eigen::VectorXd in my specific case.

A: You cannot typecast, but you can easily copy the data:
VectorXd v1;
v1 = ...;
vector<double> v2;
v2.resize(v1.size());
VectorXd::Map(&v2[0], v1.size()) = v1;

A: vector<int> vec(mat.data(), mat.data() + mat.rows() * mat.cols());

A: You can do this from and to Eigen vector :
    //init a first vector
    std::vector<float> v1;
    v1.push_back(0.5);
    v1.push_back(1.5);
    v1.push_back(2.5);
    v1.push_back(3.5);

    //from v1 to an eignen vector
    float* ptr_data = &v1[0];
    Eigen::VectorXf v2 = Eigen::Map<Eigen::VectorXf, Eigen::Unaligned>(v1.data(), v1.size());

    //from the eigen vector to the std vector
    std::vector<float> v3(&v2[0], v2.data()+v2.cols()*v2.rows());

    //to check
    for(int i = 0; i < v1.size() ; i++){
        std::cout << std::to_string(v1[i]) << " | " << std::to_string(v2[i]) << " | " << std::to_string(v3[i]) << std::endl;
    }


text:
Q: How can I store a float value in an NSArray? for ( tempI = 0; tempI < 10; tempI++ )
{
    tempJ = 1;
    NSArray *objectsForArray = [NSArray arrayWithObjects:@"array[tempI][tempJ]", @"array[tempI][tempJ+1]",  @"array[tempI][tempJ+2]", nil];
}

Can I write the code as above. I need to store an float value (array[][]) in NSArray.  Can I do it ?
My problem is, I have a matrix as
1.0   0.4   0.3   0.5
2.0   0.4   0.5   0.5
3.0   4.3   4.9   0.5

I need to retrieve values (0.4, 0.3, 0.5) using  1.0, 2.0 3.0 . How can I use NSDictionary for this?
Thank You
for( tempI = 0; tempI < 5; tempI++)
{
        NSDictionary *dictionary[tempI] = [ [NSDictionary alloc] initWithObjects:@"array[tempI][tempI + 1]", @"array[tempI][tempI + 2]", @"array[tempI][tempI + 3]", @"array[tempI][tempI + 4]", @"array[tempI][tempI + 5]", nil];
}

Can I write in this way ? Does Objective C accepts it ?
I am getting an error as

error: variable-sized object may not be initialized

A: NSArray can only store objects, not primitives, fortunatly, the NSNumber class has a convenience method that takes a float primitive and returns a float object as such:
+ (NSNumber *)numberWithFloat:(float)value

therefore you could populate your array like this:
float exampleFloat = 5.4;

NSArray *anArrayOfFloatObjects = [NSArray arrayWithObjects:
                                    [NSNumber numberWithFloat:10.0],
                                    [NSNumber numberWithFloat:2],
                                    [NSNumber numberWithFloat:4],
                                    [NSNumber numberWithFloat:exampleFloat],
                                    nil]; // Don't forget the nil to signal
                                          // end of the array

As for your specific issue, you could write:
NSMutableArray *tmpArray; // this is necessary since an NSArray can only be initialized
                          // once and we will need to have all the objects that will be
                          // added to the array available to us at once.

tmpArray = [NSMutableArray arrayWithCapacity:12]; // returns an autoreleased empty array

for (int col=0; col<=3; col++) {
    for (int row=0; row<=2; row++) {
        [tmpArray addObject:[NSNumber numberWithFloat:array[col][row]]];
    }
}
NSArray *myArray = [NSArray arrayWithArray:tmpArray];

as far as using a dictionary to retrive matrix values, the only way I can think off would be to key code your matrix values as such:
A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4
D1 D2 D3 D4
for example:
 NSMutableDictionary *myDictionary;

[myDictionary setObject:[NSNumber numberWithFloat:5.0] forKey:@"A1"];

...

NSNumber *myFloat = [myDictionary objectForKey:@"A1"];

Also, it is important to point here that whenever something is written under the format @"something here", it literally is an NSString object.  so when you write:
NSArray *objectsForArray = [NSArray arrayWithObjects:
                                             @"array[tempI][tempJ]",
                                             @"array[tempI][tempJ+1]",
                                             @"array[tempI][tempJ+2]",
                                             nil];

this is exactly the same as writting:
NSString *newString = @"Roses are red";    // example strings
NSString *newString1 = @"Violets are blue";
NSString *newString2 = @"array[tempI][tempJ+1]";
NSString *newString3 = @"These are all string objects";

NSArray *objectsForArray = [NSArray arrayWithObjects:
                                             @"array[tempI][tempJ]",
                                             newString2,
                                             @"array[tempI][tempJ+2]",
                                             nil];

A: Try:
for ( int tempI = 0; tempI < 10; tempI++ )
{
    int tempJ = 1;
    fl_tempI = float(tempI);
    NSArray *objectsForArray = [NSArray arrayWithObjects:@"array[fl_tempI][tempJ]", @"array[fl_tempI][tempJ+1]",  @"array[fl_tempI][tempJ+2]", nil];
}