text:
Q: onTapGesture not working with padding modifier in SwiftUI For some reason, the onTapGesture modifier doesn't work when I add a padding modifier. If you look below, you'll see the 3 places where I've tried to add the padding modifier. The onTapGesture modifier works fine if I comment out/remove the padding modifier, but if i uncomment any of those paddings, the onTapGesture stops working. I don't know what's going on here.
if noninitialRun == false {
                ZStack(alignment: .topTrailing) {
                    Walkthrough()
                        //.padding(-16)

                    VStack {
                        Image(systemName: "xmark")
                            //.padding()
                            .onTapGesture {
                                print("tap")
                                noninitialRun = true
                                UserDefaults().setValue(true, forKey: "notFirstRun")
                        }
                        //.padding()
                    }
                }
            }

A: It works fine with Xcode 12.3. I think your Xcode version caused it. But nevertheless, you can try:  .contentShape(Rectangle()).

VStack {
  Image(systemName: "xmark")
  .padding()
  .onTapGesture {
    print("tap")
    noninitialRun = true
    UserDefaults().setValue(true, forKey: "notFirstRun")
  }
  .padding()
}.contentShape(Rectangle())


text:
Q: How to get tar to hardlink identical content on-the-fly during archive creation? How can I get tar (or any other program that is commonly available on Linux, e.g. pax) to hardlink duplicate content on-the-fly during archive creation?
That is, I'd like to avoid hardlinking upfront and instead would like tar to take care of it.
Is that possible? How?

A: This is not possible as of now with GNU tar, but things exist :

*

*https://github.com/stfp/tar-dedup : a patched GNU tar with an experimental --dedup-filter command

*http://zbackup.org/ which eats and spits tar formatted streams and dedupes

Note that hardlinking and deduping does not have the same semantics, one would need another kind of tar node type to represent "dupe data" in order for the archive extraction process to properly recreate duplicate (and thus indendently-living) files; that would create incompatible tar archives with most standard tools (GNU tar, pax, etc) which would be a bold move.
Let me insist : if you were able to assimilate dupes with hardlinked files, you would have a problem at archive extraction :
* are they really hardlinked files like those of a Git repo ? Then they should be really recreated as hardlinked files otherwise the restored Git repo won't work ?
* or are they really identical files, and if they were restored as hardlinks, the restored archive would probably have major data leaks (imagine you have assimilated identical /etc/passwd files while archiving, restore them as a single file with multiple hardlinks : one modification in one VM becomes visible in the other!)

redpajama_set_name: RedPajamaStackExchange


text:
Q: sharepoint 2010 create list from template I created a list of documents (Word) and saved it as template.
Then I created a new list from this template in code c#, and add meta data, also in code c#.
something like this:
SPListTemplateCollection listTemplates = web.Site.GetCustomListTemplates(web);
SPListTemplate template = listTemplates[Convert.ToString(templateName)];
Guid g = web.Lists.Add(listName.Trim(), string.Empty, template);

now, when i choose "New Document" option in the new list, word document is open, with the meta data i created in the list.
this works fine when office is 2010 version.
in 2007 version i get message that word cant save the document.
in short, i think sharepoint 2010 can not save a documnent with metadata in office 2007 into list that based on a template and created in c# code.

A: I know that you can't use SharePoint 2010 Managed Metadata with Office 2007 out of the box. You can read detail information from;
Managed meatadata columns in Office 2007


text:
Q: Fogbugz API :: Searching on a custom field My version of Fogbugz is v8 and I'm trying to use the API to refine results by a custom field that i've created, so far i've got the following:
/api.asp?token=[token]&cmd=search&q=project:"=116"+plugin_customfields_at_fogcreek_com_environmentf52:LAMP&cols=sTitle,sPersonAssignedTo,ixBug,environment,product

But the API keeps giving me an error saying
The requested search axis 'plugin_customfields_at_fogcreek_com_environmentf52' is not recognized.

Does anybody know what I am doing wrong?

A: /api.asp?token=[token]&cmd=search&q=project:"=116"&plugin_customfields_at_fogcreek_com_environmentf52:LAMP&cols=sTitle,sPersonAssignedTo,ixBug,environment,product

You use & instead of + to indicate different search criteria.


text:
Q: How to add URL link in email body message in riemann I am trying to add a html URL tag in my email body. I have used like below,
:body (fn [events] "Hello Team.\n Welcome \n  Link to my website  \n * This is an automated e-mail and any responses to this e-mail will not be monitored \n Thank You!")

My html tag was not recognized . I am getting the output like below,
Hello Team,
Welcome
Link to Kibana DashBoard
 * This is an automated e-mail and any responses to this e-mail will not be monitored  Thank You!.

Do I need to use any filter to create a link in clojure.
Thanks in advance.

A: This is because by default you are sending a plain text email.
Riemann defers to Postal for sending emails, see here for how to send HTML emails.


text:
Q: is it possible to change a Char into a String with a loop/if I got a knew problem which should be the last one from my bonus exercise. At first let's explain the rules, I have a word which is shuffle. I want my user to find this word and he has a determined number of tries.
Now I want to let the user know which char from his input (txtBox.Text) was right and which one aren't. So I tried to create a method which is able to Color a char in green If the char is correctly positionned else in red. I ask my teacher and it seems to be a hard thing to do, I tried to find the solution he gave me with richBox but it's way too hard right now, i'm struggling way to much.
So ! I think of something way simpler, or at least i thought it was simpler,  I get the user input in a String and I do a loop around it, every time the correct word and the input char doesn't match I replaced it by a dot.
It doesen't work either if I try to put an index to my :
If word(i) IsNot proposition(j) Then

I'm facing an out of bound and if I try without it, it consider my string as an array of 1 and add to my listbox a single dot.
Here's my code :
    Public Sub charRight&Wrong()
        Dim proposition() As String = {txtInput.Text} //get the proposition from the user
        Dim dot As Char = "."
        Dim word() As String = {theWord} //theWord represent the right answer

        For i = 0 To theWord.Length - 1
            For j = 0 To proposition.Length - 1
                If word(i) IsNot proposition(j) Then
                    proposition(j) = dot
                End If
            Next
        Next

        lboAttempts.Items.AddRange(proposition.ToArray)
    End Sub

I don't really know where I'm wrong I hope you can point it out. Thanks again.


text:
Q: Debugging Android 2.3 browser crashes Recently, I've been trying to find (and hopefully, fix) frequent Android 2.3 browser crashes that affect the SB Nation blog network. Users will navigate to page and it will appear to load, and then about when you'd expect the DOM complete to fire, the browser appears to forcibly close and you are kicked to the home screen. This doesn't happen on every page load, so if you open the browser and try again, it will often load fine.
I have recreated the issue multiple times on my own phone, an HTC Thunderbolt (2.3.4) as well as a Droid Bionic (2.3.4). I have no Android development experience, but I assumed that hooking up the adb debugger may give me some insight into the the cause of this problem. Here are some of the logs of the crash I have captured:

*

*HTC Thunderbolt Logs

*Droid Bionic Logs
(I'd post some URLS on production that have caused these crashes, but I'm already at my two link limit.)
As you may notice, all the HTC logs differ, and the Bionic ones don't seem to offer much technical detail. This is the only common thread I found in all the HTC logs:
 D/skia    (14225): createPlugin (300,150) screen proportion:(w,h)=(0.813008,0.039288), content ratio:2.000000 mainUrl:http://athleticsnation.local:3000/
 D/skia    (14225): createPlugin F10 typical2 video content (300,150)/(369,3818), url=

My guess was F10 == Flash 10, but the Droid Bionic doesn't even have Flash installed, so I'm not convinced that is the cause.
At any rate, I'm at a loss for theories on what is causing these crashes. Is there a way to get more accurate information about these crashes? Could invalid markup be causing the browser to crash? JavaScript limitations? Any help would be greatly appreciated.

A: Probably worth looking at location permissions (and exception handling) around allowed_geolocation_origins():
From HTC dump:

10: W/ContentService( 1646): binderDied() at ObserverNode name allowed_geolocation_origins


text:
Q: Перевод на новую строку после вывода значений внутреннего массива Почему System.out.println() выполняет последующий переход на новую строку после вывода пяти значений, а не после вывода каждого значения?
public class TwoDArrays {
    public static void main(String args[]) {
        int twoD[][] = new int[4][5];
        int i, j, k = 0;
        for (i = 0; i < 4; i++)
            for (j = 0; j < 5; j++) {
                twoD[i][j] = k;
                k++;
            }
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 5; j++)
                System.out.print(twoD[i][j] + " ");
            System.out.println();
        }
    }
}

A: Если вы не выставили фигурные скобки после оператора цикла, то в цикле будет исполняться только следующий за ним метод, т.е.
for(j = 0; j < 5; j++) System.out.print(twoD[i][j] + " ");

Чтобы оба метода вывода на консоль исполнялись во внутреннем цикле напишите так:
for(j = 0; j < 5; j++) {
    System.out.print(twoD[i][j] + " ");
    System.out.println();
}


text:
Q: Can't connect to oracle database with Oracle SQL Developer When I try to connect I get error:

I disabled firewall, started the OracleServiceXE, but still get error.
When I use command lsnrctl status, I get:

lsnrctl start:

My tnsnames.ora file looks like that:
# tnsnames.ora Network Configuration File: C:\app\Coi\product\18.0.0\dbhomeXE\NETWORK\ADMIN\tnsnames.ora
# Generated by Oracle configuration tools.

XE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.0)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = XE)
    )
  )

LISTENER_XE =
  (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.8)(PORT = 1521))

ORACLR_CONNECTION_DATA =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (CONNECT_DATA =
      (SID = CLRExtProc)
      (PRESENTATION = RO)
    )


text:
Q: Using Node JS client I tried to send email via Sendgrid web API but CC or BCC not working I am using sendgrid v6.4.0, sending email using dynamic template to cc & bcc is ignored. Find the payload below -
{
  subject: 'Hello world',
  message: 'Hello plain world!',
  from: 'abcd@abcd.com',
  to: 'a@b.com',
  cc: 'b@b.com'
  bcc: 'c@b.com'
};

CC and BCC is ignored and only email received by a@b.com
Note: I found a similar question question but it was unanswered. sendgrid : add cc in email

A: For sending a single email to a single recipient with a cc and bcc
    const msg = {
      "personalizations": [
    {
      "to": [
        {
          "email": "a@b.com"
        }
      ],
      "cc": [
        {
          "email": "b@b.com"
        }
      ],
"bcc": [
            {
              "email": "c@b.com"
            }
          ]
        }
      ]
          from: 'abcd@abcd.com',
          subject: 'Hello World',
          text: 'Hello plain world',
        };

        sgMail.send(msg).then(() => {
          console.log('emails sent successfully!');
        }).catch(error => {
          console.log(error);
        });

For more info refer this


text:
Q: Why is JavaFX not recognized by Eclipse? Eclipse does not appear to recognize JavaFX. I downloaded the FX plug-in from the Eclipse Marketplace. I have tried re-configuring the build path. The message I get from Eclipse is that JavaFX cannot be resolved. It works on my Desktop, but I cannot get it to work on my Laptop. I have tried every solution I could find on the internet. Please help...
I don't know what to do.


text:
Q: What are the generally accepted guidelines for adjusting \linespread to avoid extra spreading from inline math? General Background
I am just starting to think about typesetting and LaTeX in anything close to a serious manner, and am getting lots of questions that perhaps are appropriate for this site, but perhaps are either too open-ended and opinion based, or too much about typesetting and design in general and not enough about tex; here is an attempt to ask one of these questions in an acceptable way.
I asked a professional mathematician with some serious (but, as far as I know, amateur) interest in typesetting about easy ways to improve the look of the basic amsart math documents that I upload to the arxiv (so, most people will be reading it on a computer monitor; a few studying it more deeply will print it out from their own printer in some fashion), and he gave three points:

*

*\usepackage{microtype}

*\usepackage{mathpazo}

