Does Search API index custom fields?

Question: I am using search API on my website (Version 1.8), I have a problem with indexing custom fields. In the Configuration -> Search and metadata -> Search API I have added the custom fields to be indexed, in the view in the "Fulltext search" the custom fields appeared. In the database I can see that the fields got indexed. But when I test, there is no result. Has anyone had similar troubles with Search API?
Edited: The problem occurs only with the fields of "Entity reference" type
Comment: `The problem occurs only with the fields of "Entity reference" type` well that's because entity reference fields are saved as id's (numbers and not text) in the database. So if you were to search by id it should work.
Comment: Thanks, but most obviously the users will search other users by names, not by ids. I am searching for some additional module, which could map ids with the names.
Answer: You probably need to index the referenced entity Name* (assuming you want to search on name) as a field instead of just simply the entity ID (which is what entity reference fields actually store). The pattern should look something like the following on the 'fields' page:
field_yourfield:entity:name
Comment: I am doing that, but not working. Have indexed field_contact:entity:name , made "Fulltext" type, but no result.
Comment: Down on the page there is a note: The following fields cannot be indexed since there is no type mapping for them:
Comment: Hm I would say forget the fulltext and just try as a string (no need for fulltext with an entity name). What exactly is the entity reference to? Sounds like maybe it's users?
Comment: yes, exactly. I have a custom field_contact field. And I need to implement search by contact. So in the interface i picked field_contact:entity:name but getting abovementioned message

Does Search API index custom fields?


Using DKIM from G Suite with Exim 4

Question: I have a account in G Suite (Google Apps) and i made a DKIM, is possible use this DKIM to sign sent emails from my server through exim?
If possible, how i configure the exim?
Comment: Umm, so if not by SMTP, how *are* the mails sent?
Comment: @EEAA Yep, is sent by SMTP.
Answer: Is not possible use the DKIM generated by G Suite. The G Suite support said is possible use two DKIM for one domain.
So, i follow this article: DKIM-signing outgoing mail with exim4
This another article complete the previous one: Can't get Exim4 to DKIM sign outgoing mail?

Using DKIM from G Suite with Exim 4


Xamarin Forms: Scroll to is not working when reversing the collection data

Question: I have 3 tabs on the top of the page where I am listing some data using ListView. When I tap on a tab I need to scroll to the end of the listview, I mean I need to scroll to the last item of the ListView. I am reversing the collection before setting it to the ListView. I used below codes to scroll to last item:
settingslistview.ScrollTo(tab1settingList[tab1settingList.Count - 1], ScrollToPosition.End, false);

This is working fine if we not reverse the data. But when reversing the scrolling is not working.
I am adding the sample codes of my demo project below:
MainPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ScrollToDemo.MainPage">

    <StackLayout>
        <Grid
            Margin="10,0,10,0"
            VerticalOptions="StartAndExpand">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="33*" />
                <ColumnDefinition Width="34*" />
                <ColumnDefinition Width="33*" />
            </Grid.ColumnDefinitions>

            <StackLayout
                Grid.Column="0"
                HorizontalOptions="FillAndExpand"
                Margin="2,0"
                VerticalOptions="FillAndExpand"
                Orientation="Vertical">

                <StackLayout.GestureRecognizers>
                    <TapGestureRecognizer
                        Tapped="Tab1Tapped"
                        NumberOfTapsRequired="1">
                    </TapGestureRecognizer>
                </StackLayout.GestureRecognizers>
            </StackLayout>

            <StackLayout
                Grid.Column="1"
                HorizontalOptions="FillAndExpand"
                Margin="2,0"
                VerticalOptions="FillAndExpand"
                Orientation="Vertical">

                <StackLayout.GestureRecognizers>
                    <TapGestureRecognizer
                        Tapped="Tab2Tapped"
                        NumberOfTapsRequired="1">
                    </TapGestureRecognizer>
                </StackLayout.GestureRecognizers>
            </StackLayout>

            <StackLayout
                Grid.Column="2"
                HorizontalOptions="FillAndExpand"
                    Margin="2,0"
                VerticalOptions="FillAndExpand"
                Orientation="Vertical">

                <StackLayout.GestureRecognizers>
                    <TapGestureRecognizer
                        Tapped="Tab3Tapped"
                        NumberOfTapsRequired="1">
                    </TapGestureRecognizer>
                </StackLayout.GestureRecognizers>
            </StackLayout>
        </Grid>

        <ListView
            x:Name="settingslistview"
            HasUnevenRows="True"
            SelectionMode="None"
            SeparatorColor="#cecece"
            SeparatorVisibility="None">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <Frame
                                HasShadow="False"
                                Padding="8"
                                CornerRadius="{OnIdiom Phone=20, Tablet=30}"
                                BorderColor="#bdbdbd"
                                Margin="5"
                                BackgroundColor="{Binding BGColor}">

                                <StackLayout
                                    VerticalOptions="FillAndExpand"
                                    Margin="5,0,5,0"
                                    Orientation="Horizontal">

                                            <OnIdiom x:TypeArguments="x:Double">
                                                <OnIdiom.Phone>18</OnIdiom.Phone>
                                                <OnIdiom.Tablet>27</OnIdiom.Tablet>
                                                <OnIdiom.Desktop>18</OnIdiom.Desktop>
                                            </OnIdiom>

                                </StackLayout>
                                <Frame.HeightRequest>
                                    <OnIdiom x:TypeArguments="x:Double">
                                        <OnIdiom.Phone>30</OnIdiom.Phone>
                                        <OnIdiom.Tablet>45</OnIdiom.Tablet>
                                        <OnIdiom.Desktop>30</OnIdiom.Desktop>
                                    </OnIdiom>
                                </Frame.HeightRequest>
                            </Frame>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.Footer>

            </ListView.Footer>
        </ListView>
    </StackLayout>
</ContentPage>

MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace ScrollToDemo
{
    public partial class MainPage : ContentPage
    {
        public ObservableCollection<SettingPageItems> tab1settingList;
        public ObservableCollection<SettingPageItems> tab2settingList;
        public ObservableCollection<SettingPageItems> tab3settingList;
        public MainPage()
        {
            InitializeComponent();
            tab1settingList = new ObservableCollection<SettingPageItems>();
            tab2settingList = new ObservableCollection<SettingPageItems>();
            tab3settingList = new ObservableCollection<SettingPageItems>();
            Tab1Items();
            Tab2Items();
            Tab3Items();
        }

        private void Tab1Tapped(object sender, EventArgs e)
        {
            tab1_label.FontAttributes = FontAttributes.Bold;
            tab2_label.FontAttributes = FontAttributes.None;
            tab3_label.FontAttributes = FontAttributes.None;
            settingslistview.ItemsSource = tab1settingList.Reverse();
            if (tab1settingList.Count != 0)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    settingslistview.ScrollTo(tab1settingList[tab1settingList.Count - 1], ScrollToPosition.End, false);
                });
            }
        }

        private void Tab2Tapped(object sender, EventArgs e)
        {
            tab1_label.FontAttributes = FontAttributes.None;
            tab2_label.FontAttributes = FontAttributes.Bold;
            tab3_label.FontAttributes = FontAttributes.None;
            settingslistview.ItemsSource = tab2settingList.Reverse();
            if (tab2settingList.Count != 0)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    settingslistview.ScrollTo(tab2settingList[tab2settingList.Count - 1], ScrollToPosition.End, false);
                });
            }
        }

        private void Tab3Tapped(object sender, EventArgs e)
        {
            tab1_label.FontAttributes = FontAttributes.None;
            tab2_label.FontAttributes = FontAttributes.None;
            tab3_label.FontAttributes = FontAttributes.Bold;
            settingslistview.ItemsSource = tab3settingList.Reverse();
            if (tab3settingList.Count != 0)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    settingslistview.ScrollTo(tab3settingList[tab3settingList.Count - 1], ScrollToPosition.End, false);
                });
            }
        }

        public void Tab1Items()
        {
            for(int i =1; i<= 20; i++)
            {
                tab1settingList.Add(new SettingPageItems() { Title = "Option"+i, BGColor = Color.FromHex("#e4e4e4"), TextColor = Color.Black });
            }
            settingslistview.ItemsSource = tab1settingList.Reverse();
        }

        public void Tab2Items()
        {
            for (int i = 21; i <= 40; i++)
            {
                tab2settingList.Add(new SettingPageItems() { Title = "Option" + i, BGColor = Color.FromHex("#FFEBEE"), TextColor = Color.Black });
            }
        }

        public void Tab3Items()
        {
            for (int i = 41; i <= 60; i++)
            {
                tab3settingList.Add(new SettingPageItems() { Title = "Option" + i, BGColor = Color.FromHex("#E8EAF6"), TextColor = Color.Black });
            }
        }
    }
}

public class SettingPageItems : INotifyPropertyChanged
{
    public string Title { get; set; }

    private Color bgColor;
    public Color BGColor
    {
        set
        {
            if (value != null)
            {
                bgColor = value;
                NotifyPropertyChanged();
            }
        }
        get
        {
            return bgColor;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private Color textColor;
    public Color TextColor
    {
        set
        {
            if (value != null)
            {
                textColor = value;
                NotifyPropertyChanged();
            }
        }
        get
        {
            return textColor;
        }
    }

    private string imageSource;
    public string ImageSource
    {
        set
        {
            if (value != null)
            {
                imageSource = value;
                NotifyPropertyChanged();
            }
        }
        get
        {
            return imageSource;
        }
    }
}

App.xaml
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ScrollToDemo.App">
    <Application.Resources>

    </Application.Resources>
</Application>

I have uploaded a sample demo here. I need to scroll to the last item of the listview when switching to other tabs. Currently it is on top of the page when switching.
Answer: Look at the following code:
    private void Tab1Tapped(object sender, EventArgs e)
    {
        ...
        settingslistview.ItemsSource = tab1settingList.Reverse();
        if (tab1settingList.Count != 0)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                settingslistview.ScrollTo(tab1settingList[tab1settingList.Count - 1], ScrollToPosition.End, false);
            });
        }
    }

You use  tab1settingList.Reverse(); and set it to ItemsSource. The Reverse method returns a reversed IEnumerable but it doesn't modify the origin collection. That means tab1settingList's order is not changed. So when you use scrollto method, the last item in tab1settingList is still option20.
You may do something like this:
private void Tab1Tapped(object sender, EventArgs e)
{
    ...
    ObservableCollection<SettingPageItems> reversedtab1settingList = new ObservableCollection<SettingPageItems>(tab1settingList.Reverse());

    settingslistview.ItemsSource = reversedtab1settingList;
    if (tab1settingList.Count != 0)
    {

        Device.BeginInvokeOnMainThread(() =>
        {
            settingslistview.ScrollTo(reversedtab1settingList[reversedtab1settingList.Count - 1], ScrollToPosition.End, false);
        });
    }
}

For more info, you may refer to Enumerable.Reverse(IEnumerable) Method
Hope it helps!


how to write continue in this way of typing "if"

