text:
Q: how do I search string and see if any letters are there? I need to find out if a string contains letters in it. I think I've tried every thing in the world and they haven't worked. I've tried many examples from here (and other places) but they don't work either
I know there are a lot of similar questions. I've read them and they don't work for me, so I'm asking again.
Any help is appreciated.

A: var s = "123x456";

var hasLetter = s.Any(Char.IsLetter);

A: You can use Regex
Public function containsletter(ByVal text As String) As Boolean
  Dim pattern As String = "[a-z]"
  Dim r As Regex = new Regex(pattern, RegexOptions.IgnoreCase)
  Dim m As Match = r.Match(text)
  If m.Success
  Return True;
  Else
  Return False;
  End If
End function


text:
Q: Adding an arrow below the x axis in R plots I am trying to add arrows marking specific x coordinates below the x axis in an R plot. My x axis is at y=0 and when I try to use negative y-coordinates in arrows, so the arrows will be perpendicular to x axis, I get only the very edges of the arrow plotted (although is some space, e,g where the x-axis label and tickmarks are plotted).

A: You can do this by adding an extra overlay, by calling par(new=TRUE), with reduced margins. For example:
plot(1,1) ## start a plot
opar <- par(new = TRUE, ## add a new layer
            mar = c(0,0,0,0)) ## with no margins margins
## set up the plotting area for this layer
plot(1,1,xlim=c(0,1),ylim=c(0,1),type='n',xlab='',ylab='')
arrows(0.1,0.05,0.5,0.05) ## add arrow
par(opar) ## return the plot parameters to their prior values

Edit: If you want to keep the same coordinates as in the original plot, you have to choose the x- and y-axis limits carefully. This is illustrated belo:
plot(1,1,xlim=0:1,ylim=0:1)
arrows(0.1,0.05,0.5,0.05)
gpar <- par()
opar <- par(new = TRUE, mar = c(0,0,0,0),xaxs='i',yaxs='i')

m1 <- (gpar$usr[2] - gpar$usr[1])/(gpar$plt[2] - gpar$plt[1])
c1 <- gpar$usr[1] - m1*gpar$plt[1]
m2 <- (gpar$usr[4] - gpar$usr[3])/(gpar$plt[4] - gpar$plt[3])
c2 <- gpar$usr[3] - m2*gpar$plt[3]
xlim <- c(c1, m1 + c1)
ylim <- c(c2, m2 + c2)

plot(1,1,xlim=xlim,ylim=ylim,type='n',xlab='',ylab='')
arrows(0.1,0.05,0.5,0.05,col='red')
points(1,1,col='red')
par(opar)

A: The xpd option can be used in arrows so you can just set your coordinates to be outside your plot region and set xpd to TRUE.  For example, assuming xlim = c(0,10) and ylim = (0,10), and you set the x-axis to 0 then
arrows(1.4, -1, 1.4, 0, xpd = TRUE)

draws a vertical arrow pointing up at the x-axis at position 1.4 on that axis.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SMTP issues with AWS Linux Server I have little experience with SMTPs and have come across some trouble getting my Drupal site to send out emails. The only change that had been made prior to the error was adding a CloudFront to instance. Then months later we changed the email recipient and it stopped working.
Log error from var/log/maillog:
Feb  1 20:27:43 ip-10-0-0-127: from=apache, size=860, class=0, nrcpts=3, msgid=<2017@ip-10-0-0-127>, relay=apache@localhost

Feb  1 20:27:44 ip-10-0-0-127: from=<apache@ip-10-0-0-127>, size=1043, class=0, nrcpts=3, msgid=<2017@ip-10-0-0-127>, proto=ESMTP, daemon=MTA, relay=localhost [127.0.0.1]

Feb  1 20:27:44 ip-10-0-0-127: to=l@columbia.edu,j@columbia.edu,r@columbia.edu, ctladdr=apache (48/48), delay=00:00:01, xdelay=00:00:01, mailer=relay, pri=90860, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (Message accepted for delivery)

Feb  1 20:27:49 ip-10-0-0-127: STARTTLS=client, relay=mail-in.cc.l.columbia.edu., version=TLSv1/SSLv3, verify=FAIL, cipher=, bits=256/256

Feb  1 20:27:49 ip-10-0-0-127: to=<r@columbia.edu>,<j@columbia.edu>,<l@columbia.edu>, ctladdr=<apache@ip-10-0-0-127> (48/48), delay=00:00:06, xdelay=00:00:05, mailer=esmtp, pri=181043, relay=mail-in.cc.l.columbia.edu. [128.00.000.000], dsn=5.6.0, stat=Data format error

Feb  1 20:27:49 ip-10-0-0-127: DSN: Data format error

Feb  1 20:27:49 ip-10-0-0-127: to=root, delay=00:00:00, xdelay=00:00:00, mailer=local, pri=32235, dsn=2.0.0, stat=Sent

And the following after removing the Throttle from port 25:
to=<apache@site.school.edu>, delay=00:16:00, xdelay=00:16:00, mailer=esmtp, pri=34406, relay=xxxxxxx.cloudfront.net. [54.192.19.124], dsn=4.0.0, stat=Deferred: Connection timed out with xxxxxxx.cloudfront.net.

adsl-static.isp.belgacom.be [81.xxx.xx.xx] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA

Fems.dsrtg.gov.tw [117.xx.xxx.xxx] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA

On AWS's Security Group I opened up ports for SMTP 25 and SMTPS 465:
netstat -ntlp | grep sendmail
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN
2180/sendmail

