text:
Q: Split array vertically, add rows of data, sort, and then apply regression for rainfall data I have meteorological data from many sites which are compiled together in the one array e.g. the different columns below refer to Station Year Month Rainfall respectively (the rows with nan nan nan nan are because the .csv file has string headers separating each data set).
The data I'm using is about 111 sites each with 40+ years of rainfall data, this is just a subset I was experimenting with -
 [[             nan              nan              nan              nan]
 [  1.47130000e+04   1.96800000e+03   1.00000000e+00   2.79000000e+01]
 [  1.47130000e+04   1.96800000e+03   2.00000000e+00   1.30700000e+02]
 [  1.47130000e+04   1.96800000e+03   3.00000000e+00   8.49000000e+01]
 [  1.47130000e+04   1.96800000e+03   4.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   1.96800000e+03   5.00000000e+00   2.41000000e+01]
 [  1.47130000e+04   1.96800000e+03   6.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   1.96800000e+03   7.00000000e+00   3.45000000e+01]
 [  1.47130000e+04   2.00900000e+03   3.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   2.00900000e+03   4.00000000e+00   5.65000000e+01]
 [  1.47130000e+04   2.00900000e+03   5.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   2.00900000e+03   6.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   2.00900000e+03   7.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   2.00900000e+03   8.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   2.00900000e+03   9.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   2.00900000e+03   1.00000000e+01   0.00000000e+00]
 [  1.47130000e+04   2.00900000e+03   1.10000000e+01   6.20000000e+00]
 [  1.47130000e+04   2.01000000e+03   1.00000000e+00   2.33300000e+02]
 [  1.47130000e+04   2.01000000e+03   2.00000000e+00   8.71000000e+01]
 [  1.47130000e+04   2.01000000e+03   3.00000000e+00   4.08000000e+01]
 [  1.47130000e+04   2.01000000e+03   4.00000000e+00   9.62000000e+01]
 [  1.47130000e+04   2.01000000e+03   5.00000000e+00   2.21000000e+01]
 [  1.47130000e+04   2.01000000e+03   6.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   2.01000000e+03   7.00000000e+00   2.20000000e+00]
 [  1.47130000e+04   2.01000000e+03   8.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   2.01000000e+03   9.00000000e+00   0.00000000e+00]
 [  1.47130000e+04   2.01000000e+03   1.00000000e+01   8.60000000e+00]
 [  1.47130000e+04   2.01000000e+03   1.10000000e+01   1.63000000e+01]
 [  1.47130000e+04   2.01100000e+03   1.00000000e+00   1.10800000e+02]
 [  1.47130000e+04   2.01100000e+03   2.00000000e+00   6.76000000e+01]
 [  1.47130000e+04   2.01100000e+03   3.00000000e+00   1.98000000e+02]
 [  1.47130000e+04   2.01100000e+03   6.00000000e+00   4.10000000e+00]
 [  1.47130000e+04   2.01100000e+03   1.00000000e+01   2.52000000e+01]
 [  1.47130000e+04   2.01100000e+03   1.10000000e+01   4.17000000e+01]
 [  1.47130000e+04   2.01200000e+03   1.00000000e+00   2.13600000e+02]
 [  1.47130000e+04   2.01200000e+03   2.00000000e+00   7.44000000e+01]
 [  1.47130000e+04   2.01200000e+03   3.00000000e+00   9.14000000e+01]
 [  1.47130000e+04   2.01200000e+03   4.00000000e+00   1.70000000e+01]
 [  1.47130000e+04   2.01200000e+03   5.00000000e+00   1.56000000e+01]
 [  1.47130000e+04   2.01200000e+03   7.00000000e+00   4.20000000e+00]
 [  1.47130000e+04   2.01200000e+03   1.00000000e+01   3.40000000e+00]
 [  1.47130000e+04   2.01200000e+03   1.10000000e+01   7.70000000e+00]
 [             nan              nan              nan              nan]
 [  1.47320000e+04   2.00000000e+03   9.00000000e+00   0.00000000e+00]
 [  1.47320000e+04   2.00000000e+03   1.00000000e+01   8.34000000e+01]
 [  1.47320000e+04   2.00000000e+03   1.10000000e+01   1.17000000e+02]
 [  1.47320000e+04   2.00000000e+03   1.20000000e+01   4.90800000e+02]
 [  1.47320000e+04   2.00100000e+03   1.00000000e+00   1.64200000e+02]
 [  1.47320000e+04   2.00100000e+03   2.00000000e+00   6.51600000e+02]
 [  1.47320000e+04   2.00100000e+03   3.00000000e+00   1.36800000e+02]
 [  1.47320000e+04   2.00100000e+03   4.00000000e+00   1.64400000e+02]
 [  1.47320000e+04   2.01000000e+03   9.00000000e+00   0.00000000e+00]
 [  1.47320000e+04   2.01100000e+03   1.00000000e+00   1.82400000e+02]
 [  1.47320000e+04   2.01100000e+03   2.00000000e+00   3.81000000e+02]
 [  1.47320000e+04   2.01100000e+03   3.00000000e+00   4.50800000e+02]
 [  1.47320000e+04   2.01100000e+03   4.00000000e+00   3.12800000e+02]
 [  1.47320000e+04   2.01100000e+03   5.00000000e+00   0.00000000e+00]
 [  1.47320000e+04   2.01100000e+03   6.00000000e+00   0.00000000e+00]
 [  1.47320000e+04   2.01100000e+03   7.00000000e+00   1.60000000e+00]
 [             nan              nan              nan              nan]
 [  1.55030000e+04   1.96600000e+03   1.00000000e+00   6.47000000e+01]
 [  1.55030000e+04   1.96600000e+03   2.00000000e+00   1.14000000e+01]
 [  1.55030000e+04   1.96600000e+03   3.00000000e+00   0.00000000e+00]
 [  1.55030000e+04   1.96600000e+03   4.00000000e+00   0.00000000e+00]
 [  1.55030000e+04   1.96600000e+03   5.00000000e+00   2.80000000e+00]
 [  1.55030000e+04   1.96600000e+03   6.00000000e+00   3.47000000e+01]
 [  1.55030000e+04   1.96600000e+03   7.00000000e+00   0.00000000e+00]
 [  1.55030000e+04   2.01100000e+03   2.00000000e+00   1.40500000e+02]
 [  1.55030000e+04   2.01100000e+03   3.00000000e+00   1.13700000e+02]
 [  1.55030000e+04   2.01100000e+03   4.00000000e+00   0.00000000e+00]
 [  1.55030000e+04   2.01100000e+03   5.00000000e+00   4.00000000e-01]
 [  1.55030000e+04   2.01100000e+03   6.00000000e+00   8.60000000e+00]
 [  1.55030000e+04   2.01100000e+03   7.00000000e+00   2.20000000e+00]
 [  1.55030000e+04   2.01100000e+03   8.00000000e+00   0.00000000e+00]
 [  1.55030000e+04   2.01100000e+03   9.00000000e+00   4.50000000e+00]
 [  1.55030000e+04   2.01100000e+03   1.00000000e+01   2.00000000e+00]
 [  1.55030000e+04   2.01100000e+03   1.10000000e+01   2.80000000e+01]
 [  1.55030000e+04   2.01100000e+03   1.20000000e+01   4.18000000e+01]
 [  1.55030000e+04   2.01200000e+03   1.00000000e+00   4.82000000e+01]
 [  1.55030000e+04   2.01200000e+03   2.00000000e+00   5.62000000e+01]
 [  1.55030000e+04   2.01200000e+03   3.00000000e+00   1.45600000e+02]
 [  1.55030000e+04   2.01200000e+03   4.00000000e+00   1.62000000e+01]
 [  1.55030000e+04   2.01200000e+03   5.00000000e+00   0.00000000e+00]
 [  1.55030000e+04   2.01200000e+03   6.00000000e+00   0.00000000e+00]
 [  1.55030000e+04   2.01200000e+03   7.00000000e+00   0.00000000e+00]
 [  1.55030000e+04   2.01200000e+03   8.00000000e+00   0.00000000e+00]
 [  1.55030000e+04   2.01200000e+03   9.00000000e+00   2.60000000e+00]
 [  1.55030000e+04   2.01200000e+03   1.10000000e+01   2.52000000e+01]
 [  1.55030000e+04   2.01200000e+03   1.20000000e+01   1.09900000e+02]]

*

*I need to break up the data based on the different stations (first column). I think I can do this using B = np.array_split(alldata,np.where(SN == 0)[0]) (where SN is the first column of data, with a 0 in the Station column by replacing initially in excel). However, this results with the 0 nan nan nan row being included in each split array. I've also tried - for key,items in groupby(alldata,itemgetter(0)): print(key), but not sure how to manipulate further the split data sets with the groupby() function.

*Once the data is split into separate arrays, I need to insert rows for missing months and years and to have the corresponding cells in the new rows blank for the precipitation column. I understand how to join two lists, but I'm not sure about inserting data based on missing values from a sequence, and having it apply to the whole array. For example, with the data above, I'd like all arrays to have year and month columns extending from 1966 to 1981 so I can correlate the different months together.

*Once all the data is of equal length I want to run a regressions between all precipitation data for the different sites. For example, say the first block of data is the "site of interest", I would like to get the r^2 value for the correlation between its rainfall data and other sites in the data set. Eventually, I would also like to alter the rainfall data to be a percentile of all the rainfall data at that site, and then correlate all the rainfall values in percentile form with the "site of interest"
I'm not sure if this makes sense, please let me know what I should add to the question (this is my first question).
Updated Code From User's (Brionius) Comments and Suggestions:
The code works fine up to applying the regression. Not really sure about applying a correlation using a mask.
I tried doing the correlation without a mask using slope, intercept, r_value, p_value, std_err = stats.linregress(rotated[0][0],rotated[i][0]) but it returned nan values for all the r_values, presumably because of the nan values in the dataset.
  import numpy as np

# Import data:
alldata=\
         np.genfromtxt("combinedWdata.csv",unpack=False,\
                        delimiter=",")

# Split array based on where the 'nan' values are
dataSets = filter(lambda x: len(x) > 0,\
                  np.array_split(alldata,np.where(np.isnan(alldata[:,1]))[0]))

# Delete the rows with 'nan' in it.
dataSets = [np.delete(dataSet, np.where(np.isnan(dataSet)), axis=0)\
           for dataSet in dataSets]

# Assign variables to years and months
startYear = 1877
endYear = 2013
startMonth = 1
endMonth = 12
blank_rainfall_value = np.nan

# Insert rows of the form ['nan', year, month, 0] for all relevant \
    #years/months except where there is already a row containing that year/month