Question: hey I want to type if statement with the way 2 but I need to put there a continue and it not working with any ideas ?
way 1 to type if
if ( x+2 < 0) {
    y=x+2;
}
else {
    y=-(x+2);
}

way 2 to type if
y=(x+2 < 0) ? x+2 : -(x+2)

my question how to type continue in the second way something like this :
(x==1) ? continue : x+1 ;

but this not working for me.
Comment: `continue` is used in *loops* to *continue* to the next loop iteration.
Answer: The ternary operator (?) just returns a value (conditionally). You can't use it to execute arbitrary blocks of code. In other words, if you need to conditionally call continue, you need to use an if structure, not a ternary.


Fail to load eBPF/XDP code on Raspberry Pi

Question: The main issue is that I am not able to load a eBPF code in the network interface (XDP).
I am trying to load at Raspberry Pi 3, with the following configuration:

Raspbian GNU/Linux 10 (Buster)
Kernel 4.19.50-v7+

I am using ip command as follows:
$ sudo ip -force link set dev wlan0 xdp obj portfilter.o sec filter

Prior to this, I performed clang-7 installation through apt and make command is working correctly (generation the object).
The Makefile source code is as follows:
# SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause)

LLVM_VERSION ?= -7 #update with correct LLVM / clang version
LLVM := $(shell clang$(LLVM_VERSION) --version)
CLANG_FLAGS ?= -W -Wall \
    -Wno-compare-distinct-pointer-types

SRCS=$(wildcard *.c)
OBJS=$(patsubst %.c,%.o,$(SRCS))
Q ?= @

INCLUDE_DIRS ?= -Iheaders/

%.o: %.c
    @echo "\tLLVM CC $@"
    $(Q) clang$(LLVM_VERSION) $(INCLUDE_DIRS) -O2 -emit-llvm -c $< $(CLANG_FLAGS) -o $(patsubst %.o,%.llvm,$@)
    $(Q) llc$(LLVM_VERSION) -march=bpf -filetype=obj -o $@ $(patsubst %.o,%.llvm,$@)
    $(Q) rm $(patsubst %.o,%.llvm,$@)

ifeq ($(LLVM),)
all:
    $(warning Install LLVM to compile BPF sources)
else
all: $(OBJS)
endif

clean:
    rm -f *.llvm
    rm -f *.o

.PHONY: all clean

And portfilter.c source code that is expected to be loaded:
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <linux/bpf.h>
#include <linux/icmp.h>
#include <linux/if_ether.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include "bpf_endian.h"
#include "bpf_helpers.h"

/* 0x3FFF mask to check for fragment offset field */
#define IP_FRAGMENTED 65343

/* Port number to be dropped */
#define PORT_DROP 80

static __always_inline int process_packet(struct xdp_md *ctx, __u64 off){

    void *data_end = (void *)(long)ctx->data_end;
    void *data = (void *)(long)ctx->data;
    struct iphdr *iph;
    struct tcphdr *tcp;
    __u16 payload_len;
    __u8 protocol;

    iph = data + off;
    if (iph + 1 > data_end)
        return XDP_PASS;
    if (iph->ihl != 5)
        return XDP_PASS;

    protocol = iph->protocol;
    payload_len = bpf_ntohs(iph->tot_len);
    off += sizeof(struct iphdr);

    /* do not support fragmented packets as L4 headers may be missing */
    if (iph->frag_off & IP_FRAGMENTED)
        return XDP_PASS;

    if (protocol == IPPROTO_TCP) {
        tcp = data + off;
        if(tcp + 1 > data_end)
            return XDP_PASS;

        /* Drop if using port PORT_DROP */
        if(tcp->source == bpf_htons(PORT_DROP) || tcp->dest == bpf_htons(PORT_DROP))
            return XDP_DROP;
        else
            return XDP_PASS;

    } else if (protocol == IPPROTO_UDP) {
        return XDP_PASS;
    }

    return XDP_PASS;
}

SEC("filter")
int pfilter(struct xdp_md *ctx){

    void *data_end = (void *)(long)ctx->data_end;
    void *data = (void *)(long)ctx->data;
    struct ethhdr *eth = data;
    __u32 eth_proto;
    __u32 nh_off;

    nh_off = sizeof(struct ethhdr);
    if (data + nh_off > data_end)
        return XDP_PASS;
    eth_proto = eth->h_proto;

    /* demo program only accepts ipv4 packets */
    if (eth_proto == bpf_htons(ETH_P_IP))
        return process_packet(ctx, nh_off);
    else
        return XDP_PASS;
}

Unfortunately, the actual output after ip command is as follows:
mkdir /sys/fs/bpf failed: Operation not permitted
Continuing without mounted eBPF fs. Too old kernel?

Prog section 'filter' rejected: Function not implemented (38)!
 - Type:         6
 - Instructions: 38 (0 over limit)
 - License:

Verifier analysis:

Error fetching program/map!

But the expected result is the module loaded correctly in network interface.
This code is working on a laptop with Ubuntu 18 with Kernel 4.15.0-54-generic
Please, someone knows how to correctly configure the raspberry pi to work with this code ?
Comment: Just in case, did you check that your kernel has BPF support? What does `grep BPF /usr/src/linux-headers-$(uname -r)/.config` give you?
Comment: (Or probably your .config file is not at the location I provided -- Just follow pchaigno's instructions instead :) )
Comment: Confirmed that a recompilation of kernel is required. The .config missing eBPF configuration
Answer: Your kernel likely isn't compiled with BPF support (my 4.15 Raspbian isn't). You can check that with the following steps:
sudo modprobe configs
zgrep -E "(BPF|XDP)" /proc/config.gz

Both CONFIG_BPF and CONFIG_BPF_SYSCALL should be enabled. If they aren't, then you need to recompile your kernel with these configs enabled.
Comment: Confirmed @pchaigno inspection of .config that
 CONFIG_BPF = y
but
 # CONFIG_BPF_SYSCALL is not set

Then a kernel recompile was performed:

$ make menuconfig

Configure the following:

 1) Networking support
 2) Networking options
 2.1) XDP sockets
 2.2) BPF based packet filtering framework
 2.3) enable BPF Just In Time compiler

Then also configure:

 1) General setup
 1.1) Enable bpf() system call
 1.2) Permanently enable BPF JIT and remove BPF interpreter (Y)

Comment: No `zgrep` on the Pi?
Comment: There is. I always forget about these commands. Fixed, thanks!


Display the taxonomy term name in the page.tpl from a node

Question: I want to show the term name in the header for every node. Whats the best way, espacially if the node has 2 fields with taxonomy terms and the page is in different languages.
This display nothing, but gives me also no errors:
<?php if ( !empty($node) && $node->type == 'content-type') {
  print render(field_custom('node', $node, 'field_custom', array('label'=>'hidden', )));
}
?>

EDIT
preprocess_node:
global $language;
$wrapper = entity_metadata_wrapper('node',$variables['node']);
$variables['term1'] = $variables['term1'] ->language($language->language)->field_term_ref->value()->name;

page.tpl.php:
<?php print $term1 ?>