*\linespread{1.2}
From what I've seen browsing around here, the first two points seem uncontroversial (with of course choice of font being a matter of taste); it is the third point I am trying to figure out now.
What I've observed/thought
I have gathered that it is widely accepted that it is good idea to increase the line spread when using Palantino, with the recommended range I've seen being between 1.05 and 1.10; see, in particular Why exactly is \linespread{1.05} appropriate for Palatino?; in a comment toward the bottom of the page, we have Yiannis Lazarides:  "Also I think for mathematical texts using a lot of inline math one should use 1.10"
The situation Yiannis mentions is, of course, exactly my situation; but the advice I've quoted above, and my own quick experimentation, suggests that 1.1 may not be large enough.
Testing \linespread{1.1} on the article I'm currently writing, I get several large increased line spaces because of inline math -- \left(\frac{2\pi i}{r}\right) and \Hom^{(c,d)} (\Hom being a mathoperator) causing problems.
Increasing to \linespread{1.2} seems to remove the extra space between lines from the inline fraction, but still seems to have a very small increase in line space from the second case.
Personally, I find the extra skipped white space very distracting from the text and something to be avoided, but I don't think I've ever noticed it flagged with a warning, so perhaps this isn't the general view among people who worry about these things.
Several 'pure' responses to this problem occur to me:

*

*Increase the linespread enough so that increased white spaces never happen

*Live with increased line separations

*Change the text to avoid inline math happening

*Set it so the increased white space doesn't happen by setting \lineskiplimit to a negative value as is done here
There could be approaches I have not considered, and of course mixes of the approaches above are possible and probably optimal --- for instance, setting \linespread high enough so that the spreading is rare and small, and then either living with the spreading that does happen, or setting lineskiplimit to be negative in addition to the large \linespread.
Attempt at a real question
To try to hammer my confusion into something approaching an appropriate question: what do professional mathematical typesetters / very experienced mathematical latexers think and deal with these questions?  I am not so much interested in any individuals personal preference, but in general accepted guidelines and ways of thinking about this problem.  Are there large differences of opinion in such matters?  If so, are there nice sources out there that 'teach the controversy'?
UPDATE
I realize now what it is really causing the problem is having both a sub- and super- script on the math operators.  Here is a picture of this in the wild , pulled from this arxiv entry, that is using mathpazo and \linespread{1.15}.

Here are some paragraphs from a paper in progress, pulled to illustrate the same problem in something approaching context:
\documentclass[12pt]{article}

\usepackage{amsmath}

\DeclareMathOperator{\Hilb}{Hilb}
\DeclareMathOperator{\Hom}{Hom}
\newcommand{\C}{\mathbb{C}}

\usepackage{mathpazo}

\begin{document}

The case $\Hilb^G_G$ where $v=G$ is the regular representation of $G$ has been studied
in particular depth, and is frequently referred to as GHilb.  Since the ideal sheaf of
a generic point on $[\C^2/G]$ corresponds to the regular representation of $G$, the
Hilbert-Chow morphism $\Hilb^G_G\to\C^2/G$ is an isomorphism away from $0$.  Since
$\Hilb^G_G$ is smooth, this is a resolution of singularities.  In fact, it turns out
that it is the minimal resolution of $\C^2/G$, and has been much studied.

The action of $(\C^*)^2$ on $\C^2$ induces an action on $\Hilb_n(\C^2)$, and since if
$G\subset (\C^*)^2$ then in particular $G$ and $(\C^*)$ commute, we also have a
$(\C^*)^2$ action on $\Hilb_G(\C^2)$.  The fixed points of this action on
$\Hilb_n(\C^2)$ are precisely the monomial ideas.  Since $G\subset (\C^*)^2$, we see
that the monomial ideals are also the fixed points of the action on $\Hilb_n(\C^2)^G$.

The space of $\Hom^{(c,d)}_\C(\mathcal{I},R/\mathcal{I})$ of weight $(c,d)$ vector
space maps corresponds to the cells in $\lambda$ and above $P_\lambda(c,d)$, while the
space $\Hom^{(c,d)}_R (\mathcal{I},R/\mathcal{I})$ of weight $(c,d)$ maps of $R$-
modules corresponds to the bounded regions below $P_\lambda$ and above
$P_\lambda(c,d)$.

\end{document}

And the output:

Even where there aren't horrendous extra spreads, as in the second paragraph, it still seems rather dense to my eyes, but I'm hardly an expert.

A: As a general rule increasing the linespacing is bad. (Of course this assumes that the default spacing has been set appropriate to the current font). If the inline math doesn't fit within the specified line spacing consider changing that before changing the global line spacing.
For the examples given
\documentclass{article}
\usepackage{amsmath}
\DeclareMathOperator{\Hom}{Hom}
\usepackage{mathpazo}
\showoutput
\showboxdepth5
\begin{document}

\noindent
\parbox{.4\textwidth}{
xx xx xx xx xx xx xx\\
%$\left(\frac{2\pi i}{r}\right)$\\
$(\frac{2\pi i}{r})$\\
xx xx xx xx xx xx xx\\
$\Hom^{(c,d)}$\\
xx xx xx xx xx xx xx
}
\parbox{.4\textwidth}{
xx xx xx xx xx xx xx\\
xx xx xx xx xx xx xx\\
xx xx xx xx xx xx xx\\
xx xx xx xx xx xx xx\\
xx xx xx xx xx xx xx}

\end{document}

using Computer Modern they both fit into the exiting space. Using mathpazo  the \Hom example fits but the \left \right construction is too big. Using \left \right in inline math is a bit suspect anyway and if you just use normal size brackets it fits within the specified baseline.

In general you should set your settings for the space that you consider acceptable and then if the math doesn't fit in the space, use display math or a variant notation or something (sometimes you can just use \smash to hide the hight even though it could then overprint a descender on the line above, if you know there is no descender then...) Here for example is your passage unchanged on the original baselineskip set by the font package, but with superscripts made smaller. \lineskip glue is not used, only \baselineskip glue as shown in the log, so confirming that baseline spacing has been preserved.  There are alternatives such as playing with the font dimen parameters that control script positions. But I ended up not using that, so commented out.

\documentclass[12pt]{article}

\usepackage{amsmath}

\DeclareMathOperator{\Hilb}{Hilb}
\DeclareMathOperator{\Hom}{Hom}
\newcommand{\C}{\mathbb{C}}

\showoutput
\showboxdepth4

\usepackage{mathpazo}

 \DeclareMathSizes{12pt}{12}{6.5}{5}
\begin{document}

\sbox0{$aaa$}

\typeout{
13 \the\fontdimen13\textfont2^^J
14 \the\fontdimen14\textfont2^^J
15 \the\fontdimen15\textfont2^^J
16 \the\fontdimen16\textfont2^^J
17 \the\fontdimen17\textfont2^^J
18 \the\fontdimen18\textfont2^^J
19 \the\fontdimen19\textfont2^^J
19 \the\fontdimen8\textfont3^^J
}
 %

%  \fontdimen13\textfont2=\dimexpr(\fontdimen13\textfont2)/10\relax
%  \fontdimen14\textfont2=\dimexpr(\fontdimen14\textfont2)/10\relax
%  \fontdimen15\textfont2=\dimexpr(\fontdimen15\textfont2)/10\relax
%  \fontdimen16\textfont2=\dimexpr(\fontdimen16\textfont2)/10\relax
%  \fontdimen17\textfont2=\dimexpr(\fontdimen17\textfont2)/10\relax
%  \fontdimen18\textfont2=\dimexpr(\fontdimen18\textfont2)/10\relax
%  \fontdimen19\textfont2=\dimexpr(\fontdimen19\textfont2)/10\relax
%  \fontdimen8\textfont3=\dimexpr(\fontdimen8\textfont3)/10\relax

The case $\Hilb^G_G$ where $v=G$ is the regular representation of $G$ has been studied
in particular depth, and is frequently referred to as GHilb.  Since the ideal sheaf of
a generic point on $[\C^2/G]$ corresponds to the regular representation of $G$, the
Hilbert-Chow morphism $\Hilb^G_G\to\C^2/G$ is an isomorphism away from $0$.  Since
$\Hilb^G_G$ is smooth, this is a resolution of singularities.  In fact, it turns out
that it is the minimal resolution of $\C^2/G$, and has been much studied.

The action of $(\C^*)^2$ on $\C^2$ induces an action on $\Hilb_n(\C^2)$, and since if
$G\subset (\C^*)^2$ then in particular $G$ and $(\C^*)$ commute, we also have a
$(\C^*)^2$ action on $\Hilb_G(\C^2)$.  The fixed points of this action on
$\Hilb_n(\C^2)$ are precisely the monomial ideas.  Since $G\subset (\C^*)^2$, we see
that the monomial ideals are also the fixed points of the action on $\Hilb_n(\C^2)^G$.

The space of $\Hom^{(c,d)}_\C(\mathcal{I},R/\mathcal{I})$ of weight $(c,d)$ vector
space maps corresponds to the cells in $\lambda$ and above $P_\lambda(c,d)$, while the
space $\Hom^{(c,d)}_R (\mathcal{I},R/\mathcal{I})$ of weight $(c,d)$ maps of $R$-
modules corresponds to the bounded regions below $P_\lambda$ and above
$P_\lambda(c,d)$.

\end{document}


text:
Q: lodash sorting an array of objects in javascript I have an array of objects response from the server, I am trying to sort by uid in ascending order, while keeping the entire array intact for the data array. Meaning in the data array there are 2 elements. I am trying to look at the uid in one of the arrays it is in of all the elements within the array and determine the order of how the elements should be placed within the data array.
I have tried the following using lodash, but it doesn't seem to work, but I feel I'm getting close and would like some assistance:
// sort by:
console.log(res.results[0].data[0].row[1].uid)

_.forEach(res.results, function(obj) {
  _.forEach(data, function(anotherObj) {
    _.forEach(row, function(row) {
      data.row = _.sortBy(data.row, function(row) {
      return row[1].uid;
      });
    });
  });
});

Here is the array of objects returned from server:
var res = {
  results: [{
    columns: ['large', 'medium', 'small'],
    data: [{
      row: [{
        sid: 13,
        tid: 427
      },
        {
          uid: 69,
          vid: 450,
          wid: 65
        },
        null],
      multirow: {
        nodule: [{
          xid: '427',
          properties: {
            yid: 13,
            zid: 427
          }
        },
          {
            aid: '450',
            properties: {
              uid: 69,
              bid: 450,
              cid: 65
            }
          }]
      }
    },
      {
        row: [{
          sid: 13,
          tid: 427
        },
          {
            vid: 432,
            uid: 65,
            wid: 61
          },
          null],
        multirow: {
          nodule: [{
            xid: '427',
            properties: {
              yid: 13,
              zid: 427
            }
          },
            {
              aid: '432',
              properties: {
                bid: 432,
                uid: 65,
                cid: 61
              }
            }]
        }
      }]
  }],
  errors: []
};

A: You don't need that many loops:
_.forEach(res.results, function(result) {
  result.data = _.sortBy(result.data, function(datum) {
    return datum.row[1].uid;
  });
});

You only need to iterate over the results, each of which might have a data array that you are going to sort. The sortBy callback then takes each of the elements of that array and is supposed to return the value to compare.