extendedDataSets = []
for dataSet in dataSets:
    missingMonths = [[dataSet[0][0], year, month, blank_rainfall_value] \
                     for year in range(startYear, endYear+1)\
                     for month in range(startMonth, endMonth+1) \
                     if [year, month] not in dataSet[:,1:3].tolist()]
    if len(missingMonths) > 0:
        extendedDataSets.append(np.vstack((dataSet, missingMonths)))

# Sort arrray by year, then month
finalDataSets = [np.array(sorted(dataSet, key=lambda row:row[1]+row[2]/12.0))\
                 for dataSet in extendedDataSets]

# Rotate data to compare between columns rather than rows
rotated=[]
for dataSet in finalDataSets:
    u=np.rot90(dataSet)
    rotated.append(u)
rotated=np.array(rotated)

# Delete year month and station
m=0
rotatedDel=[]
for i in rotated:
    v=[rotated[m][0]]
    rotatedDel.append(v)
rotatedDel=np.array(rotatedDel)

# Apply regression between first station and all later stations with \
#mask for nan values
m=0
r_values=[]
for i in rotatedDel:
    r_value=np.ma.corrcoef(x=\
            (np.ma.array(rotatedDel[0],mask=np.isnan(rotatedDel[0]))),y=\
            (np.ma.array(rotatedDel[m],mask=np.isnan(rotatedDel[m]))),\
             rowvar=False,allow_masked=True)
    r_values.append(r_value)
    m=m+1

A: Here's a solution to your questions (1) and (2).  Can't help you with the regression without more information about what you have in mind.
# Split array based on where the 'nan' values are
dataSets = filter(lambda x: len(x) > 0, np.array_split(alldata,np.where(np.isnan(alldata[:,1]))[0]))

# Delete the rows with 'nan' in it.
dataSets = [np.delete(dataSet, np.where(np.isnan(dataSet)), axis=0) for dataSet in dataSets]

startYear = 1966
endYear = 1981
startMonth = 1
endMonth = 12
blank_rainfall_value = np.nan

# Insert rows of the form ['nan', year, month, 0] for all relevant years/months except where there is already a row containing that year/month
extendedDataSets = []
for dataSet in dataSets:
    missingMonths = [[dataSet[0][0], year, month, blank_rainfall_value] for year in range(startYear, endYear+1) for month in range(startMonth, endMonth+1) if [year, month] not in dataSet[:,1:3].tolist()]
    if len(missingMonths) > 0:
        extendedDataSets.append(np.vstack((dataSet, missingMonths)))

# Sort arrray by year, then month
finalDataSets = [np.array(sorted(dataSet, key=lambda row:row[1]+row[2]/12.0)) for dataSet in extendedDataSets]

for dataSet in finalDataSets:
    print dataSet
    print


text:
Q: How to get field dependency like feature in visualforce page using javascript I have a VF page which needs to have only html controls.
I have an object
FieldType__c - Name field will have 3 values (Type1, Type2, Type3).
My VF page has to show the records of FieldType__c. Against each record of FieldType__c, there should be a dropdownlist that needs to show a particular set of values.
I am new to salesforce and want to know the best way to get this functionality. Right now I am saving the possible dropdownlist values in a custom object,
Valueset__c- Name field saves the values to be shown in the dropdownlist and a lookup field to fieldType__c object.
I also use a wrapper class that would hold the FieldType__c and the related records in Valueset__c
<apex:page showHeader="false" sidebar="false"  standardController="Filedtypes__c" applyHTmlTag="false" extensions="FieldtypesController" >
<apex:includeScript value="{!URLFOR($Resource.Jqueryui, '/jquery-ui-1.12.1/external/jquery/jquery.js')}"  />
<apex:includeScript value="{!URLFOR($Resource.Jqueryui, '/jquery-ui-1.12.1/jquery-ui.js')}"  />
<apex:form >
    <apex:pageBlock mode="edit" >

    </apex:pageBlock>
</apex:form>

Apex code
global with sharing class FieldtypesController {
public FieldtypesController(ApexPages.StandardController controller)
{ }

class Wrapper
{
    Filedtypes__c fType;
    List<valueset__c> statusValues;
}

@RemoteAction
global static string GetAllFieldTypes()
{
    List<Filedtypes__c> lst =  [SELECT Name FROM Filedtypes__c];
    List<Wrapper> lstwrp = new List<Wrapper>();
    for (Filedtypes__c i : lst) {
        Wrapper wrp = new Wrapper();
        wrp.fType = i;
        wrp.statusValues = [SELECT Name FROM valueset__c where FieldType__c = :i.id];
        lstwrp.add(wrp);
    }
    return Json.serializepretty(lstwrp);
}}

My page looks like the attached image.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel 5.2 foreign key errors I have created two migrations with the Jeffrey Way generators for Laravel 5. Namely: php artisan make:migrate:schema create_roles_table --schema='name:string, description:text' and php artisan make:migrate:pivot user role.
Now, my MySQL database is defaulted to InnoDB, which I've read should be. I also moved the foreign key setup to Schema::table() instead of Schema::create('role_user'). There shouldn't be anything wrong with my migrations, yet they error out with: General error: 1215 Cannot add foreign key constraint (SQL: alter table role_user add constraint role_user_user_id_foreign foreign key (user_id) references user (id) on delete cascade).
Schema::create('role_user', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->integer('role_id')->unsigned()->index();
            $table->integer('user_id')->unsigned()->index();
            $table->primary(['role_id', 'user_id']);
        });

        Schema::table('role_user', function(Blueprint $table){
            $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('role')->onDelete('cascade');
        });

I have called $table->engine = 'InnoDB'; in every migration. Also have I set all id columns to unsigned, even though they were like that already. I am clueless, who helps me out..

A: Check to see if you have already migrated the tables users and roles. Otherwise you will not be able to create a foreign key. Check your migration order as well. If you are migrating this one before the users and roles it will fail.

A: Well, apparently this was a huge typo. user instead of users, for example. I had hoped Laravel would get that right, but unfortunately Laravel and I as well didn't.

A: This might be related to your SQL engine, check your engine (mariadb, mysql, ...)

And then read the documentation from your engine regarding foreign keys.

Quick solution
Remove the onDelete('cascade') and run the migration.
You can add it manually from phpMyAdmin later on


text:
Q: Reviewing questions in Close queue with no effort by asker I've been reviewing on and off for a year or 2 and the use of the "unclear what you're asking" flag has been bugging me for a while now. It just seems like too many sub-reasons lumped together.
As you know there are quite a few questions like:

"I want this and that (...) and I want it to look exactly like that
  (...) some code excerpt from a homework assignment (...) gimmeez the code now plz hurry"

According to the accepted answer here I should just downvote them and move on, which is fine.
When I review questions like these in the Close queue however, should I close them? I usually do, and the most appropriate reason I think according to the FAQ = "unclear what you're asking" flag - but that's not true. Most of the time it is blatantly obvious what they are asking, they just didn't put any effort in to asking the question.
Is this the correct reason to use?
Or would it be a good idea to specifically have a reason to address this situation? There certainly are enough questions to tag with it. Maybe something like "You have not provided enough evidence that you have attempted a solution" or "Please provide steps on what you have attempted so far". I believe this new reason "try harder" would be less ambiguous than "its unclear".
TLDR
What close reason to use for Gimme codez?

A: Effectively this boils down to Should I use a close reason which doesn't apply but still closes the question because I think it is bad?
The answer is an obvious no. Close reasons must be used for the reason in its description only. Homework questions are on-topic if they are within the scope of the site. Not having done enough research is a valid down-vote reason, not a close vote reason. (So the answer to your question What close reason to use for Gimme codez? is none).
Often there is much more wrong with the question, so that makes it hard sometimes to choose between close reasons. Sometimes I use that reason because it is not exactly clear how the question should be applied (the question is clear on itself, but misses essential details to give a concise answer). I think it is okay to use that close reason then.


text:
Q: What is this solution of matrices called? I have the solution to a problem here.
$$
\begin{bmatrix}
    5 & 2 & 7 \\
    1 & 1 & 3 \\
    9 & 0 & 2 \\
\end{bmatrix}
\cdot
\begin{bmatrix}
    0 & 1 & 5 \\
    9 & 1 & 9 \\
    2 & 2 & 6 \\
\end{bmatrix}
$$
That gives a result of
\begin{bmatrix}
    27 & 3 & 74 \\
\end{bmatrix}
What exactly is happening here? Please help! Why isn't the solution a $3 \times 3$ matrix?

A: In Matlab, the dot function treats A and B as collections of column vectors.
The first column of A is $\vec{A_1}=(5,1,9)$, the first column of B is $\vec{B_1}=(0,9,2)$, hence the dot product $\vec{A_1}\cdot \vec{B_1}=27$ and so on, giving the total result $A\cdot B =(27, 3, 74)$ which is NOT the matrix product
You are probably looking for the operation A*B which gives the matrix product of A and B.

A: I don't know what kind of multiplication is this but when you multiply normally you should get a 3 cross 3 matrix
$$A=\begin{bmatrix}
    5 & 2 & 7 \\
    1 & 1 & 3 \\
    9 & 0 & 2 \\
    \end{bmatrix}$$
$$B=\begin{bmatrix}
    0 & 1 & 5 \\
    9 & 1 & 9 \\
    2 & 2 & 6 \\
    \end{bmatrix}$$
They are multiplying the first column of the matrix A with the first column of the matrix B element by element and adding them
Similarly the second column of matrix A with the second column of  matrix B
$$5\cdot0+1\cdot9+9\cdot2=27$$
$$2\cdot1+1\cdot1+0\cdot2=3$$
$$7\cdot5+3\cdot9+2\cdot6=74$$
$$\begin{bmatrix}
    27 & 3 & 74 \\
\end{bmatrix}$$
When you multiply matrix A with matrix B you should get
$$A*B=\begin{bmatrix}
    32 & 21 & 85 \\
    15 & 8 & 32 \\
    4 & 13 & 57 \\
    \end{bmatrix}$$


text:
Q: Redux - Specify which reducer from action.type when using combineReducer So I have a reducer:
const buttonReducer = (state = { buttons: [] }, action) => {
    switch(action.type)
    {
        case "add":
        {
            state = { ...state, buttons: [...state.buttons, action.payload] }
            break;
        }

        case "minus":
        {
            state = { buttons : state.buttons.filter( item => item !== action.payload ) }
            break;
        }
        default:
            break;
    }
    return state;
};