I don`t get any term name.
Comment: sry, the syntax error was only here a fault ;)
Comment: What modules are you using for different languages and what field of taxonomy term do you want to display?
Comment: You have a syntax error. You need a closing single quote after 'field_custom'.
Comment: i use i18n, ctools, views and have 6 content types. one content type with 2 term fields and two with one term field. in total i use 4 taxonomies. That was the only way to merge the complexity of the site. little bit hard to explain. I think i can the one with two taxonomies avoid to display the extra info term.
Comment: was the syntax error just on here, or did that make a difference on your site?
Answer: I would use an entity metadata wrapper for this:
// Load the current active language.
global $language;
// Put the node object in a wrapper.
$wrapper = entity_metadata_wrapper('node', $node);
// Get the term object.
$term = $wrapper->language($language)->field_term_ref_1->value();
// Translate the term.
$translated_term = i18n_taxonomy_term_get_translation($term, $language);
// Pass the term name to page.tpl.
$variables['term1'] = $translated_term->name;

// The same for term 2.

// Now you can print them in your page.tpl.
print $term1;

Not sure if the language part works, though.
Comment: Have you extracted the node object from $variables['node']?
Comment: Cool, 1st time i get the name! But it is not the translated. You changed the script. The $content works only for node.tpl i need it in the page.tpl
Comment: I've updated my answer, hope this will be more helpful to you.
Comment: i get -> EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityDrupalWrapper->set() (Zeile 737 ... it works if i use the code directly in page.tpl but without translation.
Comment: Oh, you have right. but the code doesn`t work. i edit my question with last changes
Comment: After your edit you have a hook_preprocess_node with page.tpl.php, that won't work. As you said before, you need the hook_preprocess_page for that and get the node object from there.
Answer: This is the 1st Solution, but the terms aren`t translated with -> i18n_taxonomy_term_get_translation($term, $language).
EDIT
The translation works with -> i18n_taxonomy_localize_terms($term). The language($language->language) in the $wrapper is not necessarry for the name translation:
    function MYTHEME_preprocess_page(&$variables) {
      if(arg(0)=="node" && is_numeric(arg(1))) {
        global $language;
        $wrapper = entity_metadata_wrapper('node',$variables['node']);
        $variables['term'] = '';
        if(isset($wrapper->field_term_ref1)) {
          $term = $wrapper->language($language->language)->field_term_ref1->value();
          $translated_term = i18n_taxonomy_localize_terms($term);
          $variables['term'] = $translated_term->name;
        }
        if(isset($wrapper->field_term_ref2)) {
          $term = $wrapper->field_term_ref2->value();
          $translated_term = i18n_taxonomy_localize_terms($term);
          $variables['term'] = $translated_term->name;
        }
      }
    }

Comment: I've edited my answer again to include term translation. Haven't tested it so I hope it works.
Comment: This doesn`t work, but no errors are shown. I try it with some other changes, but it is still in source language. The vocabulary settings are on localize and on other pages are all translations shown. Don`t know whats going wrong.
Comment: I see you've edited your answer after this comment, does that mean you got it working?
Comment: Yes. It works. Sry, i specify it better in the answer.


Can anyone learn to sing higher?

Question: So, I sing to myself a lot, and one thing that really frustrates me is that I cannot even reliably hit a middle C. (I'm male.) This is basically unacceptable to me even for ordinary shower-singing. Now after I'm a little warmed up, the highest note I've ever convinced myself I actually got was an Eb4. Now I see a lot of websites saying that you can damage your voice permanently (scary!) by straining too much. I think I might be doing this, since typically it hurts a little after any amount of time around middle C. Is there any way to determine if my voice is already damaged? One thing: if I'm ever able to reach, say, D4, it's only if I have a lot of breath and sing it loudly; it'll never come out if I try it soft.
When I search "how to sing higher" the most common advice is to 1) avoid falsetto and 2) avoid straining. That's like teaching someone to jump higher by telling them to 1) avoid cheats, like trampolines and 2) avoid jumping harder than you normally would; just jump naturally. Well, gee, I don't think I'll get any higher then! Any help?
Comment: You haven't mentioned how old you are. For men, their voices keep maturing across a long period of time—well into their late 20's or early 30's. Moreover, just because you don't know how to sing high doesn't mean you _can't._ It may be a matter of training, or it just might mean you're really a "power bass."
Comment: @aeismail By "mature", do you mean "just keep getting lower"?
Comment: No, I mean "develops," with changes at _both_ ends possible. My own range expanded by a fourth upward and a third downward during that time span. Other professional singers have talked about their range expanding over time as well, on both ends.
Comment: I increased my range dramatically by doing nasal tones and then over time learning to blend it with falsetto. So avoiding falsetto sounds a bit off. (I am in my 20's and have a Gaz Coombes style voice.)
Comment: @aeismail what type of third?
Answer: Simple advice is to take singing lessons. We here cannot know what you're doing and what you're doing wrong just by reading. You have to have a professional coaching you how to use your body in another way than you do now.
Comment: +1  Even if you can't afford to take lessons long-term, a few lessons for diagnostics and some of the basics will serve you well.
Comment: Also, helps if your teacher has a singing style similar to yours.
Answer: As Thomas Bryla said in another answer, there's really no substitute for working with someone who can hear what you're doing and observe your posture while you're doing it.  But here are some things I have learned from years of casual choral singing as a low female voice trying to do better (I usually sing tenor):

Breath support makes a big difference.  If you're feeling that straining in your throat, then you're not supporting the notes and you'll hurt yourself.  When you breathe in you should feel your diaphragm expand; as you sing you should feel it deflate.  This is hard to teach in writing.
Practice rising scales: start on a note, sing 1-2-3-4-5-4-3-2-1 on open vowels, then take the starting note up half a step and do it again.  (You can do the reverse going down too, to work on lower range.)  It's easier to approach the extremes of your range gradually and gently.  Once you're warmed up on that you can take in thirds.  (In both cases, make sure each note is crisp -- no slurring the pitch.)  Exercises are boring compared to singing the songs you like, but over time they'll get you there.  I've finally managed to smooth out an awkward break in my range doing this, and I can now produce a D5 if I have to (though I'm not happy about it; I'm really not comfortable much above B4).
When it hurts, stop for a while.  Don't wait for it to get bad.
Answer: You can definitely enhance your range a little with tuition. However, professional singers, like the rest of us, sing with what nature gave them. That's why there are some men who have the most wonderful rich, pure voices very low down. Singing high is just not important compared to singing well without strain, and a teacher can help you do both. You can always sing your favourite songs on a starting note of your choice if unaccompanied, or sing down an octave or harmonise if accompanied. Again, you might like some musicianship training for this to make it easier.
If you've not yet done so, how about looking up the ranges used for bass, tenor etc to see where you fall in the spectrum. You are not alone!
Comment: "Professional singers . . . sing with what nature gave them." This is a factually misleading statement: some of the most famous singers of our time, including Placido Domingo, "built" their voice. (Domingo, for instance, was originally a baritone!) Nature may have given people a lot more talent than they know.
Comment: Good question. I don't think I'd expect a tenor voice to emerge, but from my own experience—going from a chest voice upper limit of E♭4 to nearly A4 during my 20s, I think a solid baritone range could be possible. But, as I said, he could just as easily be a power bass that can't really have the upper range. It depends a lot on how old JJS is, what kind of sound profile he has, and how important it is for him to extend his range upward.
Comment: Interesting point about Domingo. Do you think think bodes well for JohnJamesSmith?
Answer: There's a lot of people that seem to tell you that you're not built to sing high but that's not exactly the truth. When i first went through puberty around 12 i couldn't sing middle c either but as i got vocal training i can now sing up to an A and feel no strain. It's a matter of how to learn to use your upper register.
Answer: As some other people have already mentioned, find a reputable vocal teacher to give you lessons. I myself am a bass baritone and have been taking singing lessons for the past 2-3 months or so. Before I had been struggling not only with range plateaus but worse yet, with plateaus in technique (or better said, lack of technique). Obviously, I am still struggling, but I can already see the light at the end of this very long tunnel.
Mind you, even with lessons, progress is slow, there are no magic bullets but one thing I can guarantee you, is that when you find freedom of the voice, you will forget all the things about range and start to relish in singing. There is no better feeling than singing with the freedom of the vocal instrument.
And freedom IS key if you want to sing WELL. Maybe there are some potentially damaging techniques for range expansion, but if you want to sing WELL and to really get to enjoy your singing, you need to free up the body tension.
P.S. Your story in many ways resembles mine. When I started to be range aware, the best I could hit was Eb4. With practice, a lot of bad technique and "improved" air pressure, I managed to get up to F4. Now I am going back down on working on actual singing and not on some notes. The notes will come, I can already sense that notes around the C4 are much fuller now.
Answer: It sounds like you are a bass. I'm a tenor. I can sing higher than you, but I bet you can sing way lower than me.
Some men are born to sing bass, some to sing baritone, and some to sing tenor. It's determined by your physiology, and that you cannot change.
Get some singing lessons from a professional voice teacher and learn what your natural range is, and how to work with the range you've got.
If you're a bass, then look for some songs to sing that were written for a bass and not for a tenor.
Comment: It seems though that with practice and proper technique, you could expand your range somewhat.
Comment: @WheatWilliams: Voices develop over time. A bass might not be able to sing tenor _right now_, but that doesn't mean he will never be able to sing tenor. (I've moved up from high baritone to first tenor in the last few years, so I know it's possible!)
Comment: That's what I said. Identify what your natural voice type is, and how to work with the range you've got. A person who is a bass can never sing tenor. A person who is a tenor can never sing bass. But you can learn to expand the range of notes you can sing *based on* your voice type: bass, baritone or tenor.
Comment: @WheatWilliams: Luke said that it's possible to expand your range some though, so that even a bass could still grow to be able to sing a bit higher over time.
Comment: First off, I really want to know if JohnJamesSmith is indeed a bass, and only a lesson or two with a professional voice teacher will answer that question for him. Second, I have to disagree with aeismail because his experience is unique to baritones. Some lucky baritones can also sing tenor with a good deal of training. Baritones have the widest range of all male voices. But a real tenor can never sing bass, and a real bass can never sing tenor. My point is "know thyself" and then start working on expanding your range within the context of the voice part you were born to have.
Comment: Many of us would love to have a good bass.
Answer: I've been training for about 4 years. So I've developed my voice to give myself a solid range. I'm a 21yo male, if it matters. Like said above, you could just be a bass singer. An untrained bass would struggle with Eb4 as a trained bass' limit is generally around an E4-F4. Now you didn't state an age.... But I was 17 when I started singing and I found notes higher than a middle C tricky back then too. But I enjoyed singing and kept working at it, just because I wanted to. With the vocal training I've had, by definition, I'm a bass-baritone. (like most men) I have a chest voice range spanning from roughly F2-G#4. G#4 being raised from the same limit of the OP. It's very true that you have to build your voice. You don't just have one.... Singing is a way of life. It's what I've noticed over the past 4 years. The only way to develop your voice is to treat it like a job. Now to the advanced stuff... Everyone has a chest voice range and a falsetto range. But not many people know that you can actually combine the two together and use them at the same time to form a 'mixed' voice. It's very difficult to master. I'm in the process of it myself. But it virtually eliminates 'vocal range' and voice categories like baritone and Tenor. It's very elusive and difficult to master, but it's how the rock band singers sing their songs. But for anyone struggling with limited range, is why I posted here. Research the 'mixed' voice. There are tutorials on Youtube but it's taken me about 6 months to actually work out how to use it myself (illusive). I said I'm a baritone but can easily hit a Tenor high C using this technique. I just need to actually get good at it, and work on the technique and tone of notes once so illusive to me and make sure I'm doing it correctly. Go to Youtube and listen to "Roy Kahn". I don't think there's a better master of the mixed voice, personally.
Comment: @Luke, that's just an approximation of the upper limit.
Answer: My voice teacher has worked as a voice teacher for over 20 years. She is very strict on teaching the healthy singing technique and I have had great success with her and developed my (opera) voice to a level I could never have imagined when I started singing lessons.
I am a bass (the lowest male voice type) and at the moment can still easily sing a healthy tenor high C (C5) and usually a bit higher notes than that. Voice teacher has said I have very good muscles for singing those high notes: as a result I also have no problems with the high bass notes E4/F4/F#4. I started voice lessons around 2010 and at that time struggled with notes above middle C (C4), so I think this has been a crazy improvement.
But this is not for granted for every person. My voice teacher also has other students that struggle with the high notes even though they have taken singing lessons with her longer than me. One bass student struggles with the high bass D4. Baritones rarely have a very large tessitura: they seem to struggle with something starting from high Bb4.
If you cannot sing the high notes, it is perfectly normal. Singing is about the body and muscles and every person has different physique and biology. You could have such muscles that you never reach the very high notes, even though you have sung tens of years, but could still sing well with your "normal" tessitura (of your voice type).
I have also heard basses have larger vocal cords than other voice types (such as baritones) and that is why they might have similar high notes as tenors, but their comfortable voice range "sits" lower.
You could also have sung with the wrong technique your whole life before beginning with a good voice teacher, which could also mean that you have "stuck" your body with the wrong technique (= wrong muscles --> wrong muscle memory) and may not get out of that for several years, and e.g. struggle with the high notes.
I would not say "anyone can learn high notes". I would say "anyone can learn to sing in a healthy way and with their own voice", which also results in a possibility to sing very high notes in a healthy way.
Source: based on own (partly professional opera) experience and health, plus what my voice teacher has told. Please also remember that singing technique (e.g. singing high notes) is a complex labyrinth of learning things and there does not seem to be a consensus on which is the "right" singing technique and how does the singer's body/muscles work. There is a lot of quarrel and argument on the subject, everyone think their opinion is the right one. I base mine on the fact that over the years, my body (not only the vocal cords!) responds to my singing better and better, I feel less and less vocal fatigue on my vocal cords, I can more easily notice what I am doing wrong with my muscles (mainly facial muscles) when singing and my voice has grown a lot larger over the years. I think this tells that my voice teacher has taught me a healthy technique, and I myself have practiced the right things and corrected my mistakes very well, which still allows me to sing professionally if I want to pursue that career.
Answer: I've been singing for 7 years, and I think that anyone can definitely learn to sing higher. Obviously everyone has a maximum range, so there will come a point where you can't sing a higher note without losing tonality and possibly hurting yourself. I do not know why anyone would advise avoiding falsetto. Falsetto is an excellent technique that can not only allow you to sing in a higher range, but it can also sound great and provide an alternate tone for your singing when in the upper range.
It would be a good idea for you to master the range that you're most comfortable with, but it's great to try to expand your range and step outside of your comfort zone. Just make sure it does not hurt when you're singing notes that are higher than you normally sing. If it hurts try it in falsetto. If it hurts in falsetto, then it might be higher than you should sing. However, with proper practice and vocal exercises you may be able to hit those once hard to hit notes and possibly even go higher.
Answer: There is always the question what you are expecting to do with an extended range.  I can produce sound over about 4 octaves, but people would not be interested in hearing more than about 3 of those (when I transitioned from tenor to alto/bass, I had choir concerts where I had to change my place between tenor for the old repertoire, alto for baroque and earlier repertoire, and bass for romantic and newer stuff where a male alto would have been out of style).
To those who say "don't use falsetto", my advice is "go screw your own voice".  Falsetto is the base material for developing a good downward reaching head voice.  When done correctly, it delivers a rather pure tone that is pleasant to hear and blends well with other voices.  Yes, you are "out of style" in a group of "tenors" straining their baritonal chest voice into the tenor range, but a smooth falsetto will blend even better with three strained quasi-tenor chest voices than a fourth strained quasi-tenor chest voice.
Strained voices blend badly.  You can hear out every one of them.  True tenors (those with a naturally high-reaching chest voice not requiring force) are rare.  Work the ranges you can reach comfortably with the best register and voice type you can employ.  While it takes years of practice to connect disjoint registers into smooth and controlled transitions and mixed voice types, working on the connection when you don't have the basic styles at the end points well under control on their own will not be feasible.
The mixed rein is really tricky and it makes sense bridging it from two solid shores.
Answer: My experience so far is that you CAN sing higher, as high as a tenor or even higher, but you will never sing the way a tenor does, if that's what you expect...When I started I probably couldnt sing higher than F#4 for instance(probably "yell", "sing" would be a compliment). Now I have gone as high as F#5 on good days. Basically anything you can hit with that soft falsetto voice you can hit it in your "normal" voice.
BUT your voice will still "feel like home" in a certain range of notes. This is called tessitura. It will feel more natural to sing there, your tone will be better and retain its fullness and your voice will have an easier time in general. In the end it's probably better to sing like a nice baritone/bass(assuming you are one) rather than a cheap imitation of a tenor.
I think choosing your notes is about finding the equivalent points between the different voice types. What I mean is that a tenor might sing a B4 as his high note but a bass might only hit an E4-F4. Still they might be both at the same "physiological point", it's the intensity that matters.
Answer: I had the same problem.  Notice I said had.  Your issue is one of technique.  Best advice is what others have said here which is to get a singing instructor.
I recommend a male just because imitation is so critical to the journey of singing better, and it is easier for you to imitate a male than a female voice obviously.
You can also look at Singing Success.  I don't have stock in the product, so don't worry. I'm not trying to sell you anything.  I just know how frustrated I got over this exact same issue.
Let me offer you this one piece of advice.  You are pushing too hard.  Pushing too much air.  And you are trying to sing your high notes with the full weight of chest voice.  It sounds thick and rich.  Think instead of lightening your voice to start to take on more of that tenor vocal quality.  I'm not saying you are going to become a tenor, but if you start to produce that tonal quality, then you are getting closer to proper technique needed to get higher.
So, instead of pushing, you've got to learn the  proper abdominal support and a "held back" feeling of support.  Back way off of the push.  Use MUCH less air.  Don't remove the supported abdominal feeling otherwise you will err on the other side which is to try to control the sound with your neck muscles.  Don't do that.  Keep a supported feeling but while using less air, see if you can find that lighter sound.  Let it crack if it wants to.  The cracking is a glimpse of what the lighter sound quality is supposed to be.
So let that happen while you are training.  Find a vocal coach who understands this phenomenon.  Good luck, and in the mean time, DON'T PUSH.  Pushing just forces the thicker, outer muscles of the larynx to take over, because the lighter, thinner edge muscles (the ones that make head voice and tonal brilliance) unable to hold back the air and vibrate to make the sound.  You reach a point where you cannot get any higher and the voice just stops.  Search for "head voice", and "vocal registration" and terms like that.  It's the head voice that you are missing, that will add brilliance even to your low register.  Strengthening head voice (the thin edges of the cords) will make the low stuff sound better and will allow you to go higher.  It will not turn you into a tenor or take away your low notes.
Answer: I am still not sure about how far you can increase your vocal range. But a typical baritone who practices on increases his range can get up to G4 (A4 being the extreme). Me being a lyric baritone I managed to get up to A4 with a slight strain, I can hit A4 sharp without falsetto but its just full straining and the note itself is very shaky and I can't hold it for long. I am not sure how far a baritone's range can increase but I heard there are limits to how far one can increase his range.
Answer: Anyone can sing higher with the right practice and commitment. I've found that the best way to practice is to sing along with songs that touch on notes which are just out of my comfortable range. This means that I have to strain a little bit but it's not enough to do real damage.
But the truth is, in order to get higher you have to strain some. It shouldn't be painful, but you may feel a slight ache. Drink lots of water, and suck on ginger root (anti inflammatory).

Can anyone learn to sing higher?


Natural discontinuities

Question: As I stare at a cube-shaped building whose side has length $100$ meters, while walking westward parallel to its north wall at a location $100$ meters north of the building, the distance to farthest point from me that I can see on the face of the building varies as my position changes.  As I cross the line of the western wall, I can suddenly see the southwest corner of the buidling, so that distance as a function of my position has a jump discontinuity that arises naturally from geometry.
Examples of jump discontinuities in things like Stewart's calculus text are as artificial as anything can be: they're defined piecewise.
I wouldn't mind expunging all mention of the topic from the usual calculus-for-liberal-arts students, but if it must be mentioned, natural rather than artificial examples seem infinitely preferable.  What other good ones are there?
Comment: Related question: [Nonpiecewise Function Defined at a Point but Not Continuous There](http://math.stackexchange.com/questions/651381/). Your example here would make an excellent answer to that.
Comment: I never understood the hate for piecewise definitions. How is it any more artificial than any other symbolic definition? Your question is really more about what sorts of problems would lead discontinuous functions in their formulation. (as opposed to what sorts of discontinuous functions might appear in the course of solving a problem, or what sorts of discontinuous functions can exist at all)
Comment: Perhaps there is something in the water, or perhaps Dr. Hardy and I are both teaching Calculus I at roughly the same pace. :)
Answer: Consider two unit circles, one centered at the origin and the other at $(3,0)$. Move the center of the left circle toward the right circle at a slow constant rate, so that its center at time $x$ is $(x,0)$. Let $f(x)$ be the number of intersection points between the two circles. Then $$f(x)=\begin{cases}0 & 0\leq x<1\\ 1 & x=1\\ 2 & 1<x<3 \\ 2 & 3<x<5 \\ 1 & x=5 \\ 0 & x>5\end{cases}$$
This function has jump discontinuities, as well as an infinite discontinuity at $x=3$! But I don't know how "natural" it is. It is easy to cook up such examples from geometry.
Comment: Of course if you want a discretely valued function to be continuous, it must be constant.  In algebraic geometry it is well-understood that the more realistic nice property of such functions is **semicontinuity**.  (And the fact that your function is not even semicontinuous is a motivation for counting intersection points in a more refined way...)

Natural discontinuities


Validação de CPF - Integration Services

Question: estou importando uma base com CPFs para o meu DW porém preciso fazer validação de CPF dentro do SSIS.
Alguém tem alguma ideia de como posso fazer isso?
Obrigada!

edit:
Consegui resolver da forma que eu queria.
Utilizei o script component, peguei um código de validação em c#.
Ficou dessa forma
Comment: Você quer saber se um dado número obedece à regra de formação do CPF ou se este número, além de obedecer à regra de formação, esta cadastrado na base de dados da receita como um CPF válido?
Comment: Quero saber se ele é um CPF válido de acordo com a base da receita
Comment: Então você terá que consultar a base de dados da Receita Federal. A consulta à Situação Cadastral lhe dará esta informação. O que não sei é se existe algum tipo de web service grátis para isso.
Answer: Pode utilizar uma função do SQL Server ?
<code>/*
  Cristiano Martins Alves
  Para testar: SELECT DBO.CPF_VALIDO('16195473247')
*/
CREATE FUNCTION CPF_VALIDO(@CPF VARCHAR(11))
RETURNS CHAR(1)
AS
BEGIN
  DECLARE @INDICE INT,
          @SOMA INT,
          @DIG1 INT,
          @DIG2 INT,
          @CPF_TEMP VARCHAR(11),
          @DIGITOS_IGUAIS CHAR(1),
          @RESULTADO CHAR(1)

  SET @RESULTADO = 'N'

  /*
      Verificando se os digitos são iguais
      A Principio CPF com todos o números iguais são Inválidos
      apesar de validar o Calculo do digito verificado
      EX: O CPF 00000000000 é inválido, mas pelo calculo
      Validaria
  */

  SET @CPF_TEMP = SUBSTRING(@CPF,1,1)

  SET @INDICE = 1
  SET @DIGITOS_IGUAIS = 'S'

  WHILE (@INDICE <= 11)
  BEGIN
    IF SUBSTRING(@CPF,@INDICE,1) <> @CPF_TEMP
      SET @DIGITOS_IGUAIS = 'N'
    SET @INDICE = @INDICE + 1
  END;

  --Caso os digitos não sejão todos iguais Começo o calculo do digitos
  IF @DIGITOS_IGUAIS = 'N'
  BEGIN
    --Cálculo do 1º dígito
    SET @SOMA = 0
    SET @INDICE = 1
    WHILE (@INDICE <= 9)
    BEGIN
      SET @Soma = @Soma + CONVERT(INT,SUBSTRING(@CPF,@INDICE,1)) * (11 - @INDICE);
      SET @INDICE = @INDICE + 1
    END

    SET @DIG1 = 11 - (@SOMA % 11)

    IF @DIG1 > 9
      SET @DIG1 = 0;

    -- Cálculo do 2º dígito }
    SET @SOMA = 0
    SET @INDICE = 1
    WHILE (@INDICE <= 10)
    BEGIN
      SET @Soma = @Soma + CONVERT(INT,SUBSTRING(@CPF,@INDICE,1)) * (12 - @INDICE);
      SET @INDICE = @INDICE + 1
    END

    SET @DIG2 = 11 - (@SOMA % 11)

    IF @DIG2 > 9
      SET @DIG2 = 0;

    -- Validando
    IF (@DIG1 = SUBSTRING(@CPF,LEN(@CPF)-1,1)) AND (@DIG2 = SUBSTRING(@CPF,LEN(@CPF),1))
      SET @RESULTADO = 'S'
    ELSE
      SET @RESULTADO = 'N'
  END
  RETURN @RESULTADO
END
</code>
fonte: http://www.devmedia.com.br/funcao-para-validar-cpf-no-sql-server/2723
Comment: Na vdd, eu preciso usar algum componente que faça a validação. Como o conditional split, q ai os cpfs validos eu vou inserir na tabela e os inválidos eu vou gerar um output.
Comment: aí é só usar a função... não ?
Comment: Da forma que eu queria fazer achei melhor usar o script component
Comment: bacana, você conseguiu valida-lo tambem na base da receita ?
Comment: Eu usei um script em C# que valida faz a validação. Que por fim é a mesma lógica do seu script
Comment: No comentario da sua pergunta, você diz que valida pela base da receita, a validação do codigo que postei, é pelo digito verificador. Você consegue validar pela base da receita ? ou seja, saber se o CPF está ativo na receita federal ?
Comment: Quando eu disse que valido pela base da Receita é pra saber se é um CPF que realmente existe. Acho que rolou uma confusão nesse conceito. Saber se ele está ativo ou não, não era o meu objetivo.
Comment: Certo, porém só alertando que essa lógica do dígito verificador, apenas informa se o número tem o formato do CPF, ainda assim, pode ser que não exista, ok? rsrs boa sorte =]

Validação de CPF - Integration Services


WinForms setup DataGridView with one column bound to List

Question: I'm using C# 4.0 and WinForms. I'm trying to get my DataGridView to be setup like this
[CheckBox]  [TextColumn]  [ComboBoxColumn]

This is for a menu similar to the SQL Server Import/Export tool. The checkbox will tell me whether the table is to be transferred. TextColumn is the source table name. And ComboBoxColumn is a list of the tables in the destination database.
Example
[Transfer]  [SourceTable]  [DestinationTable]
    X       MyTableSource  MyTableDest

Where MyTableDest would be a list I could choose from like (TableA, TableB, TableC), or I could input my own name.
I tried this.dataGridView.DataSource = myBindingList where mybindingList has my custom object that looks like
public class Mine {
   public bool Transfer { get; set;}
   public string Source { get; set;}
   public List<string> Destination { get; set; }
}

I don't need a full solution - just direction on how to achieve this
Comment: Your Destination property shouldn't be a list, it's just a string.  The drop down list for the DestinationTable would be the list.
Comment: @LarsTech But then how would the DestinationTable list get populated?
Answer: The Mine class isn't holding a list of destinations, only a single destination, so your class should look like this:
public class Mine {
  public bool Transfer { get; set; }
  public string Source { get; set; }
  public string Destination { get; set; }
}

Then using a DataGridView control that has those three columns you specified, this is a quick example to get it running:
Column1.DataPropertyName = "Transfer";
Column2.DataPropertyName = "Source";
Column3.DataPropertyName = "Destination";
Column3.DataSource = new List<string>() { "aaa", "bbb", "ccc" };

List<Mine> grid = new List<Mine>();
grid.Add(new Mine() { Transfer = true, Source = "xxx", Destination = "bbb" });
grid.Add(new Mine() { Transfer = false, Source = "yyy", Destination = "aaa" });
grid.Add(new Mine() { Transfer = true, Source = "zzz", Destination = "ccc" });

dataGridView1.DataSource = grid;

Column3 is the ComboBox column where you specify the list of options in the DataSource property of that column, so the list is separate from the class of Mine objects.


Obstructions to lifting a map for the Hopf fibration

Question: This is a bit of an elementary question, but
suppose $\pi: \mathbb{S}^3\to \mathbb{S}^2$ is the Hopf fibration, are there reasonably computable obstructions to when a map $f:M\to \mathbb{S}^2$ can be lifted to a map $\tilde{f}:M\to \mathbb{S}^3$?
If it matters everything can be taken in the smooth category. Also, I am most interested in the case that $M$ is an open subset of a oriented closed surface if this simplifies things at all.
My understanding is that if $M$ is a disk this there is no obstruction,
I apologize if this is trivial but it is not by area of expertise...
Comment: You're not asking a trivial question, not at all.  It looks like it could be a great homework question right after one has learned the basics of fiber bundles and obstruction theory.  Or bundles and classifying spaces.
Comment: I'm a big fan of the hopf fibration, its one of those examples I wish I had understood better when I was still a student...
Answer: The Hopf fibration is of the form
$$S^1 \to S^3 \to S^2$$
Since the Hopf fibration is an $S^1$-bundle, there is a classifying map
$$S^2 \to BS^1$$
where $BS^1 \simeq K(\mathbb Z,2) \simeq Gr^+_{\infty,2}$, i.e. it is the Grassmannian of oriented 2-dimensional vector bundles.  So the Hopf fibration is the pull-back of the unit circle bundle of this classifying map, moreover, the map $S^2 \to Gr^+_{\infty,2}$ is the generator of $\pi_2 Gr^+_{\infty,2} \simeq \mathbb Z$.
A map $M \to S^2$ lifts to a map $M \to S^3$ if and only if the pull-back of the generator of $H^2 S^2 \simeq \mathbb Z$ in $H^2 M$ is zero.  This is because the tautological circle bundle over $Gr^+_{\infty,2}$ is the Stiefel manifold $V_{\infty,2}$ which is contractible.  So the only obstruction is the map $M \to BS^1$, which via the Serre interpretation of $H^2$ is the pull-back of the generator under the map $M \to S^2$.
Comment: Thanks!  That is along the lines of what my intuition suggested (at least based on the identity map from the sphere to itself).


is there vpn type software out there that allows remote desktop-type gui capabilities for multiple concurrent users?

Question: *except buying in CAL licenses for Windows Server 200x.
I'd like this software to run on a windows desktop box. There would only be ~4 connections max at any one time to use a single app like excel so performance shouldn't be much of a worry.
basically I'd like each remote session to be unaware there is another user on the system i.e. independent sessions which is how I understand multiple user win server remote desktop works.
Is there an alternative out there?
Comment: This has nothing to do with VPN.
Comment: @sysadmin1138 The N in VPN is for Network; there's no secured network connection here, it's an application layer security he's after. I have to agree with Stephane, mentioning something like SSL (et al) would make much more sense, or simply stating "secured" even more so. Using the wrong terminology shows ignorance or lack of effort on the Questioner's part; that perception has been exacerbated by his uncouth responses. He's shown himself to be the type we shouldn't welcome in the community.
Comment: VPN-type software. AS IN SECURE REMOTE CONNECTION?! god. nothing to do with VPN...
Comment: I believe @Stephane is referring to the style of VPN that emulates a full network stack on a remote network, rather than a single secured application. Both can allow secure remote access, and can be called "VPN" by a wide variety of users, but VPN in the sense Stephane is talking about is not what is being discussed here.
Comment: SSL is predominantly for web based applications so someone who needs to get out more could flame for that too. Fact is the need for you to speculate on what another 'contributor' may or may not have meant shows clear ambiguousness in his response. But hey, if you get your rocks off at chastising randoms then I'd suggest you go elsewhere.
Comment: SSL is not "predominantly for web based applications". It's predominately for security application layer communications. I suppose the difference is lost on some.
Comment: This question is being locked because there is no longer any more constructive discussion happening, and we're diving into dangerous territory. So I'm stopping that now.
Answer: Windows has very explicit licensing requirements. I doesn't matter if it's a whole desktop or a single application (remote session application presentation). The peopling connecting must be licensed. There are administrative exceptions that allow certain use scenarios where you don't need to purchase licenses, but that's not what you're asking about. If you're asking how these licensing requirements can be skirted, this Q will be closed as OT (we do not condone licensing violations and will not help you do so).
If you need a whole application running you can use something else entirely like Citrix. But that's generally just as expensive as Windows Terminal Services and CALs.
If you just need to share an Excel-type spreadsheet (and/or other office documents) a hosted app like Google Docs would be much cheaper and provide almost all the same functionality (per common use).
Comment: If I'm not being too presumptuous, you probably have a small network and a server. You're thinking you can pop an application or two on the server and "share" it out to the other computers, with something similar to Remote Desktop Connections. And something simple like that seems like it should be cheap. The issue is that you're looking for the best of all worlds, full desktops, flexible server, connection/location abstraction and flexibility; all that capability and flexibility costs a lot (and there's no cheap way to get around that).
Comment: "If you need a whole application running you can use something else entirely like Citrix. But that's generally just as expensive as Windows Terminal Services and CALs."

So are there legal alternatives to the method I outlined or not? Why has this been voted down before you even hear me out? Jeez.
Comment: I didn't downvote, but it's most likely because what you're asking for is usually asked by people trying to break their licenses. The only legal way to share Windows sessions (running on actual MS Windows) is by having Terminal Services CALs. Citrix looks like Windows but for the sake of licensing is not. Another note, if you're sharing Excel via Terminal Services you need Excel CALs for every TS CAL (so 4 TS CALs would require 5 Excel/Office CALs). But this is getting deep into licensing and you'd need to talk in detail about your environment to get accurate licensing advice from MS.
Answer: If you want dumb terminals connecting to multiple sessions on a single host the only way to do it free and legally is with Linux.
Comment: There are quite a few other free OSes besides Linux distros...
Comment: OK, Unix-based OSes, generally, the many flavours of Linux out there being the most abundant and well supported.
Comment: No Unix-based OSes are free (AIX, HP-UX, SunOS, Xenix, etc); SCO still owns the rights to Unix and doesn't allow free distribution of any kind. Linux was 'inspired' by Minix, which wasn't even Posix compatible until 1997. Linux might have the greatest quantity, certainly not the greatest quality.


Get information from string with a wsdl in PHP

Question: I have:
<code>$data = file_get_contents('php://input');
</code>
and it returns this:
<code><soap:Header>
  <wsim:WSEAuthenticateHeader>
     <wsim:Usser>?</wsim:Usser>
     <wsim:Password>?</wsim:Password>
  </wsim:WSEAuthenticateHeader>
</soap:Header>
<soap:Body>
  <wsim:postScormRequest>
     <wsim:item1></wsim:item1>
     <wsim:item2></wsim:item2>
     <wsim:item3></wsim:item3>
  </wsim:postScormRequest>
</soap:'... (length=535)
</code>
How can I get the information of the user, password and items?
Comment: This is a duplicate of [How to parse SOAP XML](https://stackoverflow.com/questions/4194489/how-to-parse-soap-xml) .  The [accepted answer](https://stackoverflow.com/a/24085540/5517065) should work for your purpose.
Comment: You were using the PHP `SoapClient` in your other questions. Why not use that here?
Answer: Your XML is incomplete, as we talk on comments
Comment: Thanks a lot, but I can't use nusoap... I try to use simplexml whit `$obj = new SimpleXMLElement($data);