Reference: http://www.golinuxhub.com/2013/06/statdeferred-connection-timed-out.html
Changed my sendmail.mc fileto the following:
DAEMON_OPTIONS(`Port=smtp,Addr=0.0.0.0, Name=MTA')dnl

Copied over the changes and restarted the mail service using:
m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf
service sendmail restart

Changed my ect/host file to:
127.0.0.1 localhost
54.192.37.15 site.school.edu site

Reference: https://www.drupal.org/node/1155
One last thing I forgot to mention! The domain name is pointing to the site.cloudfront.net domain name. Hope this helps.
Is there anything else I'm missing that could help with the issue?
Thanks,

A: Cloudfront has no bearing on SMTP.
Amazon throttles outgoing SMTP as part of spam blocking: https://aws.amazon.com/premiumsupport/knowledge-center/ec2-port-25-throttle/
You can request to have the throttle lifted off of a link from that page.


text:
Q: SelectInput R shiny I am a beginner in R shiny. I use an Oracle database.
I have a table T_Client(CLI_ID, CLI_NAME, CLI_INFO).
I display CLI_NAME from T_CLIENTin selectinput which I used reactive function sqlOutput()
But I can't display all columns from T_CLIENT in the renderTable, the funCtion sqlOutput() doesn't work well.
Any help please ? Thanks in advance.
library(DBI)
library(ROracle)
library(shinydashboard)

header <- dashboardHeader()

sidebar <- dashboardSidebar()

body <- dashboardBody(
  uiOutput("ui_assetClass"),
  tableOutput("table2"))

shinyApp(
  ui = dashboardPage(header, sidebar, body),
  server = function(input, output, session= open()) {

    drv <- dbDriver("Oracle")
    host <- "host"
    port <- xxxx
    svc <- "svc"
    connect.string <- paste(
      "(DESCRIPTION=", "(ADDRESS=(PROTOCOL=tcp)(HOST=", host, ")(PORT=", port, "))",
      "(CONNECT_DATA=(SERVICE_NAME=", svc, ")))", sep = "")
    DB <- dbConnect(drv, username = "username", password = "password", dbname = connect.string)

    sqlOutput<- reactive({

   sqlInput<- dbGetQuery(DB,"select CLI_NAME from T_CLIENT")

      sqlInput
    })

    output$ui_assetClass <- renderUI({
      selectInput(" Clients", "choose client", choices = sqlOutput())
    })

    dabaBaseInput2 <- reactive({
      x <- dbGetQuery(DB, sprintf("SELECT CLI_ID, CLI_NAME, CLI_INFO FROM T_CLIENT where CL_NOM = '%s' ",sqlOutput()))
      x
    })

    output$table2 <- renderTable({
      dabaBaseInput2()
    })

  })


text:
Q: override tpl values from values yaml I have yaml definition as below
      resources:
        {{- template "tpl.podMemory" (dict "mapValue" $value "mapKey" $key ) }}

and my tpl file as below
{{- define "tpl.podMemory" }}
{{- if .mapValue.memory }}
{{- if eq .mapValue.memory "Tiny" }}
            requests:
              memory: 512Mi
            limits:
              memory: 768Mi
{{- end }}

below example of values.yaml file and I want to override the values above in tpl file so that it will deploy my resources with new values in value.yaml
  service1:
     requests:
       memory: 1000Mi
     limits:
        memory: 2000Mi
   memory: Tiny
   deploy: true

How to override mapValue present in tpl  using values.yaml?


text:
Q: Does rewarded-ads allow to check what the user got rewarded so far? Background
I've recently read about rewarded ads, as shown here:

*

*https://github.com/googleads/googleads-mobile-android-examples

*https://developers.google.com/admob/android/rewarded-video
The problem
I can't find any API about the recent rewards, of what the user got so far.
What I've tried
I tried to check on the docs and tried to check all possible functions of the API via the IDE itself.
The samples on Github show how to get a callback that you got a reward (so you can save it for later), but this will be lost in the case of uninstall of the app, or if you switch to another device that has the same app with the same user account.
The questions

*

*Is there a way to get all rewards of the user for the current app (even after uninstall&re-install) ? If so, how?
If not, what's the best way to do it to fill this gap? Is there one from Google?

*Is there a way to get what the reward is worth in real money?

*Are there other similar services like the one of Google, of rewarded videos, that also provide an API to check on recent rewards ?

A: AdMob does not keep a track of your users earning. You will have to keep the track of the users earning by yourself or by using some other service.
They will only provide you with an Video ad and will notify you once the Video a is completed so that you can award your users the points/virtual currency.
However there are other services such as Tapjoy which provide ads as well as provide you with the option to keep the track of your users earning. I think Tapjoy is free to use only if you use their Ad Network to show their ads to the user, which will help you to earn and also keep a track of the earnings under one portal.


text:
Q: Zimbra Default Admin Console What is the default address to get to a Zimbra Admin Console? Any default ports too?

A: I found the answer to my question, it looks to be like the following:
https://mailserveraddress:7071/zimbraAdmin/


text:
Q: Cannot insert WHERE statement with a variable in php query     <?php

    // Working SELECT query.
    $db = new SQLite3('casino.db');

    // This works great and returns only name = bergpau !!!
    $results = $db->query('SELECT * FROM employe WHERE username="bergpau"');
   while ($row = $results->fetchArray())
         print  $row['nom'] . "
";

   // This DOES NOT WORK AT ALL, returns no values !!! HELP !!!
   $astring = "bergpau";
   $results = $db->query('SELECT * FROM employe WHERE username=$astring');
   while ($row = $results->fetchArray())
        print  $row['nom'] . "
";

   ?>

Opening database, ok
return no value since it cannot validate string in WHERE clause

A: Strings, in SQL (and PHP), need to be quoted like you did in your first query (username="bergpau"). This also could open you to SQL injections; you should use parameterized queries.
$results = $db->query("SELECT * FROM employe WHERE username='{$astring}'");

Also variables in single quotes aren't processed by PHP.

Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

-http://php.net/manual/en/language.types.string.php
Alternatively you could pass the quotes in the assignment (note the double quotes are for the encapsulation in PHP, the single quotes are stored in the value of $astring):
$astring = "'bergpau'";

then you'd just need to concatenate the variable.
$results = $db->query('SELECT * FROM employe WHERE username=' . $astring);


text:
Q: Sharepoint List Item Permission behavior for List with restricted read/edit What is the expected behavior for SharePoint when a user trying to access a SharePoint online (Office 365) list item in a list with restricted read/edit access when the user that did not create the list item only has contribute list permissions and does not have general override list behavior or full control for the list but does have full control permission for the list item? I believe in SP2007 that the user was allowed to access and edit the item but that in our Office 365 SharePoint site the user is unable to access the item. Is this the expected behavior or have I made a configuration error?
The steps taken to get to this point are:

*

*create a new list in SharePoint Online/Office365.

*Using the list advanced settings restrict the access (both read and edit) to only the user that created the item.

*Create a general group to with edit permissions for the list.

*Create a second group with full control permissions for the list

*Have a user in the full control group add a list item

*While authenticated as user in the full control group, add full control item-level permissions for that list item for User "B," who is not in the full control group for the list.

*Have User "B" attempt to edit the list item.

User "B" is unable to access the item. I think that this is a changed behavior from WSS 2007. If this is the intended behavior of these combinations of permissions and item level restrictions, we will have to re-architect our solution. But if there is something that will allow User "B" to edit an item that was created by someone else, that would be easier to implement.
One other potential twist, which I don't think is relevant, is that this site is a secondary SharePoint site in our Office 365 account.
Thank you in advance for your feedback.

A: This is typical behavior. I don't remember how this worked in 2007, but now you'll need to set permissions differently for users to be able to see only their own, plus individual items.
You could:

*

*Give the "full control" Override Check-Out permissions at the list level (not the item level).

*Use a simple workflow to set permissions when an item is created, granting contribute permissions to the user who created the item, and to your "full control" group.


text:
Q: Möbius inversion formula? If i have two arithmetic functions F and G such as:
$$ F(n)= \sum_{d | n} G(d,n)$$
where $G$ depends on the divisors of $n$ and $n$. And where $n \leq m$ where $m$ is a fixed positive integer. Can I use the Möbius inversion formula for $n \leq m$ ? I think yes we can.
But i would like to know if we can applied Möbius inversion formula because it's a simple consequence of the Möbius inversion formula (where $n \in \mathbb{N}^*$) or a consequence of the generalization explained here: https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula#Generalizations
(That is named also Rota inversion formula)
Thanks for your answers.

A: Generally, things work in this way.
For every $d \mid n$, you should define $f(d, n), g(d, n) $. Then
$$(*) \ \ f(m, n) =\sum_{m \mid d \mid n} g(d, n) $$
Holds for every $m \mid n$ iff
$$g(m, n) =\sum_{m \mid d \mid n} \mu(d/m) f(d, n) $$
Holds for every $m \mid  n$. This is just a matter of arranging terms in a proper way: it is a combinatorial fact.
If you want to invert the equation, you should:
 1. Extend your $f$ to $\bar{f} $, such that $\bar{f}(1,n)=f(n) $;
 2. Verify that for all $m \mid n$ the equation $(*) $ holds.
Remark. Normally, you have both $f, g$ one-variable functions. The two steps I told you are made in this way:

*

*Set $\bar{f}(m, n) =f(n/m), \bar{g} (m, n) =g(n/m) $.

*If the equation $(*) $ is satisfied just for $m=1$, then
$$  \bar{f}(m, n) =f(n/m) =\sum_{d\mid n/m} g(n/md) =\sum _ {m \mid d' \mid n} g(n/d') = \sum _{ m \mid d' \mid n} \bar{g} (d', n) $$
It holds for every $m$.


text:
Q: Error: C:\Users\user\AppData\Roaming\Python\Python311\site-packages\pyqtgraph\debug.py:128: RuntimeWarning: Ignored exception: I wrote the code below with python 3.11.0 and PyQt6 to draw a random graph.
sorry for its length.
from random import randint
from sys import argv
from PyQt6.QtCore import QRect, Qt, QTimer
from PyQt6.QtGui import QColor, QKeyEvent, QMouseEvent, QPainter, QPen, QPaintEvent
from PyQt6.QtWidgets import QApplication, QVBoxLayout, QWidget
from pyqtgraph import PlotWidget, mkPen

class Window(QWidget):
    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        screenWidth = 1920
        screenHeight = 1080
        self.gX = []
        self.gY = []
        self.framesShowPerSecond = 30
        self.age = 0
        self.maxAge = 500
        self.windowWidth = 1920
        self.windowHeight = 1080
        self.isRunning = True
        self.clockCounterVariable = 0
        self.milliseconds = 0
        self.seconds = 0
        self.minutes = 0
        self.hours = 0
        self.graph = PlotWidget(self)
        self.graph.setGeometry(100, 100, 1720, 880)
        self.graph.showGrid(x=True, y=True)
        style = {'color':'white', 'font-size':'20px'}
        self.graph.setLabel('left', 'Y', **style)
        self.graph.setLabel('bottom', 'X', **style)
        self.graph.setBackground('black')
        self.setWindowTitle("test")
        self.setGeometry((screenWidth - self.windowWidth) // 2, (screenHeight - self.windowHeight) // 2, self.windowWidth, self.windowHeight)
        self.setLayout(QVBoxLayout())
        self.showFullScreen()
        self.setStyleSheet("background-color:rgb(20, 20, 20);font-size:20px;")
        self.xCounter = 0
        self.clock = QTimer(self)
        self.graphicTimer = QTimer(self)
        self.clock.timeout.connect(self.clockCounter)
        self.graphicTimer.timeout.connect(self.update)
        self.graphicTimer.start(round((1/self.framesShowPerSecond)*1000))
        self.clock.start(10)
        self.show()

    def clockCounter(self) -> None:
        if self.clockCounterVariable % 10 == 0:
            self.gX.append(self.xCounter)
            self.xCounter += 1
            self.gY.append(randint(0, 100))
        self.clockCounterVariable += 1

    def keyPressEvent(self, event: QKeyEvent) -> super:
        key = QKeyEvent.key(event)
        if key == 112 or key == 80: # P/p
            if self.isRunning:
                print("pause process")
                self.isRunning = False
                self.clock.stop()
                self.graphicTimer.stop()
            else:
                print("continue process")
                self.isRunning = True
                self.clock.start(1000)
                self.graphicTimer.start(round((1/self.framesShowPerSecond)*1000))
        elif (key == 115) or (key == 83): # S/s
            self.closeWindow()
        self.update()
        return super().keyPressEvent(event)

    def mousePressEvent(self, event: QMouseEvent) -> super:
        if event.buttons() == Qt.MouseButton.LeftButton and not self.isHelpMenuShown:
            if self.isRunning:
                print("pause process")
                self.isRunning = False
                self.clock.stop()
                self.graphicTimer.stop()
            else:
                print("continue process")
                self.isRunning = True
                self.clock.start(1000)
                self.graphicTimer.start(round((1/self.framesShowPerSecond)*1000))
        return super().mousePressEvent(event)

    def paintEvent(self, event: QPaintEvent) -> super:
        self.graph.plot(self.gX, self.gY, pen = mkPen(color=(255, 255, 255), width=2))
        self.milliseconds = self.clockCounterVariable
        self.seconds, self.milliseconds = divmod(self.milliseconds, 100)
        self.minutes, self.seconds = divmod(self.seconds, 60)
        self.hours, self.minutes = divmod(self.minutes, 60)
        painter = QPainter()
        painter.begin(self)
        painter.setPen(QPen(QColor(255, 128, 20),  1, Qt.PenStyle.SolidLine))
        painter.drawText(QRect(35, 30, 400, 30), Qt.AlignmentFlag.AlignLeft, "{:02d} : {:02d} : {:02d} : {:02d}".format(self.hours, self.minutes, self.seconds, self.milliseconds))
        if self.clockCounterVariable <= 3:
            painter.drawText(QRect(self.windowWidth//2-300, self.windowHeight//4-40, 600, 40), Qt.AlignmentFlag.AlignCenter, "for see help menu press 'h/H'")
        painter.end()
        return super().paintEvent(event)

    def closeWindow(self) -> None:
        print("closing window ...")
        self.close()

if __name__ == "__main__":
    App = QApplication(argv)
    window = Window()
    exit(App.exec())

it works and draws the graph but makes the warning below continuously.
It makes the code slow.
how I can fix it? why do I get this warning?
C:\Users\user\AppData\Roaming\Python\Python311\site-packages\pyqtgraph\debug.py:128: RuntimeWarning: Ignored exception:
Traceback (most recent call last):
  File "E:\Document\test.py", line 113, in <module>
    exit(App.exec())
  File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\pyqtgraph\widgets\GraphicsView.py", line 137, in paintEvent
    return super().paintEvent(ev)
  File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\pyqtgraph\debug.py", line 128, in w
    printExc('Ignored exception:')
  --- exception caught here ---
  File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\pyqtgraph\debug.py", line 126, in w
    func(*args, **kwds)
  File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\pyqtgraph\graphicsItems\PlotCurveItem.py", line 905, in paint
    p.drawLines(*self._getLineSegments())
TypeError: arguments did not match any overloaded call:
  drawLines(self, PyQt6.sip.array[QLineF]): not enough arguments
  drawLines(self, QLineF, *): not enough arguments
  drawLines(self, PyQt6.sip.array[QPointF]): not enough arguments
  drawLines(self, QPointF, *): not enough arguments
  drawLines(self, PyQt6.sip.array[QLine]): not enough arguments
  drawLines(self, QLine, *): not enough arguments
  drawLines(self, PyQt6.sip.array[QPoint]): not enough arguments
  drawLines(self, QPoint, *): not enough arguments
  printExc('Ignored exception:')

how I can fix this warning?
it seems to me there is some bug in pyqtgraph. am I right?


text:
Q: Eclipse: impossible to load from Git repository I am trying to use Eclipse to connect to GIT repository.
I go to File -> Import -> Git -> Projects from Git -> Clone URI...
There I fill everything what is needed. And on the next tab I set the master branch.
I pick the directory, which should be the Local Destination (i.e. C:\Dev\Eclipse_workspace\Automation).
The folder Automation doesn't exist.
On the next screen, I choose "Import as general project".
It tells me "Project Automation already exists".
So I remove the folder.
But then it tells me "Directory C:\Dev\Eclipse_workspace\Automation does not exist".

Unfortunately, I have to use Eclipse on dedicated computer for this current project and don't have the option to use other IDE.
Can you give me any advice of whether it's a bug, or just some misunderstanding?
Thank you.

A: It doesn't work this way because importing here only works if the repository is outside the workspace.
Either select a location outside the workspace or do the following:

*

*Clone the project into the workspace as you did it, but without importing: In Quick Access (Ctrl+3) type Clone a Git Repository to open the Clone dialog

*Create a new General Project named Automation: File > New > Other...: General > Project


text:
Q: counting values per subject I would like to add a new column to a dataset called COUNT. My dataset has a variables subject, tox1 , tox2, tox3 (character variables) with  different values. A subject can appear multiple times in my dataset, I want to count the occurrence of 'ADR' per subject. What I want to do is create a new variable called COUNT that counts how many times a subject has a specific value ie 'ADR' for tox1, tox2 and tox3; when a SUBJECT does not have an observation for that specific value, I want COUNT to have a result of zero.
Here's an example of the dataset I would like (in this example, I want to count every instance of "ADR" per SUBJECT as COUNT).
 INPUT subject $ tox1 $ tox2 $ tox3 $;
 datalines;
1   ADR c s
1   ADR d f
1   s ADR f
1   a w e
2   d f g
3   e d ADR
3   k ADR f
4   N ADR ADR
4   Q ADR d
4   ADR d f
4   r v h
4   ADR f g
5   g f d
5   r t u
5   g h j
;

THIS IS INPUT DATASET
SUBJECT TOX1 TOX2 TOX3 COUNT
1   ADR c s    3
1   ADR d f    3
1   s ADR f    3
1   a w e      3
2   d f g      0
3   e d ADR    2
3   k ADR f    2
4   N ADR ADR  5
4   Q ADR d    5
4   ADR d f    5
4   r v h      5
4   ADR f g    5
5   g f d      0
5   r t u      0
5   g h j      0

THIS IS THE REQUIRED OUTPUT FOR COUNT VARIABLE

A: Here is a data step approach
data have;
INPUT subject $ tox1 $ tox2 $ tox3 $;
datalines;
1 ADR c   s
1 ADR d   f
1 s   ADR f
1 a   w   e
2 d   f   g
3 e   d   ADR
3 k   ADR f
4 N   ADR ADR
4 Q   ADR d
4 ADR d   f
4 r   v   h
4 ADR f   g
5 g   f   d
5 r   t   u
5 g   h   j
;

data want (drop = i);
   count = 0;
   do _N_ = 1 by 1 until (last.subject);
      set have;
      by subject;
      array tox {3};
      do i = 1 to dim(tox);
         if tox [i] = 'ADR' then count = sum(count, 1);
      end;
   end;
   do _N_ = 1 to _N_;
      set have;
      output;
   end;
run;

Result:
count subject tox1 tox2 tox3
3     1       ADR  c    s
3     1       ADR  d    f
3     1       s    ADR  f
3     1       a    w    e
0     2       d    f    g
2     3       e    d    ADR
2     3       k    ADR  f
5     4       N    ADR  ADR
5     4       Q    ADR  d
5     4       ADR  d    f
5     4       r    v    h
5     4       ADR  f    g
0     5       g    f    d
0     5       r    t    u
0     5       g    h    j


text:
Q: How to make a node.js application run permanently? On a Debian server, I installed Node.js. I understand how to launch an app from putty with this command line:
node /srv/www/MyUserAccount/server/server.js

and get to it on the address 50.51.52.53:8080 (IP and port).
But as soon as I close putty, then I cannot reach the address 50.51.52.53:8080 anymore.
How to make a Node.js application run permanently?
As you can guess, I am a beginner with Linux and Node.js.

A: I've found forever to do the job perfectly fine.
Assuming you already have npm installed, if not, just do
sudo apt-get install npm

Then install forever
npm install forever --global

Now you can run it like this
forever start app.js

https://codingweb.io/run-nodejs-application-background/

A: No need to install any other package.
Run this command
node server.js > stdout.txt 2> stderr.txt &

server.js is your server file or it can be api.js
After that hit "exit" to close terminal
exit

A: Another way is creating a system unit for your app. create a "XXX.service" file in "/etc/systemd/system" folder, similar to this:
[Unit]
Description=swagger
After=network.target

[Service]
ExecStart=/usr/bin/http-server /home/swagger/swagger-editor &
WorkingDirectory=/home/swagger
Restart=always
RestartSec=30

[Install]
WantedBy=multi-user.target

A benefit is the app will run as a service, it automatically restarts if it crashed.
You can also use sytemctl to manage it:
systemctl start XXX to start the service, systemctl stop XXX to stop it and systemctl enable XXX to automatically start the app when system boots.

A: Try pm2 to make your application run forever.
npm install -g pm2
and then use
pm2 start server.js
to list and stop apps, use commnds
pm2 list
pm2 stop 0

A: I hope this will help you.
At the command line, install forever:
npm install forever -g

Create an example file:
sudo nano server.js

You can edit the file and get results directly in your browser.
You can use filezilla or any editor to edit the file.
Run this command to run the file:
forever start --minUptime 1 --spinSleepTime 1000 -w server.js

A: I'd recommend looking for something such as Forever to restart Node in the event of a crash, and handle daemonizing this for you.

A: If you just want to run your node app in the terminal always, just use screen.
Install on ubuntu/ debian:
sudo apt-get install screen

Usage:
$ screen
$ node /path/to/app.js

ctrl + a and then ctrl + d to dismiss
To get is back:
One screen: screen -r
If there's more than one you can list all the screens with: screen -ls
And then: screen -r pid_number

A: You could install forever using npm like this:
sudo npm install -g forever

And then start your application with:
forever server.js

Or as a service:
forever start server.js

Forever restarts your app when it crashes or stops for some reason. To restrict restarts to 5 you could use:
forever -m5 server.js

To list all running processes:
forever list

Note the integer in the brackets and use it as following to stop a process:
forever stop 0

Restarting a running process goes:
forever restart 0

If you're working on your application file, you can use the -w parameter to restart automatically whenever your server.js file changes:
forever -w server.js

A: You could simply use this
nohup node /srv/www/MyUserAccount/server/server.js &

This will keep the application running and to shut it down you will have to kill it.
For that you could install htop and then search for node and then kill it

A: forever package worked for me, just one thing, it depends on deep-equal, so if you had issue with installing it like:
npm -g install forever

Try:
npm -g install forever deep-equal@1.1.1

instead.

A: As we know that there are many options to do this. Here is a pure Shell solution, with no need for extra programs / packages.
This solution will restart server.js if it crashes for some reason / errors.
Let's say this is a run.sh:
#!/usr/bin/env sh

while :; do
    node server.js

    echo "Restarting..."
    sleep 1
done

Make sure to make the run.sh file executable:
chmod +x run.sh

And to run it:
./run.sh

If you want to run it in the background:
./run.sh &

Run in the background super-silently (detached, without any output):
( ./run.sh > /dev/null 2>&1 & )

A: Although the other answers solve the OP's problem, they are all overkill and do not explain why he or she is experiencing this issue.
The key is this line, "I close putty, then I cannot reach the address"
When you are logged into your remote host on Putty you have started an SSH linux process and all commands typed from that SSH session will be executed as children of said process.
Your problem is that when you close Putty you are exiting the SSH session which kills that process and any active child processes.  When you close putty you inadvertently kill your server because you ran it in the foreground.  To avoid this behavior run the server in the background by appending & to your command:
node /srv/www/MyUserAccount/server/server.js &

The problem here is a lack of linux knowledge and not a question about node.  For some more info check out: http://linuxconfig.org/understanding-foreground-and-background-linux-processes
UPDATE:
As others have mentioned, the node server may still die when exiting the terminal.  A common gotcha I have come across is that even though the node process is running in bg, it's stdout and stderr is still pointed at the terminal.  This means that if the node server writes to console.log or console.error it will receive a broken pipe error and crash.  This can be avoided by piping the output of your process:
node /srv/www/MyUserAccount/server/server.js > stdout.txt 2> stderr.txt &

If the problem persists then you should look into things like tmux or nohup, which are still more robust than node specific solutions, because they can be used to run all types of processes (databases, logging services, other languages).
A common mistake that could cause the server to exit is that after running the nohup node your_path/server.js & you simply close the Putty terminal by a simple click. You should use exit command instead, then your node server will be up and running.

A: I recommend use PM2, which is a process manager for Node.js applications. PM2 provides an easy way to manage and daemonize applications (run them as a service).
refer this link - https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-centos-7

A: Forever is a very good NodeJs module to do exactly that.
Install forever by typing in the command line
$ npm install forever -g

Then use the following command to run a node.js script
$ forever start /path/to/script.js

You are good to go. Additionally you can run
$ forever list

to see all the running scripts. You can terminate any specific script by typing
$ forever stop [pid]

where [pid] is the process ID of the script you will obtain from the list command. To stop all scripts, you may type
$ forever stopall

A: Installation
$ [sudo] npm install forever -g

You can use forever to run scripts continuously
forever start server.js

forever list

for stop service
forever stop server.js

A: During development, I recommend using nodemon. It will restart your server whenever a file changes. As others have pointed out, Forever is an option but in production, it all depends on the platform you are using.
You will typically want to use the operating system's recommended way of keeping services up (e.g. http://www.freedesktop.org/wiki/Software/systemd/).

A:
nohup working i checked in AWS Ubunto vm follow the correct syntax

ubuntu@ip-172-00-00-00:~/ms$ nohup node server.js &

then press enter you will see this line

ubuntu@ip-172-00-00-00:~/ms$ nohup: ignoring input and appending output to 'nohup.out'

then type this

rm nohup.out

A: You can use PM2, it's a production process manager for Node.js applications with a built-in load balancer.
Install PM2
$ npm install pm2 -g

Start an application
$ pm2 start app.js

If you using express then you can start your app like
pm2 start ./bin/www --name="app"

Listing all running processes:
$ pm2 list

It will list all process. You can then stop / restart your service by using ID or Name of the app with following command.
$ pm2 stop all
$ pm2 stop 0
$ pm2 restart all

To display logs
$ pm2 logs ['all'|app_name|app_id]

A: Here's an upstart solution I've been using for my personal projects:
Place it in /etc/init/node_app_daemon.conf:
description "Node.js Daemon"
author      "Adam Eberlin"

stop on shutdown

respawn
respawn limit 3 15

script
  export APP_HOME="/srv/www/MyUserAccount/server"
  cd $APP_HOME
  exec sudo -u user /usr/bin/node server.js
end script

This will also handle respawning your application in the event that it crashes. It will give up attempts to respawn your application if it crashes 3 or more times in less than 15 seconds.

A: First install pm2 globally
npm install -g pm2

then start
pm2 start bin/www


text:
Q: show progress-bar while downloading table row from sql server in android
I am fetching table row from sql server in android and i want to display in progress-bar but i am facing problem.I am using SQL Connection class which not allowing to take length of a table row.my connection classs.

String ip="192.168.43.85";
String classs="net.sourceforge.jtds.jdbc.Driver";
String db="mydatabasename";
String uname="myname";
String pass="pass";

@SuppressLint("New Api")
public Connection CON() throws IOException{

    StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Connection connection=null;
    String ConUrl=null;

    try {

        Class.forName(classs);
        ConUrl="jdbc:jtds:sqlserver://"+ip+";"
                + "databaseName="+db+";user="+uname+";password="
                +pass+";";
        connection= DriverManager.getConnection(ConUrl);

    } catch (ClassNotFoundException e) {
        Log.e("ERRO",e.getMessage());

    } catch (SQLException e) {
        Log.e("ERROR",e.getMessage());
    } catch (Exception e) {
        Log.e("ERROr", e.getMessage());
    }

    return connection;
}

I tried some examples from google but all examples uses http and url but i don't have url to find length.
    Connection conn = null;
    try {
        conn = connectionClass.CON();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (conn == null) {

        Toast.makeText(getApplicationContext(), "Error in Connection with server.Make sure your internet connection is ON", Toast.LENGTH_SHORT).show();
    } else {

        Statement stmt = null;

        try {
            //String Slqquery = "select * from Zmat";
            String Slqquery1 = "select GlobalSummaryReportFlag,StudyID,StoreCode,StudyDesc from GlobalCountSummaryReport where GlobalSummaryReportFlag='1' and StudyId='" + strStudyId1 + "' and StoreCode='" + strStudyCode2 + "' and StudyDesc='" + strStudyDes3 + "'";

            stmt = conn.createStatement();
            ResultSet rs3;
            rs3 = stmt.executeQuery(Slqquery1);
            if (rs3.next()) {

                progress1=new ProgressDialog(MenuActivity.this);
                progress1.setMessage("Downloading GC");
                progress1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progress1.setIndeterminate(true);
                progress1.setProgress(0);
                progress1.setMax(100);
                progress1.show();
        final int totalProgressTime = 100;
        new Thread(new Runnable() {
            @Override
            public void run() {
                int jumpTime = 0;

                while(jumpTime < totalProgressTime) {
                    try {
                        Data();
                        if (countForHireMapping == 0 || CountForArticle == 0) {
                            Toast.makeText(getApplicationContext(), "Downloaded UnSuccessfully Please Retry", Toast.LENGTH_SHORT).show();
                            delete2();
                            progress1.dismiss();
                        } else {

                            sleep(200);
                            jumpTime += 5;
                            progress1.setProgress(jumpTime);
                            progress1.dismiss();
                            Intent intent = new Intent(MenuActivity.this, LocationActivity.class);
                            startActivity(intent);
                            Toast.makeText(getApplicationContext(), "Downloaded Successfully", Toast.LENGTH_SHORT).show();
                        }

                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }).start();

            } else {
                Toast.makeText(getApplicationContext(), "Gc Not Completed", Toast.LENGTH_SHORT).show();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }`

A: You should use AsyncTask in your MainActvity
It contains 3 methods:

*

*onPreExecute(): Inside this method place whatever you want to do before the class is executed.(In your case a progressBar )

*doInBackground(): Inside this method place whatever you want the app to do in background.(Example: getting data from server)

*onPostExecute(): Inside this method, place whatever you want to do once the background process is done. (Example: Setting the views according to the received data from online server)
Here is a tutorial to get you upto speed on AsyncTask.
Happy coding.


text:
Q: Area under the ROC curve accuracy Why is the area under the ROC curve better than raw accuracy as an out-of- sample evaluation metric?

A: In a short answer we could say the following. It's not better per se, but what we can say more correctly is that it is a general representation of wrong/right classification percentages of the model for any given cutoff chosen. As such it allows to evaluate the discriminatory power of the model regardless the choice of a specific cutoff.
The representation of the model accuracy via contingency tables (and the related statistics) depends on the chosen cutoff, based on which, in a binary classification model, you can draw a contingency table with the percentages of true positives, false positives, true negatives and false negatives. So for your model, you choose a cutoff and, based on that, you draw a table showing the 1-specificity and sensitivity of the model (and their complements to 1).
On the contrary the ROC curve plots the same concepts of 1-specificity ($x_{i}$) and sensitivity ($y_{i}$) for each given cutoff i on a $(x_{i},y_{i})$ coordinate system assuming that for each point in the plot the cutoff varies (so each point in the graph represents de facto the results in the contingency table obtained assuming that the cutoff is i). As you can see it can be considered a generalization of the contingency table approach for a generic i that is allowed to vary in the ROC plot. Therefore it allows to analyze the classification performance of the model (and the trade-off of specificity vs sensitivity) regardless the specific cutoff that you choose, thus segregating the two distinct important problems of choosing a good classification model per se (for any give cutoff), and then choosing a good cutoff. The AUC is just a numerical representation of the area under the ROC allowing to put the overall performance described by the ROC in a synthetic numerical form.


text:
Q: JetBrains Rider - Pytest 'chromedriver must be in Path' from IDE configuration only I recently upgraded to macOS 12 Monterey and my run configuration for python seems to have borked and I cannot seem to find the right magic buttons. It has been working fine until the upgrade.
I have a run configuration that runs pytest <test-path>
When I run it I get this exception
if err.errno == errno.ENOENT:
>               raise WebDriverException(
                   "'%s' executable needs to be in PATH. %s" % (
                       os.path.basename(self.path), self.start_error_message)
E                       selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://chromedriver.chromium.org/home

venv/lib/python3.9/site-packages/selenium/webdriver/common/service.py:81: WebDriverException

if I run pytest <test-path> from the terminal, works like a dream. I am running from a virtual env, but if I which chromedriver from the venv or not, I see the directory - I can run chromedriver by name in venv or not.
(venv) me ~/Documents/project(main)* $ which python3
/Users/me/project/venv/bin/python3

the run configuration in Rider is pointed to this same python interpreter
What gives, where is $PATH getting lost in this mix?

A: You can directly put the executable path in your code like this and that work perfectly:
from selenium import webdriver

# put the executable path
driver = webdriver.Chrome(executable_path="path/to/chromedriver.exe")


text:
Q: How to change sequelize model.findOne() target table? I am new to sequelize.js. I have one model User. I try to use findOne function to check whether the user is existed or not.
This is my user model.
const Sequelize = require('sequelize')
const db = require('../database/db.js')

module.exports = db.sequelize.define(
  'user',
  {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: Sequelize.STRING
    },
    email: {
      type: Sequelize.STRING
    },
    username: {
      type: Sequelize.STRING
    },
    password: {
      type: Sequelize.STRING
    },
    address: {
      type: Sequelize.STRING
    },
    created: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW
    },
    role: {
      type: Sequelize.STRING
    }
  },
  {
    timestamps: false
  }
)

