text:
Q: Text filter on two types of queries I want to Filter some events by text on the key_Value but also by name displayed
for that i made some if/else statements for the names :
box.descEvents.forEach((printEvent: PrintEvent) => {
    let printEventDisplay: string

    if (!printEvent) {
        return null
    }

    if (printEvent.name === 'interpass_ready') {
        printEventDisplay =
            `Part cooled down to ${printEvent.meta['interpass_temp']}°C ` +
            `in ${printEvent.meta['wait_time']}s`
    } else if (printEvent.name === 'chunk_init' || printEvent.name === 'chunk_done') {
        printEventDisplay = box.getNameLabel(printEvent.name)
        printEventDisplay += ' ' + (parseInt(printEvent.value) + 1).toString()
    } else if (printEvent.name === 'control_fault') {
        printEventDisplay = box.getStopLabel(printEvent.meta.reason) + ': '
    } else if (eventDenylist.includes(printEvent.name)) {
        return
    } else if (triggerSignals.includes(printEvent.name)) {
        printEventDisplay = box.getNameLabel(printEvent.name) + ' '
        if (printEvent.name === 'limit_switch') {
            printEventDisplay +=
                printEvent.value === 'True' || printEvent.value === true
                    ? 'released'
                    : 'triggered'
        } else {
            printEventDisplay +=
                printEvent.value === 'True' || printEvent.value === true
                    ? 'triggered'
                    : 'released'
        }
    } else if (openedSignals.includes(printEvent.name)) {
        printEventDisplay = box.getNameLabel(printEvent.name) + ' '
        printEventDisplay +=
            printEvent.value === 'True' || printEvent.value === true ? 'closed' : 'open'
    } else if (sourceSignals.includes(printEvent.name)) {
        printEventDisplay = box.getNameLabel(printEvent.name) + ' from '
        printEventDisplay += printEvent.meta['source'] ? printEvent.meta['source'] : 'unknown'
    } else if (printEvent.name == 'running') {
        printEventDisplay = 'Robot '
        printEventDisplay +=
            printEvent.value === 'True' || printEvent.value === true ? 'started' : 'stopped'
    } else if (printEvent.name == 'sync_calibration') {
        printEventDisplay = 'Sync calibration values '
        if (printEvent.value == 'request') {
            printEventDisplay += 'requested'
        } else if (printEvent.value == 'done') {
            printEventDisplay += 'finished'
        }
    } else {
        if (printEvent.name && printEvent.value !== null) {
            printEventDisplay =
                box.getNameLabel(printEvent.name) + ': ' + printEvent.value.toString()
        } else if (printEvent.name) {
            printEventDisplay = printEvent.name
        } else {
            console.dir(printEvent)
        }
    }

i made a local state to activate whenever textfield is used:
const [filterQuery, setFilterQuery] = React.useState('')

const getEventNames = box.getNameLabel(printEvent.name).split(',')

    if (filterQuery) {
        filteredList.push(

                {getEventNames
                    .filter((name) => name.toLowerCase().includes(filterQuery.toLowerCase()))
                    .map((name) => (

                            <AccordionItem
                                printEventDisplay={printEventDisplay}
                                printEvent={printEvent}
                                eventName={name ? ' (filtered event)' : null}
                                eventSource={eventSource ? eventSource : null}
                                eventID={eventID}
                                eventLineNumber={eventLineNumber}
                                printEventValue={printEventValue ?? ''}
                                checkColorToggle={checked}
                                clsxClass={
                                    checked
                                        ? clsx({
                                            [classes.accordionWarning]:
                                                printEvent.name === 'warning',
                                            [classes.accordionRunning]:
                                                printEvent.name === 'running' &&
                                                printEvent.value === false,
                                            [classes.accordionChunkStarted]:
                                                printEvent.name === 'chunk_init',
                                            [classes.accordionChunkDone]:
                                                printEvent.name === 'chunk_done',
                                            [classes.accordionControlFault]:
                                                printEvent.name === 'control_fault' &&
                                                printEvent.value === true,
                                            [classes.accordionTorchCollisionTriggered]:
                                                printEvent.name === 'torch_collision' &&
                                                printEvent.value === true,
                                            [classes.accordionRobotStarted]:
                                                printEvent.name === 'running' &&
                                                printEvent.value === true,
                                            [classes.accordionRobotStopped]:
                                                printEvent.name === 'running' &&
                                                printEvent.value === false,
                                            [classes.accordionTorchCollisionReleased]:
                                                printEvent.name === 'torch_collision' &&
                                                printEvent.value === false,
                                            [classes.accordionSafetyChainTriggered]:
                                                printEvent.name === 'safety_chain' &&
                                                printEvent.value === true,
                                            [classes.accordionInterpass]:
                                                printEvent.name === 'interpass_temp' &&
                                                printEvent.value &&
                                                printEvent.meta['interpass_temp'],
                                            [classes.accordionSafetyChainRelease]:
                                                printEvent.name === 'safety_chain' &&
                                                printEvent.value === false,
                                            [classes.accordionLimitSwitch]:
                                                (printEvent.name === 'limit_switch' &&
                                                    printEvent.value === 'True') ||
                                                printEvent.value === true,
                                        })
                                        : classes.accordionDefault
                                }
                                clsxText={''}
                                setColorToggle={toggleChecked}
                                eventList={undefined}
                                accordionItem={undefined}
                                printEventName={undefined}
                                scrollableDiv={undefined}
                            />

                    ))}

        )
    }

how do i make the query look for the printEventDisplay, instead of the printEvent.name?
can i use an OR operator or an AND after the fist query type?

A: i have a global state already including these names so i included it it in the variable:
const getEventNames = box.getNameLabel(printEventDisplay).split(',') || box.getNameLabel(printEvent.name).split(',')


text:
Q: Unable to initialize boost::multi_array unless T has a no-argument constructor It seems that boost::multi_array<T, n> requires that T have a no-argument constructor.  Consider the following example.
#include <boost/multi_array.hpp>

class ConstructorHasArguments {
    ConstructorHasArguments(int arg) {};
}

int main() {
    boost::multi_array<ConstructorHasArguments, 1> foo;
    return 0;
}

This results in a compile error.
no matching function for call to 'ConstructorHasArguments::ConstructorHasArguments()

The problem is that, when the copy constructor for boost::multi_array<T,n> tries to allocate space for the copy, it attempts to call T().  I could, of course, add a no-argument constructor to my class.  But what if I have a class for which a no-argument constructor doesn't make sense?
Is there a simple way to use boost::multi_array when T does not have a no-argument constructor?

A: It is not only the copy constructor - actually all constructors of boost::multiarray will call allocate_space(), which in turns invokes std::uninitialize_fill_n(base, allocated_elements_, T());. Therefore a constructor without argument is required here. I don't think there is a way to bypass it if you still want to use boost::multi_array. (I am referring to the source code of boost-1.46.0.)
An alternative may be like this: you allocate and initialize space by yourself. Then pass the address to boost::multi_array_ref. In this case you will have to manage the memory.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Drag drop views in constraintlayout move views to top left corner I am new to constrain layout and after reading documentations i know that view must have 1 horizontal and 1 vertical coordinates but whenever i drag a new view into design it move to 0,0 coordinates

My XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_marginTop="181dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />

    <ImageButton
        android:id="@+id/imageButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="@+id/imageView3"
        app:layout_constraintEnd_toEndOf="@+id/imageView3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_add_friend" />

</androidx.constraintlayout.widget.ConstraintLayout>

I already set views vertical and horizontal constrain but it still hangs at the top left also tried with vertical and horizontal bias but views sticks to top left.Please help
I also checked this and this but not working for me.

A: It happens sometimes if we move around commits. For me it's mostly build related issue. Building the project or make project would fix this issue.


text:
Q: R Shinydashboard submenuitems using same UI I have a basic app with a MenuItem that when clicked displays a plot of a specific variable. The variable can be chosen from a SelectInput in the UI for this MenuItem.
However, what I'd really like to do is to have the possible variables be displayed as subMenuItems of the original MenuItem, so that when one is clicked it grabs the currently selected variable and renders the plot. This looks visually neater to me than using a SelectInput dropdown.
I was trying to get this working by having each tabItem link to the same uiOutput that displays the appropriate content, but Shiny doesn't seem to like having multiple tabs with the same output. Is there any way to achieve this functionality?
Code example that doesn't work:
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
    dashboardHeader(),
    dashboardSidebar(
        sidebarMenuOutput("menu"),
        textOutput("res")
    ),
    dashboardBody(
        tabItems(
            tabItem("dashboard", "Dashboard tab content"),
            tabItem("widgets", "Widgets tab content"),
            tabItem("chartsHome", "Main charts content"),
            tabItem("subitem1", uiOutput("chart")),
            tabItem("subitem2", uiOutput("chart"))
        )
    )
)

server <- function(input, output, session) {
    output$res <- renderText({
        paste("You've selected:", input$tabs)
    })
    output$menu <- renderMenu({
        sidebarMenu(
            # Setting id makes input$tabs give the tabName of currently-selected tab
            id = "tabs",

            menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
            menuItem("Widgets", icon = icon("th"), tabName = "widgets"),
            menuItem("Charts", icon = icon("bar-chart-o"), tabName="chartsHome",
                     menuSubItem("Sub-item 1", tabName = "subitem1"),
                     menuSubItem("Sub-item 2", tabName = "subitem2")
            )
        )
    })

    output$chart <- renderUI({
        if (input$tabs == "subitem1") {
            HTML("Chart with first variable as output")
        } else if (input$tabs == "subitem2") {
            HTML("Chart with second variable as output")
        }
    })

}

shinyApp(ui, server)

A: You can't have duplicate IDs, they have to be unique. You can investigate these yourself by right clicking on the page and then inspect, click on console and you will see the errors. For you its Uncaught Duplicate binding for ID chart
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenuOutput("menu"),
    textOutput("res")
  ),
  dashboardBody(
    tabItems(
      tabItem("dashboard", "Dashboard tab content"),
      tabItem("widgets", "Widgets tab content"),
      tabItem("chartsHome", "Main charts content"),
      tabItem("subitem1", uiOutput("chart")),
      tabItem("subitem2", uiOutput("chart2"))
    )
  )
)

server <- function(input, output, session) {
  output$res <- renderText({
    paste("You've selected:", input$tabs)
  })
  output$menu <- renderMenu({
    sidebarMenu(
      # Setting id makes input$tabs give the tabName of currently-selected tab
      id = "tabs",

      menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
      menuItem("Widgets", icon = icon("th"), tabName = "widgets"),
      menuItem("Charts", icon = icon("bar-chart-o"), tabName="chartsHome",
               menuSubItem("Sub-item 1", tabName = "subitem1"),
               menuSubItem("Sub-item 2", tabName = "subitem2")
      )
    )
  })

  toRender <- reactive({
    if (input$tabs == "subitem1") {
      HTML("Chart with first variable as output")
    }
    else if (input$tabs == "subitem2") {
      HTML("Chart with second variable as output")
    }
    else{
      return()
    }
  })

  output$chart <- renderUI({
    toRender()
  })

  output$chart2 <- renderUI({
    toRender()
  })

}