var_dump ($obj);` and say _object(SimpleXMLElement)[58]_ and try to cast to string `var_dump ((string) $obj);` and say _string '

' (length=9)_
Comment: There is something wrong with your payload. Where is the XML root tag (soap envelope) and its name Spaces?
Comment: Oh... you are rigth... the xml was wrong... When I fix it I can manage with SimpleXMLElement. Thanks a lot


Looking for a command line ftp client that can upload entier folder

Question: I need something like Filezilla that does the same thing in a console. The default ftp client on Ubuntu can only upload files, mput doesn't seem to work on folders. I have many folders and sub folders and doing so via command line is a pain. Also scp etc is not an option for me. Thanks.
Answer: lftp in conjunction with the mirror -R command.
Answer: Have a look at ncftp and its ncftpput -R command.
Comment: Cool! It even comes by default. :)
Comment: Thank you so much! I was looking for this tool for ages, I used it in 2006 and I forgot its name, now here it is!
Answer: The ncftp family is a very slick and powerful command line client that supports everything you want including interactive and batch jobs.


proto3 encoding - struct vs marshaled struct

Question: I wish to know if there could be any significant difference in terms of mem efficiency between marshaling a struct and marshaling a marshaled struct.
Example:
Assume we have a struct B with some fields.
message B{...}

The common representation:
message A {
    B b = 1;
}

Another way:
message A {
    bytes b = 1;
}

Where b is a marshaled B struct.
Generally, is it a good practice? any efficiency implications?
Thanks,
Elad
Comment: minor point - note that there's no such thing as "proto3 encoding" - the encoding hasn't changed at all in the public protobuf time; "proto3" relates only to the DSL syntax, and doesn't impact the encoding at all.
Answer: At the payload level, they are identical - however, in terms of how implementations treat them, there may be differences. The most obvious difference is that you can't use a bytes until you further deserialize it; this has pros and cons:

if you weren't ever going to touch it anyway, this could be fine and advantageous - avoiding some CPU processing that you didn't need for read or write; this will also mean that any downstream allocations (strings, etc) don't need to happen - so you only have a single allocation chunk: easy and efficient
if you do need to read it, then in addition to making life less convenient, you could have allocated an extra chunk of memory for the raw form (a chunk of bytes), and you'll need to allocate for the deserialized form; if you went straight to the deserialized form, most implementations would have skipped that intermediate allocation

So: yes, it will have different characteristics. Whether they are advantageous (or the opposite) depends on whether you also need to do the extra deserialization step on the bytes payload
Answer: I think it's a bad practice to declare a bytes field instead of a struct you would have otherwise specified in a proto file.
It's called a specification hole: you will have to write an additional documentation to describe how the receiver has to understand the bytes


yii flash message not displaying after redirection in view page

Question: flash messages was working fine in local when i moved it into production(cpanel) its not displaying. I am not getting any error or warning.
In controller, i am setting flash like this
Yii::app()->user->setFlash('success', "Slider updated Successfully.");

and in view,
<?php if (Yii::app()->user->hasFlash('success')): ?>

    <?php echo Yii::app()->user->getFlash('success'); ?>

<?php endif; ?>

Answer: The Yii flash messages are stored in the PHP session variables.
Are you able to set Session variables? Perhaps this will come in handy (Not able to set session variable in online server)
Comment: thankyou.. i had PHP session problem. its solved and working fine now


Two questions about normal distribution and its calculation

Question: dear community members, I got this question in my handbook for exam preparation. I was trying to calculate the output but I'm stuck with figuring out the correct value.
The question is:
According to the Census, self-employed individuals in Romania worked an average 44.6 hours per week, with a variance 210.25 hours. The average of hours worked among wage workers was 40 hours per week. Assuming this variable is approximately normally distributed, find the proportion who worked longer than wage workers on average (consider only two decimal points in computation).
So will it be just 5% standard deviation, and, thus, 5% of workers?
Answer: They tell you that $p$, the proportion of self-employed is approximately normal. Hence,
\begin{align*}
P(p>40) = 1-P(p<40) &= 1-P\left(Z<\frac{40-44.6}{\sqrt{210.25}}\right) \\
&= 1-\Phi(-0.3172414)\\
&= 0.6244698,
\end{align*}
where $Z$ is the standard normal distribution.


How to return an array from SQL in VB?

Question: I'm trying to run a SQL query from VB that returns an array of all unique values (Btl) for a given day, in time ascending order.
I'm working off of someone else's code and modifying from a version that only returned a single int value each day. (e.g. '1' , but I would like it to modify it to return '1 2 3 4')
I've tried to convert the 'Btl' variable to an array like 'Btl()' but I get the error that "Value of type 'Integer()' cannot be converted to 'Integer'"
        'Get 'wherecl' table
        Function GetBtl(ByVal tblRS As String, ByVal nday As Integer, ByVal sqlConn As
     SqlConnection) As Integer
        ' Get the day's sample bottle
        Dim wherecl As String
        wherecl = "WHERE (DATEDIFF(d, { fn NOW() }, TmStamp) = " & nday & ")"
        Dim Q4 As String

        ' SQL cmd to get array of unique bottles each day
        Q4 = "SELECT distinct BottleToSample FROM " & tblRS & " " &
    wherecl &
    " ORDER BY TmStamp ASC;"
        'End If

        Dim MCGQ4 As New SqlCommand(Q4, sqlConn)
        Dim Btl As Integer = MCGQ4.ExecuteScalar    'This is the bottle number
        Return Btl

    End Function

This version compiles, but doesn't display any results.
I would like it to deliver "1 2 3 4" for example
Comment: ExecuteScalar only returns one value, you'll have to use ExecuteReader
Comment: @RyanWilson DataAdapter is overkill. needs only a reader
Comment: @Mr.Tripodi Why is it overkill? So you can do `while DataReader.Read()` ???
Comment: Just use .Load method on DataTable. Actually, id probably just create the array from Reader and not use DT
Answer: As an unknown (presumably) number of bottles will be read, it is a good idea to put the data into a List(Of Integer) - a List will expand its capacity automatically when items are added to it. If you actually need the data in an array, that can easily be done.
When using a connection to a database, that connection should be opened, the data read, and then the connection disposed of immediately. SQL Server Connection Pooling makes that efficient. In the case of the code in the question, I achieved that by using the connection string from the connection. The Using Statement takes care of freeing up unmanaged resources even if something goes wrong.
Function GetBtl(ByVal tblRS As String, ByVal nday As Integer, ByVal sqlConn As SqlConnection) As Integer()
    Dim sampleBottles As New List(Of Integer)

    ' Get the day's sample bottles
    Dim wherecl As String = "WHERE (DATEDIFF(d, { fn NOW() }, TmStamp) = " & nday & ")"
    ' SQL cmd to get array of unique bottles each day
    Dim Q4 As String = "SELECT distinct BottleToSample FROM " & tblRS & " " & wherecl & " ORDER BY TmStamp ASC;"

    Using conn As New SqlConnection(sqlConn.ConnectionString),
          MCGQ4 As New SqlCommand(Q4, conn)

        conn.Open()
        Dim rdr = MCGQ4.ExecuteReader()

        While rdr.Read()
            sampleBottles.Add(rdr.GetInt32(0))
        End While

    End Using

    Return sampleBottles.ToArray()

End Function

Also, I notice that there is a line Dim Btl As Integer = MCGQ4.ExecuteScalar in the code in the question, which indicates that Option Strict is set to "Off". That is a sub-optimal condition; it would be a good idea to use Option Strict On. It could take some effort to correct all the code with that, but it will end up removing variable type problems.

How to return an array from SQL in VB?


if statement using char string - wont recognize string

Question: #include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

int main()

{
    bool flag= true;
    int menu_option;
    char first_band [16], second_band [16], third_band [16], fourth_band [16], green[16];

    while (flag)
    {

    printf("Please choose an option:\n");
    printf("To run the program, enter 1.\n");
    printf("For help, enter 2.\n");
    printf("To exit, enter 3.\n");
    scanf("%i", &menu_option);

       switch (menu_option)

      {
        case 1:
            printf("Please enter the colour of the first band on the resistor:\n");
            scanf(" %s", first_band);
            printf("Please enter the colour of the second band on the resistor:\n");
            scanf(" %s", second_band);
            printf("Please enter the colour of the third band on the resistor:\n");
            scanf(" %s", third_band);
            printf("Please enter the colour to fourth band ont he resistor. If there is no fourth    band, enter 'null'.\n");
            scanf(" %s", fourth_band);
            flag=false;
            break;

        case 2:
           flag=true;
            printf("program instructions");
            break;

        case 3:
           flag=false;
            return 0;
            break;

        default:
            flag=true;
            printf("Invalid command.\n");
            break;
       }

   }

       printf("%s", first_band);

       if (first_band == "green")
           printf("the first band is %c\n", first_band);

 return (0);

}

So i can't get the last "if" statement to print "the first band is %s". the print statement right           above it is to see if the program is even reading the user input...which it seems to be. It just won't seem to recognize the word and execute the if statement. I feel like my syntax is wrong when dealing with the char strings, which is causing this problem, but I'm new to this so a helping hand would be much appreciated.
Comment: You can't compare strings like that in C.
Comment: Use strcmp() to compare the contents of C strings.
Answer: You have to use strcmp() instead.
if (strcmp(first_band, "green") == 0)
           printf("the first band is %c\n", first_band);


How can I delete some data from Firebase Realtime Database?

Question: I have this functions to save and get data on it:
to save:
try {
        const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', {
        method: 'post',
        body: JSON.stringify(addNewLocation)
            })
        const response = await fetch(request)
        window.location.reload()
        return await response.json()
    } catch (error) {
        alert('Try again: ', error)
        }

//to get:

try {
        const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', { method: 'get'})
        const response = await fetch(request)
        return await response.json()
    } catch (error) {
        alert('Try again: ', error)
    }

And when I use "delete" instead of "get" it deletes the locations folder entirely, but when I use a link with a key at the end of the link, I get an error
Comment: Hello, if my answer was helpful you can accept it by clicking the tick icon. [What should I do when someone answers](https://stackoverflow.com/help/someone-answers) else feel free to ask further queries.
Answer: You need make a DELETE request at the location you need to delete.
curl -X DELETE \
  'https://[PROJECT_ID].firebaseio.com/locations.json'

const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', { method: 'DELETE'})
const response = await fetch(request)
return await response.json()

I'm not sure about how your database structure looks like but the above request will delete the whole "locations" node. Here's an example:

If you want to delete only location2, then make a delete request at https://[PROJECT_ID].firebaseio.com/locations/location2.json
I'm not sure if there's any specific reason for you to use the REST API but you can try using Firebase Web SDK. It's easier to use, for example to delete location2:
firebase.database().ref("locations/location2").remove()

Comment: Thank you so much. I forgot to add ".json" at the end of the link
Answer: you can use the remove method
let userRef = this.database.ref('users/' + userId);
    userRef.remove()

Comment: tip : adding code fences can highlight the code and make it better to read (especially if you have a lot of code)
Answer: You can use the following code
deleteSomeData(id) {
      fetch(
         // don't add .json at [data Name]
        `https://[your FireBase project url]/[data Name (don't add .json)]/${id}.json`,
        {
          method: 'Delete',
          headers: {
            'Content-Type': 'application/json',
          },
        }
      )
        .then((response) => {
          if (response.ok) {
               // if sucess do something
          } else {
               // if fail throw error
            throw new Error('could not delete data');
          }
        })
        .catch((error) => {
          this.error = error.message;
          console.log(id);
        });
    },

