Does the transformation $a_n \leadsto \frac{a_n}{1+a_n}$ unconditionally preserve divergence of a series?

Question: If $\sum{a_{n}}$ is divergent, prove that $\sum\frac{a_{n}}{1+a_{n}}$ is divergent.
Is this always true? Because I found in the books this is just when $a_{n}>0$, and when I use $a_{n}=(r_{1},r_{2},-1,r_{4},-1,...)$, can we still say that the second series is divergent? Where $r_{i}$ can be any real such that $(a_{n})$ converges to zero. (The position of the $-1$ doesn't matter, it is just there to make the second series not defined).
Comment: Series, not sequence, @Clarinetist!
Comment: But $a_{n} = (1)$ isn't divergent, is it? - so you haven't found a counterexample.
Comment: Sorry it was -1. So the sequence is not even defined, that was my question if we can consider that case as divergence.
Comment: $a_n = (-1)$ isn't divergent, is it?
Comment: Are we given that $a_n$ are all positive?
Comment: -1-1-1-1 goes to -infinity
Comment: Oops, thanks @TedShifrin!
Comment: @JorgeRamos The question is undefined if any $a_n=-1$.
Comment: you are right, my mistake but consider a sequence that goes to zero, but has -1, everywhere then.
Comment: $a_{n}$ could be any real.
Comment: Related: http://math.stackexchange.com/questions/480931/proving-sum-n-geq-1-fraca-n1-a-n-diverges-provided-sum-a-n-diverg .
Comment: @JorgeRamos You can't have $(a_n)=(r_1,r_2,-1,r_4,-1,\ldots)$ because then some $n$ has $a_n=-1$ and so $-1/0$, an element of the partial sum, is *undefined*. The question is undefined if *any* $a_n=-1$.
Comment: That was my question, more like a philosophical question, because the definition of converge of series says that if the limit exist and is finite, but that would imply that if the limit doesn't exist the series not convergence.
Answer: This is not always true. Let us take $a_n=\frac{1}{n}+\frac{(-1)^n}{\sqrt{n}}$. The series $\sum a_n$ obviously diverges, but $$\frac{a_n}{1+a_n}=a_n-a_n^2+O(a_n^3)=\frac{1}{n}+\frac{(-1)^n}{\sqrt{n}}-\left(\frac{1}{n}+\frac{(-1)^n}{\sqrt{n}}\right)^2+O\left(\frac{1}{n^{3/2}}\right)=\frac{(-1)^n}{\sqrt{n}}+O\left(\frac{1}{n^{3/2}}\right),$$ so $\sum \frac{a_n}{1+a_n}$ converges.
Answer: If $a_n < 1$,
$\frac{a_n}{1+a_n}
> \frac{a_n}{2}
$.
If $a_n \ge 1$,
$\frac{a_n}{1+a_n}
\ge \frac{1}{2}
$.
The sum of either of these diverge.
Comment: If a_n <0 , a_n/(1+a_n) > a_n/2 is not always true. I think you are assuming a_n >0


How to check whether a 3D point is left or right of a vector

Question: I am making a pathfinding AI based off a waypoint graph using DirectX. I have a car with a forwards vector to tell me which direction it's facing. The car will always move in the XZ plane, and never change it's Y coordinate. I want to tell the car to turn right if the next waypoint is on it's right, and the opposite for left. This is the current code that I have for the pathfinding function, and what I'm currently doing to check right (which is incorrect)
void Car::Pathfinding(XMVECTOR forwards)
{
    int nextNode;
    if(currentNode + 1 > waypoints->size())
        nextNode = 0;
else
    nextNode = currentNode + 1;

    Accelerate();
    if(onRightOf(forwards, waypoints->at(nextNode)))
        TurnLeft();
    else if(onLeftOf(forwards, waypoints->at(nextNode)))
        TurnRight();

        //SquaredDisplacement is just Pythagoras's theorem without sqrt
    if(squaredDisplacement(waypoints->at(nextNode)) < 100)
        currentNode = nextNode;
}
bool Car::onRightOf(XMVECTOR forwards, XMFLOAT3 b)
{
    forwards = XMVector3AngleBetweenVectors(forwards, XMLoadFloat3(&b));
    XMStoreFloat3(&b, forwards);
    if(b.x <= XM_PI / 4) //So it doesn't have to be exact
                         //The onLeftOf has a >= instead of <=
        return false;
    return true;
}

I'm aware that XMVector3AngleBetweenVectors will always return positive, although it would be stellar if it didn't.
Answer: Let's vector
CB = b - CurrentPosition

(I don't see a variable for curr. pos. in your code)
then find sign of expression (it is Y-component of vector product, like cross-product)
forwards.X * CB.z -forwards.X * CB.X

If it is positive, B is left to current path, if negative - to right


mechanize and redirecting (ruby)

Question: I thought that mechanize follows redirection by default ... by my script ends at the redirection page. How can I handle this?
require 'rubygems'
require 'mechanize'

agent = WWW::Mechanize.new

page = agent.get("http://www.vbulletin.org/forum/index.php")

login_form = page.form_with(:action => 'login.php?do=login')

login_form['vb_login_username'] = 'user name'
login_form['vb_login_password'] = ''
login_form['vb_login_md5password_utf'] = 'md5 hash from the password'
login_form['vb_login_md5password'] = 'md5 hash from the password'

page = agent.submit login_form

#Display welcome message if logged in
puts page.parser.xpath("/html/body/div/table/tr/td[2]/div/div").xpath('text()').to_s.strip

output = File.open("login.html", "w") {|f| f.write(page.parser.to_html) }

redirection page html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

    <meta http-equiv="Refresh" content="2; URL=http://www.vbulletin.org/forum/index.php">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="generator" content="vBulletin 3.6.12">
<meta name="keywords" content="vbulletin,forum,bbs,discussion,jelsoft,bulletin board,hacks,modifications,addons,articles,programming,site review">
<meta name="description" content="This is a discussion forum powered by vBulletin. To find out about vBulletin, go to http://www.vbulletin.com/ .">
<link rel="stylesheet" type="text/css" href="clientscript/vbulletin_css/style-befeb917-00023.css" id="vbulletin_css">
<link rel="stylesheet" type="text/css" href="clientscript/blue.css" id="blue">
<link rel="alternate" type="application/rss+xml" title="vBulletin.org Forum RSS Feed" href="external.php?type=RSS2">
<title>vBulletin.org Forum</title>

<form action="http://www.vbulletin.org/forum/index.php" method="post" name="postvarform">

Redirecting...

Thank you for logging in, my username.

Click here if your browser does not automatically redirect you.

</form>

Answer: There is an option in mechanize for that. Mechanize does not follow meta refreshes by default, we can set that option though.
agent.follow_meta_refresh = true

Comment: Nice! I didn't know about that either.
Answer: Are you sure it's HTTP 30x Redirect response? Not normal "200 OK" response with page containing <meta http-equiv="refresh" content="100;url=...">. Mechanize follows first type of redirection, second is just normal response with link, which you should follow.
I can't check, because you didn't posted username/password in code.
Edit:
After your update, this should be enough to follow redirection after login:
page.link_with(:text => "Click here if your browser does not automatically redirect you.").click

Comment: @MBO: how can I check what type it is? I do not have to click anything in my browser, the page refreshes itself. I added the redirection page html in my question. Can I ask how do you know what type of redirection mechanize follows?
Comment: @Radek your other option would be to just have mechanize get "http://www.vbulletin.org/forum/index.php" (or rather the href of the link @MBO mentioned) after you've been sent to this page.
Comment: that's definitely the way how to solve it ... I found something else. See my answer

mechanize and redirecting (ruby)


none static nested class inside static class c#

Question: consider this scenario
Public static Class GlobalParam
{
//static classes strings int and more...
  class NoneStaticClass
  {
    //some noneStatic params
  }
}

in another class ( none static ) I call for an instance of NoneStaticClass in this fashion
GlobalParam.noneStaticClass NSC = new GlobalParam.noneStaticClass();

//some manipulation on NSC params

Later I use Method Like that
void DoSomething(GlobalParam.noneStaticClass nsc)
{
  GlobalParam.noneStaticClass NewNSC = nsc
  //Some manipulation in NewNSC
}

now when I check the data stored in NSC I can clearly that it has been changed , why is that ?
does putting none static class inside a static is not correct in some way ?
Comment: I think this question is entirely unrelated to static-ness. This is about references to instances vs. deep copying of instances.
Comment: Can you make your example more clear? That is, include a simple program that shows the whole flow of logic? It's not entirely clear what you're doing here (e.g. are you passing `NSC`  as a parameter to `DoSomething()`?
Comment: Please explain what you are trying to achieve, as I think the method your trying is not suitable to the problem
Comment: Looks like you're just passing around the same instance of NoneStaticClass. Naming the variable `NewNSC` in that method doesn't make it a new one.
Comment: Thank you all and you probably right that it is a dup , but I've never encountered this problem before , and now  I can tell it is wrong !
Comment: ... or [this](http://stackoverflow.com/questions/16696448/how-to-make-a-copy-of-an-object-in-c-sharp) or [this](http://stackoverflow.com/questions/78536/deep-cloning-objects) or [this](http://stackoverflow.com/questions/5843958/how-to-make-a-copy-of-a-reference-type) or [this](http://stackoverflow.com/questions/20698361/cloning-a-reference-type) ...
Comment: Nesting classes is almost never a good idea. And the nesting and static are unrelated to the core of your question.
Answer: Whatever your class is nested or normal class, whenever you do an assignement like  GlobalParam.noneStaticClass NewNSC = nsc, NewNSC and nsc will always reference the same object.
If you want a copy of your nsc object, here are some ways to do it :

If your class has all members with value type, you can use a struct
instead of class. It will be copied each time you make an assignment
with.
If not, you should referer to object cloning
Comment: yes without some `Clone()` like call, no hope
Answer: This is because your are not creating a new instance of the class when you write GlobalParam.noneStaticClass NewNSC = nsc you are merely assigning a reference to the existing NSC object to the new variable NewNSC. Therefore when you call NewNSC you are calling the same object as NSC.
In order to create a new instance of the object you would need to do this:
GlobalParam.noneStaticClass NewNSC = new GlobalParam.noneStaticClass();


A Custom Tab bar with two images in each tab using react navigation?

Question:
I am creating an app using React Native for ios. Instead of having an active tintColor I want to have two little triangles (another image/icon) which appears when you are on the selected tab. It is important that the center y axis of the triangles is = to the y axis of the bottom of the tabbar image and that the tab icon is in the center of the triangles as seen below. At the moment I have the tab bar, the icons and navigation working - I just don't know how to make the triangles appear:
ICON TABS
import React, {Component} from 'react';
import {
     Image,
     TouchableOpacity,
     View
} from 'react-native';

class IconTab extends Component {
    render() {
        let icon = require('./Assets/Settings.png');
        const {press, focused, index} = this.props;
        if (index === 0) {
           icon = require('./Assets/Settings.png');
        } else if (index === 1) {
           icon = require('./Assets/Home.png');
        } else if (index === 2) {
           icon = require('./Assets/Search.png');
        } else if (index === 3) {
          icon = require('./Assets/Inbox.png');
        } else {
          icon = require ('./Assets/Profile.png');
        }
        return (
            <TouchableOpacity onPress={press}>
                <Image source={icon} resizeMode={'contain'}/>
            </TouchableOpacity>
        );
     }
  }
 export default IconTab;

TAB BAR
import React, { Component } from 'react';
import { View, Platform, StyleSheet, Image, TouchableOpacity } from 'react
native';
import {SafeAreaView} from 'react-navigation';
import IconTab from "./IconTab";

class TabBar extends Component {
   render() {
     const {
        navigation,
        jumpToIndex,
     } = this.props;
     const {
        routes
     } = navigation.state;
     return (
        <SafeAreaView forceInset={{ top: 'always' }}>
           <View style={styles.tabbarcontainer}>
               <Image
                  style={styles.bg}
                  source={require('./Assets/Header.png')}
                  resizeMode={'stretch'}/>
               <View style={styles.tabbar}>
                  {routes && routes.map((route, index) => {
                  const focused = index === navigation.state.index;
                  const tabKey = route.key;
                return <IconTab
                      press={() => jumpToIndex(index)}
                      key={route.key}
                      index={index}
                      focused={focused}
                      />
                   })}
               </View>
            </View>
         </SafeAreaView>
       );
     }
  }

 const styles = StyleSheet.create({
    tabbarcontainer: {
       height: 50,
    },
    bg: {
       position: 'absolute',
       width: '100%',
       height: 44,
       alignSelf: 'center',
    },
    tabbar: {
       margin: 5,
       height: 34,
       flexDirection: 'row',
       justifyContent: 'space-around',
       alignItems: 'center',
       alignContent: 'center',
       backgroundColor: 'transparent',
       borderTopColor: 'transparent',
    },

 });

 export default TabBar;

THE TAB NAVIGATOR
import {TabNavigator} from 'react-navigation';
import TabBar from "./TabBar";
import Settings from "./Settings";
import Home from "./Home";
import Search from "./Search";
import Inbox from "./Inbox";
import Profile from "./Profile";

export const TabRouter = TabNavigator({
    Settings: {
            screen: Settings,
    },
    Home: {
            screen: Home,
    },
    Search: {
            screen: Search,
    },
    Inbox: {
            screen: Inbox,
    },
    Profile: {
            screen: Profile,
    },
 }, {

    initialRouteName: 'Home',
    tabBarComponent: TabBar,
    tabBarPosition: 'top',

 });

App.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';

import {TabRouter} from "./Components/TabRouter";

export default class App extends Component {
   render() {
      return <TabRouter/>;
    }
}

The reference I used to build this is https://github.com/tuanson45/react-native-custom-tab
I really appreciate any replies and help with this!
Thanks
Comment: Did you already manage to get this working?
Comment: Yes I have a solution. I will write it below.
Answer: TABBAR
import React, { Component } from 'react';
import { View, Platform, StyleSheet, Image, TouchableOpacity } from 'react-
native';
import {SafeAreaView} from 'react-navigation';
import IconTab from "./IconTab";

class TabBar extends Component {
  render() {
    const {
      navigation,
      jumpToIndex,
    } = this.props;
    const {
      routes
    } = navigation.state;
    return (
        <SafeAreaView style={{zIndex: 10}} forceInset={{ top: 'always' }}>
          <View style={styles.tabbarcontainer}>
                <Image
                   style={styles.bg}
                   source={require('./Assets/Header.png')}
                   resizeMode={'stretch'}/>
            <View style={styles.tabbar}>
              {routes && routes.map((route, index) => {
                const focused = index === navigation.state.index;
                const tabKey = route.key;
                return <View key={route.key} style={{ alignItems: 'center' }}>
                  <IconTab
                    press={() => jumpToIndex(index)}
                    key={route.key}
                    index={index}
                    focused={focused}
                  />
                  {focused && <Image source= {require('./Assets/Triangles.png')}
                                     style={{ position: 'absolute', top: 38 }} />}
                </View>;
              })}
            </View>
          </View>
      </SafeAreaView>
       );
    }
}

const styles = StyleSheet.create({
  tabbarcontainer: {
    height: 44,
  },
  bg: {
    position: 'absolute',
    width: '100%',
    height: 44,
    alignSelf: 'center',
  },
  tabbar: {
    margin: 5,
    height: 34,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    alignContent: 'center',
    backgroundColor: 'transparent',
    borderTopColor: 'transparent',
  },

});

export default TabBar;

Comment: Thanks, best of luck with your app! Your code has been very helpful since I am also designing a custom tab bar.
Comment: I am so glad to help! I spent weeks trying to find solutions! Custom tab bars are tricky! Best of luck to you too :)


Linear independent or linear dependent?

Question: I am not sure to say if the following set is independent:
$$ \{1, \sin x, \cos x\}$$
I would say they are independent because after an analysis of the coefficients in the linear combination equal zero, the only setting possible are when they are all equal zero.
How should I prove this?
Comment: What is your field of coefficients? Because if, for instance, it's the field of elementary functions, then (under most reasonable definitions of elementary functions), they are linearly dependent.
Comment: Well, if "*after an analysis of the coefficients in the linear combination equal zero, the only setting possible are when they are all equal zero*" means what it looks to mean, then you have proved it.
Answer: HINT: write $$\alpha+\beta\sin(x)+\gamma\cos(x)=0$$
Setting $$x=\frac{\pi}{2}$$ you will get
$$\alpha+\beta=0$$
Setting $$x=\pi$$ then we get
$$\alpha-\gamma=0$$
and Setting $$x=0$$
then we have $$\alpha+\gamma=0$$
can you solve this?
Answer: None of the $3$ vectors in the set is a linear combination of the other vectors. Therefore, the set is linear independent.
Answer: Consider the function $f(x) = a + b\sin x + c \cos x$, which is infinitely continuously differentiable.
Linearly independence of the set in question is the same as showing that $f(x) \equiv 0$ if and only $a = b =c =0$.
Suppose that $f(x) \equiv 0$. Then derivatives of all orders are identically zero.
To see that $b$ and $c$ must be zero, note that $0 = f'(0) = b$ and $0 =f''(0) = -c$, but then these two conditions together with the assumption that imply that $a = 0$.
Hence, it follows that $f(x) = 0$ for all x implies that $a = b = c = 0$. This proves linearly independence of the set in question.

Linear independent or linear dependent?


When does the writer of a named pipe do its work?

Question: I'm trying to understand how a named pipe behaves in terms of performance. Say I have a large file I am decompressing that I want to write to a named pipe (/tmp/data):
gzip --stdout -d data.gz > /tmp/data

and then I sometime later run a program that reads from the pipe:
wc -l /tmp/data

When does gzip actually decompress the data, when I run the first command, or when I run the second and the reader attaches to the pipe? If the former, is the data stored on disk or in memory?
Comment: think its valid. From the man page:` "-d, --decompress, --uncompress. This option selects decompression rather than compression."`
Comment: shouldn't that be gunzip to decompress ?
Answer: Pipes (named or otherwise) have only a very small buffer if any -- so if nothing is reading, then nothing (or very little) can be written.
In your example, gzip will do very little until wc is run, because before that point its efforts to write output will block. Out-of-the-box there is no nontrivial buffer either on-disk or in-memory, though tools exist which will implement such a buffer for you, should you want one -- see pv with its -B argument, or the no-longer-maintained (and, sadly, removed from Debian by folks who didn't understand its function) bfr.


Cannot style material-ui Date Picker OK/Cancel button

Question: I followed the steps in this link to change the background color material-ui --> Date Picker dialog by changing the theme. Changing the theme changed background color but it did not change the color of the OK and CANCEL buttons.How to change the color of OK and CANCEL buttons?
Comment: The material-ui documentation says something about "dialogContainerStyle" can be used to Override the inline-styles of DatePickerDialog's Container element. But I do not know how to use that attribute.
Answer: You have two options to customize the color of the OK and Cancel buttons.

(Easier) If you are okay with all flat buttons in your application using same, customized color you want to use on your Date Picker buttons, then you can simply add
flatButton: {
    primaryTextColor: purple500, // Whatever color you want.
}

to the object you are passing into your getMuiTheme() call.
If you are only customizing the button colors in this situation, and want the other Flat Buttons in your application to take the theme's color, then you need to customize the muiTheme right before the DatePicker is used.
So if we wanted to have all of our Flat Buttons to be cyan500, then we would set that at our main
const mainMuiTheme = getMuiTheme({
    flatButton: { primaryTextColor: cyan500 }
})

const WrapperWithMainThemeProvider = (props) => {
    return (
        <MuiThemeProvider muiTheme={mainMuiTheme}>
            <MyDatePicker />
        </MuiThemeProvider>
    )
}

Then if wanted the buttons in our DatePicker to be customized, then we do that in a custom component.
class MyDatePicker extends React.class {
    render() {
        const muiTheme = getMuiTheme({
            ...this.context.muiTheme,
            flatButton: {
                primaryTextColor: purple500,
            }
        })

        // Customize the muiTheme, and pass it down in a new MuiThemeProvider.
        // Only Flat Buttons that are children of this component
        // will have the new color.
        return (
            <MuiThemeProvider muiTheme={muiTheme}>
                <DatePicker />
            </MuiThemeProvider>
        )
    }
}

MyDatePicker.contextTypes = {
    muiTheme: React.PropTypes.object.isRequired
}

Answer: Material-UI uses Flatbutton as default on datepicker or for any dialog. Which means the OK/CANCEL button you see on datepicker is nothing but a flatbutton. So to apply background color to OK/CANCEL button of Date picker you have to use color instead of primaryTextColor. The color attribute of flatbutton does change the button background color. Please find example below and Screenshot here
import DatePicker from 'material-ui/DatePicker';

const mainMuiTheme = getMuiTheme({
flatButton: { color: '#333' }
})

const WrapperWithMainThemeProvider = (props) => {
return (
    <MuiThemeProvider muiTheme={mainMuiTheme}>
        <DatePicker
          floatingLabelText="Date Of Birth"
          hintText="Select Date Of Birth"
          container="inline"
          locale="en-US"
          firstDayOfWeek={0}
          autoOk={true}
          value={this.state.dob}
          onChange={this.changeDateOfBirth}
          defaultDate={this.state.dateYesterday}
      >
      </DatePicker>
    </MuiThemeProvider>
)
}

And below is what Material-UI expects muiTheme styles for FlatButton.
 flatButton: {
  color: transparent,
  buttonFilterColor: '#999999',
  disabledTextColor: fade(palette.textColor, 0.3),
  textColor: palette.textColor,
  primaryTextColor: palette.primary1Color,
  secondaryTextColor: palette.accent1Color,
  fontSize: typography.fontStyleButtonFontSize,
  fontWeight: typography.fontWeightMedium,
}

For more information about muiTheme styles of each material-UI component check the following link https://github.com/mui-org/material-ui/blob/master/src/styles/getMuiTheme.js
I tested this and it worked for me. Hope this answer helpful.
Comment: Where can I view all those DatePicker properties ?


VBA - Pulling a value on the same row based on another column

Question: I need a macro that will scroll down column B until it's values pass 6. Then, on the first value that passes take the value on that row from column A (I'll refer to this value as X) Then go to another sheet in the same book and insert 3 rows after column C has become greater than or equal to X. I am very new to vba and have no idea what I'm doing but, I'm in a time crunch and could use some help. I don't know if this will help but I wrote out some super pseudo code that might be able to explain it. (not only do I need an X but I also need a Y to insert 3 rows in another spot on the second sheet)
Survey.cell
    dls = Where(column("J") > 6.0 get.row)
    kop = Where(column("B") meets dls)

Survey.cell
    inc = Where(column("C") >85 get.row)
    lnd = Where(column("B") meets inc)

Journal.cell
    Where cloumn("M") >= kip insert.row & inerst.row & insert.row
    Where column("M") >= lnd insert.row & insert.row & insert.row

The closest thing I could find to this is here:
How to find text in a column and saving the row number where it is first found - Excel VBA
but, it's not exactly what I need. I appreciate any help offered. Have a good day!
Comment: I am not quite sure I understand this correctly. First you need to scroll through column B (from row 1 to end?) and when you find that a value is 6 or more, then copy the value to the left of it (column A) and inserting this value in another sheet in column C + 3 = F? In the first row where the value in column C is greater than or equal to value X (from sheet1 column A) ?
Comment: Sorry I tried to explain as best as I could. But, what you said was close. After finding the value in column A I need to take that value (X), go to another worksheet, and insert 3 blank rows after the Values in column b on the second worksheet surpass value (X).
Answer: If I got your question right, this should do it. If there are also non-numeric values in the sheet, this will fail.
Sub DoIt()
    Dim i As Long
    Dim x As Double
    Dim Worksheet1 As Worksheet
    Dim Worksheet2 As Worksheet
    Dim ColumnA As Long
    Dim ColumnB As Long
    Dim ColumnC As Long

    Set Worksheet1 = ActiveWorkbook.Worksheets("Sheet1") ' Change name of sheet if necessary
    Set Worksheet2 = ActiveWorkbook.Worksheets("Sheet2") ' Change name of sheet if necessary
    ColumnA = 1  ' Change if you want other columns, 1 = A-column, 2 = B etc
    ColumnB = 2
    ColumnC = 3

    For i = 1 To Worksheet1.UsedRange.Rows.Count
        If Worksheet1.Cells(i, ColumnB).Value > 6 Then
            x = Worksheet1.Cells(i, ColumnA).Value
            Exit For
        End If
    Next

    If x = 0 Then MsgBox "No value greater then 6 found in colum b in sheet 1"

    For i = 1 To Worksheet2.UsedRange.Rows.Count
        If Worksheet2.Cells(i, ColumnC).Value >= x Then
            Worksheet2.Rows(i + 1).Insert
            Worksheet2.Rows(i + 1).Insert
            Worksheet2.Rows(i + 1).Insert
            Exit Sub
        End If
    Next

    MsgBox "No value greater then " & x & " found in column C in sheet 2"
End Sub

Comment: You're very welcome. I'd appreciate it if you mark this question as answered, so that the question is more or less "closed".
Comment: Sorry it's my first time actually interacting with the community.


Lagrange/Rolle question

Question: Prove that:

for every $x>0:\arctan x+\arctan(1/x)=\pi/2$
for $-1\leq x\leq1: \arcsin x+\arccos x=\pi/2$

This are some question I got on my Lagrange worksheet. Can someone help me with a solution with Lagrange/Rolle sentences?
Comment: Show that the derivative vanishes. The mean value theorem (a consequence of Rolle) implies that the function is constant. To determine that constant use $x=1$ or the limit $x\to \infty$.
Comment: The functions are constant sret at their initial or final values of function and so all intermediate differential  incremented values are also same. Draw a right triangle with acute angles $x, y= \pi/2-x$ for the exact verification.
Answer: Consider the function
$$ f(x) = \arctan(x) + \arctan(1/x). $$
Its derivative is
$$ f'(x)= \frac{1}{1+x^2} + \frac{1}{1+1/x^2} \frac{-1}{x^2} = \frac{1}{1+x^2}-\frac{1}{1+x^2}=0. $$
Therefore the function is constant over $(0,\infty)$. Then $f(x) = \lim_{x\to\infty} f(x) = \frac{\pi}{2}$.
Comment: it's constant because it's derivative is 0.
Comment: What are you talking about? The function is differentiable, so continuity it's automatic.
Comment: ok ok no problem :)
Comment: :) ............

Lagrange/Rolle question


continuous extension of $P_r*F(θ)$

Question:
Let $F:[-π,π]→[0,∞]$ be $2π$_ periodic, integrable and "continuous" function. For $-π≤θ≤π$ and $0≤r<1$.
Show that $$ P_r*F(θ)=\dfrac{1}{2\pi}\int_{-\pi}^{\pi}\dfrac{1-r^2 }{1-2r \cos (θ-t)+r^2}F(t) dt$$
can be continuously extended to the unit circle, as mapping again to$ [0,∞]$?

I know that  $ P_r*F(θ)→ F(\theta)$ as $r→ 1$, when $F$ is continous on the unit circle, but I'm not sure how to prove this 'continuous extension' when $F$ takes  $∞$, If any one can help!
Thanks.
Answer: The proof for the usual continuous (finite) case is local, so in other words, showing that $P_r*F(e^{i\theta})→ F(e^{i\theta})$ depends only on a small neighborhood of $e^{i\theta}$ on the circle (and moreover one can show "full" continuity in the sense that if $u(re^{i\theta})=P_r*F(e^{i\theta})$ we actually have $u(z) \to F(e^{i\theta}), z \to e^{i\theta}, |z| \le 1$.
In particular, for finite points of continuity, $\theta$ nothing changes as long as we can show that away from $e^{i\theta}$ the Poisson integral converges to zero with $r$. Fixing $e^{i\theta}=1$ for notational convenience, this would mean to show that
$\dfrac{1}{2\pi}\int_{\delta}^{2\pi-\delta}\dfrac{1-r^2 }{1-2r \cos (t)+r^2}F(t) dt \to 0, r \to 1, \delta >0$ arbitrary; in the usual case this follows immediately from the Poisson Kernel properties and the boundness of $F$, while here we use that $F \ge 0$ integrable so we can apply the Monotone convergence theorem since $g(r,t)=\dfrac{1-r^2 }{1-2r \cos (t)+r^2}F(t)$ is decreasing in $r$ to zero (at least where $F(t)$ is finite hence ae) for $r \ge |\cos \delta|$ - as the derivative in $r$ is clearly negative for $r \ge |\cos t|$ and $|\cos t| \le \cos \delta$
Hence the only thing you need to do is to prove the result at points $\theta$ where $F$ is infinite and assume for notational convenience $e^{i\theta}=1$ - so we need to prove that $u(z) \to \infty, z \to 1$; but for each $N$ there there is a neighborhood of $1$ where $F(e^{i\theta}) \ge N, |\theta| \le 2\alpha_N$ for some small $\alpha_N >0$ so
$u(re^{i\theta})=\dfrac{1}{2\pi}\int_{-\pi}^{\pi}\dfrac{1-r^2 }{1-2r \cos (θ-t)+r^2}F(t) dt=\dfrac{1}{2\pi}\int_{-\pi}^{\pi}\dfrac{1-r^2 }{1-2r \cos t+r^2}F(t+\theta) dt \ge$
$\ge \dfrac{1}{2\pi}\int_{-\alpha_N}^{\alpha_N}\dfrac{1-r^2 }{1-2r \cos t+r^2}F(t+\theta) dt \ge \dfrac{N}{2\pi} \int_{-\alpha_N}^{\alpha_N}\dfrac{1-r^2 }{1-2r \cos t+r^2}dt$, for $|\theta| \le \alpha_N$
But now as before $\dfrac{1}{2\pi}(\int_{-\pi}^{-\alpha_N}+\int_{\alpha_N}^{\pi})\dfrac{1-r^2 }{1-2r \cos (t)+r^2} dt \to 0, r \to 1$ so one can pick $r_N$ for which the integral above is at most $1/N, r \ge r_N$ and putting things together we get:
$u(re^{i\theta}) \ge \dfrac{N}{2\pi} \int_{-\alpha_N}^{\alpha_N}\dfrac{1-r^2 }{1-2r \cos t+r^2}dt \ge \dfrac{N}{2\pi} (\int_{-\pi}^{\pi}\dfrac{1-r^2 }{1-2r \cos t+r^2}dt-1/N)=\dfrac{N-1}{2\pi}$ for $|\theta| \le \alpha_N, r \ge r_N$ hence indeed $u(z) \to \infty, z \to 1$ and we are done!
Comment: Thank you very much! but why for finite points of continuity, $\theta$ does not change things? what if it equals $0$?
Comment: In the third paragraph, shouldn't be $\cos (\theta -t)$ ?
Comment: For finite points the proof is just a sketch assuming that you know how the proof works in the finite case where one splits the integral in the small part around the point which gives the limit $f(\theta)$ and the part outside where one needs to prove that the integral goes to zero and now one uses monotone convergence instead - the full proof would need indeed detail like the $\alpha_N$ in the infinite case and technically you are right that one would need a $t-\theta$ but they are away from $\delta$ still so the derivative is still negative for $r$ close to $1$ etc

continuous extension of $P_r*F(θ)$


When did Stradivarius become "Stradivarius!"

Question: Instruments built by the Stradivarius family are popularly thought of amongst the pantheon of "greatest ever".1 But have they always been considered this way? Were they held in similarly high regard in their day and continuously up to the present? Were they just ordinary violins until some "great master" musician declared them the best, and the declaration became self-fulfilling?
What is the origin and history of the popular fame of the Stradivarius?

1 I make no claim one way or another about the actual quality of the instruments; I'm interested in the history or their popular reputation, regardless individual opinion of them.
Comment: I feel like there are two "levels" to the question. Were they celebrated, elite collector's pieces even in their own time? Sure. But the second question is about how "household names," those names that represent their categories to the exclusion of others, get to be that way. Itzhak Perlman, Yo-Yo Ma, Julliard, Steinway... These are names that everyone is familiar with, even if unfamiliar with, say, Joshua Bell, Jacqueline du Pré, Curtis Institute, and Bösendorfer. How did Stradivarius come to eclipse in this way Amati, Stainer, Guerneri, et al? That sounds like a fascinating mystery story.
Comment: I consider this as question weakly related to music, and completely explained by the psychological urge to rank (raising from a cognitional overload if  the numerous relevant facets would have to be prioritzed and evaluated separately). While the most striking examples **are** instruments (grand piano -> Steinway, bassoon -> Heckel), a similar list may be created e.g. for cars easily.
Comment: @Tim I think '59 Les Paul Standard would be closer equivalent. Stratocaster was intended to be mass produced right from beginning.
Comment: Almost the same question could be posed regarding the Stratocaster.
Comment: @guidot The phenomenon holds for other entities, too; people (when did Shakespeare become *Shakespeare*) or institutions (cf Juilliard vs every other music school). But of course you can't valuate or hoard people or institutions (well, I mean you *can*, but not in the same ways); Strads stand at a perfect-storm convergence of economics, art object, and sociology as mediated through the commodity of classical music (and indeed the keystone role the violin played in that history).
Comment: @guidot In other words, I'm defending it as a music-history question because, although human creatures always have loved to fetishize and meme-ify their favorite cultural artifacts, the reception history of the Strad stands as a model of the reception history of classical music.
Comment: @ojs Lol, you could argue that so were Stradivaris (over 1,000 instruments over ca 50 years, running a family workshop under his own name).
Comment: @guidot Your comment addresses the matter of why we rank things, but it doesn't address why Strads came to be placed at the top of the ranking. Are you suggesting that a large population of people all arbitrarily and independently picked the same instrument to rank at the top?
Comment: @AndyBonner 20 instruments per year sounds like small boutique builder to me. For comparison, 1000 Stratocasters are currently made in a week.
Comment: Isn't the thing that really makes a "Stradivarius" their crazy sale prices and mystique in the general public? Not blind listening tests. I knew a cellist who was more impressed with his Guadagnini instrument. Maybe sale prices are an indicator to consider.
Comment: @MichaelCurtis That's exactly the question: when and how did the mystique come into being?
Comment: I wish I could give you dates, but I don't know the topic. I'm just suggesting a history of sale prices could be a way to try to make "mystique" a bit more objective.
Comment: Say *Stradivarius* to a violinist and they'll imagine a *violin*, but say it to a brass player and they'll imagine a trumpet or trombone maybe...
Answer: They were famous from the first, as were some other Cremona violin makers. Later on, the Strads were rebuilt (as were other marks) to 19th century standards; the rebuilds worked better on the Strads. There is a (possibly apocryphal) story about Cremona factory signs. Supposedly Amati, Guarneri, and Stradivarius each had a factory on the same block in Cremona.
Amati had a sign on their factory: "Best Violins in Italy."
Guarneri had a sign on their factory: "Best Violins in the World."
Stradivarius had a sign on their factory: "Best Violins on the Block."
Comment: @Dekkadeci Although I haven't researched enough yet, the anecdote smacks of myth. But as to "which is best," I could slyly say that that would be introducing a subjective question. But that's kind of Aaron's point: if he was one among equals in his day, and if even today some players might say (with perhaps a hint of sour grapes) "I prefer a Guarneri"... Then why *is* a Strad a *Strad*, and (maybe the more fascinating) *when* did it become one? (Let the record show I intend to post an answer, but need more research.)
Comment: Alright, which one of those companies made the best violins...? (Yes, I know all of those slogans have a chance of spouting hyperbole on their own and mutually contradict each other.)
Comment: Ha... Reminds me of John being asked whether Ringo was the best drummer in the world and responding, "He's not even the best drummer in the Beatles!"
Answer: I think for the type of performer that these violins are a possibility it is not just the quality of the workmanship, but the oldness of the wood. There is no way to fake old wood. As a violin vibrates, the sound goes into the fibers of the wood and trough many years of playing the tone improves. I do believe that these violins would be pretty temperamental. They may also have problem with intonation and staying in tune, but all these minor inconveniences may be worthwhile for the warm tone that simply cannot be had by a violin compromising of any younger wood.
Comment: I'm not asking why they're considered good instruments. I'm asking for the history of when and how they became known as "the best."
Comment: They started being considered the best when people realised the older the wood the better the sounds the violin makes.
Comment: That would make exactly the answer I'm looking for as long as you can include some specifics of when and how that realization came about, along with some sources.
Comment: Also probably a fact that there full tonal capabilities were not fully realised in the days of gut strings. The strads were probably violins with the oldest wood and an acceptable level of craftsmanship. The craftsmanship improved over the years, but that level of old wood could never be attained again.
Comment: _sound goes into the fibers of the wood and trough many years of playing the tone improves_ [citation needed]


Find the point of intersection of the straight line $\frac{X+1}{4}=\frac{Y-2}{-2}=\frac{Z+6}{7}$ and plane $3X+8Y-9Z=0$

Question: Find the point of intersection of the straight line
$$\frac{X+1}{4}=\frac{Y-2}{-2}=\frac{Z+6}{7}$$ and plane $3X+8Y-9Z=0$

the point of the line is $M(-1,2,-6)$ and direction vector of the line is $A(4,-2,7)$

I would like to get some advice how to do that.
Thanks!
Comment: Did you mean to say that the direction vector is $\langle 4, -2,7 \rangle$?
Comment: yes, fixed thanks
Answer: $$
\frac {X+1}4 = \frac {Y-2}{-2} = \frac {Z+6}7 = k \\
X = 4k - 1 \\
Y = -2k + 2 \\
Z = 7k - 6
$$
Substitute it to the equation of plane
$$
3X+8Y-9Z = 0 \\
12k-3 - 16k + 16 - 63k + 54 = 0 \\
-67k + 67 = 0 \\
k = 1
$$
Since you know $k$, you can easily find $X,Y,Z$.
$$
X = 4k-1 = 3 \\
Y = -2k+2 = 0 \\
Z = 7k-6 = 1
$$
So, point of intersection is $(3,0,1)$.
Answer: Write all the parameters as one of them, say:
$$y=\frac{-x-1}2+2=\frac{-x+3}2\;,\;\;z=\frac{7x+7}4-6=\frac{7x-17}{4}$$
Substitute in the plane's formula:
$$3x+8\left(\frac{-x+3}2\right)-9\left(\frac{7x-17}4\right)=0\iff -\frac{67}4x+\frac{201}4=0\implies$$
$$ x=3\;,\;y=0\;,\;z=1$$
From here it follows that I've no idea what you call $\,M\,$ to as the intersection point between the given line and given plane is $\;(3,0,1)\;\ldots$


Localization of Tor of an algebra

Question: Let $R$ be a commutative ring, let $A$ be an $R$-algebra, let $S\subset A$ be a multiplicative subset, and let $M$ be an $R$-module. Is it true that
$\mathrm{Tor}_p^R(S^{-1}A,M) \cong S^{-1}\mathrm{Tor}_p^R(A,M)$ ?
The first problem is that I don't even see how the right hand side makes sense. For that, I would need $\mathrm{Tor}_p^R(A,M)$ to be an $A$-module, but how is it so? For $p=0$, this is $A\otimes_R M$ and it is, indeed, an $A$-module, but if I take a projective resolution of $R$-modules $P_\bullet \to A$, the $P_i$ need not be $A$-modules, so this line of thought doesn't go through...
Answer: This is true, to see that this is indeed an isomorphism and why the right $\operatorname{Tor}_p^R(A,M)$ is indeed an $A$-module, you can take a projective resolution $P_\bullet\rightarrow M$ of $M$. Then $\operatorname{Tor}_p^R(S^{-1}A,M)=H_p(S^{-1}A\otimes_R P_\bullet)$. But we have the following isomorphisms :
$$ S^{-1}A\otimes_R P_\bullet\simeq S^{-1}A\otimes_A (A\otimes_R P_\bullet) $$
and
$$ H_p(S^{-1}A\otimes_A (A\otimes_R P_\bullet))\simeq S^{-1}A\otimes_A H_p(A\otimes_R P_\bullet)=S^{-1}H_p(A\otimes_R P_\bullet)$$
(this is because the functor $S^{-1}A\otimes_A\cdot$ is exact and commutes with homology).
Finally $S^{-1}H_p(A\otimes_R P_\bullet)=S^{-1}\operatorname{Tor}_p^R(A,M)$.
Comment: Great, thanks. I should have resolved $M$, not $A$.

Localization of Tor of an algebra


Error with postfix gmail smtp on ubuntu

Question: I have setup the postfix-gmail-smtp on my GCP instance and it was working for past few months but stopped working now. I have checked and re-installed based on the steps mentioned in https://tonyteaches.tech/postfix-gmail-smtp-on-ubuntu/ but not still not working. Any suggestion on how to fix this issue ?
Br,
Ranjeeta
Comment: Please provide your actual postfix configuration.
Answer: I don't know about other countries but I know in the UK on May 30th 2022 Google disabled the less secure apps access to gmail.
This means that Google no longer allows other apps to logon to gmail using just your account username and password.
Now you have to enable 2-step-verification on Google and then configure an App Password on your Google account. Then use that generated App Password for the mail password in your IMAP or SMTP config.
See:
https://support.google.com/accounts/answer/6010255?hl=en
https://support.google.com/accounts/answer/185833?hl=en
https://www.gmass.co/blog/gmail-smtp/
Comment: @RSingh you say you setup `2-step-verification` but have you do not say you have configured an `App Password`? Please confirm you have done both.
Comment: I have setup the 2 step-verification on Google /Gmail but still does not work. I am not getting an error message now. Any idea what file should I refer here for potential error log ?
Comment: yes you right it works and it is because my 2 step verification and password was not setup correctly. It works now, thank you

Error with postfix gmail smtp on ubuntu


Prove that Cyclic Group with only one generator can have at most 2 element

Question: I want someone to check my proof
Suppose the cyclic group with one generator can have more than 2 element
Consider 2 element since number of generator can't exceed number of element then it has 2 element.
But if it not,It must have <1> as generator and atleast  prime number as generator.That contradict
Therefore cyclic group with only one generator can have at most 2 element
Answer: Take $G$ such a Group with its unique generator $g\in G$. But then $g^n=e\iff \left(g^{-1}\right)^n=e$ thus $g^{-1}$ is also a generator. Can you take from here?
Comment: I can't .  I have I just started read abstract algebra I'm newbie in this field-*-
Comment: ok I get that now thank


Corrupted malloc area by scanf()

Question: i have an issue with my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct hashTable{
char *data;
struct hashTable *next;
}HASHTABLE;

HASHTABLE **linkedHashTable[100];
void SaveHashTable1(char *str2,char *str3)          //s retazenim---Linked List
{
int hashResult;
HASHTABLE* linkedHashTableNode=NULL, *new_;

hashResult=StringToInt(str2);

if(linkedHashTable[hashResult]==NULL)
{
    linkedHashTableNode=(HASHTABLE*)malloc(sizeof(HASHTABLE));

    linkedHashTableNode->data=(char*)malloc(strlen(str3)*sizeof(char));
    strcpy(linkedHashTableNode->data,str3);

    linkedHashTableNode->next=NULL;
    linkedHashTable[hashResult]=&linkedHashTableNode;
}
else
{
    linkedHashTableNode=*linkedHashTable[hashResult];
    while(linkedHashTableNode->next!=NULL)
        linkedHashTableNode=linkedHashTableNode->next;

    new_=(HASHTABLE*)malloc(sizeof(HASHTABLE));

    new_->data=(char*)malloc(strlen(str3)*sizeof(char));
    strcpy(new_->data,str3);
    new_->next=NULL;
    linkedHashTableNode->next=new_;
}

 }
 int main(void)
 {
char *str1=NULL, *str2=NULL, *str3=NULL;
int i;

while(1)
{
    scanf("%s ", str1);
    if((strcmp(str1, "save"))==0)       //SAVE
    {
        scanf("%s %[^\n]s", str2, str3);

        SaveHashTable1(str2, str3);
    }
}
}

this is part of code, wich I have problem, when I try execute this:
linkedHashTableNode->data=(char*)malloc(strlen(str3)*sizeof(char));
strcpy(linkedHashTableNode->data,str3);

always I get memmory space near by memory area of scanf(), so when I read data from console again,  then original data  are rewrite. And I have no Idea where can be a problem.
Thanks for your help.
Answer: You're not requesting enough memory in the malloc call. strlen tells you how many characters are in the string, not including the terminating NUL, but strcpy is going to copy the terminating NUL character anyway.
Answer: It looks to me that you have a couple of problems.
First of all, the scanf() function can be a bit dicey to use so you may want to consider modifying the main so that you get a line at a time using gets() and then parse the line of input.  However this is not a show stopper.
In your main() you need to allocate memory for str1, str2, and str3.  They are pointers to NULL in your question.  See scanf man page.
I suggest you take a look at the following, modified version of your application.  Still using the scanf() however there are several other changes that you should consider.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct hashTable{
    char  *data;
    struct hashTable *next;
}HASHTABLE;

HASHTABLE *linkedHashTable[100];

// stub version of StringToInt() so that it will compile and I can
// do a couple of simple tests in the debugger.
int StringToInt(char *str2)
{
    return 1;
}

void SaveHashTable1(char *str2,char *str3)          //s retazenim---Linked List
{
    int hashResult;
    HASHTABLE *new_;

    hashResult=StringToInt(str2);

    new_ = (HASHTABLE *)malloc(sizeof(HASHTABLE));
    if(linkedHashTable[hashResult] != NULL)
    {
        // since there is at least one entry in the table, lets traverse the list
        // until we reach the end.  we will then append our new entry onto the end.
        HASHTABLE *linkedHashTableNode;
        HASHTABLE *lastLinkedHashTableNode;

        linkedHashTableNode = linkedHashTable[hashResult];
        while(linkedHashTableNode != NULL) {
            lastLinkedHashTableNode = linkedHashTableNode;
            linkedHashTableNode = linkedHashTableNode->next;
        }
        lastLinkedHashTableNode->next = new_;
    } else {
        linkedHashTable[hashResult] = new_;
    }

    new_->data = (char *)malloc(strlen(str3) + 1);
    strcpy(new_->data, str3);
    new_->next=NULL;
}

int main(void)
{
    char  str1[128], str2[128], str3[128];

    while(1)
    {
        scanf("%s ", str1);
        if((strcmp(str1, "save"))==0)       //SAVE
        {
            scanf("%s %[^\n]s", str2, str3);
            SaveHashTable1(str2, str3);
        }
    }
}

Comment: @user1726810, if this answers your question, please mark it as an answer.  You had several problems with your code that this rewrite addresses.  You need to understand that a local, stack variable will disappear after a function returns so keeping the address of it as you were in your hash table will not work.  All in all you had a number of problems involving memory and variables so that is an area you should do further study.
Answer: you should notice that strlen("hello world") == 11 but "hello world needs a char[12] to be stored
strlen(str3) returns the number of char in str3 but doesn't count the '\0' car at the end of strlen3
therefore strcpy is not able to copy the end string caractere

Corrupted malloc area by scanf()


JSQMessages TextForMessageBubbleTopLabel, swift

Question: I did some research about how to display sender name above the message bubbles on JSQMessage, but nothing is showing above the bubbles. Below is my code: the messages work fine, it is just the display name. Suggestions?
func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
    let message = messages[indexPath.item];

    // Sent by me, skip
    if message.senderId == senderId {
        return nil;
    }

    // Same as previous sender, skip
    if indexPath.item > 0 {
        let previousMessage = messages[indexPath.item - 1];
        if previousMessage.senderId == message.senderId {
            return nil;
        }
    }

    return NSAttributedString(string:message.senderId)
}

func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
    let message = messages[indexPath.item]

    // Sent by me, skip
    if message.senderId == senderId {
        return CGFloat(0.0);
    }

    // Same as previous sender, skip
    if indexPath.item > 0 {
        let previousMessage = messages[indexPath.item - 1];
        if previousMessage.senderId == message.senderId {
            return CGFloat(0.0);
        }
    }

    return kJSQMessagesCollectionViewCellLabelHeightDefault
}

