How can I sample from a shifted and scaled Student-t distribution with a specified mean and sd in R?

Question: I'm currently building some Bayesian models with the brms package and the default intercept prior is student_t(3, 0, 6.3) and so I'm looking to visualise the prior predictive distribution from this prior. Typically I would just use functions like rnorm or unif depending on the distribution; however, the rt function only takes  n and df arguments and I cannot specify an SD of 6.3.
How can I sample from this distribution?
Comment: @Zen This is incorrect (if you meant the standard deviation by $\sigma$) as $t_\nu$ has variance $\frac{\nu}{\nu-2}$. It should be `x <- mu + sigma * sqrt((df-2)/df) * rt(n, df)`.
Comment: To clarify, the comments and answers suggest how to sample from a shifted and scaled Student-$t$ distribution, and this is probably what the OP intends. (I have edited the title accordingly.) This is different from sampling from a Student-$t$ distribution that is shifted but not scaled and where we know the sd from which we can derive the d.f. parameter.
Comment: The alternative compound Gaussian approach is to first generate `s<-1/rgamma(n,df/2,(df-2)*sigma^2/2)` and then `x<-rnorm(n,mu,s)`.
Answer: While that $6.3$ seems not to mean the standard deviation in Stan, if that's what you want to do...
...do it in multiple steps.

Simulate from the t-distribution with the appropriate degrees of freedom $\nu$, using rt.

Divide by the population standard deviation, $\sqrt{\frac{
\nu
}{
\nu-2
}}$. Now the population standard deviation is $1$.

Multiply by your desired standard deviation.

Add your desired mean, since the population mean is $0$.

You can combine these steps in one function.
rt_modified <- function(N, nu, mu, standard_dev){
    x1 <- rt(N, nu) # 1
    x2 <- x1/sqrt(nu/(nu-2)) # 2
    x3 <- x2 * standard_dev # 3
    x4 <- x3 + mu # 4
    return(x4)
}

Comment: This is wrong. @fisher-j is the correct answer. The original poster is asking specifically how to generate samples in R equivalent to the samples that Stan generates for the purpose of visualizing a prior in R.  The method that you suggest will not produce equivalent samples to what Stan sampler will produce. This matters because many Stan default prior recommendations (e.g. for logit-scale parameters ) make use of the Student-t.
Comment: Breaking it up into the four steps makes perfect sense, thanks a lot @Dave, much appreciated!
Answer: I tried @Dave answer, and got different results than those predicted by the random number generator used by Stan which is how priors are sampled when using brms::brm with sample_priors = TRUE.
The r function rt has a non-centrality parameter which gives similar results to stan when the scale of the stan student_t_rng function is set to 1, but doesn't support a "scale" parameter.
The function ggdist::rstudent_t is defined as:
function (n, df, mu = 0, sigma = 1)
{
    rt(n, df = df) * sigma + mu
}

We can test the stan function using the rstan package by exporting our own version of the stan student t random number generator. I'm using $DF = 3$, $\mu = 2$, and $\sigma = 2$.
library(rstan)

model_code <- "
  functions {
    real stan_student_t_rng() {
      return student_t_rng(3, 2, 2);
    }
  }
  model {}
"
expose_stan_functions(stanc(model_code = model_code))

And compare the results of the different approaches.
y1 <- rt_modified(1e4, 3, 2, 2)
y2 <- ggdist::rstudent_t(1e4, 3, 2, 2)
y3 <- sapply(numeric(1e4), \(x) stan_student_t_rng())
quantile(y1, c(0.05, 0.5, 0.95))
quantile(y2, c(0.05, 0.5, 0.95))
quantile(y3, c(0.05, 0.5, 0.95))

#                           5%       50%      95%
# rt_modified        -1.209507 0.1514803 1.513690
# rstudent_t         -2.601524 2.0410839 6.845778
# stan_student_t_rng -2.631746 2.0084448 6.712253

It would seem there is a difference in the interpretation of these two different approaches, but to get results similar to Stan, specifically the priors returned by brms::brm with sample_priors = TRUE, we can use the method used by ggdist::rstudent_t.
Comment: `sigma` is a scale parameter, *but it is not the standard deviation.*  There's nothing invalid about that--it's just a different parameterization.  To get results similar to Stan, you have to account for that, as Dave explained in the answer.
Comment: In that parameterization, $\sigma$ is not the SD: it rescales the standard student t distribution, whose SD is $\sqrt{\nu/(\nu-2)}.$ It's a good choice because all student t distributions with $\nu\le 2$ have *infinite* standard deviations.
Comment: That `rstudent_t` function does not divide by the population variance. I will not say that the function is wrong to do what it does, but skipping that step represents a different procedure than the function I gave, and that procedure is not what the original question seeks. To use that function means that `sigma` must consider both the targeted standard deviation and the standard deviation of $t_{\nu}$, which is the $\sqrt{\dfrac{\nu}{\nu - 2}}$ in the answer I posted.
Comment: @whuber stan uses this pdf: $\text{StudentT}(y|\nu,\mu,\sigma) = \frac{\Gamma\left((\nu + 1)/2\right)} {\Gamma(\nu/2)} \ \frac{1}{\sqrt{\nu \pi} \ \sigma}
\ \left( 1 + \frac{1}{\nu} \left(\frac{y - \mu}{\sigma}\right)^2
\right)^{-(\nu + 1)/2} $ . Does this reflect the same parameterization used in their random number generator where $\sigma$ is a scale and *not* the SD?
Comment: This is the correct answer to the original poster's question. While the original poster did use the term "SD", meaning standard deviation is it clear from the context that they are interested in sampling from a student-t distribution with scale term set to 6.3. In Stan, the arguments for the function student_t(nu, mu, sigma) clearly specify that sigma is a scale term. So the original poster is asking for an R equivalent to the Stan function student_t(3, 0, 6.3).


Method in Java interface that returns class or subclass type

Question: I have an interface:
public interface Displayable {
    public Class <Screen> classToDisplay();
}

and some classes:
public class Screen {

}

public class ScreenSubclass extends Screen {

}

public class Cue implements Displayable {

    @Override displayClass() {
        return ScreenSubclass.class;
    }

}

I'm getting an IDE error telling me they are incompatible types. What return value would be needed for 'classToDisplay()' to return a class or subclass type of Screen?
Answer: Just figured it out. Use the ? wildcard along with 'extends'...
Change the return type for 'displayClass' to:
public Class<? extends Screen> displayClass();


Properly setting up callbacks for dynamic dropdowns plotly dash

Question: I am trying to create a Dash dashboard where dropdown options in one box are dependent on the previous dropdown selection.
The data consists of two dictionaries, with two keys each. Each key contains a dataframe with a couple of columns. The exact data:
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import numpy as np
from plotly.subplots import make_subplots
import plotly.express as px
import pandas as pd
from pandas import Timestamp
import numpy as np

df_vals_prod={'corn':pd.DataFrame({'time': {1: Timestamp('2020-09-23 06:00:00'),
  2: Timestamp('2020-09-23 12:00:00'),
  3: Timestamp('2020-09-23 18:00:00'),
  4: Timestamp('2020-09-24 00:00:00')},
 '2m_temp_prod': {1: 0.020584322444347606,
  2: 0.08973907730395358,
  3: 2.3866310395722463,
  4: 3.065472457668321},
 'total_precip_prod': {1: 1.372708470272411,
  2: 2.135683294556938,
  3: 1.9811172016307312,
  4: 2.1082116841869323}}),
'soybeans':pd.DataFrame({'time': {1: Timestamp('2020-09-23 06:00:00'),
  2: Timestamp('2020-09-23 12:00:00'),
  3: Timestamp('2020-09-23 18:00:00'),
  4: Timestamp('2020-09-24 00:00:00')},
 '2m_temp_prod': {1: 0.6989001827317545,
  2: -0.8699121426411993,
  3: -0.9484359259520706,
  4: 0.7391299158393124},
 'total_precip_prod': {1: -0.07639291299336869,
  2: 0.19182892415959496,
  3: 0.8719339093510236,
  4: 0.90586956349059}})}

df_vals_area={'corn':pd.DataFrame({'time': {1: Timestamp('2020-09-23 06:00:00'),
  2: Timestamp('2020-09-23 12:00:00'),
  3: Timestamp('2020-09-23 18:00:00'),
  4: Timestamp('2020-09-24 00:00:00')},
 '2m_temp_area': {1: -1.6820417878457192,
  2: -0.2856437053872421,
  3: 0.3864022581278122,
  4: 0.5873739667356371},
 'total_precip_area': {1: 1.3703311242708185,
  2: 0.25528434511264525,
  3: 0.5007488191835624,
  4: -0.16292114222272375}}),
'soybeans':pd.DataFrame({'time': {1: Timestamp('2020-09-23 06:00:00'),
  2: Timestamp('2020-09-23 12:00:00'),
  3: Timestamp('2020-09-23 18:00:00'),
  4: Timestamp('2020-09-24 00:00:00')},
 '2m_temp_area': {1: 1.3789989862086967,
  2: -0.7797086923820608,
  3: 1.0695635889750523,
  4: 1.136561500804678},
 'total_precip_area': {1: -0.6035111830104833,
  2: -0.18237330469451313,
  3: -0.7820158376898607,
  4: -0.6117188028872137}})}

app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])
weight_opts=['Production','Area']

controls = dbc.Card(
    [    dbc.FormGroup(
            [
                dbc.Label("Crop"),
                dcc.Dropdown(
                    id="Crop",
                    options=[
                        {"label": col, "value": col} for col in list(df_vals_prod.keys())
                    ],
                    value=list(df_vals_prod.keys())[0],
                    clearable=False,
                ),
            ]
        ),

        dbc.FormGroup(
            [
                dbc.Label("Weighting"),
                dcc.Dropdown(
                    id="weights",
                    options=[
                        {"label": i, "value": i} for i in weight_opts
                    ],
                    value=weight_opts[0],
                    clearable=False,
                ),
            ]
        ),
        dbc.FormGroup(
            [
                dbc.Label("Forecast Variable"),
                dcc.Dropdown(
                    id="forecast_v",
                ),
            ]
        ),

    ],
    body=True,
)

app.layout = dbc.Container(
    [
        html.Hr(),
        dbc.Row([
            dbc.Col([
                dbc.Row([
                    dbc.Col(controls)
                ],  align="start"),
                dbc.Row([
                    dbc.Col([
                        html.Br(),
                        dbc.Row([
                            dbc.Col([html.Div(id = 'txt1')
                            ])
                        ]),
                        html.Br(),
                        dbc.Row([
                            dbc.Col([html.Div(id = 'txt2')])
                        ])
                    ])
                ])
            ],xs = 2)
            ,
            dbc.Col([
                dbc.Row([
                    dbc.Col([html.Div(id = 'plot_title')],)
                ]),
                dbc.Row([
                    dbc.Col(dcc.Graph(id="crop-graph")),
                    #dbc.Col(dcc.Graph(id="cluster-graph"))
                ])
            ])
        ],),
    ],
    fluid=True,
)