shinyApp(ui, server)


text:
Q: How do I solve $c^2 + 1 > 2c - 1$ when $c \ge 2$? We have been given a question to do as part of a task set by our lecturer, however he has failed to provide any examples of similar questions with all the corona stuff going on, and I cannot find the name of the method used to solve it. The question is as follows.

Suppose that $c\in \Bbb N$. Prove that:
If $c\ge 2$ then $c^2+1>2c−1$.

What is this type of question called, and what would be the working to solve it?

A: $$(c-1)^2\geq 0>1\Rightarrow c^2-2c+1> -1\Rightarrow c^2+1>2c-1$$
Now this would be the case for any $c\in N$, thus valid for $c\geq 2$.
(I think you meant some else equation)

A: This is a good example of when proof by induction is useful. The base case is $c=2$. Then assume that the inequality holds for some $k>2$ and show that the inequality holds for $k+1$.


text:
Q: Wrong line numbers with multiline grep -P [ Perl extension ] match I have been using  grep with perl extension for multiline match .However it turns out that the line number of all the match depends on the number of lines in the first multiline match  !
The grep regex  to find the c function start :
   grep -iPn '^[^\S\n]*?\w+\s+\w+?\s*\([\w-0-9,/* \s]*\)\s*\{$'

I can explain better with an example :
Suppose these two function exists in the source file
      int f1(int a) {

      int
      f2 (int b )
      {

In this case ,the grep matches the regex successfully and the line number output to stdout is in par with the line number of the source file .
The problem arises when a multiline function comes first .This alters the line number output and after examining the file for some time I came to a conclusion. The multiline functions are matched but read as a single line by the grep therefore it assigns the whole function a single line number.The next line that follows the function gets its line number short depending on the number of lines the 'function definition start regex 'occupies.
There are numerous multiline C functions in my file and the line number is way too deviated for each one of them.
Is there a way to correct this ?

A: Using the pcregrep for the same regex shows the correct line number !
 pcregrep -Mni '^[^\S\n]*?\w+\s+\w+?\s*\([\w-0-9,/* \s]*\)\s*\{$'

A: Your solution doesn't work with my (linux, gnu)grep.
I need to add -z to make it work. With -z "lines" are separated by a null char; this way you have a single "line", so line numbers wont work :( but byte offset do. Sometimes that is enough...
So, using grep:
grep -ziPbo '^[^\S\n]*?\w+\s+\w+?\s*\([\w-0-9,/* \s]*\)\s*\{$'

obtaining
24:int
f2 (int b )
{


text:
Q: Left join returning count of 1 even though no rows exist for that count? I have a query that looks like the following. It uses a cte:
SELECT  d.hour,
        hourkey,
        range,
        COUNT(*) as 'count'
FROM dimhour d
    LEFT JOIN cte2
        ON d.hour = cte2.hourkey
        AND range IS NOT NULL
WHERE d.hour <= 23
GROUP BY d.hour,
         hourkey,
         range
ORDER BY d.hour DESC

This is the result of this query:
hour   hourkey  range    count
18     NULL     NULL     1
17     NULL     NULL     1
16     NULL     NULL     1
15     15       99%      15
14     14       99%      15
13     13       99%      15
12     12       99%      15
11     11       99%      15
10     10       99%      15

The result of cte2 is too large to post here, but I can tell you that the hours where cte2.hourkey is null do not have a single row within cte2. There's nothing after Hr15 that could possibly return a positive number for count(*). But count(*) somehow returns 1 for those.
Why is this query returning a count(*) of 1 for non-existing hours and how can I remove them?

A: COUNT(*) will return a count of all rows in a particular group, including the row it's on.  If you want it to count a particular column, you need to specify the column, such as COUNT(cte2.hourkey).  This will count non-null records within the group.
SELECT d.hour, hourkey, range, COUNT(cte2.hourkey) AS [count]
FROM dimhour d LEFT JOIN cte2 ON
d.hour = cte2.hourkey
AND range IS NOT NULL
WHERE d.hour <= 23
GROUP BY d.hour, hourkey, range
ORDER BY d.hour desc

If you don't want the rows to show at all, you need an INNER JOIN instead of a LEFT JOIN:
SELECT d.hour, hourkey, range, COUNT(cte2.hourkey) AS [count]
FROM dimhour d INNER JOIN cte2 ON
d.hour = cte2.hourkey
AND range IS NOT NULL
WHERE d.hour <= 23
GROUP BY d.hour, hourkey, range
ORDER BY d.hour desc

A: The expression:
count(*) as [count]

returns the number of rows in the result set.  LEFT JOIN is guaranteeing at least one row, even if it doesn't match.
To count the matches, then count one of the columns used for the JOIN (or the primary key):
count(cte2.hourkey) as [count]

Note:  Only use single quotes for string and date constants.  Using them for columns is likely to cause problems in the future.

A: To answer from a different perspective, in a way I think may be easier to understand:
If you take out the GROUP BY, you get:

hour   hourkey  range
18     NULL     NULL
17     NULL     NULL
16     NULL     NULL
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
15     15       99%
14     14       99%
...

If you now group by hour, hourkey, range, how many rows do you see for 18, NULL, NULL? I spot one row. It's right there at the top. That's what COUNT(*) is returning.
And that's how to approach this too: the count you want, is that a count you can easily obtain from this result set? If not, then look for another approach. In your case, you appear to want to do the grouping on cte2. So write that instead!
select d.hour, sub.hourkey, sub.range, sub."count"
from dimhour d
left join (
    select cte2.hourkey, cte2.range, count(*) as "count"
    from cte2
    where cte2.range is not null
    group by cte2.hourkey, cte2.range
) as sub
on d.hour = sub.hourkey
where d.hour <= 23
order by d.hour desc

One difference is that now instead of 0, you'll get NULL, but you could use ISNULL(sub."count", 0) to avoid that if it bothers you.


text:
Q: How do we remove just the "+" sign from mobile number , I am collecting mobile number in a registration form with +919xxxx. But for sending SMS through API my SMS provider don't allow + prefix instead they allow country code with mobile number
So for this instance alone I need to remove the + prefix and Post mobile number in API string so which code I should use in PHP ?
Any advice greatly appreciated

A: you can use this code it will work and remove "+" from your number
    $str = "+912789635241";
    $remove = trim($str,"+");
    echo $remove;


text:
Q: Is there anyway I can measure the lux level (illuminance level) on a surface? I am trying to design a lighting experiment using Unity. I have different types of lighting in a scene and now I need to know the illuminance level (lux level) on a surface in an environment that I have designed. Is there any way that I can do that? or any plug-ins that I can use?
I am not using HDRP but I realized it uses physical light units, though I am still not sure if it means I can get an illuminance value on a surface using that either. Should I switch to HDRP?
I will be grateful if anyone could help me, I am new to this. Thanks!


text:
Q: Vector subderivatives and "simple algebra" which turn out not to be so simple In Friedman, Hastie and Simon (2013) an algorithm is proposed for a group-LASSO penalized regression possibly involving many variables. The problem is as follows:
$\underset{\beta}{min}\{ \frac{1}{2}|| Y - X \beta ||_2^2 + \lambda \sum_{k \leq p} ||\beta_{k.}||_2\}$
with $Y$, an $n \times M$ matrix, $X$, an $n \times p$ matrix and $||a||_2^2 := \sqrt{a^Ta} $. Let use also note $X_{.k}$ as the $k^{th}$ column of a matrix $X$ and, $X_{k.}$ as its $k^{th}$ row.
They propose to take as given all $\beta_{j.}$ for $j \neq k$, except $\beta_{k.}$, hence we get the objective:
$\underset{\beta}{min}\{ \frac{1}{2}|| R_{-k} - X_{.k} \beta_{k.} ||_2^2 + \lambda ||\beta_{k.}||_2\}$
where $R_{-k} := Y - \sum_{j \neq k} X_{.j}\beta_{j.}$. From here, we can take a subderivative with respect to $\beta_{j.}$ so that our solution $\hat{\beta}_{k.}$ satisfies:
$- X_{.k}^TR_{-k} + ||X_{.k}||_2^2 \hat{\beta}_{k.} + \lambda S(\hat{\beta}_{k.}) = 0$
where $S(a) \begin{cases} = \frac{a}{||a||_2} \text{ } if a \neq 0 \\ \in \{u \; \; \text{s.t.} \; \; ||u||_2 \leq 1 \}
\end{cases}$
Now, I have a questions.
It concerns how you go from the FOC-like equation above to this equation:
$\hat{\beta}_{k.} = \frac{1}{||X_{.k}||_2^2} max\{0, 1 - \frac{\lambda}{||X_{.k}^T R_{-k}||_2} \} X_{.k}^T R_{-k}$
i.e., how do you isolate the solution vector in the FOC-like equation involving the subderivative? On page 4, they call it "simple algebra."
It's important that I understand it because I need to apply the same algorithm in a slightly different context. Instead of having a penalty of the form
$\lambda ||\beta_{k.}||_2$
I have one of the form
$\lambda ||W_{k.}||_2$
where $W := Q_n \beta$. If it is of any interest, I am an economist. I know some mathematics, but I am not a mathematician by any stretch of the imagination.

A: Here is a sketch of the missing algebra.
Given the FOC in terms of the row vector $a^T$
$$\eqalign{
(x^Tx)a^T + \Big(\frac{\lambda}{\sqrt{a^Ta}}\Big) a^T = x^TR \\
\Bigg(x^Tx + \frac{\lambda}{\sqrt{a^Ta}}\Bigg) a^T = r^T \\
\Bigg(\chi^2 + \frac{\lambda}{\alpha}\Bigg) a^T = r^T \\
}$$
So $a$ is seen to be a scalar multiple of $r$.
Square both sides and solve for the unknown scalar $\alpha$.
$$\eqalign{
\Bigg(\chi^2 + \frac{\lambda}{\alpha}\Bigg)^2 \alpha^2 = \rho^2 \\
\Big(\alpha\chi^2 + \lambda\Big)^2 = \rho^2 \\
\alpha = \frac{\rho-\lambda}{\chi^2} \\
}$$
Substituting $\alpha$ recovers the $a$ vector in terms of the known quantities.
To relate this all to the current problem let
$$\eqalign{
a^T &= {\hat\beta},\quad &x = X_k,\quad &r^T = X_k^TR_k \\
\alpha^2 &= \|a\|^2,\quad &\chi^2 = \|x\|^2 ,\quad &\rho^2 = \|r\|^2 \\
}$$


text:
Q: Oracle SQL Developer How To Default To Other Users Tables? In order to see all of the tables in our companies DB I have to go find the main sys account. Is there a way to default my connection so that it shows the other users tables?

A: Any table that your connecting account has at least SELECT privileges on will show up in the "Other Users" node of the navigation tree.  If the table does not show up there then it is a database permissions issue, not a SQL Developer configuration issue.

A: Think you don't want to repeated type otheruser.tablename in all your queries. If that is the case you want to run this
alter session set current_schema = otheruser;

A: What do you mean by "see all of the tables"? Are you happy if you know they're there, or do you need to see their content. In the former case dba_tables should do. In the latter case it's a matter of the privileges assigned to you.

A: Change your connect to login as the main Sys user.  Otherwise like dpbradley says you will have to go find them under the Other Users node.

A: If you connect to (e.g.) DB2 using JDBC driver, you can use this syntax:
jdbc:db2://localhost:50000/WESBDB:currentSchema=WESB;

Not only that the schema WESB will be your current schema, but it will be also the default schema in the tree on the Connections tab.
Note: It seems that it works for DB2 only.

A: As Ram, I also do it with
alter session set current_schema = otheruser;
It works if you want to access to the tables of a particular user


text:
Q: Euler Project 2 So I am not very good at it yet at all (understatement). I am trying to solve problems in the Euler project, and I am already stuck on 2.

Each new term in the Fibonacci sequence is generated by adding the previous 2 terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Here is my code which I have repeatedly tried to fix:
(I think there is something wrong with the for loop logic.)
public class tesy {
    public static void main(String args[]) {
        int fib = 0;
        int tot = 0;
        int total = 0;

        for (fib = 0; tot < 4000000; fib++) {
            tot = fib + (fib + 1);

            if (tot % 2 == 0) {
                total = tot + total;
            }
        }
        System.out.println(total);
    }
}

A: You don't seem to be following the actual equation used to generate a fibonacci sequence, therefore there is no (obvious) way of fixing your code.
int fibA = 1, fibB = 2, total = 0;

while(fibB <= 4000000) {
    // Add to the total, set fibA to fibB and get the next value in the sequence.
    if(fibB % 2 == 0) total += fibB;
    int temp = fibA;
    fibA = fibB;
    fibB = fibB + temp;
}

The above code should find the sum of all values less than or equal to 4000000

A: Your logic is erroneous in couple of ways,
tot = fib + (fib + 1); /** This will always be `(2*fib + 1)` and `fib` is getting
incremented by 1 each time. You have no reference to the previous two terms of the
sequence. **/

Try the below logic instead.
class Fibonacci
{
    public static void main (String[] args)
    {
        int fiboFirst = 1;
        int fiboSecond =2;
        int fib = 0;
        int sum = 0;

        while(fiboSecond < 4000000)
          {
            // This will calculate the current term of the sequence
            fib = fiboFirst + fiboSecond;

            // Below two lines will update fib[i] and fib[i - 1] terms
            // for the next loop iteration.
            fiboFirst = fiboSecond;   // fib[i]
            fiboSecond = fib;   // fib[i -1]
            if (fib % 2 == 0)
              {
                sum = sum + fib;
              }
          }
        System.out.println(sum+2);
    }
}

Explanation
Here fiboFirst is equivalent to F[n] and fiboSecond is equivalent
  to F[n - 1] in the Fibonacci sequence definition. In each iteration,
  those two values should be replaced, in order to be used in the next
  iteration. That is why I have these two lines,
fiboFirst = fiboSecond;   // fib[i]
fiboSecond = fib;   // fib[i -1]

HERE is the execution of the above program

A: Here is a solution that uses BigInteger. Please verify the results.
public class Fibonacci{

    public static void main(String[] args) {
        BigInteger r = fibonacciEvenSum();
        System.out.println(r);
    }

    public static BigInteger fibonacciEvenSum(){
        int f = 1;
        int s = 2;
        int mn4 = 4000000;
        BigInteger sum = BigInteger.valueOf(0);

        while(s <= mn4){
            if(s % 2 == 0){
                sum = sum.add(BigInteger.valueOf(s));
            }
            f = f + s;
            s = s + f;
        }
        return sum;
    }

}

A: Before writing a program like this, you should first think of what's underlying this program. You should first understand how to generate a Fibonacci series before graduating on to doing something with the series. I'll give you my solution so that you can understand.
class euler2 {
    public static void main(String[] args) {
        int a = 0, b = 1; /* the first elements of Fibonacci series are generally
                          thought to be 0 and 1. Therefore the series is 0, 1, 1, 2, 3... .
                          I've initialized first and second elements such  */
        double sum = 0; // The initial sum is zero of course.
        while (b < 4000000) /* since b is the second term, it will be our control variable.
                            This wouldn't let us consider values above 4M. */
        {
            int ob = b; // to swap the values of a and b.
            b = a + b; // generating next in the series.
            a = ob; // a is now the older value of b since b is now a + b.
            if (b % 2 == 0) // if b is even
                sum += b; // we add it to the sum
        }
        System.out.println(sum); // and now we just print the sum
    }
}

Hope this helped!


text:
Q: How can I force Access to refresh references when the database is opened I have a problem with a user's workstation. There is a development version of the Access database that is distributed to workstations using a .bat file. The database is working perfectly on all workstations other than one.
The particular workstation will not let the user run specific Query's, giving a 3075 Error. I have been across the web and realized that this is a problem with the references. However there are no MISSING references, but if I force Access to refresh its references, by checking an un-selected reference, then again removing the reference, the database works perfectly. It works perfectly until the user again runs the .bat and receives the latest version of the DB.
I have un-registered and re-registered the references using Regsvr32.exe but still the problem persists.
I have performed a COMPLETELY fresh install of Office but still the problem persists.
Is there a way to force Access to refresh its references via VBA on open?
Failing that I will be forced to do a clean install of the machine.
The machine developed this problem within a matter of 30 minutes and has been working perfectly for 2-3 years before hand.

A: You indicated you can resolve the problem manually "by checking an un-selected reference, then again removing the reference".
You can use VBA code to add and remove a reference.  There are 2 different methods to add a reference: AddFromFile; and AddFromGuid.  AddFromFile requires the full path of the file which provides the reference.  AddFromGuid requires a GUID, and Major and Minor versions for the reference.
It's easy to gather that information from an existing reference.  I added a reference to Excel Type Library, then inspected its properties in the Immediate window.
? References("Excel").FullPath
C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE
? References("Excel").Guid
{00020813-0000-0000-C000-000000000046}
? References("Excel").Major
 1
? References("Excel").Minor
 7

Then I can remove that reference and add it back again with the AddFromFile method.
References.Remove References("Excel")
References.AddFromFile "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE"

Or with the AddFromGuid method ...
References.Remove References("Excel")
References.AddFromGuid "{00020813-0000-0000-C000-000000000046}", 1, 7

Those methods work with my database.  However, my database does not have a references problem to start with.  If yours does, I don't know if this will work.


text:
Q: Does the Laplace transform biject? Someone wrote on the Wikipedia article for the Laplace trasform that 'this transformation is essentially bijective for the majority of practical uses.'
Can someone provide a proof or counterexample that shows that the Laplace transform is not bijective over the domain of functions from $\mathbb{R}^+$ to $\mathbb{R}$?

A: For "the majority of practical uses" it is important that the Laplace transform ${\cal L}$ is injective. This means that when you have determined a function $s\mapsto F(s)$ that suits your needs, there is at most one process $t\mapsto f(t)$ such that $F$ is its Laplace transform. You can then look up this unique $f$ in a catalogue of Laplace transforms.
This injectivity of ${\cal L}$ is the content of Lerch's theorem and is in fact an essential pillar of the "Laplace doctrine". The theorem is proven first for special cases where we have an inversion formula, and then extended to the general case.
The difference between "injectivity" and "bijectivity" here is that we don't have a simple description of the space of all Laplace transforms $F$. But we don't need to know all animals when we want to analyze a zebra. Lerch's theorem tells us that it has a unique pair of parents.

A: Bijective from what space of functions to what space of functions?
For example, by the Paley-Wiener theorem the Laplace transform is a bijection from $L^2(0,\infty)$ to the functions $F$ analytic in the open right half plane whose restrictions to vertical lines in the right half plane have uniformly bounded $L^2$ norm.

A: It depends on you set of definition. If you ask wheter it is bijective from the functions defined on $\mathbb{R}$, compare the laplace transform of
$$
f(x)=\begin{cases}
\sin(x)&x\geq0\\
0&x<0
\end{cases}
$$
and
$$
g(x)=\sin(x), \forall x.
$$


text:
Q: Internationalization in Yii2 (Database) I'm kinda struggling what is going on right now.
I want to set up a site with multilanguage-functionality. For that, I read the topic about Internationalization in the guides. I don't want to use the text-/file-version, I want to use the DB instead.
I found out, that there is something like the DbMessageSource. I applied the migration and have the following tables in my DB:
message
message_source
In my config-file, I addes these lines:
'components' => [
    'cache' => [
        'class' => 'yii\caching\FileCache',
    ],
    'i18n' => [
        'translations' => [
            '*' => [
                'class' => 'yii\i18n\DbMessageSource',
                'forceTranslation' => true,
                'sourceMessageTable' => '{{%source_message}}',
                'messageTable' => '{{%message}}',
                'enableCaching' => false,
                'cachingDuration' => 3600,
                'sourceLanguage' => 'en_US'
            ],
        ],
    ],
],

In my view, I call the translation-function like this:
echo yii::t('header_menu', 'news');

It is actually displaying "news", but regardless of the language I set, nothing is stored in the DB. Am I missing something? I thought every string, which is in a translate-function would be stored in the DB?
Thanks in advance

A: By itself it won't be in DB. It just selects if data is already there. You should do it by yourself or use lajax translate manager extension, it will scan all your project automatically and fill database with messages.


text:
Q: How to fixed react native nested parent ScollView as window height? Here is styling of my nested ScrollView
<ScrollView style={{ flex: 1 }}  refreshControl={
               <RefreshControl
                refreshing={refreshing}
                onRefresh={() => {
                  ...
                }}
              />}>
...
 <ScrollView style={{ flex: 1 }}
             nestedScrollEnabled={true}
             >
 ...
 </ScrollView>
...
</ScrollView>

Result of my code: Parent scroll view can scroll but child scroll  view cannot. Child just render as long as the list is.
I believe {flex:1} in child is the main reason why child dont work. But I need flex:1 because I want it to occupy all the remaining spaces and I have other component didnt have a specific height.
I do not need the scolling function for parent and want to keep it as window size. I only need the refresh control for parent.
I tried to set parent scroll view as window height but the component will be cut out instead of squeezing the child scroll view.
Thankyou.


text:
Q: Iterating comma separated list in views How do you loop over a values from a checkbox within a view.
This is what I have tried so far:
if request.method == 'POST':
        form = SomeForm(request.POST)
        # Check we have valid data before saving trying to save.
        if form.is_valid():
            data = form.cleaned_data
            groups = data['thischeckbox']
            for item in groups:
                print(item)

But this gives a KeyError.

A: if request.method == 'POST':
    form = SomeForm(request.POST)
    # Check we have valid data before saving trying to save.
    if form.is_valid():
        data = form.cleaned_data
        groups = data['thischeckbox'].split(",")
        for item in range(len(groups))
            print(groups[item])


text:
Q: a question on summation expansion Q1.
$$\sum\limits_{j=0}^{N-1} \sum\limits_{i=0}^{N-1} \sum\limits_{y=0}^{j} \sum\limits_{x=0}^{i} a(x)a(y)b(|x-y|) $$
Given that $b(0) = 0$, Find the coefficient of $b(k)$, $0\le k \le N-1$ in the above expansion.
Q2. $$\sum\limits_{j=0}^{N-1} \sum\limits_{i=0}^{N-1} \sum\limits_{x=0}^{\min(i,j)} a(x) .$$
Find the coefficient of $a(x)$ in the above expansion?

A: Let us use a general approach. A first principle to evaluate multiple sums is:

When dealing with multiple sums, see what happens when exchanging the order of the summations.

Re Q2, this means writing the sum $S$ as a sum over $x$ of $a(x)$ times a sum over $i$ and $j$.
Which brings us to a second general principle:

Sums over a fixed set of integers are easier.

And to the most useful tool to apply this principle:

Write the spans of sums as indicator functions.

In this context, some people use Iverson bracket $[\mathfrak A]$ to mean $1$ if assertion $\mathfrak A$ is true and $0$ otherwise, and I will use this convention. For instance, still Re Q2,
$$
S=\sum_{j=0}^{N-1}\sum_{i=0}^{N-1}\sum_{x=0}^{N-1}[x\le \min\{i,j\}]\cdot a(x).
$$
But $[x\le \min\{i,j\}]=[x\le i]\cdot[x\le j]$, hence exchanging the order of the summations yields
$$
S=\sum_{x=0}^{N-1}a(x)\sum_{i=0}^{N-1}[x\le i]\sum_{j=0}^{N-1}[x\le j].
$$
The sum over $i$ and the sum over $j$ coincide and their common value is
$$
\sum_{j=0}^{N-1}[x\le j]=\sum_{j=x}^{N-1}[x\le j]=N-x,
$$
hence
$$
S=\sum_{x=0}^{N-1}(N-x)^2a(x).
$$
This solves Q2.
The solution for Q1 is somewhat more involved, but I suggest that you now see how far you can go with these principles to try to solve it.


text:
Q: Type trait dependent specialization of template function I have a simple templated function, defined in a library I am using
template<class T>
T create(std::vector<char>& data)
{
    T newValue{};
    /* Do something with data */
    return newValue;
}

and I want to specialize this function in case T implements a specific interface
template<class T>
std::enable_if_t<std::is_base_of<Interface, T>::value, T> create( std::vector<char>& data)
{
    T newValue{};
    newValue.InterfaceFunction(data);
    return newValue;
}

but I cannot make this work, the function I have specialized is not used. How can I achieve making a specialization of an already defined template function?

A: This is not template specialization but templates overloading, and function templates can't be partial specialized. The problem is that when you specify a type deriving from Interface both the function templates are exact match, which leads to ambiguity.
You can apply SFINAE.
template<class T>
std::enable_if_t<!std::is_base_of<Interface, T>::value, T> create(std::vector<char>& data)
{
    T newValue{};
    /* Do something with data */
    return newValue;
}

template<class T>
std::enable_if_t<std::is_base_of<Interface, T>::value, T> create( std::vector<char>& data)
{
    T newValue{};
    newValue.InterfaceFunction(data);
    return newValue;
}

LIVE


text:
Q: How can I locate a directory and automatically set the working directory path to it in R? I have a "Box Sync" folder directly under my R's default root directory. I am trying to create code such that even if there are other directories in between my directory and the "Box Sync" folder, I can locate and set that as the working directory.

A: You can use list.dirs(recursive=T) to find all directories in your working directory, then use endsWith to find those which are named Box Sync themselves. You can further filter these if needed and assign with setwd:
dirs <- list.dirs(recursive = T)  # List all directories in the working directory
box_dirs <- dirs[endsWith(dirs, 'Box Sync')]  # Show the ones ending with 'Box Sync'

box_dirs
    [1] "./Box Sync"
    [2] "./Library/Application Support/Box/Box Sync"
    [3] "./Library/Logs/Box/Box Sync"

setwd(box_dirs[1])


text:
Q: Cannot type anything in react native TextInput component I am new to react-native. I am doing a simple salary calculator component for practice. I have two TextInput components, but I can't seem to type anything in them. Here is the code for my component:
class SueldoCalc extends Component {
  constructor(props)
  {
     super(props);
  }

 calcSalario()
 {
   console.log("Calculating");
 }

render()
{
return (
  <View>
      <Text>Entre las horas trabajadas:</Text>
      <TextInput />
      <Text>Entre el rate por hora:</Text>
      <TextInput />
      <TouchableHighlight onPress={this.calcSalario}>
        <Text>Calcular salario...</Text>
      </TouchableHighlight>
  </View>
);

}

}

I tried subscribing to onTextChange events, but nothing. This is so basic, I can't find anything out there. Please help! I am running the app on Android Simulator for Visual Studio.

A: I had the same problem both in Android and IOS. After I set width and height as the following (be careful both width and height must be set), the problem solved:
<TextInput style={{ height: 20, width: 100 }} />

A: You should specify onTextChange handler then set the state from there. Your <TextInput /> should have a value property:
<TextInput
    value={this.state.horas}
    onChange={this._onChangeHandler}
/>


text:
Q: return an array from glob node js The issue
I'm using the answer here Get all files recursively in directories NodejS
however, when I assign it to a constant I'm trying to return the directories so I can have them available in an array, I have looked through globs documentation for an asnwer https://github.com/isaacs/node-glob, however I have had no successful results, I have tried using glob.end() and I have also console.log the folds variable below, I can see all the list of available methods and I have tried to use some of them with no success, does anyone know how to return the array like in the code example below? Thank you!
 const glob = require('glob');
 const src = 'assets';

function getFiles(err, res){
  if (err) {
   console.log('Error', err);
  } else {
  return res
  }
}

let folds =  glob(src + '/**/*', getFiles);

A: I had the same problem.
glob() is asynchronous and that can make returning the end result somewhat complicated.
Use glob.sync() instead (where .sync stands for synchronous)
Example:
const files = glob.sync(src + '/**/*');


text:
Q: Category name update with category Id in magento2 I am trying below code to update category name and parent id by categoryId,
 public function __construct(
    \Magento\Catalog\Model\CategoryFactory $categoryFactory

) {
    $this->categoryFactory = $categoryFactory;

}
 $catId = 5;
$name = 'test';
try {
   $category = $this->categoryFactory->create()->setStoreId(1)->load($catId);
   $category->setName($name);
   $category->save();
  echo "Category is updated successfully";
}
catch (Exception $e) {
        print_r($e->getMessage());
}

But category name is not updating for me. Where i am wrong please anyone suggest me

A: We need to identify the id of category tree root. Then, we created an instance of the category, set its path, parent_id, name, etc.
$parentId = \Magento\Catalog\Model\Category::TREE_ROOT_ID;

$parentCategory = $this->_objectManager
                      ->create('Magento\Catalog\Model\Category')
                      ->load($parentId);
$category = $this->_objectManager
                ->create('Magento\Catalog\Model\Category');
//Check exist category
$cate = $category->getCollection()
            ->addAttributeToFilter('name','test')
            ->getFirstItem();

if(!isset($cate->getId())) {
    $category->setPath($parentCategory->getPath())
        ->setParentId($parentId)
        ->setName('test')
        ->setIsActive(true);
    $category->save();
}

You can try this it's working fine for me.


text:
Q: How can I make three.js update a scene after adding an object or group of objects? I am fairly new to three.js and have a problem I can't readily find an answer for.
Here is a codepen that should sum up the situation: http://codepen.io/anon/pen/PPYPzO
var container, stats;
var camera, controls, scene, renderer, raycaster, mouse;

init();
animate();
add_world();

var indie_render = true;
for(var j = 0; j < 20; j++){
  add_objects(20);
  indie_render = !indie_render;
  console.log("adding more objects...");
  if(!indie_render){render();}
}

function add_world(){
  var geometry = new THREE.BoxGeometry( 1000, 1000, 1000);
  var mesh = new THREE.MeshBasicMaterial( {color: 0xf5f5dc, wireframe: false, opacity: 0.2, transparent:true } );
  var world = new THREE.Mesh( geometry, mesh );
  scene.add( world );
  render();
}

function add_objects(num, indiv){
  var geometry = new THREE.SphereGeometry( 5, 32,32 );
  var material = new THREE.MeshBasicMaterial( { shading: THREE.FlatShading } );
  material.color.setRGB( Math.random(), Math.random(), Math.random() );
  for ( var i = 0; i < num; i ++ ) {
    var mesh = new THREE.Mesh( geometry, material );
    mesh.position.x = ( Math.random() - 0.5 ) * 1000;
    mesh.position.y = ( Math.random() - 0.5 ) * 1000;
    mesh.position.z = ( Math.random() - 0.5 ) * 1000;
    mesh.updateMatrix();
    mesh.matrixAutoUpdate = false;
    scene.add( mesh );
    if(indie_render){
      console.log("individual render");
      render();
    }
  }
}

function init() {
  camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 2000 );
  camera.position.set(500, 500, -1000);
    camera.up.set( 0, 1, 0 );
    camera.lookAt(500,500,500);
  controls = new THREE.OrbitControls( camera );
  controls.addEventListener( 'change', render );

  //world
  scene = new THREE.Scene();

  // lights
  light = new THREE.DirectionalLight( 0xffffff );
  light.position.set( 1, 1, 1 );
  scene.add( light );

  light = new THREE.DirectionalLight( 0x002288 );
  light.position.set( -1, -1, -1 );
  scene.add( light );

  light = new THREE.AmbientLight( 0x222222 );
  scene.add( light );

  renderer = new THREE.WebGLRenderer( { antialias: false } );
  renderer.setClearColor( 0x000000, 1 );
  renderer.setSize( window.innerWidth, window.innerHeight );
  renderer.sortObjects = false;
  container = document.getElementById( 'container' );
  container.appendChild( renderer.domElement );

  mouse = new THREE.Vector2();
  raycaster = new THREE.Raycaster();
  container.addEventListener( 'mousemove', onMouseMove, false );
  container.addEventListener( 'mousedown', onMouseDown, false );
  window.addEventListener( 'resize', onWindowResize, false );

}

function animate() {
  requestAnimationFrame( animate );
  controls.update();
}

function render() {
  renderer.render( scene, camera );
}

function onMouseMove( e ) {
  mouse.x = ( e.clientX / renderer.domElement.width ) * 2 - 1;
  mouse.y = - ( e.clientY / renderer.domElement.height ) * 2 + 1;
}

function onMouseDown( e ) {
  mouse.x = ( e.clientX / renderer.domElement.width ) * 2 - 1;
  mouse.y = - ( e.clientY / renderer.domElement.height ) * 2 + 1;

  if(e.button == 2){    //right button
    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObjects( scene.children, true );
    if ( intersects.length > 0 ) {
      var geometry = new THREE.SphereGeometry( 5, 32,32 );
      var material = new THREE.MeshBasicMaterial( { color:0xff0000, shading: THREE.FlatShading } );
      var mesh = new THREE.Mesh( geometry, material );
      mesh.position.set(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z);
      scene.add(mesh);
      render();
    }
  }
}

In this demo, I init() and animate() a blank scene, and then add a translucent cube, following what seems to be convention. Then I add groups of spheres to the scene in a nested for loop, randomly placing the spheres inside the cube and making a render() call after every scene.add() call.
Currently, the scene adds all the spheres and only then is visible to the user, even though I can add individual objects after the for-loop objects are added (by right-clicking on the cube). I need for the user to be able to watch as spheres are added, rather than waiting for the whole thing to be done.
I realize this may not be the most efficient way to render the scene, but it would be quite helpful if, for example, the info on the objects to be animated is arriving asynchronously from a server. Does anyone have a suggestion?
Thanks

A: 1) First: move call render() to animate:
function animate() {
  requestAnimationFrame( animate );
  render();
  controls.update();
}

2) Call add_objects asynchronously: setTimeout( add_objects, 0, 20 );
http://codepen.io/anon/pen/bVbEEP


text:
Q: Faild to update row mongoose Here is the code:
Item.findByIdAndUpdate(req.params.id, item, {new: true}, function(err, model){
          if(err){
              console.log('error');
          } else{
              console.log('success');
              res.redirect('/admin/filetype');
          }

      })

I am using those code to update a row of my table.. the id from paramiter is coming correctly and other values also..
But its consoling err as I console there but there not present any other error.

A: try this
 Model.findByIdAndUpdate(
    req.params.id,
    {
      foo: req.body.bla
    },
    { new: true }
    )
    .then(data => {
     // todo somethig
    })
    .catch(err => {
     // error handle here
    })


text:
Q: Build Failed: NPM: command not found - ReactJS project I am absolute beginner in Jenkins started learning from yesterday. I went through theory session yesterday that went quit well. However, on when I am trying hands on it I stuck with probably petty issue for Jenkins user.
I am running Jenkins on my mac machine and it's a completely brand new setup
here is the error
+ echo 'build start...'
build start...
[first-job] $ /bin/sh -xe /Users/Shared/Jenkins/tmp/jenkins2233817479314329111.sh
+ npm install
/Users/Shared/Jenkins/tmp/jenkins2233817479314329111.sh: line 2: npm: command not found
Build step 'Execute shell' marked build as failure
Finished: FAILURE

Project config.


text:
Q: How to use Scanner to extract integers from {int:int}? I have to read integers from stdin, it comes in following format:
{4:11},{23:29},{1:7}...

I tried to use scanner delimiter, but I think it has problem with the first '{'
Scanner scanner =  new Scanner(System.in).useDelimiter("\\D");
while (scanner.hasNext()){
  int x = scanner.nextInt();
  int y = scanner.nextInt();
}

I get this exception:
Exception in thread "main" java.util.InputMismatchException
 at java.base/java.util.Scanner.throwFor(Scanner.java:939)
 at java.base/java.util.Scanner.next(Scanner.java:1594)
 at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
 at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
 at Algorithm.main(Algorithm.java:63)

A: You are specifying a delimiter pattern with the following
    scanner.userDelimiter("\\D"); // This \\D is pattern which will be matched.

You need to specify the pattern it like following:
    scanner.userDelimiter("\\D+") // With + keyword you are saying that it can be 1 or more.

Latest working code should look like following:
    Scanner scanner =  new Scanner(System.in).useDelimiter("\\D+");
    while(scanner.hasNext()){
        int x = scanner.nextInt();
        int y = scanner.nextInt();

        System.out.println("x: " + x);
        System.out.println("y: " + y);
    }

The other example is explicitly parsing the string with regex which you may not needed to if you only looking for delimiter pattern matching.
Note: Since you getting with nextInt(), and not validating the input so if there is invalid input(different input does not contain int) then you will get exception

A: You simply need to extract continuous sequences of digits, regardless of the delimiter. You can read input line by line and parse with a \d+ regex:
Pattern pattern = Pattern.compile("\\d+");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  Matcher matcher = pattern.matcher(line);
  while (matcher.find()) {
    System.out.println(matcher.group());
  }
}