Answer: You are not using the correct method signatures they should be the overridden methods from the library.
Change
 func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {

to ->
override func collectionView(_ collectionView: JSQMessagesCollectionView, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath) -> NSAttributedString? {

and this
func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {

to ->
override func collectionView(_ collectionView: JSQMessagesCollectionView, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout, heightForMessageBubbleTopLabelAt indexPath: IndexPath) -> CGFloat {

Let me know if you need any more help.


Como alterar as cores dos geom_points no R

Question: library(tidyr)
library(dplyr)
library(ggplot2)
library(lubridate)

Suponha o seguinte df:
Ano<-c(2012:2020)
Janeiro<-c(112,127,121,131,150,158,137,165,164)
Fevereiro<-c(101,101,94,114,126,119,122,138,144)
Março<-c(97,101,101,123,126,138,137,154,114)
Abril<-c(97,94,97,122,125,141,129,142,6)
Maio<-c(96,98,98,136,126,135,136,144,4)

fen<-data.frame(Ano, Janeiro, Fevereiro, Março, Abril, Maio)

Depois:
Uso "gather" para colocar os dados no formato tidy;
Uso "mutate" junto com "ymd" e "paste" para colocar os anos no formato "Date";
Uso "select" para selecionar as colunas que me interessam;
Uso "arrange" para organizar em ordem cronológica;
Uso o "ggplot"+ "geom-line" e "geom_point" para criar o gráfico.
fen %>%
  gather(mes, n_voos, c(Janeiro:Maio)) %>%
  mutate(dt=ymd(paste(Ano, mes, "1"))) %>%
  select(dt, n_voos) %>%
  arrange(dt) %>%
  ggplot()+
  geom_line(aes(dt, n_voos))+
  geom_point(aes(dt, n_voos))

O resultado é:

Minha dúvida:
Há alguma forma de eu COLORIR os pontos de acordo com os meses?
Por exemplo: gostaria de todos os meses de Janeiro com a cor azul, todos os de Fevereiro com a cor verde, todos os de Março de preto, e assim por diante.
Tentei adicionar um "col=dt" na última linha, mas o resultado gerou uma alteração nas cores dos pontos segundo os ANOS. Ficou assim:
fen %>%
  gather(mes, n_voos, c(Janeiro:Maio)) %>%
  mutate(dt=ymd(paste(Ano, mes, "1"))) %>%
  select(dt, n_voos) %>%
  arrange(dt) %>%
  ggplot()+
  geom_line(aes(dt, n_voos))+
  geom_point(aes(dt, n_voos, col=dt))

Ficou assim:
Answer: Para colorir segundo os meses, deve usar mes em aes(color = mes), não a data dt, como está no código da pergunta.
Note ainda que apesar do gather funcionar e ser a forma usada no passado, o pacote tidyr tem agora help('pivot_longer'), a forma recomendada.
fen %>%
  pivot_longer(
    cols = Janeiro:Maio,
    names_to = "mes",
    values_to = "n_voos"
  ) %>%
  mutate(dt = ymd(paste(Ano, mes, "1")),
         mes = factor(mes, levels = c("Janeiro", "Fevereiro", "Março", "Abril", "Maio"))) %>%
  ggplot(aes(dt, n_voos)) +
  geom_line() +
  geom_point(aes(color = mes))

Comment: @itamar Agora há o `pivot_wider`. Mas tanto o `gather` como o `spread` não vão desaparecer. Isto é dito nas páginas de help do [`pivot_longer`](https://tidyr.tidyverse.org/reference/pivot_longer.html)  e do [`pivot_wider`](https://tidyr.tidyverse.org/reference/pivot_wider.html). Em ambos os casos na última frase da secção Details. Portanto, se está habituado a usar as funções mais antigas, e para as quais há muitos exemplos na rede e no SO, não haverá problema. Eu acho que as novas funções são mais intuitivas e mais flexíveis.
Comment: Obrigado pela dica sobre o "pivot_longer". A propósito: e como relação ao "spread" (costumo usar como o oposto do "gather") há alguma dica? Ou sigo com o "spread"?


BigQuery: Aggregating distinct values in JSON

Question: I have a table (few million rows) which I'm grouping by using some columns. One of other columns contains simple 1-layer key:value JSON with unknown keys. Let's say it's:
{"key1": "value1", "key2": "value2", "key3":"value33"} in row1
and {"key2": "value22", "key3": "value33"} in row2.
Both row1 and row2 have the same columns used in groupby, so I want to aggregate these JSON results. Final result should be a JSON containing all keys which appeared in grouped rows, and their values should be lists of distinct values for these keys. For row1 and row2, result would be:
{"key1": ["value1"], "key2": ["value2", "value22"], "key3":["value33"]}
Is this possible to achieve such aggregation in normal query? Or I need to use e.g. remote function written in python?
I tried to find a proper solution, but I only saw similar logic for cases in which we have defined names of JSON keys. Here they can be random, and we're not aware what we will get.
Answer: Use below (BigQuery Standard SQL)
CREATE TEMP FUNCTION  extract_keys(input STRING) RETURNS ARRAY<string> LANGUAGE js AS """
  return Object.keys(JSON.parse(input));
  """;
CREATE TEMP FUNCTION  extract_values(input STRING) RETURNS ARRAY<string> LANGUAGE js AS """
  return Object.values(JSON.parse(input));
  """;
SELECT id, FORMAT('{%s}', STRING_AGG(kv)) json
FROM (
  SELECT id,
    FORMAT('"%s":%s', key, FORMAT('%T', ARRAY_AGG(val))) kv
  FROM your_table,
  UNNEST(extract_keys(json)) key WITH OFFSET
  JOIN UNNEST(extract_values(json)) val WITH OFFSET
  USING(OFFSET)
  GROUP BY id, key
)
GROUP BY id

if applied to sample data as in your question
WITH your_table AS (
  SELECT 1 id, '{"key1": "value1", "key2": "value2", "key3":"value33"}' json UNION ALL
  SELECT 1, '{"key2": "value22", "key3": "value33"}' UNION ALL
  SELECT 2, '{"key2": "value22", "key3": "value33"}'
)

output is


In which direction is this statement true?

Question: Having a hard time how I would go at this question.
$\exists x \in G, P(x) \wedge Q(x) \iff
    (\exists x \in G, P(x)) \wedge (\exists x \in G, Q(x))$
$\forall x \in D, P(x) \vee Q(x) \iff
    (\forall x \in D, P(x)) \vee (\forall x \in D, Q(x))$
Comment: Let $G=D=\{0,1\}$ for simplicity. Try different things for $P$ and $Q$.
Answer: Hint 1:
Note that in the first bi-conditional, RHS is true whenever LHS is true, since if there is a single thing with both properties P and Q (LHS)---say a Pink Queen, then it does follow that there is something Pink and that there is a Queen. If this is a material bi-conditional, then even when LHS is false or impossible the '$\Longrightarrow$' direction will be true. Consequently the '$\Longrightarrow$' direction of the first formula is always true (valid). The '$\Longleftarrow$' direction isn't valid however, for suppose there is something Pink and there is a thing that is a Queen, but the Pink thing and the thing that is a Queen needn't be the same thing---the thing that is a Queen may be White (say), and as such not Pink. Try to use similar reasoning for the second bi-conditional.
Hint 2:
You may want to construct a counter-model for either of the directions. Here two-item models will suffice, as suggested by $\color{navy}{\text{columbus8myhw}}$ above.
Let $G=D=\{ a,b\}$, and recall that for finite domains $D$, $\exists x \in D, P(x)$ is equivalent to $P(a_1) \lor P(a_2) \lor...\lor P(a_n)$ for an n sized domain, and $\forall x \in D, P(x)$ is equivalent to $P(a_1) \land P(a_2) \land...\land P(a_n)$. This gives you a way to transform those FOL frormulae into PC formulae, the validity of which you can check using semantic trees or truth tables, if no obvious countermodels come to mind.
Hint 3: The first bi-conditional for a two element model would be equivalent to the formula $( P(a) \land Q(a)) \lor ( P(b) \land Q(b)) \iff ( P(a) \lor P(b)) \land ( Q(a) \lor Q(b))$. Now consider the model where $P=\{a \}$ and $Q=\{b \}$, and note that this is a counter-model for the '$\Longleftarrow$' direction, since the RHS conjunction is true since both of its conjuncts are true, i.e. $P(a)$ and $Q(b)$ is true on this model, and LHS disjunction isn't true since both of its disjuncts fail to be true on account of there being an absence of an object $\alpha \in G$ such that both $P(\alpha)$ and $Q(\alpha)$.
The above counter-model is merely a formalization of the earlier counterexample given in Hint 1: think of $a$ as the Pink thing in $G$, and $b$ as the Queen in $G$, but that doesn't entail that there needs to be a single object in $G$ that is both a Queen and Pink. Hope that helps.


I need to write Macro in c for assembly language commands

Question: I have written this macro to add assembly language commands in C:
TEST_ASM(asm_command)  asm( #asm_Command )

which works perfectly for single commands like:
TEST_ASM("nop")
TEST_ASM("write 0")

But, for this:
TEST_ASM("e_li r3, 0x201")

It gives error:

macro "TEST_ASM" passed 2 arguments, but takes just 1 for

This error is due to the comma in asm command which looks for the next argument.
Could it be possible that macro take comma as string?
I don't want to use variable argument macro as it will give warnings in static analysis.
Comment: Something to think about when trying to write code like this (from the [docs](https://gcc.gnu.org/onlinedocs/gcc/Basic-Asm.html)): *Do not expect a sequence of asm statements to remain perfectly consecutive after compilation. If certain instructions need to remain consecutive in the output, put them in a single multi-instruction asm statement. Note that GCC's optimizers can move asm statements relative to other code, including across jumps.*  BTW, a multi-instruction asm might look like `mov eax, 1\nmov ebx, 2`.
Comment: What compiler do you use? Would you mind providing fully [MCVE](http://stackoverflow.com/help/mcve) which demonstrates "good" and "bad" behavior?
Comment: @yeputons He uses "asm", which is a GNU extension, in his answer, so I'm assuming gcc or something compatible.
Comment: @yeputons  I use above macro for variety of compilers like cosmic ghs
Answer: Do not use stringification in macro, following snippet works for me on gcc:
#define TEST_ASM(asm_Command) asm( asm_Command )

int main()
{
  TEST_ASM("mov $1,%eax");
  return 0;
}


the Intersection of smooth curves can be countable but not finite set?

Question: Given two parametric $C^{1}$ curves in $R^{k}$, i.e. $\xi$ $\eta$ whose parametrization are defined on subsets $[a,b]$ and $[c,d]$ such that the ending points $\xi(b)=\eta(d)$. Assume that $\dot{\xi}\ne=0$. Can
$\xi$ $\eta$ intersect on a countable set but not finite set?
Thanks.
Comment: Can you really not find an example?! Draw one
Comment: I mean: you have surely seen the graph of the function $x^2\sin 1/x$ or something similar.
Comment: You can actually make the intersection an uncountable set having no intervals in it.
Answer: Here is a simple example $(x,0)$ and $(x, x^4 \sin(\pi/x))$ for $-1 \leq x \leq 1$:

The intersections are clearly countable, by making the correspondence between integers $i$ and $1/i$.
Note that the derivative at 0 is:
${d \over d x} x^4 \sin(\pi/x) = 4 x^3 \sin \left(\frac{\pi }{x}\right)-\pi  x^2 \cos \left(\frac{\pi }{x}\right)$ which is $0$ for the limit $x \to 0$.
Comment: While I agree one the idea I disagree on some technical details. The curve $(x, \sin \frac1x)$ is not differentiable at \(0,0\). Moreover, the endpoints condition $\xi(c)=\eta(d)$ is not satisfied.
Comment: Maybe $x^{4} sin(1/x)$ should work.
Comment: Multiply by $e^{-1/x}$ instead of $x^4$ and you'll have a $C^\infty$ example.
Comment: is the derivative continuous at $0$?
Comment: @FrancescoCiardiello:  Is that necessary for the problem?
Comment: @DavidG.Stork yes, it is. I am looking for two parametrized curves smooth at $b$ and $d$ respectively.
Comment: However I am looking for not a curve whose derivative is defined at $b$ or $d$ a not a curve whose derivative can be extended by continuity at $0$.
Comment: @DavidG.Stork your new example is not even continuous at $0$. I think multiplying the sinusoid by $x^2$ and using the zero function instead of that quadratic should fix it.
Comment: @AnthonyCarapetis: With $x^2$ you will have differentiable but not $C^1$, but $x^3$ will do $C^1$, and as zhw pointed out one can easily get a $C^\infty$ version.


Compass Blueprint Liquid starting point

Question: I'm trying to move to a liquid grid using the compass/blueprint/liquid (http://compass-style.org/reference/blueprint/liquid/) however Im getting stuck with the very basic stuff.
Can someone point me to a set of template files which I can use to start out with i.e containing the right includes and settings for a liquid layout?
Answer: why not use susy for as the grid system? It's better integrated in compass and designed specifically for liquid layouts. Also, you can still use blueprint for other things, just exclude the grid.
<code>sudo gem install compass-susy-plugin
compass create myproject -r susy -u susy
</code>

Compass Blueprint Liquid starting point


jq - add prefix to values on array

Question: input json:
[
{
  "login": "u1",
  "name": "u1",
  "role": "User",
  "groups": [
    {
      "id": "1234",
      "name": "G1"
    },
    {
      "id": "1235",
      "name": "G2"
    }
  ],
  "created": "2020-05-11 11:06"
},
{
  "login": "u2",
  "name": "u2",
  "role": "User",
  "groups": null,
  "created": "2020-05-11 11:06"
}
]

I use following filter to get users and groups they are member of:
$ jq -r '
  .[]
  | [.login,
     .name,
     ( if .groups == null
       then "grp:-"
       else (del(.groups[]
             | select(.name=="All Users"))
            | [.groups[].name] | join("|"))
       end )]
  | @tsv' json

u1      u1      G1|G2
u2      u2      grp:-

How to add grp: prefix for each found group?
Expected output would be:
u1      u1      grp:G1|grp:G2
u2      u2      grp:-

Answer: Use + to concatenate strings:
jq -r '.[]
       | [.login,.name,(
           if .groups == null
           then "grp:-"
           else (
               del(.groups[] | select(.name=="All Users"))
               | ["grp:" + .groups[].name]
#                 ~~~~~~~~
               | join("|")
           )
           end
      )]
      | @tsv'

You can even avoid specifying "grp:" twice, but you need to return an array from the then branch, too:
jq -r '.[]
       | [.login, .name, (
           (
               if .groups == null
               then ["-"]
               else (
                   del(.groups[] | select(.name=="All Users"))
                   | [.groups[].name]
               )
               end
           )
           | map("grp:" + .)
           | join("|")
       )]
       | @tsv'

Update:
Getting inspiration from peak I guess this produces the output you wanted:
jq -r '.[]
        | .groups //= []
        | del(.groups[] | select(.name=="All Users"))
        | .groups[0] //= {name: "-"}
        | [.login, .name, ( ["grp:" + (.groups[].name)] | join("|") ) ]
        | @tsv'

Comment: @Chris - Does the variant solution I posted just now handle the edge case appropriately from your point of view?
Comment: @peak: I modified it a bit and I think it produces the expected output now. Thanks for the idea.
Comment: I found one issue when groups array has only "All Users" which I delete - then instead "grp:-" I get empty output. Here sample input for such case: [{"login":"u1","name":"u1","role":"User","groups":[{"id":"1234","name":"G1"},{"id":"1235","name":"G1"}],"created":"2020-05-11 11:06"},{"login":"u2","name":"u2","role":"User","groups":null,"created":"2020-05-11 11:06"},{"login":"u3","name":"u3","role":"User","groups":[{"id":"1234","name":"All Users"}],"created":"2020-05-11 11:06"}]
Answer: Here's a slightly shorter and perhaps tidier variant of the solution already given. It has the advantage of handling the edge case mentioned in a comment elsewhere on this page.
  .[]
  | .groups //= [{name: "-"}]
  | [.login,
     .name,
     (del(.groups[] | select(.name=="All Users"))
     | ["grp:" + (.groups[].name)] | join("|"))
    ]
  | @tsv

Simpler still
  .groups //= [{name: "-"}]
  | .groups |= map(select( .name != "All Users") )
  | [.login, .name,
     (.groups | map("grp:" + .name) | join("|")) ]
  | @tsv```

jq - add prefix to values on array


If $x_n:=\sqrt{n}$, show that $(x_n)$ satisfies $\lim|x_{n+1}-x_n|=0$, but that it is not a Cauchy sequence.

Question: If $x_n:=\sqrt{n}$, show that $(x_n)$ satisfies $\lim|x_{n+1}-x_n|=0$, but that it is not a Cauchy sequence.
We see that
$$|x_{n+1}-x_n|=|\sqrt{n+1}-\sqrt{n}|=|(\sqrt{n+1}-\sqrt{n})\cdot\frac{\sqrt{n+1}+\sqrt{n}}{\sqrt{n+1}+\sqrt{n}}|=\bigl|\frac{1}{\sqrt{n+1}+\sqrt{n}}\bigr|$$
This seems to simplify nicely, but I am not quite sure where to proceed.
Relevant definitions:

$\lim(x_n) = x$ if and only if for $\varepsilon>0$, $\exists k\in\mathbb{N}$ such that for all $n\geq k$, $|x_n-x|<\varepsilon$.
A sequence $(x_n)$ is a Cauchy sequence if for every $\varepsilon>0$, $\exists h\in\mathbb{N}$ such that for all $n,m\geq h$, $|x_n-x_m|<\varepsilon$.
Answer: Take $\epsilon=\frac12$. For any $h\in \mathbb{N}$, choose $n=h$ and $m=4h$. Then $|x_m-x_n|=|\sqrt{4h}-\sqrt{h}|=|2\sqrt{h}-\sqrt{h}|=\sqrt{h} \ge 1$ which contradicts the definition of Cauchy sequence for above $\epsilon$.
Answer: You have shown that
$$|x_{n+1}-x_n|=\frac1{\sqrt{n+1}+\sqrt n}\ ,$$
and this clearly approaches $0$ because $\sqrt{n+1}$ and $\sqrt n$ both approach $\infty$.  (There is no need to use the definition with $\epsilon$ etc unless you have been instructed to do so.)
The easy way to show that $x_n$ is not Cauchy is to note that any Cauchy sequence is convergent (in $\Bbb R$), and $x_n=\sqrt n$ is not convergent.
Answer: Hint (not intended to be a complete solution):$$\left|\dfrac{1}{\sqrt{n+1}+\sqrt{n}} \right| \leq \left|\dfrac{1}{\sqrt{n}+\sqrt{n}}\right| = \left|\dfrac{1}{2\sqrt{n}}\right|\text{.}$$
Take $k := \left \lceil{\left(\dfrac{1}{2\epsilon}\right)^2}\right \rceil $.


How is population density typically calculated?

Question: I was recently plunking down some population density figures into a spreadsheet for further study and simply using figures found on individual Wikipedia country pages.  I wasn't really paying attention to them until I got to Equatorial Guinea, which didn't list a population density figure in its infobox.  So, I thought, How hard can this be?  I'll just do a quick math calculation of my own and then I'll have the population density figure.
After doing this, however, the number I came up with made me wonder if it was correct.  I then discovered that population density figures for Equatorial Guinea varied from one source to another.  Some examples (using density per square mile) are listed below:
20 (no year given, but the page cites the Census Bureau and was posted in 2016)
62 (2009) (Source: Wikipedia article on "List of countries by population density")
73 (Source: a 1991 Census Bureau publication titled, "World Population Profile: 1991" containing a projection for 2020)
150 (2010) (Source: Wikipedia article on "List of countries and territories by population density," which cites Guinea Ecuatorial)
When I attempted to do the calculations myself, I worked with two figures -- the area and the population -- using 10,830 sq. mi. for the area and a population figure of 1.2 million.  Unless my math is wrong, that would equate to a population density of 110.8.  As you can see, all of this has left me wondering whether or not I should just use my own calculation or attempt to find a consistent, reputable source.  What would you recommend?
If you recommend finding a reputable source, which sources consistently do the best job of calculating population statistics and is there any sort of independent review board that rates the various entities publishing these statistics?
Also, while on the topic, I have a feeling that some variance may exist in how population densities are derived.  For example, large parts of some countries are desert (Libya) and others have suffered severe damage due to man-made/natural disasters such as the burning of oil fields (Kuwait) or flooding (Bangladesh).  Is total land area still used in the calculation for such areas?  Does flooding increase the % water a country is considered to have?  Are bodies of water included in the total land area for a country and subsequently used as the calculation for population density?
Thanks in advance to any who have insight/expertise on this topic and can share it with us.
Answer: Depends on what areas are used. There is nothing wrong with doing this country by country. However, in cities, the local population density is high but not so outside of them. In general, I would use an easy button, as lots of people have had this same question and done a lot of work on it.
Comment: I like your idea, @Carl.  My "easy button" this time turned out to be focusing on other aspects of my study, but your "easy button" looks very interesting.  I look forward to experimenting with it in the future.  Thank you for sharing it with us.
Comment: I feel good about helping. All compliments warmly received. I liked your question, too. (+1)


JSON Object Access Value

Question: This is my JSON response:
{
    "2f2EdLjYHcTx4APbgnlvE2SCXQb2": {
        "name": "test",
        "latitute": 7.4866174,
        "longitute": 80.3637889
    },
    "pJua8KSpMwSXiSlWJcDE4sEkOuZ2": {
        "name": "akalanka",
        "latitute": 7.4866198,
        "longitute": 80.3638016
    }
}

How can i access name, latitude and longitute in JavaScript?
I tried using this method, it shows data but i can't access the properties I need:
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "http://localhost:3000/get/json", false );
    xmlHttp.send();
    var data=xmlHttp.responseText;

    var x=[];

    x=JSON.parse(xmlHttp.responseText);
    // x=data.length;

    console.log(x);
    // latitute=x.latitute;
    // longitute=x.longitute;
    z=15;
    myMap();
}

Comment: @Bravo the JSON is absolutely valid
Answer: Two problems in the code:
1) You are using xmlHttp incorrectly.
You are sending the request but parsing the result directly (without waiting for the request to succeed).
xmlHttp.open( "GET", "http://localhost:3000/get/json", false );
xmlHttp.send();

xmlHttp.onload = function () {
 // Request finished. Do processing here.
};

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
2) You need to use the key to access the 'latitute'.
Object.keys(x).forEach(field => {
  console.log(x[field].latitute);
  console.log(x[field].longitute);
});

So it should look like this:
xmlHttp.open( "GET", "http://localhost:3000/get/json", false );
xmlHttp.send();

xmlHttp.onload = function () {
  var x = JSON.parse(xmlHttp.responseText);
  Object.keys(x).forEach(field => {
    console.log(x[field].latitute);
    console.log(x[field].longitute);
  });
};

Answer: First, please confirm that you already get responseText by using onreadystate method.
After that, please try with this.
var responseText = `{"2f2EdLjYHcTx4APbgnlvE2SCXQb2":{"name":"test","latitute":7.4866174,"longitute":80.3637889},"pJua8KSpMwSXiSlWJcDE4sEkOuZ2":{"name":"akalanka","latitute":7.4866198,"longitute":80.3638016}}`;

var x = JSON.parse(responseText);

console.log(x);

Object.keys(x).forEach(field => {
  console.log(x[field].name);
});

Comment: Thanks your approach was also correct, i was tested it. thank for your help
Answer: Beware your properties are misspelled longitute, latitute... te? Should be de
I'd convert the nonstandard UID-as-keys to a simple Array.
Quick example using fetch API:

const myMap = (data) => {
  console.log(`lat:${data.latitute}, lng:${data.longitute}`)
};

const fetchMapData = async () => {
  const response = await fetch('https://jsbin.com/mijopocunu/js');
  const json = await response.json();
  const dataArr = Object.keys(json).map(k => (json[k].id = k, json[k]));
  dataArr.forEach(myMap);
};

fetchMapData();
Comment: Thanks, your code also work and i'm able to access the data  :)

JSON Object Access Value


Let $X$ be a metric space. Suppose $\{p_n\}$ and $\{q_n\}$ are Cauchy sequences in $X$. Show that $\{d(p_n,q_n)\}$ converges.

Question: I had some issues proving this, so I relaxed the conditions to prove the statement in $\mathbb{R}$ first. Here is my attempt:
Note: I used the following theorem:
Theorem. Every Cauchy sequence of real numbers converges.
Proof. By the theorem, we know $\{p_n\}$ and $\{q_n\}$ converges since they are Cauchy. So by definition,
$(1)$ $p_n \rightarrow p$ for given $\epsilon > 0,\ \exists N_1>0$ such that $d(p_n,p)< \epsilon /2$.
$(2)$ $q_n \rightarrow q$ for given $\epsilon > 0,\ \exists N_2>0$ such that $d(q_n,q)< \epsilon /2$.
Let $N> max(N_1,N_2)$. So $\forall n \geq N$,
$$d(p_n,q_n) \leq d(p_n,p) + d(p,q) + d(q_n,q)\ (*)$$
$$< \epsilon /2 + d(p,q) + \epsilon /2$$
$$\Rightarrow d(p_n,q_n) - d(p,q) < \epsilon\ (1)$$
Similarly, mult. $(*)$ by $-1$ and rearrange to get
$$d(p,q) - d(p_n,q_n) > \epsilon\ (2)$$
Thus, by $(1)$ and $(2)$ we get
$$|d(p_n,q_n) - d(p,q)| < \epsilon$$
Hence, $d(p_n,q_n) \rightarrow d(p,q)$. $□$
Now, how can I generalize it to any metric space $X$? For some reason, I think it cannot be done. Thank you!
Comment: Show that $d(p_n,q_n)$ is a Cauchy sequence of real numbers.
Answer: You don't want to use the fact that $p_n,q_n$ converges in your proof because it doesn't hold unless $X$ is a complete metric space. So instead, try to show that if $p_n,q_n$ are Cauchy in $X$ then $d(p_n,q_n)$ is Cauchy in $\mathbb{R}$ and then use the fact that $\mathbb{R}$ is complete so every Cauchy sequence in $\mathbb{R}$ converges. To do that, try to estimate
$$ \left| d(p_n,q_n) - d(p_m,q_m) \right| $$
in terms of $d(p_n,p_m), d(q_n,q_m)$ using the triangle inequality and then show that this is Cauchy because $d(p_n,p_m), d(q_n,q_m)$ are Cauchy.
Comment: @CuriousMathStudent: Yes, but you shouldn't write $p_n \to p$ because it is not true (and you don't use it) and similarly for $q_n \to q$. Also, it should be $-\varepsilon$ in the second starred equation.
Comment: Oh right! I forgot being Cauchy doesn't imply convergence unless we are in a complete metric space. Thank you for very much for your help!
Comment: Thank you for the tip! Here is my attempt (again!):

Proof. Let $\{p_n\}$ and $\{q_n\}$ be Cauchy in $X$. Then,

$(1)$ $p_n \rightarrow p$ for given $\epsilon > 0,\ \exists N_1>0$ such that $d(p_n,p_m)< \epsilon /2,\ \forall n, m> N_1$.

$(2)$ $q_n \rightarrow q$ for given $\epsilon > 0,\ \exists N_2>0$ such that $d(q_n,q_m)< \epsilon /2,\ \forall n, m>N_2$.

Let $N> max(N_1,N_2)$. So $\forall n \geq N$,
$$d(p_n,q_n) \leq d(p_n,p_m) + d(p_m,q_m) + d(q_m,q_n)\ (*)$$
$$< \epsilon /2 + d(p_m,q_m) + \epsilon /2$$
$$\Rightarrow \boxed{d(p_n,q_n) - d(p_m,q_m) < \epsilon}\ (*)_1$$
(cont.)
Comment: (cont.)

Similarly, multiply $(*)$ by $-1$ and get
$$-d(p_n,q_n) \geq -d(p_n,p_m) - d(p_m,q_m) - d(q_m,q_n)$$
$$ d(p_m,q_m) - d(p_n,q_n) > -\epsilon /2 - \epsilon /2$$
$$\Rightarrow \boxed{d(p_m,q_m) - d(p_n,q_n) > \epsilon}\ (*)_2$$

By $(*)_1$ and $(*)_2$ we get
$$|d(p_n,q_n) - d(p_m,q_m)| < \epsilon$$
Thus, we have shown that $d(p_n,q_n)$ is Cauchy... in $\mathbb{R}$.
Hence, by the completion of $\mathbb{R}$, $d(p_n,q_n)$ converges.
QED.

Is my attempt okay?


Create Full AWS RDS Snapshot

Question: Can I create a full database snapshot or backup (manual/automated) for Amazon RDS Postgres Databases and not incremental ones. I want to create a job that provides full database parquet files everyday and share it with the Data warehousing team.
The document here says the following:

The first snapshot of a DB instance contains the data for the full DB instance. Subsequent snapshots of the same DB instance are incremental, which means that only the data that has changed after your most recent snapshot is saved.
Comment: Hey Marcin, we ended up creating a lambda for a quick solution. AWS Glue looked promising, but it did not let us select clusters though, it shows a list of databases only. So we have two environments (dev & qa) on the same AWS account having the same database name with different clusters, it would not work in this case. Also we were not able to see a list of tables when selecting our database. Hence we implemented a lambda with AWSSDK for quick implementation. Thanks for your help though :).
Answer: The RDS snapshots do not create Parquet files, as they are based on EBS snapshots.
To get Parquet files the best way would be to setup a Glue job which can run automatically on your schedule.
Comment: I should have mentioned RDS snapshot when exported to S3 gives out parquet file per object (table)
Comment: @shaikhspear Then what's wrong with those parquet files? They are incomplete?
Comment: every new snapshot only has the incremental data (that changed since the last snapshot was taken). Only the first snapshot is a full database snapshot. I want to find a way to generate Full data snapshots for every export.
Comment: @shaikhspear If you copy snaphot to a different region, it will be full.

Create Full AWS RDS Snapshot


mixed volume properties

Question:
Show that the mixed volume $MV_n(P_1,\dots,P_n)$ is invariant under all permutations of the $P_i.$

2.Show that the mixed volume is linear in each variable
$MV_n(P_1,\dots,\lambda P_i+\beta P_i',\dots,P_n)=\lambda MV_n(P_1,\dots,P_i,\dots,P_n)+\beta MV_n(P_1,\dots,P_i',\dots,P_n)$ for all $i=1,\dots,n$ and $\lambda, \beta \geq0$ in $\mathbb{R}$.
Comment: You might want to give your definition of mixed volume. There are a few, and they are not even the same (they differ by a factor n!), and for some of them those two claims are tautologies.
Comment: The $n$ dimensional mixed volume of a collection of polytopes $P_1,\dots,P_n$ denoted by $MV_n(P_1,\dots,P_n)$ is the coefficient of the monomial $\lambda_1 \lambda_2 \dots \lambda_n$ in $vol_n(\lambda_1 P_1+\dots + \lambda_nP_n).$
Comment: $vol_n(P)=\frac{1}{n} \sum_F a_F vol'_{n-1}(F)$ where the sum is taken over all facets of $P$. (note $vol'$ is the normalized volume of the facet F of the lattice polytope $P$ given by $vol'_{n-1}(F)=\frac{vol_{n-1}(F)}{vol_{n-1}\mathcal{P}}$, where $\mathcal{P}$ is a fundamental lattice paralletope for $\nu^\perp_F \cap \mathbb{Z}^n.$
Answer: I assume your homework is long overdue.  Anyways I guess this could be interesting for somebody else.
Concerning 1):  This follows relatively quick from the definition of the mixed volume that you gave in the comment.  Note that the Minkowski sum $\lambda_1P_1 + \dots + \lambda_nP_n$ is invariant under permutations.  (To prove that, look at the definition of Minkwoski sums and use that $a+b=b+a$ for $a, b \in$ any vector space.)  So
\begin{equation}
vol_n(\lambda_1P_1 + \dots + \lambda_nP_n) = vol_n(\lambda_{\sigma(1)}P_{\sigma(1)} + \dots + \lambda_{\sigma(n)}P_{\sigma(n)})
\end{equation}
 for any permutation $\sigma$.  Hence the coefficient of $\lambda_1\lambda_2\ldots\lambda_n$ of the polynomial on the left equals the coefficient of $\lambda_{\sigma(1)}\lambda_{\sigma(2)}\ldots\lambda_{\sigma(n)}$ on the right hand side.

mixed volume properties


White notes on black background

Question: I'm learning how to read notes, and i've encountered something that i don't quite understand. Could any of you can tell me why in this piece, some of notes are written white on black background?

 - link to exactly moment of sonata
Answer: In other videos I've seen, white notes on a black background aren't played in that portion of the video (first repeat when 2nd repeat is being played, etc.).

White notes on black background


Alternative To Conditional Panel In Shiny R

Question: I have an app where I would like to add different numbers of UiOutputs based on a number chosen by the user. Right now I am finding myself doing a ton of redundant conditional panels to create the outcome I am looking for. I was wondering if there is an easier way to produce the desired outcome through a function like "switch".
Here is the code using conditional Panels. The outcome is desirable. The amount of conditional panels and repetition is not.
I will only show with 2 conditional Panels but in my app I have 9. The app simply asks the users how many stocks they want to chose in their portfolio and the amount of shares for each stock.
library(shiny)

tickers = c("SPY", "IWM", "QQQ")

ui <- fluidPage(

    # Application title
    titlePanel("Old Faithful Geyser Data"),

    mainPanel(
        h3("lets test the corr Mat"),
        #inputs stock
        #inputs weight
       radioButtons("howMany", "How Many ETF's?", choices = c(1, 2, 3, 4, 5, 6), selected = 1),
        actionButton("stest", "Stress Portfolio"),
       conditionalPanel("input.howMany == '1'",
                        selectizeInput("stock1", "choseStock 1", choices = tickers, selected = "SPY"),
                        numericInput("weight1", "Choose Number of Shares 1", value = 100, min = 0, max = NA, step = 1)),
       conditionalPanel("input.howMany == '2'",
                        selectizeInput("stock1", "choseStock 1", choices = tickers, selected = "SPY"),
                        selectizeInput("stock2", "choseStock 2", choices = tickers, selected = "QQQ"),
                        numericInput("weight1", "Choose Number of Shares 1", value = 100, min = 0, max = NA, step = 1),
                        numericInput("weight2", "Choose Number of Shares 2", value = 100, min = 0, max = NA, step = 1))
    )

)

# Define server logic required to draw a histogram
server <- function(input, output) {

}

# Run the application
shinyApp(ui = ui, server = server)

Answer: With my limited Shiny / R experience, I see two routes:  one in which you dynamically generate variable names, and one where you just pretty it up a bit.  I'm not confident I can do the former justice, so here's a way to do the latter:
tickers = c("SPY", "IWM", "QQQ")

ui <- fluidPage(

  # Application title
  titlePanel("Old Faithful Geyser Data"),

  mainPanel(
    h3("lets test the corr Mat"),
    radioButtons("howMany", "How Many ETF's?", choices = c(1, 2, 3, 4, 5, 6), selected = 1),
    actionButton("stest", "Stress Portfolio"),

    fluidRow(
      column(width=6, selectizeInput("stock1", "choseStock 1", choices = tickers, selected = "SPY")),
      column(width=6, numericInput("weight1", "Choose Number of Shares 1", value = 100, min = 0, max = NA, step = 1))
  ),

# This is really all I had to offer
    conditionalPanel("input.howMany > 1",
                fluidRow(
                  column(width=6, selectizeInput("stock2", "choseStock 2", choices = tickers, selected = "QQQ")),
                  column(width=6, numericInput("weight2", "Choose Number of Shares 2", value = 100, min = 0, max = NA, step = 1))
                )
    )

  )

)

# Define server logic required to draw a histogram
server <- function(input, output) {

}

# Run the application
shinyApp(ui = ui, server = server)

Line 17 calls out my two cents:  keep stock1 and weight1, then change your conditionalPanel logic a bit to add in the new inputs.  With fluidRow and a pair of columns, successive variables have their own rows.
Extending this wouldn't be much cleaner, but at least each conditionalPanel would only have two new inputs and that would shorten your code a little


Python3 isnumeric() method not working as expected

Question: I'm just getting to explore some other Python methods such as isnumeric(). I have an assignment task where I'm to search and extract numbers from text. I have posted the code below.
handle = open("words3.txt")
for line in handle:
   line = line.rstrip()
   split = line.split()
   for word in split:
      x = word.isnumeric()
      print(x)

With this I am getting a traceback... But I think I have followed the rules of str.isnumeric(). Can someone please tell me what I am doing wrong?
File "assignment11.py", line 10, in <module>
    x = word.isnumeric()
AttributeError: 'str' object has no attribute 'isnumeric'

Comment: I can't reproduce the error.
Comment: @pavel no, just `.split()` is like `.split(" ")`. So, that may return list of words from `line`.
Comment: `line.split()` will return the `line` itself. What is the point of this line of code?
Comment: @Kshitiz, oh right, thanks. Never used `split()` like this, prefer to always specify.
Answer: isnumeric() works on Unicode strings. To define a string as Unicode you could change your string definitions like so:
s = u'This is my string'
#OR
s=unicode('some string', 'utf-8')
isnum = s.isnumeric()

Or you can do this to change word into string:
x = str(word).isnumeric()

Comment: OP says it's with Python 3
Comment: Yeah? What is wrong then?
Comment: *that `u` isn't required to make a string literal a unicode string... `str` **is unicode***
Comment: `unicode()` also? Should I delete, that and just leave `str()` only? Then that also doesn't make any sense cuz `word` is also already string!
Comment: `unicode` **doesn't exist in Python 3** it's just `str`.and yes, calling `str` on a `str` is pointless
Comment: Then deleting answer is the best, right? Because after deleting everything, there is nothing left!
Comment: @juanpa.arrivillaga additionally I have found that, for which question this is closed as duplicate, there answer are same as mine. That also doesn't make any sense, cuz if that doesn't solve the OP problem then why this question is closed without any answer?


What is it called when a DJ rewinds, then fastforwards quickly?

Question: Not too quickly or abrupt like a scratch, but when it's done at a linear speed at something like a tenth of a second both ways, further the record is brought to where it would have been had this technique never been done; in other words the rhythm is uninterrupted.
It seems like a lot of "trap" music is doing this and I don't know what to call it.
A good example is the following mix where it occurs frequently:

1:54:03 (Or 114 minute mark)
It's done a number of times after the time posted. I love it, but don't know what to call it.
Comment: After listening to the example, I'd call it a _reverse playback_ instead of a rewind. The vocal track is simply reversed for a moment, while the underlying beat is unchanged. Then, to keep the vocal track in sync with the beat, it is either fast forwarded or jump-cut forward to line back up after the moment of reverse. Not sure what this technique is called.
Comment: Googling reverse playback and I'm only getting information on reversing whole songs and videos, however I really like how your described what is happening. Maybe there isn't a name for this yet, but I hope at the very least that one gets invented so it is easier to talk about.
Answer: I have just listened to it. If  you want to do that live you need the instrumental on one deck and the a cappella on the other one then you slowly rewind it and then jump to the part you cued (where you want the song to start again). On regular turntables you would have to lift the needle and bring it back to the position where it was before  you rewinded.
In an audio editing software it is easy to do though, it is often used to censor songs in Hip Hop. It is used in the song "Ching a ling" of Missy Elliot:

If you have ableton live for example, you warp your a cappella to the rhythm of your beat so that both always stay synced if you speed up the tempo. You select the part of the a cappella you want to reverse, you split the track and select the part you want to reverse. In the clip window at the bottom of the window you click on "R" to make the clip reversed. As simple as that .
I found that it is also called backmasking and it is when a message is hidden by playing it in reverse in a song lol... http://www.backmaskonline.com/index.php?page=rap
Comment: I will, from here on, call it backmasking ;). Thanks.

With that backmask link, I now see the technique is quite simply to do, although I'm sure it is more challenging to find good times to put it into the music.
Answer: I am not sure if you are talking about that but the way you describe it, it seems to be a baby scratch. If the record is brought back then forward, it is a scratch but then you have different kinds of scratching techniques from the baby scratch to the crabbing.
In dancehall music I know DJs do a lot of "Pull up", they stop the record by rewinding it and then they play it again from start.
If you have another link where we can hear it, please share it.
Comment: Did you listen to the mix at the 114 minute mark?
It's also done 3 times in a row at the 113 minute mark as well.

I'm not well versed in the terminology, but I looked up Baby Scratch and they don't really sound any bit a like. Maybe that's because the videos I watched they used a less complicated sound to scratch. There is no album scratch sound in it, just the record being played in reverse for a moment.

I think the comment by NReil describes it really well.
Answer: the used effect is to sensor explicit lyrics.
It is a function on the 'club standard' DJ players from Pioneer.
The effect is called: Reverse on Slip Mode
reverse wil play the backwards. slipmode  is the mode that will pick up the song were it should be if you would not play it backward (so it stays in time)
(there are some other effects you can use in slipmode like making (short) loops for a stutter effect.
Irie!
jimmy Spliff
'get together & feel alright'
ps: a demo video


Prove $\sum 3^k = O(3^n)$

Question:
Prove $\sum_{k=0}^n 3^k = O(3^n)$.

Below there is a picture from my text that contains the proof. My question pertains to the notation and/or assumptions in the proof. I don't need help with basic induction, below you'll see I'm not exactly sure what I'm confused about, it may be notation or possibly something quantifier related.

The author's explanation is giving me a bit of confusion near the end of the induction step when they require that
$$\left(\frac{1}{3} + \frac{1}{c}\right) \leq 1 \tag{A}$$
I'm not sure why the constant being less than $1$ is necessary. The way I was thinking of it (maybe my definition of big O notation is off) is that in our induction we should be verifying that
$$\text{if} \quad \sum_{k=0}^n{3^k} \leq c_1 3^n \quad \text{then} \quad \sum_{k=0}^{n+1}{3^k} \leq c_2 3^{n+1} \tag{B}$$
for some constants $c_1$ and $c_2$. If that's a valid induction approach then (by hijacking the author's proof)
$$\cdots \leq c_13^n + 3^{n+1} = \left(\frac{c_1}{3} + 1\right)3^{n+1}= c_23^{n+1} \tag{C}$$
Which would complete the proof.

T
Comment: The author's proof shows that there is one $c$ that works for every $n$ (namely every $c > 3/2$). If you allow $c$ to change in the inductive step, you're not proving anything interesting at all: for every function $f$ with $f(n) > 0$, you can always find $c_n$ with $\sum_{k=0}^n 3^k \leq c_n f(n)$. So you would get that the series is in $O(1/n)$, for example.
Answer: Use the Geometric Series Theorem:
$$\sum_{k=0}^n 3^k = {3^{n+1} - 1 \over 2} = (3/2)3^{n} - 1/2 = O(3^n)..$$

Prove $\sum 3^k = O(3^n)$


Mozart Notated Staccatos - Continuing After Notation Ends?

Question: In Mozart's "Don Giovanni" there are many phrases notated as staccato which, after 2-3 measures, no longer have the staccato notation to the end of the phrase. (Ex. Dover full score p.393 measures 251-256 in Violin II).

Is it Mozart's intention that the staccati continue to the end of the phrase or do they revert back to non-staccato notation as written?
Any help greatly appreciated!
Comment: Is that by any chance Act II scene 23, a recit starting "Crudele"?
Comment: Note to self for a future answer: the relevant bit in the manuscript is p 199-200 of https://vmirror.imslp.org/files/imglnks/usimg/4/45/IMSLP351835-PMLP36804-mozart-don-giovanni-act2-lores.pdf. The articulation marks do stop where Dover stops, though I might interpret them as dots rather than vertical strokes.
Comment: Meanwhile the short version of my answer is that yes, composers (and Mozart, and especially in this score) often don't bother writing "*simile*" when an articulation is clearly meant to continue.
Comment: @AndyBonner did they ever write it in the 18th century?  I always associated it with the 19th.  In the 18th century they just expected people to have a bit of common sense.  But in any event that's no recitative; it's a trio.
Answer: My guess, as it is only a guess but based on experience, is that the staccatos should continue.
I find that quite often notations come with an unstated expectation that the player should play in the style and feel of the period. There was no need to write this in the score or parts as the players simply knew how to play the music. A lot of small details would simply not be needed to be notated -- I believe the staccato simile is an example of that.
In more modern times similar things occur, examples might include "swing", where parts of the bars are "swung", i.e. the written notation is a simplification. Generally two eighth notes would be played closer to 2/3 + 1/3 triplets (although the exact "swing" is not exactly the same as triplets). From the same period as Mozart, Wiener Waltz, when performed for dancing is  played with a longer first beat of the bar compared to beat 2 and three. The players know the style and play things the "correct" way, as I guess the musicians at Mozart's time would have done without detailed instructions in their parts.
An additional problem arises when editors of later times start adding their own interpretation of how to indicate the correct way to play the music. You can find the same score (and parts for musicians) with wildly different notations depending on when the score was edited. In the original question I believe (guessing) that the score has been edited according to the editor's taste adding the staccatos but not the simile.


All consumers of a Provider will re-render when value prop changes?

Question: I'm trying to understand React Context API better. In the react docs I stumbled on this paragraph:

All consumers that are descendants of a Provider will re-render
whenever the Provider's value prop changes. The propagation from
Provider to its descendant consumers (including .contextType and
useContext) is not subject to the shouldComponentUpdate method, so the
consumer is updated even when an ancestor component skips an update.

I'm having a hard time understanding this, since the definition of a consumer is a little unclear to me. If I try to create an example (codingsandbox) the result is always the same: If the value changes, all children (not consumers) of the Provider rerender.
I'd love to understand what is meant by the paragraph above. Is there a case where the context value updates without triggering a new render of its children (preferably in a function component)?
Answer: The problem, according to your sandbox, is how state is being managed in the main app component.
<code>  //your useState
  const [store, setStore] = React.useState([]);

  //the button that is setting the state
  <button onClick={() => setStore([])}>Reset store value</button>
</code>
This causes the state in the component to change, which rerenders the App component itself, which causes a rerender of all it's children. If you wish to update the context state only, you should avoid storing the value in state and rather directly mount the function within the Context Object for logic to change the property within the value object
Comment: @Xen_mar It implies it. After all, when you render a component, it does need to call the render functions for all children (unless they opt out of that with e.g. `shouldComponentUpdate()` or `React.memo`).
Comment: hey, I have figured out why this is the case, will edit the answer
Comment: Ok, it certainly looks like it. But in this case I'd argue that the react documentation is wrong here. For me, consumers does not mean "all children".
Comment: Thanks @AKX - I'd still argue that this is not completely correct. To me, a consumer would be a component that either uses `useContext` or ``. To me, the paragraph implies that a value change would only update the consumers and their respective subtrees. This would mean that components would have a subscription relationship to their provider vs. a prop-based relationship.
Comment: After all, if we look at something like redux, we also see a subscriber-consumer based relationship that only updates respective subtrees.
Comment: Thanks! I actually hadn't looked at it from this perspective. Just a short note to the docs: Nowhere are they "mounting the function directly within the context object". The docs store the value in state, too. They're just defining an initial shape of the context that mirrors the expected shape. I tried putting a mutable `ref.current`value into a context, but without the rerendering nothing is happening. So I guess its all-or-nothing when it comes to rerendering. I'm still quite sure the docs on this are wrong or at least misleading.