Now say I have another reducer (we'll call it componentReducer) that looks similar to this, just with the code in the cases changed. Now how do I specify which reducer it should go to after I've done the combineReducers?
const reducers = combineReducers({
    component: componentReducer,
    button: buttonReducer
});

Will store.component.dispatch(...) work? Or should I just simply rename the cases?
Connection:
const Search = connect(
    (store) =>
    {
        return { number: store.component.number};
    }) (SearchComponent);

A: If you want to use the same dispatch action name for those two reducers, you could use a third variable to the dispatch like dispatch({action: 'add', reducer: 'button', payload: {..your data goes here..}}). Then you would also need to add a conditional to your reducer like this:
const buttonReducer = (state = { buttons: [] }, action) => {
  if(action.reducer == 'button'){
    switch(action.type){
      ... your code goes here ...
    }
  }

Although you could do the above, I recommend you stay away from that solution and stick to naming your dispatch actions according to what they do exactly, like this: ADD_BUTTON and ADD_COMPONENT instead of just add.


text:
Q: Hosting SSL tunneled OpenVPN and HTTPS on the same server at the same 443 port Is there a way to host a SSL-tunneled (using stunnel) OpenVPN server and a regular Apache HTTPS server on the same server using HAProxy? It seems that by using stunnel, the format of the packets should all the way be the same. Is there any ways to make a difference between the two kinds of packets (which is not detectable by DPI) for the HAProxy to sort them out? I tried to use different domain names for the HTTPS server and the OpenVPN Server (though they point to the same IP address) but seems it doesn't work because OpenVPN does not use SNI.
Thanks a lot!


text:
Q: Django include template tag multiple template choices I have a requirement where in I have to include a template inside a template tag. But the template I want to include is not fixed. I have list of templates and whichever is found first need to be included.
The include template tag however takes only a single template name.
Is there a way to modify this behavior or any other way to achieve this.
I was using custom template tag for the same, but I am getting warning since updating to django 1.9 that
RemovedInDjango110Warning: render() must be called with a dict, not a RequestContext.
return t.render(context)

This is my custom template tag
@register.simple_tag(takes_context=True)
def custom_include(context, *template_choices):
    template_choices = (context['optionalTemplate'],) + template_choices
    t = template.loader.select_template(template_choices)
    return t.render(context)

I tried getting dict from context, and it seemed to work (atleast I thought that). But some of the context data went missing. For example my google analytics hits went to zero and that sort of stuff.
request = context['request']
mydict = context.dicts[0]
return t.render(mydict, request)

Can anyone suggest how to achieve this.

A: You need to flatten the context into a single dict. This will merge the data from all the internal dicts:
mydict = context.flatten()
return t.render(mydict, context.request)

Also check the docs.


text:
Q: Access Denied on Red Hat (Amazon EC2) I have set up both /home/ec2-user/.ssh/authorized_keys and /root/.ssh/authorized_keys to contain the public key of the private key I intend to use. This has already worked with an Ubuntu instance, but with the ubuntu user.
The issue is, whether I SSH to this instance's public DNS address and use root or ec2-user as the user in PuTTy, I get
Access denied
ec2-user@ec2-54-213-118-179.us-west-2.compute.amazonaws.com's password:

And a prompt for my password.
This all worked with my Ubuntu instance, but doesn't seem to work with my Red Hat instance.
How do I get Red Hat to properly accept my private key and not prompt me for a password?

A: You can try adding your private key to your running Pageant which is basically the ssh agent that does the handshake for Putty ssh sessions.
There's an example on how to use Pageant in the WinSCP page:
http://winscp.net/eng/docs/ui_pageant

A: I believe it's related to this bug:
https://forums.aws.amazon.com/thread.jspa?messageID=475492#
If you are using EBS can you try mounting the EBS volume on another instance and examine the problem?

A: Does the authorized_keys file have 600 permissions?
chmod 600 /home/ec2-user/.ssh/authorized_keys
Does the .ssh directory have 700 permissions?
chmod 700 /home/ec2-user/.ssh/
What does the file /var/log/secure say?  That file will usually explain why a SSH login failed.


text:
Q: Creating a comma separated vector I have a numeric vector, one, which I'm trying to turn into a character vector where
each element is separated by commas.
> one = c(1:5)
> paste(as.character(one), collapse=", ")
[1] "1, 2, 3, 4, 5"
> paste(as.character(one), sep="' '", collapse=", ")
[1] "1, 2, 3, 4, 5"

However, I want the output to look like:
"1", "2", "3", "4", "5"

Am I missing some parameter from the paste function?
Help!?

A: You say you want a character vector with that output, but others who find this question may be looking for one of these functions instead:
First, a way to get output ready for input to R; that would be dput:
> dput(as.character(one))
c("1", "2", "3", "4", "5")

Second, a way to output a csv file, which would be write.csv or write.table.  These functions take a parameter file, not used here, to directly output to a file.
> write.table(matrix(as.character(one),nrow=1), sep=",",
              row.names=FALSE, col.names=FALSE)
"1","2","3","4","5"

> write.csv(matrix(as.character(one),nrow=1),row.names=FALSE)
"V1","V2","V3","V4","V5"
"1","2","3","4","5"

A: In addition to shQuote, see the functions sQuote and dQuote to wrap text in single and double quotes respectively. You'll also want to set options(useFancyQuotes=FALSE) to get plain (unidirectional) ASCII quotes.

A: Something similar with toString
toString(paste0("'",1:10,"'") )

A: Just to add on to Noah's answer if you want to use the paste function:
paste(shQuote(one, type="sh"), collapse=", ")

Should give you:
[1] '1','2','3','4','5'

A: Assuming you want your output in a character string (as opposed to a vector of characters) you could try:
paste("'",as.character(one),"'",collapse=", ",sep="")

That gives you single quotes around the numbers rather than double quotes, but it's basically what you seem to want.
And you can always escape to get double quotes:
rs <- paste("\"",as.character(one),"\"",collapse=", ",sep="")
cat(rs)

that should print out what you want with the double quotes.

A: shQuote is probably the best way to do this. Specifically, this gets you the output you want:
cat(paste(shQuote(one, type="cmd"), collapse=", "))

If single quotes are fine, you can use:
paste(shQuote(one), collapse=", ")

type="cmd" actually provides escaped quotes, which is what's actually useful for most contexts, but if you really want to display it somewhere with unescaped quotes, cat provides that.


text:
Q: Accessibility question: do select dropdown elements need to be tab-able to go up/down the menu? I've been trying to find an answer to this, but can't quite get a clear one. I'm using a MUI Select component in my app, and noticed that it the menu items are able to be navigated with up/down keys and selected with the enter key, but not able to go up/down with the tab key. Is this a best practice for accessibility, or is it not required? I also looked at this guideline, which seems like tabbing isn't required. Just want need some validation on this. Thank you!

A: If you mean the different options of a dropdown menu, no, they shouldn't be reachable with tab.
This is probably more a common convention  or a recommandation than an absolute obligation, as far as I know.
It comes from native UI control/widget/component conventions on most operating systems that have been in use long time before the web.
The tab key is normally used to go from a control to the next.
But when you go through the different options of a dropdown menu, you stay on the same control.
So dropdown options don't have to, and even really shouldn't be reachable with the tab key.
The same answer applies on the different tabs of a tab control, or the items in a list of selectable items. Normally when navigating with tab, you should only reach the currently selected / active element. Another press on tab key moves to the next interactive control.

A: As mentioned before, the goal of TAB is typically to move from a specific input control.to another, not within it.  Thus, the use of arrow keys and enter is fine.  However as a screen reader user myself, I run across custom "selection" boxes that fail to work properly due to many reasons.   even if keyboard navigation works as expected outside of a screen reader context.  It isn't clear  to me if you tried this under a screen reader.


text:
Q: Wordpress: Load custom CSS for specific plugin admin Page I am learning about Wordpress, and i want to load custom CSS for a specific admin page of my plugin. I read at Wordpress Plugin API and do something like this:
//I ADD MY OPTION PAGES
add_action( 'admin_menu', 'my_plugin_menu' );
function my_plugin_menu() {
    add_menu_page( 'My option page', 'My plugin', 'manage_options', 'my-fist-slug', 'my_first_func', 'dashicons-star-empty');
    add_submenu_page('my-fist-slug', 'General Setting', 'General', 'manage_options', 'my-fist-slug', 'my_first_func');
    add_submenu_page('my-fist-slug'', 'Some else options', 'Some options', 'manage_options', 'my-second-slug', 'my_second_func');
}

I just want to load my CSS only for my option pages, then i do this:
add_action('admin_enqueue_scripts', 'ln_reg_css_and_js');
function ln_reg_css_and_js($hook)
{
    if($hook != 'my-first-slug'){
        return;
    }

    wp_enqueue_style('boot_css', plugins_url('inc/bootstrap.css',__FILE__ ));
    wp_enqueue_script('boot_js', plugins_url('inc/bootstrap.js',__FILE__ ));
    wp_enqueue_script('ln_script', plugins_url('inc/main_script.js', __FILE__), ['jquery'], false, true);
}

This has same codes like the WP codex. But, i don't know how to define $hook, and the result is my custom css was not loaded. Anyone can teaches me how to do this?

A: add_action('admin_enqueue_scripts', 'ln_reg_css_and_js');

    function ln_reg_css_and_js($hook)
    {

    $current_screen = get_current_screen();

    if ( strpos($current_screen->base, 'my-fist-slug') === false) {
        return;
    } else {

        wp_enqueue_style('boot_css', plugins_url('inc/bootstrap.css',__FILE__ ));
        wp_enqueue_script('boot_js', plugins_url('inc/bootstrap.js',__FILE__ ));
        wp_enqueue_script('ln_script', plugins_url('inc/main_script.js', __FILE__), ['jquery'], false, true);
        }
    }

A: You can also include the CSS on specific plugin page as well :)
//Enqueue Admin CSS on Job Board Settings page only
if ( isset( $_GET['page'] ) && $_GET['page'] == 'job-board-settings' ) {
    // Enqueue Core Admin Styles
    wp_enqueue_style( simple_job_board, plugin_dir_url( __FILE__ ) . 'css/simple-job-board-admin.css');
    }

A: function load_custom_wp_admin_style($hook) {
        // $hook is string value given add_menu_page function.
        if($hook != 'toplevel_page_mypluginname') {
                return;
        }
        wp_enqueue_style( 'custom_wp_admin_css', plugins_url('admin-style.css', __FILE__) );
}
add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );

For more see: Codex examples


text:
Q: Optimization Algorithm for efficient stochastic evaluation of blocks Are there stochastic optimization algorithms that benefit from evaluating the target function at multiple, predefined values at the same time?
Say I have a one-dimensional, smooth, and bounded function $f(x)$ which I can only observe with noise. The function $f$ is some expectation that I evaluate using Monte-Carlo simulations. One evaluation of $f(x)$ takes a lot of time. But evaluating $f$ at multiple values $\mathbf x$, $f(\mathbf x) = [f(x_1), f(x_2), \dots, f(x_N)]$, takes only slightly more time than evaluating at one point.
I'd like to know how to facilitate this property for optimization to decrease the time it takes to optimize the function.
Analytical or AD derivatives of $f$ are not available.


text:
Q: Passing logged in user credentials to Powershell cmdlet I have a Windows Service running (service is running as "NT AUTHORITY\SYSTEM") on Windows 2012 Server. This service needs to get a list of VMs from a remote machine. It executes cmdlet equivalent of "get-vm -ComputerSystem RemoteServer1". Currently logged in user is 'Administrator' who has access to call get-vm on the remote machine. However, "NT AUTHORITY\SYSTEM" does not have permission to call get-vm on the remote machine. Below is the code.
PowerShell psStopVM = PowerShell.Create();
psStopVM.AddCommand("Stop-VM");
psStopVM.AddParameter("Name", vmName);
psStopVM.AddParameter("ComputerName", VMHost);
psStopVM.AddParameter("Force", true);

psStopVM.Invoke(); //exception occurs here

When I run this code, I get the following error.
Microsoft.HyperV.PowerShell.VirtualizationOperationFailedException: You do not have permission to perform the operation. Contact your administrator if you believe you should have permission to perform this operation. ---> System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
How can I pass the credentials of logged in user (Administrator) in the C# code such that I can successfully call get-vm cmdlet from C# Code?

A: You can either use Invoke-Command and create an ad hoc session with admin creds to invoke you command with sufficient privileges or, if you need to run more than one command, you can create a remote runspace with admin credentials and execute your commands in that runspace. This will require WinRM service configured and running.
You other option, and I would go that route, is to run the service under identity of the admin user or a dedicated account with sufficient privileges instead of NT AUTHORITY\SYSTEM. This way you do not store your admin creds insecurely with your code, not naming other consequences of hard-coding creds.


text:
Q: Setting up a Picker in swift i am trying to create a picker so that the user can select there title (mr/mrs etc) however i keep getting 2 errors
1: Type 'ViewController' does not conform to protocol 'UIPickerViewDataSource'
2: Definition conflicts with previous value
the first is in the class viewcontoller line (line 2). the second error is in the titlepicker function at the end of the code
i have search online and could find anyway to fix these
import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource //first error here
{
@IBOutlet weak var titlepicker: UIPickerView!

var titlepickerdata : [String] = [String]()
override func viewDidLoad()
{
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    //connect data
    self.titlepicker.delegate = self
    self.titlepicker.dataSource = self
    //input data into the array
    titlepickerdata = ["Mr","Ms","Mrs","Miss","Other"]
    // The number of columns of data
    func numberOfComponentsInPickerView(titlepicker: UIPickerView) -> Int
    {
        return 1
    }

    // The number of rows of data
    func pickerView(titlepicker: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        return titlepickerdata.count
    }

    // The data to return for the row and column that's being passed in
    func pickerView(titlepicker: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? // second error returned here
    {
        return titlepickerdata[row]
    }
}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

A: You have put the definitions of numberOfComponentsInPickerView, pickerView(_:numberOfRowsInComponent:), and titlepicker(_:titleForRow:forComponent:) inside the definition of didReceiveMemoryWarning. Swift supports nested functions, so this is legal syntax. However, because they are defined inside didReceiveMemoryWarning, those functions are not instance methods so they don't meet the requirements of the UIPickerViewDataSource protocol.
It is much easier to see this sort of problem if you indent your code properly. Then those three functions are indented an extra level, showing that they are nested inside didReceiveMemoryWarning. You can fix the indentation of the entire file using the menu option Edit > Select All (default shortcut: ⌘A), and then menu option Editor > Structure > Re-Indent (default shortcut: ⌃I).
Also, after you move the definitions outside of didReceiveMemoryWarning, you will need to rename titlepicker(_:titleForRow:forComponent:) to pickerView(_:titleForRow:forComponent:) if you want it to be used as part of the UIPickerViewDelegate protocol.
UPDATE
OK, now you have taken the three functions out of didReceiveMemoryWarning and put them in viewDidLoad, which is wrong for exactly the same reasons. Those functions need to be on the same level as viewDidLoad and didReceiveMemoryWarning.

A: The 2nd error is because, last three functions, e.g. numberOfComponentsInPickerView, are miss-placed in the didReceiveMemoryWarning function.
The 1st error is therefore there, since XCode cannot find the "required" functions of the UIPickerViewDataSource


text:
Q: Predator-prey simulation using Python. Problems with Python reading equation wrong? I'm doing a predator prey simulation that prints the number of prey and predators in a certain period.
This is my first time posting so if there are any problems please let me know.
The information I am implementing for testing is:
a= .1
b= .01
c= .01
d= .00002
prey_population = 1000
predator_population = 20
periods = 10

a = float(input("Enter the rate at which prey birth exceeds natural death: "))
b = float(input("Enter the rate of predation: "))
c = float(input("Enter the rate at which predator deaths exceed births without food: "))
d = float(input("Predator increase with the presence of food: "))

prey_population = int(input("Enter prey population: "))
predator_population = int(input("Enter predator population: "))

periods = int(input("Enter the number of periods: "))

for i in range(1, periods + 1):
    prey_population = int(prey_population * (1 + a - b * predator_population))
    predator_population = int(predator_population * (1 - c + d * prey_population))

    print("After period", i, "there are", predator_population, "predators")
    print("After period", i, "there are", prey_population, "prey")

My information is accurate for prey until the 6th period, my predator output is accurate only to the 3rd period.
My output is:
After period 1 there are 20 predators
After period 1 there are 900 prey

After period 2 there are 20 predators
After period 2 there are 810 prey

After period 3 there are 20 predators
After period 3 there are 729 prey

After period 4 there are 20 predators
After period 4 there are 656 prey

After period 5 there are 20 predators
After period 5 there are 590 prey

After period 6 there are 20 predators
After period 6 there are 531 prey

After period 7 there are 19 predators
After period 7 there are 477 prey

After period 8 there are 18 predators
After period 8 there are 434 prey

After period 9 there are 17 predators
After period 9 there are 399 prey

After period 10 there are 16 predators
After period 10 there are 371 prey

The numbers it should show are:
After period 1 there are 20 predators
After period 1 there are 900 prey

After period 2 there are 20 predators
After period 2 there are 808 prey

After period 3 there are 20 predators
After period 3 there are 724 prey

After period 4 there are 21 predators
After period 4 there are 648 prey

After period 5 there are 21 predators
After period 5 there are 580 prey

After period 6 there are 21 predators
After period 6 there are 518 prey

After period 7 there are 21 predators
After period 7 there are 463 prey

After period 8 there are 21 predators
After period 8 there are 413 prey

After period 9 there are 21 predators
After period 9 there are 369 prey

After period 10 there are 21 predators
After period 10 there are 330 prey

A: Each turn you update the value of prey_population before using the new value to calculate predator_population. This is throwing off the results.

A: I found the problem, yes it was rounding. The int in the equation was rounding the answer. I changed it to a float and rounded in the print statement. I very much appreciate the help from everyone.

A: I don't think this qualifies as an answer, but it's too long to be put in a comment, so "practicality beats purity".
What you're asking your code to do, for every turn is:
The new number of preys is equal to:

*

*the old number of preys

*

*plus this turn's new births (birth rate * current preys) (1)

*minus this turn's killed preys [(predation rate * current predators) * current preys] (1)

*round this all down.

The new number of predators is equal to:

*

*the old number of predators

*

*minus the fixed rate of death (death rate * current predators) (1)

*plus the "food births" [("food birth" rate * new number of preys) * current predators] (1)

*round this all down.

Is this what it's supposed to do?
(1)  at this point the new number isn't rounded down yet


text:
Q: Css and JS image zoom on scroll top I found this really cool app and it has a few features that I can't figure out.
One in particular is the image zoom on scroll up so that you don't see "behind" the app. I included a video demo here
I don't know if they have the image set to the background, or if the image is in another container. I am talking about the top picture of Batman.
I'm new to js and haven't been able to see any solutions that would point me in the right direction!
Thanks everyone!

A: They are probably building into how far you've scrolled down the page. For example, you can get the distance the user has scrolled with:
var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;

If you bound this into the scroll event, like so:
window.addEventListener("scroll", function(){
    var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
    console.log(scrollTop);
}, false)

Then you can alter the size of some image based on how far you've scrolled down. Here's an example of how this could be used to change the size of some image:

window.addEventListener("scroll", function(){
 var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
 image = document.getElementById("theImage");
    var dimension = 100 + 400 - Math.min(400,scrollTop) + "%";
    image.style.backgroundSize = dimension+" "+dimension;
}, false)
#theImage {
  width: 100%;
  text-align: center;
  background-image: url('http://lorempixel.com/1000/1000/sports/');
  background-position: center;
  height: 800px;
}

Some text

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.


text:
Q: Как проверить переменные, которые возвращает контроллер? def index
  @user
end

Как проверить значение переменной user, когда в тестах перейдем в метод контроллера index?

A: Обычно переменные контроллера проверяются с помощью метода рспека - assigns, так, например, для вашего случая:
get :index
expect(assigns(:user)).to_not be_nil

На сайте RelishApp можно почитать подробнее.


text:
Q: How would I specify this dually left & right arrow (categorical, two opposing functors notation)?
This is used in Categories for the Working Mathematician to introduce two opposing functors U,V between the category of sets and the category of K-vector spaces, where K is a field.
Can this be done in a LaTeX code that renders on MSE?


text:
Q: Numpy - is there a way to specify broadcasting dimension? Broadcasting is only possible (as far as I know) with matrices matching shape from the end (shape [4,3,2] is broadcastable with shapes [2], [3,2], [4,3,2]). But why?
Consider the following example:
np.zeros([4,3,2])

[[[0 0]
  [0 0]
  [0 0]]

 [[0 0]
  [0 0]
  [0 0]]

 [[0 0]
  [0 0]
  [0 0]]

 [[0 0]
  [0 0]
  [0 0]]]

Why broadcasting with [1,2,3], or [1,2,3,4] isn't possible?
Adding with [1,2,3] (shape: [3], target shape: [4,3,2]) expected result:
[[[1 1]
  [2 2]
  [3 3]]

 [[1 1]
  [2 2]
  [3 3]]

 [[1 1]
  [2 2]
  [3 3]]

 [[1 1]
  [2 2]
  [3 3]]]

Adding with [1,2,3,4] (shape: [4], target shape: [4,3,2]) expected result:
[[[1 1]
  [1 1]
  [1 1]]

 [[2 2]
  [2 2]
  [2 2]]

 [[3 3]
  [3 3]
  [3 3]]

 [[4 4]
  [4 4]
  [4 4]]]

Or, if there would be concerns about multi dimensional broadcasting this way, adding with:
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]

(shape: [4,3], target shape: [4,3,2]) expected result:
[[[ 1  1]
  [ 2  2]
  [ 3  3]]

 [[ 4  4]
  [ 5  5]
  [ 6  6]]

 [[ 7  7]
  [ 8  8]
  [ 9  9]]

 [[10 10]
  [11 11]
  [12 12]]]

So basically what I'm saying is that I can't see a reason why it couldn't find the matching shape, and do the operations respectively. If there's multiple dimensions matching in the target matrix, just select the last one automatically, or have the option to specify which dimension we want to perform the operation.
Any ideas/suggestions?

A: The broadcasting rules are simple and unambiguous.

*

*add leading size 1 dimension as needed to match total number of dimensions

*adjust all size 1 dimensions as needed to match

With (4,3,2)
(2,) => (1,1,2) => (4,3,2)
(3,2) => (1,3,2) => (4,3,2)

(3,) => (1,1,3) => (4,3,3) ERROR
(4,) => (1,1,4)
(4,3) => (1,4,3)

With reshape or np.newaxis we can add explicit new dimensions in the right place:
(3,1) => (1,3,1) => (4,3,2)
(4,1,1) => (4,3,2)
(4,3,1) => (4,3,2)

Why doesn't it do the last stuff automatically?  Potential ambiguity.  Without those rules, especially the 'add only leading', it would be possible to add the extra dimension in several different places.
e.g.
(2,3,3) + (3,) => is that (1,1,3) or (1,3,1)?
(2,3,3,3) + (3,3)


text:
Q: how to effeciantly format json data I am trying to format json data in the most efficient way. I need to format 2 different keys in a object. both are strings
I made a fiddle with the json
fiddle
var json = [
{
    "Id": 1,
    "ReportId": 1,
    "ReportName": "HBO: {MSA}"
    "QueueDate": "2015-08-25T17:16:54.233",
    "Parameters": "<xml><CBSA>Abilene, TX</CBSA><CBSASK>3</CBSASK><CBSAID>1203</CBSAID><CBSACode>10180</CBSACode><MonthNumber>6</MonthNumber><Month>June</Month><Year>2015</Year><FromDate>06/01/2014</FromDate><ToDate>06/01/2015</ToDate></xml>"
},
{
    "Id": 2,
    "ReportId": 2,
    "ReportName": "HBO:{Marvin}"
    "QueueDate": "2015-08-25T17:20:50.463",
    "Parameters": "<xml><CBSA>Abilene, TX</CBSA><CBSASK>3</CBSASK><CBSAID>1203</CBSAID><CBSACode>10180</CBSACode><MonthNumber>6</MonthNumber><Month>June</Month><Year>2015</Year><FromDate>06/01/2014</FromDate><ToDate>06/01/2015</ToDate></xml>"
},
{
    "Id": 3,
    "ReportId": 2,
    "ReportName": "HBO:{Marvin}"
    "QueueDate": "2015-08-25T17:23:58.377",
    "Parameters": "<xml><CBSA>Abilene, TX</CBSA><CBSASK>3</CBSASK><CBSAID>1203</CBSAID><CBSACode>10180</CBSACode><MonthNumber>6</MonthNumber><Month>June</Month><Year>2015</Year><FromDate>06/01/2014</FromDate><ToDate>06/01/2015</ToDate></xml>"
}

]
I need to end up with:
ReportName: 'MSA',
Parameters: 'Abilene, Tx'

A: You can use $.parseXML() to convert the xml string  to an xml document object, then wrap that in $() to use jQuery traverse methods on it
$.each(json, function (_, item) {
    var $xml = $($.parseXML(item.Parameters));
    var cbsa = $xml.find('CBSA').text();
    $('body').append($('<p>').text(cbsa));
});

Reference: parseXML() docs
DEMO


text:
Q: Automatic restart of a crashing Linux daemon I have a Linux server application that I managed to "deploy" as a daemon that can be started automatically when the machine starts, independently of user sessions..
I wonder if it is possible to tell the system to automatically restart the application when it crashes, like the service manager in Windows..
Thank you in advance.

A: What you need is a process supervisor, a utility that manages your daemon and decides when to start/stop it among other things.
There are several of these out there such as supervisord, upstart, runit etc. You will have to research them and find one that best suits your needs.
Hope that helps.

A: Give it a look to monit, it monitors any service/daemon. You have to configure Monit in order to know what criteria to use to start/stop or email you in case something wrong/strange is going on.


text:
Q: Given λ > 0 compute the expectation of the following expression Given $\lambda > 0$, compute $\mathbb{E}[e^{-\lambda B(t)}\int_{0}^{t}e^{\lambda B(s)}dB(s)]$
My approach so far,
Let $$X(t) = e^{\lambda B(t)}; X(0)=1,$$
$$dX(t) = X(t)dB(t) + \frac{1}{2}X(t)dt$$
$$X(t) = 1 + \int_{0}^{t}X(s)dB(s) + \frac{1}{2}\int_{0}^{t}X(s)ds$$
$$\int_{0}^{t}X(s)dB(s) = X(t) - 1 - \frac{1}{2}\int_{0}^{t}X(s)ds$$
So, $$\mathbb{E}\Big[e^{-\lambda B(t)}\int_{0}^{t}e^{\lambda B(s)}dB(s)\Big] = \mathbb{E}\Big[e^{-\lambda B(t)}\Big[e^{\lambda B(t)}-1-\frac{1}{2}\int_{0}^{t}e^{\lambda B(s)}ds\Big]\Big] = \mathbb{E}\Big[1 - e^{-\lambda B(t)} - e^{-\lambda B(t)}\Big(\frac{1}{2}\int_{0}^{t}e^{\lambda B(s)}ds\Big)\Big].$$
How do I go from here? More specifically, how do I calculate $\mathbb{E}\Big[\frac{1}{2}\int_{0}^{t}e^{\lambda B(s)}ds\Big]$?
Edited after seeing the answers:
$$\mathbb{E}\Big[1 - e^{-\lambda B(t)} - \frac{1}{2}\int_{0}^{t}e^{\lambda B(s)}ds\Big] = 1 - e^{\lambda^2t/2} - (e^{\lambda^2t/2}-1)/\lambda^2$$
Here, I have used the fact that $M_{B(t)}(\lambda)= M_{B(t)}(-\lambda)$, where, $M_{B(t)}(\lambda)$ is the Moment Generating function of B(t) $\sim N(0,t)$.

A: Hint
Apply Fubini yields $$\mathbb E\left[\int_0^t e^{\lambda B_s}\,\mathrm d s\right]=\int_0^t\mathbb E[e^{\lambda B_s}]\,\mathrm d s$$

A: $E\int_0^{t}e^{\lambda B(s)}ds=\int_0^{t}Ee^{\lambda B(s)}ds=\int_0^{t}e^{\lambda^{2} s/2} ds=\frac 2 {\lambda^{2}}(e^{\lambda^{2} t/2}-1) $.

A: The last equality is not true, it should be
$$ \mathbb E[1-e^{-\lambda B_t}- \frac{e^{-\lambda B_t}}{2}\int_0^t e^{\lambda B_s}ds] = 1 - e^{\frac{\lambda^2 t}2} - \frac{1}{2}\int_0^t e^{\frac{\lambda^2(t-s)}{2}}ds = 1-e^{\lambda^2t/2} -  \frac{1}{\lambda^2}(e^{\lambda^2 t/2}-1)  $$


text:
Q: New Install - SharePoint Foundation 2013 - Missing Templates? Know this is a basic question, but I'm stumped.
Just installed SharePoint Foundation 2013 ... when I go to "Site Content", new subsite, I only see the following templates available:

*

*Collaboration tab: Team Site and Blog

*Enterprise: Basic Search Center

Shouldn't I see other default templates, such as "wiki" and "project sites"?

A: That's all which comes with SharePoint Foundation, their is nothing missing.
If you need other templates, you have to go either standard or enterprise edition or use some coding.
Available Templates in SPF

*

*Collaboration - Team Site

*Collaboration - Blog

*Enterprise - Basic Search Center

Also read the below post for discontinued features in 2013.
http://technet.microsoft.com/en-us/library/ff607742(v=office.15).aspx#section1
http://office.microsoft.com/en-us/sharepoint-help/discontinued-features-and-modified-functionality-in-microsoft-sharepoint-2013-HA102892827.aspx

A: SharePoint Foundation 2013 comes only with those templates you already discovered.
To create a Wiki simply create a Team Site and add a Wiki Page Library app to it.
For project tracking like stuff there are apps like Issue Tracking and Tasks.
Anything beyond this needs customisation or third-party apps on Foundation.


text:
Q: WPF set startup value in Combobox I have a WPF application where the user can set the serial port setting. At startup i want to set the comboboxes for the serialport settings with the last setting used previously. These settings are stored in the app.config file.
For the Parity, Stopbits and Comport is works fine but for the baudrate and number of databits i'm not able to set the default value at startup. The only difference for the baudrate and the databits is that i add the items for the combobox in the xaml file. For the other settings i add the items dynamically at startup.
For the baudrate and i do :

<ComboBox x:Name="BaudrateCmbbox" FontSize="12" SelectionChanged="BaudrateCmbbox_SelectionChanged">
      <ComboBoxItem>9600</ComboBoxItem>
      <ComboBoxItem>19200</ComboBoxItem>
      <ComboBoxItem>38400</ComboBoxItem>
      <ComboBoxItem>115200</ComboBoxItem>
</ComboBox>

For the databits i do

<ComboBox x:Name="DatabitsCmbbox" FontSize="12" SelectionChanged="DatabitsCmbbox_SelectionChanged">
    <ComboBoxItem>7</ComboBoxItem>
    <ComboBoxItem>8</ComboBoxItem>
</ComboBox>

The comboboxes for Parity, Stopbits and portname are filled via
private  void SetPortParity()
    {
        foreach (string s in Enum.GetNames(typeof(Parity)))
        {
           ParityCmbbox.Items.Add(s);
        }
    }

    private void SetPortName()
    {
        foreach (string s in SerialPort.GetPortNames())
        {
            ComportsCmbbox.Items.Add(s);
        }
    }

    private void Stopbits()
    {
        foreach (string s in Enum.GetNames(typeof(StopBits)))
        {
            StopbitsCmbbox.Items.Add(s);
        }
    }

In the "Window_loaded" methode i do :
 private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        SetPortParity();
        SetPortName();
        Stopbits();

        BaudrateCmbbox.SelectedItem = ConfigurationManager.AppSettings.Get("Baudrate");
        DatabitsCmbbox.SelectedItem = ConfigurationManager.AppSettings.Get("Databits");
        ParityCmbbox.SelectedItem = ConfigurationManager.AppSettings.Get("Parity");
        StopbitsCmbbox.SelectedItem = ConfigurationManager.AppSettings.Get("StopBits");
        ComportsCmbbox.SelectedItem = ConfigurationManager.AppSettings.Get("Comport");

    }