text:
Q: assigning dtype to a np.array changes the expected shape When I assign a dtype to an np.array it changes the shape (it has a shape that I don't want).
But if I don't assign the dtype it has the expected shape.
How can I assign dtype without changing the shape of my np.array?
I would like 'arr_d' to be the same (with same shape) as 'arr'.
>>> blender = [(1, 1, 2.0), (-1, 0, -101), (1, 1, 2.0), (-1, 0, -101)]
>>> arr = np.array(blender)
>>> arr
array([[   1.,    0.,    2.],
       [  -1.,    0., -101.],
       [   1.,    1.,    2.],
       [  -1.,    1., -101.]])
>>> arr.shape
(4, 3)
>>> dtype = [('sum', 'int'), ('cc', 'int'), ('xprob', 'int')]
>>> arr_d = np.array(blender, dtype=dtype)
>>> array([( 1, 1,    2), (-1, 0, -101), ( 1, 1,    2), (-1, 0, -101)],
      dtype=[('sum', '<i8'), ('cc', '<i8'), ('xprob', '<i8')])
>>> arr_d.shape
(4,)


text:
Q: Swift protocol interacting with objective-c ViewController Class I am trying to trigger a function from my view controller class in a swift class using a protocol.
@objc protocol KestrelDeviceConnectDelegate: AnyObject {
    func readingIsOver()
}

class KestrelDeviceConnect: NSObject {

    weak var delegate: KestrelDeviceConnectDelegate?

    func timerAction() {
        timerCounter += 1
        if(timerCounter >= 20){
            progressHUD.hide()
            timerCounter = 0
            timer.invalidate()
            self.delegate?.readingIsOver()

            //present kestrel alert
        }
    }
}

in the view controller class viewdidload
KestrelDeviceConnect *bluetoothManager = [[KestrelDeviceConnect alloc]init];
bluetoothManager.delegate = self;

function I want to be called from my swift class
- (void)readingIsOver {
    [[self logConditionsButton] setHidden:NO];
}

A: You need to hold a strong reference by making bluetoothManager an instance variable
KestrelDeviceConnect *bluetoothManager;

bluetoothManager = [[KestrelDeviceConnect alloc]init];


text:
Q: About DI and SRP I'm writing the following class
public class UserApplication
{
    private IUserRepository UserRepository { get; set; }

    private IUserEmailerService UserEmailerService { get; set; }

    public UserApplication(IUserRepository userRepository, IUserEmailerService userEmailerService)
    {
        this.UserRepository = userRepository;
        this.UserEmailerService = userEmailerService;
    }

    public bool Authenticate(string login, string pass)
    {
        // Here I use UserRepository Dependency
    }

    public bool ResetPassword(string login, string email)
    {
        // Here I only use both Dependecies
    }

    public string GetRemeberText(string login, string email)
    {
        // Here I only use UserRepository Dependency
    }
}

I'm using Unity for manage my instances so I realised that I only use both dependencies on only one method so when I ask the container to give a instance for this class both dependencies are inject into this class but I don't need the two instances for all methods so in Authenticate user I only need the repository.
So am I wrong doing this? Is there another way that only have the dependecy I use for all cases in this class?
I think of using the Command Pattern to that so I class 3 classes with one method and only the dependencies I need inside that like this:
public class AuthenticateUserCommand : ICommand
{
    private IUserRepository UserRepository { get; set; }

    public string Login { get; set; }

    public string Password { get; set; }

    public void Execute()
    {
        // executes the steps to do that
    }
}

public class ResetUserPasswordCommand : ICommand
{
    private IUserRepository UserRepository { get; set; }

    private IUserEmailerService UserEmailerService { get; set; }

    public string Login { get; set; }

    public string Email { get; set; }

    public void Execute()
    {
        // executes the steps to do that
    }
}

A: Another approach is to create a role-specific interface for each behavior. So you'd have IUserAuthenticationService, IUserPasswordResetService, and IUserRememberPasswordService. The interfaces could be implemented by a single class, such as UserApplication or they could be implemented with individual classes to maintain SRP. The command pattern you describe has a similar advantage for SRP. One issue with the command pattern is that those dependencies still have to be provided by something. If the dependencies are provided by the controller, then you still have to get the dependencies to the controller in the first place and you are left with a similar problem as your first example.
The trade-off in the role-specific interface case as well as the command pattern is a loss of cohesion. The cost of this is certainly a matter of preference and perspective as is the degree to which you want to enforce SRP. On one hand, the cohesion provided by having a single class handle authentication related behavior can be beneficial. On the other hand, it can lead to a dependency misalignment as you describe.

A: I usually implement a form of the command pattern as you are considering doing.  However, it also has elements of what eulerfx has mentioned.  I just call them tasks.  For example:
public interface ITask
{
    void Execute();
}

public interface IAuthenticateTask : ITask {}

public interface IResetPasswordTask : ITask {}

I then implement these and have the required dependencies injected.  So I have role specific interfaces and implementations.
I would not go with the service locator as you stated in your answer bit.
When I do have a situation where I need access to various tasks as I do in the controller of an ASP.NET MVC project I use property injection instead of constructor injection.  I just have my DI container (I use castle) require certain injections based on a convention at runtime.
In this way I can still easily test the controller since I do not need to provide all the constructor injected objects but only those properties that I need for the test, with the added benefit that certain injected properties will still be required just as would be provided by constructor injection.
update:
There are a couple of options available using this approach.  The main interface one would be interested in for a task is the role-specific one.  The inherited interface(s) such as ITask would be only for convenience in simple cases.  It can be extended also with generics:
public interface ITask<TInput>
{
   void Execute(TInput input);
}

public interface IOutputTask<TOutput>
{
   TOutput Execute();
}

public interface IOutputTask<TOutput, TInput>
{
   TOutput Execute(TInput input);
}

Once again these are for convenience:
public interface IAuthenticateTask : IOutputTask<bool> {}

// or

public interface IAuthenticateTask : IOutputTask<AuthenticationResult> {}

You could work just on the role level:
public interface IAuthenticateTask
{
    AuthenticationResult Execute(string username, string password);
}

One need only rely on the role-specific interface for dependencies.

A:
So am I wrong doing this?

No. 2 dependencies are not the end of the world, they don't make the constructor bloated or unreadable.
Previously given answers would be good fits for cases when you have 3-4+ dependencies though.
You could also occasionally pass a particular dependency as a parameter to a method if it is only used in that method. In this sense, you might want to give Unity's method call injection a try although I'm not sure it was precisely intended for that purpose.


text:
Q: Connecting variable string for WHERE clause How do I connect the variable string for where clause in Firebird?
I have two variables type of SMALLINT. These variables are incremented after one iteration in while loop.
From these variables I create DATE for where-> between selection in SQL, something like this (this is my ineffectual try) :
 yearmin=extract (year from DATAMIN);
 yearmax=extract (year from DATAMAX);
 monthmin=extract (month from DATAMIN);
 monthmax=extract (month from DATAMAX);
 aktyear=rokmin;
 actmonth=monthmin;

 while  (actyear<=yearmax and actmonth<=monthmax) DO
 BEGIN
SELECT
[...]
 WHERE (g.GDATAP BETWEEN (:actyear || :actmonth || 01) AND ( :actyear || :actmonth || 30))
[...]

   INTO :Zaw,:Sum;
 actyear=actyear+1;
 actmonth=actmonth+1;
 SUSPEND;
 end

A: The || is string concatenator operator but in the expression g.GDATAP BETWEEN (:actyear || :actmonth || 01) you don't have strings but ints. Firebird won't do type conversion for you. So to make it work you have to cast to (var)char, something like
cast(:actyear as varchar(4)) || cast(:actmonth as varchar(2)) || '01'

You might have to add date separators too, ie
cast(:actyear as varchar(4)) || '-' || cast(:actmonth as varchar(2)) || '-01'

I don't remember the formats Firebird accepts off the top of my head...
It looks like you construct these dates in the loop, so it might be better to initialize start date before the loop and then increment it by required amount using DATEADD() function.


text:
Q: Example of a function $f:\mathbb{R}^2\rightarrow\mathbb{R}$ such that $\partial_{u}f \neq \nabla f.\vec{u}$ Is there an example of a function $f:\mathbb{R}^2\rightarrow\mathbb{R}$ such that
$$\partial_{u}f \neq \nabla f\cdot u$$
for all unit vectors $u$?
I'm trying to find an example. I already know that it can not be a differentiable function, otherwise the equality always holds. Any tips?

A: As in the comments: an example is
$$ f(x,y) = \begin{cases} x & x=y \\ 0 & \text{otherwise} \end{cases} $$
This $f$ is continuous at $0$, and Gateaux differentiable at $0$. Notice $f(x,0) = f(0,y) = 0$ for all $x,y$, so $f_x(0)=f_y(0) = 0$. Yet, for $u\propto (1,1)$, $\partial_u f(0) \neq 0$.


text:
Q: Unable to execute my script when converting it to exe I created a script to extract data from a pdf using tabula-py and PyPDF2. When I run my program through Jupyter-notebook and from the cmd, it works perfectly. After converting it to executable with pyinstaller, I get this error:
Error: Unable to access jarfile
E:\Users\paulhong\AppData\Local\Temp\_MEI175522\tabula\tabula-1.0.2-jar-with-dependencies.jar
Error:
Traceback (most recent call last):
File "test.py", line 115, in <module>

File "test.py", line 32, in extractDataDik
tempDf = tabula.read_pdf(file, area = (72, 252, 115.2, 352.8), guess=False, pages='1')
File "site-packages\tabula\wrapper.py", line 108, in read_pdf
File "subprocess.py", line 395, in check_output
File "subprocess.py", line 487, in run
subprocess.CalledProcessError: Command '['java', '-Dfile.encoding=UTF8', '-jar',
'E:\\Users\\paulhong\\AppData\\Local\\Temp\\_MEI175522\\tabula\\tabula-1.0.2-jar-with-dependencies.jar', '--pages', '1', '--area',
'72,252,115.2,352.8', 'E:\\Users\\paulhong\\Desktop\\Purchase Order
2\\SKM_C45819060508450 (003).pdf']' returned non-zero exit status 1. [47140] Failed to execute script test

I also couldn't find the folder _MEI175522 on the specified path.
My python version is 3.7.1
Java version is 1.8
pyinstaller version is 3.4
Tabula-py is the latest version
How can I fix this issue?

A: I had a similar problem, and I was able to solve it using the solution at this link: Unable to access jarfile 'tabula-1.0.2-jar-with-dependencies.jar'
I built my app within a virtual environment, so I added a tabula folder with the tabula-1.0.2-jar-with-dependencies.jar file to my site-packages folder. Running the command pyinstaller --add-data apps\Lib\site-packages\tabula\tabula-1.0.2-jar-with-dependencies.jar;tabula --onefile Table_OCR.py builds the executable correctly for me.

A: It looks like the tabula module hasn't been copied to the dist folder of your executable, in my experience this is a common problem with pyinstaller it can often miss packages in the python directory.
Go to the dist folder and check if the tabula folder is there, if it's not then you'll need to copy it over.
Go to your python directory, it should be somewhere like this:
C:\Users\<user_name>\AppData\Local\Programs\Python\Python37-32\Lib\site-packages
Copy over any packages from here that need to be in the dist folder


text:
Q: How to display selected text, not selected value, of a dropdownlist in a displaytemplate? So I have this piece of code in my displaytemplate:
@Html.DropDownListFor(blah => blah.InputtedData, ddv)

and I get an actual dropdownlist. I've tried this piece of code:
@Html.DisplayFor(blah => blah.InputtedData, ddv)

And I get 1 (the number one), the selectedvalue. But I want to display Yes, the selectedtext. So how do I display the selectedtext in a dropdownlist in a displaytemplate and not the selectedvalue?
Per request:
namespace TESTMVC.ViewModels
{
    public class CtrlInputDataModel
    {
        public CtrlTypeModel RowCtrl { get; set; }
        public long InputtedDataID { get; set; }
        public string InputtedData { get; set; }
        public DateTime InputtedDate { get; set; }

        public CtrlInputDataModel()
        {

        }

        public CtrlInputDataModel (CtrlTypeModel newRowCtrl, long newInputtedDataID, string newInputtedData, DateTime newInputtedDate)
        {
            RowCtrl = newRowCtrl;
            InputtedDataID = newInputtedDataID;
            InputtedData = newInputtedData;
            InputtedDate = newInputtedDate;
        }
    }
}

The ViewModel that ddv is based on:
namespace TESTMVC.ViewModels
{
    public class DefaultValueModel
    {
        public string Label { get; set; }
        public string Value { get; set; }

        public DefaultValueModel()
        {

        }

        public DefaultValueModel(string newLabel, string newValue)
        {
            Label = newLabel;
            Value = newValue;
        }
    }
}

A: You cannot do it with the built in Html.DisplayFor.  However you can create a custom displaytemplate e.g. /Views/Shared/DisplayTemplates/DropdownListTest.cshtml where you manually select the text from the dropdownlist values based on your property:
@model string
@((IEnumerable<SelectListItem>)ViewData["ddv"])
    .Where(s => Model == s.Value)
    .Select(s => s.Text).SingleOrDefault()

Then you can use it with the following (little bit complex) syntax:
@Html.DisplayFor(blah => blah.InputtedData,
     "DropdownListTest", //template name
     new { ddv = ddv } // aditional view data: the property name needs to be ddv
})