Answer: You can user item id to delete it like below.
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations/<localtion_id>.json', { method: 'delete'})
your location id can be value like this,  -MyB0qQoQuf9lPnwderfg


Pytorch logical indexing in a 3D tensor

Question: I have three tensors, a with size(n,4,m), b with size(n,4,1), c with size (n,k,m). a contains batch of node features I want to get, b indicates valid node index (invalid index is masked by 999), c is the batch of node feature set to be exact. n and k are for number of batch and number of nodes respectively.
The goal is to replace valid node features of a with corresponding node features of c with the index value sorted in b
So far, I use a nested for loop to implement it
import torch
n=4
a = torch.arange(n*4*4).view(n,4,4)
value_c = torch.zeros(n,6,4)
b=torch.randint(0,3,(n,4,1))
b[0,1:]=999
b[2,2:] = 999
for i in range(n):
    for j in range(4):
        if b[i,j]<999:
            a[i,j]=value_c[i,b[i,j].long()]

But it is really slow for a large dataset. Is there any ways to speed up it (e.g. with logical indexing)?
Answer: Sure. For starters, I suggest masking invalid indices with nan or inf or some special value; using a specific integer is just asking for hard-to-catch issues as you scale the size of your data up. This does give the complication that b will need to be of type float (so it can store nan values) and you'll have to cast it to long before using it to index. Personally I think this is worth the indexing safety but you can do as you want.
To use list-style indexing, we'll want to unravel indices into a into a 1D tensor for each dimension of a.
i = torch.arange(n).unsqueeze(1).expand(n,4).reshape(-1)  # something like [0,0,0,0,1,1,1,1 ...]
j = torch.arange(4).unsqueeze(0).expand(n,4).reshape(-1)  # something like [0,1,2,3,0,1,2,3,...]