This is how I check the user.
const express = require('express')
const users = express.Router()
const cors = require('cors')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')

const User = require('../../models/User')
users.use(cors())

process.env.SECRET_KEY = 'secret'

users.post('/register', (req, res) => {
    console.log("testing register zzz");
  const today = new Date()
  const userData = {
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password,
    address: req.body.address,
    created: today,
    role: req.body.role
  }

  User.findOne({
    where: {
      email: req.body.email
    }
  }).then(user => {
      if (!user) {
          console.log("not inside database");
        bcrypt.hash(req.body.password, 10, (err, hash) => {
          userData.password = hash
          User.create(userData)
            .then(user => {
              res.json({ status: user.email + 'Registered! liao' })
            })
            .catch(err => {
              res.send('error: ' + err)
            })
        })
      } else {
          console.log("inside database");
        res.json({ error: 'User already exists' })
      }
    })
    .catch(err => {
        console.log("??????  "+err);
      res.send('error: ' + err)
    })
})

However, I received an error show me that table users does not exist. The table name in mysql database is user. How to change the findOne target table name so that findOne function search the user table instead of users table?

A: You can set freezeTableName attribute of a model to true to disable pluralization of model names that sequelize does by default.
Please refer to the following example given in sequelize docs
var User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING,
    field: 'first_name' // Will result in an attribute that is firstName when user facing but first_name in the database
  },
  lastName: {
    type: Sequelize.STRING
  }
}, {
  freezeTableName: true // Model tableName will be the same as the model name
});