The problem here is that i can't set the baudrate and databits values from the app.config.
The other settings work fine.
How can i solve this issue

A: That's because ConfigurationManager.AppSettings.Get("Baudrate") and ConfigurationManager.AppSettings.Get("Databits") returns a string but the Items\SelectedItem on your Baudrate & Databits comboboxes are ComboBoxItems.
Instead you could set SelectedValuePath="Content" on your Baudrate & Databits comboboxes set SelectedValue instead of SelectedItem:

BaudrateCmbbox.SelectedValue =
ConfigurationManager.AppSettings.Get("Baudrate");
DatabitsCmbbox.SelectedValue =
ConfigurationManager.AppSettings.Get("Databits")

Alternatively though, you could just set these two the same way as the others, from your config file.


text:
Q: Google Map isn't loading when downloading my app from Google play store When I download my app from google play the Google Map is no loaded.
When I download the app with the .apk file directly (transfer it to my phone and downloading) it did load!
I searched all over and it still doesn't work.
This is what I did:

*

*In Android studio, Build->Generate Sign APK I created a new Keystore 'keystore' and a new Key 'app'

*run: keytool -list -v -keystore keystore.jks -alias app.

*In the output from step 2, under 'Certificate fingerprints:' I took the 'SHA1' value and my package name 'com.gilshelef.feedme' (from AndroidManifest.xml file) and generated a new API key in the Google api console. I restricted the key to 'android apps' and added my SHA1 and package name.