text:
Q: mapping class attributes to other (same attributes) class I have 2 classes with exactly the same named attributes (1 business class, and 1 data class).
At this moment i've written a 'convert' method that maps all the attributes van 1 class to the other:
private class BusinessLogic convert(Datalogic dataclass)
{
    Businesslogic businessclass = new BusinessLogic();
    businessclass.ID = dataclass.ID;
    businessclass.name = dataclass.name;
    .....
    return businessclass;
}

It seems to be that there must be a far more simpler way. I'm only not sure how to search for it. Can someone put me on the right track.

A: This is a task for a mapping tool, e.g. AutoMapper - if all the properties are named the same this pretty much is a one-line since by convention they will be mapped to the corresponding property in the target class.
For your particular example that could be:
Mapper.CreateMap<Datalogic, BusinessLogic>();
BusinessLogic businessclass = Mapper.Map<Datalogic, BusinessLogic>(dataclass);

A: AutoMapper is a library available which does this Object to Object mapping for you.
With AutoMapper, Your code can be reduced to some thing like
Mapper.CreateMap<Datalogic , Businesslogic >();
Product product= GetProductFromDB(2);
Businesslogic productViewItem = Mapper.Map<Datalogic , Businesslogic >(product);

Home page: http://automapper.org/
Source: https://github.com/AutoMapper/AutoMapper
Tutorial link http://www.codeproject.com/Articles/61629/AutoMapper