k = b[i,j].squeeze() # assemble desired indices of c into 1D tensor as well

Now i,j, and k each contain nx4 indices, which is roughly the number of elements you want to replace. Now lets re-index each tensor once to remove all of the invalid indices.
valid = torch.where(torch.isnan(k),0,1).nonzero().squeeze().long()
k = k[valid]
i = i[valid]
j = j[valid]

And now we're ready to index.
a[i,j,:] = c[i,k,:]

You may have to do a bit of type-casting to get everything to work out (a and c for instance need to have the same type.)

Pytorch logical indexing in a 3D tensor


Basis of $\mathbb C^3$

Question: We know that the canonical basis of $\mathbb R^3$ is $\{(1,0,0),(0,1,0),(0,0,1)\}$. Does this basis work for $\mathbb C^3$? Is there a canonical basis of $\mathbb C^3$? Does my question depend on the field of the scalars? ($\mathbb R$ or $\mathbb C$)
Answer: Yes, this basis works also for $\mathbb C^3$. Reason: if $(u,v,w) \in \mathbb C^3$, then
$(u,v,w)=u*(1,0,0)+v*(0,1,0)+w*(0,0,1)$
and $(1,0,0),(0,1,0),(0,0,1)$ are linear independent in $ \mathbb C^3$
Answer: Yes.
If the scalars are complex, it's exactly the same.  But if the scalars have to be real, then $\mathbb{C}^3$ is a six dimensional space.
Comment: Could you explain a little bit why? thank you very much for your answer
Comment: What do you think would be a basis for $\mathbb{C}$ if the scalars are in $\mathbb{R}$?  [Hint: this space would be two dimensional]
Comment: I got it. Thank you again.