*I placed the generated key (step 3) in my Manifest file:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />

*In android studio, Build->generate sign APK I used the same keystore that I created in step 1 and the same key.

*I uploaded the generated apk to Google play.
After I downloaded my app from google play the map is still blank!
NOTES:

*

*I also tried to changed the extension of the keystore from .jks to .keystore since android studio uses the .jks extension.

*I verified that the key from google api console and the one Im using in my AndroidManifest.xml file is the same.

*I verified the package name in google api console and Manifest file.

*I followed this: this tutorial 'Displaying the release certificate fingerprint'. The output looks the same except for the 'Signature algorithm name: SHA1withRSA'. the signature algorithm name in my release keystore is 'SHA256withRSA' maybe this is the problem?

What am I doing wrong??

A: Its because of google_maps_key is different in release mode from the one in debug mode.
when you sign your app the release version is made then you can do following:

*

*Find release SHA-1 fingerprint (here)

*Get another api_key for google maps api from google

*Put the new api_key in src/release/values/google_maps_api.xml (In Project View) or (app/res/values/google_maps_api.xml(release) in Android View)

hope it helps you...


text:
Q: How to initialze an appium android driver on version 4.0.0 with selenium 3.141.0 I can't find any documentation outlining how to initialize an appium android driver.
I had this test somewhat working with appium 3.0.0.2 and selenium 3.11 but then received the following error when trying to find an element by class name:

OpenQA.Selenium.InvalidSelectorException: 'Locator Strategy 'css selector' is not supported for this session

Ideally I don't want to go back to an older version of selenium as I already have a set of working tests using 3.14. This is my test at the moment, and I cant find clear documentation telling me how to implement an appium driver in C#.
  public void androidTest(){
      AndroidDriver<AndroidElement> driver;
      DesiredCapabilities cap = new DesiredCapabilities();
      cap.SetCapability("deviceName", "myName");
      cap.SetCapability("platformName", "Android");
      cap.SetCapability("automationName", "UiAutomator2");
      cap.SetCapability("appPackage", "myPackage");
      cap.SetCapability("appActivity", "myActivity");

      Uri url = new Uri("http://127.0.0.1:4723/wd/hub");

      driver = new AndroidDriver<IWebElement>(url, cap);

      driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

      driver.FindElementByName("android.widget.EditText").SendKeys("testString");
   }

I get the following two error messages
Argument 1:

cannot convert from 'System.Uri' to 'OpenQA.Selenium.Remote.ICommandExecutor'

Argument 2:

cannot convert from 'OpenQA.Selenium.Remote.DesiredCapabilities' to 'OpenQA.Selenium.DriverOptions'    ArenaTests

What arguments do I need to pass into this constructor to get this setup working?

A: I worked this out. If anyone runs into this, the following initialisation works for me.
public void androidTest(){
    AndroidDriver<AndroidElement> driver;
    AppiumOptions options = new AppiumOptions();
    options.PlatformName = "Android";
    options.AddAdditionalCapability("deviceName", "MyDevice");
    options.AddAdditionalCapability("platformVersion", "PlatformV");
    options.AddAdditionalCapability("automationName", "UiAutomator2");
    options.AddAdditionalCapability("appPackage", "MyPackage");
    options.AddAdditionalCapability("appActivity", "MyActivity");

    Uri url = new Uri("http://127.0.0.1:4723/wd/hub");

    driver = new AndroidDriver<AndroidElement>(url, options);
    driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

    // Some example selectors
    driver.FindElementByClassName("android.widget.EditText").SendKeys("test");
    driver.FindElement(MobileBy.AndroidUIAutomator("new UiSelector().className(\"android.widget.EditText\").instance(1)")).SendKeys(Username);
}

A: thanks h brooker you helped me alot
for UWP users:
AppiumOptions options = new AppiumOptions();
            options.PlatformName = "UWP";
            options.AddAdditionalCapability("deviceName", "WindowsPC");
            options.AddAdditionalCapability("app", AppId);
session = new WindowsDriver<WindowsElement>(new
                Uri("http://127.0.0.1:4723"), options);

A: I think the URI is creating an issue ..
Try using URL like the following snippet..
        URL url = new URL("http://127.0.0.1:4723/wd/hub");

        driver = new AppiumDriver<MobileElement>(url,cap);


text:
Q: Как нажать на кнопку Selenium? Здраствуйте, имеется такая кнопка:

Я хочу на нее сделать клик, вот код -

chrome.find_element_by_xpath('//input[@value="Выберите файл..."]').click()

В итоге имею такую ошибку:

selenium.common.exceptions.ElementNotInteractableException: Message:
element not interactable

Как это сделать? Кнопка кликабельна мышью

A: попробуйте нажать по name
chrome.find_element_by_class_name('ваш атрибут name').click()

здесь очень подробно всё прописано https://selenium-python.readthedocs.io/locating-elements.html

A: Проблема была в том, что элемент не успевал прогрузиться, поставил 1 сек задержки, заработало все. Спасибо @cauf

A: если страница не успевает подгружаться пробуй так
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#your selector'))).click()


text:
Q: Mat-pseudo-checkbox icon off-center and smaller than usual While implementing a list of checkboxes, it came to my attention that the mark when the checkbox is checked isn't styled the way it is supposed to be. When I compare it to the documentation, I notice it is a lot smaller and way off-center. I'm starting to wonder if this has something to do with my other css, or if I'm missing something.
HTML

Users ({{participants.length}})

      <mat-icon>search</mat-icon>

        <mat-form-field>
          <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
        </mat-form-field>

      <mat-form-field>
        <mat-label>Columns</mat-label>
        <mat-select [formControl]="columns" multiple>
          <mat-select-trigger>
            {{columns.value ? columns.value[0] : ''}}
             1" class="additional-selection">
              (+{{columns.value.length - 1}} {{columns.value?.length === 2 ? 'other' : 'others'}})

          </mat-select-trigger>
          <mat-option *ngFor="let column of selectedColumns" [value]="column">{{column}}</mat-option>
        </mat-select>
      </mat-form-field>

... rest of page

CSS
::ng-deep .mat-focused .mat-form-field-label {
  /*change color of label*/
  color: #f59225 !important;
}

::ng-deep.mat-form-field-underline {
  /*change color of underline*/
  background-color: #f59225 !important;
}

::ng-deep.mat-form-field-ripple {
  /*change color of underline when focused*/
  background-color: #f59225 !important;
  ;
}

::ng-deep .mat-primary .mat-pseudo-checkbox-checked {
  background: #f59225;
}

.download-btn {
  background-color: #f59225;
  color: #f9f9f9;
}

.additional-selection {
  opacity: 0.75;
  font-size: 0.75em;
}

.wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

}

.form-wrapper {
  width: 100%;
}

.filterbar {
  display: flex;
  align-items: center;
  width: 50%;
}

mat-form-field {
  width: 100%;
}

mat-table {
  margin: 5px;
  width: 100%
}

.mat-row:hover {
  cursor: pointer;
  background-color: gainsboro;
}

.spinner-card {
  display: flex;
  justify-content: center;
  align-items: center;
}

.general-wrapper {
  width: 90%;
  margin: 0 auto;
}

body,
html {
  width: 100%;
}

mat-cell:last-of-type {
  margin-right: 0px;
}

mat-cell {
  word-wrap: break-word;
  word-break: normal;
  margin-right: 8px;
}

.status ::ng-deep .mat-progress-spinner circle,
.mat-spinner circle {
  stroke: #f59225 !important;
}

this is what my checkboxes currently look like:

A: This is just a css issue with the library itself. I've noticed the same thing in my own instance of the library. You can override the mat styles with your own to fix it.
With the following css, I think the end result looks much better.
.mat-option .mat-pseudo-checkbox-checked::after {
  top: 3px;
  width: 11px;
  height: 5px;
  border-left: 3px solid currentColor;
}


text:
Q: Reality, realizing, affinity, etc.: A terminology question In Snapper & Troyer's book Metric Affine Geometry the word "reality" at one point occurs in the phrase (IIRC) "reality problems", meaning questions about whether the imaginary part of a complex number is indeed zero.  And in a paper I had in the American Mathematical Monthly in 2003, I used the word "affinity" in some phrase like "the desired affinity follows", which the context made clear meant something like: "thus we have proved that this mapping is affine, as desired."  No one complained about that, so I take it that I was "licensed" in the sense in which that word applies to poets and dramaturges.
So now some muse or demon rested on my shoulder and inspired me to write "realizing the denominator", meaning multiplying the numerator and denominator by the complex conjugate of the denominator.  I've never seen it or heard it.  Googling indicates that it is far from unprecedented, even though I've never come across it, but of course so are many offenses against good usage.
Since this forum is the priest to whom I confess my sins What normative advice can the sages here assembled offer me?

A: "rationalizing the denominator" still applies. To make explicit that the process is using $k$ as its base field, "$k$-rationalizing the denominator" (or rationalizing "over $k$" / "relative to $k$").  The suggestion is therefore

$\mathbb{R}$-rationalizing the denominator