text:
Q: Python, compare numbers I tried to write code as below to compare a serious of numbers.
largest = None
smallest = None
while True:
    nums = numl = input("Enter a number: ")

    if numl == "done" : break

    if smallest == None:
        smallest = nums
    elif smallest > nums:
        smallest = nums
    print(smallest)

    if largest == None:
        largest = numl
    elif largest < numl:
        largest = int(numl)
    print(largest)

print("Maximum is", largest)
print("Minimum is", smallest)

However, it makes the wrong result or even post error
Can someone help to check it?
Thank you in advance.

A: First of all I would request you to post the code with the question rather than an image link.
According to your code, you are taking input() which returns string, then you are trying to see if a string is > a int
which won't work
you can compare int with int and str with str


text:
Q: overflow:hidden jumps to top in Safari I try to achieve a scrollable lightbox without the effect of "furtherscrolling" the content behind it. So I set my html tag to "overflow:hidden" which works just fine in Chrome but not on Safari.
Any ideas how to fix this?

A: Try to add position:relative to your element

A: You have to disable momentum/inertia scrolling to make it work in iOS, have a look at this link. This worked for me
How to disable inertial scrolling on body for iOS browsers?


text:
Q: Make only enumeration of restriction default value in jaxb I have something like this in xsd (which I cannot edit):
<xsd:simpleType name="Foo">
    <xsd:restriction base="xsd:string">
        <xsd:enumeration value="BAR"/>
    </xsd:restriction>
