text:
Q: How do I use a yaml anchor in an Ansible when conditional? I'm trying to check the value of a variable in a role, but I don't know what the variable name will be beforehand, as it is set outside the role.
I tried to use a yaml anchor to achieve this like so:
- set_fact:
    set_anchor: &job_status_data_key "{{ job_running_check_key }}"
[...]
- name: Set current state
  set_fact:
    loop_finished_successfully: true
  when: *job_status_data_key != "Running"

Where job_running_check_key  at the start, is set outside the role and contains the variable name I'll be checking against.
but ansible appears not to appreciate pointers in the conditionals
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)

Syntax Error while loading YAML.
  did not find expected key

The error appears to be in 'path/to/role/task.yml': line 15, column 30, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

    loop_finished_succesfully: true
  when: *job_status_data_key != "Running"
                             ^ here

There's probably a proper syntax to achieve this, but I haven't managed to figure it out until now.

A: You're confusing ansible features with YAML features.
A YAML alias is a reference to an existing node. An ansible condition is a Jinja2 expression without quotes.
YAML doesn't know about ansible or Jinja. A YAML alias must be part of the YAML structure. Jinja, on the other hand, does not know about YAML. The consequences are:
*job_status_data_key != "Running"

is invalid YAML. The YAML syntax defines that an alias starts with * and contains a single name of an anchor. The following !=… content is therefore a syntax error. Now you might think "okay, let's quote it then so that YAML reads it as string and Jinja can evaluate it":
'*job_status_data_key != "Running"'

This is now a valid YAML scalar. If given as value for when:, it will be evaluated as Jinja expression. The thing is, Jinja doesn't know that *job_status_data_key is supposed to be a YAML alias and in fact, at the time this expression is evaluated, the information about the anchored value of that name has already vanished.
The bottom line is: Don't use anchors and aliases for variables. They are a tool designed for serializing cyclic data structures inside YAML. Ansible offers variables and you should use those instead.