But if don't plan to reuse this functionality just inline your the logic and use this instead of the Html.DisplayFor:
@ddv.Where(s => s.Value == Model.InputtedData)
    .Select(s => s.Text).SingleOrDefault()


text:
Q: Why am I getting a Shader Compiler Error #143, #160 and #216 when comiling a vertex Shader using OpenGL? I just started to learn about Grpahics in C++, and about shaders and sprites. I wrote a small vertex shader, and a fragment shader.
Vertex Shader:
#version 130

in vec2 vertexPosition;

void main() {
    gl_Position.xy = vertexPosition;
    gl_Position.z = 0.0;
    gl_Position.w = 1.0;
}

Fragment Shader:
#version 130

out vec3 color;

void main() {
    color = vec3(0.94, 0.37, 0.36);
}

While Compiling, I am getting the following Error Messages:
Fragment shader failed to compile with the following errors:
ERROR: 0:6: error(#143) Undeclared identifier: gl_Position
ERROR: 0:6: error(#216) Vector field selection out of range "xy"
ERROR: 0:6: error(#160) Cannot convert from: "default in highp 2-component vector of vec2" to: "float"
ERROR: 0:7: error(#216) Vector field selection out of range "z"
ERROR: 0:8: error(#216) Vector field selection out of range "w"
ERROR: error(#273) 5 compilation errors.  No code generated

How do I fix these errors?
PS: I am using an AMD A10 8700P Radeon R6 processor builtin graphics.
While reading other questions I noticed that using AMD Graphics Card is the root cause of several problems, so if that is the problem in my case, then how do I fix that?
I am using a seperate class for all GLSL Manipulations.
GLSLProgram.h:
#pragma once

#include <GL/glew.h>

#include <string>

class GLSLProgram
{
public:
    GLSLProgram();
    ~GLSLProgram();

    void compileShaders(const std::string &vertexShaderFilePath, const std::string &fragmentShaderFilePath);

    void linkShaders();

    void addAttribute(const std::string& attributeName);

    void use();
    void unuse();
private:
    int _numAttributes;

    void compileShader(const std::string &filePath, GLuint id);

    GLuint _programID;

    GLuint _vertexShaderID;
    GLuint _fragmentShaderID;
};

GLSLProgram.cpp:
#include "GLSLProgram.h"
#include "Errors.h"

#include <fstream>
#include <vector>

GLSLProgram::GLSLProgram() :
_numAttributes(0), _programID(0), _vertexShaderID(0), _fragmentShaderID(0)
{
}

GLSLProgram::~GLSLProgram() {
}

void GLSLProgram::compileShaders(const std::string &vertexShaderFilePath, const std::string &fragmentShaderFilePath) {
    _vertexShaderID = glCreateShader(GL_VERTEX_SHADER);
    if (!_vertexShaderID) {
        fatalError("Vertex Shader failed to be created!");
    }

    _fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
    if (!_fragmentShaderID) {
        fatalError("Fragment Shader failed to be created!");
    }

    compileShader(vertexShaderFilePath, _vertexShaderID);
    compileShader(vertexShaderFilePath, _fragmentShaderID);
}

void GLSLProgram::linkShaders() {
    // Vertex and fragment shaders are successfully compiled.
    // Now time to link them together into a program.
    // Get a program object.
    _programID = glCreateProgram();

    // Attach our shaders to our program
    glAttachShader(_programID, _vertexShaderID);
    glAttachShader(_programID, _fragmentShaderID);

    // Link our program
    glLinkProgram(_programID);

    // Note the different functions here: glGetProgram* instead of glGetShader*.
    GLint isLinked = 0;
    glGetProgramiv(_programID, GL_LINK_STATUS, (int *)&isLinked);
    if (isLinked == GL_FALSE)
    {
        GLint maxLength = 0;
        glGetProgramiv(_programID, GL_INFO_LOG_LENGTH, &maxLength);

        // The maxLength includes the NULL character
        std::vector<char> errorLog(maxLength);
        glGetProgramInfoLog(_programID, maxLength, &maxLength, &errorLog[0]);

        // We don't need the program anymore.
        glDeleteProgram(_programID);
        // Don't leak shaders either.
        glDeleteShader(_vertexShaderID);
        glDeleteShader(_fragmentShaderID);

        std::printf("%s\n", &(errorLog[0]));
        fatalError("Shaders failed to link!");
    }

    // Always detach shaders after a successful link.
    glDetachShader(_programID, _vertexShaderID);
    glDetachShader(_programID, _fragmentShaderID);
    glDeleteShader(_vertexShaderID);
    glDeleteShader(_fragmentShaderID);
}

void GLSLProgram::addAttribute(const std::string &attributeName) {
    glBindAttribLocation(_programID, _numAttributes++, attributeName.c_str());

}

void GLSLProgram::use() {
    glUseProgram(_programID);
    for(int i = 0; i < _numAttributes; ++i) {
        glEnableVertexAttribArray(i);
    }
}

void GLSLProgram::unuse() {
    glUseProgram(0);
    for(int i = 0; i < _numAttributes; ++i) {
        glDisableVertexAttribArray(i);
    }
}

void GLSLProgram::compileShader(const std::string &filePath, GLuint id)
{
    std::ifstream shaderFile(filePath);
    if (shaderFile.fail())
    {
        perror(filePath.c_str());
        fatalError("Failed to open " + filePath);
    }

    std::string fileContents = "";
    std::string line;

    while (std::getline(shaderFile, line))
    {
        fileContents += line + "\n";
    }

    shaderFile.close();

    const char *contentsPtr = fileContents.c_str();
    glShaderSource(id, 1, &contentsPtr, nullptr);

    glCompileShader(id);

    GLint success = 0;
    glGetShaderiv(id, GL_COMPILE_STATUS, &success);

    if (success == GL_FALSE)
    {
        GLint maxLength = 0;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength);

        //The maxLength includes the NULL character
        std::vector<char> errorLog(maxLength);
        glGetShaderInfoLog(id, maxLength, &maxLength, &errorLog[0]);

        glDeleteShader(id);

        std::printf("%s\n", &(errorLog[0]));
        fatalError("Shader " + filePath + " Failed to compile");
    }
}

Fatal Error just prints the string supplied and exits.

A: gl_Position is only valid in vertex shaders.
You compile the vertex shader twice, but you don't compile the fragment shader in compileShaders:
It has to be
compileShader(vertexShaderFilePath, _vertexShaderID);
compileShader(fragmentShaderFilePath, _fragmentShaderID);

instead of
compileShader(vertexShaderFilePath, _vertexShaderID);
compileShader(vertexShaderFilePath, _fragmentShaderID);


text:
Q: Visio removing UML model info when saving file I had created a .vsd file in Visio Premium 2010, saved it, emailed a copy to my colleague. Couple of days later, I reopen it, only to find that for some reason, it no longer treats the  the document as a UML template-based document.
As a result of this, I cannot do any edits on the file. Any ideas as to why the UML info gets discarded?
Is there any workaround so that I can edit the file? How can I make Visio think into believing the file is based on the UML template?
Note:

*

*Copy + paste from the existing file to a new one is not practical because there are 18+ tabs and Visio seems to discard all names and other meta-data information on pasting.

*I've created a new diagram using the "Create New From Existing.." dialog, doesn't help, it's still the same issue.

A: As to how to repair the association and re-link objects to the UML template I am not certain and sadly do not have access to Visio at the moment to try anything out, but if the line-art is intact but simply not editable you should at least be able to recover the artwork, if not the references.
You may be able to select the entire drawing, right click it, and under the Shapes menu you should see an option to Ungroup.  This should at least break the file down into lines and shapes that are editable.
I would recommend doing this on a copy of your original file, keeping the original safe in case it can be recovered.
When using a template Ungroup-ing should usually give a warning that it will break references to the template.
Does anyone else have access to the file, could they have modified it in any way?  Visio does have an option to remove hidden data and if someone went into the document, hit that button and selected the "Remove these items..." it looks like it also breaks the links to template and stencil files.  I've shown the dialog from Visio 2007 below, I would expect similar in 2010.

A: I would strongly recommend against the ungrouping technique suggested above. That's almost always a bad idea for shapes from Visio stencils. You're likely to lose all of most of the crucial data in the shapes.
If you click File>Info, what is listed to the right of "Template" on the right side of the screen? Does it say "UML Model Diagram", something else or nothing?
What happens if you create a simple one page UML diagram and repeat the same steps, i.e., close it than open it again later?


text:
Q: Trivial order by double type: performance crash Characters:

*

*id BIGINT

*geo_point POINT (PostGIS)

*stroke_when TIMESTAMPTZ (indexed!)

*stroke_when_second DOUBLE PRECISION

PostgeSQL 9.1, PostGIS 2.0.
1. Query:
SELECT ST_AsText(geo_point)
FROM lightnings
ORDER BY stroke_when DESC, stroke_when_second DESC
LIMIT 1

Total runtime: 31100.911 ms !
EXPLAIN (ANALYZE on, VERBOSE off, COSTS on, BUFFERS on):
Limit  (cost=169529.67..169529.67 rows=1 width=144) (actual time=31100.869..31100.869 rows=1 loops=1)
  Buffers: shared hit=3343 read=120342
  ->  Sort  (cost=169529.67..176079.48 rows=2619924 width=144) (actual time=31100.865..31100.865 rows=1 loops=1)
        Sort Key: stroke_when, stroke_when_second
        Sort Method: top-N heapsort  Memory: 17kB
        Buffers: shared hit=3343 read=120342
        ->  Seq Scan on lightnings  (cost=0.00..156430.05 rows=2619924 width=144) (actual time=1.589..29983.410 rows=2619924 loops=1)
              Buffers: shared hit=3339 read=120342

2. Selecting another field:
SELECT id
FROM lightnings
ORDER BY stroke_when DESC, stroke_when_second DESC
LIMIT 1

Total runtime: 2144.057 ms.
EXPLAIN (ANALYZE on, VERBOSE off, COSTS on, BUFFERS on):
Limit  (cost=162979.86..162979.86 rows=1 width=24) (actual time=2144.013..2144.014 rows=1 loops=1)
  Buffers: shared hit=3513 read=120172
  ->  Sort  (cost=162979.86..169529.67 rows=2619924 width=24) (actual time=2144.011..2144.011 rows=1 loops=1)
        Sort Key: stroke_when, stroke_when_second
        Sort Method: top-N heapsort  Memory: 17kB
        Buffers: shared hit=3513 read=120172
        ->  Seq Scan on lightnings  (cost=0.00..149880.24 rows=2619924 width=24) (actual time=0.056..1464.904 rows=2619924 loops=1)
              Buffers: shared hit=3509 read=120172

3. Correct optimization:
SELECT id
FROM lightnings
ORDER BY stroke_when DESC
LIMIT 1

Total runtime: 0.044 ms
EXPLAIN (ANALYZE on, VERBOSE off, COSTS on, BUFFERS on):
Limit  (cost=0.00..3.52 rows=1 width=16) (actual time=0.020..0.020 rows=1 loops=1)
  Buffers: shared hit=5
  ->  Index Scan Backward using lightnings_idx on lightnings  (cost=0.00..9233232.80 rows=2619924 width=16) (actual time=0.018..0.018 rows=1 loops=1)
        Buffers: shared hit=5

As you can see there are two bad and very different collisions though the query is a quite primitive when the SQL optimizer uses index:

*

*Even if the optimizer doesnt use the index, why using As_Text(geo_point) instead of id takes so much more time? There is only one row in result!

*Impossibility of using first order index when an unindexed field is presented in ORDER BY. Mention that as on practice only few rows on each second are presented in DB.

Of course above is a simplified query, extracted from a more complex construction. Usually I select rows by date range, applying complicated filters.

A: PostgreSQL can't use your index to produce values in the desired order for the first two queries. When two or more rows have identical store_when identical they are returned from the index scan in arbitrary order. To decide the correct order for the rows would require a secondary sorting pass. Because PostgreSQL executor doesn't have a facility to perform that secondary sort it falls back to a full sort approach.
If you regularly need to query the table with that order then replace your current index with a composite index that includes both columns.
You can transform your current query into a form that explicitly specifies the secondary sort on only the largest value of store_when:
 SELECT ST_AsText(geo_point) FROM lightnings
 WHERE store_when = (SELECT max(store_when) FROM lightnings)
 ORDER BY stroke_when_second DESC LIMIT 1

A: First step could be: create a composite index on {stroke_when, stroke_when_second}


text:
Q: Isotope issue - When resizing browser images overlap I´m trying to get Isotope working correctly on my website, except some images overlap when resizing the screen.
When searching I found the following $(window).load(function(){ ..... });.
Except I have no idea how to make it work on the following page:
http://maxvanderpluijm.nl/bbtest2/zorgappartementen/
Could somebody help me please, I'm kinda lost over here :(
Thanks in advance!!!
Greets,
Max


text:
Q: Fatal error: Call to a member function escape() on a non-object in I'm trying to update my queries, but I stumble upon the same error again and again...
Fatal error: Call to a member function escape() on a non-object in ...
This is my function:
    //update activity
    public function updateActivity($db, $id) {
    $sql    = "UPDATE tblLeidingAgenda SET
    datum       = '".$db->escape($this->datum)."',
    uur         = '".$db->escape($this->uur)."',
    titel       = '".$db->escape($this->titel)."',
    uitleg      = '".$db->escape($this->uitleg)."',
    link        = '".$db->escape($this->link)."',
    aanwezig    = '".$db->escape($this->aanwezig)."',
    auteur      = '".$db->escape($this->auteur)."'
    WHERE id    = '".$id."'";
    return $db->insert($sql);
}

And this is my code:
if (empty($_POST['up_datum']) || empty($_POST['up_uur']) || empty($_POST['up_titel']) || empty($_POST['up_uitleg'])) {
        $error = 'no input';
    } else {
        $datecorrect=date('Y-m-d',strtotime($_POST['up_datum']));

        $agenda = new Leidingsactiviteit();
        $agenda->datum          = $datecorrect;
        $agenda->uur            = $_POST['up_uur'];
        $agenda->titel          = $_POST['up_titel'];
        $agenda->uitleg         = $_POST['up_uitleg'];
        $agenda->auteur         = $_SESSION['user']['naam'];

        if ($agenda->updateActivity($_DB,$_POST['id'])) {
            $feedback = 'ok';
            $bericht = 'test';
            mail('me@gmail.com', 'Update: '.$agenda->titel, $bericht);
        }
        else {
            $feedback = 'not ok';
         }
    }

EDIT $_DB declared...
 define('MYSQL_HOST',  '***');
 define('MYSQL_DB',    '***');
 define('MYSQL_USER',  '***');
 define('MYSQL_PASSW', '**');

 // Initialize (global vars)
 $_DB = new DBConnection(MYSQL_HOST, MYSQL_DB, MYSQL_USER, MYSQL_PASSW);

A: Where is the variable $_DB declared?  From what you have posted, it never gets declared so I don't know what is inside the object (if it is even an object by that point to begin with).
Try var_dump($_DB); before the if ($agenda->updateActivity($_DB,$_POST['id'])) and post the results of that if you don't figure out your problem.


text:
Q: Filtering the page with xml I want to filter websites using xml depending on whether the values are contained in it or not. I have such a script and I don't know why, but it filters well once, not, can anyone advise me something?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note SYSTEM "Note.dtd">
<filter>
<min_szerokosc>111</min_szerokosc>
<min_wysokosc>111</min_wysokosc>
<min_glebokosc>111</min_glebokosc>
<max_szerokosc>1111</max_szerokosc>
<max_wysokosc>1111</max_wysokosc>
<max_glebokosc>1111</max_glebokosc>
<typ>power&free</typ>
<myjnia_automat>1</myjnia_automat>
<kabina_automat>1</kabina_automat>
<transport_gorny>1</transport_gorny>
<extra></extra>
</filter>

<?php

$cat=new Kategoria;

$kat=array(205,233,234,206,204,203,202);
//$kat=array(206);

foreach($_POST as $k => $v){
    if($v=="on"){
    $_POST[$k]=1;
    }
}

foreach($kat as $a => $b){

$result=$cat->getKategoria($b);

//print_r($_POST);

foreach($result as $res => $val){
    if(preg_match("/tab_[0-9]{1,2}_filter/i",$res)>0){
    //print_r($val);
    $xml = simplexml_load_string($val);

        if($xml){

        if($_POST['typ'] == $xml->typ){

        if($_POST['min_szerokosc'] <= $xml->min_szerokosc &&
        $_POST['min_wysokosc'] <= $xml->min_wysokosc   &&
        $_POST['min_glebokosc'] <= $xml->min_glebokosc &&
        $_POST['max_szerokosc'] <= $xml->max_szerokosc &&
        $_POST['max_wysokosc'] <= $xml->max_wysokosc   &&
        $_POST['max_glebokosc'] <= $xml->max_glebokosc &&
        $_POST['myjnia_automat'] == $xml->myjnia_automat ||
        $_POST['myjnia_reczna'] == $xml->myjnia_reczna ||
        $_POST['wanna'] == $xml->wanna &&
        $_POST['kabina_automat'] == $xml->kabina_automat ||
        $_POST['kabina_jedno_stanowiskowa'] == $xml->kabina_jedno_stanowiskowa ||
        $_POST['kabina_dwu_stanowiskowa'] == $xml->kabina_dwu_stanowiskowa &&
        $_POST['transport_gorny'] == $xml->transport_gorny ||
        $_POST['transport_dolny'] == $xml->transport_dolny){

        print "true:{$b}:{$res} \n";
       }else{
       //print "false\n";
       //print("{$_POST['typ']} == $xml->typ");
                        }
                    }
                }
    //print($res."\n");
        }
    }
}

?>

How do I compose an if statement to be able to refer to each of the values of the xml file ?
How can I filter this simple xml?

A: I found a solution to my problem - and these are weights for the searched values - thanks to this I can precisely filter the list from the xml file
$resx=0;

    if($_POST['typ'] == $xml->typ){
    $resx=$resx+100;
    }else{
    $resx=$resx-100;
    }

    if($_POST['min_szerokosc'] <= $xml->max_szerokosc && $_POST['min_wysokosc'] <= $xml->max_wysokosc && $_POST['min_glebokosc'] <= $xml->max_glebokosc ){
    $resx=$resx+600;
    }else{
    $resx=$resx-600;
    }

    if($_POST['max_szerokosc'] <= $xml->max_szerokosc && $_POST['max_wysokosc'] <= $xml->max_wysokosc && $_POST['max_glebokosc'] <= $xml->max_glebokosc ){
    $resx=$resx+5000;
    }else{
    $resx=$resx-5000;
    }

    if($_POST['myjnia_automat'] == $xml->myjnia_automat || $_POST['myjnia_reczna'] == $xml->myjnia_reczna || $_POST['wanna'] == $xml->wanna){
    $resx=$resx+40000;
    }else{
    $resx=$resx-40000;
    }

    if($_POST['kabina_automat'] == $xml->kabina_automat || $_POST['kabina_jedno_stanowiskowa'] == $xml->kabina_jedno_stanowiskowa || $_POST['kabina_dwu_stanowiskowa'] == $xml->kabina_dwu_stanowiskowa){
    $resx=$resx+30000;
    }else{
    $resx=$resx-30000;
    }

    if($_POST['transport_gorny'] == $xml->transport_gorny || $_POST['transport_dolny'] == $xml->transport_dolny){
    $resx=$resx+200;
    }else{
    $resx=$resx-200;
    }

    //print $resx."+";

    if($resx >= 75900 || $_POST['czysc']==1){
//some code;
}


text:
Q: Creating a list of pairs using comprehensions I'm trying to create a list of pairs, p, from 2 ranges,
r1 = [i for i in range(0, 10, 2)]
r2 = [j for j in range(10, 0,-2)]

Such that,
p[0] = [r1[0], r2[1]]
p[1] = [r1[1], r2[1]]
.....
p[-1] = [r1[-1], r2[-1]]

Naively I thought,
p = [[i, j] for i in range(0, 10, 2) for j in range(10, 0, -2)]

would do this but I soon saw the error of my ways.
I also tried,
p = [r1[:], r2[:]]

but yeah that didn't work either.
Then I tried,
p = []
for i, j  in zip(r1, r2):
    p.append([i, j])

Which does work!
But that got me wondering, is there a Pythonic way of doing this using list comprehensions?
The 2 ranges will always be the same length in implementation but not always spanning the same domain.
EDIT: to be clear I was wondering if it was possible to generate the ranges r1 & r2 within the comprehension as well as the comprehension giving the pairing.

A: Converting to list comprehension for the one that works as mentioned in  code you posted above, may be you can try:
[[i,j] for i, j  in zip(r1, r2)]

Or to add range in list comprehension:
[[i,j] for i, j  in zip(range(0, 10, 2), range(10, 0, -2))]


text:
Q: Dynamic Index Creation - SQL Server Ok, so I work for a company who sells a web product which has a MS SQL Server back end (can be any version, we've just changed our requirements to 2008+ now that 05 is out of extended support). All databases are owned by the company who purchases the product but we have VPN access and have a tech support department to deal with any issues. One part of my role is to act as 3rd line support for SQL issues.
When performance is a concern one of the usual checks is unused/missing indexes. We've got the usual standard indexes but depending on which modules or how a company utilises the system then it will require different indexes (there's an accounting module and a document management module amongst others). With hundreds of customers it's not possible to remote onto each on a regular basis in order to carry out optimisation work. I'm wondering if anybody else in my position has considered a scheduled task that may be able to drop and create indexes when needed?
I've got concerns (obviously), any changes that this procedure makes would also be stored in a table with full details of the change and a time stamp. I'd need this to be bullet proof, can't be sending something out into the wild if it may cause issues. I'm thinking an overnight or (probably) weekly task.
Dropping Indexes:

*

*Would require the server to be up for a minimum amount of time to ensure all relevant server statistics are up to date (say 2 weeks or 1 month).

*Only drop unused indexes for tables that are being actively used (indexes on unused parts of the system aren't a concern).

*Log it.

*This won't highlight duplicate indexes (that will have to be manual), just the quick wins (unused indexes with writes).

Creating Indexes

*

*Only look for indexes with a value above a certain threshold.

*Would have to check whether any similar indexes could be modified to cover the requirement. This could be on a ranking (check all indexed fields are the same and then score the included fields to see if additional would be needed).

*Limit to a maximum number of indexes to be created (say 5 per week) to ensure it doesn't get carried away and create a bunch at once). This should help only focus on the most important indexes.

*Log it.

This would need to be dynamic as we've got customers on different versions of the system with different usage patterns.
Just to clarify: I'm not expecting anybody to code for this, it's more a question relating to the feasibility and concerns for a task like this.
Edit: I've put a bounty on this to gather some further opinions and to get feedback from anybody who may have tried this before. I'll award it to the answer with the most upvotes by the time the bounty duration ends.

A: I can't recommend what you're contemplating, but you might be able to simplify your life by gathering the inputs to your contemplated program and making them available to clients and the support team.
If the problem were as simple as you suppose, surely the server itself or the tuning advisor would have solved it by now.  You're making at least one unwarranted assumption,

require the server to be up for a minimum amount of time to ensure all relevant server statistics are up to date.

Table statistics are only as good as the last time the were updated after a significant change.  Uptime won't guarantee anything about truncate table or a bulk insert.

This won't highlight duplicate indexes

But that's something you can do in a single query using the system tables.  (It would be disappointing if the tuning gadget didn't help with those.)   You could similarly look for overlapping indexes, such as for columns {a,b} and {a}; the second won't be useful unless {b} is selective and there are queries that don't mention {b}.
To look for new indexes, I would be tempted to try to instrument query use frequency and automate the analysis of query plan output.  If you can identify frequently used, long-running queries and map their physical operations (table scan, hash join, etc.) onto the tables and existing indexes, you would have good input for adding and removing indexes.  But you have to allow for the infrequently run quarterly report that, without its otherwise unused index, would take days to complete.
I must tell you that when I did that kind of analysis once some years ago, I was disappointed to learn that most problem children were awful queries, usually prompted by awful table design.  No index will help the SQL mule.  Hopefully that will not be your experience.
An aspect you didn't touch on that might be just as important is machine capacity.  You might look into gathering, say, hourly snapshots of SQL Server stats, like disk queue depth and paging.  Hardly a server exists that can't be improved with more RAM, and sometimes that's really the best answer.

A: SQL perf tuning advisor worth a check: https://msdn.microsoft.com/en-us/library/ms186232.aspx
another way could be to get performance data, start here: https://www.experts-exchange.com/articles/17780/Monitoring-table-level-activity-in-a-SQL-Server-database-by-using-T-SQL.html and generate indexes based on the performance table data
check this too : https://msdn.microsoft.com/en-us/library/dn817826.aspx


text:
Q: 'Emailed' as a verb (vs 'sent email') I've started to see 'emailed' a lot in our company correspondence but as a non-native speaker I always tend to use 'sent email' instead. Here are some examples from reliable sources:

"I worked with a lady in England named Elizabeth; she's the best namer of horses I've ever met," Mr. Roberts said. "So I emailed her and asked what I would name him. She emailed right back. She didn't say 'I suggest,' or 'I think.'" She said, "His name is Benediction."
-- New York Times

"We condemn the use of the death penalty in all its forms. The death penalty is an inhuman, cruel and irreversible punishment that has no place in modern law," Swedish Foreign Minister Margot Wallstrom said in an emailed comment to Reuters news agency. -- Independent

Can we use 'email' as a verb as it is? How normal is this?
According to my own research, 'emailed' has been used a lot but 'email' as a verb is not common. So is this an exception just for the past tense?
Emailed - Lengusa
Email them - Lengusa (replace them with him/her etc)

A: Yes, email can be a verb. Just as you can send mail or mail something in English, you can send an email or email something.
According to the Oxford English Dictionary, email as a verb goes back at least to the 1980s:

1983   Computokid in net.micro (Usenet newsgroup) 25 Aug.   Young stuff interested in correspondence (via dull old paper mail) might email a letter to me to forward.

By the 1990s, email was understandable enough to use in an advertisement to UNIX users:

1993   UNIX Rev. Mar. 28/3 (advt.)    Call, fax or email for a free demo.

It's hard to overstate how commonly understood the usage is. As a small illustration, here are four members of the United States Congress (1,2,3,4) using email me in the title of a site about contacting them via email.

A: Yes, email is very much used as a verb, especially by native speakers, I have noticed that as well. Gngram is very clear about it:

Note that it can be used both transitively (send something by email)

[ + two objects ] Has he emailed you that list of addresses yet?
[Cambridge English Dictionary]

and intransitively:

: to communicate by email
As I write this, a colleague who takes an amateur interest in tracking the weather emailed to say it would be "among the hottest days of 2019 so far, if not #1".
[Merriam-Webster]


text:
Q: Utilizar 2 OnKeyUp no mesmo Input Consegui um código JavaScript que me atende perfeitamente, mas ele está dividido para ser usado em dois inputs, mas preciso que ele seja executado no mesmo input.
Segue abaixo o código. Ele é executado no evento OnKeyUp, então gostaria de saber se existe a possibilidade de executar o script abaixo no mesmo input?
function mascara_data(data)
{
    var mydata = '';
    mydata = mydata + data;
    if (mydata.length == 2)
    {
        mydata = mydata + '/';
        document.forms[0].data.value = mydata;
    }
    if (mydata.length == 5)
    {
        mydata = mydata + '/';
        document.forms[0].data.value = mydata;
    }
    if (mydata.length == 10)
    {
        verifica_data();
    }
}

function verifica_data()
{

    dia = (document.forms[0].data.value.substring(0, 2));
    mes = (document.forms[0].data.value.substring(3, 5));
    ano = (document.forms[0].data.value.substring(6, 10));

    situacao = "";
    // verifica o dia valido para cada mes
    if ((dia < 01) || (dia < 01 || dia > 30) && (mes == 04 || mes == 06 || mes == 09 || mes == 11) || dia > 31)
    {
        situacao = "falsa";
    }

    // verifica se o mes e valido
    if (mes < 01 || mes > 12)
    {
        situacao = "falsa";
    }

    // verifica se e ano bissexto
    if (mes == 2 && (dia < 01 || dia > 29 || (dia > 28 && (parseInt(ano / 4) != ano / 4))))
    {
        situacao = "falsa";
    }

    if (document.forms[0].data.value == "")
    {
        situacao = "falsa";
    }

    if (situacao == "falsa")
    {
        alert("Data inválida!");
        document.forms[0].data.focus();
    }
}

function mascara_hora(hora)
{
    var myhora = '';
    myhora = myhora + hora;
    if (myhora.length == 2)
    {
        myhora = myhora + ':';
        document.forms[0].hora.value = myhora;
    }
    if (myhora.length == 5)
    {
        verifica_hora();
    }
}

function verifica_hora()
{
    hrs = (document.forms[0].hora.value.substring(0, 2));
    min = (document.forms[0].hora.value.substring(3, 5));

    alert('hrs ' + hrs);
    alert('min ' + min);

    situacao = "";
    // verifica data e hora
    if ((hrs < 00) || (hrs > 23) || (min < 00) || (min > 59))
    {
        situacao = "falsa";
    }

    if (document.forms[0].hora.value == "")
    {
        situacao = "falsa";
    }

    if (situacao == "falsa")
    {
        alert("Hora inválida!");
        document.forms[0].hora.focus();
    }
}

A: Crie uma outra função que irá enviar os dados para as outras 4 funções. Essa função também irá se encarregar de validar os dados, ou seja, não precisa chamar as funções que verificam dentro das funções das máscaras (por isso deixei os trechos do código comentado com //, que você pode apagá-los).
Agora, como um extra, criei uma validação com RegEx para verificar se o valor digitado é no formato dd/mm/aaaa hh:mm (apenas números). Veja:

function valida_data(datahora){

   var formato = /^\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}$/.test(datahora);

   if(datahora.length < 10){
      mascara_data(datahora);
   }else{
      verifica_data();
   }

   if(datahora.length >= 13 && datahora.length < 16){
      mascara_hora(datahora.substr(11));
   }else if(datahora.length == 16){
      verifica_hora();
   }

   if(datahora.length == 16 && !formato){
      alert("formato inválido");
   }

}

function mascara_data(data)
{
    var mydata = '';
    mydata = mydata + data;
    if (mydata.length == 2)
    {
        mydata = mydata + '/';
        document.forms[0].data.value = mydata;
    }
    if (mydata.length == 5)
    {
        mydata = mydata + '/';
        document.forms[0].data.value = mydata;
    }
//    if (mydata.length == 10)
//    {
//        verifica_data();
//    }
}

function verifica_data()
{

    dia = (document.forms[0].data.value.substring(0, 2));
    mes = (document.forms[0].data.value.substring(3, 5));
    ano = (document.forms[0].data.value.substring(6, 10));

    situacao = "";
    // verifica o dia valido para cada mes
    if ((dia < 01) || (dia < 01 || dia > 30) && (mes == 04 || mes == 06 || mes == 09 || mes == 11) || dia > 31)
    {
        situacao = "falsa";
    }

    // verifica se o mes e valido
    if (mes < 01 || mes > 12)
    {
        situacao = "falsa";
    }

    // verifica se e ano bissexto
    if (mes == 2 && (dia < 01 || dia > 29 || (dia > 28 && (parseInt(ano / 4) != ano / 4))))
    {
        situacao = "falsa";
    }

    if (document.forms[0].data.value == "")
    {
        situacao = "falsa";
    }

    if (situacao == "falsa")
    {
        alert("Data inválida!");
        document.forms[0].data.focus();
    }
}

function mascara_hora(hora)
{
    var myhora = '';
    myhora = myhora + hora;
    if (myhora.length == 2)
    {
        myhora = myhora + ':';
        document.forms[0].data.value = document.forms[0].data.value.substr(0,11) + myhora;
    }
//    if (myhora.length == 5)
//    {
//        verifica_hora();
//    }
}

function verifica_hora()
{
    hrs = (document.forms[0].data.value.substring(11, 13));
    min = (document.forms[0].data.value.substring(14, 16));

    alert('hrs ' + hrs);
    alert('min ' + min);

    situacao = "";
    // verifica data e hora
    if ((hrs < 00) || (hrs > 23) || (min < 00) || (min > 59))
    {
        situacao = "falsa";
    }

    if (document.forms[0].data.value == "")
    {
        situacao = "falsa";
    }

    if (situacao == "falsa")
    {
        alert("Hora inválida!");
        document.forms[0].data.focus();
    }
}
<form>
   <input type="text" name="data" OnKeyUp="valida_data(this.value);" maxlength="16"> dd/mm/aaaa hh:mm<br>
</form>


text:
Q: How to call a PHP page uri from Bash on a local nginx server I have a php page that runs on a local uri on a local nginx server. It is called like this:
http://example.dev/index.php?v=var
Is it possible to call this php page from inside a Bash script in order to make it run just like I do by typing the uri in Firefox?
I tryed to access the script directly in cli:
php /home/public_html/example.dev/index.php
but it didn't work (it looks that php running under fastCGI and PHP-CLI work somehow  differently).
Any ideas?

A: Try GNU Wget
wget http://example.dev/index.php?v=var

or cURL
curl http://example.dev/index.php?v=var

to run it like a browser would.
Note: But this is not CLI in any way.

A: php -f <path-to-file>

php can output whatever you tell it to. It doesn't have to be HTML.

A: You can use a bash script to call a URI page by mfetching it with a program like curl:
curl -s 'http://example.dev/index.php?v=var' > /dev/null

…or you can be a little more hands on and use nc:
echo 'GET /index.php?var' | nc example.dev 80


text:
Q: Comparing two arrays of unequal length I have two arrays, say
array1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
array2 = {13, 4, 6, 20, 21};

I want to compare these two arrays by cycling array1 through all elements in array2. The output should be the position in each array where they match a condition, where the condition array2[[m]] = array1[[n]]-1 is true. That is, the output should be:
output = {6,2}

Because in array2, $5-1 = 4$. (array1[[6]] = 5 and array2[[2]] = 4). So far, my code is
output = {Position[array1, #][[1, 1]],
 Position[array2, #][[1, 1]]} & /@ (I have no idea)

Where the code on the left hand side of Map gives me the positions of a true condition. On the right hand side of Map, I'm not sure what to do.
To clarify a little bit, the code I want is similar to
output = {Position[array1, #][[1, 1]],
Position[array2, #][[1, 1]]} & /@ Intersection[array1, array2]

Except I want the position of the element when array2 = array1-1 instead of when array1 = array2.

A: You can use Tuples to construct all pairs of positions and use Select to pick the pairs that satisfy your condition:
pairs = Tuples[{ Range[Length[array1]], Range[Length[array2]]}];
Select[pairs, array1[[#[[1]]]] - 1 == array2[[#[[2]]]] &]

{{6, 2}, {8, 3}}

You can also use Outer as follows:
Join @@ Outer[If[array1[[#]] - 1 == array2[[#2]], {##}, Nothing] &,
  Range[Length[array1]], Range[Length[array2]]]

{{6, 2}, {8, 3}}

Yet other ways: variations on Roman's method using Position and Outer combination:
Position[1] @ Outer[Subtract, array1, array2]
Position[True] @ Outer[Equal, array1 - 1, array2]
Position[{i_, i_}]@Outer[List, array1 - 1, array2]

{{6, 2}, {8, 3}}

A: This is a general solution for any condition between the elements of array1 and array2:
Position[Outer[List, array1, array2], {i_, j_} /; j == i - 1]

{{6, 2}, {8, 3}}

@kglr's solutions are simpler than this when the condition is a difference as in the given problem.


text:
Q: How to use OMP_NUM_THREADS OpenMP I'm studying Parallel Programming in Visual Studio using C++. So, I get the practice work in which I should to set up number of threads using environment variable - OMP_NUM_THREADS. But how its using I don't know. Here's my code:
#include <omp.h>
#include <iostream>
#include <thread>
using namespace std;
int main()
{

#pragma omp parallel
        {
        cout << "Hello World\n";

        }
        return 0;

}

So, how I can get use it? What should I do?

A: Try to use #pragma omp parallel num_threads(4). I tested and it did print four times. FYI, OpenMP set_num_threads() is not working.


text:
Q: how to make graphic timelines in mathematica Hi does anyone know how to make timelines with mathematica?

Something like that would be great!

A: I tried to do something similar a few months ago
The easiest way is to write several functions:

EventFrame function creates event lables
EventFrame[str_, {date_, height_}, OptionsPattern[FontSize -> 14]] :=
Graphics[{
  Black, Thick, Line[{{date, height}, {date, 0}}],
  Text[Framed[Style[str, FontSize -> OptionValue[FontSize]],
  {Background -> White, FrameStyle -> Black,FrameMargins -> Automatic}], {date, height}]
}]

DateConv converts date {yr,mon,day} into single real number
Needs["Calendar`"]
LeapYearQ[year_] := DateQ[{year, 2, 29}]
DateConv[y_, m_, d_]:=y+(DateDifference[{y},{y, m, d}]+1)/If[LeapYearQ[y], 366, 365]
DateConv[{y_, m_, d_}]:=y+(DateDifference[{y},{y, m, d}]+1)/If[LeapYearQ[y], 366, 365]

TimeLine function creates timeline
TimeLine[min_, max_] :=
Graphics[{
  (* TimeLine *)
  Black, Thick, Line[{{min, 0}, {max, 0}}],
  (* year ticks *)
  Thin, Table[Line[{{x, 0.5}, {x, 0}}], {x, min, max}],
  (* year labels *)
  Table[Text[Framed[Style[x, FontSize -> 20],
  {Background -> White, FrameStyle -> White}], {x, 1}], {x, min, max}]
}]

Now all we need is a Show function.
Use Pane for for easier viewing
Pane[Show[
    EventFrame["Event 1", {DateConv[1988, 6, 2], 4}],
    EventFrame["Event 2", {DateConv[1990, 8, 15], -2}],
    (************************)
    TimeLine[1985, 1995],
    (************************)
     AspectRatio -> 1/6, ImageSize -> {1400, 280}],
    (************************)
    ImageSize -> {550, 280}, Scrollbars -> {True, False}]

Output without Pane

Edit
EventFrame2 function
EventFrame2[str_, {date_, height_}, OptionsPattern[{FontSize -> 14, offsets -> {0, 0}}]] :=
Graphics[{
  Thick,Line[{{date, height}, {date, 0}}],
  Text[Framed[Style[Column@{Style[ToString[Floor[date]],
  Bold,TextAlignment -> Left], str},
  FontSize -> OptionValue[FontSize]],
 {Background -> White, FrameStyle -> Black,FrameMargins -> Automatic}],
{date, height},OptionValue[offsets]]
} ]

Example
EventFrame2["Event 1", {DateConv[1988, 6, 2], 4}, offsets -> {-0.97, -0.5}]

Update 2014 - Mathematica 10
LeapYearQ is now a standard Mathematica function.
DateDifferencenow returns Quantity[n_,"Days"]
New DateConv function:
DateConv[y_, m_, d_] :=
 y + (DateDifference[{y}, {y, m, d}][[1]] + 1)/If[LeapYearQ[y], 366, 365]

A: As of Mathematica 10.1, creating a timeline is built-in with TimelinePlot[].
TimelinePlot[{
    Labeled[Interval[{DateObject[{2010, 2, 1}], DateObject[{2013, 5, 4}]}], "label1"],
    Labeled[DateObject[{2012, 4, 6}], "label2"],
    Labeled[Interval[{DateObject[{2011, 3, 1}], DateObject[{2012, 12, 21}]}], "label3"]
  }]

Lots of possibilities, looking at the documentation!
TimelinePlot[EntityClass["Movie", "BackToTheFutureFranchise"] -> "ReleaseDate"]

A:
Based on data in Comm ACM. This took a while to only partially automate, largely through a helper function that spreads out the years:
diffuse[a_][years_List] :=
  Module[{x0 = 1, x1 = Length[years], y0 = Min[years],
    y1 = Max[years]},
   years //
    MapIndexed[ {#1, (((y1 - y0)/(x1 - x0))*(First[#2] - x0) +
           y0) a + (#1) (1 - a)} &]];

diffuse maps a list of time points and spreads the interor points. The parameter a in principle can be any real number but higher values in [0,1] correspond to increasingly uniform spacing.
is defined in op form for use in Dataset:
data = {<|"Year" -> 1906, "Author" -> "Markov", "Contribution" -> "Markov theory"|>, <|"Year" -> 1907, "Author" -> "Perron","Contribution" -> "Perron theorem"|>, <|"Year" -> 1912, "Author" -> "Frobenius", "Contribution" -> "Perron-Frobenius theorem"|>, <|"Year" -> 1929, "Author" -> "von Mises", "Contribution" -> "Power method"|>, <|"Year" -> 1941,"Author" -> "Leontief",  "Contribution" -> "Econometric model"|>, <|"Year" -> 1949,  "Author" -> "Seeley", "Contribution" -> "Sociometric model"|>, <|"Year" -> 1952, "Author" -> "Wei", "Contribution" -> "Sport ranking model"|>, <|"Year" -> 1953, "Author" -> "Katz", "Contribution" -> "Sociometric model"|>, <|"Year" -> 1965, "Author" -> "Hubbell", "Contribution" -> "Sociometric model"|>, <|"Year" -> 1976,  "Author" -> "Pinsk, Narin",  "Contribution" -> "Bibliometric model"|>, <|"Year" -> 1998, "Author" -> "Kleinberg", "Contribution" -> "HITS"|>, <|"Year" -> 1998, "Author" -> "Brin, Page", "Contribution" -> "PageRank"|>} //Dataset;

Some years cluster:
data[All, "Year"] // Normal // NumberLinePlot

Make interpolation function (alternatively, can define an Association)
shift = data[
  GroupBy[#Year &] /* Keys /* diffuse[0.35] /* Interpolation]

Values a ~ 1/3 work for this particular data and graphics w/ coorindated shift:
itemGraphics := {{Darker@Blue, Disk[{#Year, 0}, 0.25]},
   {Thickness[0.001], Opacity[0.5],
    BezierCurve[{{#Year, 0}, {#Year, 2}, {shift[#Year],
       1 + 3/4}, {shift[#Year], 1 + 3/2}, {shift[#Year], 3}}]},
   Text[Column[{Style[ToLowerCase@#Author, Darker@Blue,
       FontSize -> 14, Bold],
      Style[ToLowerCase@#Contribution, Small]},
     Spacings -> 0], {shift[#Year], 4}, {-1, 1/2}, {1, 1},
    BaseStyle -> None]} &

Layout w/o timeline shows label clashing :
data[Graphics, itemGraphics]

data[GroupBy[#Year &]][Values,
   MapIndexed[Translate[#1, {0, 6 (First[#2] - 1)}] &], itemGraphics] //
  Normal // Graphics[{#}, Axes -> {True, False},
   PlotRange -> {{1900, 2020}, All},
   TicksStyle -> Directive@{FontSize -> 15, Darker@Blue},
   ImageSize -> 1000, ImagePadding -> 50] &

At a=0.7 balloon lines are stretched and spacing is more even but many labels are shifted way off past the years of future events.

This illustrates the interaction of ImageSize, AspectRatio, fonts, and data content (time clustering, ties, label dimensions (no easy way to get bounding boxes) seriously complicates automating layout.


text:
Q: OpenCV write jpeg buffer into Popen object I am doing some image operations on a numpy array via OpenCV. These images are then being baked out to jpeg, then ingested into FFMPEG to make a video. However, baking it out to a file is not very efficient. I would like to stream this directly into FFMPEG. In theory, it would look something like this:
p = Popen(['/usr/local/bin/ffmpeg', '-s', '1920x1080',
                   '-pix_fmt', 'yuvj420p',
                   '-y',
                   '-f', 'image2pipe',
                   '-vcodec', 'mjpeg',
                   '-r', self.fps,
                   '-i', '-',
                   '-r', self.fps,
                   '-f', 'mp4',
                   '-vcodec', 'libx264',
                   '-preset', 'fast',
                   # '-crf', '26',
                   'output/{}.mp4'.format(self.animation_name)], stdin=PIPE)

image_resize = cv.resize(self.original_image, (0, 0), fx=zoom, fy=zoom)
M = np.float32([[1, 0, x_total], [0, 1, y_total]])
image_offset = cv.warpAffine(image_resize, M, (self.original_image_width, self.original_image_width))
image = image_offset[0:self.output_raster_height, 0:self.output_raster_width].copy()
cv.imwrite(p.stdin, image) # this doesn't actually work, but that's the idea...

I've been able to achieve this with Pillow using this setup:
p = Popen(['/usr/local/bin/ffmpeg', '-s', '1920x1080',
                   '-pix_fmt', 'yuvj420p',
                   '-y',
                   '-f', 'image2pipe',
                   '-vcodec', 'mjpeg',
                   '-r', self.fps,
                   '-i', '-',
                   '-r', self.fps,
                   '-f', 'mp4',
                   '-vcodec', 'libx264',
                   '-preset', 'fast',
                   # '-crf', '26',
                   'output/{}.mp4'.format(self.animation_name)], stdin=PIPE)

image_resize = self.original_image.resize((resize_width, resize_height), resample=PIL.Image.BICUBIC)
image_offset = ImageChops.offset(image_resize, xoffset=int(x_total), yoffset=int(y_total))
image = image_offset.crop((0, 0, self.output_raster_width, self.output_raster_height))

image.save(p.stdin, 'JPEG')

So, my question is:
How would I write an OpenCV Jpeg buffer into the p.stdin object like it's being done in the Pillow version?


text:
Q: Why does add(1)(2) work when calling a function? I've never seen this format before. What is happening when you run
add(1)(2)

Or
add(1)(2)(3)

A: add would need to be a callable class as follows:
class add(int):
    def __call__(self, v):
        return add(self + v)

In that way you could assert that (for example):
add(1)(4) == 5


text:
Q: Mapping and binding nested objects and arrays I have an object and within this object I have items and one of the items is an array which also contains objects. A sample of the data is shown below.
I am using knockout to bind this data to the view so I think I need to implement a double loop for returning the objects and the objects within the child array to be able to bind them in the view.
Sample data:
"singers": {
        "ijiyt6ih": {
            "id": ObjectId('ijiyt6ih'),
            "name": "John",
            "songs": [
                {
                    "id": ObjectId('okoiu8yi'),
                    "songName": "Hello There",
                    "year": "1980"
                },
                {
                    "id": ObjectId('sewfd323'),
                    "songName": "No More",
                    "year": "1983"
                }
            ]
        },
        "98usd96w": {
            "id": ObjectId('98usd96w'),
            "name": "Jack",
            "songs": [
                {
                    "id": ObjectId('iew342o3'),
                    "songName": "Hurry Up",
                    "year": "1985"
                }
            ]
        }
    }

I need to find a way to appropriately loop through this so that I can modify the returned data to bind it to the viewModel using knockout.
Here is how my viewModel looks like:
singersViewModel = function(data) {
   var self = {
           singerId: ko.observable(data.id),
           singerName: ko.observable(data.name),
           songName: ko.observable(...),
           songYear: ko.observable(...)
       };

I am not sure if I will have to return two different sets of data or not.
As for the looping. I was able to loop and return the list of singers to display on the page but I am not able to get the list of songs displayed within each singer.
Here is my loop so far:
var self = {},
    singer,
    tempSingers = [];

    self.singers = ko.observableArray([]);
    for (singer in singers) {
        if (singers.hasOwnProperty(singer)) {
             tempSingers.push(new singersViewModel(singers[singer]));
           }
     }
     self.singers(tempSingers);

I tried to duplicate the same type of loop for songs within this loop but i would get an error using hasOwnProperty because songs is an array.

A: In the included snippet you can see how you can map the original data to a viewmodel that can be bound to a view.
I've left the ids as regular properties, and converted the names into observables, so thatthey can be edited. At the bottom you can see the current viewmodel state.
There is also a sample view which iterates the list of singers, and also the list of song within each singer.
As you can see I'm implementing the solution using mapping. For mapping you need to implement a callback that receives each original object and returns a new one with a new structure. For example this part of the code
_.map(_singers, function(singer) {
    return {
      id: singer.id,
      name: ko.observable(singer.name),
      // ... songs:
})

iterates over each singer (the sample data in the question), and for each one creates a new object with the id, an observable which includes the name (and the mapping of songs, which I don't show in this fragment).
NOTE: I'm using lodash, but many browsers support map natively as an array function

var ObjectId = function (id) { return id; }

var singers = {
        "ijiyt6ih": {
            "id": ObjectId('ijiyt6ih'),
            "name": "John",
            "songs": [
                {
                    "id": ObjectId('okoiu8yi'),
                    "songName": "Hello There",
                    "year": "1980"
                },
                {
                    "id": ObjectId('sewfd323'),
                    "songName": "No More",
                    "year": "1983"
                }
            ]
        },
        "98usd96w": {
            "id": ObjectId('98usd96w'),
            "name": "Jack",
            "songs": [
                {
                    "id": ObjectId('iew342o3'),
                    "songName": "Hurry Up",
                    "year": "1985"
                }
            ]
        }
    };

var SingersVm = function(_singers) {
  var self = this;
  self.singers = _.map(_singers, function(singer) {
    return {
      id: singer.id,
      name: ko.observable(singer.name),
      songs: _.map(singer.songs, function(song) {
        return {
          name: ko.observable(song.songName),
          id: song.id
          };
        })
    };
  });
  return self;
};

var vm = new SingersVm(singers);
//console.log(vm);
ko.applyBindings(vm);

      <input data-bind="value: name"/> ()

          <input data-bind="value: name"/> ()


text:
Q: Losing more rep than expected during a downvote I seem to have lost too much reputation for a single down vote to an answer that I made for my own question. I lost the normal 2 reputation, but I also seemed to have lost a second set of 2, totalling 4 reputation lost on a single down vote.
Is this the expected behaviour, or did something go wrong?

A: You received one on the question as well (someone's in a grumpy mood because Santa hasn't come yet).

It happens to list the reputation lost for both the question and answer in your profile, labeled with the title of the question.

A: This is because someone downvoted both your answer and question.
So what you are seeing is -2 for the answer downvote, and -2 for the question downvote. That is why it is listed twice in your recent reputation changes on your profile summary.
Sometimes it can be hard to tell this happens when the net total is 0 (as it is for the question you asked), but if broken apart1 (by clicking on the post score), it is actually +1, -1 (at the time I am writing this at least).
1. In order to see the breakdown of the votes, you must be an "Established User" by earning at least 1000 reputation on Stack Overflow


text:
Q: Prove If $x^2\equiv 1 \bmod 3$ then $x$ is even If $x^2\equiv1 \bmod 3$ then $x$ is even. I dont understand how to prove if this is right or wrong. Thanks

A: OK let's just try some numbers $1^{2}=1$ is congruent to $1$ mod $3$ and is odd. $2^{2}=4$ is also congruent to $1$ mod $3$. $3^{2}=9$ is congruent to zero mod $3$ and then the pattern just repeats for $4$ which is congruent to $1$ mod $3$. So we have two examples that are congruent to $1$ mod $3$, one is odd and one is even. So the fact that a number is congruent to $1$ mod $3$ tells us nothing about whether it is odd or even. I hope this helps.

A: There are only three alternatives:
\begin{align}
& 0^2 \equiv 0 \\
& 1^2 \equiv 1 \longleftarrow \text{This is a counterexample.} \\
& 2^2 \equiv 1
\end{align}

A: $x^2 \equiv 1 \mod 3 \iff x \equiv \pm 1 \mod 3 \iff x = 3n\pm 1 \; (n \in \mathbb Z)$.
Numbers of the form $x = 3n \pm 1$ are even if $n$ is odd and odd if $n$ is even.


text:
Q: Calculate Difference between time in Teradata I want to take difference of 2 date fields but both are varchar field
SyntaxEditor Code Snippet :
start_time- 2018-03-02 06:31:22

end_time -  2018-03-02 06:33:32.478000

I want the result in integer as 2 in min always  and it should be an integer always

Result :- 2

It would be very great if anyone can help to achieve my case.
Thanks

A: You can utilize interval calculations like cast((cast(end_time as timestamp) - cast(start_time as timestamp) minute(4)) as int), but it will fail for > 9999 minutes.
This is SQL UDF for calculating the difference of timestamps in seconds without limitations:
REPLACE FUNCTION TimeStamp_Diff_Seconds
(
   ts1 TIMESTAMP(6)
  ,ts2 TIMESTAMP(6)
)
RETURNS DECIMAL(18,6)
LANGUAGE SQL
CONTAINS SQL
RETURNS NULL ON NULL INPUT
DETERMINISTIC
SQL SECURITY DEFINER
COLLATION INVOKER
INLINE TYPE 1
RETURN
(CAST((CAST(ts2 AS DATE)- CAST(ts1 AS DATE)) AS DECIMAL(18,6)) * 60*60*24)
      + ((EXTRACT(  HOUR FROM ts2) - EXTRACT(  HOUR FROM ts1)) * 60*60)
      + ((EXTRACT(MINUTE FROM ts2) - EXTRACT(MINUTE FROM ts1)) * 60)
      +  (EXTRACT(SECOND FROM ts2) - EXTRACT(SECOND FROM ts1))
;

If you can't create UDFs you can copy the source and apply a final / 60 and cast it as integer.


text:
Q: Excel VBA Run time error 1005=4 I am getting a runtime error when running this marco in excel. The code when rows = 1 works perfectly but I get a runtime error after the else. I can't seem to figure out the problem
If rows = 1 Then
Sheets("Sales Report").Range("C" & 1 + rows).Formula = "=SUMIFS('Stock Log'!$I$2:$I$1048576,'Stock Log'!$H$2:$H$1048576,B2,'Stock Log'!$B$2:$B$1048576,""<=""&A2)"
Else
Sheets("Sales Report").Range("C" & 1 + rows).Formula = "=SUMIFS('Stock Log'!$I$2:$I$1048576,'Stock Log'!$H$2:$H$1048576," & Cells(rows + 1, 2).Address & ",'Stock Log'!$B$2:$B$1048576,""<=""" & Cells(rows + 1, 1).Address & ",'Stock Log'!$B$2:$B$1048576,"">""" & Cells(rows, 1).Address & ")"
End If


text:
Q: Watir's ability to find element in iframe depends on previous code @browser = Watir::Browser.new #:phantomjs (same with firefox)
@browser.window.maximize

@browser.goto 'http://www.romnation.net/'

size = ['728', '90']
p @browser.iframes(width: size[0], height: size[1]).length
@browser.iframes(width: size[0], height: size[1]).each do |ifr|
    p ifr.img.src if ifr.img.present? # 1
end

size = ['160', '600']
p @browser.iframes(width: size[0], height: size[1]).length
@browser.iframes(width: size[0], height: size[1]).each do |ifr|
    p ifr.img.src if ifr.img.present?
end

This program will say that there are no iframes (160, 600) on a page (even though there are). If I don't search for (728, 90) iframes first, program always finds (160, 600) iframes. Further more, it happens only if I don't only search for (728, 90) iframes first, but if I search for images (line 1) in these iframes also.
Why on earth may that be? Am I missing something?

A: This is a known bug - https://github.com/watir/watir-webdriver/issues/237
I have an open pull request that fixes it, but it is still waiting for full review:
https://github.com/watir/watir-webdriver/pull/286
Window#use helps because it returns the driver to the top-level browsing context.
It is essentially doing:
@browser.driver.switch_to.default_content
or
@browser.assert_exists

A: size = ['728', '90']
p @browser.iframes(width: size[0], height: size[1]).length
@browser.iframes(width: size[0], height: size[1]).each do |ifr|
    p ifr.img.src if ifr.img.present? # 1
end

@browser.window(:url => 'http://www.romnation.net/').use #__________new

size = ['160', '600']
p @browser.iframes(width: size[0], height: size[1]).length
@browser.iframes(width: size[0], height: size[1]).each do |ifr|
    p ifr.img.src if ifr.img.present?
end

Switching to main window again with @browser.window(:url => 'http://www.romnation.net/').use helps.


text:
Q: How to preserve formatting while copy-pasting from Eclipse IDE to PowerPoint 2010 Is there a way I could copy the source code from Eclipse IDE and paste it on PowerPoint preserving the formatting?
When I try to do it I get zero indentation when pasting it to PowerPoint 2010.
The copy-paste from Eclipse to Microsoft Word works just fine, but not with PowerPoint.

A: Depending on your version of office, there are always the three options available while pasting in any office product, they are

*

*Use Destination Theme.

*Keep Source Formatting. (suitable for your case)

*Keep Text Only.

However, I would suggest if you are doing this for only presentation purpose, you should take screenshots from eclipse and use them with suitable styles in your presentation. Hope this helps.

A: If I paste from Eclipse straight to PowerPoint I get some format mistakes. Some things stay bold or colored. But if you go from Eclipse to Word and then copy from Word to PowerPoint then the formatting is preserved. This is true for PowerPoint 2013 too.


text:
Q: Authenticating a user in Azure AD through a web api? I'm working on integrating Azure AD authentication with various apps on different platforms.
Is there a way to get an authentication token id from a user logging in through a web api like 'azureadlogin.com/login?user=ted&password=passwordhash'
There seems to be ways of doing it through node or javascript or C# apps but I'd really like to just have a simple web request way of doing it as there are many different apps on different platforms that need to make use of this feature.

A: No.
There is a way to authenticate with username + password by doing a POST request and using Resource Owner Password Credentials flow, but I don't recommend it.
ROPC will not work if:

*

*User's password has expired

*User is MS account/federated from on-prem AD

*User has multi-factor authentication enabled

You have a wide selection of authentication flows which work in all these scenarios too, and don't involve the user giving their password to you.
For example:

*

*Authorization code flow

*Implicit grant flow

*Device authentication flow

A: You can use username/password authentication. But if your app has user interface, so it could popup the regular Azure AD login page, I would recommend not to use it. A major reason for using Azure AD (or other identity providers) is that the user doesn't want your app to know his password.
There's a sample which does what you want. The code in question is here.
The sample uses .NET and the ADAL.net library, but you can do similar stuff on other platforms.