</xsd:simpleType>

JAXB generates this java code in class representing element, which has Foo as child:
    public Foo getValue() {
        return value;
    }

    public void setValue(Foo value) {
        this.value = value;
    }

But there is only one possible value of Foo, so I would prefer to see something like this in my java code:
public Foo getValue() {
    if( value == null )
    {
        return Foo.BAR; //Foo already is defined as enum, so this code is fine
    }
    return value;
}

Is there some easy way to make this happen in JAXB?

A: to sum up, you are expecting a default value for Foo ? if so try to add a default value on the  Foo type element instead.
see http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints for default value


text:
Q: Best way to handle buttons with an action (but not form action) In my code I use the aristo design buttons, I insert them like:
    %button.aristo-default
      &laquo My button text

This works very inconvenient cause sometimes I need a link on the button and that is not possible with this code without using query on click events { :onclick => '' )
What would be a good way to implement a link in rails and make it look like a button, just plain CSS hacking or are there some other good methods?
UPDATE:
Since I'm only looking to make a link look like a button, I think I better look for a solution to do so in CSS. Using the button element implies a form post wich I don't care about, just getting my link "buttoned"

A: Depending on what you are trying to do, suggest using the button_to helper. This helps implement a POST to a specified URL (or you can specify other HTTP verbs if those are appropriate). See here for Rails documentation on button_to
Alternatively, if you want a form tag helper, try button_tag - you can read more about this here.
If you are just looking to take a link and style it as a button (keeping in mind that the general philosophy is that buttons are meant for those links/actions that result in something changing), you could just give your <a> element a class of button and style that using CSS.


text:
Q: How to build a dataframe instead of just printing list from a for loop? I have a for loop that generates a list but I'd like to turn that into a dataframe. I get stuck with how to correctly append the elements. Currently, this is my for loop and a snippet of what I get back
#find all course titles and print list
courseTitleElems = driver.find_elements_by_xpath("//h3[@class='head']")
for courseTitleElem in courseTitleElems:
    courseTitle = courseTitleElem.text
    timeElems = courseTitleElem.find_elements_by_xpath("following-sibling::div/div[contains(@id,'children')]//div[contains(@class,'timeColumn')]")
    print("\n" + courseTitle)
    for timeElem in timeElems:
        timeColumn = timeElem.get_attribute("textContent").strip("\n")
        print("\n" + timeColumn)

and what prints is this
1- Freshman Computer Science
     F
     9am-9:50am
     M
     9am-9:50am
19- From Impossible to I'm Possible: Analysis of Impostor Phenomenon
     T
     10am-11:50am
     TH
     8am-9:50am
     W
     9am-9:50am