text:
Q: Find the deepest-nested children elements of each element in an xml tree I am trying to find the deepest-nested children element of each element in an xml tree. I am currently using the lxml library, specifically etree.
I am using the following xml code as an example:
<item>
  <a1>value1</a1>
  <a2>value2</a2>
  <a3>value3</a3>
  <a4>
    <a11>value222</a11>
    <a22>value22</a22>
  </a4>
</item>

I would like the output to show that the a1, a2 and a3 elements have no child elements and that a11 and a22 are the deepested nested children of the a4 element.

A: XPath
Basically you'd like to see all elements whose list of child elements is empty.
An empty list in XPath can be converted to false. So the XPath expression you want to resolve could be (not tested):
//*             -> deliver any element
//*[*]          -> deliver any element that has children
//*[*=false]    -> deliver any element that has no children

Also see How to use XPath in Python?
Custom
You can parse the document into a DOM tree, then traverse that tree and list all nodes where getChildNode() returns a list that does not contain any further element.


text:
Q: Table Column structure decimal I want to store rating values into my table as is.
Ratings are from 0.0 to 5.0 (using rateYo jQuery plugin)
My rating column is decimal(3.2)
But whenever I try to insert a rating value with decimal points it will get rounded down. 3.5 = 4.
Or should I just leave it as is?
Will I still be able to get an accurate average rating if all individual ratings are rounded down when inserted into the table?
3.4 + 3.6 / 2 = 3.5 = 4
3 + 4 / 2 = 3.5 = 4
so its still the same but that's only for 2 ratings. What if there were hundreds of them with random values (3.22, 3.5, etc.)

A: Your field is defined as decimal(3.2) mysql does not throw an error on this 'invalid' (quoted because this may be what you intended) definition (it probably should be 3,2) but seems to treat it like an integer.
If a number is inserted into an exact type column (DECIMAL or integer), it is inserted with its exact value if it is within the column range.
If the value has too many digits in the fractional part, rounding occurs and a warning is generated. Rounding is done as described in Section 12.21.4, "Rounding Behavior" - https://dev.mysql.com/doc/refman/5.7/en/precision-math-expressions.html https://dev.mysql.com/doc/refman/5.7/en/precision-math-rounding.html