@app.callback(
    Output('forecast_v','options'),
    [Input('weights', 'value')]
)

def update_var_dropdown(weight):
    if weight=='Production':
        return [{'label': i, 'value': i} for i in df_vals_prod['corn'].columns[1:]]
    elif weight=='Area':
        return [{'label': i, 'value': i} for i in df_vals_area['corn'].columns[1:]]

@app.callback(
    Output("crop-graph", "figure"),
    [   Input("Crop", "value"),
        Input("weights", "value"),
        Input("forecast_v", "value"),

    ],
)

def crop_graph(Crop, val, weight):

    # plotly figure setup
    fig = make_subplots(specs=[[{"secondary_y": True}]])

    if weight:
        fig.add_trace(go.Scatter(name=val, x=df_vals_prod[Crop]['time'], y=((df_vals_prod[Crop][val]-273)*(9/5))+32, mode = 'lines', line=dict(color='red', width=4),
                                hovertemplate='Date: %{x|%d %b %H%M} UTC
Temp: %{y:.2f} F<extra></extra>'), secondary_y=False,
                  )
        fig.update_yaxes(title_text="Temp (F)", color='red', secondary_y=False,)
        fig.update_yaxes(title_text="24hr Forecast Change (F)", secondary_y=True)

    return(fig)

app.run_server(mode='external', port = 8099)

As you can see, this 6 hourly data and is meant to be plotted as a time series. Now I want to add a couple of dropdowns. The first dropdown (Crop) selects which crop to choose (corn or soybeans), which are the two keys from each dictionary.
The second dropdown (Weighting) now selects which dataframe we want to use. What the user selects in this second dropdown will determine the options to select in the third dropdown.
The third dropdown will select the actual variable (Forecast Variable), which is one of two columns available in each dataframe. So if in dropdown 2, "Production" is selected, the options for dropdown 3 would consist of '2m_temp_prod' or 'total_precip_prod'. For "Area" in dropdown 2, dropdown 3 options would be '2m_temp_area' or 'total_precip_area'.
Here is the code I have so far. I am able to setup the callback properly for the dropdowns, but I don't think my second callback is working properly. I understand how to create the dynamic dropdown, but I am not sure how to translate that to actually plotting the data.
That produces this plot. Notice that the dropdowns are what I want, but it doesn't plot. How do I add in the 'weight' to make the desired plot? What I would expect is just a simple line graph where the data depends on all of the dropdowns chosen.

Edit: as suggested by vestland, I am including a much smaller data sample. The specific values in this case don't matter, just the structure of the data. See above for more concise data.
Comment: Could you provide *one* complete code snippet with your data sample and your imports?
Answer: I haven't been able to figure out why your code fails. But I've been putting together an example that I think will come close to what you're looking for here. It builds on an example from the plotly docs, and so has a bit different layout from what you've got in your question. The main take-away is that three sets of radio buttons will let you:

select a weight: ['prod', 'area'],
which in turn will define the options in another callback: ['2m_temp_prod', 'total_precip_prod'] or ['2m_temp_area', 'total_precip_area'].
And you're also able to select produce ['corn', 'soybeans']

It's very possible that I've misunderstood the logic of what you want to achieve here. But just give me some feedback along the way and we can work out the details.
Dash app for selection DF: prod | Crops: corn | Column: 2m_temp_prod

Dash app for selection DF: area | Crops: soybeans | Column: total_precip_area

Complete code:
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

# data
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import numpy as np
from plotly.subplots import make_subplots
import plotly.express as px
import pandas as pd
from pandas import Timestamp
import numpy as np

# data ##########################################################################
index1= [1,2,3,4]
columns1 =['time', '2m_temp_prod' , 'total_precip_prod']

index2= [1,2,3,4]
columns2 = ['time', '2m_temp_area', 'total_precip_area']

df_vals_prod = {'corn': pd.DataFrame(index=index1, columns = columns1,
                                data= np.random.randn(len(index1),len(columns1))).cumsum(),
                'soybeans' : pd.DataFrame(index=index1, columns = columns1,
                                     data= np.random.randn(len(index1),len(columns1))).cumsum()}

df_vals_area= {'corn': pd.DataFrame(index=index2, columns = columns2,
                                data= np.random.randn(len(index2),len(columns2))).cumsum(),
               'soybeans' : pd.DataFrame(index=index2, columns = columns2,
                                     data= np.random.randn(len(index2),len(columns2))).cumsum()}

# mimic data properties of your real world data
df_vals_prod['corn']['time'] =   [Timestamp('2020-09-23 06:00:00'), Timestamp('2020-09-23 12:00:00'),
                                  Timestamp('2020-09-23 18:00:00'), Timestamp('2020-09-24 00:00:00')]
df_vals_prod['corn'].set_index('time', inplace = True)
df_vals_prod['soybeans']['time'] =   [Timestamp('2020-09-23 06:00:00'), Timestamp('2020-09-23 12:00:00'),
                                      Timestamp('2020-09-23 18:00:00'), Timestamp('2020-09-24 00:00:00')]
df_vals_prod['soybeans'].set_index('time', inplace = True)

df_vals_area['corn']['time'] =   [Timestamp('2020-09-23 06:00:00'), Timestamp('2020-09-23 12:00:00'),
                                  Timestamp('2020-09-23 18:00:00'), Timestamp('2020-09-24 00:00:00')]
df_vals_area['corn'].set_index('time', inplace = True)
df_vals_area['soybeans']['time'] =   [Timestamp('2020-09-23 06:00:00'), Timestamp('2020-09-23 12:00:00'),
                                      Timestamp('2020-09-23 18:00:00'), Timestamp('2020-09-24 00:00:00')]
df_vals_area['soybeans'].set_index('time', inplace = True)

# dash ##########################################################################
app = JupyterDash(__name__)

# weighting
all_options = {
    'prod': list(df_vals_prod[list(df_vals_prod.keys())[0]].columns),
    'area': list(df_vals_area[list(df_vals_prod.keys())[0]].columns)
}

app.layout = html.Div([
    dcc.RadioItems(
        id='produce-radio',
        options=[{'label': k, 'value': k} for k in all_options.keys()],
        value='prod'
    ),

    html.Hr(),

    dcc.RadioItems(
        id='crop-radio',
        options=[{'label': k, 'value': k} for k in list(df_vals_prod.keys())],
        value=list(df_vals_prod.keys())[0]
    ),

    html.Hr(),

    dcc.RadioItems(id='columns-radio'),

    html.Hr(),

    html.Div(id='display-selected-values'),

    dcc.Graph(id="crop-graph")
])

# Callbacks #####################################################################

# Weighting selection.
@app.callback( # Dataframe PROD or AREA
    Output('columns-radio', 'options'),
    # layout element: dcc.RadioItems(id='produce-radio'...)
    [Input('produce-radio', 'value')])
def set_columns_options(selected_produce):
    varz =  [{'label': i, 'value': i} for i in all_options[selected_produce]]
    print('cb1 output: ')
    print(varz)
    return [{'label': i, 'value': i} for i in all_options[selected_produce]]

# Columns selection
@app.callback(
    Output('columns-radio', 'value'),
    # layout element: dcc.RadioItems(id='columns-radio'...)
    [Input('columns-radio', 'options')])
def set_columns(available_options):
    return available_options[0]['value']

# Crop selection
@app.callback(
    Output('crop-radio', 'value'),
    # layout element: dcc.RadioItems(id='columns-radio'...)
    [Input('crop-radio', 'options')])
def set_crops(available_crops):
    return available_crops[0]['value']

# Display selections in its own div
@app.callback( # Columns 2m_temp_prod, or....
    Output('display-selected-values', 'children'),
    [Input('produce-radio', 'value'),
     Input('crop-radio', 'value'),
     Input('columns-radio', 'value')])
def set_display_children(selected_produce, available_crops, selected_column):
    return('DF: ' + selected_produce +' | Crops: ' + available_crops + ' | Column: '+ selected_column)

# Make a figure based on the selections
@app.callback( # Columns 2m_temp_prod, or....
    Output('crop-graph', 'figure'),
    [Input('produce-radio', 'value'),
     Input('crop-radio', 'value'),
     Input('columns-radio', 'value')])
def make_graph(selected_produce, available_crops, selected_column):

    # data source / weighting
    if selected_produce == 'prod':
        dfd = df_vals_prod
    if selected_produce == 'area':
        dfd = df_vals_area

    # plotly figure
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=dfd[available_crops].index, y=dfd[available_crops][selected_column]))
    fig.update_layout(title=dict(text='DF: ' + selected_produce +' | Crops: ' + available_crops + ' | Column: '+ selected_column))
    return(fig)

app.run_server(mode='inline', port = 8077, dev_tools_ui=True,
          dev_tools_hot_reload =True, threaded=True)

Edit 1 - Dropdown menus.
All you have to do to get the desired dropdown buttons is to change each
dcc.RadioItems()

to
 dcc.Dropdown()

Now you'll get:

Complete code:
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

# data
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import numpy as np
from plotly.subplots import make_subplots
import plotly.express as px
import pandas as pd
from pandas import Timestamp
import numpy as np

# data ##########################################################################
index1= [1,2,3,4]
columns1 =['time', '2m_temp_prod' , 'total_precip_prod']

index2= [1,2,3,4]
columns2 = ['time', '2m_temp_area', 'total_precip_area']

df_vals_prod = {'corn': pd.DataFrame(index=index1, columns = columns1,
                                data= np.random.randn(len(index1),len(columns1))).cumsum(),
                'soybeans' : pd.DataFrame(index=index1, columns = columns1,
                                     data= np.random.randn(len(index1),len(columns1))).cumsum()}

df_vals_area= {'corn': pd.DataFrame(index=index2, columns = columns2,
                                data= np.random.randn(len(index2),len(columns2))).cumsum(),
               'soybeans' : pd.DataFrame(index=index2, columns = columns2,
                                     data= np.random.randn(len(index2),len(columns2))).cumsum()}

# mimic data properties of your real world data
df_vals_prod['corn']['time'] =   [Timestamp('2020-09-23 06:00:00'), Timestamp('2020-09-23 12:00:00'),
                                  Timestamp('2020-09-23 18:00:00'), Timestamp('2020-09-24 00:00:00')]
df_vals_prod['corn'].set_index('time', inplace = True)
df_vals_prod['soybeans']['time'] =   [Timestamp('2020-09-23 06:00:00'), Timestamp('2020-09-23 12:00:00'),
                                      Timestamp('2020-09-23 18:00:00'), Timestamp('2020-09-24 00:00:00')]
df_vals_prod['soybeans'].set_index('time', inplace = True)

df_vals_area['corn']['time'] =   [Timestamp('2020-09-23 06:00:00'), Timestamp('2020-09-23 12:00:00'),
                                  Timestamp('2020-09-23 18:00:00'), Timestamp('2020-09-24 00:00:00')]