My goal is to build a dataframe that looks something like this
Course Title                      Day        Time
1- Freshman Computer Science      F          9am-9:50am
19- From Impossible to I'm..      M          9am-9:50am

A: You will need to put the values you want in a list of dictionaries or a list of lists. Then, you can give that list-of-dictionaries to pandas.DataFrame() and it'll create the dataframe for you. For example,
# This list will hold all the rows that we want to make the dataframe with
alldata = []

for courseTitleElem in courseTitleElems:
    courseTitle = courseTitleElem.text.strip()
    timeElems = courseTitleElem.find_elements_by_xpath("following-sibling::div/div[contains(@id,'children')]//div[contains(@class,'timeColumn')]")

    # Based on your output, it looks like items in timeElems alternate between day of week and time.
    # So we take alternate elements as dayElem and timeElem using zip() and list slicing
    for dayElem, timeElem in zip(timeElems[::2], timeElems[1::2]):
        timeColumn = timeElem.get_attribute("textContent").strip() # strip ALL whitespace
        dayColumn = dayElem.get_attribute("textContent").strip()

        # Create the dictionary containing the data for each row
        courseinfo = {"Course Title": courseTitle, "Day": dayColumn, "Time": timeColumn}
        # Append the dictionary to the main list.
        alldata.append(courseInfo)

# Now that you've parsed everything, make the dataframe
df = pd.DataFrame(alldata)


text:
Q: Merging params and IList constructors Is there any way to merge these two constructors into one? Basically they accept the same array of Point3D type.
public Curve(int degree, params Point3D[] points) {}

public Curve(int degree, IList<Point3D> points) {}

Thanks.

A: If you want to have 2 different constructors you can:
public Curve(int degree, params Point3D[] points) : this(degree, (IList<Point3D>)points) { }
public Curve(int degree, IList<Point3D> points) { }

Or if you want only one constructor lets say the first then you can initialize like this:
new Curve(0,new List<Point3D>().ToArray());

By having one constructor calling the other you don't need to duplicate all your logic and you still enable both formats of initialization.

Though Array implements IList<T> one cannot remove the (IList<Point3D) due to compile error of: compiler ...... cannot call itself

A: If it looked like this:
public Curve(int degree, Point3D[] points)
{
    ...
}

public Curve(int degree, IList<Point3D> points)
{
    ...
}

than you could use: (as long as you only need to iterate on the collection for its contained Point3Ds)
public Curve(int degree, IEnumerable<Point3D> points)
{
    ...
}

However, since you want to have a params constructor, that it impossible to do because you won't be able to invoke the constructor like that:
Curve curve = new Curve(30, p1, p2, p3);

But only like that:
Curve curve = new Curve(30, new Point3D[] {p1, p2, p3});

You can reuse their code by using:
public Curve(int degree, params Point3D[] points)
{
    ...
}
public Curve(int degree, IList<Point3D> points) : this(degree, points.ToArray()) { }

or the other way around:
public Curve(int degree, IList<Point3D> points)
{
    ...
}
public Curve(int degree, params Point3D[] points) : this(degree, points as IList<Point3D>) { }

which will initialize the instance using the params constructor the same way it uses the List one.
P.S.: You might want to consider changing the IList to IEnumerable anyway to allow the user of that class to use it more abstractly.

A: If I'm understanding you correctly, the problem is that you can not simply do the following:
public Curve(int degree, params Point3D[] points)
            : this(degree, points) //want to chain to (int, IList<Point3D>) constructor
{
}

public Curve(int degree, IList<Point3D> points)
{
}

Because you get the following compile time error: Error CS0516 Constructor 'Curve.Curve(int, params int[])' cannot call itself".
You can get around this by simply casting the reference to the appropiate type
public Curve(int degree, params Point3D[] points)
    : this(degree, (IList<Point3D>)points)
{
}

This works because and array T[] implements IList<T>.


text:
Q: Picture is not showing in jsp page My image is not showing in JSP page.I am using Eclipse.I have created a folder 'img' in WEB-INF folder,then saved the picture in this and the code in jsp page is .Why the picture is not showing?

A: WEB-INF is not publicly available.  The servlet container protects this directory in your web app, and no resources will be served directly from this directory.  img/home.jpg will be relative to the directory of the current page.  Try moving the img folder to the top level of your web app (the same level as WEB-INF).  Then use the absolute path in your img tag: /img/home.jpg.

A: You need to keep img folder at the same level as WEB-INF.
Keep static files like HTML, image, stylesheet, javascript, etc. under the web root, not inside WEB-INF because it is not accessible.
After doing this,Change your img tag like this

See Also

*

*Folder structure in web application


text:
Q: What graph traversal algorithm should I use for this? I need to traverse a directed graph in a certain way and I'm not sure the algorithm to use. Perhaps Stackoverflow can help.
The situation
- I have a directed graph where the edges have a number associated with them. Let's assume this number is a distance measured in feet, miles, ..., whatever.
I'd like to traverse from a start node and find all edges that are some defined distance from the start node
For example, I want to start at some node and traverse the graph and find every edge where I've traveled 100 miles from the start.
For example(2),
start_node ---- edge-1(80 miles) ---> node(2) ---- edge-2(40 miles) ---> node(3) ---edge-3(50 miles) ---
start_node ---- edge-4(40 miles) ---> node(4) ---- edge-5(70 miles) ---> node(5) ---edge-6(50 miles) ---
Starting at start_node and traveling 100 miles the answer would be edge-2, edge-5.
Any thoughts on what traversal algorithm I should be using/considering?
Thanks

A: I would choose Dijkstra algorithm. Just stop when the path to the last marked node is more than defined.

A: Dijkstra's algorithm.

A: Assuming no edge can be traversed more than once, your problem is a generalization of the Longest path problem, which is NP-hard. Therefore, polynomial-time approaches like Dijkstra's algorithm won't work.
If your graph is not very large, you could do dynamic programming: a table D[v, k] that stores for each vertex v and each number of edges all possible distances from the root to v with k edges, plus all possible predecessors for each possible distance. D[v, k] can be filled in if D[v, k-1] is done. You repeat this until no distance is below 100 anymore, and then you can do backtracking from each vertex that has reached cost exactly 100.

A: i think you can use something similar to Dijkstra's algorithm
http://en.wikipedia.org/wiki/Dijkstra's_algorithm


text:
Q: Why isn't my callback function for this Jquery .post working? Here is the code for the jquery:
<script type="text/javascript">
    $(document).ready(function(){
        $('#room').submit(function(){
            $.post('backend/CreateRoom.php', $('#room').serialize() ,function(data) {
                alert(1);
                $('#llama').append(data);
                console.log('working');
            });
        });
        return false;
     });
</script>

The function part does not seem to be working. The PHP code on the backend/CreateRoom.php seems to work fine(the code updates a PHP database) works fine, it just doesnt update the div, or do anything I put in the function. Help?

A: Looks like you are returning false on document ready. I think you want that on submit.
$(document).ready(function(){
    $('#room').submit(function(){
        $.post('backend/CreateRoom.php', $('#room').serialize() ,function(data) {
            alert(1);
            $('#llama').append(data);
            console.log('working');
        });
     return false;
    });

});

or prevent default:
$(document).ready(function(){
    $('#room').submit(function(event){
        event.preventDefault();
        $.post('backend/CreateRoom.php', $('#room').serialize() ,function(data) {
            alert(1);
            $('#llama').append(data);
            console.log('working');
        });
    });
});


text:
Q: Indexing dictionary in depth, two cases When indexing dictionary in depth I've found different results in the same (as I think) constructions:
q)d:`a`b!(1 2 3;4 5 6)
q)d[`a`b;0]
1 4
q)d[`a`b]0
1 2 3

Why is this happening? How q understands and distinguishes two different cases? Before this I was confident that, for example, calling dyadic function f[a;b] and f[a]b are the same. And now I am not sure even about this.

A: To index at depth you either need semi colons separating your arguments, or use the dot. Your second example,
d[`a`b] 0

Is taking the 2 lists from the dictionary values and then indexing to return the first.
While
d[`a`b;0]

or
 d .(`a`b;0)

Is taking the 2 lists, and then indexing at depth, taking the first element of each, due to the semi colon/dot
When you call a dyadic function it is expecting two parameters, passing one inside the square brackets creates a projection, which is basically using an implicit semi colon, so
f[a]b

is the same as
f[a;]b

which is the same as
f[a;b]

The result of
f[a]

is a projection which is expecting another argument, so
f[a] b

evaluates f[a], then passes argument b to this function, with usual function application via juxtaposition
Your dictionary indexing example does not create a projection, and hence the indexing is not expecting any more arguments, so the first indexing
d[`a`b]

is evaluated immediately to give a result, and then the second index is applied to this result.
It would work the same for a monadic function
q){5+til x}[5] 2
7

Like the top level dictionary index, the application is carried out and then the result is indexed, as only one argument was expected, with no projection involved

A: EDIT - Adam beat me to it!
I don't think you can consider a function invocation f[a;b] or f[a]b as equivalent to indexing. f[a]b for a function is a projection but you can't project indexing in the same way. A function has a fixed valence, aka fixed number of inputs, but indexing can be done at any depth.
If you take your dictionary and fabricate it to have more depth, you can see that you can keeping indexing deeper and deeper:
q)d:{`a`b!2#enlist value x}/[1;d]
q)d[`a`b;1;1]
5 5
q)d:{`a`b!2#enlist value x}/[2;d]
q)d[`a`b;1;1;1;1]
5 5
q)d:{`a`b!2#enlist value x}/[2;d]
q)d[`a`b;1;1;1;1;1;1]
5 5

Yet you can still index just at the top level d[`a`b]. So the interpreter has to decide if its indexing at the top level, aka d @ `a`b or indexing at depth d . (`a`b;0).
To avoid confusion it indexes at top level if you supply one level of indexing and indexes at depth if you supply more than one level of indexing. Thus no projections (at least not in the same manner).
And as mentioned above, functions don't have this ambiguity because they have a fixed number of parameters and so they can be projected.

A: What's happening here is that d[`a`b] has the depth/valence as d. So when you apply d[`a`b]0 the zero is not indexing at depth. You get expected results if you don't index multiple values of your dictionary:
q)d[`a`b;0]~d[`a`b][0]
0b
q)d[`a;0]~d[`a][0]
1b
q)d[`b;0]~d[`b][0]
1b

This is more clear if you instead consider a 2x3 matrix which has identical behavior to your original example
q)M:(1 2 3;4 5 6)
q)M[0 1;0]
1 4
q)M[0 1][0]
1 2 3

Indexing any one row results in a simple vector
q)type M[0]
7h
q)type M[1]
7h

But indexing more than one row results in a matrix:
q)type M[0 1]
0h

In fact, indexing both rows results in the same exact matrix
q)M~M[0 1]
1b