Basis of $\mathbb C^3$


What is a proc in Crystal Lang?

Question: I read the documentation on Procs in the Crystal Language book on the organizations's site. What exactly is a proc? I get that you define argument and return types and use a call method to call the proc which makes me think it's a function. But why use a proc? What is it for?
Answer: You cannot pass methods into other methods (but you can pass procs into methods), and methods cannot return other methods (but they can return procs).
Also Proc captures variables from the scope where it has been defined:
a = 1
b = 2

proc = ->{ a + b }

def foo(proc)
  bar(proc)
end

def bar(proc)
  a = 5
  b = 6
  1 + proc.call
end

puts bar(proc) # => 4

A powerful feature is to convert a block to Proc and pass it to a method, so you can forward it:
def int_to_int(&block : Int32 -> Int32)
  block
end

proc = int_to_int { |x| x + 1 }
proc.call(1) #=> 2

Also, as @Johannes Müller commented, Proc can be used as a closure:
def minus(num)
  ->(n : Int32) { num - n }
end

minus_20 = minus(20)
minus_20.call(7) # => 13

Comment: The example about block forwarding is not really great because it doesn't actually use a Proc's unique features. You can do the same with a plain block (using `yield`). The power of a block is that it can be stored (for example in an instance variable) and forms a closure.
Comment: @JohannesMüller, thank you, I've updated the answer.
Comment: BTW, you can use a proc method as well, see: https://stackoverflow.com/a/46728999/7450793
Answer: The language reference explains Proc pretty well actually:

A Proc represents a function pointer with an optional context (the closure data).

So yes, a proc is essentially like a function. In contrast to a plain block, it essentially holds a reference to a block so it can be stored and passed around and also provides a closure.
Answer: A Proc is simply a function/method without a name. You can pass it around as a variable, and it can refer to variables in it's enclosing scope (it's a closure). They are often used as a way of passing method blocks around as variables.

What is a proc in Crystal Lang?


drupal_render($node_view); is not working

Question: Node page is not loading once I add below code
 drupal_render($node_view);

I was referring https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_view/7
and added below code in my node--type.tpl.php
<?php
  $node = node_load($nid);
  $node_view = node_view($node);
  $rendered_node = drupal_render($node_view);
  echo $rendered_node;
?>

Comment: are you sure $nid has value ?
Comment: yes.i declared  $nid=$node->nid . If i hard code node id of type of itself the page is not loading, if i give node id of other types the page is loading.
Comment: you want to get views data?
Comment: i want to print node content in a particular view mode
Comment: Can you define "not working"? What happens? A white screen, a timeout, an error message? Is there something relevant in the Apache/PHP/Drupal logs?
Answer: As I don't have the Drupal sources at hand right now, I didn't digg into it yet. But I'm pretty sure the node_view() function is using your node--type.tpl.php for rendering its output.
So calling it within your template will lead to a recursion. You might want to check on that.
Comment: Good point. But it would only lead to recursion if the node loaded with `node_load($nid)` is of the same bundle as the "type" in `node--type.tpl.php`, right?


excel vba - Select all filtered rows except header after autofilter

Question: I'm trying to write a macro to do the following:

from Sheet1 watch the A column for the data I input;
when I write something in a cell in the A column use that value to filter Sheet2;
after the filter is done, copy everything except the column header from the second sheet into the first one, even if there are multiple values.

I tried writing this:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Set KeyCells = Range("A:A")
    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then
        copy_filter Target
    End If
End Sub

Sub copy_filter(Changed)
    Set sh = Worksheets("Sheet2")
    sh.Select

    sh.Range("$A$1:$L$5943") _
        .AutoFilter Field:=3, _
            Criteria1:="=" & Changed.Value, _
            VisibleDropDown:=False
    Set rang = sh.Range("$A$1:$L$5943") _
        .SpecialCells(xlCellTypeVisible)

    rang.Offset(0, 0).Select
    Selection.Copy

    Worksheets("Sheet1").Select
    Worksheets("Sheet1").Range(Changed.Address).Offset(0, 1).Select
    Selection.PasteSpecial Paste:=xlPasteValues

    sh.Range("$A$1:$L$5943").AutoFilter
    Application.CutCopyMode = False
End Sub

However when I copy the selection the header row gets copied as well, but using .Offset(1, 0) cuts the header and 1 additional row and doesn't account for cases when the filter returns no results.
How can I select every filtered rows except for the header?
Answer: Use sh.UsedRange will give you a dynamic range.  Where as, sh.Range("$A$1:$L$5943") will not shrink and grow to match your dataset.
We can trim the header row off like this:
    Set rang = sh.UsedRange.Offset(1, 0)
    Set rang = rang.Resize(rang.Rows.Count - 1)

But SpecialCells(xlCellTypeVisible) will throw a No cells were found. error if there is no data to  return.  So we'll have to trap the error like this:
On Error Resume Next

Set rang = rang.SpecialCells(xlCellTypeVisible)

If Err.Number = 0 Then

End If

On Error GoTo 0

    Sub copy_filter(Changed)
        Dim rang As Range

        Set sh = Worksheets("Sheet2")

        sh.UsedRange.AutoFilter Field:=3, _
                                Criteria1:="=" & Changed.Value, _
                                VisibleDropDown:=False

        Set rang = sh.UsedRange.Offset(1, 0)
        Set rang = rang.Resize(rang.Rows.Count - 1)

        On Error Resume Next
        Set rang = rang.SpecialCells(xlCellTypeVisible)
        If Err.Number = 0 Then
            rang.Copy
            Worksheets("Sheet1").Range(Changed.Address).Offset(0, 1).PasteSpecial Paste:=xlPasteValues
        End If

        On Error GoTo 0

        sh.Cells.AutoFilter

        Application.CutCopyMode = False

    End Sub
Comment: How your code is taking care of this requirement of OP `•when I write something in a cell in the A column use that value to filter Sheet2;` I am not quite getting it that it may be possible without worksheet change event.
Comment: I didn't include the OP's worksheet change event because didn't need refactoring.  copy_filter(Changed) will still be called the same way.
Comment: Thanks for clarifying.


ToUnixTimeSeconds method missing after migration to VS 2017

Question: var item = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