text:
Q: Any unix utility/tool to auto backup files before saving? I would like to know if there is any existing unix utility or tool that would make a backup of a file with a date/timestamp appended to the filename.
Basically I am looking to automatically make backup of my config files like the .bashrc, .vimrc, etc when I change the file and save using some text editor.
vim specific solution would also be helpful. May be adding some kind of hook only for specific files that creates a copy of the previously saved file and then goes on to save the currently modified file.

A: I'm using a simple backup scheme that appends a .YYYYMMDD[a-z] extension, too.
For that, I've written a set of Vim plugins and scripts: The writebackup plugin defines a :W[riteBackup] command in Vim that makes a backup of the current file.
With the writebackupAutomator plugin, you can have Vim make the backup automatically.
And the writebackupVersionControl plugin offers you additional commands from "real" version control systems, like diffing and moving through history.
In addition to the Vim plugins, I also provide the basic writebackup functionality outside of Vim as VBScript and Bash Shell script versions on my personal website; maybe those are helpful to you or at least provide a starting point!

A: You can configure Vim to make backups automatically in various ways. For example, I think you could hook into the writebackup plugin for certain file groups.
The CopyFS filesystem keeps copies of all old versions of the files stored on it.
But I don't recommend either of these approaches. The best way to keep backups of old file versions — which is a good thing — is to keep them under version control. A simple version control system such as CVS takes about ½ hour to set up. A more modern and more powerful, but more complex system such as Bazaar or Git or Mercurial might take a whole hour. Spend an afternoon setting them up and learning the basic commands, you won't regret it.


text:
Q: SimpleXML: Get Child of Parent with Specific Attribute I'm trying to extract get the PageViews % for 'US' only and I'm having trouble setting up the xpath for it.  Any ideas?
<aws:TrafficData>
<aws:DataUrl type="canonical">jobdiagnosis.com/</aws:DataUrl>
<aws:RankByCountry>
  <aws:Country Code="IN">
    <aws:Rank>54968</aws:Rank>
    <aws:Contribution>
      <aws:PageViews>0.46%</aws:PageViews>
      <aws:Users>0.46%</aws:Users>
    </aws:Contribution>
  </aws:Country>
  <aws:Country Code="US">
    <aws:Rank>703</aws:Rank>
    <aws:Contribution>
      <aws:PageViews>78.11%</aws:PageViews>
      <aws:Users>77.39%</aws:Users>
    </aws:Contribution>
  </aws:Country>
</aws:RankByCountry>

xpath('//Country[Code="US"]//PageViews')

A: All of the elements in your document are in some namespace so you need to register a prefix for that namespace URI and use that prefix in every step of your XPath expression where you refer to element names. The registered prefix doesn't have to match the one used in your document, but the namespace URI must match.
Assuming you have read the XML into variable $xml
$xml->registerXPathNamespace("aws", "http://that.namespace.uri");
$pageviews = $xml->xpath('//aws:Country[@Code="US"]/*/aws:PageViews');

A: try this:
xpath('//Country[Code="US"]//PageViews')

instead of this:
xpath('//Country[Code="US"]//PageView')

UPDATE
try this:
xpath('/Country[@Code="US"]/PageViews']

A: mind the namespace (aws):
$pageviews = $xml->xpath('//aws:Country[@Code="US"]/Contribution/PageViews');

Or use http://www.php.net/manual/en/simplexmlelement.registerxpathnamespace.php

A: Thanks for the assistance everyone, but I was still unable to get this to work using xpath. Decided to resort to looping through the 'Rank by Country' array until it found 'US'. Not ideal but it will work for my needs. Thanks again!


text:
Q: MySQL equivalent of WITH in oracle Is there a MySQL equivalent of the WITH clause in Oracle?

A: That will work but it's a pity it won't provide the advantage of using the WITH clause, that is not to execute the same query several times (with complex queries could be reaaaally slow and very demanding for the database engine; I suffered it).
I would suggest inserting each SELECT defined in the original WITH clause into its own temporary table, and use them inside the query.
In MySQL, the temporary table will drop itself once the user session ends.
EDIT:
I just saw this answer in a similar thread which clearly exposes the 3 workarounds with MySQL:

*

*TEMPORARY tables

*DERIVED tables

*inline views (effectively what the WITH clause represents - they are interchangeable)

https://stackoverflow.com/a/1382618/2906290
and an example of MySQL procedure which creates and drops the temporary tables in case you continue with your session and want to free those resources
(I would use it just as an example of the syntax):
https://stackoverflow.com/a/5553145/2906290

A: There is not. Unless (until) one develops it (MySQL is open-source, anyone can contribute.)
The ANSI/ISO SQL WITH keyword is used to define Common Table Expressions (CTEs) and it simplifies complex queries with one or several nested references. It's available in Oracle, Postgres, SQL-Server, DB2 but not in MySQL.
The final query may have references (usually in the FROM clause but they could be in any other part) to anyone of the common table expressions, one or more times. The query can be written (without CTEs) in MySQL using derived tables but the references have to be made repeatedly.
Example of a silly query showing all persons born in the 50s and in the month of July and the number of all persons born in the same year:
WITH a AS
    ( SELECT name, birthdate, YEAR(birthdate) AS birthyear
      FROM persons
      WHERE birthdate >= '1950-01-01' AND birthdate < '1960-01-01'
    )
, b AS
    ( SELECT birthyear, COUNT(*) AS cnt
      FROM a
      GROUP BY birthyear
    )
SELECT a.name, a.birthdate, b.cnt AS number_of_births
FROM a JOIN b
  ON a.birthyear = b.birthyear
WHERE MONTH(a.birthdate) = 7 ;

In MySQL, it could be written as:
SELECT a.name, a.birthdate, b.cnt AS number_of_births
FROM
    ( SELECT name, birthdate, YEAR(birthdate) AS birthyear
      FROM persons
      WHERE birthdate >= '1950-01-01' AND birthdate < '1960-01-01'
    ) AS a
  JOIN
    ( SELECT birthyear, COUNT(*) AS cnt
      FROM
        ( SELECT name, birthdate, YEAR(birthdate) AS birthyear
          FROM persons
          WHERE birthdate >= '1950-01-01' AND birthdate < '1960-01-01'
        ) AS aa
      GROUP BY birthyear
    ) AS b
  ON a.birthyear = b.birthyear
WHERE MONTH(a.birthdate) = 7 ;

Notice the duplication of code for the derived table a. In more complex queries, code would have to be written multiple times.


text:
Q: Scraping an aspx site with HtmlUnit, how does one click on a Javascript button? I'm attempting to scrape an .aspx site, which is a essentially just a big paginated table along the lines of the one found here: http://data.fingal.ie/ViewDataSets/ (Note, the actual site I'm scraping is behind a paywall, so can't post the actual link ).
However, the problem is that rather than each page of the table having a unique url, the table changes pages by posting to itself, and then updating the content inside of the table.
The next page button looks like this:

How would I simulate a click on this button using HtmlUnit?

A: You would want to find the
.
The easiest way of doing this would be using xPath:
final WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("http://<<YOUR URL HERE>>");

final HtmlDivision div = page.getFirstByXPath("//div[@class='dpxButton']");
page = div.click();
// This returns the page shown after the click

This will perform the click. I assume that it is loaded through AJAX, in which case you may want to use:
while(some new element doesn't exist; or some 'completed' condition) {
    // Wait for javascript to catch up.
    webClient. waitForBackgroundJavaScript(1000);
}


text:
Q: How To Install dompdf (HTML to PDF converter for PHP5) on MAMP on a Mac? How do I install the dompdf convertor (https://github.com/dompdf/dompdf) on my localhost using MAMP on my MAC computer?
I downloaded the dompdf folder to my computer but I have no idea what to do next? Do I simply copy it to a certain folder in my MAMP application folders?
The instructions on dompdf's git site says: "Download an archive of dompdf and extract it into the directory where dompdf will reside". Where should dompdf reside?


text:
Q: Beans added dynamically are not considered by ConditionalOnBean I am registering beans dynamically at startup with BeanDefinitionRegistryPostProcessor:
Bean class:
@RequiredArgsConstructor
public class DynamicBean {

    private final String name;
    private final Object value;

}

Properties class:
@Data
public class DynamicProperties {
    private List<Bean> beans;

    @Data
    public static class Bean {
        private String name;
        private Object value;
    }
}

BeanDefinitionRegistryPostProcessor:
@Configuration
public class DynamicBeanRegistrar implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        DynamicProperties dynamicProperties = Binder.get(environment)
                .bind("dynamic", Bindable.of(DynamicProperties.class))
                .orElseThrow(IllegalStateException::new);

        dynamicProperties.getBeans().forEach(bean -> {
            GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
            beanDefinition.setBeanClass(DynamicBean.class);

            String beanName = bean.getName();

            ConstructorArgumentValues cav = new ConstructorArgumentValues();
            cav.addGenericArgumentValue(bean.getName());
            cav.addGenericArgumentValue(bean.getValue());
            beanDefinition.setConstructorArgumentValues(cav);

            beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinition);
            log.info("Registered dynamic bean")
        });
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        // noop
    }
}

I also have another configuration class using @ConditionalOnBean annotation for some beans:
@Configuration(proxyBeanMethods = false)
public class AnotherConfiguration {

    @Bean
    public Object a() {
        return new Object ();
    }

    @Bean
    public Object b() {
        return new Object ();
    }

    @Bean
    @ConditionalOnBean(DynamicBean.class)
    public Object x() {
        return new Object();
    }

    @Bean
    @ConditionalOnBean(DynamicBean.class)
    public Object y() {
        return new Object();
    }
}

The problem is that the @ConditionalOnBean annotation doesn't seem to know about the dynamically registered beans and is therefore evaluating as false, causing beans x and y not to be created.
I have tried using @AutoConfigureBefore(AnotherConfiguration.class) on my DynamicBeanRegistrar as well as implementing PriorityOrdered, but that didn't seem to have any effect.
Is there any way to achieve the expected behaviour?


text:
Q: iPhone: Reassignment of instance variable = deallocation? I have an instance variable NSMutableArray* searchResults.
First, I initialize it:
self.searchResults = [[NSMutableArray alloc] init];

Then, at the course of my app, it gets reassigned frequently:
NSMutableArray* results = [searcher getResults];
self.searchResults = results;

My question is will this cause a memory leak because the array it pointed to previously may not get deallocated during this reassignment? Do I explicitly need to do this:
NSMutableArray* results = [searcher getResults];
self.searchResults = nil;
self.searchResults = results;

Of course, I release it in dealloc, and set it to nil in viewDidUnload.

A: If the @property was declared with retain or copy and it was created by @synthesize, there is no memory leak. If that is not the case, you could have one, depending on the implementation of the method.

A: Well, you may have a memory leak, but not for the reasons you think.  The answer depends on how your property was declared, and whether you're releasing the object after you allocate it.
When declaring a property that your object owns (as opposed to something like a delegate, which is owned by a different object), you typically declare it like this:
@property (nonatomic, retain) NSMutableArray *searchResults;