So we should expect
q)M[0]~M[0 1][0]
1b

as we see above.
None of this should have an impact on calling dyadic functions, since supplying one parameter explicitly results in a function projection and therefore the valence is always reduced.
q)type {2+x*y}
100h
q)type {2+x*y}[10]
104h


text:
Q: Determining min and max values in an ASCII raster dataset using Python? I have a raster dataset in ASCII format. Using Python, I need to determine the min and max values inside the dataset. I've been told that the header information is key, which contains things like number of rows/columns, cell size, and etc.
Can't you simply skip the header information and read the entire dataset to determine the min and max values?
This is what I'm trying to do. I'm skipping the first couple of lines which contain the header information, and trying to determine the values from there on. The following is sort of what I have, but need some guidance as I am new to Python.
raster_file = open('data.asc', 'r') # Open the file
data = raster_file.readlines()[4:] # Read the lines in the file, and skip the first six lines

for lines in data:
    print max(data) # Find the max value in data
    print min(data) # Find hte min value in data

Any suggestions?

A: You want raster data statistics.
See what you are doing in the gui first (for homework.)
Then you can use a python window or a script.
import arcpy
arcpy.CalculateStatistics_management("c:/data/image.tif", "4", "6", "0;255;21")

A: import sys

class Ascii_file(object):
    def __init__(self,file):
        self.raster_file = open(file, 'r') # Open the file
        self.max=sys.float_info.min
        self.min=sys.float_info.max
    def __minmax(self,value):
        if value>self.max:self.max=value
        if value<self.min:self.min=value
    def getMinMax(self):
        data = self.raster_file.readlines()
        data_values=data[6:]
        nodata=float(data[5].split()[1])
        for line in data_values:
            values=line.split(" ")
            for value in values:
                value=float(value)
                if value==nodata:continue
                else: self.__minmax(value)
        return self.min, self.max

if __name__=="__main__":
    myfile = Ascii_file('data.asc')
    print myfile.getMinMax()

A: You can use numpy.  See the example below.  A numpy masked array can be generated accounting for the no data values.  See the numpy help topic for mafromtxt and genfromtxt
Below is a small ascii file with a nodata value of -999

ncols          3
nrows          3
xllcorner      0
yllcorner      0
cellsize       1
NODATA_value   -999
0 1 2
-999 4 5
6 7 8

>>> import numpy as np
>>> ascii_file = "c:/temp/Ascii_3x3_1nodata.asc"
>>> an_array = np.mafromtxt(ascii_file, 'float', '#', None, 6, None, '-999')

>>> print an_array

[[0.0 1.0 2.0]
 [-- 4.0 5.0]
 [6.0 7.0 8.0]]

>>>

from there it is simply a matter to determine the statistics you want
>>> print an_array.min()
0.0
>>> print an_array.max()
8.0
>>> print an_array.mean()
4.125
>>>

A: If you don't want to use numpy (and you really should, it's perfect for this sort of thing), then you will need to:

*

*initialise your maximum variable to a very large negative number and your minimum variable to a very large positive number

*split each line to get a list of strings and use list comprehension to convert it to a list of floats

*finally use something like maximum = max(maximum, max(myfloatlist)) and an equivalent for the minimum value.

A: I just did this the other day. I used arcpy.RasterToNumPyArray, converted the numpy array to a list, then iterated through my list via a list comprehension to find the min and max values.
import arcpy
import numpy
myArray = arcpy.RasterToNumPyArray(r"D:\NED_93512417\NED_93512417_3DEM_RPRJ.TIF")
p = myArray.tolist()

max_elev = max([item for sublist in p for item in sublist])
min_elev = min([item for sublist in p for item in sublist])


text:
Q: Realm Java query on two columns of nested object Here is my Structure:
class Class1 {
  String name;
  RealmList<Class2> objects;
}

class Class2{
  String field1;
  String field2;
  String field3;
}

What I want to do is query all the Class1 object where Class2.field1 in ["someValue1"] and Class2.field2 = "someValue2" but unable to do so.
Here is my query:
realm.where(Class1.class).in("objects.field1",getField1Array()).equalTo("objects.field2", getField2()).findAll()
Above query does or operation on field1 and field2 where as what i want is and operation.
Is it possible to query by 2 columns of nested object? if yes than how?
Example:
{
    "class1": [
        {
            "name": "JOHN",
            "objects": [
                {
                    "field1": "COMPLETE",
                    "field2": "f2"
                },
                {
                    "field1": "HOLD",
                    "field2": "f3"
                }
            ]
        },
        {
            "name": "JOHN",
            "objects": [
                {
                    "field1": "COMPLETE",
                    "field2": "f1"
                },
                {
                    "field1": "HOLD",
                    "field2": "f3"
                }
            ]
        }
    ]
}

In this query
realm.where(Class1.class).in("objects.field1",["COMPLETE", "INPROGESS"]).equalTo("objects.field2", "f3").findAll()

I expect query to return empty list, but I received both the object.

A: realm.where(Class1.class)
  .in("objects.field1",["COMPLETE", "INPROGESS"])
  .findAll()
  .equalTo("objects.field2", "f3")
  .findAll()

If that doesn't work, then what you need to do is set up a bi-directional relationship, and invert the query to be based on Class2 instead of Class1.


text:
Q: Data retrieval query for firebase not working
Above is the db structure and below is the code to retrieve the data from firebase database, I am unable to get the data from my db.I need help in retrieving the data from my firebase db.I have attached the database image for the view of my db.
function check(userId,snapcity){
  var rootRef=firebase.database().ref().child('users');
    rootRef.on('child_added', function(snap){
      if(snap.child("userId").val()==userId){

        snapcity=snap.child("city").val();
      }
  });
  console.log(snapcity);
      console.log(ajaxData.geoplugin_city);
  if(snapcity){
    if(snapcity!=ajaxData.geoplugin_city){
      logout();
      alert("you can't login because previously you were logged from "+snapcity );

    }
  }
}
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {

    // User is signed in.
    userId=user.uid;
    //alert(userId);
    var date = new Date();
    var n = date.toDateString();
    var time = date.toLocaleTimeString();
    datetime=n+" "+time;
    snapcity="";
    check(userId,snapcity);
    var database = firebase.database();
    writeUserData(userId,ajaxData.geoplugin_request,ajaxData.geoplugin_city,datetime);
    document.getElementById("user_div").style.display = "block";
    document.getElementById("login_div").style.display = "none";

    var user = firebase.auth().currentUser;

    if(user != null){

      var email_id = user.email;
      document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
      console.log('data');
      console.log(ajaxData);
      html="
ip: "+ajaxData.geoplugin_request+"

Country Code: +44

Country: "+ajaxData.geoplugin_countryName+"

Country Abbrevation: "+ajaxData.geoplugin_countryCode+"

Region Code: "+ajaxData.geoplugin_regionCode+"

Region Name: "+ajaxData.geoplugin_regionName+"

City: "+ajaxData.geoplugin_city+"

Time Zone: "+ajaxData.geoplugin_timezone+"

Latitude: "+ajaxData.geoplugin_latitude+"

Longitude: "+ajaxData.geoplugin_longitude+"

Last Login: "+datetime+"
";
      $('#data').html(html);
    }

     } else {
        // No user is signed in.

document.getElementById("user_div").style.display = "none";
        document.getElementById("login_div").style.display = "block";

      }
    });

  [1]: https://i.stack.imgur.com/JVeRD.jpg

A: This:
rootRef.on('child_added', function(snap){
  if(snap.child("userId").val()==userId){
    snapcity=snap.child("city").val();
  }
});

Can be replaces by:
rootRef.child(userId).once('value', function(snap){
  snapcity = snap.child("city").val();
});

Next you need to move all code that needs snapcity into the callback function. So:
rootRef.child(userId).once('value', function(snap){
  snapcity = snap.child("city").val();
  console.log(snapcity, ajaxData.geoplugin_city);
  if(snapcity){
    if(snapcity!=ajaxData.geoplugin_city){
      logout();
      alert("you can't login because previously you were logged from: "+snapcity );
    }
  }
});


text:
Q: PHP valid http statuses On my website users can enter a HTTP status code into a standard text input field. i.e, 200, 400, 404, 403 etc...
Is there any way to check if the HTTP status code is valid. For example if a user enters '123' it will return false. I currently cannot think of or find a way other than doing a large ugly if or switch statement.

A: According to w3.org the following HTTP/1.1 status codes are valid:
$status_code = array("100","101","200","201","202","203","204","205","206","300","301","302","303","304","305","306","307","400","401","402","403","404","405","406","407","408","409","410","411","412","413","414","415","416","417","500","501","502","503","504","505");

if(in_array("404", $status_code)){
    echo "valid";
  }else{
    echo "invalid";
  }

A: For those using Symfony or Laravel, you can do the following :
use Illuminate\Http\Response;

function is_valid_http_status(int $code) : bool {
    // thanks @James in the comments ^^
    return array_key_exists($code, Response::$statusTexts);
}

Assuming that Response is one of those:

*

*Symfony\Component\HttpFoundation\Response

*Illuminate\Http\Response

A: There are no built-in functions to achieve this in PHP, but a less verbose way for a check than an if or switch statement could be the use of an array:
$validStatusCodes = [200, 201, 202, ...];

if (in_array($submittedStatusCode, $validStatusCodes)) {
    // Ok
} else {
    // Not ok
}


text:
Q: Django form with just a BooleanField I'm rather new to Django and I'm using Django 1.0.
I have this:
forms.py:
class MyForm(forms.Form):
    extra_cheeze = forms.BooleanField(required=False,
                                      initial=False,
                                      label='Extra cheeze')

views.py:
def order_something(request):
    form = MyForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        # do stuff...

The problem is that the form is not valid unless the checkbox is checked, so there doesn't seem to be a way to get a False value from the field.
As far as I can understand from the docs, it should work. It works if I add a CharField to my form...
Am I misunderstanding something here or is this a bug? (Yes, I have googled but found nothing relevant)
Update: As suggested by @Dominic Rodger, I tried adding a hidden field
dummy = forms.CharField(initial='dummy', widget=forms.widgets.HiddenInput())
and that makes the form valid. This workaround enables me to move on right now, but it would still be interesting to know if I'm misunderstanding something...

A: This also works for me on 1.1, 1.0.3 and 1.0 (I have these three Virtual environments setup). I only tested this in FireFox so if its a browser issue thats another matter but as far as I know they all handle POST data with checkboxes the same.
Here is the full code for the project so you can reproduce at your leisure and compare with yours to see the difference.
Setting up in Ubuntu
$ django-admin.py startproject testing
$ cd testing/
$ python manage.py startapp myfirst

Then in the myfirst app folder;
/myfirst/views.py
from django.shortcuts import render_to_response

from myfirst.forms import MyForm