text:
Q: Изменить размер рамки предварительного просмотра при выборе фото из галереи У меня размер ImageView гораздо уже стандартной рамки предварительного просмотра. Как задать размеры, например, по ширине весь фрейм, а высота 300px.
 private func chooseImage(sourse: UIImagePickerController.SourceType) {
    if UIImagePickerController.isSourceTypeAvailable(sourse) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        imagePicker.sourceType = sourse

        self.present(imagePicker, animated: true, completion: nil)
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Jquery to append a li to an ul where oid=xxx I am trying to append a li to only the UL which has a certain oid value set like this
$('ul.sortablespm oid=' + data).append('

');

It works fine without the oid parameter, but then adds the li to all ULs on the page..

A: Use the appropriate attribute selector syntax, that is, [name="value"]:
$('ul.sortablespm[oid="' + data + '"]').append('

');

A: Here is a working example of what I believe you are looking for.
http://jsfiddle.net/chapmanc/wU6Vs/
If the ul object has a unique id you can simply use that as your selector and append an item to that object.
For example a ul with an id of myList:

a

b

c

And a function to append to that object using the unique selector:
$('#myList').append('
d
');

This appends a li item to the myList object. Notice the '#' character in front of myList when using an id selector.


text:
Q: How to filter the column of one DataFrame by the value of another DataFrame Here is my df1, that has 365 values for 365 days in a year
    Date  Data_Value
0  01-01        33.3
1  01-02        30.6
2  01-03        31.1
3  01-04        30.0
4  01-05        30.0
5  01-06        31.1
6  01-07        31.1

And here is my df2 which has 7262 rows of data containing several rows for one date of the year.
mnth_day  Data_Value
0    10-07        30.0
1    10-18        21.1
2    02-25        14.4
3    03-22        28.9
4    02-25        28.9
5    09-03        24.4
6    11-19        25.0

I need to check in how many days 'Data_Value' in df2 exceeds 'Data_Value' in df1. How can I do that?

My expected output will look like:
    Date  Data_Value
0  01-01        33.3
1  01-02        30.6
2  01-03        31.1
3  01-04        30.0
4  01-05        30.0
5  01-06        31.1
6  01-07        31.1

Here the 'Date' column will be in which date the 'Data_Value' in df2 exceeds the 'Data_Value' of df1. and 'Data_Value' column will be that biggest 'Data_Value'.


text:
Q: Probability of 4 consecutive numbers on a random Lotto Max Quick Pick Picked up a quick pick Lotto Max ticket from a store today.
The numbers were as follows
14 15 16 17 29 46 47 Quick Pick
It is standard lottery game 7 balls, each number from 1 to 50
What are the odds of getting 4 consecutive numbers on a random quick pick?

A: To cover all the cases, you'll need to either use something like the inclusion-exclusion principle or explicitly (and individually) count all the cases with a run of exactly four, a run of exactly five, etc.  Fortunately, since you're asking for four (or more) out of seven, you never have to consider the cases with multiple runs matching within one ticket, so these are all mutually exclusive and cover all the possibilities. I'll work the cases with a run of exactly four so you can see how it works:
We'll start similarly to wjmccann's answer, by looking at where the run of four can begin and where the other numbers can be chosen from.  In principle, the run of four can begin at any of 47 different positions (1..4 through 47..50), and since there are six numbers that can't be chosen (the run itself, and either of the two numbers adjacent to it), for each run of four the remaining three numbers can be chosen from any of the 50-6=44 other places, and so the count of tickets is 'roughly' $47\cdot {44\choose 3}$.  Unfortunately, there's a small catch in this due to edge effects; for two of those 47 cases (the (1..4) case and the (47..50) case), we can actually choose the remaining three numbers from 45 different places rather than 44.  So the precise count of tickets with a run of exactly four numbers in them is $2\cdot{45\choose 3}+(47-2)\cdot{44\choose 3}$.  You should be able to find the precise counts of tickets with runs of exactly five numbers, exactly six numbers, and exactly seven numbers in them; adding these then gives the total count of tickets with a run of (at least) four consecutive numbers.

A: If you are ok with tickets that have at least four consecutive numbers, than this isn't that tough.
First we choose a starting number for our sequence of four consecutive numbers. In the numbers $1-50$ we have $47$ possible sequences for this. Now we need to select the remaining three numbers for your ticket from the other $46$ possible numbers. Finally, to get the probability you multiply these together and then divide by all possible tickets.
$$
\dfrac{47\binom{46}{3}}{\binom{50}{7}} \approx .714\%
$$


text:
Q: Uncaught ReferenceError: global is not defined Hello I'm trying to use stomp in angular. once i use it in my project I lost my whole project , I get white page nothing is working.
this.stompService.subscribe('/topic/vehicle', (): void => {
  this.getnotificationsByReceiver();
});

please can't understand what is this. I tried many times same issue

A: This possible duplicate of this.
The global object is not available. Possible solution to change it to window object.


text:
Q: pseudo element :last-child not work as it's way but :first-child does!! why? in code below i try to make last child of p elements color to red but don't work, but first child by :first-child pseudo element work. in this case last child of div element would be to color red, but last child of body wouldn't.
`

p:last-child {
  color: red;
}

Lorem, ipsum.

Lorem, ipsum.

Lorem, ipsum.

Lorem, ipsum.

Lorem, ipsum.

Lorem, ipsum.

Lorem, ipsum.

Lorem, ipsum.

Lorem, ipsum.

`


text:
Q: How do I populate a C# ComboBox with the names of the last 4 months? I want to display the names of the last 4 months in a ComboBox using C#. When a user selects a month  I need to pass the date/time to a query. How can I display the month name while using a date/time as the value?

A: Bind your combo box by DisplayMember = 'Month Name' and ValueMember = theDateTime
ListItemCollection items = new ListItemCollection();
DateTime now = DateTime.Now;
for (int count = 1; count <= 4; count++)
{
    items.Add(new ListItem(now.ToString("MMM"), now.ToString()));
    now.AddMonths(-1);
}
combobox.DisplayMember = "Text";
combobox1.ValueMember = "Value";
combobox1.DataSource = items;

Then get the user selected value in date time
DateTime selected = Convert.ToDateTime(combobox1.SelectedValue);

A: You don't give much in terms of details.  I assume selected month value is an integer.  You can create a dummy DateTime object to have as a placeholder for your month value:
new DateTime(DateTime.Now.Year, selectedMonth, DateTime.Now.Day);

A:
Just another idea: the solution below stores the real DateTime in the List instead of just the month, e.g., 5/1/2011.  When the combo box is selected, the output will really be the date.
Code behind:
    public MainWindow()
    {
        InitializeComponent();

        MyMonths = new List<DateTime>();
        var thisMonth = new DateTime(
            DateTime.Now.Year,
            DateTime.Now.Month,
            1);

        for (var i = 0; i < 4; i++)
        {
            MyMonths.Add(thisMonth.AddMonths(-i));
        }

        this.DataContext = this;
    }

    public List<DateTime> MyMonths
    {
        get { return (List<DateTime>)GetValue(MyMonthsProperty); }
        set { SetValue(MyMonthsProperty, value); }
    }
    public static readonly DependencyProperty MyMonthsProperty =
        DependencyProperty.Register("MyMonths", typeof(List<DateTime>), typeof(MainWindow), new UIPropertyMetadata(null));

Xaml:
    <StackPanel>
        <ComboBox x:Name="dateCombo"
                  Margin="10"
                  SelectedIndex="0"
                  ItemsSource="{Binding MyMonths}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Converter={StaticResource dateTimeConverter}}"/>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </StackPanel>

DateTimeConverter:
public class DateTimeConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is DateTime)
        {
            var d = (DateTime)value;
            return d.ToString("MMM");
        }
        return string.Empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

Update: For formatting the month:
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month


text:
Q: Please help just using html and css how to show hide either of div from nav bar buttons I have two divs. One displays configure wifi and other displays status. What is happening is that, when I click on the navbar button it shows the Wific configure div and if I click it again it hides it.
and if I click the second button show status div, it shows the status along witht he configure wifi div. then I have to click either of the button for what I do not want to see.
what I want to acheive just using css and html of what I have attempted is to toggle between divs when respective button is clicked in nav bar.

.toggle-content {
  display: none;
}

.toggle-content.is-visible {
  display: block;
}

html {
  font-family: Arial;
  display: inline-block;
  margin: 0px auto;
  text-align: center;
}

ul {
  list-style-type: none;
  margin: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  font-size: 1.0rem;
  text-align: center;
  padding: 14px 26px;
  text-decoration: none;
}

li a:hover {
  background-color: #111;
}

.center {
  margin: auto;
  border-style: groove;
  padding: 10px;
}

h2 {
  font-size: 1.0rem;
}

p,
{
  font-size: 3.0rem;
}

.units {
  font-size: 1.2rem;
}

</style>

Configure Wifi

Show Status

Connect to a Wifi Network!

  Choose ssid:
  <select name="wifi" id="ssid">
  </select>

  Enter password:
  <input type="password" id="pass"></input>

  <input type="button" value="Rescan">
  <button id="button_save" class="button_wifi" onclick="update()">Connect</button>

I want to be able to toggle between the two divs not toggle on off by clicking the same button in navbar twice though even if it exists its ok but when I choose show status the configure wifi div should hide.


text:
Q: I want to recover the posts of my Facebook account to simple table, but I am facing some problems I am using C# and ASP.NET to code this. I don't want the user to be forced to log in and authorize my facebook app, so I wrote this code to get my token that works fine:
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/oauth/access_token?client_id=MYID&client_secret=MYSECRET&user_id=MYUSERID&grant_type=client_credentials");
        myRequest.Method = "GET";
        WebResponse myResponse = myRequest.GetResponse();
        StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
        string result1 = sr.ReadToEnd();
        sr.Close();
        myResponse.Close();
        string token = result1.Substring(13, result1.Length - 13);

Then I wrote this code to get my recent posts:
        HttpWebRequest myRequest1 = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}","https://graph.facebook.com/app/posts?access_token=",token));
        myRequest1.Method = "GET";
        WebResponse myResponse1 = myRequest1.GetResponse();
        //StreamReader sr1 = new StreamReader(myResponse1.GetResponseStream(), System.Text.Encoding.UTF8);
        StreamReader sr1 = new StreamReader(myResponse1.GetResponseStream());
        string result2 = sr1.ReadToEnd();
        sr1.Close();
        myResponse1.Close();

How can I quickly transform this JSON object into a table?


text:
Q: Rails generate scaffold error message i'm having trouble generating scaffolding in my rails app:rails generate scaffold User name: string email:string
dyld: lazy symbol binding failed: Symbol not found: _rb_str_new_static Referenced from: /Users/macowner/workspace/toy_app/vendor/bundle/gems/json-1.8.3/lib/json/ext/parser.bundle Expected in: flat namespace
dyld: Symbol not found: _rb_str_new_static Referenced from: /Users/macowner/workspace/toy_app/vendor/bundle/gems/json-1.8.3/lib/json/ext/parser.bundle Expected in: flat namespace

A: One of your gems doesn't match your installed Ruby version.
Open up your Terminal utility, cd /Users/macowner/workspace/toy_app and run:
gem pristine --all
bundle install

This command will restore your gems to their original condition at the time you installed them.


text:
Q: How to JOIN these 3 tables together in SQL? So I have 3 tables in total called companies_company c, companies_sharedtrainingunit cst and companies_trainingunit ct. The first JOIN I created joined c and cst on the same company id.
SELECT c.id as consuming_company_id, c.name as consuming_company_name, cst.id as channel_connection_id, cst.training_unit_id as channel_id
FROM companies_sharedtrainingunit cst
FULL JOIN companies_company c ON c.id = cst.company_id
ORDER BY company_id ASC

which yields a table with results like

consuming_company_id
consuming_company_name
channel_connection_id
channel_id

1
company_1
2000
100

Now I want this joined table created above joined to the same info from table c and a new table ct ie
SELECT c.id as owned_company_id, c.name as owned_company_name, ct.id as channel_id, ct.name as channel_name, ct.description as channel_description
FROM companies_trainingunit ct
FULL JOIN companies_company c ON c.id = ct.company_id
ORDER BY c.id

owned_company_id
owned_company_name
channel_id
channel_name
channel_description

2
company_2
100
channel_100
description_100

I have tried joining these two queries but no luck :(
I know they need to be joined on their channel ids
In the end I am looking for my table to looking something like:

channel_connection_id
consuming_company_id
consuming_company_name
channel_id
channel_name
channel_description
owned_company_id
owned_company_name

2000
1
company_1
100
channel_100
description_100
2
company_2

A: Looks like you need to join with companies_company twice. Also, an inner join is sufficient:
SELECT cst.id as channel_connection_id,
       c1.id as consuming_company_id,
       c1.name as consuming_company_name,
       cst.training_unit_id as channel_id,
       ct.name as channel_name,
       ct.description as channel_description,
       c2.id as owned_company_id,
       c2.name as owned_company_name,
FROM companies_sharedtrainingunit cst
   JOIN companies_company c1 ON c1.id = cst.company_id
   JOIN companies_trainingunit ct ON cst.training_unit_id = ct.id
   JOIN companies_company c2 ON c2.id = ct.company_id
ORDER BY cst.company_id ASC;

A: I would expect a left join starting with companies to be sufficient to get the rows you want.  Does this do what you want?
SELECT c.id as consuming_company_id, c.name as consuming_company_name,
       cst.id as channel_connection_id, cst.training_unit_id as channel_id,
       ct.id as channel_id, ct.name as channel_name, ct.description as channel_description
FROM companies_company c LEFT JOIN
     companies_sharedtrainingunit cst
     ON c.id = cst.company_id LEFT JOIN
     companies_trainingunit ct
     ON c.id = ct.company_id
ORDER BY c.company_id ASC;

A: I find it hard to understand your data model. There are tables with "trainingunit" in their names, but there is no trainingunit ID. Instead there is a "channel_id" you want to join on. Why is that?
Then, you are using full outer joins to include companies without training units and training units without companies. Does that even make sense?
However, provided your queries are correct and you want to join them, just do so:
select *
from
(
  SELECT c.id as consuming_company_id, c.name as consuming_company_name, cst.id as channel_connection_id, cst.training_unit_id as channel_id
  FROM companies_sharedtrainingunit cst
  FULL JOIN companies_company c ON c.id = cst.company_id
) q1
(
  SELECT c.id as owned_company_id, c.name as owned_company_name, ct.id as channel_id, ct.name as channel_name, ct.description as channel_description
  FROM companies_trainingunit ct
  FULL JOIN companies_company c ON c.id = ct.company_id
) q2 using (channel_id)
order by channel_id;


text:
Q: How to stop execution until a setState in React Native Recently have created a logout function. By which when user clicks on logout, they will be prompted a dialog asking "Are you sure that you want to logout ? ". For Dialog , I used a package named react-native-popup-dialog.
Actually, whats happening is as this app is clubbed with redux. I used action for logout functionality. And for dialog , i have used component level state.
My Dialog Code:
<Dialog
    visible={this.state.showDialog}
    dialogTitle={
    <DialogTitle
    title="Confirm Logging Out"
    textStyle={{ fontSize: 15 }}
    />}
    width={0.8}
    footer={
        <DialogFooter>
          <DialogButton
            text="CANCEL"
            textStyle={{ fontSize: 14 }}
            onPress={() => {
              this.setState({ showDialog: false });
            }}
          />
          <DialogButton
            text="CONFIRM"
            textStyle={{ fontSize: 14 }}
            onPress={() => {
                this.onLogoutPress();
            }}
          />
        </DialogFooter>
      }
    onTouchOutside={() => {
    this.setState({ showDialog: false });
    }}
>
    <DialogContent>
        <Text style={{ fontSize: 14, top: 10 }}>Are you sure you want to logout ?</Text>
    </DialogContent>
</Dialog>

And my Logout Button Code:
<TouchableOpacity onPress={()=> this.setState({ showDialog: true})} >
  <CardItem>
    <Icon name="log-out" style={{ color: '#03A9F4' }} />
    <Body>
      <Text>Logout</Text>
    </Body>
    <Right>
      <Icon name="arrow-forward" />
    </Right>
  </CardItem>
</TouchableOpacity>

So my onLogoutPress() code:
onLogoutPress() {
this.setState({ showDialog: false },() => {
    this.props.logOut(() => {
        this.props.navigation.dispatch(resetActionToWelcome);
    })
})

}
The issue I am facing is that, when I click on confirm button the "onLogoutPress()" shoots up, and the dialog is not closing instead of that the resetAction of react navigation shoots up.  As setstate is async function I think it took time to get back, within that the logout action is shoots up and app gets start from splash screen. But till the dialog is kept open.
How to deal with this?

A: change you function like below,
hope it will work for you
first ways,
onLogoutPress() {
   this.setState({ showDialog: false },() => {
   setTimeout(() => {
     this.props.logOut(() => {
           this.props.navigation.dispatch(resetActionToWelcome);
      })
      }, 500);

   })
}

another way using arrow function,
onLogoutPress = () => {
   this.setState({ showDialog: false },() => {
     this.props.logOut(() => {
           this.props.navigation.dispatch(resetActionToWelcome);
      })
   })
}


text:
Q: tables in Ram or DB tables, for best performances I am programming a server application (chat server side) with java, which receive requests and send to a target.

*

*I have several tables in the database, and when the server
application starts, I programmed it to copy all the content of the
database to Map tables (in the ram) in order to speed up the pull

*

*push data while the application running.
Dose this correct way? Or you suggest me to pull data from the database directly when I need a detail. and remove the Map<>
tables from the ram!?

*I suffer from memory leak.

*Does dealing with the database slows the application?

A: Whether caching all or some of the data in memory makes sense depends on your use case. It can improve performance but it adds complexity which might not be needed.
You can load millions or even billions of records into a JVM, but much more then this you need an off heap storage such as a data store for this purpose or a database. Using off heap memory, you can have trillions of records in a JVM but this is rarely needed.


text:
Q: Getting lat/lng from wkid, latestwkid and x y coordinates I am receiving some JSON feed with this data
"geometryType": "esriGeometryPoint",
"spatialReference": {
    "wkid": 102100,
    "latestWkid": 3857
  },

and set of coordinates like
"geometry": {
   "x": -11696523.780400001,
   "y": 4804891.0001000017
}

If there a way to convert this x and y to lat/lng which I can use in Google Maps?
I have read some references but there either I can`t see the answer, or it's goes very deep into GIS terminology which I just can't afford to learn at the moment.

A: You could use the ArcGIS server REST endpoint to convert to wkid 4326 (lat/lon). Here's a URL for one of Esri's sample servers:
https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer/project?inSR=102100&outSR=4326&geometries=%7B%0D%0A++%22geometryType%22+%3A+%22esriGeometryPoint%22%2C%0D%0A++%22geometries%22+%3A+%5B%0D%0A+++++%7B%0D%0A+++++++%22x%22+%3A+-11696523.780400001%2C+%0D%0A+++++++%22y%22+%3A+4804891.0001000017%0D%0A+++++%7D%0D%0A++%5D%0D%0A%7D&f=HTML

Pasting the coordinate in google maps gives you this (Littleton, right?):
https://maps.google.com/?q=39.5785846502541+-105.071660830008
If you just need to convert the occasional coordinate this will work fine, but I guess as soon as it's thousands of coordinates, you are going to want to automate stuff.
As for the meaning of latestWkid, see here: https://support.esri.com/en/technical-article/000013950

A: Based on Berend, the quickest link is:
https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer/project
Then see it on google map
https://maps.google.com/?q=39.5785846502541+-105.071660830008

A: For a formula that you can implement, see this page for an explanation and scroll down the bottom for various implemenations 3857 to/from 4326
Python Implementation provided:
def MetersToLatLon( mx, my ):
    "Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum"

    lon = (mx / originShift) * 180.0
    lat = (my / originShift) * 180.0

    lat = 180 / math.pi * (2 * math.atan( math.exp( lat * math.pi / 180.0)) - math.pi / 2.0)
    return lat, lon


text:
Q: Can "Pooled Averages" be considered as "Better" compared to "Individual Averages"? I am an MBA Student taking courses in statistics.
We had this discussion today in our class. Suppose we have a large dataset that contains the "Age Group" and "Gender" of people within a country and if they have some specific "Disease or Not".
Using this data, by filtering on different subsets, we calculate that:

*

*Suppose the probability of having a specific disease in the entire population is p1

*Suppose the probability of having a specific disease for the population of men is p2

*Suppose the probability of having a specific disease for the population of women is p3

*Suppose the probability of having a specific disease for the population of young people is p4

*Suppose the probability of having a specific disease for the population of old people is p5

*Suppose the probability of having a specific disease for the population of old men is p6

*Suppose the probability of having a specific disease for the population of young men is p7

*Suppose the probability of having a specific disease for the population of old women is p8

*Suppose the probability of having a specific disease for the population of young women is p9

Now, imagine we realize that we forgot to collect the data for this one young man. What is the probability that he has this disease?
The obvious answer to this question seems like the probability is p7. But after thinking about this for a while, I had the following ideas:

*

*What if the probability of having this disease is significantly more influenced by some variable that is not measured in this dataset (e.g. smoking)?

*What if some of these subsets have a very small population? (e.g. suppose only 1% of all data is old men)

*Suppose young men smoke a lot but this forgotten young man does not smoke - the probability of him having a disease might be closer to that of some other subgroup?
For such cases, I thought that it might be better to try and "average out" this out information to safeguard against possible risks. For example - perhaps the probability that this young man has the disease is: (p1 + p2 + p4 + p7)/4 ?
This way, we have taken into consideration hidden trends and patterns within the entire population, the entire population of young people and the entire population of young men. The effects and skewness from possible outliers should now have been more smoothened out?
From my Algebra classes, I know that there is no guarantee that p7 must equal to (p1 + p2 + p4 + p7)/4. This brings me to my question:
In the absence of any other information and prior knowledge on this disease - is it possible that (p1 + p2 + p4 + p7)/4 might be a "less riskier" estimate compared to p7 alone?
Is this a valid estimation procedure, or have I misunderstood how averages and pooled averages are intended to be interpreted and used?
Note 1: Of course the drawback to this pooled approach is that if there are no outliers in the data, then p7 would have been a more accurate estimate and we put ourselves in our a worse position by pooling the averages.
Note 2: If we did in fact have some prior knowledge, it could have been interesting to take a "weighted pooled average" of the probabilities. But in the absence of prior knowledge and additional information, it looks like we have no choice but to assume equal weighting.

A: You can use the p7 probability as an estimate. (or if this estimate is very inaccurate, you can also simply conclude that you do not know enough for an accurate answer and more information should be gathered)
If you somehow want to improve this estimate then you need to add information. Either by more measurements or by information based on theory. The latter can be tricky and create bias.
Example

*

*measurement 1: 100 young men among which 20 got sick
estimate $p_7 = 0.2 \,(s.e. 0.04)$

*measurement 2: 10 000 old men among which 5 000 got sick.
estimate $p_6 = 0.5 \,(s.e. 0.005)$
The estimate $p_6$ is much more accurate, but can you honestly use it to predict the probability for a young man to get sick?
By using the $p_6$ figure you added more information, but it might be inaccurate information. You should only use information that makes sense. That is, when you know/assume that it will have a small bias (the acceptable level of 'small' depending on how accurate you desire to be).

A related concept is the bias-variance trade-off
A typical cases in statistics where bias is added is regularised regression. The 'correctness' of the added bias is determined by training and validating a model during which the amount of bias is optimized based on the perfotmance of the model.

Another related concept is Bayesian statistics. It provides a way to update knowledge after acquiring more data. Of course, if there is not a lot of data, then the final quality of the estimate depends a lot on the prior knowledge. You could use the accurate number $p_6$ as prior knowledge, but you would have to reduce the weight that you give to it. How you do this is relatively subjective but in a workflow with increasingly more knowledge and information the subjectivity reduces.


text:
Q: Using SQLite as production database, bad idea but We are currently using postgresql for our production database in rails, great database, but I am building the new version of our application around SQLite. Indeed, we don't use advanced functions of postgres like full text search or PL/SQL. Considering SQLite, I love the idea to move the database playing with just one file, its simple integration in a server and in Rails, and the performance seems really good -> Benchmark
Our application's traffic is relatively high, we got something like 1 200 000 views/day. So, we make a lot of read from the database, but we make a few writes.
What do you think of that ? Feedback from anyone using or trying (like us) to use SQLite like a production database ?

A: If you do lots of reads and few writes then combine SQLite it with some sort of in-memory cache mechanism (memcache or redis are really good for this). This would help to minimize the number of accesses (reads) to the database. This approach helps on any many-reads-few-writes environment and it helps to not hit SQLite deficiencies - in your specific case.

A: SQLite is designed for embedded systems. It will work fine with a single user, but doesn't handle concurrent requests very well. 1.2M views per days probably means you'll get plenty of the latter.

A: For doing only reads I think in theory it can be faster than an out-of-process database server because you do not have to serialize data to memory or network streams, its all accessed in-process. In practice its possible an RDBMS could be faster; for example MySQL has pretty good query caching features and for certain queries that could be an improvement because all your rails process would use this same cache. With sqllite they would not share a cache.


text:
Q: Mystery computer appearing in the Finder's source list On my MacBook, in the Finder's sidebar there's a machine appearing under "Shared" that I don't recognize and definitely doesn't exist on our local network. When I attempt to connect to it, I get this message:

The server "otseeley-remote" is available on your computer. Access the volumes and files locally.

What is this and how do I get rid of it? I already checked Disk Utility and there are no extraneous volumes mounted or anything.
EDIT:
Additional information based on the questions below:

*

*There are only two computers on the network, both running Mac OS X - this MacBook, and my PowerBook. The PowerBook shows up in the source list as a separate item from "otseeley-remote"

*There is no Time Capsule on the network, though I do have a Time Machine drive plugged into the PowerBook (not shared, though)

*No VPN

*One wired printer, connected to the MacBook

*Two other wifi networks other than my own appear in the wifi dropdown, so I suppose it's possible that the mystery machine is on a neighbor's network (though why would it show up in my source list?)

EDIT 2:
The mystery computer shows up on both my MacBook's and PowerBook's source list, but not always at the same time. Sometimes it appears on one and not the other; other times, it appears on both.
EDIT 3:
I have two user accounts on the MacBook and both accounts show the "otseeley-remote" item in the Finder. Not sure if that means anything, but just wanted to add another data point.

A: The message "The server "otseeley-remote" is available on your computer. Access the volumes and files locally" means that what you're seeing in the sidebar is your own computer, not a different machine... why you're seeing it is the real question, and unfortunately I don't have any great answers for you.
More troubleshooting is in order, and if this were shorter I would have posted it as a comment....
There's a very similar question on SuperUser which unfortunetly has no answers... if I were you, I would comment on that question and link to this one. That will bump that question and possibly get an answer to it.
Someone has the exact same issue on MacWorld's forums however they never returned to give any more detail or let us know if the problem was solved...
Do you have an Airport Extreme with a drive attached to it? This person and this person also mentioned seeing the same message with an Airport Extreme device which had an attached USB hard drive.
A lot of people refer to this problem when talking about virtualization software. That was my first thought, but you said you're not using it.
If you turn off your airport card, does the share go away?
If you open the Terminal and type/paste in: ping -c 5 otseeley-remote.local, what do you see?
EDIT: Let's see if this reveals anything. If you use a program like Bonjour Browser, do you see otseely-remote under any of the services? (You can expand all the levels of the tree by option-clicking on the topmost disclosure arrow twice)

A: I've added a possible answer over on SuperUser
https://superuser.com/questions/268380/mysterious-shared-server-with-same-name-appearing-disappearing/338732

Sounds like you might have SMB (Windows) Sharing turned on.
To check, go to the System Preferences and click on Sharing. In the list on the left click on 'File Sharing' then there is a little button on the top right called 'options'. In the drop-down that appears check that SMB sharing is un-ticked.

A: Similar to what josh is saying, I would try and see if you hit this with some sort of network trace. What I recommend for easiest use is Bonjour Browser. This program lists all the bonjour services and who is advertising them, in this case we are talking AFP probably. I use this often at work to find who is using an iTunes shared library in two clicks.
Just run the app and it will display all computers on the network who offer Bonjour services and you can expand the type of service to see which computers are offering it.

A: In 10.7 removing the "shared" phantom computer can often be done by going to System Preferences>Sharing – then toggle on and off all the radio buttons that contain the word "sharing." This should reset the sidebar to default.

A: You may have a stowaway computer on your AirPort network.
Here are a few steps to check this possibilty:

*

*activate your AirPort network;

*open a Terminal

*type arp -i en1 -a
Check all the MAC addresses displayed by arp. They should all belong to your own Mac, PC, iPhone and Co.. If not, then you have identified a
stowaway computer on your network.
This would mean that your AirPort network is not secured.
Then you can identify which kind of computer this stowaway is by looking at the 3 first digits of its MAC address and locate them within the :
IEEE OUI official list.
From the described symptoms, this uninvited computer is on the far limit
of your AirPort network. This may be a few hundred meters in outdoor, and about 25 m far in a concrete building.

A: This may not be the answer, but I got rid of mine by going to the System Preferences > Sharing and unchecked Remote Login.  I don't have a clue how I happened to enable that before!

A: This may be meaningless to your situation, but I found this article educational -- about how a person's mac has two MAC addresses associated with it (one for its wifi identity and one for its non-wifi, ethernet identity.)   One of those "jekyll and hyde" existences is likely the other mystery machine for SOME of the people with this problem -- namely ME.
Take a read through this --
http://www.macmousecalls.com/files/who_is_invading.html

A: I tried all the tricks I could find without success, but eventually solved it with the clue here that the phantom names on the network were "stowaways" on the Airport network.
I had about 8 variations on the name of the Mac Mini on our network: some were names I gave it, some were simply appended numbers to one of the names. All three computers (two Mavericks and one Yosemite) on the network showed the same shared ghost devices. Must be a router storing the names of the phantom computers. I have a FiOS router, plus an Apple Airport Extreme connected to FiOs via ethernet, and also an old Airport Time Capsule for backups only (no wi-fi) daisy chained off the Airport Extreme, so there were three possible culprits.
I unplugged both the FiOs router and the Airport Extreme, waited a minute, then plugged the FiOS router back in; after it was back online, I plugged the Airport Extreme back in. Partial success! Some of the newer ghost names went away, but four of the older ones remained. Must be the old Airport Time Capsule. I unplugged it, waited, then plugged it back in. Success! All the phantom names on the network are now gone from all the computers. This is not a problem that can be fixed locally by changing settings or trashing .plist files.

A: I turned WiFi on and off and it got rid of the shared computer.


text:
Q: On passing arguments to super class, an error flags: "module.__init__() takes at most 2 arguments (3 given)"? class info:
    def __init__(self, **kwargs):
        self._variables = kwargs

class waybill(info):
    def __init__(self, **kwargs):
        super(waybill, self).__init__(**kwargs)

Error -: module.__init__() takes at most 2 arguments (3 given)
What could probably the reason why this error is flagging? I am using Python 3.2

A: Is info defined in the same file? Or is it info.info from info.py? If you're importing info, trying changing it to the following:
from info import info

Additional information: If you simply import info then info is a module, and waybill is subclassing module.

A: super(waybill, self).__init__(kwargs)

should be:
super(waybill, self).__init__(**kwargs)


text:
Q: How to calculate "score" based on tags match This will be a bit hard to explain. I have 3 tables, 1 for User, 1 for Interest & 1 for User_Interests. I want to calculate a score and add it to a new column. The score calculation is not that hard: Base points: 50. For each interest both users have I want to add 3 points to score, if a user has a interest that I don't have, I want to add 1 point to score. Is this possible using mySQL SELECT?
User:
| ID |
| 0 |
| 1 |
| 2 |
Interest:
| ID | title |
User_Interests:
| User_ID | Interest_ID |
This will however depends on my own ID. The end result I am looking is a list of all users and there score based on the tags from the user I supply. Let's say my user ID is 0:
Result:
| ID | score |
| 1 | 69 |
| 2 | 54 |

A: This LEFT JOIN lists common interests and interests of the other user that this user does not have.
SELECT
    count(my.interest_id) AS common_interests,
    count(*) AS all_interests

FROM users_interests ui
LEFT JOIN users_interest my ON
    (   my.user_id=$user_id
    AND my.interest_id=ui.interest_id )
GROUP BY ui.user_id

The answer (according to the number of points you assign) would be common_interests*2 + all_interests


text:
Q: Is the path that a planet takes orbiting the sun a centripetal one or one that follows a geodesic path? Is the path that a planet takes orbiting the sun a centripetal one or one that follows a geodesic path? My point is that if the planet follows a centripetal path all objects on the planet will experience a varying force depending on whether they are on the inner side of the planet as it is orbiting or the outer side. If as Einstein states the planet is following a curved / space time geodesic then there will be no forces acting on the planet or objects on the surface of that planet. It appears to me that it cannot be both and that a simple experiment will prove one or the other true.

A: A planet orbiting a central body is subject to gravitation as a force in Newtonian mechanics. Only one point on the planet accelerates toward the central body as would be suggested by Newton's law of gravitation. The planet forces particles at points removed from this key point to accelerate in a way that differs from the gravitational acceleration toward the central body at the point. From the perspective of Newtonian mechanics, tides result from the gradient of the gravitational acceleration vector, mathematically described by the Newtonian tidal tensor).
A planet is subject to gravitation as the curvature of space-time caused by the central body in the context of general relativity. Only one point on the planet follows a geodesic about this central body. The planet forces particles at points removed from this key point follow a curve that is not a geodesic.  From the perspective of general relativity, tides result from the geodesic deviation, mathematically described by the Riemann curvature tensor.
Just as geodesics in general relativity becomes Newtonian orbits in the limit of velocities that are very small compared to the speed of light and distances that are very large compared to the Schwarzschild radius, the Riemann curvature tensor becomes the Newtonian tidal tensor in this limit.

A: From the simple perspective of looking at the differential in the force, this is something we most certainly do observe. This is called tidal forcing and is what makes planets elongated in the direction along the radial path to the star, causes tides in the oceans and, in the extremes, leads to tidal breakup and tidal disruption events. The idea behind all of these is that the gravitational force is greater at the side of the planet closer to the sun (or other body such as moon, black hole etc.) then the side that is farther. Since the force scales as the inverse square, for large objects or close objects, the difference can be very large, even enough to rip the object apart.

A: A body in free fall describes a geodesic per definition. A planet orbits a central mass in free fall and thus follows a geodesic. Strictly however this is true only for its center of mass, because all other points feel forces as you say and thus are not in free fall.


text:
Q: Mutliple left joins return double rows I have 4 tables

*

*users

*pictures

*messages

*friendrequests

I'm trying to get friend requests and new messages in a single query. It works well but as I left join 'friendsreuqests' I get multiple rows.
Here is my query:
SELECT username,
  f1.userid as reqId,
  m1.msg, m1.userid,
  p1.picHash, p1.extension, UNIX_TIMESTAMP( m1.sent ) AS date
FROM users
  LEFT JOIN pictures p1 ON p1.userid = users.id
  LEFT JOIN messages m1 ON m1.contactid = users.id AND m1.delivered =0
  LEFT JOIN friendrequests f1 ON f1.contactid = users.id AND f1.delivered=0 AND f1.request =1
WHERE users.id =7
ORDER BY date ASC

This is the MySQL result:
Kungen  3     gregegerg     1    dc825b1c8a35593be4d172db7    jpg    1369839537
Kungen  12    gregegerg     1    dc825b1c8a35593be4d172db7    jpg    1369839537
Kungen  3     HEJH          1    dc825b1c8a35593be4d172db7    jpg    1369839540
Kungen  12    HEJH          1    dc825b1c8a35593be4d172db7    jpg    1369839540

As you see there result is doubled. I want to get only two rows at this point. If I have two new messages but no new friends requests those 2 rows should be NULL.

A: If you want to get friend requests and messages in a single query, then I would expect the query to have a union all.  Your query is doing a join between the tables.  This would add information about friend requests as additional columns.  You want it in additional rows.
I'm not sure which fields in the friends table correspond to which fields that you are requesting.  But here is an example of a query using union all:
SELECT username, users.id as reqId, m1.msg, m1.userid,
       p1.picHash, p1.extension, UNIX_TIMESTAMP( m1.sent ) AS date
FROM users LEFT JOIN
     pictures p1 ON p1.userid = users.id LEFT JOIN
     messages m1 ON m1.contactid = users.id AND m1.delivered =0
WHERE users.id =7
union all
SELECT username, users.id as reqId, NULL, NULL,
       NULL, NULL, UNIX_TIMESTAMP( f1.sent ) AS date
FROM users LEFT JOIN
     friendrequests f1
     ON f1.contactid = users.id AND f1.delivered=0 AND f1.request =1
ORDER BY date ASC

A: If you LEFT JOIN  both friend requests and messages like you do you will get No of messages times number of friend requests in your result set. In you example you have 2 requests and 2 messages resulting in (2*2=) 4 rows.
Perhaps you should consider using a union instead? With a union you will be able to get one row for each friend request and one row for each message. That should suit your needs better.
You will still get 4 rows in your example (2+2), though.

A: Adding GROUP BY clause with all fields in it will surely help, but you will have to decide, which value for second field you want to keep (3 or 12).
If you definitely know, that there are always 2 rows with that field differing, than you can select both MIN(m1.msg) and MAX(m1.msg)

A: The problem is that after the first two joins you get this if im right:
Kungen  gregegerg       1   dc825b1c8a35593be4d172db7   jpg     1369839537
Kungen  HEJH            1   dc825b1c8a35593be4d172db7   jpg     1369839540

now with joining the friendrequests table on f1.contactid = users.id you join the requests for user 3 and 12 on both entries with the userid 1 resulting in:
Kungen  3   gregegerg       1   dc825b1c8a35593be4d172db7   jpg     1369839537
Kungen  12  gregegerg       1   dc825b1c8a35593be4d172db7   jpg     1369839537
Kungen  3   HEJH            1   dc825b1c8a35593be4d172db7   jpg     1369839540
Kungen  12  HEJH            1   dc825b1c8a35593be4d172db7   jpg     1369839540

Now to get the right result you would need to join the friendrequests table on something that connects with the message or timestamp as this is the only column that differs.


text:
Q: In Go, how do I capture stdout of a function into a string? In Python, for example, I can do the following:
realout = sys.stdout
sys.stdout = StringIO.StringIO()
some_function() # prints to stdout get captured in the StringIO object
result = sys.stdout.getvalue()
sys.stdout = realout

Can you do this in Go?

A: I agree you should use the fmt.Fprint functions if you can manage it. However, if you don't control the code whose output you're capturing, you may not have that option.
Mostafa's answer works, but if you want to do it without a temporary file you can use os.Pipe. Here's an example that's equivalent to Mostafa's with some code inspired by Go's testing package.
package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

func print() {
    fmt.Println("output")
}

func main() {
    old := os.Stdout // keep backup of the real stdout
    r, w, _ := os.Pipe()
    os.Stdout = w

    print()

    outC := make(chan string)
    // copy the output in a separate goroutine so printing can't block indefinitely
    go func() {
        var buf bytes.Buffer
        io.Copy(&buf, r)
        outC <- buf.String()
    }()

    // back to normal state
    w.Close()
    os.Stdout = old // restoring the real stdout
    out := <-outC

    // reading our temp stdout
    fmt.Println("previous output:")
    fmt.Print(out)
}

A: I think the whole idea is not advisable (race condition) at all, but I guess one can mess with os.Stdout in a way similar/analogical to your example.

A: This answer is similar to the previous ones but looks cleaner by using io/ioutil.
http://play.golang.org/p/fXpK0ZhXXf
package main

import (
  "fmt"
  "io/ioutil"
  "os"
)

func main() {
  rescueStdout := os.Stdout
  r, w, _ := os.Pipe()
  os.Stdout = w

  fmt.Println("Hello, playground") // this gets captured

  w.Close()
  out, _ := ioutil.ReadAll(r)
  os.Stdout = rescueStdout

  fmt.Printf("Captured: %s", out) // prints: Captured: Hello, playground
}

A: I don't recommend this, but you can achieve it with altering os.Stdout. Since this variable is of type os.File, your temporary output should also be a file.
package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
)

func print() {
    fmt.Println("output")
}

func main() {
    // setting stdout to a file
    fname := filepath.Join(os.TempDir(), "stdout")
    fmt.Println("stdout is now set to", fname)
    old := os.Stdout // keep backup of the real stdout
    temp, _ := os.Create(fname) // create temp file
    os.Stdout = temp

    print()

    // back to normal state
    temp.Close()
    os.Stdout = old // restoring the real stdout

    // reading our temp stdout
    fmt.Println("previous output:")
    out, _ := ioutil.ReadFile(fname)
    fmt.Print(string(out))
}

I don't recommend because this is too much hacking, and not very idiomatic in Go. I suggest passing an io.Writer to the functions and writing outputs to that. This is the better way to do almost the same thing.
package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

func print(w io.Writer) {
    fmt.Fprintln(w, "output")
}

func main() {
    fmt.Println("print with byes.Buffer:")
    var b bytes.Buffer
    print(&b)
    fmt.Print(b.String())

    fmt.Println("print with os.Stdout:")
    print(os.Stdout)
}

A: Even though the options listed above works, there is a clean approach in modern Go, that makes use of io.Pipe and io.Copy.
package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

// Your function
func some_function(w *io.PipeWriter) {
    defer w.Close()
    // Fill pipe writer
    fmt.Fprintln(w, "Hello World")
}

// main function
func main() {
    // create a pipe reader and writer
    pr, pw := io.Pipe()

    // pass writer to function
    go some_function(pw)

    // custom buffer to get standard output of function
    var b bytes.Buffer

    // create a multi writer that is a combination of
    // os.Stdout and variable byte buffer `b`
    mw := io.MultiWriter(os.Stdout, &b)

    // copies pipe reader content to standard output & custom buffer
    _, err := io.Copy(mw, pr)

    if err != nil {
        if err != io.EOF {
            panic(err)
        }
    }

    // use variable
    fmt.Println(b.String())
}

The above program works this way:

*

*Create a pipe that gives a reader and writer. It means, if you write something into pipe writer, will be copied to pipe reader by go

*Create a MultiWriter with  os.Stdout and custom buffer b

*some_function(as a go-routine) will write a string into pipe writer

*io.Copy will then copy content from pipe reader into multi-writer

*os.Stdout will receive the output as well as your custom buffer b

*Use buffer b
io package comes with all batteries included to work with io.Reader and io.Writer. No need to use os package, unless files are involved.
Running snippet:
https://goplay.tools/snippet/3NcLVNmbEDd


text:
Q: Azure - multiple virtual network gateways? Within Azure, can a single virtual network have two gateways, one for devices that are policy based, and the other for route based? If so, how?
As to why I'm asking: I need to connect a legacy network in a hosted data center that only provides a Cisco VPN tunnel that is static only. Now I can't do vnet to vnet connections.
This should be basic, but I'm having a heck of a time finding the answer.

A: As Drifter104 mention, you can connect multiple sites to the same VNet, but only through the same gateway (see here), you can't have multiple gateways on a single VNET. This is true currently both in Classic and ARM deployments.

A: Although this isn't an answer to the general use case there is a way to set up Azure to Azure VPN links which don't require the dynamic route based functionality.

*

*Define the two virtual network gateways using the policy based option.

*Define the two 'local network gateways' using the same IP addresses / names as the virtual gateways above.

*Define the connections using the site-to-site (ipsec) options.


text:
Q: Use .call when I instantiate a new class I try to call a function of classA inside my mainClass. And then I try to call functions of mainClass inside classA. I tried to use .bind() and .call() but it doesn't work. It only works if I use .bind(this) or .call(this) on functions, but not while I try to instantiate a new class.
index.js
let ClassA = require('./ClassA')

class mainClass {

    constructor() {
        this.doSomething()
    }

    doSomething() {
        let classA = new ClassA().call(this)
        classA.doSomething()
    }

    aFunction() {
        console.log('done')
    }

}

new mainClass()

classA.js
module.exports = class ClassA {

    constructor() {
    }

    doSomething() {
        console.log('doSomething')
        this.doSomething2()
    }

    doSomething2() {
        this.aFunction() // main Class
    }

}

TypeErrpr: this.doSomething2 is not a function

A: In a comment you've clarified what you're trying to do (it's also a code comment in the question):

How can I call aFunction() from classA then?

You'd do that by giving the code in ClassA access to your instance. You might pass it to the constructor which could save it as an instance property, or you might pass it to doSomething.
Here's an example passing it to the constructor:

class ClassA {

    constructor(obj) {           // ***
        this.obj = obj;          // ***
    }

    doSomething() {
        console.log('doSomething');
        this.doSomething2();
    }

    doSomething2() {
        this.obj.aFunction();    // ***
    }

}

class mainClass {

    constructor() {
        this.doSomething();
    }

    doSomething() {
        let classA = new ClassA(this);
        classA.doSomething();
    }

    aFunction() {
        console.log('done');
    }
}

new mainClass();


text:
Q: get new list which contain any numeric value from current list using LINQ query How to get new list which contain any numeric value from current list using LINQ query in c#.
??
i.e :
CurrentList  >> abc, bcd123, abcd, 332bcd
what I want : NewList  >> bcd123, 332bcd
What i have done in past:
 var newList= videos.Select(x => x.OldList.Contains("1"));

A: You can use Enumerable.Any to check if any character in string is number (with help of Char.IsNumber method):
var newList = videos.Where(x => x.OldList.Any(Char.IsNumber));

Another option is usage of regular expression:
var regex = new Regex(@"\d");
var newList = videos.Where(x => regex.IsMatch(x.OldList));

A: You can use Regular expression
 var newList= videos.Select(x => System.Text.RegularExpressions.Regex.IsMatch(x.OldList, @"\d"));


text:
Q: joint pdf of two statistically independent random variables Let A and B be statistically independent, identically distributed (iid)
random variables having chi-square distribution with four degrees of freedom.

*

*calculate the joint pdf for $X=\frac{A-B}{A+B}$ and $Y=A+B$

*calculate the marginal pdfs of X and Y

So I did the following:
The chi-square distribution with four degrees of freedom is given by $f_X(x) = \frac{1}{4}x e^{-x/2}$
Since A and B are statistically independent $f_{A,B} = f_A(a) \cdot f_B(b)=\frac{1}{16}a b e^{-\frac{a+b}{2}}$
So since $X=\frac{A-B}{A+B}$ and $Y=A+B$ I expressed that as $A=\frac{1}{2}(Y+XY)$ and $B=\frac{1}{2}(Y-XY)$
Now for the transformation I have to calculate the det. of the Jacobian matrix
$\det\begin{pmatrix} \frac{\partial \frac{1}{2}(Y+XY)}{\partial X}
 & \frac{\partial \frac{1}{2}(Y+XY)}{\partial Y} \\ \frac{\partial \frac{1}{2}(Y-XY)}{\partial X}
 & \frac{\partial \frac{1}{2}(Y-XY)}{\partial Y}\end{pmatrix} = \det\begin{pmatrix} 1/2 Y
 & 1/2[1+X] \\ -1/2 Y
 & 1/2[1-X]\end{pmatrix} = \frac{1}{2} Y$
So the joint pdf will be $f_{X,Y}(x,y) = f_{A,B}\left(\frac{1}{2}[y+xy], \frac{1}{2} [y-xy]\right) \cdot \frac{1}{2} Y = \frac{1}{128}y^3(1-x^2)e^{-y/2}$
When I now try to calculate the marginal density $f_Y(y) = \int_0^\infty \frac{1}{128}y^3(1-x^2)e^{-y/2} \, dx$ i have the problem that it doesn't converge
I would be thankful if someone could show me where my mistake is .

A: Thanks to @Henry I found out my mistakes, I used the wrong integration borders,
just for completeness i will answer my own question:
$f_X(x) = \int\limits_0^{\infty} \frac{1}{128}y^3(1-x^2)e^{-y/2}\, dy = \frac{3}{4} (1-x^2)$
$f_Y(y) = \int\limits_{-1}^{1} \frac{1}{128}y^3(1-x^2)e^{-y/2}\, dx = \frac{1}{96}y^3e^{-y/2}$
So we see $X$ and $Y$ are again statistically indepent since $f_{X,Y}(x,y) = f_X(x) \cdot F_Y(y)$
Thanks again Henry


text:
Q: Is there a way to derive sin/cos series from multiple angle formulas? I was reading about multiple angle formulas to expand $\sin{(nx)}$ or $\cos{(nx)}$ to be in terms of $\sin{x}$ and $\cos{x}$ on Wolfram MathWorld, and came across these formulas:

These formulas look so much like the Taylor series expansions of the respective functions that I feel there must be a way to further transform these equations into ones representing the value of $\sin{x}$ and $\cos{x}$. I would expect some form of calculus to come into play, but I'm not sure where I would even start. In other words, I want to start with the above formulas and algebraically manipulate them to get:
$$\sin{x}=x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}+\ldots$$
$$\cos{x}=1-\frac{x^2}{2!}+\frac{x^4}{4!}-\frac{x^6}{6!}+\ldots$$
The formulas come from T. J. I'A. Bromwich and T. M. MacRobert's book An Introduction to the Theory of Infinite Series, 3rd ed.

A: Yes, this is possible. Fix $t$ and write $a=t/n$ so that $x=\sin(t/n)$. In the last formula you cite from Bromwich (1991), for $n$ even
$$\cos t=1-\frac{(nx)^2}{2!}+ \frac{(nx)^4}{4!} (1-2^2/n^2)-\frac{(nx)^6}{6!}(1-2^2/n^2)(1-4^2/n^2)+\ldots \tag{*}$$
As $n \to \infty$, we have $nx=n\sin(t/n) \to t$ as $n \to \infty$, so the series (*) converges to the Taylor series for cosine, term by term. To control the error, observe that truncating the series after $k$ terms incurs an error of order $\frac{t^{2k}}{(2k)!}$, uniformly in $n$, so we may choose $k$ to ensure this truncation incurs an error less than $\epsilon/2$.   The first $k$ terms do indeed converge to the corresponding terms in the Taylor series as $n \to \infty$, so we may choose $n$ to ensure that the error in each of these terms is less than $\frac{\epsilon}{2k}$.
The other three formulas can be handled in the same way.


text:
Q: Firebase transaction. parent node or individual child nodes? I am trying to determine if my transaction pattern is correct in my Cloud Function. As I understand, you should limit updates to child nodes. So I've tried to follow that general rule.
/functions/index.js
//not rate limited
//writes:
// - board.posts+1
// - thread.replies+1
// - thread.pages+1 if page count should change Math.ceil(thread.replies+1/POSTS_PER_PAGE)=pages
exports.newPost2 = require('./lib/new-post-2')(functions,firebase,rootRef,POSTS_PER_PAGE);

/functions/lib/new-post-2.js
module.exports = function(functions,firebase,rootRef,POSTS_PER_PAGE){

    return functions.database.ref('/posts/{forum}/{board}/{thread}/{post}').onWrite(function(event){

        // Only edit data when it is first created.
        if (event.data.previous.exists()) {
            return;
        }
        // Exit when the data is deleted.
        if (!event.data.exists()) {
            return;
        }

        var params = event.params;
        var forum = params.forum;
        var board = params.board;
        var thread = params.thread;
        var post = params.post;

        //first increment the replies node of the thread.
        rootRef.child('threads').child(forum).child(board).child(thread).child('replies').transaction(function(data) {

            return data + 1;//increment reply count for thread.

        }).then(function(snapshot){
            //now, our snapshot should contain the updated value of replies.
            var replies = snapshot.val();

            //update the page count of the thread
            rootRef.child('threads').child(forum).child(board).child(thread).child('pages').transaction(function(data) {
                return Math.ceil(replies+1/POSTS_PER_PAGE);//replies is always +1 because OP of thread doesnt count as a reply.
            });

            //update the posts count for the board. this field is also updated by another firebase cloud function, when a thread is created
            rootRef.child('forums').child(forum).child('boards').child(board).child('posts').transaction(function(data){
                return data + 1;//increment post count for the board.
            });
        });

    });
};

I'm worried about possibly racing while updating page count of thread and post count of board after the initial reply field is incremented on thread. I'm wondering if there is a safer way I can restructure this to update all 3 fields within the first transaction, if its possible.


text:
Q: React way to use forms in html, submit action happens along with ajax request My usecase is of following.
I have some React component looking like that:
    var MyComponent = React.createClass({
        handleButton() {
           $.ajax..... post {this.state.inputData} to server
           error: console.log(url,error)
        },

        handleInputOnChange(event) {
           this.setState({inputData: event.target.value});
        },

        render: function () {
          return (
           <form>
             <input type="text" id="input1" onChange={this.handleInputOnChange}/>
             <button>apply</button>
           </form>
                  )
        }
    });

The problem is that when I push the button, the server gets the correct data, no errors in logs and everything seemingly goes fine, but the browser console shows an error: error, "" , strange stuff appears in the   address line looking like localhost:8080?input1= and the page reloads from the server, loosing all entered data.
Obviously html submit action happens along with ajax POST request though the <form> doesn't contain any url or other directions to do that.
I changed <form> tag in the component to <div> tag and the problem disappeared.
But my html developer told that all input data should be handled inside the <form> only, and I am very wrong and so went to the dark side.
Sorry for a dumb question, I'm still a beginner in frontend, but what is the right way to handle this?

A: If you are handling the request via ajax, you should prevent the default behaviour of the button click, meaning the form won't get submitted automatically.
So inside handleButton you would get the event object and call preventDefault:
handleButton(event) {
  event.preventDefault()
  $.ajax..... post {this.state.inputData} to server
  error: console.log(url,error)
}

This should stop a page refresh.


text:
Q: Changing the VTable of an external Class After a some googling I found a way to modify the VTable of a Class, but in my case I just have a pointer to my class as well as an interface to cast it to. I need to redirect one of those functions (in a DLL; no source code) to one of my functions. Problem is I don't know on which index the function is on, so in order to find it I tried scanning the VTable for the pointer to that function.
Is there any way to do this?
Here is my code so far:
typedef DWORD (__thiscall *CW_FUNC)();

class ClassWriter
{
public:
    PVOID m_hObj;
    PVOID *__vfptr;
    PVOID m_old[256];
    void SetObj(PVOID hObj)
    {
        m_hObj = hObj;
        __vfptr = *(PVOID **)hObj;
    }
    void AddOverride(int offset, PVOID newfunc)
    {
        DWORD dwNull;
        m_old[offset] = __vfptr[offset];
        VirtualProtect(__vfptr + offset * 4, 4, PAGE_EXECUTE_READWRITE, &dwNull);
        __vfptr[offset] = newfunc;
    }
    int GetOffset(PVOID func)
    {
        for (int i = 0; __vfptr[i] != NULL; i++)
        {
            if (func == __vfptr[i]) return i;
        }
    }
    CW_FUNC GetFunc(int offset)
    {
        return (CW_FUNC)m_old[offset];
    }
};

void WINAPI ChangeFunc()
{
    ClassWriter cw;
    HMODULE hMod = GetModuleHandle("dll_to_change.dll");
    IMyInterface *myObj = (IMyInterface*)GetProcAddress(hMod, "GetMyClass")();
    cw.SetObj(myObj);
    int d = cw.GetOffset(myObj->MyFunction);
    cw.AddOverride(d, OverrideFunction);
}

A: So for all that view this question and don't really know how to do it now:
I'm using ollydbg, but you can use any other debugger/dumper.
Best way of doing this is putting your code into a dll. Make sure to execute your function, else the compiler won't compile it (at least for me)
void OverrideFunction()
{
    HMODULE hMod = GetModuleHandle("mydll.dll"); // If not loaded yet use LoadLibrary()
    IMyInterface *myObj = (IMyInterface*)GetProcAddress(hMod, "GetMyObject")(); // Get the pointer to your object
    char buffer[64];
    sprintf_s(buffer, "0x%X", OverrideFunction); // Print position of current function into buffer
    MessageBox(0, buffer, "", 0);
    myObj->MyFunction(); // Put in your function
}

Now either execute your code until the MessageBox() and open that address in your debugger or if your compiler created an export function you can just go to YourDll.OverrideFunction
Look for a line below, that is something like this (if your compiler detects names)
CALL DWORD PTR DS:[<&USER32.MessageBoxA>]

or
CALL DWORD PTR [YourDll._imp__MessageBoxA]

the next CALL after that should be your class function, in my case:
CALL DWORD PTR DS:[EAX+34]

Your offset is 0x34 which would be 52 (remember always to calculate the hex numbers). To get the index in the VTable you have to divide by 4 (size of a pointer) which would be 13 in my case.
void __fastcall NewFunc(IMyInterface *myObj, int null, (additional params)) // fastcall stores the first 2 params int ECX and EDX, thiscall stores the this-object in ECX
{
//  Your code
}

void OverrideFunction()
{
    DWORD dwNull;
    HMODULE hMod = GetModuleHandle("mydll.dll"); // If not loaded yet use LoadLibrary()
    IMyInterface *myObj = (IMyInterface*)GetProcAddress(hMod, "GetMyObject")(); // Get the pointer to your object
    PVOID *vtable = *(PVOID**)myObj; // The first int in your object is a pointer to the vtable
//  OldFunc = vtable[13]; // You might want to call your old function again, so save the pointer
    VirtualProtect(&vtable[13], 4, PAGE_EXECUTE_READWRITE, &dwNull); // Always unprotect the memory
    vtable[13] = NewFunc;
}

Now everytime MyObject calls MyFunction, NewFunc will be executed instead


text:
Q: Apache server not responding in ec2 I have a flask application hosted on ec2 ubuntu instance and to serve the http request i also have apache and wsgi configured. However i am not able to access my application in ec2 and the request is getting timed out everytime.
enter image description here

A: On further investigation i found that apache is accepting request but i have used open cv in my code and the code functionality that uses open cv is taking a long amount of time.


text:
Q: Can't type or add blocks in the WordPress editor I'm currently on WordPress version 6.0, using Block Theme on Google Chrome.
When I try to add/edit a page/post, the following occurs.

*

*Added text appends before the placeholder "Add Title" in the title.

*The editor does not allow typing in the "Type / to choose a block" part, but if I click below it, I can add text that is appended to the muted text.
Third-party cookies and JavaScript are both enabled. I also tried clearing the entire time cache but was unable to address the problem.
I have also deactivated all the plugins but the problem persists.
It does, however, work flawlessly in Firefox. But I'm stumped as to why on Chrome it isn't working.
Thanks in advance!
Screenshot of the issue: https://i.stack.imgur.com/hrtYa.png


text:
Q: How to add a dynamic label in a VBA userform and assign a specific cell value? In the code below I am adding a label "dLblQty" on the click of save button on the userform. And this button needs to be assigned a value from Cell A27 then A28 and so on in each iteration of button press.
But this gives a Runtime error  '438': Object doesn't support this property or method.
Please suggest correct way of doing this.
Below is the snippet:
Dim strCap As String

strCap = Worksheets("Tax Invoice - Intra State").Range("A1").Value

Dim dLblQty As Control
Set dLblQty = UserForm1.Controls.Add("Forms.Label.1", "dLblQty", True)
With dLblQty
    .Top = 20
    .Left = 20
    .MultiLine = True
    .Height = 100
    .Caption = strCap
End With

A: The error is thrown because the Label control doesn't have a multiline property or method. The rest of the snippet functions perfectly.

A: The code certainly gives no errors on removing multiline and enterkeybehavior as these are textbox properties. But this didn't solve my problem of adding a dynamic label and dynamically assigning a cell value to it.
After trying a few times, I understood what I was doing wrong.
I declared my label as an object of MSForms.label class and this did the trick. Below is the solution:
Dim strCap As String
Dim dLblItem As MSForms.Label

strCap = Worksheets("Tax Invoice - Intra State").Range("B1").Value

Set dLblItem = UserForm1.Controls.Add("Forms.Label.1", "dLblItem", True)
With dLblItem
    .Top = 20
    .Left = 20
    '.MultiLine = True
    '.EnterKeyBehavior = True
    .Height = 100
    .Caption = strCap
    .BackColor = &HFF&
    .ForeColor = &H8000&
End With


text:
Q: How to get text response from alexa voice service I'm using following python library to query alexa voice service.
https://pypi.org/project/avs-client/
In request I send audio file and in response I receive audio file.

*

*How to get text response using the above mentioned library ?

*How to connect to AVS directly and get the text and audio response ?


text:
Q: disable or move keyboard-switching dialog while leaving functionality intact I have several keyboard/language layouts on my Windows 10 machine, and I frequently switch between them using Windows key + Shift. My issue is that when I'm sharing my screen in a meeting, every time I switch languages, the keyboard-switching window shown here comes up:

This can be distracting, especially to other people. Is there a way to continue to be able to switch layouts but suppress the keyboard-switching window, or control where it appears so I can move it to my auxiliary monitor (my laptop monitor), so that it won't be seen when I share my main monitor? I'm okay with the "language bar" display in my taskbar changing, just not the larger dialog.
Note that I do not define "hot keys for input languages" in the "Text Services and Input Languages" dialog (since this has never worked correctly for me, and since I would rather use Windows key + Shift rather than Ctrl-0, Ctrl-1, etc.). Thus, the key sequences for these are deliberately set to "None":

A: I used the approach suggested by @JosefZ in his comment, but I had to take some steps that were complicated enough that I wanted to mention them together with screenshots.
Here's a screenshot that shows the "Change Key Sequence" button (at the bottom); clicking on it brings up the dialog box that covers the one behind it.

Note that it's possible to add a sequence that changes the language, and/or a sequence that changes the layout, but you can't do a single cycle through all language/keyboard combinations as you can with the Win + space keys. This is actually fine with me, since I generally want to cycle through languages. (For English, I have a US and an International layout, but I usually only need to use the US.) None of the keys or key combinations worked for me other than the grave accent key, but that was also fine with me, even though it did mean that I had to come up with a new keyboard layout because I was already using a Grave + AltGr + Shift key combination.
Getting to the dialog that shows the "Change Key Sequence" button is surprisingly unstraightforward. Searching for it in the start menu didn't work. I had to go to "PC settings", then "Time & Language", then "Language", then "Input language hot keys":

I also recommend setting "Let me use a different input method for each app window". This makes things much simpler for me to work with, given that I often want to type in one language in one window and a different language in another. Now I don't have to change the language every time I go from one window to another.


text:
Q: MySQL/MariaDB TRIGGER I get an error when I try to create the below trigger on MySQL/MariaDB
CREATE TRIGGER `ABC` BEFORE INSERT ON `TABLE1`
FOR EACH ROW BEGIN
DECLARE LCL_VAR INTEGER;
SET LCL_LCL_VAR = NEW.A - NEW.B;
SET NEW.D= V;
END;

ERROR

CREATE TRIGGER Q_DUR_CALC BEFORE INSERT ON TASK_Q_SWH
FOR EACH ROW BEGIN
DECLARE LCL_Q_DUR INTEGER;
MySQL said: Documentation
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 3

I've got a couple other triggers that I used to build this one. I can't figure out what is wrong syntactically with this. Can I please request for help to spot the problem with this?

A: When you write a trigger you must specify a delimiter so that mysql explicitly executes your trigger block within the specified delimiter. If the delimiter is not provided then when it encounters any ; within the trigger statement it will try to execute the command till that block and hence you may get errors.
If you are using any user interface tools for generating the trigger you may check if there is an option to set the delimiter like in PHPMyadmin.
In CLI the trigger needs to be having a delimiter and it becomes
delimiter //

create trigger Q_DUR_CALC before insert on TASK_Q_SWH
for each row
begin
 declare LCL_Q_DUR INTEGER;
 set LCL_Q_DUR = new.TQ_TASK_DUR - new.TQ_TASK_RUN_DUR;
 SET new.TQ_Q_DUR = LCL_Q_DUR;
end;//

delimiter ;

A: The problem was with the ";" after END. Strange that it complained about line 3!!
Here is the corrected version
CREATE TRIGGER `Q_DUR_CALC` BEFORE INSERT ON `TASK_Q_SWH`
FOR EACH ROW BEGIN
DECLARE LCL_Q_DUR INTEGER;
SET LCL_Q_DUR = NEW.TQ_TASK_DUR - NEW.TQ_TASK_RUN_DUR;
SET NEW.TQ_Q_DUR = LCL_Q_DUR;
END


text:
Q: Cairo and Shoes in Ruby How do I use Cairo ta draw on a shoes window?
I am trying to start a school project for Computer Graphics. Can anybody post a simple code that draws a circle on a shoes window? I'd be very grateful. I have been searching for quite a while now... I've reached nowhere yet. so, please help me!! :)

A: I'm not sure how you would use Cairo in Ruby. It's not my area of expertise; however drawing circles in Shoes is not difficult at all. The following example allows circles to be created from mouse clicking and dragging.
Shoes.app do
    ox,oy = nil,nil
    click{|button, x, y| # on click, set the original x and y position
        if button == 1
            ox = x
            oy = y
        end
    }
    release{|button, x, y| #on mouse release, draw the circle
        if button == 1
            oval(
                :left => [ox, x].min, # furthest left point
                :top => [oy, y].min, # furthest top point
                :radius => ((ox-x).abs + (oy-y).abs) / 2 # the average of the positive difference between original and final x and y points
            )
        end
    }
end

Obviously, depending on your specific requirements, you will need to decide whether it is good enough.
In my experience, Shoes is a decent platform for making a broad range of low to medium power apps. However, if you're trying to build something substantial, like a graphics package, there are probably better solutions.


text:
Q: Android retrieving a TextView results in Null. Have setContentView; Used correct id; have activity in Maifest I'm getting a nullPointerE at run time, and have researched what problems could cause it, and I believe I suffer from none of them.
I believe the problem is that I have my layout in a fragment, and, though the app loads it correctly when I activate the intent, I think when I setContentView it doesn't find the view there.  I've tried setting the fragment as the content view, but it crashes then as well.  Also, I'm using a fragment for another screen and can access the view just fine.  I thought it might be accessing the string from the intent, but I confirmed that I'm getting a null object when I use findViewById with the if statement in the onCreate method.  The app runs just fine (without executing the inner code of course).
Here is my class:
public class Home extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    Intent prev = getIntent();
    String tipOfTheDay = prev.getStringExtra(Login.EXTRA_TIP);
    String welcome = prev.getStringExtra(Login.EXTRA_WELCOME);
    TextView welcomeScreen = (TextView) findViewById(R.id.textViewHome);
    if (welcomeScreen != null) {
        welcomeScreen.setText(welcome + "\n" + tipOfTheDay);
    }
}

Here is my activity_home.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.wingman.Home"
tools:ignore="MergeRootFrame" />

Here is my fragment_home.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.wingman.Home$PlaceholderFragment" >

<TextView
    android:id="@+id/textViewHome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="42dp"
    android:text="@string/empty" />

<ImageButton
    android:id="@+id/imageButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageButton1"
    android:layout_below="@+id/imageButton1"
    android:src="@drawable/ic_launcher"
    android:contentDescription="@string/q_button" />

<ImageButton
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageButton3"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="40dp"
    android:src="@drawable/ic_launcher"
    android:contentDescription="@string/calendar_button" />

<ImageButton
    android:id="@+id/imageButton3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/imageButton2"
    android:layout_centerHorizontal="true"
    android:src="@drawable/ic_launcher"
    android:contentDescription="@string/tips_button" />

<ImageButton
    android:id="@+id/imageButton4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageButton3"
    android:layout_below="@+id/imageButton3"
    android:src="@drawable/ic_launcher"
    android:contentDescription="@string/texts_button" />

Here is my manifest:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.wingman"
    android:versionCode="1"
    android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.wingman.Login"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.example.wingman.Home"
        android:label="@string/title_activity_home" >
    </activity>
</application>

Thanks for looking.  I'm trying to do more research on fragments, but I honestly don't know if that's even the cause.

A: Your TextView is in the fragment xml, but when you are calling
TextView welcomeScreen = (TextView) findViewById(R.id.textViewHome);

it's looking for in the activity_home.xml

A: Try this to set your TextView
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_home, null)
TextView textView = (TextView) view.findViewById(R.id.textViewHome);

EDIT You can check this link for a tutorial on fragments


text:
Q: Passport.js - browser GET requests are OK, but AJAX requests from JS code are not? I have configured Passport on a Node.js server and am using the Twitter auth strategy primarily.
I am confused by a recent discovery that seems to suggest that a GET request with a browser URL (using the web browser searchbar) seems to be authenticated differently than a AJAX request from inside the application code. For example, if I login with Passport, I can access everything by pointing my browser to certain urls that make a request directly to the backend server. But any request by Angular or jQuery to the backend API seems to be unauthorized.
Could this be at all correct? If so, how would Passport know the difference between a browser request and the AJAX request from inside the JS code?

A: By default, a cross-origin XHR request won't include cookies (which are normally used to maintain state in applications that require authentication).
You can change that by setting withCredentials:
var xhr = new XMLHttpRequest();
xhr.open(...);
xhr.withCredentials = true;

You may need to adjust the CORS rules on the server to say Access-Control-Allow-Credentials: true.
See also MDN.

A: The Twitter auth strategy requires that the user be signed into Twitter and has allowed your "app" permission to access your Twitter account information. This cannot be done with a XHR because how would the user enter their Twitter credentials to log into Twitter if the user wasn't already signed in? How would the user approve the permissions your Twitter "app" is requesting if the request is sent via XHR?
This applies to all of the Passport strategies that utilize OAuth or OpenID. The user's browser has to go directly to the auth provider's site so that they can either A) login to the auth provider or B) approve the permissions you're requesting in your application. Once the user has done that the auth provider (in your case Twitter) will then redirect the user's browser back to your application's endpoint with some kind of token which your application will then use to request information from the auth provider (such as email address, full name, etc.)


text:
Q: Help with SPF record setup for multiple domains? I have setup a mail server where the host name is mail.mail-apps.com. I have setup a wild card entry in my DNS for the IP address. The mail cname point to the wild card. I then setup an mx record that points to mail.mail-apps.com
I will have multiple domains that I will point to the IP address of the mail server. so, for example: mail.somedomain.com will point to the IP address of the mail server. In my mail server I setup a domain alias that will pick up the mail.somedomain.com. I can only have 1 IP and 1 HostName for my mail server.
For mail.mail-apps.com and the mail.somedomain.com, how do I setup my SPF records? I am so lost on how it works.
I am using hMailServer on a windows 2008 server.

A: SPF records will be created in each domain that the users on the server will be sending from.  So, for instance, when you send from user@mail-apps.com, a receiving server will check the SPF record for mail-apps.com.  If your mail-apps.com server sends a message from a user with an email address of user@customerdomain.com, the SPF record for customerdomain.com is what it will check.
So, given that you've just got the one server that will be doing the sending, an example SPF record would look like this:
v=spf1 a:mail.mail-apps.com ~all
This would authorize whatever host resolves at mail.mail-apps.com to send mail for that domain.
You'd want to put this entry in each domain that your server would be sending mail for.


text:
Q: Testing TapGesture with 6 repeats (iOS and Swift) This might be a fun one.  I'm setting up UI testing in XCode.
One part of my app requires the user to tap on the screen 6 times to perform a particular action.  The code is below.
        let tapGesture = UITapGestureRecognizer(target: self,action:#selector(self.doSomething(_:)))
        tapGesture.numberOfTapsRequired = 6
        aView.addGestureRecognizer(tapGesture)

Where I am having trouble is testing this gesture recognizer.  The following code is created by the test recorder, but doesn't work when just tested.
    let app = XCUIApplication()
    let elem = app.otherElements.containingType(.Image, identifier:"elementName").element
    elem.tap()
    elem.tap()
    elem.tap()
    elem.tap()
    elem.tap()
    elem.tap()

I even tried adding a slight delay between each element (about I've tried values between 1.0 and 0.02 seconds), but nothing seems to actually work.
Any thoughts?

A: Here is what I've found so far.  At its fastest, a tap takes a little over one second in the UI tester, which is WAY too long (not even close by a wide margin).  So I had to make a workaround (aka: a hack)
Here is my work-around.

*

*IN the UITests target I added an "Other Swift Flags" "-D TEST".  Now from my code I can use preprocessor checks in my main project.  '#if TEST'.

*I added a button to the ui on the view in question.  Wired it via a standard "touch up inside" event handler.

*In my view controller I did something like this:
#if !TEST
myButton.hidden = true
#endif

*Modified my UI test code to find that button and do a simple tap instead.


text:
Q: Using vuejs with existing html I have a list of elements, rendered server-side.
Each item has a button that changes its status.

Item 1

    <form method="post" class="list-item-form">

        <input type="submit" name="changeStatus" class="button-unpublish" value="Unpublish">

    </form>

Item 2

    <form method="post" class="list-item-form">

        <input type="submit" name="changeStatus" class="button-unpublish" value="Unpublish">

    </form>

I'm using the following code to replace each item with a vue component
var ms = document.querySelectorAll('.vue-mount')
for (var i = 0; i < ms.length; i++) {
  new Vue({
    render: h => h(SubscriptionButton)
  }).$mount(ms[i])
}

And on the component i get the values of data-is-published and data-item-id and set them on the component
<template>
  <input
  type="submit"
  @click.prevent="changeStatus()"
  :value="isPublished === 1 ? 'Unpublish' : 'Publish'">
</template>


text:
Q: SonarQube rules are not getting detected I'm a big fan of SonarQube as a developer. This time though I need to do admin work since I need to configure it from a fresh install. I see this rule in SonarQube "Methods should not have too many lines" but I don't see that it belongs to any of the default profiles ("FindBugs+FB-Contrib", "Sonar Way"). I think that's the reason I don't see any rule violations of this type from any of the projects. I thought this should be part of a common default profile since this is a pretty common violation. How can I add this rule to the profile?
There are other rules that I need to add which I expected also to be in the default/available profiles already.

A: You can't edit built-in profiles. Instead, you'll have to create a new profile, and then you'll be able to edit the rules to your heart's content. I suggest you initialize your new profile either by copying the rules from the built-in profile of your choice, or by inheriting from that profile. Note that choosing the latter means your profile can (and probably will) be updated by upgrading your analyzers; each new version of SonarJava, for instance, implements new rules and many of them are added to the Sonar way profile.


text:
Q: Naming returned columns in Pandas aggregate function? I'm having trouble with Pandas' groupby functionality. I've read the documentation, but I can't see to figure out how to apply aggregate functions to multiple columns and have custom names for those columns.
This comes very close, but the data structure returned has nested column headings:
data.groupby("Country").agg(
        {"column1": {"foo": sum()}, "column2": {"mean": np.mean, "std": np.std}})

(ie. I want to take the mean and std of column2, but return those columns as "mean" and "std")
What am I missing?

A: If you want to have a behavior similar to JMP, creating column titles that keep all info from the multi index you can use:
newidx = []
for (n1,n2) in df.columns.ravel():
    newidx.append("%s-%s" % (n1,n2))
df.columns=newidx

It will change your dataframe from:
    I                       V
    mean        std         first
V
4200.0  25.499536   31.557133   4200.0
4300.0  25.605662   31.678046   4300.0
4400.0  26.679005   32.919996   4400.0
4500.0  26.786458   32.811633   4500.0

to
    I-mean      I-std       V-first
V
4200.0  25.499536   31.557133   4200.0
4300.0  25.605662   31.678046   4300.0
4400.0  26.679005   32.919996   4400.0
4500.0  26.786458   32.811633   4500.0

A: For pandas >= 0.25
The functionality to name returned aggregate columns has been reintroduced in the master branch and is targeted for pandas 0.25. The new syntax is .agg(new_col_name=('col_name', 'agg_func'). Detailed example from the PR linked above:
In [2]: df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
   ...:                    'height': [9.1, 6.0, 9.5, 34.0],
   ...:                    'weight': [7.9, 7.5, 9.9, 198.0]})
   ...:

In [3]: df
Out[3]:
  kind  height  weight
0  cat     9.1     7.9
1  dog     6.0     7.5
2  cat     9.5     9.9
3  dog    34.0   198.0

In [4]: df.groupby('kind').agg(min_height=('height', 'min'),
                               max_weight=('weight', 'max'))
Out[4]:
      min_height  max_weight
kind
cat          9.1         9.9
dog          6.0       198.0

It will also be possible to use multiple lambda expressions with this syntax and the two-step rename syntax I suggested earlier (below) as per this PR. Again, copying from the example in the PR:
In [2]: df = pd.DataFrame({"A": ['a', 'a'], 'B': [1, 2], 'C': [3, 4]})

In [3]: df.groupby("A").agg({'B': [lambda x: 0, lambda x: 1]})
Out[3]:
         B
  <lambda> <lambda 1>
A
a        0          1

and then .rename(), or in one go:
In [4]: df.groupby("A").agg(b=('B', lambda x: 0), c=('B', lambda x: 1))
Out[4]:
   b  c
A
a  0  0

For pandas < 0.25
The currently accepted answer by unutbu describes are great way of doing this in pandas versions <= 0.20. However, as of pandas 0.20, using this method raises a warning indicating that the syntax will not be available in future versions of pandas.
Series:

FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version

DataFrames:

FutureWarning: using a dict with renaming is deprecated and will be removed in a future version

According to the pandas 0.20 changelog, the recommended way of renaming columns while aggregating is as follows.
# Create a sample data frame
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
                   'B': range(5),
                   'C': range(5)})

# ==== SINGLE COLUMN (SERIES) ====
# Syntax soon to be deprecated
df.groupby('A').B.agg({'foo': 'count'})
# Recommended replacement syntax
df.groupby('A').B.agg(['count']).rename(columns={'count': 'foo'})

# ==== MULTI COLUMN ====
# Syntax soon to be deprecated
df.groupby('A').agg({'B': {'foo': 'sum'}, 'C': {'bar': 'min'}})
# Recommended replacement syntax
df.groupby('A').agg({'B': 'sum', 'C': 'min'}).rename(columns={'B': 'foo', 'C': 'bar'})
# As the recommended syntax is more verbose, parentheses can
# be used to introduce line breaks and increase readability
(df.groupby('A')
    .agg({'B': 'sum', 'C': 'min'})
    .rename(columns={'B': 'foo', 'C': 'bar'})
)

Please see the 0.20 changelog for additional details.
Update 2017-01-03 in response to @JunkMechanic's comment.
With the old style dictionary syntax, it was possible to pass multiple lambda functions to .agg, since these would be renamed with the key in the passed dictionary:
>>> df.groupby('A').agg({'B': {'min': lambda x: x.min(), 'max': lambda x: x.max()}})

    B
  max min
A
1   2   0
2   4   3

Multiple functions can also be passed to a single column as a list:
>>> df.groupby('A').agg({'B': [np.min, np.max]})

     B
  amin amax
A
1    0    2
2    3    4

However, this does not work with lambda functions, since they are anonymous and all return <lambda>, which causes a name collision:
>>> df.groupby('A').agg({'B': [lambda x: x.min(), lambda x: x.max]})
SpecificationError: Function names must be unique, found multiple named <lambda>

To avoid the SpecificationError, named functions can be defined a priori instead of using lambda. Suitable function names also avoid calling .rename on the data frame afterwards. These functions can be passed with the same list syntax as above:
>>> def my_min(x):
>>>     return x.min()

>>> def my_max(x):
>>>     return x.max()

>>> df.groupby('A').agg({'B': [my_min, my_max]})

       B
  my_min my_max
A
1      0      2
2      3      4

A: This will drop the outermost level from the hierarchical column index:
df = data.groupby(...).agg(...)
df.columns = df.columns.droplevel(0)

If you'd like to keep the outermost level, you can use the ravel() function on the multi-level column to form new labels:
df.columns = ["_".join(x) for x in df.columns.ravel()]

update:
in newer pandas instead of .ravel() use .tolist() or .to_numpy() use df.columns = ["_".join(x) for x in df.columns.tolist()]

For example:
import pandas as pd
import pandas.rpy.common as com
import numpy as np

data = com.load_data('Loblolly')
print(data.head())
#     height  age Seed
# 1     4.51    3  301
# 15   10.89    5  301
# 29   28.72   10  301
# 43   41.74   15  301
# 57   52.70   20  301

df = data.groupby('Seed').agg(
    {'age':['sum'],
     'height':['mean', 'std']})
print(df.head())
#       age     height
#       sum        std       mean
# Seed
# 301    78  22.638417  33.246667
# 303    78  23.499706  34.106667
# 305    78  23.927090  35.115000
# 307    78  22.222266  31.328333
# 309    78  23.132574  33.781667

df.columns = df.columns.droplevel(0)
print(df.head())

yields
      sum        std       mean
Seed
301    78  22.638417  33.246667
303    78  23.499706  34.106667
305    78  23.927090  35.115000
307    78  22.222266  31.328333
309    78  23.132574  33.781667

Alternatively, to keep the first level of the index:
df = data.groupby('Seed').agg(
    {'age':['sum'],
     'height':['mean', 'std']})
df.columns = ["_".join(x) for x in df.columns.ravel()]

yields
      age_sum   height_std  height_mean
Seed
301        78    22.638417    33.246667
303        78    23.499706    34.106667
305        78    23.927090    35.115000
307        78    22.222266    31.328333
309        78    23.132574    33.781667

A: I agree with the OP that it seems more natural and consistent to name and define the output columns in the same place (e.g. as is done with tidyverse's summarize in R), but a work-around in pandas for now is to create the new columns with desired names via assign before doing the aggregation:
data.assign(
    f=data['column1'],
    mean=data['column2'],
    std=data['column2']
).groupby('Country').agg(dict(f=sum, mean=np.mean, std=np.std)).reset_index()

(Using reset_index turns 'Country', 'f', 'mean', and 'std' all into regular columns with a separate integer index.)

A: With the inspiration of @Joel Ostblom
For those who already have a workable dictionary for merely aggregation, you can use/modify the following code for the newer version aggregation, separating aggregation and renaming part. Please be aware of the nested dictionary if there are more than 1 item.
def agg_translate_agg_rename(input_agg_dict):
    agg_dict = {}
    rename_dict = {}
    for k, v in input_agg_dict.items():
        if len(v) == 1:
            agg_dict[k] = list(v.values())[0]
            rename_dict[k] = list(v.keys())[0]
        else:
            updated_index = 1
            for nested_dict_k, nested_dict_v in v.items():
                modified_key = k + "_" + str(updated_index)
                agg_dict[modified_key] = nested_dict_v
                rename_dict[modified_key] = nested_dict_k
                updated_index += 1
    return agg_dict, rename_dict

one_dict = {"column1": {"foo": 'sum'}, "column2": {"mean": 'mean', "std": 'std'}}
agg, rename = agg_translator_aa(one_dict)

We get
agg = {'column1': 'sum', 'column2_1': 'mean', 'column2_2': 'std'}
rename = {'column1': 'foo', 'column2_1': 'mean', 'column2_2': 'std'}

Please let me know if there is a smarter way to do it. Thanks.

A: such as this kind of dataframe, there are two levels of thecolumn name:
 shop_id  item_id   date_block_num item_cnt_day
                                  target
0   0       30          1            31

we can use this code:
df.columns = [col[0] if col[-1]=='' else col[-1] for col in df.columns.values]
result is:
 shop_id  item_id   date_block_num target
0   0       30          1            31