I'm assuming this is how your property is declared.  The retain clause of that declaration means that an object will automatically be retained whenever it is assigned through this property's setter method (i.e. either through self.searchResults = foo or [self setSearchResults:foo];).
If the property already references an existing object, then the retain clause causes that existing object to be automatically released when the property gets reassigned.  So setting self.searchResults = nil; prior to doing another assignment does indeed cause that existing object to be released, but this really isn't necessary because self.searchResults = results; also releases any existing object before it retains and stores the new reference.
You may have a memory leak on this line:
self.searchResults = [[NSMutableArray alloc] init];

After this line, your retain count is +2.  It got +1 for the alloc, and +1 for the property assignment.  This creates a memory leak, unless you have [self.searchResults release] elsewhere in your method.  The way I'd fix it is like this:
self.searchResults = [[[NSMutableArray alloc] init] autorelease];

Whenever you're confused about memory management, it's always worthwhile to go back and reread the Memory Management Programming Guide.

A: if you have declared the property as retain, for self.searchResults, you should assign an autoreleased instance. i.e.
header file:
@property(nonatomic,retain)NSMutableArray *searchResults;

implementation file:
@synthesize searchResults;
self.searchResults=[[[NSMutableArray alloc] init] autorelease];

if you have a synthesise a property with retain, it will create setters and getters for you.
self.searchResults will call a function something like this:
-(void)setSearchResults:(NSMutableArray *)array{
    if(searchResults!=array){
        [searchResults autorelease];
        searchResults = [array retain];
    }
}

so you can do this without having to worry:
self.searchResults=[searcher getResults];


text:
Q: How can I customize a SharePoint Page with no left-side navigation and Search on top? I need to create the layout bellow in SharePoint Online.
Please notice this requirements:

*

*There should be no left side navigation.

*The Search functionality should be on the top right corner.

*The page should be responsive so that, in small screens, web parts that are side-by-side should get on top of each other instead.

A: *

*There should be no left left side navigation.
= You can change it by, clicking on gear, change the look then at the bottom you see the classic change the look option, click it, you will be redirected to the classic page on changing the looks option, click the current layout, then at the left side, you can see a dropdown option for site layout, change the 'Seatle' to 'Oslo' then save it, see the update in the site.

*The Search functionality should be on the top right corner.
= Im not sure if this is doable in modern, you can create a custom webpart dedicated for this piece via spfx webpart but it would be a bit overkill

*The page should be responsive so that, in small screens, web parts that are side-by-side should get on top of each other instead.
= Modern sharepoint will do this for you. You can also test it out in their SharePoint App, its in the apps store.
Let me know if the concept helps, happy learning!


text:
Q: Classification of, Information Regarding Particular Family of Polyhedra: Let $n\ge4$. Let $n$ vertices be distributed on a spherical boundary. Let the vertices lie on this boundary as would electrons on a spherical boundary. That is, they are distributed "equally" by electron repulsion.
Let $P$ be the convex polyhedron formed by connecting the vertices to their sphere-distance nearest neighbor vertices. P is an $n$-vertex approximation to a sphere. At $n\to\infty$, P is a sphere.
Below is an example with n = 30. The faces are not drawn, but an edge between every vertex triplet is drawn. This should at least provide some visualization of the shape I am describing.

I am looking for a name and/or information for/regarding this family of polyhedra. Alternatively, any tips with regards to my problem, below, would be appreciated.
Motivation: I am working on a software project in which it has become necessary to quickly graph polyhedra of this type. I am able to generate the vertices, but the only algorithm which I am able to discover to graph these polyhedra takes $O(V^{3})$ time. But, this draws every single face possible between extra triplet of vertices. The majority of these faces are inside of the shape and so are invisible. I expect that if I could learn more about these types of polyhedra that I should be able to realize an algorithm which only draws the outer faces, resulting in a much faster software solution.
Note: I did ask about this on StackOverflow before, but my question was not answered.

A: Given that all your points lie on a sphere, the polyhedron you want should be convex, so you can find it by computing the convex hull of the points. There are efficient $O(n\log n)$ algorithms for doing so, and lots of software available.
This is pretty much independent of the particular scheme by which you arranged these points, which is known as the Thomson problem.
(By the way, your statement that the polyhedron is "formed by connecting the vertices to their sphere-distance nearest neighbor vertices" is incorrect: this procedure would only give you a tree, not a polyhedron.)