df_vals_area['corn'].set_index('time', inplace = True)
df_vals_area['soybeans']['time'] =   [Timestamp('2020-09-23 06:00:00'), Timestamp('2020-09-23 12:00:00'),
                                      Timestamp('2020-09-23 18:00:00'), Timestamp('2020-09-24 00:00:00')]
df_vals_area['soybeans'].set_index('time', inplace = True)

# dash ##########################################################################
app = JupyterDash(__name__)

# weighting
all_options = {
    'prod': list(df_vals_prod[list(df_vals_prod.keys())[0]].columns),
    'area': list(df_vals_area[list(df_vals_prod.keys())[0]].columns)
}

app.layout = html.Div([
    dcc.Dropdown(
        id='produce-radio',
        options=[{'label': k, 'value': k} for k in all_options.keys()],
        value='area'
    ),
#     dcc.Dropdown(
#     id='produce-radio',
#     options=[
#         {'label': k, 'value': k} for k in all_options.keys()
#     ],
#     value='prod',
#     clearable=False),

    html.Hr(),

    dcc.Dropdown(
        id='crop-radio',
        options=[{'label': k, 'value': k} for k in list(df_vals_prod.keys())],
        value=list(df_vals_prod.keys())[0]
    ),

    html.Hr(),

    dcc.Dropdown(id='columns-radio'),

    html.Hr(),

    html.Div(id='display-selected-values'),

    dcc.Graph(id="crop-graph")
])

# Callbacks #####################################################################

# Weighting selection.
@app.callback( # Dataframe PROD or AREA
    Output('columns-radio', 'options'),
    # layout element: dcc.RadioItems(id='produce-radio'...)
    [Input('produce-radio', 'value')])
def set_columns_options(selected_produce):
    varz =  [{'label': i, 'value': i} for i in all_options[selected_produce]]
    print('cb1 output: ')
    print(varz)
    return [{'label': i, 'value': i} for i in all_options[selected_produce]]

# Columns selection
@app.callback(
    Output('columns-radio', 'value'),
    # layout element: dcc.RadioItems(id='columns-radio'...)
    [Input('columns-radio', 'options')])
def set_columns(available_options):
    return available_options[0]['value']

# Crop selection
@app.callback(
    Output('crop-radio', 'value'),
    # layout element: dcc.RadioItems(id='columns-radio'...)
    [Input('crop-radio', 'options')])
def set_crops(available_crops):
    return available_crops[0]['value']

# Display selections in its own div
@app.callback( # Columns 2m_temp_prod, or....
    Output('display-selected-values', 'children'),
    [Input('produce-radio', 'value'),
     Input('crop-radio', 'value'),
     Input('columns-radio', 'value')])
def set_display_children(selected_produce, available_crops, selected_column):
    return('DF: ' + selected_produce +' | Crops: ' + available_crops + ' | Column: '+ selected_column)

# Make a figure based on the selections
@app.callback( # Columns 2m_temp_prod, or....
    Output('crop-graph', 'figure'),
    [Input('produce-radio', 'value'),
     Input('crop-radio', 'value'),
     Input('columns-radio', 'value')])
def make_graph(selected_produce, available_crops, selected_column):

    # data source / weighting
    if selected_produce == 'prod':
        dfd = df_vals_prod
    if selected_produce == 'area':
        dfd = df_vals_area

    # plotly figure
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=dfd[available_crops].index, y=dfd[available_crops][selected_column]))
    fig.update_layout(title=dict(text='DF: ' + selected_produce +' | Crops: ' + available_crops + ' | Column: '+ selected_column))
    return(fig)

app.run_server(mode='inline', port = 8077, dev_tools_ui=True,
          dev_tools_hot_reload =True, threaded=True)

Comment: Thanks for your good work as usual. This is definitely great, but would really love to have dropdowns instead of radio items. It appears to work as I intended. Any reasons why the dropdowns aren't an option?
Comment: @EliTurasky They are an option! Should have kept them then. If the rest of the suggestion is OK I'll have the dropdowns sorted out in a few hours.
Comment: oh okay. I have tested the code and it is doing what I had hoped for.
Comment: @EliTurasky No problem! Out of curiosity... Is your work for an assignment? Part of a study paper? Or for work perhaps? You *do not* have to answer that. Just curious...
Comment: trying to learn for work. Nothing required, but trying to better myself so that I can contribute more. Why do you ask?!
Comment: @EliTurasky I think python, plotly and dash combined is a fantastic portfolio of tools. Right now I'm diving into *everything* plotly. And that includes *how* others use plotly, and for what purposes. Your use-case seemed particularly interesting with crops, weather (?) etc. I also find it much more intriguing to assist others with their professional work, and not *home*work.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/222256/discussion-between-eli-turasky-and-vestland).
Comment: Do you have a little bit of time for a conceptual question? Don't think it needs a new question at this point, but having trouble finding anything online.
Comment: @EliTurasky Sure. I'm in the same chatroom as before


Codename One building project locally doesn't recognize facebook JAR on classpath

Question: I am trying to get Codename One work on my Ubuntu machine locally so that I don't have to send builds to codenameone.com. I followed the steps in this tutorial:
http://sjhannah.com/blog/?p=228
and installed all successfully. when I go to my project directory and run:
ant build-for-android-device-locally

I get the following error:
/home/petr/projects/MyApp/dist/android/src/com/codename1/social/FacebookImpl.java:37: error: package com.facebook does not exist

So I downloaded the facebook sdk, compiled it using Gradle, and added the generated facebook JAR file to the CLASSPATH variable in my /etc/bash.bashrc file:
CLASSPATH="/home/petr/android-sdk-linux/platforms/android-21/android.jar:/home/petr/projects/MyApp/lib/CLDC11.jar:/home/petr/projects/MyApp/lib/CodenameOne_SRC.zip:/home/petr/projects/MyApp/lib/CodenameOne.jar:/home/petr/android-sdk-linux/extras/google/google_play_services/libproject/google-play-services_lib/libs/google-play-services.jar:/home/petr/android-sdk-linux/facebook-android-sdk-3.23.0/facebook/build/libs/facebook-3.23.0-sources.jar"
export CLASSPATH

Then I closed my terminal, reopened it again and tried to build using  ant again, but I keep getting the same "com.facebook does not exist" error. Why doesn't java recognize the JAR file?
Answer: Check the version of the facebook sdk you used. In version 4, the package names changed from com.facebook to com.facebook.android. I recommend you use version 3.23.1


In a Discussion Involving Formal Languages, Can a Word Be Regarded as an "Expression"?

Question: In order to avoid sounding repetitious by too frequently using the word "word," I would like to be able use the word "expression," writing, e.g., "Applying the function $f$ to the lang$_{1}$ word $ab$ yields the expression $abba$, which is a word in the lang$_{2}$ language."
Is that an acceptable usage of the term expression?
Also, if I were to instead write "Applying the function $f$ to the lang$_{1}$ word $ab$ yields the word $abba$, which is a member of the lang$_2$ language," could I be criticized for first identifying $abba$ as a word without specifying the set in which it is considered such until I reach my sentence's dependent clause to reveal that crucial piece of information?  Or is it okay to call something a "word" in the general sense that there exists some language in which it is a word?  (I know I could rephrase using "...the lang$_{2}$ word $abba$...", but such rephrasing would prove extremely awkward, given the context of my discussion.)
Comment: I think your second sentence is fine.
Answer: Expression isn't actually wrong, but it's awfully general; when you're talking about a word, it's generally better to use the more precise term word (or sometimes string). For the example in your first paragraph I would write simply:

Applying $f$ to $ab\in\text{lang}_1$ yields $abba\in\text{lang}_2$.

Your version is unnecessarily wordy. There's no real need here for function, word, or expression: all are perfectly clear from the context.
Comment: I would either write "to the word $ab$" or "to $ab$", but "to the $ab$" looks awkward to me.
Comment: @J.-E.Pin: To me as well. If I remember correctly, I originally wrote 'to the word $ab$' and then decided that 'the word' was unnecessary. Apparently I failed to erase both words.


Javascript Date comparison is bizarre

Question: I feel like this should live on a code golf post but the following behaviour caused a strange bug and is superficially unfathomable:
(a = new Date()) < (b = new Date())
a  // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
b  // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
a < b    // false (correct)
a === b  // false (incorrect)  << b    // false (correct)
a <= b   // true (correct)
a >= b   // true (correct)