The code causes the compilation error "Does not contain a definition for ToUnixTimeSeconds...".
It works well in VS 2015, also I have using System; namespace and references to both mscorlib and System (22.214.171.124 version). Many other members of DateTimeOffset exist.
Comment: try to run `dotnet restore` manually on your project and close-open VS.
Answer: (Editing based on Eric's comment)
Following APIs were added in .NET Framework 4.6; from release notes:

Support for converting dates and times to or from Unix time
The following new methods have been added to the DateTimeOffset structure to support converting date and time values to or from Unix time:

DateTimeOffset.FromUnixTimeSeconds
DateTimeOffset.FromUnixTimeMilliseconds
DateTimeOffset.ToUnixTimeSeconds
DateTimeOffset.ToUnixTimeMilliseconds

You can also check the "Applies To" section in official docs to confirm compatibility: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimeseconds#applies-to
Just update your application target framework to framework version 4.6 or higher in project file (.csproj):
<PropertyGroup>
  <TargetFramework>net46</TargetFramework>

  ...
</PropertyGroup>

then in C# code:
public static long UnixTimeNowSec => DateTimeOffset.Now.ToUnixTimeSeconds();

Comment: In other words, [`ToUnixTimeSeconds` was introduced in .NET 4.6](https://msdn.microsoft.com/en-us/library/system.datetimeoffset.tounixtimeseconds(v=vs.110).aspx#Anchor_3), so make sure your project targets .NET 4.6 or higher (Properties -> Application -> Target framework).
Answer: i recently i have the same problem in a new project. What i do after doing some google search and testing find a function like this one:
public static long ToUnixEpochDate(DateTime date) => new DateTimeOffset(date).ToUniversalTime().ToUnixTimeSeconds();

//Usage
var now = DateTime.UtcNow;
var result = ToUnixEpochDate(now).ToString();

Hope it helps. Also try as @Kiratijuta mention in comment to target .net 4.6 or later.
Comment: This will result in the same error (you're still calling `ToUnixTimeSeconds` in the static method). @Kiratijuta is correct that the project needs to target .NET 4.6 or higher.


Find the power series of $f(x)=\frac{1}{x^2+x+1}$

Question: I want to find the power series of $$f(x)=\frac{1}{x^2+x+1}$$
How can I prove the following?
$$f(x)=\frac{2}{\sqrt{3}} \sum_{n=0}^{\infty} \mathrm{sin}\frac{2\pi(n+1)}{3} x^n  \,\,\,\, |x|<1$$
In particular I would like to know how to proceed in this case. The polinomial $x^2+x+1$ has no roots so here I cannot use partial fraction decomposition: what method should I use?
Comment: Note that $f(x) = \frac{1-x}{1-x^3}$. Can you find a power series for $g(x) = \frac{1}{1-x^3}$?
Comment: Expand $\frac{1}{1+X}$ and replace $X$ by $x+x^2$.
Comment: Note: You can use partial fraction decomposition with complex roots. This is sometimes interesting and/or useful as a technique, and might be of interest here. Have you computed explicitly the first few terms of the given power series? They will come out more simply than is apparent from the formula.
Answer: $$\frac1{x^2+x+1}=\frac{1-x}{1-x^3}=(1-x)\frac{1}{1-x^3}$$ when $x\ne 1$.
Comment: Compute the first few values of $\sin(2\pi(n+1)/3)$ to see what it is.  This will also explain that $2/\sqrt{3}$ in your formula.
Comment: Thanks for the reply! I find $$\frac{1}{1-x^3}=\sum_{0}^{\infty} (-x^3)^n \,\,\,\, |x|<1$$
But then I don't know how to deal with $1-x$.. And in the result there is a $\mathrm{sin}$ which I have no idea where it comes from if I use this method..
Comment: @Gianolepo Well, $(1-x)\frac{1}{1-x^3}$ equals $1-x$ times $\frac{1}{1-x^3}$, so you multiply them. You know how to multiply polynomials, and multiplying power series is no different.
Comment: rest is GEdgar's comment. The period is $3$. (0,1,2) (3,4,5) ...
Answer: The polynomial $x^2+x+1=\Phi_3(x)$ has no real roots, but it vanishes at $x=e^{\pm\frac{2\pi i}{3}}$. In particular, by setting $\omega=\exp\left(\frac{2\pi i}{3}\right)$ and $\overline{\omega}=\omega^2=\exp\left(\frac{4\pi i}{3}\right)$,
$$ \frac{1}{x^2+x+1} = \frac{1}{(x-\omega)(x-\omega^2)} = \frac{i\omega^2}{\sqrt{3}}\cdot\frac{1}{1-\omega^2 x}-\frac{i\omega}{\sqrt{3}}\cdot\frac{1}{1-\omega x} $$
where the RHS, expanded as the difference between two geometric series, equals
$$ \frac{i}{\sqrt{3}}\sum_{n\geq 0}\left(\omega^{2n+2}-\omega^{n+1}\right)x^n =\frac{2}{\sqrt{3}}\sum_{n\geq 0}\sin\left(\frac{2\pi(n+1)}{3}\right)x^n$$
as wanted. That clearly simplifies, since
$$ \frac{1}{1+x+x^2}=\frac{1-x}{1-x^3} = \sum_{m\geq 0}\left(x^{3m}-x^{3m+1}\right),$$
too, and the Taylor series at the origin is unique.
Comment: Note that $\omega^2=\omega^{-1}$ which may help to see where the sine function comes from.
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

Lets $\ds{r \equiv -\,{1 \over 2} + {\root{3} \over 2}\,\ic = \expo{2\pi\ic/3}.\quad r\ \mbox{and}\ \bar{r}\quad \mbox{are the roots of}\quad x^{2} + x + 1 = 0}$.

\begin{align}
{1 \over x^{2} + x + 1} & =
{1 \over \pars{x - r}\pars{x - \bar{r}}} =
\pars{{1 \over x - r} - {1 \over x - \bar{r}}}{1 \over r - \bar{r}} =
\bracks{2\ic\Im\pars{1 \over x - r}}{1 \over 2\ic\Im\pars{r}}
\\[5mm] & =
-\,{2\root{3} \over 3}\,\Im\pars{\bar{r}\bracks{1 \over 1 - \bar{r}x}} =
-\,{2\root{3} \over 3}\,\Im\pars{\bar{r}\sum_{n = 0}^{\infty}
\bracks{\bar{r}x}^{n}} \\[5mm] & =
-\,{2\root{3} \over 3}\,\sum_{n = 0}^{\infty}
x^{n}\,\Im\pars{\bar{r}^{\, n + 1}} =
-\,{2\root{3} \over 3}\,\sum_{n = 0}^{\infty}
x^{n}\,\Im\pars{\exp\pars{-\,{2\bracks{n + 1}\pi \over 3}\,\ic}}
\\[5mm] & =\ \bbox[15px,#ffe,border:2px dashed navy]{\ds{%
{2\root{3} \over 3}\,\sum_{n = 0}^{\infty}
\sin\pars{2\bracks{n + 1}\pi \over 3}x^{n}}}\qquad\qquad\verts{x} < 1
\end{align}


basis vector of tangent space of manifold

Question: In this article https://en.wikipedia.org/wiki/Tangent_space, under the section title Basis of the tangent space at a point, it says "... Then for every tangent vector v\in TpM, one has...." followed by an equation for a tangent vector v. But I don't see enough reasoning/explanation to justify the equation.
The same topic is also discussed in this article
https://bjlkeng.github.io/posts/manifolds/. Similarly, it says right before Equation (10), "So every tangent vector v\in TpM, we have..." followed by Eq (10). Again, I don't see why.
I completely understand Eqs. (8) and (9), showing the derivative of function f over curve gamma(t) as the inner product of tangent vector v and the gradient of f, i.e., it is the directional derivative of f along the direction of v.
However, what I do not understand is why the LHS of Eq. (8) becomes a tangent vector v in Eq. (10), when function f is dropped on the RHS. In other words, how can a tangent vector on the LHS be the same as the weighted sum of n differential operators (treated as basis of tangent space) on the RHS?
Comment: Do you have a good grasp of the tangent space conceptually? The expression for $v$ is simply the components of the vector in the direction of each basis vector. Do you understand why the basis vectors are defined that way?
Answer: I think I have some idea about my own question above after reading this post:
https://math.stackexchange.com/questions/3330025/why-are-the-partial-derivatives-a-basis-of-the-tangent-space#:~:text=The%20tangent%20space%20is%20viewed%20as%20the%20space,they%20are%20identified%20as%20directional%20derivative%20operators.%20Share
My realization is that the partials $\partial/\partial x_i$ are not the basis of the tangent space $T_p(R^n)$, instead, they are the basis of a different space $D_p(R^n)$, an isomorphic mapping of the tangent space $T_p(R^n)$.
In other words, any tangent vector $v\in T_p(R^n)$ can be mapped to $D_v\in D_p(R^n)$, which can be expressed as a linear combination of the partials $\partial/\partial x_i$ as the basis.
Please correct me if I am wrong.
Comment: There are many different ways to define the tangent space and$$T_p\mathbb R^n=D_p(\mathbb R^n)$$is one of them.
Comment: In fact, there is a characterization of the tangent space that defines it up to an isomorphism. This is explained [here](https://math.stackexchange.com/a/3935431/572841).


If $\gcd(m,n)= 1$ and $n \leq km$ and $m \leq kn$

Question: If $\gcd(m,n)= 1$ and $n \leq km$ and $m \leq kn$
I want to prove that $ mn \leq k$
If I multiply the first inequality by $m$ I will get that $mn \leq km^2$
And If I multiply the second inequality by $n$ I will get that $mn \leq kn^2$
But that How to deduce that $mn \leq k$.
Is it even possible ?
Comment: @DietrichBurde what if $k \neq 1$ ?
Comment: what if you have $k=7,m=3,n=2$ then we have $\gcd(m,n) = 1$ and we also have that $m \leq kn$ and $n \leq km$  so it's not impossible as u said !! @DietrichBurde
Comment: Well, one of the inequalities in redundant as we can take $m \geq n$ without loss of generality.
Answer: It's not true in general. Take $k=2$, $n=11$ and $m=13$. Then
$$11 \leq 2 \cdot 13$$
$$13 \leq 2 \cdot 11$$
$$\gcd(11,13) = 1$$
but
$$nm = 11\cdot 13 \geq 2 = k$$


httpd.conf virtual host not working

Question: I've added this:
<VirtualHost *:8888>
    ServerName dietron
    DocumentRoot /Users/kieransenior/Development/reformsoft_dietron/trunk/var/www/dietron/htdocs

    <Directory /Users/kieransenior/Development/reformsoft_dietron/trunk/var/www/dietron/htdocs>
        AllowOverride All
        Options All
    </Directory>

    php_value include_path .:/Users/kieransenior/Development/reformsoft_dietron/trunk/var/www/dietron/include:/usr/local/lib/pear
    php_value magic_quotes_gpc off
    php_value register_globals off
</VirtualHost>

to my httpd.conf in the hope that my .htaccess file in the htdocs folder will be picked up with the following rules:
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1

That is the entire contents.  I'm renaming .htaccess on my MBP by doing mv i.htaccess .htaccess which I'm assuming is correct?  I'm using MAMP therefore the httpd.conf has a load of default settings and I added the first snippet above at the very end of it.  I'm then restarting it by stopping Apache and starting it again.  The index.php gets picked up fine, however when I do http://localhost:8888/anythinghere it comes up with a 404, which shouldn't happen.
Any ideas on what I'm doing wrong?
EDIT: Here's my httpd.conf
EDIT: Here's the error in the Apache log:
[Fri Jun 05 16:02:22 2009] [error] [client ::1] File does not exist: /Users/kieransenior/Development/reformsoft_dietron/trunk/var/www/dietron/htdocs/testing

Comment: I duplicated this config on my machine and it works OK. Did you check the error log for clues?
Comment: Have you checked your apache logs? you can also set RewriteLog and RewriteLogLevel to see what's going on. but these two directives has to go into you vhost, not the .htaccess file.
Comment: Which and where is the error log?
Answer: A couple of suggestions.
First, on line 461 of your httpd.conf:
AccessFileName afn.htaccess

Shouldn't that be .htaccess?
The second thing I see is that the server name is set:
ServerName dietron

but you're trying to access it with localhost
I'd suggest that you put an entry in your /etc/hosts file so that dietron resolves, either to your local ip address or your loopback (127.0.0.1), and then access the server with http://dietron:8888
Comment: That's what I get for staring at httpd.conf all day.  Thankyou sir.
Answer: Ensure that your AllowOverride directive is set properly at a global level. If no override is allowed (AllowOverride None) at your webroot, then your htaccess file will be ignored.
Comment: I've provided a link to my actual httpd.conf located in Applications/MAMP/conf/Apache/
Comment: Your `NameVirtualHost` directive value needs to match your virtual host config:

NameVirtualHost *:888

   ...

See if that solves the whole problem.
Comment: Unfortunately that didn't work either.  Perhaps I should actually install Apache and MySQL locally as opposed to using MAMP?  That way I have more control over it.
Comment: For the purposes of config, if you have access to your httpd.conf, you have full access to Apache. I ended up using the MacPorts version, myself, but for other reasons. You already have full access to the configuration.  I did notice a typo in my comment above, if you didn't catch it: NameVirtualHost *:8888 (4 8's, not 3).

httpd.conf virtual host not working