"Realize" and "decomplexify" have accepted meanings very different from this.  "Realify" and "realification" share the same problem as decomplexification, that they read like synonyms for restriction of scalars from $\mathbb{C}$ to $\mathbb{R}$.

A: "Decomplexizing the denominator" would not be as correct as "realizing the denominator", but it is less ambiguous and it sounds better for me.


text:
Q: Cucumber pass whole example to a step I want to pass a whole example to some test step as an Map object. How can it be achieved?
lets say I have scenario
Scenario Outline: some description text
When user do something
Then the user should see something
Examples: set 1
  | Param Title |
  | value 1     |
Examples: set 2
  | Param Title | Param Title 2 |
  | value 2     | value 3       |

in the step definition of When user do something I want a map that would have map {"Param Title":"value 1"} for first example and {"Param Title":"value 2","Param Title 2":"value 3"} for the second example. Is there any way to do that in cucumber or my only option is to write same scenario multiple times for each example?

A: The cost of writing a step definition is trivial compared to the complexity you are adding by trying to pass your map into a generic step def.
If you implement all your step definitions as single calls to a helper method it really doesn't matter if you have lots of step definitions that do the same thing. When you follow this pattern your step definitions perform one function, they translate a string phrase into a method call.
Let me give you some examples
Given I am logged in
Given I am logged in as an admin
Given Fred is logged in
Given Bill is logged in
Given Sam is logged in as an admin

Now you would probably want to write just one step definition for all of these, but that is actually a mistake and a false optimisation. Its much simpler to do the following (all examples are in ruby)
Given 'I am logged in' do
  @i ||= create_user
  login as: @i
end

Given 'I am logged in as an admin' do
  @i ||= create_admin
  admin_login as: @i
end

Given 'Fred is logged in' do
  @fred ||= create_user(first_name: 'Fred')
  login as: @fred
end

Given 'Bill is logged in' do
  @bill ||= create_user(first_name: 'Bill')
  login as: @fred
end

Given 'Sam is logged in as an admin' do
  @sam ||= create_admin(first_name: 'Sam')
  login as: @sam
end

All the work here is being done by the helper methods (create_user, create_admin, login, admin_login), so it doesn't matter if you have twenty step definitions that do login so long as they all use the helper methods to do the work you have no real code duplication, and you have simplicity and consistency.
This is a completely different approach to the one you are currently taking. But a valid answer to any cuke question involving doing complex things with steps and step definitions is to stop trying to do complex things and instead more simple things.

A: You may write like below in feature file where Param Title is defined as Column
When user do something <Param Title>

In Step Definition, you may write. in this way, you don't have to write again and again scenarios and you can write multiple examples as multiple rows in one example set
@When("user do something ([^\"]*)")
public void useractivity(String Title){

}


text:
Q: Is it possible to selectively delete data (specifi page URLs) from Google Analytics? I'm pretty sure the answer to this question is "no", but I would like to get a definitive answer from an official source, and also understand what my alternative options might be.
Long story short, my app has old data in it that used to include user email addresses as a GET parameter. Those URLs are showing up as unique page view URLs in Google analytics, like this:

I don't want to be recording email addresses in my Google Analytics account (for privacy reasons), and I have fixed the code that was causing this in the first place, but I also want to delete or scrub the old data that currently exists in Google Analytics.
From everything I've read, it doesn't sound like this is possible without completely deleting the property, maybe even the account?
To be clear, I am NOT interested in creating new views that don't include URLs with email parameters in them, or otherwise change the view and not the data. The data needs to be gone and be completely inaccessible to anyone with access to this Google Analytics account.
Here are the options I've come up with:

*

*Delete the property and start over. I'm pretty sure this will
actually delete the collected data, but it's not clear to me if I
would have to actually delete the account itself to achieve that.

*Set the data retention time to the lowest possible value (looks like 14 months right now) and wait 14 months for it to go away https://support.google.com/analytics/answer/7667196?hl=en

*Perform some kind of magic to get in contact with an actual human at Google who could help me scrub or remove this data.

Does this sound right? Are there options I'm missing? If there's a way to do this through a Google API that would not be a problem.

A: If this is still a relevant issue. GoogleAnalytics provides a way to delete some data. Universal Analytics https://support.google.com/analytics/answer/9450800?hl=en and GA4 https://support.google.com/analytics/answer/9940393?hl=en&ref_topic=2919631

A: You are right: changing the data, that you have collected, and Google Analytics have already processed, is not possible. You have the option to make changes during processing with various filters, e.g. Search-and-replace filters, but as it is written in this official support article:

Like all filters, search-and-replace filters only apply to hits
  collected after you've applied the filter to the view (filters cannot
  change historical data).

Regarding you suggested options:

*

*Deleting a view or property will result in a permanent loss of data after a 35 days period of waiting time. (While this could be undone.) So unless the requirement of scrubbing the collected PII is more important than having your historical data, this should not be a way to go. The same applies to deleting the whole account, so it would be enough to delete affected properties or views.

*From the article you have linked as well, you can see, that data retention is about removing user and event level data, and it will not affect the data in aggregated reports. My understanding is, that an already created, page level report will keep showing the page with an email address:

Keep in mind that standard aggregated Google Analytics reporting is
  not affected.

I hope these references help you to evaluate your options. Sorry for not being able to come up with a solution, but the basic concept is, as highlighted in this Google article:

Once Analytics processes the data, it's stored in a database where it can't be changed


text:
Q: How to perform file I/O in C in Xcode? I am using Xcode as my IDE for C.
#include <stdio.h>

int main (int argc, const char * argv[])
{
    FILE *file;
    int numberTest = 0;
    file = fopen("fileTest.dat", "r");
    if (file == NULL)
    {
        printf("File not found!\n");
    }
    fscanf(file, "%d", &numberTest);
    printf("I read the number: %d\n", numberTest);
    fclose(file);
    return 0;
}

The file is in my Xcode bundle and is in the same folder as the rest of the project in the HDD. The problem is that fopen() keeps returning NULL.

A: You're assuming that the file is in the current working directory when the executable is launched, which it probably isn't, and which is always a bad assumption anyway, even if it happens to be true in some cases.
As a quick fix you can just hard code the absolute path to the file for now, e.g.
file = fopen("/Users/me/Desktop/fileTest.dat", "r");

A: The file is not found because it is not on your path when the executable is run. You will need to add the file to your target so that it is copied to the build directory when you build your sources.


text:
Q: What is the correct method for compiling a c++ application with TCL/TK8.4 so that it can be run on a system with TCL/TK8.5? I have a C++ application that acts as an interpreter for TCL/TK.
tms was compiled against TCL/TK8.4.
I need to run this in an environment that only has TCL/TK8.5 installed.
When I run the application on the TCL/TK8.5 system, I get this error:
tms: error while loading shared libraries: libtk8.4.so: cannot open shared object file: No such file or directory

tms is compiled on a Linux box using g++ and the -ltcl8.4 and -ltk8.4 flags.

A: If you linked the application against the 8.4 libraries then you have to have 8.4 shared objects present to run the application. You should be shipping your executable plus all the tcl libraries and scripts necessary as a package.
Having said that -- it is actually possible to do what you are talking about. The stubs mechanism used to allow Tcl extensions to be loaded into hight versions of tcl than they were compiled against can be extended to use in executables that host the Tcl interpreter. See the tcl wiki for more detailed discussion but you can arrange to dynamically load the Tcl shared library and initialize it using the stubs mechanism. There is an example on that page. However, doing this may lead to issues where the installed version of Tcl is missing things your application expects. If you stick with the standard route for embedding Tcl where you ship your application plus all the Tcl files required you can insulate your application from system specific variations.
Another possibility is to link your application to a dll/shared library that includes a virtual filesystem that contains all the supporting Tcl scripts. Originally referred to as stardll and also as basekit dlls. This makes it possible to link your executable to a single dll/.so that holds all the Tcl dependent information.


text:
Q: I'll call it a week I work in a multi-national company and I've heared this sentence a lot from non-native speakers on Fridays.

I'll call it a week.

I'm not a native speaker, but to my ears it's only natural to say:

I'll call it a day.

Which one is right?
Do you use another sentence to finish your week?

A: "Let's call it a day" is an idiom, even a cliché.  Meaning "Let us decide to end work now".
It is productive enough that "Call it a week" is a natural development. People normally have a break from work at the weekend, analogous to the break from work overnight. It and has plenty of examples on the internet. It would be less natural to say "Call it a month" because normally people don't have a break from work at the end of the month.
You don't need any sentence to end the day or the week.  If you say the same thing everyday it would sound boring.  There are so many things you could say  "I'm off now", "Have a great weekend, everyone", "See you all on Monday" and so on.


text:
Q: Android AsyncTask return the value after finishing work this is my first post.
I apologize for not good English.
I have read many questions about this topic.
Writes an application that download phone numbers and message to clients from the database on the server.
public class Connect extends AsyncTask<String,Integer,ArrayList<CUSTOMER>>{
ArrayList<CUSTOMER> clients= new ArrayList<CUSTOMER>();
 if(type.equals("login"))
    {
    //... conection code
    while((line = bufferedReader.readLine())!= null) {
                if (line.equals(error)) {

                    break;
                } else {

                    result += line + "\n";
                    String podziel = new String(line);
                    String[] tab = null;
                    tab= podziel.split(";");
                    for (int i = 0; i < tab.length; i++) {
                        Log.e("peta "+Integer.toString(i), tab[i]);
                    }
                    licznik++;
                    CUSTOMER C= new CUSTOMER(Integer.parseInt(tab[0]), tab[1], tab[2]);
                    clients.add(C);
                    Thread.sleep(3000);
                    //Log.e("k "  , clients.get(0).getId()+" "+clients.get(0).getNumer()+" "+clients.get(0).getDescryption()+"\n");

                }
            }

            return clients;
}

1:
public class MainActivity extends AppCompatActivity {

ArrayList<CUSTOMER> to_sent= new ArrayList<CUSTOMER>();

    public void conn(View view)  {
    String type="login";
    Connect connect = new Connect(this, type);
    to_sent=connect.execute(domena,  DB_name, name, password, ip).get();
    }
 }

2:
public class MainActivity extends AppCompatActivity {

ArrayList<CUSTOMER> to_sent= new ArrayList<CUSTOMER>();