** Edit **
Where is this documented please?
Comment: Possible duplicate of [Compare two dates with JavaScript](http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript)
Comment: Could this occur because `>=` compares the raw numbers associated with the `Date` while `===` checks for object equality?
Comment: @Hacketo that's not true
Comment: @Hacketo those are strings, not objects. Comparing primitives and objects are different
Comment: Regarding "*Where is this documented*", you need to look at the [*ECMAScript 2015*](http://www.ecma-international.org/ecma-262/6.0/#sec-abstract-relational-comparison) algorithms for the operators involved, namely *Abstract Relational Comparison* for `<` and `>`, *Abstract Equality Comparison* for `==` and *Strict Equality Comparison* for `===`.
Comment: … your question being why this was so?
Comment: https://jsfiddle.net/ors21sd6/ Interesting, indeed.
Comment: They are not the same objects so `===` make sense.
Comment: @Hacketo I thought that too, but `{a:1} === {a:1}` is `false`...
Answer: All of your comparisions other than the === one are coercing the dates to numbers (their time values, milliseconds since The Epoch) and then comparing those numbers. The === comparison is checking if a and b refer to the same object. (== would do the same thing.)
The times are (in your example) exactly the same, but there are still two distinct objects. Hence the results you're seeing.
Annotated:
// Create two Date instances, check if a's time value is less than b's
// (probably not, but it's just feasible this could cross a millisecond
// threshold)
(a = new Date()) < (b = new Date())

// Show the value of a and b
a  // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
b  // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)

// See if a's time value is less than b's
a  b    // false

// See if a's time value is less than or equal to b's
a <= b   // true

// See if a's time value is greater than or equal to b's
a >= b

Or to put it another way, your code was basically doing this (note where the + signs are and aren't):
(a = new Date()) < (b = new Date())
a  // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
b  // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
+a < +b    // false
a === b    // false
+a > +b    // false
+a <= +b   // true
+a >= +b

Note that if the times are exactly the same, +a === +b (or +a == +b, or — being tricky — +a == b or a == +b) would all be true, because we'd be comparing time values.
Just for fun, here's an example where we know the underlying time values are exacty the same:

var a, b;
var now = Date.now(); // = +new Date(); on old browsers
show("create and compare: ", (a = new Date(now)) < (b = new Date(now)), "a's time is not < b's");
show("+a < +b:   ", +a < +b,   "a's time is not < b's");
show("a < b:     ", a < b,     "a's time is not  +b:   ", +a > +b,   "a's time is not > b's");
show("a > b:     ", a > b,     "a's time is not > b's");
show("+a <= +b:  ", +a <= +b,  "a's time is equal to b's");
show("a <= b:    ", a <= b,    "a's time is equal to b's");
show("+a >= +b:  ", +a >= +b,  "a's time is equal to b's   ");
show("a >= b:    ", a >= b,    "a's time is equal to b's   ");

function show(prefix, result, because) {
    var msg = prefix + result + ", " + because;
    var pre = document.createElement('pre');
    pre.innerHTML = msg.replace(/&/g, "&").replace(/</g, "<");
    document.body.appendChild(pre);
}
Answer: To compare dates you need to use .getTime(). So the correct comparison should be:
a.getTime() === b.getTime() //true
a.getTime() > b.getTime()   //false
...

Comment: `a < b` is same as `a.getTime() < b.getTime()`or `+a < +b`
Comment: That's because the date is equal: `new Date().getTime() === new Date().getTime()` is `true`. `getTime()` is indeed the correct way as also mentioned here: http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript
Comment: @Mark— `a.getTime() < b.getTime()` is identical to `a < b`. Both compare the time value.

Javascript Date comparison is bizarre


Classes structure

Question: I am quite confused about this subject, let's say I have a Authentication class (logging in, logging out, checking if logged in or not)
A User class (that holds a User, getters, setters, save etc)
Where should I put stuff like creating a User, and like validating a Username? A new class, like "UserManager" or something?
Answer: This is more of a design question, which makes it a little difficult to answer since there probably isn't an objectively right way to do this. Rather, several people have created several different solutions that all work equally well.
One suggestion would be to create a Users (plural) class that has public methods like addNew (returns User object) and userExists (returns Bool), as well as validateUsername (also returning Bool).
This Users class could contain additional logic used to managing your user-base as a whole.
Answer: What I like to do is to include the create/validate/etc.. methods in the user class
class user{
       function __construct($iduser){
            $this->id=$iduser;

       }

       function getHref(){
         return "/profile/".$this->id;
       }

       function create($username){
           //insert your user in db
           //retrieve the id of the created user
           $iduser=mysql_insert_id();

           $newuser=new user($iduser);
           return $newuser;
       }

       function validate($username){

          mysql_query("your code to validate");

          return true or false;
       }
}

$name="john";
if(user::validate("$name")){
    $mynewuser=user::create("john");

    $href=$mynewuser->getHref();
    header("Location: $href"); //let s redirect him to its home page
    //or use any other method...
}

Comment: Well, I guess my solution is very much alike "Jonathan Sampson" one. except I was more verbose

Classes structure


Problemas com pdo erro ao criar arquivo logerro.txt

Question: Notice: Undefined variable: strErro
   <?php
  class DB{
  private static $conn;
  static function getConn(){
      if(is_null(self::$conn)){
          self::$conn = new PDO('mysql:host=localhost;dbname=sllapsocial','root','');
          self::$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
     }

     return self::$conn;
  }
   }

   function logErros($errno){
   if(error_reporting()==0) return;

  $exec = func_get_arg(0);

   $errno = $exec->getCode();
   $errstr = $exec->getMessage();
   $errfile = $exec->getFile();
   $errline = $exec->getLine();
   $err = 'CAUGHT EXCEPTION';

  if(ini_get('log_errors')) error_log(sprintf("PHP %s: %s in %s on line     %d",$err,$errstr,$errfile,$errline));

   $strErro = 'erro:'.$err.' no arquivo: '.$errfile.' ( linha '.$errline.' ) ::     IP('.$_SERVER['REMOTE_ADDR'].') data:'.date('d/m/y H:i:s')."\n";
   }

  $arquivo = fopen('logerro.txt','a');
//Aparece aqui Notice: Undefined variable: strErro estou fazendo corréto?
    fwrite($arquivo,$strErro);
    fclose($arquivo);

   set_error_handler('logErros');

Answer: O problema é o escopo da váriavel $strErro ela foi definida dentro da função e não pode ser acessada fora dela.
   function logErros($errno){
      //código omitido ...

      if(ini_get('log_errors')) //if em uma linha...
         error_log(sprintf("PHP %s: %s in %s on line     %d",$err,$errstr,$errfile,$errline));

      $strErro = 'erro:'.$err.' no arquivo: '.$errfile.' ( linha '.$errline.' ) ::     IP('.$_SERVER['REMOTE_ADDR'].') data:'.date('d/m/y H:i:s')."\n";
   } //<---- fim da função $strErro não pode ser acessada depois dessa linha.

   //código fora da função....
   $arquivo = fopen('logerro.txt','a');
   fwrite($arquivo,$strErro);

A solução mais simples é dar um return $strErro no final função. A chamada nova seria feita dassa forma:
$msg = logErros($errno);
if($msg){
   fwrite($arquivo, $msg);
   fclose($arquivo);
}

Comment: Incrível como uma simples indentação CORRETA joga o erro aos olhos.
Comment: @PapaCharlie, pois é primeiro achei o if não era excutado depois vi que era um if de uma linha só =\
Comment: Pois é, aquele `}` após `$strErro` é tenso, mata qualquer lógica - você pensa que é uma coisa mas é outra. O código tem "indentação inversa" oO
Comment: Colocou o `return $strErro` no final de `logErros()` ?
Comment: O PDO não tem relação com isso. O problema é que você tem **N³** erros, e quando arruma um, aparece seguinte, e depois outro...
Comment: Use [file_put_contents](http://php.net/manual/pt_BR/function.file-put-contents.php)


EXT3-FS: error (loop0) ext3_lookup unlinking inode

Question: Running CentOS 5.6 with mdadm RAID1, 2TB, 3 partitions (boot, swap and root).  I had a kernel panic in the server, and after rebooting, the system stays up for about 5-10 minutes, the it starts printing out fsck errors to the console and the root file system is put into readonly mode.
I rebooted into single-user mode, unmounted the / partition and tried to run

e2fsck -f /dev/md2

but it hung at Stage 1 for over 8 hours without updates.  I notice that the RAID is being resynched (cat /proc/mdstat) -- could this be impacting the e2fsck?  I ran smartctl on both disks, they both came back healthy so I don't think this is a disk problem, though I don't have any clue what triggered the RAID rebuild.
Anyway, is there a problem running e2fsck on a raid device that is being resynched?  Anything I can do to get fsck out of stage 1, or get more feedback on progress?  Why is the error pointing to loop0 instead of one of the actual devices?
Answer: The (loop0) should have given me a clue. The problem was not with any hard drive filesystem -- it was with the RAM based tmpfs. My /tmp directory was mounted using a tmpfs (/dev/shm)

/usr/tmpDSK             /tmp   ext3

The ext3 errors were occurring in the RAM based tmpfs. Once I unmounted /tmp (had to force it using umount -l /tmp), the errors went away and everything started working.  The question remains why an in-memory filesystem would get ext3 errors, but at least I'm up and running.
Comment: Sounds like it's time to run http://www.memtest.org/


CSS animation when border's size change

Question: I have a little probleme with my website: when I click on one of my boxes, the size of it changes, but without transition, even if I put transitions everywhere in my CSS. Here is my code and screens.
Thanks for your help.
Edit : I add my code in snippet, sry
Basically, my code works well, I juste want the transition when I close a box to be less brutal. If you don't want to check all the code, the variables starting by -tran are times (between 200 and 1000 ms).
first screen
second screen

const   body = document.querySelector("body"),
        sidebar = body.querySelector(".sidebar"),
        toggle = body.querySelector(".toggle"),
        searchBtn = body.querySelector(".search-box"),
        modeSwitch = body.querySelector(".toggle-switch"),
        modeText = body.querySelector(".mode-text"),
        moi = body.querySelector(".article"),
        afficher_moi = body.querySelector(".afficher_moi");

        toggle.addEventListener("click", () =>{
            sidebar.classList.toggle("close");
        });

        searchBtn.addEventListener("click", () =>{
            sidebar.classList.remove("close");
        });

        modeSwitch.addEventListener("click", () =>{
            body.classList.toggle("dark");

            if(body.classList.contains("dark")){
                modeText.innerText = "Light Mode";
            }
            else{
                modeText.innerText = "Dark Mode";
            }
        });

        $(document).ready(function () {
            $(".article1").click(function () {
              $(".article1").toggleClass("close");
            });
          });

        $(document).ready(function () {
            $(".article2").click(function () {
              $(".article2").toggleClass("close");
            });
          });

        $(document).ready(function () {
            $(".article3").click(function () {
              $(".article3").toggleClass("close");
            });
        });

        $(document).ready(function () {
            $(".article4").click(function () {
              $(".article4").toggleClass("close");
            });
        });

/* Importation des polices */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

/* Tout */
*{
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* Initialisation des variables au lancement */
:root{
    --body-color: #e4e9f7;
    --sidebar-color: #fff;
    --primary-color: #695cfe;
    --primary-color-light: #f6f5ff;
    --toggle-color: #ddd;
    --text-color: #707070;

    --tran-02: all 0.2s ease;
    --tran-03: all 0.3s ease;
    --tran-04: all 0.4s ease;
    --tran-05: all 0.5s ease;
    --tran-10: all 1s ease;

}

/* Body */
body{
    height: 100vh;
    background: var(--body-color);
    transition: var(--tran-05);
}

body.dark{
    --body-color: #18191a;
    --sidebar-color: #242526;
    --primary-color: #3a3b3c;
    --primary-color-light: #3a3b3c;
    --toggle-color: #fff;
    --text-color: #ccc;
}

body.dark .sidebar header .toggle{
    color: var(--text-color);
}

body.dark .sidebar li a:hover .icon, body.dark .sidebar li a:hover .text{
    color: var(--text-color);
}

body.dark .menu-bar .mode i.sun{
    opacity: 1;
}

body.dark .menu-bar .mode i.moon{
    opacity: 0;
}

body.dark .switch::before{
    left: 1.25vw;
}

/* sidebar */
.sidebar{
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 13vw;
    padding: 0.925vh 0.73vw;
    background: var(--sidebar-color);
    transition: var(--tran-05);
    z-index: 100;
}

.sidebar header .toggle{
    position: absolute;
    top: 50%;
    right: -1.302vw;
    transform: translateY(-50%) rotate(180deg);
    height: 1.302vw;
    width: 1.302vw;
    background: var(--primary-color);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    color: var(--sidebar-color);
    font-size: 1.145vw;
    transition: var(--tran-05);
}

.sidebar .text{
    font-size: 0.83vw;
    font-weight: 500;
    color: var(--text-color);
    transition: var(--tran-05);
    white-space: nowrap;
    opacity: 1;
}

.sidebar .image{
    min-width: 3.125vw;
    display: flex;
    align-items: center;
    justify-content: center;
}

.sidebar li{
    height: 4.63vh;
    margin-top: 0.93vh;
    list-style: none;
    display: flex;
    align-items: center;
}

.sidebar li .icon{
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.042vw;
    min-width: 3.125vw;
}

.sidebar li .icon, .sidebar li .text{
    color: var(--text-color);
    transition: var(--tran-05);
}

.sidebar .image-text img{
    width: 2.08vw;
    border-radius: 0.3125vw;
}

.sidebar .search-box{
    background: var(--primary-color-light);
    border-radius: 0.3125vw;
    transition: var(--tran-05)
}

.sidebar .menu{
    margin-top: 3.24vh;
}

.sidebar li a{
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    text-decoration: none;
    border-radius: 0.3125vw;
    transition: var(--tran-05);
}

.sidebar.close header .toggle{
    transform: translateY(-50%);
}

.sidebar .menu-bar{
    height: calc(100% - 4.63vh);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

/* sidebar header */
.sidebar header{
    position: relative;
}

.sidebar header .image-text{
    display: flex;
    align-items: center;
}

/* sidebar close */
.sidebar.close{
    width: 4.58vw;
}

.sidebar.close .text{
    opacity: 0;
}

.sidebar.close ~ .home{
    left: 4.58vw;
    width: calc(100% - 4.58vw);
}

/* header */
header .image-text .header-text{
    display: flex;
    flex-direction: column;

}

.header-text .name{
    font-weight: 600;
}

.header-text .profession{
    margin-top: -0.104vw;;
}

/* searchbox */
.search-box input{
    height: 100%;
    width: 100%;
    outline: none;
    border: none;
    border-radius: 0.3125vw;
    font-size: 0.83vw;
    font-weight: 500;
    background: var(--primary-color-light);
    transition: var(--tran-05);
    color: var(--text-color);
}

/* menu */

.menu-bar .mode{
    position: relative;
    border-radius: 0.3125vw;
    background-color: var(--primary-color-light);
}

.menu-bar .mode .dark-light{
    height: 4.63vh;
    width: 3.125vw;
    display: flex;
    align-items: center;
}

.menu-bar .mode i{
    position: absolute;
    transition: var(--tran-05);
}

.menu-bar .mode i.sun{
    opacity: 0;
}

.menu-bar .mode .toggle-switch{
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    min-width: 3.125vw;
    cursor: pointer;
    border-radius: 0.3125vw;
    background: var(--primary-color-light);
}

/* toggle-switch & switch */

.toggle-switch .switch{
    position: relative;
    height: 2.04vh;
    width: 2.29vw;
    border-radius: 1.3vw;
    background: var(--toggle-color);
}

.switch::before{
    content: '';
    position: absolute;
    height: 1.39vh;
    width: 0.78vw;
    border-radius: 50%;
    top: 50%;
    left: 0.26vw;
    transform: translateY(-50%);
    background: var(--sidebar-color);
    transition: var(--tran-05);
}

/* Pages */

/* Accueil (home) */

.home{
    position: relative;
    height: 100vh;
    left: 13.02vw;
    right: 0;
    width: calc(100% - 13.02vw);
    background: var(--body-color);
}

.home .text{
    font-size: 1.5625vw;
    font-weight: 500;
    color: var(--text-color);
    padding: 0.74vh 2.08vw;
}

.home .text article{
    display: inline-block;
    position: relative;
    margin-top: 5%;
    padding: 2%;
    margin-left: 5%;
    align-content: center;
    justify-content: center;
    border-radius: 6px;
    border: solid 1px;
    height: 100%;
    width: 40%;
    opacity: 1;
    /* float: left; */
}

.home .text article.close{
    transition: var(--tran-05);
    height: 100%;
}

.home .text article .description .afficher_moi{
    position: absolute;
    transform: translateY(50%) rotate(180deg);
    height: 1.302vw;
    width: 1.302vw;
    background: var(--primary-color);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    color: var(--toggle-color);
    font-size: 1.145vw;
    transition: var(--tran-05);
    z-index: 100;
    top: 30%;
    right: 10%;
}

.home .text article.close .afficher_moi{
    transform: translateY(50%);
}

.home .text article.close p{
    opacity: 0;
    height: 0;
    transition: var(--tran-05);
}

/* évenement */
.sidebar li a:hover{
    background: var(--primary-color);
}

.sidebar li a:hover .icon, .sidebar li a:hover .text{
    color: var(--sidebar-color);
}

.home .text article:hover{
    cursor: pointer;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Slidebar + Dark  mode</title>
    <link rel="stylesheet" href="style.css">
    <link href='https://firstname.lastname@example.com/css/boxicons.min.css' rel='stylesheet'>

                    Lucas DUMONT
                    Etudiant

                            <input type="text" placeholder="Rechercher ...">

                            Accueil

                            CV

                            Projets

                            Loisirs

                            Contact

                            Se connecter

                        Dark Mode

Bienvenue sur mon site

A propos de moi

                    Insérer description de moi

A propos de moi

                    Insérer description de moi

A propos de moi

                    Insérer description de moi

A propos de moi

                    Insérer description de moi

Comment: What is the value of `--tran-05`?
Comment: Please insert the CSS as a snippet, along with the HTML. That way everybody can run it and copy/modify as needed.
Comment: Sorry, I just did it !
Answer: Have you tried CSS : box-sizing:border-box?
* {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

https://www.w3schools.com/cssref/css3_pr_box-sizing.asp
Comment: Just tried it, it changed nothing :'(
Comment: try to post a working fiddle of the code, will help everyone debug is properly.
jsfiddle maybe
Comment: A snippet isn't enough ? I don't know how to give you a jsfiddle

CSS animation when border's size change


Template reused on repeated node

Question: I have a node repeated on the page, once for styled dropdown menu through submenuesmall view and once as node when that submenu is selected. Submenu is styled with node--view--submenuesmall.tpl.php that is OK. But same template is used for node later instead of normal node.tpl.php
If I omit that node from submenuesmall normal node.tpl.php is used.
Is that standard behaviour and how can I fix it or did I do something wrong. All modules are up to date.
Answer: Solution acording to @Vaibhav tip...
// node__view__submenuessmall is used in view
// for creating block menues with images
// when same node is used in menue and on page
// wrong theme_hook_suggestion is used on page

function cuter_preprocess_node(&$variables){
 if(array_key_exists('theme_hook_suggestions',$variables))
  {
    $lastVar = count($variables['theme_hook_suggestions'])-1;
    if($variables['theme_hook_suggestions'][$lastVar]=='node__view__submenussmall')
    {
      //dpr($variables['theme_hook_suggestions'][$lastVar]);
      $variables['theme_hook_suggestions'][$lastVar]='foobar';
      //dpr($variables['theme_hook_suggestions'][$lastVar]);
    }
  }
}

Answer: I believe, you can handle this in template.php of your theme, using the hook - hook_preprocess_page OR hook_preprocess_node.
Here you can change the Template file which is going to be used for that particular node, but you will have to identify at what time which TPL is to be used.
Comment: Thanks!
I recognized the pattern in my case, if used in view, 'theme_hook_suggestions' contains 'node__view__viewname_NODENUM' and when suggestion is wrong last one is 'node__view__viewname'. So I wrote following function (p.s. I'm not PHP developer, this can probably be better)

Template reused on repeated node


Disable payment via custom module

Question: is there anyway, we can disable payment of specific payment option via custom module? I Have done some research that payment in drupal commerce is setup via rules, so is there an option we can create custom module and hit the current payment rules and disable it?
and is there a way via custom module, we can get the list of available or activated payment?
some references would be great.
thank you!
Comment: payment methods are rules, so it can be disabled from rules configuration, why do you need custom module for that
Comment: I need to disable the payment on certain days but this will be annually, as rules can not receive token of years in field I tested
Answer: Option 1: Hook Form Alter
Rules are event-based conditional actions. For "showing" or "hiding" payments, that event it almost always going to be simply showing the form on checkout. So, technically, you could just use hook_form_alter() and locate the checkout pane that has the payment details and modify from there.
A video where I walk you through how to do hook_form_alter: https://youtu.be/xYMd6WDqxKY?t=1m3s (admittedly, this is for a different use case, but I do show you how to locate the form_id and customize the form_alter for whatever situation you're in).
Option 2: Custom Rules Condition
Another option would be to create a rule condition that you can add to your payment gateways. I think this would be more in spirit with how Drupal Commerce works.
Over here, I have shown you how to create a custom Rules action and condition:
Different vat rate per commerce shipping service
There is also a clear example here:
How do I add a new condition in Rules 2?
How to do option 2
As I said above, this is how Drupal Commerce is supposed to work. If you create a custom rule condition (perhaps there's a business server that returns a REST true/false for an A/B comparison) then that condition is exposed in the user interface and keeps the logic in code where it can be maintained separate from being implemented.

Create the custom rule condition in your custom module with your custom logic
Add that condition to your payment method: /admin/commerce/config/payment-methods
Know that every time that payment method might appear (both in checkout and on the order editing payment screen) that rule condition will be run
Comment: I wanted to do a custom module, as rules does not allow me to insert any [token] in the data comparison of the date field. as I need to run this rules annually and the way to achieve that is to use custom module, so at the current date every year, the payment will be off/disabled. that is something I am looking to prepare..
Comment: Yes, the custom rule condition is in a custom module, where your logic can take advantage of any contextual entities and return a true/false. Thus, option 2 is a custom module approach (that happens to integrate with the rules system). ... Otherwise you can do option 1 and just use hook_form_alter.

Disable payment via custom module


Categories REST API relation with Blog Posts

Question: I am new to Drupal.
I am trying to create a news app with Drupal as back end.
I created a Category Taxonomy and attached it with Articles Content type.
Then I created View for Articles Rest api and I am successfully getting all the content. You can see here - Link
Then I created a new Rest Api View for Categories with is also returning List of Categories. Link
1. The problem is how can I link both ? So I can return the list of
    posts in categories when user click on a category name.
2. I also want to show the list of categories and when someone click on a category, it should return all the posts of that category.
This is something relationship issue. How can I achieve this ? I am new in Drupal. Please help.
Comment: Can anyone help me???
Answer: My suggestion is to add an extra field in your views and render the URL to content as a result of it.
( add title field, in the formatter section, chose URL )
let me know if you don't know how to create link to content view field.


Get radio field value in data selector in rules

Question: In content type form, I have a select list as radio with two values "Complaint" and "Feedback".
After content type save, I need to send email if "Complaint" is checked to email@example.com and if "Feedback" is checked then send email to email@example.com
I know how to do that with text field (e.g field-text-field is empty or not) but not yet found any solution with radio buttons.
Note: I have installed the Rules module, and also enabled its sub-modules Rules UI and Rules Scheduler.
Answer: Step 1
To get your rule to work like you want it to work, for the "Complaint"-part you should use these Rules Conditions (in the specified order):

Entity has field, for your "select list" field.
List contains item, whereas:

the list is also about that same "select list" field.
the item you want to check for (if it is contained in the list) is "Complaint".

With those 2 Rules Conditions, your Rules Action to be performed is to send the eMail to firstname.lastname@example.com.
For an example Rule (in rules export format) in which you can see this at work, refer to the answer to "How to check for product taxonomy term in Rules actions (Ubercart)". In that case it's about a list of taxonomy terms, but the idea is the same.
Step 2
Create a similar rule by reepeating Step 1, but now for "Feedback".
Step 3 (optional)
If you'd be willing to also use the Conditional Rules module, you could merge the rules from Step 1 and 2 in a single rule, ie because this module allows you to include Rules Conditions as part of Rules Actions.
Comment: I found this helpful. At first I tried  a simple data comparison, but it wasn't properly getting the value of the check boxes. After following your details from step 1 I got it working.
Comment: @Draevelop merci for the feedback!
Answer: If you want to do this writing a custom code here is one solution:
while saving the node call a submit function
$form['#submit'] = 'your function';

Check the value of the radio button and provide the $to parameter accordingly.
then use the snippet below to send the custom email  through your module
$module = 'module_name';
$key = 'key for the email';
$to = 'mailaddress';// which you set above according to the selected radio value
$language = language_default();
$from = 'from_email_address';
$send = FALSE;
$subject = 'subject line';
$body = 'body of the email';
$params = array(
'subject' => $subject,
'body' => $body,
);
$message = drupal_mail($module, $key, $to, $language, $params, $from, $send);
$message['subject'] = $subject;
$message['body'] = array();
$message['body'][] = $body;
// Retrieve the responsible implementation for this message.
$system = drupal_mail_system($module, $key);
// Format the message body.
$message = $system->format($message);
// Send e-mail.
$message['result'] = $system->mail($message);
if ($message['result'] == 1) {
drupal_set_message(t('Mail has been sent to the user'), 'status');
}
else {
drupal_set_message(t('Mail was not sent'), 'error');
};


ssh tunnel and rdesktop in one line

Question: To access a windows machine remotely I have to tunnel through a ubuntu server of mine. To setup the tunnel I have
ssh -l root -C -L 9999:windowsmachine:23389 myserver

Then I have to open another console and run
rdesktop -u user -password -f localhost:9999

How can I combine these in a single command or script?
Answer: (Disclaimer: See comments for a more efficient solution.)
This is tricky for a number of reasons:

ssh needs to run in the foreground to hold the connection open. This makes it challenging to do this within a single instance of a shell, because the second command needs to execute in parallel to it being foreground.
You can't test for the return status of the ssh command, because the connection will have closed by then. This means the resktop command will fire regardless of whether ssh authentication succeeded.
For the rdesktop command to not be interactive, it needs to supply the password in the command line. Storing the password in the script is a bad idea.

Try something like this:
#!/bin/bash

# Request password, no echo
read -s RDP_PW

# Insert password validation here (i.e. make sure we got input)

# Execute sleep+rdesktop in a background subshell, redirect STDOUT to /dev/null.
( sleep 5; rdesktop -u user -p$RDP_PW -f localhost:9999 ) >/dev/null &

# Run the ssh command. We have 5 seconds establish the tunnel.
ssh -l root -C -L 9999:windowsmachine:23389 myserver

Adjust the sleep statement as needed. You may want to remove the /dev/null redirection until you're sure this works. You also may want to redirect STDERR.
A better approach relies on the terminal program you're using within X, or whether or not you're familiar with a terminal multiplexer. If your terminal program provides a way for you to invoke a command in a new tab, prefix ssh with the appropriate command for doing that. If you go the multiplexer route, use the syntax for invoking ssh in a new multiplexer window. Dealing with passwords prompts from ssh in both cases is up to you.
Comment: You can also use the "-f" and "-N" flags (background, and no remote command execution), then you can run ssh first and rdesktop afterwards without a need for the sleep command.
Comment: @Derek I like your answer much better than my own. :) You should probably submit it as an answer and get the credit, it's the more efficient solution.

ssh tunnel and rdesktop in one line


Why does Cmaj7 and Emaj7 sound good (or a name to describe this progression)?

Question: I have an extremely limited understanding of theory, and from what I currently understand, chords will sound good together if they share a common key/scale (e.g. for C major scale, the chords that sound good will be Cmaj, Dmin, Emin, etc.).
However, for Cmaj7 and Emaj7, I can't seem to find a "well-known" scale (key) that fits both.  For example:

C major doesn't sound great
E major sounds okay with the Emaj7, but sounds bad with the Cmaj7
E minor pentatonic sounds okay with with the Cmaj7, but sounds bad with the Emaj7
etc.

There just seem to be too many conflicting notes like the G,C from the Cmaj7 and G#,C# from the Emaj7.  The same seems to be true for plain Cmaj and Emaj (sounds good together, but a lot of conflicting notes if trying to find an underlying key/scale).
Follow-up: E natural minor seems to sound good on top of both chords.  Similar to above, it seems to conflict on the 3rd and 7th note, so I'm confused why that works well with the chord progression.
Comment: So you're asking why CM7 followed by EM7 sounds good despite that not being an individual scale that sounds good over both?
Comment: I'm voting to close this question since it seems overly subjective ("sounds good" / "sounds bad" can't really be "measured").
Comment: @aaron yeah, pretty much
Comment: Alternatively, a name describing this "chord progression" could be useful too (edited the title)
Comment: What reason should there be for one scale to fit both chords?
Answer: In general, chords with common tones and whose non-common tones are only a short distance apart will make a good progression.

CMaj7 = C  E G  B
EMaj7 =   E  G# B D#

or, put another way:

CMaj7 = E  B  C  G
EMaj7 = E  B  D# G#

* two common tones
* one minor second
* one augmented second.

Note that the interval C–D# is native to the E harmonic minor scale.
Comment: Also the E chord could be described as borrowed from the parallel major.
Comment: @ToddWilcox The parallel major of? Please clarify.
Comment: Of E minor. Cmaj7 is diatonic in E minor, so that's one way to think about it.
Comment: @ToddWilcox That would explain OP's observation that E natural minor sounded good. Would you mind if I incorporate your observation into my post?
Comment: Not at all etc etc
Answer:
... chords will sound good together if they share a common key/scale

The term to describe that is diatonic, when all the pitches of a musical passage belong to a single scale/key.
When pitches are used from outside a single scale/key, you call that chromatic.
You can have chord progressions that sound good that are either diatonic or chromatic. There are many aspects that go into good harmony (chord progressions). For example, chord root progression by descending fifth. But the topic of harmony cannot be described in a short answer. It requires a full course of study.
The chord progression you are looking at can be described as having a chromatic mediant relationship, which is when the chord roots are separated by a major or minor third while the two chords are of the same quality. This particular chord relationship does not occur in plain diatonic music, hence the chromatic label.
At the risk of over-simplifying, when harmony is chromatic you can think of two general situations: the music is modulating to a new key, or if the chromaticism is extreme you start to get into atonal music, or it might be better to call it non-tonal, non-functional harmony.
If you are just alternating between Cmaj7 and Emaj7, the harmony is essentially static, and definitely not a case of modulating to a new key. You won't find a diatonic scale that match both chords. Listing the two chords and their respective major scales should show why that is the case...

Cmaj7
      *           *
|     |     |     |
C  D  E  F  G  A  B  C
      E  F# G# A  B  C D# E
      |     |     |    |
      *           *
Emaj7

In that diagram the | indicates the respective chord tones and the * indicates the common chord tones between the two chords.
Notice the G and G#. The G is the fifth, the dominant of C major, but the G# is the third, the mediant of E major. Both tones are essential tones in the respective keys. The dominant provides an essential tonal degree in C major, the mediant provides the major modal quality in E major. You will not find any single pitch that will fulfill those two functions, and that's why one scale will not work for both keys.
What you can do instead is focus the melody not on a single scale but instead on the chord tones of each chord when the chord changes. To provide unity between the two chords focus on the two common chord tones, the E and the B. Treat the other tones like passing tones. So, for example, over Cmaj7 you could play the descent C B then passing tone A and with the change to Emaj7 continue from A down to G#. You might then ascend through the A and with the change back to Cmaj7 ascend from A to B. Such a line undulates around the common tone B which is the seventh of Cmaj7 and the fifth of Emaj7.
You could think of those melodic tones G# A B C as a segment of an A minor scale, but I don't think that is particularly helpful. When the chords are essentially chromatic, trying to shoehorn the melody into a diatonic scale just forces the melody to work against the grain of harmony. It's probably better to treat the melody more fluidly, more chromatically, while focusing on the common chord tones for some harmonic unity.
Answer: A different kind of perspective... I hope.
What happens in my harmonic ear with a chord progression  Cmaj7 - Emaj7 (repeat)? How can I treat this chord progression, what kind of a melody could I draw over it?
I feel Emaj7 as being the most natural home chord here, and the Cmaj7 makes chromatic alterations to the context, essentially sounding like being in E minor. In other words, it's doing the good old jazzy trick, switching between minor and major. Melodic lines centering on E fit well over those chords, and during the Emaj7 chord it's like in E major, and during the Cmaj7 chord it's like in E minor. Back and forth. I like the sound of chromatic alterations, and I guess so do many other people.
It's also possible to treat the Cmaj7 chord as a key center during that chord, and arrange melodic elements around that, and then modulate to E during the Emaj7, moving the center point back and forth. I tried it, and it can be done, but it feels weird and clunky, compared to E being a center and changing the harmony around the E.
You say "E minor pentatonic sounds okay with with the Cmaj7", and that's why I'm fairly sure that you hear the chord progression just like me - you hear E as being a tonal center. The only missing piece in the puzzle is to know about chromatic alterations. When the Emaj7 chord comes, you switch your thinking from E minor to E major.
To demonstrate this way of treating the chords - and with good reason to believe it's quite exactly the way that was meant in the question - I wrote a little smooth-jazzish tune:

The key center is always E, just the pitches around it are changed back and forth.


Is there a way of seeing how many open sessions there are in IIS6?

Question: I have a feeling we are being hit by very high traffic, how do I prove or disprove my theory?
Answer: You can use performance counters (perfmon), specifically Web Service\Current Connections
Comment: How do I add live sessions in Perfmon?
Answer: Check your IIS log files, they log every single request that comes into the server. By default, they should be located in C:\inetpub\logs\LogFiles\, however, your server administrator may have changed that
Comment: Can I analyzer them live without affecting them (as far as I can understand most text editors will have a fit as the file constantly changes)


How to hide blocks based on content type or for specific nodes?

Question: In some of my nodes I need to show only "body" part of node. I don't want to show blocks etc. in those nodes. How can I do this ?

Create a new "content type" and put the data from existing nodes to that type of node. And excluding that "content type" from each of the blocks.
By using javascript/jquery like: $('div'.block).remove()

Any more elegant answers?
Answer: The answer very much depends on how the nodes you want to show only bodies of are different from all other nodes of same content type.
I see two possible solutions:

Create a new content type and convert all the nodes you want to it. Then you can specify in blocks visibility settings not to show blocks on the nodes of that content type and create a new template for this content type in which only body is printed.
Another way is to give the context module a try. The context module provides a much more flexible way to control blocks visibility so you can specify different contexts for your normal nodes (and assign blocks to this context) and your no-blocks nodes with no blocks assigned.

I'm sure there must be other ways to accomplish this, but these two are the first things I thought of :)
Answer: Creating a new content type, just for this, seems like something you should try to avoid (the number of content types should always be reduced where possible). These days there is another alternative available: use the Rules block visibility module. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
Need to show a block only for users registered more than a month ago?
Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
What about displaying or hiding a block based on current weather conditions?
All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules intercept the situation where someone uses an URL that corresponds to "some of your nodes" (as in your question), so that the block is NOT shown for those nodes.
For that, create a Rules Component with a Rules Condition that performs a Text comparison with Parameter: Text: [site:current-page:path] and an appropriate Matching Text for the URLs like "NOT (node/nid1 AND  node/nid2)", whereas nid1 and nid2 or the node ids of nodes for which the blocks should not be shown.


How to Select Specific Columns in Pandas DataFrame Using Multiple Boolean Conditions

Question: I'm trying to find a very good, comprehensive answer to the above question.
Let's take the following dataframe:
df = pd.DataFrame(np.random.randn(4,4), columns=['A', 'B', 'C', 'D'])
df['Category'] = pd.Series(['Cat1', 'Cat2', 'Cat1', 'Cat2'])
df:
            A         B         C         D Category
  0  0.057456  0.462712 -1.245539  0.095947     Cat1
  1  0.741688  0.353600  1.130754 -1.692440     Cat2
  2  0.638623 -0.109566  0.118509 -0.692661     Cat1
  3 -0.905806  0.284818 -0.094696 -1.325617     Cat2

I understand the basic nomenclature of using df.A or df['A'] to select column A, and df[['A', 'B']] to select both columns A and B.
And if I want to pass in boolean conditions I can do things like df[df.A > 0] to return rows where df.A is greater than 0.  And I can include multiple conditions like df[(df.A > 0) & (df.Category == 'Cat1')] to include multiple conditions.
One thing I am not seeing though, is how I could select a subset of the dataframe columns with the same two boolean conditions used above.
Two approaches I have tried without success:
df['B'].where(df.A > 0)

This returns all of the rows in the index, whereas I'd only like the ones that return True for said condition.
I've also tried using query without success because it can't be used on a Series.
So df['A'].query(some condition) returns an error message.
Ideally the solution I'm looking for has the following conditions:

Can be used both on single columns or multiple columns.  Ie, you can choose both df['A'] and df['B'] with it.
Can use multiple boolean conditions if you want to, not just one.
Only returns the rows that evaluate to True for the condition, not all the rows.
Ideally is syntactically simple, but if that's not possible then so be it.

Thank you.
Answer: I think you are looking for .loc
df.loc[df.A>0,'B']
0    0.462712
1    0.353600
2   -0.109566
Name: B, dtype: float64
df.loc[(df.A>0)&(df.B<0),['B','C']]
          B         C
2 -0.109566  0.118509

Comment: You are too fast! And congratulations for 100K!
Answer: You are proceeding correctly with your df['B'].where(df.A > 0) condition. However, just append few more function after it to achieve only True results.
An example with multiple (can pass single too) condition:
df[['B','C']].where((df.A > 1) & (df.D>0)).dropna().reset_index(drop=True)

Answer: Just a variation of @W-B's answer using query:
df.query('A > 0 and B < 0').loc[:, ['B', 'C']]

or
df.query('A > 0 and B < 0')[['B', 'C']]

will also print
          B         C
2 -0.109566  0.118509

Comment: @Datanovice: What do you mean by "only work on the index"? I looked at the four requirements listed in the question, and think that `query` addresses all of them. It also [works fine on different index levels](https://stackoverflow.com/a/49045951/1534017).
Comment: Apologies, I should have consulted the docs first. I was thinking of the.   .filter function. Thanks for teaching me something new.
Comment: @Datanovice: No worries :)


.join() command with maximum string length in python

Question: I want to join a list of ids to a string, where each id is separated by an 'OR'. In python I can do that with
' OR '.join(list_of_ids)

I am wondering whether there is a way to prevent this string from becoming too large (in terms of bytes). The reason why this is important for me is that I use that string in an API and that API imposes a max length of 4094 bytes.
My solution is below, I am just wondering whether there is a better one?
list_of_query_strings = []
substring = list_of_ids[0]
list_of_ids.pop(0)
while list_of_ids:
    new_addition = ' OR ' + list_of_ids[0]
    if sys.getsizeof(substring + new_addition) < 4094:
        substring += new_addition
    else:
        list_of_query_strings.append(substring)
        substring = list_of_ids[0]
    list_of_ids.pop(0)
list_of_query_strings.append(substring)

Comment: Why do you need this?
Comment: For the record, `sys.getsizeof` has very little to do with the length of the string, especially on Python 3.3+. It's (roughly) the number of bytes used to store the string, including all overhead, but on Py3 in particular, the numbers vary wildly depending on whether it's ASCII, latin-1, BMP or non-BMP, whether it has a cached UTF-8 form (an implementation detail that is fairly unpredictable), etc. It has no useful relationship to the number of characters. When you concatenate the strings, it's often gets smaller than the sum of the original strings thanks to removing object header redundancy.
Comment: What is the plan after it's gets to long, create a new string or removing stuff from the beginning?
Comment: hi I clarified my question... first it is a limit on the number of bytes, not characters, sorry for the confusion... second the point why I need this is because of API max request limits.
Comment: @carl: `sys.getsizeof` is still going to be wrong for number of bytes though. Each `str` has a Python object header; the joined string collapses `n` headers down to one (saving memory). Similarly, a dozen ASCII strings joined to a single non-BMP string will end up *much* larger than the component sizes (because all the ASCII data will end up stored as four bytes per character, when originally it was one byte per character). The only useful way to look at this that isn't totally arbitrary would be the size of the encoded form in a given encoding (e.g. how large is the UTF-8 form in bytes).
Answer: Just for fun, an over-engineered solution (that avoids Schlemiel the Painter repeated concatenation algorithms, allowing you to use str.join for efficient combining):
from itertools import count, groupby

class CumulativeLengthGrouper:
    def __init__(self, joiner, maxblocksize):
        self.joinerlen = len(joiner)
        self.maxblocksize = maxblocksize
        self.groupctr = count()
        self.curgrp = next(self.groupctr)
        # Special cases initial case to cancel out treating first element
        # as requiring joiner, without requiring per call special case
        self.accumlen = -self.joinerlen

    def __call__(self, newstr):
        self.accumlen += self.joinerlen + len(newstr)
        # If accumulated length exceeds block limit...
        if self.accumlen > self.maxblocksize:
            # Move to new group
            self.curgrp = next(self.groupctr)
            self.accumlen = len(newstr)
        return self.curgrp

With this, you use itertools.groupby to break up your iterable into pre-sized groups, then join them without using repeated concatenation:
 mystrings = [...]

 myblocks = [' OR '.join(grp) for _, grp in
             groupby(mystrings, key=CumulativeLengthGrouper(' OR ', 4094)]

If the goal is to produce strings with a given byte size using a specified encoding, you could tweak the CumulativeLengthGrouper to accept a third constructor argument:
class CumulativeLengthGrouper:
    def __init__(self, joiner, maxblocksize, encoding='utf-8'):
        self.encoding = encoding
        self.joinerlen = len(joiner.encode(encoding))
        self.maxblocksize = maxblocksize
        self.groupctr = count()
        self.curgrp = next(self.groupctr)
        # Special cases initial case to cancel out treating first element
        # as requiring joiner, without requiring per call special case
        self.accumlen = -self.joinerlen

    def __call__(self, newstr):
        newbytes = newstr.encode(encoding)
        self.accumlen += self.joinerlen + len(newbytes)
        # If accumulated length exceeds block limit...
        if self.accumlen > self.maxblocksize:
            # Move to new group
            self.curgrp = next(self.groupctr)
            self.accumlen = len(newbytes)
        return self.curgrp

Comment: very nice solution... like for other solutions, len() does only count the number of characters, which fails at least for the API I am using. I guess the API expects a utf8 string? but I don't really know. sys.getsizeof() seems to work for me, but you don't seem to like that?
Comment: @carl: `sys.getsizeof` might "work", but it would also end up producing groups that are much smaller than your API would actually accept (assuming it's not somehow size dependent on the raw `PyUnicode_Object` size in bytes). For example, `sys.getsizeof('a')` is 54, even though it's usually one byte when stored to disk or sent over the wire (and never more than four, even encoded as UTF-32); `sys.getsizeof(' OR ')` is 53 (smaller because weirdness). So if you had an input of `['a'] * 100`, joined with `' OR '`, you'd treat it as ~10 KiB, when it's likely transmitted as < 500B.
Comment: so what is your suggestion for how to deal with this? Like I said, if I use len(), the string is too long... so the API does not seem to expect ASCII
Comment: @carl: I can't give you a suggestion without knowing what the API is doing. If the API is encoding as UTF-8, then my second implementation is correct (note: It's assuming you can hit, but not exceed, the max length; you'd change the test to `>= self.maxblocksize` if the max length was exclusive, not inclusive). But the API might be prefixing it with a byte count, or using UTF-16, or some other approach. You haven't provided sufficient detail.
Comment: @carl: BTW, an example of why `sys.getsizeof` is so useless for computing the size of the resulting string after concatenation: `sys.getsizeof(chr(0x1ffff)) + sys.getsizeof('a' * 4000)` is 4129. `sys.getsizeof(chr(0x1ffff) + 'a' * 4000)` (the concatenation of the two input strings) is 16080 (the non-BMP character means all four thousand `a`s need to be stored in 4 bytes a piece, instead of the 1 byte a piece they used in a pure ASCII string). If `sys.getsizeof` is actually important, something is *terribly* wrong with your API.
Answer: This is a simpler solution than your current one:
list_of_query_strings = []
one_string = list_of_ids[0]

# Iterate over each id
for id_ in list_of_ids[1:]:
    # Add the id to the substring if it doesn't make it to large
    if len(one_string) + len(id_) + 4 < 4094:
        one_string += ' OR ' + id_
    # Substring too large, so add to the list and reset
    else:
        list_of_query_strings.append(one_string)
        one_string = id_

Comment: small issue... the string should not start with 'OR'. Like the join command, 'OR' should only appear between ids
Comment: also len() does only check for number of characters, right? While 4094 is the number of bytes
Comment: I corrected that issue. Yes, `len` returns the number of character. That is the same as the number of bytes if you're only using ASCII. If you need unicode, my answer will answer will fail.
Comment: My algorithm would still work, except you would need to switch out `len` for some `number_of_bytes` function.
Comment: you still need to remove the 'OR' in the last line, but I agree that would work


Django Projects & Apps

Question: i am a django newbie, and trying to get my projects and apps in a directory on my desktop.. I need to add these directories to the python path so it knows where they live and can interact with eachother.. how can I do this best? I found several ways which might have downsides???

through shell, import sys, sys.path.append('/my/dir') isn't permanent?
through sitecustomize.py, this is permanent but in my python IDE it seems modules get loaded multiple times? because my python in running in a framework (macosx)
through commandline export PYTHONPATH:$ etc etc

So whats the way to go ?
Answer: I tend to use the simple
import sys
path = '/var/www/Django/'
if path not in sys.path:
    sys.path.append(path)

In my WSGI scripts which "power" my application. I also have a custom management command that does exactly this before calling shell. Previously to that, I simply dumped the above in
settings.py.
/var/www/Django is where all my projects belong - thus if I'm referring to a project I always use project.app. Once I've created a portable app for re-use, it graduates and lives in /var/www/Django itself and gets included via other project's settings.py. Does that make sense?

Django Projects & Apps


Script em Python não gera o gráfico como esperado

Question: Meu algoritmo em Python está rodando perfeitamente, só não consigo gerar o gráfico! Não consegui identificar o erro... O que tem de errado?
import matplotlib.pyplot as plt

va=float(input('Digite o valor a ser aplicado: '))
juros=1.05
inflacao=1.02
saque=25000
vaplicacao=[va]
nsaque=0
vsaque=[]

while saque<=vaplicacao[len(vaplicacao)-1]:
    va=(vaplicacao[len(vaplicacao)-1]*juros)-(saque)
    vaplicacao.append(va)
    nsaque=nsaque+1
    saque=saque*inflacao
    vsaque.append(nsaque)

plt.plot(vsaque,vaplicacao,'b-')
plt.title('Saldo x Saque')
plt.grid(True)
plt.xlabel('Saque ao longo dos anos')
plt.ylabel('Saldo ao longo dos anos')
plt.show()

Comment: Mas não estava rodando perfeitamente? Ficou confuso agora. Esse erro aparece para você também?
Comment: E quais são as entradas que está utilizando? Porque todos os testes que fiz obtive o erro "*ValueError: x and y must have same first dimension, but have shapes*".
Comment: Eu preciso que o gráfico mostre no eixo "X" o vetor "vsaque" e no eixo "Y" o vetor "vaplicacao". Este é o erro que aparece aqui.    Traceback (most recent call last):
  File "C:\Users\Guilherme\Desktop\EXERCÍCIO 5 LISTA 5.py", line 18, in
    plt.plot(vsaque,vaplicacao,'b-')
  File "C:\Users\Guilherme\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\pyplot.py", line 3358, in plot
    ret = ax.plot(*args, **kwargs)
Comment: É que eu rodei o algorítimo sem as informações para gerar o gráfico e mandei ele dar um print no vetor "vsaque" e "vaplicacao". Com isso pude visualizar se o algorítimo estava calculando corretamente e está.. Agora eu preciso que ele gere um gráfico com esses vetores, só que quando inseri os códigos para gerar o gráfico aparece estes erros informados
Answer: Você está inicializando a lista vaplicacao com um valor:
vaplicacao=[va]

Enquanto a lista vsaque inicia vazia:
vsaque=[]

Como, dentro do laço, você sempre adiciona um valor em cada lista, a lista vaplicacao sempre terá um elemento a mais que vsaque; assim, é impossível plotar em um gráfico uma curva que tenha n pontos no eixo das abcissas e n+1 pontos no eixo das ordenadas. Se você iniciar vsaque com um valor possivelmente funcionará:
vsaque=[nsaque]

Aliás, para pegar o último elemento da lista, basta fazer lista[-1]; não precisa de lista[len(lista)-1].
import matplotlib.pyplot as plt

va = float(input('Digite o valor a ser aplicado: '))
juros = 1.05
inflacao = 1.02
saque = 25000
vaplicacao = [va]
nsaque = 0
vsaque = [nsaque]

while saque <= vaplicacao[-1]:
    va = vaplicacao[-1]*juros - saque
    vaplicacao.append(va)
    nsaque += 1
    saque = saque*inflacao
    vsaque.append(nsaque)

plt.plot(vsaque, vaplicacao, 'b-')
plt.title('Saldo x Saque')
plt.grid(True)
plt.xlabel('Saque ao longo dos anos')
plt.ylabel('Saldo ao longo dos anos')
plt.show()

Comment: Perfeito! Funcionou, comecei a lista vsaque=[nsaque]... Muito Obrigado!
Answer: No seu caso, como a contagem de saques é linear e sequencial, você não precisa montar uma lista para o eixo X do gráfico. A matplotlib é capaz de fazer isso automaticamente, e seu programa poderia ficar mais compacto, veja só:
import matplotlib.pyplot as plt

va = float(input('Digite o valor a ser aplicado: '))

juros = 1.05
inflacao = 1.02
saque = 25000
vaplicacao = [va]

while saque <= vaplicacao[-1]:
    va = (vaplicacao[-1] * juros) - saque
    saque *= inflacao
    vaplicacao.append(va)

plt.plot( vaplicacao, 'b-')
plt.plot( vaplicacao, 'ro')

plt.grid(True)
plt.title('Saldo x Saque')
plt.xlabel('Saque ao longo dos anos')
plt.ylabel('Saldo ao longo dos anos')

plt.show()

Saída (va=800000):

Saída (va=600000):

Saída (va=400000):


How can I interpret this correlation?

Question: I got correlation coefficient r = 0.33
but my p-value = 0.124 > 0.05
Is there a non-significant correlation or no correlation at all?
Comment: Please read some of the many threads on the topic how to interpret (insignificant) p-values. For example: [How do you know if an insignificant P value is because of chance error or because the sample size of the data is too small?](https://stats.stackexchange.com/q/578478/237901)
Answer:
I got correlation coefficient r = 0.0001 but my p-value = 0.000001 <
0.05. I have a massive dataset. Is there a non-significant correlation or no correlation at all?

I flipped a penny one and a dime once and they both landed on heads. I
got correlation coefficient r = 1 but my p-value is more than 0.05.

The "technically correct" answer to your question may or may not be what you want. However, it is this:

I got correlation coefficient r = 0.33 but my p-value = 0.124 > 0.05
Is there a non-significant correlation or no correlation at all?

There is a non-significant correlation (the same as in the second example).

How can I interpret this correlation?


If $A\oplus B\approx A$ then $B=0$?

Question: Suppose $A,B$ abelian groups, such that $A\oplus B\approx A$, can I conclude that $B=0$?
If it's true, is there any hint how to prove it?
Comment: $\approx$ means isomorphic ?
Comment: You need more assumption than that, assuming $\oplus$ means direct sum.  It would hold for *finite* abelian groups.
Answer: No; consider $A=\Bbb{Z}^{\Bbb{N}}=\bigoplus_{n\in\Bbb{N}}\Bbb{Z}$.

If $A\oplus B\approx A$ then $B=0$?


Module for enforcing mandatory minimum number of tags in content type field?

Question: The built-in tag field functionality allows definition of a maximum number of tags, but not a minimum number.
Is there a contrib module to enforce a minimum?
Comment: I'm voting to close this question because it's asking for recommendations or suggestions on books, tools, modules, themes, distributions, tutorials, or other off-site resources.
Answer: You should be able to use Field Validation.

This module adds an extra tab to each field instance, allowing you to
  specify validation rules for your field instances.

Just create your term/entity reference field and set up a validation rule using the Number of Selections rule.
Leave the maximum number of fields empty, and enter the minimum you require as the minimum required values.


squid Access Denied. for http but not https, dispite removing http_access deny CONNECT !SSL_ports

Question: I have the following config file.Comments and blank lines removed. Lines starting #> are the ones I removed to get normal http to work. But it is still blocked.
acl localnet src 172.16.0.0/12 #docker
acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
acl CONNECT method CONNECT
#>http_access deny !Safe_ports
#>http_access deny CONNECT !SSL_ports
http_access allow localhost manager
#>http_access deny manager
http_access allow localnet
http_access allow localhost
#>http_access deny all
http_port 3128
cache_dir aufs  /media/richard/extra2/squid-cache 20000 16 256
coredump_dir /var/spool/squid
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320

https works if I connect to 127.0.0.1; https even works when disabled.
https does not work when connecting to 172.16.0.1, the same machine on the docker interface.
How do I get squid to proxy plain http?
Answer: I added debug_options ALL,1 33,2 to the top of the config file, then found this in the logs:
local=172.17.0.1:3128 remote=192.168.43.64

It looks like it is detecting the remote as my IP address on the external interface. I then added
acl localnet src 192.168.0.0/16 # RFC1918 possible internal network

to the config and it works. Note this is a security problem, as now we allow connections from this network.
I have no idea why the remote IP is not from the same network. I have no idea why https worked. I will use my local firewall, but I would still like a fix (in case the fire wall gets miss-configured).
Comment: I will not accept my own answer, as it does not explain or fully fix the problem.


Close Mic beep Sound or Sound of single Application Flutter

Question: Can we Close All sounds of single application that will not effect other apps sound or general sound , or
i am working on voice recognition app , is there any solution to close mic beep sound , because i have to take repeatedly input from user and beep sound of mic start and stop is distrubing
Thanks in advance
Comment: did yu resolve ?
Answer: You could do:
<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val amanager: AudioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
    amanager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, AudioManager.ADJUST_MUTE, 0);
}
</code>
In MainActivity.kt, this should mute most things.


How to correctly morph shapes with android.graphics.Path?

Question: For example I have a square shape drawn on Canvas with android.graphics.Path, how to morph it into circle or any other shape?
It's possible to do it with SVG, VectorDrawables, you can see examples here.
But how to do it with android.graphics.Path?
Answer: You can morph vectors with AnimtedVectorDrawables, here is a tutorial for that.
One web tools to use is ShapeShifter, and here is a tutorial for that.

Be aware that Android don't fully support SVG.
  Had issues with gradients since it's done different in SVG then in VectorDrawables.
Comment: I need to morph android.graphics.Path that I've drawn with canvas.drawPath, I'm not sure how to convert that into pathData. I'm not using svg or drawables.


Shopping cart delete button is not removing the correct line item.

Question: I have 2 blocks on my shopping cart. The view block for the Main Product and another for the Specials ( which is an add-on), each block has their own delete button. I use a Views Field View on the Main Product block to call the Specials blocks. Each specials and main products are connected via node referencing. I can't use just 1 view block to show it like that because I need the added specials to be filtered/shown below the main product where it's connected.

When removing a specials, it deletes the line item properly but when I try to remove a main product it deletes the special that follows the main product and when there's no more special for that specific main product, it deletes the specials of other main product. It does not delete the line item where the remove is connected. I don't know why it works like that because each remove has their own line item.
Answer: Sounds to me like both of your forms on the page have the same form ID and use the same numeric key (likely 0) to identify the first item in the form. Thus when you submit it, Drupal doesn't know how to differentiate which form was submitted and makes a best guess, removing the 0th item in that form.
Alternately, if your configuration is generating a form within a form, that's invalid HTML and would explain a similar confusion on Drupal's part for the processing of the form. You would need to find an alternate method for getting the secondary form on the page, such as using the block system to embed the second form on the page.
Comment: Hi, it has different form ID but the form of the Specials ( add-on ) is inside the form of Main Product since the view was embedded within a view. how can I make this work?
Comment: Ok, that is also illegitimate HTML and makes sense why Drupal wouldn't know what to do with the submission. You need it to be added to the page some other way, such as through the block system, to prevent it from becoming part of the other Views form.