def testing(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            result = "valid"
        else:
            result = "not valid"
    else:
        form = MyForm()
        result = "no post"

    return render_to_response('test.html', {'form':form, 'result':result,})

/myfirst/forms.py
from django import forms
class MyForm(forms.Form):
    extra_cheeze = forms.BooleanField(required=False,initial=False,label='Extra cheeze')

/myfirst/templates/test.html
<html>
<head>
</head>
<body>
    <form action="." method="POST">
        {{ form }}
        <input type="submit" value="test">
    </form>
    {{ result }}
</body>
</html>

/urls.py
    from django.conf.urls.defaults import *
from myfirst.views import testing

urlpatterns = patterns('',
     (r'.*', testing),
)

Then just run the project $ python manage.py runserver and browse to http://localhost:8000/. You'll actually find that required doesn't do anything with the checkbox, since you can't leave it blank - a 'blank' answer is effectively 'no'. If you want to make sure a user selects an answer have a multiple choice where the user has to select yes or no. You could force them to answer with radio buttons too.

A: There was a bug in the code in my question. Thanks to @d0ugal for helping me spot it by including a slightly different example.  The problem was here:
form = MyForm(request.POST or None) # <- PROBLEM HERE!!!!!!!!!!!!!!!!
if request.method == 'POST' and form.is_valid():
    # do stuff...

The bug was that I assumed that request.POST would evaluate to True if it was a post. But since browsers don't post anything for a not-checked checkbox, and that was the only field, the POST data was an empty dictionary, which evaluates to False. This caused None to be used as initialization data, causing the form to be unbound and not valid.
@d0ugal's example does the safe thing and tests request.method first.

A: This is not an answer, it describes the Django behaviour only.
Django 3.0.7 on Python 3.8.4rc1, Debian 10/testing.
My scenario is html <form> with more django forms.Form rendered classes inside, one of them has BooleanField only. (There are other small <forms> in page like a search form).
class OrderInvoiceTypeForm(forms.Form):
    is_business = forms.BooleanField(label="business", initial=False)  # with or without required=False

I submit via submit button which IS NOT in OrderInvoiceTypeForm but IS in the html .
With required=False form is always valid and is_business key is in .cleaned_data.
Without required (or with =True):
checked:
form_with_boolean.is_valid()    # True
form_with_boolean.cleaned_data  # {'is_business': True}

unchecked:
form_with_boolean.is_valid()    # False
form_with_boolean.cleaned_data  # {}

In 2nd case in dev tools I can see that browser (Chrome) doesn't send the is_business value POST variable. Adding of hidden field will not help.


text:
Q: Divide 2 columns and create new column with results I have a data frame with columns:
User_id PQ_played PQ_offered
 1           5        15
 2          12        75
 3          25        50

I need to divide PQ_played by PQ_offered to calculate the % of games played. This is what I've tried so far:
new_df['%_PQ_played'] = df.groupby('User_id').((df['PQ_played']/df['PQ_offered'])*100),as_index=True

I know that I am terribly wrong.

A: It's much simpler than you think.
df['%_PQ_played'] = df['PQ_played'] / df['PQ_offered'] * 100

         PQ_offered  PQ_played  %_PQ_played
User_id
1                15          5     33.333333
2                75         12     16.000000
3                50         25     50.000000

A: You can use lambda functions
df.groupby('User_id').apply(lambda x: (x['PQ_played']/x['PQ_offered'])*100)\
.reset_index(1, drop = True).reset_index().rename(columns = {0 : '%_PQ_played'})

You get
    User_id %_PQ_played
0   1       33.333333
1   2       16.000000
2   3       50.000000

A: I totally agree with @mVChr and think you are over complicating what you need to do. If you are simply trying to add an additional column then his response is spot on. If you truly need to groupby it is worth noting that this is typically used for aggregation, e.g., sum(), count(), etc. If, for example, you had several records with non-unique values in the User_id column then you could create the additional column using
df['%_PQ_played'] = df['PQ_played'] / df['PQ_offered'] * 100

and then perform an aggregation. Let's say you wanted to know the average number of games played of the games offered for each user, you could do something like
new_df = df.groupby('User_id', as_index=False)['%_PQ_played'].mean()

This would yield (numbers are arbitrary)
   User_id  %_PQ_played
0        1    52.777778
1        2    29.250000
2        3    65.000000


text:
Q: How to install iproute2 on OEL6 OCI image I need to use ip l2tp in OEL6 image from OCI. I am not able to get a newer version of iproute2 since the one i have doesn't have ip l2tp:
Usage: ip [ OPTIONS ] OBJECT { COMMAND | help }
       ip [ -force ] -batch filename
where  OBJECT := { link | addr | addrlabel | route | rule | neigh | ntable |
                   tunnel | maddr | mroute | mrule | monitor | xfrm | token
}
       OPTIONS := { -V[ersion] | -s[tatistics] | -d[etails] | -r[esolve] |
                    -h[uman-readable] | -iec |
                    -f[amily] { inet | inet6 | ipx | dnet | link } |
                    -o[neline] | -t[imestamp] | -b[atch] [filename] |
                    -rc[vbuf] [size]}

i have the following version:
rpm -qi iproute
Name        : iproute                      Relocations: (not relocatable)
Version     : 2.6.32                            Vendor: Oracle America
Release     : 57.0.1.el6                    Build Date: Tue 01 May 2018 07:11:37 PM GMT
Install Date: Fri 22 Feb 2019 12:50:48 AM GMT      Build Host: x86-ol6-builder-04.us.oracle.com
Group       : Applications/System           Source RPM: iproute-2.6.32-57.0.1.el6.src.rpm
Size        : 964229                           License: GPLv2+ and Public Domain
Signature   : RSA/8, Tue 01 May 2018 07:11:56 PM GMT, Key ID 72f97b74ec551f03
URL         : http://www.linuxfoundation.org/collaborate/workgroups/networking/iproute2
Summary     : Advanced IP routing and network device configuration tools
Description :
The iproute package contains networking utilities (ip and rtmon, for
example) which are designed to use the advanced networking
capabilities of the Linux 2.4.x and 2.6.x kernel.

i upgraded all the packages:
yum update
Loaded plugins: security, ulninfo
Setting up Update Process
No Packages marked for Update

I downloaded the newest version of iproute2:
 wget https://mirrors.edge.kernel.org/pub/linux/utils/net/iproute2/iproute2-5.0.0.tar.gz
and i tried to compile it:
make

lib
    CC       libgenl.o
In file included from ../include/uapi/linux/kernel.h:5,
                 from ../include/uapi/linux/netlink.h:5,
                 from ../include/uapi/linux/genetlink.h:6,
                 from libgenl.c:10:
../include/uapi/linux/sysinfo.h:9: error: expected specifier-qualifier-list before '__kernel_long_t'
make[1]: *** [libgenl.o] Error 1
make: *** [all] Error 2

searching for the error i stumbled upon this:
https://patchwork.ozlabs.org/patch/843454/
Any ideas how to get iproute2?
thank you,
C.

A: Here's a fast way to get it upgraded.

*

*Look at the current version:

$ ip -V
ip utility, iproute2-ss091226

*Create a new file referencing the OL6 OpenStack 1.0 repo and add the repo (here are the contents that I used):

$ cat /etc/yum.repos.d/oracle-openstack-ol6.repo
[ol6_openstack10]
name=Oracle Linux $releasever OpenStack 1.0 ($basearch)
baseurl=http://yum$ociregion.oracle.com/repo/OracleLinux/OL6/openstack10/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
gpgcheck=1
enabled=1

*Run sudo yum update (you should see iproute it in the list of updated packages)

*Validate that the version was changed:

$ ip -V
ip utility, iproute2-ss130221

*Finally, you can check to see if l2tp is listed now (mine has it - copied below):

$ ip
Usage: ip [ OPTIONS ] OBJECT { COMMAND | help }
       ip [ -force ] -batch filename
where  OBJECT := { link | addr | addrlabel | route | rule | neigh | ntable |
                   tunnel | tuntap | maddr | mroute | mrule | monitor | xfrm |
                   netns | l2tp | tcp_metrics }
       OPTIONS := { -V[ersion] | -s[tatistics] | -d[etails] | -r[esolve] |
                    -f[amily] { inet | inet6 | ipx | dnet | bridge | link } |
                    -l[oops] { maximum-addr-flush-attempts } |
                    -o[neline] | -t[imestamp] | -b[atch] [filename] |
                    -rc[vbuf] [size]}


text:
Q: how to make a coroutine finish first before other coroutine start Hi im a newbie in unity and c#..
I have two script file in the same scene,
1 coroutine in file versionchecker.cs to get a version number data from my web server
public string versionURL = "http://localhost/check.php";

 IEnumerator GetVersion()
 {
     WWW vs_get = new WWW(versionURL);
     yield return vs_get;

     if (vs_get.error != null)
     {
         connection = 1;
     }
     else
     {
         currentVersion = vs_get.text;
         bundleVersion = PlayerSettings.bundleVersion;
         connection = 0;
     }
 }

But in another file in beginingscreen.cs, i have a coroutine for a begining screen..
 void Start () {
     if(!isExit)
         StartCoroutine (BeginningAnimation ());
     else
         StartCoroutine (EndAnimation ());
 }

 IEnumerator BeginningAnimation()
 {
     fade.FadeIn (1.5f);
     yield return new WaitForSeconds (2);
     fade.FadeOut (1);
     yield return new WaitForSeconds (0.9f);
     Application.LoadLevel (LevelToLoad);
 }

 IEnumerator EndAnimation()
 {
     yield return new WaitForSeconds (0.5f);
     fade.FadeOut (1);
     yield return new WaitForSeconds (1);
     Application.Quit ();
 }

this script i place it in the same scene of my game.. but sometimes the coroutine for begining screen finish first before the coroutine for get version because the get version need a connection to webserver, and sometime the web server is lagging..
so how can i make the get version coroutine finish first and after that begining screen can start..

A: Two different approaches:
You could just add the component script (beginingscreen.cs) only when the first coroutine finished executing. Thus ensuring that the other coroutines do not start too early.
IEnumerator GetVersion()
{
    // ...
    gameObject.AddComponent<BeginingScreen>();
}

You can make the Start method a coroutine in beginingscreen.cs, then call GetVersion and wait for its completion (GetVersion needs to be publicly visible) :
IEnumerator Start()
{
    var getVersion = gameObject.GetComponent<VersionChecker>();
    if (getVersion != null)
    {
        yield return StartCoroutine(getVersion.GetVersion());
    }

    if(!isExit)
        yield return StartCoroutine (BeginningAnimation());
    else
        yield return StartCoroutine (EndAnimation());
}

In both solutions, you need the two components (scripts) to somehow interact with each other. Or you can create a third script that handles this interaction.