text:
Q: Rails 4 + Postgresql - Joins table with 2 conditions I need to list Inputs that have Translations with language_id = 1 and dont have Translations with language_id = 2
My current scope is:
scope :language, -> (id){joins(:translations).where('translations.language_id = 1)}

Models:
class Input < ActiveRecord::Base
  has_many :translations
  has_many :languages, through: :translations
  scope :language, -> (id) {joins(:translations).where('translations.language_id = 1')}

  def translation_from_language(language)
    self.translations.where(language: language).take
  end
end

class Translation < ActiveRecord::Base
  belongs_to :input
  belongs_to :language
  before_save :default_values

  #Apenas para testar o scope de search
  scope :search, -> (part) { where("LOWER(value) LIKE ?", "%#{part.downcase}%") }

  # Se nao setar um input manualmente, irá criar um novo
  def default_values
    self.input ||= Input.create
  end
end

class Language < ActiveRecord::Base
  has_many :translations
  has_many :inputs, through: :translations
end

A: So my solution is just create a query like
Input.where("id IN ( SELECT input_id
                     FROM translations
                     WHERE language_id = 1
                   )
             AND id NOT IN (
                     SELECT input_id
                     FROM translations
                     WHERE language_id = 2
                   )")


text:
Q: How to disable 'contentDescription' warning on gradle with lintOptions? I would like to disable this warning:

[Accessibility] Missing 'contentDescription' attribute on image

I know the solution android:contentDescription:"@null". But I want to be able to do the entire project and not on each of my ImageView.
On documentation of tools android, they advocate to do it like this:
android {
    lintOptions {
        disable 'TypographyFractions','TypographyQuotes'
        ...
    }
}

My question is what is the name of lint options for this warning "contentDescription attribute on image"?

Edit, My Solution:
Click on Suppress with @SuppressLint (Java) or tools:ignore (XML)
This button add this on your <ImageView .. />:
tools:ignore="ContentDescription"

So you just need to add this lintOptions on your build.gradle:
android {
    lintOptions {
        disable 'ContentDescription'
    }
}

A: I think you can disable it in your gradle config as well.
You can find a list of Lint issues here. If you check it the you can see that it contains the TypographyFractions and it contains also the ContentDescription. Please note that I didn't try them but I think it should work.
So in my opinion you should do it in the following way:
android {
    lintOptions {
        disable 'ContentDescription'
        ...
    }
}

A: If not mistaken, you can disable them using Android Studio Preferences settings as follows:
Windows -> Preferences -> Inspection -> Uncheck "Image Without Content Description"
Try this tutorial to see how he has forced it to be converted to error. May be altering things here would fix it for you.


text:
Q: On a Theorem of Lee's book on Differential Geometry The following theorem is from Lee "Introduction to Smooth Manifolds".
Suppose $\widetilde{M}$ is a connected smooth manifold with a discrete group $\Gamma$ acting smoothly, freely and properly on $\widetilde{M}$. Then the quotient map $\pi:\widetilde{M}\to \widetilde{M}/\Gamma$ is a smooth normal covering map.
My question is if the connected assumption on $\widetilde{M}$ necessary? I do not see if this assumption plays any role in the proof. Secondly, how to show that $\Gamma$ acts trasitively on the fibers of $\pi$ ? My third question is if the covering group of $\widetilde{M}/\Gamma$ and $\Gamma$ are isomorphic? Clearly, each element of $\Gamma$ acts as a Deck transformation on $\widetilde{M}$. Is the other way also true?


text:
Q: Start page from same point when Beamer frame has no title
I am making a presentation using beamer environment in latex. However, one of my slides does not have the frame title (The slide next to slide  no. 17 in this pic). So, what is happening is that the text in slide no. 18 is starting from the place of the frame title above the blue line. However, I want the text in slide no. 18 to start below the blue line. What shall I do to accomplish that?
For the purpose of MWE, and since the template in this pic may  not be available with everyone, so for simplification, I have made another MWE, that does not require any extra template files to run, but has the same problem.
\documentclass[compress]{beamer}
\begin{document}

\section{Introduction to }
\begin{frame}[t]{\bigskip \Large Introduction }
\begin{itemize}
    \item Delay is a
        \item Delay is a
            \item Delay is a    \item Delay is a
                \item Delay is a
                    \item Delay is a
                        \item Delay is a    \item Delay is a    \item Delay is a    \item Delay is a    \item Delay is a
\end{itemize}
\end{frame}

\begin{frame}[t]
\begin{itemize}
    \item Delay is a
    \item Delay is a
    \item Delay is a    \item Delay is a
    \item Delay is a
    \item Delay is a
    \item Delay is a    \item Delay is a    \item Delay is a    \item Delay is a    \item Delay is a
\end{itemize}
\end{frame}

\end{document}

A: Workaround: use just the \bigskip as title for frames that do not have a real title.
\documentclass[compress]{beamer}
\begin{document}

\section{Introduction to }
\begin{frame}[t]{\bigskip \Large Introduction }
\begin{itemize}
    \item Delay is a
        \item Delay is a
            \item Delay is a    \item Delay is a
                \item Delay is a
                    \item Delay is a
                        \item Delay is a    \item Delay is a    \item Delay is a    \item Delay is a    \item Delay is a
\end{itemize}
\end{frame}

\begin{frame}[t]{\bigskip}
\begin{itemize}
    \item Delay is a
    \item Delay is a
    \item Delay is a    \item Delay is a
    \item Delay is a
    \item Delay is a
    \item Delay is a    \item Delay is a    \item Delay is a    \item Delay is a    \item Delay is a
\end{itemize}
\end{frame}

\end{document}


text:
Q: Can an XML Schema defined tag have different constraints based on data type? I'm working on a custom XML format that involves a formatted list of points. We would like to support multiple types of coordinates systems, such as Cartesian and Spherical. Can this be done?
Example:
<point type="cartesian">
<c1>5.0</c1>
<c2>5.6</c2>
<c3>9.1</c3>
</point>
<point type="spherical">
<c1>5.0</c1>
<c2>5.6</c2>
<c3>9.1</c3>
</point>

Where there are automatically bounds for the spherical coordinates keeping c1 positive, and c2,c3 in the range 0 to 2PI. While having no bounds for c1 through c3 in the cartesian version. If this can not be written as a Scheme, can I at least do it this way?
<point type="cartesian">
<c1 type="cartesian">5.0</c1>
<c2 type="cartesian">5.6</c2>
<c3 type="cartesian">9.1</c3>
</point>
<point type="spherical">
<c1 type="spherical">5.0</c1>
<c2 type="spherical">5.6</c2>
<c3 type="spherical">9.1</c3>
</point>

In this case I know I can enforce constraints on an element by it's type, but can I enforce a particular element to have the same type as it's parent?
I hope this is clear enough to get what I am trying to do here. I want to constrain the type of data the c1 through c3 types will accept by setting the type of the point element.

A: No, this is not possible.
On the other hand, you can have sphericalPoint and cartesianPoint elements which extend point. Under some circumstances, you can restrict the types of the child elements, assuming they are a subset of the type of the parent elements. You can also add child elements which did not exist in the base type.


text:
Q: Select2 Multi-Value Select Boxes not displaying correctly EDIT:
I have figured out what my problem was for this perticular issue.
SOLUTION: For this perticular issue I had permission issues. Since I copied the chosen and select2 project folders straight into my application apparently the permissions were incorrect. The solution is either creating the plugin files within your project while developing, or doing a    'chmod 0755 -R select2/'    in terminal given you're using a *nix machine. That was it. It wasn't any conflict issues between chosen and select2 or anything like that.
Original post:
I'm trying to create a clean Multi-Value Select Box using Select2.
I've tried both Select2 and Chosen.js and the results are the same.
The box doesn't display correctly. It displays an old style ugly multi select box like if there wasn't any javascript involved.
Here is an image showing how it displays: http://d.pr/i/bUa5
What I'm trying to get is a multi select box like the one in this forum.
Hope someone can help?
Here is my test code:
<!doctype html>
<head>
<title>Select2 Example</title>
<link href="select2.css" rel="stylesheet"/>
<link rel="stylesheet" href="chosen/chosen.css">
</head>
<body>
<form>

    <select id="e1" multible>
        <option value="AL">Alabama</option>
        <option value="AR">Arizona</option>
        <option value="CA">California</option>
        <option value="WS">Wisconsin</option>
        <option value="NY">New York</option>
        <option value="TX">Texas</option>
        <option value="OR">Orlando</option>
    </select>

        <select id="chzn-select" data-placeholder="Choose a country..." style="width:350px;" multiple class="chzn-select" tabindex="4">
        <option value="AL">Alabama</option>
        <option value="AR">Arizona</option>
        <option value="CA">California</option>
        <option value="WS">Wisconsin</option>
        <option value="NY">New York</option>
        <option value="TX">Texas</option>
        <option value="OR">Orlando</option>
    </select>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="select2.js"></script>
<script src="chosen/chosen.jquery.js"></script>

<script>

    $(".chzn-select").chosen();

    $(document).ready(function() { $("#e1").select2(function() {
        placeholder: "Select State"
    }); });
</script>
</body>

A: I've had loads of trouble with this, but managed to get it working.
Differences between my code and yours:
My document ready function is in my head, not my body, also i had just $("#e1").select2(); No inner function.
Have you tried when running in a browser, right clicking and choosing view source and opening up your .js and .css files to make sure they are visible to your html?
Lastly for the select2 you have put multible instead of multiple
I binned chosen as i couldnt get it to work, but select 2 is built on it, so i'd go for that. Also as they are built on one another this could be causing some conflict, so i'd get rid of chosen and try that.
Hope this helps
ps: I have implemented it this way, but now when i remove options from the multiple select, they are gone from my drop down choice and cannot be re-added. The examples for this are not very straight forward, wish there were some simple examples for this useful add on!


text:
Q: Using Entity manager and JPA, returns object only When i run the following code it was return only object list. i want the list in vehicle. what is the error in my code?
My Dao Class Is:
public class VehicleDao {

HibernateTemplate template;
private EntityManager emManager;

@PersistenceContext
public void setEm(EntityManager emManager) {
    this.emManager = emManager;
}
public List<Vehicle> getVehicleDataUsing_Sp()
{
Properties prop= new Properties();
    try {
        InputStream input = new FileInputStream("E:\\spring4AndHibernate5\\src\\Query.properties");
        prop.load(input);
        Query query = emManager.createNativeQuery(prop.getProperty("vehicleQuery"));
        List<Vehicle> list = query.getResultList();
        return list;
        }
}

A: You can't return List<Vehicle> when you have specified the return type as void.
Try this instead:
public List<Vehicle> getVehicleDataUsing_Sp()

And you also need to add a catch block after the try block, like this:
catch(Exception e)
{
}

A: Because it's a native query, it doesn't know what to try mapping it to, unless you tell it.
Try:
Query query = emManager.createNativeQuery(prop.getProperty("vehicleQuery"), Vehicle.class);

A: You either need to define the result class in your native query definition (use resultClass=Vehicle.class where you have defined your named query)
and/or
you need to map the native class when using createNamedQuery (use createNativeQuery(prop.getProperty("vehicleQuery"), Vehicle.class)).


text:
Q: Is the assembly dll signed when we create key and hit 'build'? we are trying to sign an assembly dll from VS2010. To sign, we go to the signing tab and create a new key. Then, build the solution. A DLL is generated.
Has VS already signed this DLL? or do we need to run some coomand like snk on the DLL file?

A:
Has VS already signed this DLL?

Yes, unless you specifically request delay signing.
Note that this means that a configuration which specifies signing requires the key to be present, which doesn't mesh well with the key being a private resource with limited access. Delay signing is one option, but another is to have multiple configurations where some produce signed assemblies and some produce unsigned assemblies. See the Noda Time project file for example, where we have "Release", "Signed Release", "Release Portable" and "Signed Release Portable" (as well as debug configurations). The signed builds are only used when actually releasing a version publicly; most development is performed using the unsignged configurations.


text:
Q: How to limit access to grappelli filebrowser using django auth permissions? I need to restrict user access to filebrowser using permissions. For example, only users with permission "can_upload_files" should be able to see Filebrowser in my custom dashboard.
Is this possible?
Thanks!

A: If the thing you want to accomplish is to simply hide the "Media Management" group from your dashboard, you can use the following conditional in your dashboard.py code:
if context.get('user').has_perm('accounts.can_upload_files'):
    self.children.append(modules.LinkList(
        _('Media Management'),
        column=2,
        children=[
            {
                'title': _('FileBrowser'),
                'url': '/admin/filebrowser/browse/',
                'external': False,
            },
        ]
    ))

Note that this will not actually limit access to the FileBrowser, simply hide the link.

A: This can be done by a middleware. Something like:
from django.http import HttpResponseForbidden

class MediaLibraryAccess(object):
    def process_request(self, request):
        if not request.path.startswith('/admin/media-library'):
            return None
        if request.user and request.user.is_superuser:
            return None
        return HttpResponseForbidden('Access Forbidden')

Do not forget to activate the middleware in your settings.py
MIDDLEWARE_CLASSES = (
       ...
       "myapp.middleware.MediaLibraryAccess",
)

In this example I am checking for superuser but you could easily check for a specific permission...


text:
Q: inserting a document where the value of one key is an array variable I am try to insert a document using the insert(). The document has a key field called ancestors with value as an array of ids. This codes is as follows;
var ids = [];
var fid = db.facultis.find({fname: "Sciences"})._id;
ids.push (fid);
var did = db.departs.find({dname: "Chemistry"})._id;
ids.push (did);
db.programs.insert({ prgname: "B.Sc. Pure Chemistry", ancestors:ids})

When run the code on MONGO shell and find() method it displays the following document.
    {
      "_id" : ObjectId("570b8380d63a4e26124c8c36"),
       "prgname" : "B.Sc. Pure Chemistry",
       "ancestors" : [
            null,
            null
       ],
      "duration" : 4,
    )"

Why are the values of the "ancestors" field all null?

A: The elements of that field are null because you are using the wrong method to get the _id values; you are using find() which returns a cursor to the selected documents in the collection, not the actual document hence when you
try to access the _id property of a cursor object, it returns null.
You most probably want to use the findOne() method which returns a single document that satisfies the specified query criteria, thus you can get the _id field:
var ids = [];
var fid = db.facultis.findOne({fname: "Sciences"})._id;
ids.push (fid);
var did = db.departs.findOne({dname: "Chemistry"})._id;
ids.push (did);
db.programs.insert({ prgname: "B.Sc. Pure Chemistry", ancestors: ids})


text:
Q: WMIC in Linux return [wmi/wmic.c:212:main()] ERROR: Retrieve result data I try to use wmic in java to get device info, and it works success when I use CLI with command wmic -U user%password //192.168.xxx.xx "select name,status from Win32_service" | grep WinRM directly,
I have ask my colleague,and he said the error must be cause by the Cmd String array because String result get a value  [wmi/wmic.c:212:main()] ERROR: Retrieve result data, but I just can't find what's wrong.
Here is my code:
String[] Cmd = new String[]{"wmic", "-U", "user%password", "//192.168.xxx.xx", "\"select name,status from Win32_service\" | grep WinRM"};
        try {
            for (String s : Cmd) {
                System.out.println("Cmmand String:" + s);
            }
            Process proc = null;
            proc = Runtime.getRuntime().exec(linuxCmd);
            proc.getOutputStream().close();

            InputStreamReader ir = new InputStreamReader(proc.getInputStream(), Charset.forName("x-windows-950")); //Using charset "x-windows-950" For the decode of the Traditional Chinese Windows.!!!
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            StringBuilder sb = new StringBuilder();
//                System.out.println("Column Name: " + line);
            while ((line = input.readLine()) != null) {
//                    logger.debug("Result" + input.getLineNumber() + ":" + line);
                sb.append(line.trim()).append("\n");
            }
            String result = sb.toString().trim();
            System.out.println("Result: " + result);
        } catch (Exception ex) {

        }

A: The ERROR occur because it seem grep as part of wmi query,It works after using where instead of grep.


text:
Q: Coefficients of a cubic equation having one positive real root and two complex root with negative real part Let $0 \lt \alpha \lt 1$ and $\beta,\gamma \gt 0$. Let $p(x) =x^{3}-\gamma x^{2}-\alpha x-\frac{\beta }{\gamma }$.
Can we choose $\alpha ,\beta ,\gamma $ such that $p(x)$ has one positive real root and two conjugate complex roots with negative real part?

A: Given cubic polynomial $p(x)$ with coefficients as shown,Descartes Rule of Signs tells us there will be one positive root and either two or no negative roots.  If only one real root exists, then of course a conjugate pair of complex roots must exist.
So what is required is to choose:
$$ p(x)=(x-r)(x^2 + bx + c) $$
in a compatible way, i.e. that $r \gt 0$, that the quadratic factor above has a conjugate pair of roots with negative real part, and that the expanded product has coefficients as prescribed.
The conjugate pair of roots is guaranteed by a negative discriminant, $b^2 \lt 4c$, while their real part being negative implies $b \gt 0$.  For the rest let's multiply out:
$$ p(x) = x^3- (r-b)x^2- (rb- c)x- rc $$
We've already deduced that $r$ and $c$ are positive, so a negative constant term of $p(x)$ is certain.
Likewise for the coefficient of $x^2$ to have the proper sign means $b \lt r$.  Finally we want $0 \lt rb- c \lt 1$ to meet the condition on $\alpha$ the coefficient of $x$.
It's not hard to find a suitable choice for $r,b,c$.  Taking $b = 1$, we need $r$ greater than that, say $r = 1.1$.  Then $c$ needs to be big enough to get the negative discriminant but small enough that $\alpha = rb- c$ is between $0$ and $1$.  So $c = 1$ will work:
$$ p(x) = (x-1.1)(x^2 + x + 1) = x^3 - 0.1x^2 - 0.1x - 1.1 $$


text:
Q: How can I create a content slider using JavaScript? I am trying to make a content slider using JavaScript. After looking at examples from Google this is as far as I've gotten:
HTML:

item1

item2

item3

item4

CSS:
.nav {
    position: relative;
    top: 170px;
    width: 1200px;
    height: 200px;
    margin: 10px auto;
    font-family: 'NavFont';
    font-size: 20px;
}
.navItem {
    width: 280px;
    background: #CCB095;
    padding: 100px 0;
    border-radius: 100%;
    float: left;
    margin: 10px;
}
.navItem:hover {
    background: white;
}
.navItem .active {
    background: red;
}
.container {
    width: 1200px;
    height: 700px;
    overflow: hidden;
    position: relative;
    top: 200px;
    margin: 0px auto;
}
.wrapper {
    width: 4800px;
    height: auto;
    position: absolute;
}
.content {
    width: 1200px;
    height: 700px;
    float: left;
}
.item1 {
    background: red;
}
.item2 {
    background: green;
}
.item3 {
    background: blue;
}
.item4 {
    background: yellow;
}

JavaScript:
var links = document.querySelectorAll(".navItem");
var wrapper = document.querySelector(".wrapper");

for (var i = 0; i < links.length; i++) {
    var link = links[i];
    link.addEventListener('click', setPosition, false);
}

addClass(links[0], "active");

function addClass(element, classToAdd){
    var CurrentClassValue = element.className;

    if(CurrentClassValue.indexOf(classToAdd) == -1){
        if ((CurrentClassValue == null) || (CurrentClassValue === "")) {
            element.className = classToAdd;
        }
        else {
            element.className += " " + classToAdd;
        }
    }
}

function removeLinks() {
    for (var i = 0; i < links.length; i++) {
        removeClass(links[i], "active");
    }
}

function removeClass(element, classToRemove) {
    var CurrentClassValue = element.className;

    if (CurrentClassValue.indexOf(classToRemove) != -1) {
        element.className = element.className.replace(classToRemove, "");
        return;
    }

    if(CurrentClassValue.indexOf(classToRemove + " ") != -1){
        element.className = element.className.replace(classToRemove + " ", "");
        return;
    }

    if(CurrentClassValue.indexOf(" " + classToRemove) != -1){
        element.className = element.className.replace(" " + classToRemove, "");
        return;
   }
}

function setPosition (e) {
    removeLinks();

    var clickedLink = e.target;
    addClass(clickedLink, "active");
    var position = clickedLink.getAttribute("data-pos");
    wrapper.style.left = position;
}


text:
Q: In Laravel how do i filter string on reuqest object for all inputs in middleware? Let me explain in details
I want to protect my query string variable for Injection String
URL: http://domainname.com/report?start_date='; SELECT; --
Like as you see in above URL there some unexpected string and i want to trim that while getting that on controller using $request object
Ex: $start_date = $request->get('start_date');
And then i am using this $start_date directly to the query
I don't want to use validator on that how could i do that using middle-ware for all inputs (not specific to only start_date)
Fetch all inputs and strip tags and remove special characters

A: You already have Middlware called TrimStrings it's normally located at
/app/Http/Middlware/TrimStrings.php

After that you can overwrite the function transform so it looks like this
<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;

class TrimStrings extends Middleware
{
    /**
     * The names of the attributes that should not be trimmed.
     *
     * @var array
     */
    protected $except = [
        'password',
        'password_confirmation',
    ];

    protected function transform($key, $value)
    {
        $value = htmlentities($value);
        $value = htmlspecialchars($value);
        $value = $this->myCustomFilteringFunction(); // You can add your function and to whatever you want

        if (in_array($key, $this->except, true)) {
            return $value;
        }

        return is_string($value) ? trim($value) : $value;
    }
}

There is no need to reinvent the wheel this middleware method transform will be called on every field. So everything is being taken care of. Just add your filtering rules.


text:
Q: javascript/youtube api check state for playback restrictions
javascript/youtube api check state for playback restrictions

The problem is that i embed from gdata/youtube-api and sometimes it returns playback
video restrictions or embed not allowed. So i was checking for a state or something
to handle this. i tried adding the &format=5. & tried the -1 event.
With no luck. Any ideas would be greatly appreciated.
    function onPlayerStateChange(event) { if(event.data == -1){//rest of code}}
Thanks in advance.
Edit3/Solution to this problem: as you have the onError set to a function in that function
capture event and check for error was a solution to this problem.
    function onPlayerError(event) {if(event.data === 150 || event.data === 101) {//rest here}}
EDIT: adding more of the code.
EDIT 2: errorcode matching is the answer the only problem now is that i don't
know how to capture just the errorcode any ideas ?
<iframe id="player" type="text/html" width="560" height="50" src="'.$striphttp.'"></iframe>

  var tag = document.createElement('script');
  tag.src = "http://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
      playerVars: { 'autoplay': 1, 'controls': 1,'autohide':1,'wmode':'opaque' },
      //videoId: 'JW5meKfy3fY',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange,
        'onError': onPlayerError
      }
    });
  }

  function onPlayerError(event) {
  window.location.href = "#";

  }

  function onPlayerReady(event) {
    //event.target.mute();
  }

  function onPlayerStateChange(event) {
    if(event.data == 0) {
            window.location.href = "#";
            //location.reload();
    }

}

A: You could load the json data about the video before trying to embed and check the restrictions:
var xmlhttp = new XMLHttpRequest();
var url = 'http://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&q=TJC-subagTg';

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var response = JSON.parse(xmlhttp.responseText);
        console.log(response.data.items[0].accessControl);
        console.log(response.data.items[0].restrictions);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

http://embed.plnkr.co/P6LqDCdPgTH0HiU3SReR/preview


text:
Q: call from web service to another wcf service throwing an error I have one console application (i.e. Project1/Solution1).I am calling one web service (.asmx) from console application which is in separate project (i.e. Project1/Soloution2)
Through single web method there is call to two different business class methods (i.e. Project2/Soloution2) which in turn call two different external wcf services.
I am programmatically creating the endpoint and binding elements to call the wcf methods.
EndpointAddress ed = new EndpointAddress(rtd.WebServiceUrl);
BasicHttpBinding binding = new BasicHttpBinding("BasicHttpBinding_TestService");
ServiceClient client = new ServiceClient(binding, ed);

string response = client.Getdetails(string input1, string input2)

I am getting error "No elements matching the key 'BasicHttpBinding_TestService' were found in the configuration element collection" although I have added this configuration
in my app.config file.
Section in my app.config file
<binding name="BasicHttpBinding_TestService" closeTimeout="00:00:05"
                    openTimeout="00:00:05" receiveTimeout="00:00:15" sendTimeout="00:00:05"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="2047487456" maxBufferPoolSize="524288" maxReceivedMessageSize="2047487456"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="2047487456"
                        maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="Transport">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>

Even I added this in the web.config file where my web method resides (i.e. Project1/Soloution2) and in the calling console application's app.config file.

A: Take a look at the bindings in your web.config files from your external WCF service. The bindings in the Web.config of the WCF application and the app.config of the client application must match in order for that binding configuration to work.


text:
Q: I'm unable to align my Navbar in react js I'm quite new to ReactJS and I just started to make a portfolio web page. I started to make the navigation bar which would contain all the menus. Also, I made use of react-bootstrap.
I've already run the following commands on the terminal:
npm install --save react-bootstrap bootstrap
npm install --save bootstrap
npm install --save react-router-dom

Question 1:
How to get the desired navigation bar? It's not getting aligned to the right although I mentioned it to be 'ml-auto'. I doubt that it is because of the bootstrap issue.
import React from 'react';
import {BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Container from 'react-bootstrap/Container';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import './App.css';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      title: 'Neha Chaudhary',
      headerLinks: [
        {title : 'Home', path : '/'},
        {title : 'Team', path : '/team'},
        {title : 'News', path : '/news'},
        {title : 'About', path : '/about'},
        {title : 'Reach Us', path : '/reachUs'},
        {title : 'Portfolio', path : '/portfolio'}
      ],
      home : {
        title : "Becoming",
        subTitles : "Projects that make a difference",
        text : "Check out my projects below"
      },
      team : {
        title : "Becoming",
        subTitles : "Projects that make a difference",
        text : "Check out my projects below"
      },
      news : {
        title : "Becoming",
        subTitles : "Projects that make a difference",
        text : "Check out my projects below"
      },
      about : {
        title : "Becoming",
        subTitles : "Projects that make a difference",
        text : "Check out my projects below"
      },
      reachUs : {
        title : "Becoming",
        subTitles : "Projects that make a difference",
        text : "Check out my projects below"
      },
      portfolio : {
        title : "Becoming",
        subTitles : "Projects that make a difference",
        text : "Check out my projects below"
      }
    }
  }

  render() {
    return (
      <Router>
        <Container className="p-0" fluid={true}>

        <Navbar expand="lg" variant="light" bg="light">
            <Navbar.Brand>Neha</Navbar.Brand>

            <Navbar.Toggle className="border-0" aria-controls="navbar-toggle" />
            <Navbar.Collapse id="navbar-toggle">
              <Nav className="ml-auto">
                <Link className="nav-link" to="/">Home</Link>
                <Link className="nav-link" to="/portfolio">Portfolio</Link>
                <Link className="nav-link" to="/team">Team</Link>
                <Link className="nav-link" to="/news">News</Link>
                <Link className="nav-link" to="/about">About</Link>
                <Link className="nav-link" to="/reachUs">ReachUs</Link>

              </Nav>
            </Navbar.Collapse>
          </Navbar>

        </Container>
      </Router>
    );
  }
}

export default App;

Question 2:
Is the className="p-0" pre-defined? I was going through a video tutorial and it said it makes padding=0.
So, if it pre-defined how can I get to know about all these classes?
Output

A: Did you include React-Bootstrap's CSS files?
Check out the getting started documentation. There is a CSS file you need to include in order to get React-Bootstrap's styles.

A: Apparently you haven't check the react-bootstrap docs. I will suggest you should read the docs first as it's better than any video tutorial out there.
In regards to your issue, If I am not mistaken, you will also need to add react bootstrap css in addition to the react-bootstrap components .