    public void conn(View view)  {
    String type="login";
    Connect connect = new Connect(this, type);
    connect.execute(domena,  DB_name, name, password, ip).get();
    to_sent=connect.clients;
    }
 }

3:
    public void sent(View view) {
    String type="sent";
    Connect connect = new Connect(this, type);
    connect.clients=to_sent;
    connect.execute(domena,  DB_name, name, password, ip);

}

If he uses the first method, UI blocks and ProgresDialog can not be seen. The other one seems to me not correct, but it works correctly with ProgresDialog.
As simple as possible return ArrayList clients to Main Activity?
I need this Array to next button.
If I wrote something wrong, please tell me.

A: You're missing the entire point of an AsyncTask.  It does not return a value, because its executing in parallel.  If you were to wait until it was finished, there would be no point in using the AsyncTask at all.  Any code that needs to be done after the task finishes should be put in onPostExecute.


text:
Q: ArrayList in Java access Array of value in MySQL I have a Java bean that has a field like below,
List<String> address = new ArrayList<>();
address.add("Pearl");
address.add("Granby");

I also have a table in MySQL database name building and a column name street of its own. when I use JDBC to connect to MySQL database, how can I use this ArrayList to query in MySQL database like SELECT * FROM building WHERE street IN ("Pearl", "Granby"). Or have any better query to execute this connect. Forgive me for my poor language.
I tried to connect directly and get error like:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'building.address IN [Pearl, Grandby]'

A: String result = address.stream().collect(Collectors.joining("','", "'", "'"));


text:
Q: Help installing amdgpu-pro with r9 390 Following the directions found on AMD's site here here, I run in to a problem trying to extract the drivers. Here is what my terminal reads
~/Downloads$ tar -Jxvf amdgpu-pro-16.40-348864.tar.xz
xz: (stdin): File format not recognized
tar: Child returned status 1
tar: Error is not recoverable: exiting now
I have attempted redownloading the file multiple times, with the same results. Any ideas on what to do?


text:
Q: Open Graph Meta Tags with Nuxt Im working on a site that is made with Node, vue & Nuxt, this site deal with multiples and dinamic products,  the products have a main card that is render on the fly and showed to customers, Im trying to set the  Open Graph html header meta tags dynamically to share in Whatsapp, Linkedin, Facebook and show the preview when the link is shared, But I have no success.
I put the meta in "export default" vue component area like this:
 head () {
    const title = (MasterKeys.ENV !== 'production' ? '[' + MasterKeys.ENV.toUpperCase() + '] ' : '') + '%s - ' + (process.env.npm_package_name || '') + this.title
    return {
      titleTemplate: title,
      meta: [
        { hid: 'og:site-name', property: 'og:site_name', content: process.env.npm_package_name },
        { hid: 'og-url', property: 'og:url', content: document.location.href },
        { hid: 'og-type', property: 'og:type', content: 'website' },
        { hid: 'og-title', property: 'og:title', content: title },
        { hid: 'og-description', property: 'og:description', content: this.description },
        { hid: 'og-image', property: 'og:image', content: this.image },
        { hid: 'twitter-card', name: 'twitter:card', content: 'summary_large_image' }
      ]
    }
  },

The site is configured with ssr option off in nuxt.config.js:
export default {
  ssr: false,
.
.
.
.

I can summarize all that I investigated:

*

*In a client request Vue send to client minimum HTML, and Javascript of execute the rest of logic.

*The client (Twitter, Facebook, etc) Open-Graph renderer does not have a Javascript engine that proccess the logic sent by nuxt in
Javascript form.
There is a form in Nuxt - Vue to achive That?


text:
Q: Text animation has stopped working - html isn't finding my CSS3 anymore So I'm using a CSS3 animation on a WP theme I'm trying to build as a student project, half an hour ago it was working fine. I added in the 3 text / images boxes at the bottom, checked back and now it has stopped working!
I've been trying to amend this for ages now and I'm too scared to go any further in case I break more stuff!
The webpage is http://jacobstone.co.uk/leggera2/
JS Fiddle here - http://jsfiddle.net/2hjz8/
So my html is

Leggera

Responsive

This is

    leggera
    a theme in progress

    built on bootstrap

    how I learn stuff

    how we do it

& The CSS is:
/* fancy scroll title */
div .Iam {
    position: relative;
    width: 625px;
    padding-left: 1%;
    padding-top: 1%;
    right: 45px;
    top: -80px;

}

.Iam {
  padding: 2em 5em;
  font: normal 40px/50px Montserrat, sans-serif;
  color: #999;
  text-shadow: 2px 2px 1px rgba(38, 38, 38, 1);
}
.Iam p {
  height: 50px;
  float: left;
  margin-right: 0.3em;
}
.Iam b {
  float: left;
  overflow: hidden;
  position: relative;
  height: 50px;
}
.Iam .innerIam {
  display: inline-block;
  color: #e74c3c;
  position: relative;
  white-space: nowrap;
  top: 0;
  left: 0;
}

/*animation*/
-webkit-animation:move 5s;
   -moz-animation:move 5s;
    -ms-animation:move 5s;
     -o-animation:move 5s;
        animation:move 5s;
/*animation-iteration-count*/
-webkit-animation-iteration-count:infinite;
   -moz-animation-iteration-count:infinite;
    -ms-animation-iteration-count:infinite;
     -o-animation-iteration-count:infinite;
        animation-iteration-count:infinite;
/*animation-delay*/
-webkit-animation-delay:1s;
   -moz-animation-delay:1s;
    -ms-animation-delay:1s;
     -o-animation-delay:1s;
        animation-delay:1s;
}
@keyframes move{
    0%  { top: 0px; }
    20% { top: -50px; }
    40% { top: -100px; }
    60% { top: -150px; }
    80% { top: -200px; }
}

@-webkit-keyframes move {
    0%  { top: 0px; }
    20% { top: -50px; }
    40% { top: -100px; }
    60% { top: -150px; }
    80% { top: -200px; }
}
@-moz-keyframes move {
    0%  { top: 0px; }
    20% { top: -50px; }
    40% { top: -100px; }
    60% { top: -150px; }
    80% { top: -200px; }
}
@-o-keyframes move {
    0%  { top: 0px; }
    20% { top: -50px; }
    40% { top: -100px; }
    60% { top: -150px; }
    80% { top: -200px; }
}
@keyframes move {
    0%  { top: 0px; }
    20% { top: -50px; }
    40% { top: -100px; }
    60% { top: -150px; }
    80% { top: -200px; }
}

Thanks in advance for your time!

A: It looks like the closing bracket (}) after left: 0; in .Iam .innerIam is the problem.
If you remove it the animation is working again.
Updated JSFiddle

A: You didn't include your animation in the correponding class.
.Iam .innerIam {
display: inline-block;
color: #e74c3c;
position: relative;
white-space: nowrap;
top: 0;
left: 0;

/*animation*/
-webkit-animation:move 5s;
-moz-animation:move 5s;
 -ms-animation:move 5s;
 -o-animation:move 5s;
    animation:move 5s;
/*animation-iteration-count*/
-webkit-animation-iteration-count:infinite;
-moz-animation-iteration-count:infinite;
-ms-animation-iteration-count:infinite;
 -o-animation-iteration-count:infinite;
    animation-iteration-count:infinite;
 /*animation-delay*/
-webkit-animation-delay:1s;
-moz-animation-delay:1s;
-ms-animation-delay:1s;
 -o-animation-delay:1s;
    animation-delay:1s;
}

Working Fiddle


text:
Q: can't connect to elasticsearch or kibana running on remote Ubuntu server Quite a beginner to Elasticsearch and Kibana. I followed the instructions on Docker Hub pages to install them on my Ubuntu 18.04 server. Below are the webpages that I referred to:
Elasticsearch 7.0.3
Kibana 7.0.3
After successfully installing the docker images, I can see both containers running on my server:

I can also get right results when curling locally:

However, both curl commands showed 'Failed to connect to [my server ip : the port number]: Time out' error if I curled from another machine. Two reasons that I could think of:

*

*Firewall

*The server is not listening on the correct ports

So I checked both. Below are the results:

I could be wrong but everything looks good to me. Any ideas?
-Updates
I forgot to mention that I am able to ping my ubuntu server because if I type [my server ip address] in my browser, it will give me this 'welcome to nginx' page

A: Edit your elasticsearch.yml/kibana.yml files and use 0.0.0.0 as network.host instead of localhost.
To use your curl command,replace localhost by the ip address.


text:
Q: Like php mysqli Estou trabalhando em um sistema de likes (curtidas) mas as coisas estão muito confusas, eu tenho a tabela do Post (O conteúdo a ser curtido) com as seguintes colunas
|ID|TITLE|CONTENT|LIKES|

Na coluna LIKES, sempre que um usuário aperta o botão curtir é adicionado +1 ao numero atual, mas eu preciso salvar cada post que o usuário curtiu, isto é uma tabela para saber quais posts cada usuário curtiu, para alterar o estilo do botão e sinalizar que ele ja curtiu o Post e até mesmo pra que ele possa "descurtir" o post. A principio eu pensei em criar uma tabela com o uma coluna para o ID do usuário e uma coluna para cada Post e definir false para não curtido e true para curtido, mas é claro que isso seria inviável pois são muitos posts, então qual é a melhor maneira de fazer isso!

A: O que queres é uma relação entre tabelas NxN (muitos para muitos), um utilizador pode curtir vários posts, e um post pode ser curtido por vários utilizadores.
O mais convencional é criar uma tabela pivot, ex:
Nome da tabela: posts_likes
+----+---------+---------+
| id | id_user | id_post |
+----+---------+---------+
|  1 |       1 |       1 |
|  2 |       2 |       1 |
|  3 |       1 |       2 |
+----+---------+---------+

Desta maneira podes verificar se um determinado utilizador curtiu um certo post:
SQL, ex:
SELECT * FROM `posts_likes` WHERE `id_user`= 10 AND `id_post` = 103;

Se alguma linha for retornada significa, neste caso, que o utilizador cujo id = 10 curtiu o post cujo id = 103, e aí poderás alterar o estilo do botão e sinalizar que ele ja curtiu o Post.


text:
Q: How to add elements to an array? swift everybody! I've just started learning swift so sorry if the question is dumb. I want to add values to an array "uu" using a loop. However every time it just overwrites "uu".
Pls help, thanks!
My code

A: That is simple as
uu.append(newNumber)


text:
Q: Parse Ajax Posted JSON data in DelegatingHandler Without going into the details of why I want to do this, here is what I want to do.
Json data is posted using jquery like so:
jq.ajax({
    url: 'api/values',
    type: 'POST',
    dataType: 'json',
    data: { a: 'hello', b: 'world' }
});

In a WebAPI DelegatingHandler, I'd like to parse that content back into Json:
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    var data = request.Content.ReadAsStringAsync().Result;
    //data is url encoded, I want it as json...
    //???
    //...I'm going to do something with the json string here

    var response = await base.SendAsync(request, cancellationToken);
    return response;
}

Json.NET will do this by the time it gets to the WebAPI method that's going to handle it, so clearly it's doable, I'm just not sure how.
Note that I don't need it to be strongly typed or anything like that - a plain Json string will do.