Unable to add more content in main page because grid is full

Question: I want more buttons after "hurt status" but the size of grid becomes smaller, so I am unable to do so. Can I use scrollviewer to do that or something else?
Xaml Code is as Below

    <Button Content="Angry Status" HorizontalAlignment="Left" Margin="0,27,0,0" VerticalAlignment="Top" Height="66" Click="Button_Click" Width="400"/>
        <Button Content="Attitude Status" HorizontalAlignment="Left" Margin="2,79,0,0" VerticalAlignment="Top" Width="400" Height="66" Click="Button_Click_1"/>
        <Button Content="Awesome Status" HorizontalAlignment="Left" Margin="0,131,0,0" VerticalAlignment="Top" Width="400" Height="66" Click="Button_Click_2" />
        <Button Content="Best Status" HorizontalAlignment="Left" Margin="2,183,-2,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="Break Up Status" HorizontalAlignment="Left" Margin="0,235,-2,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="Cool Status" HorizontalAlignment="Left" Margin="2,279,0,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="FriendShip Day Status" HorizontalAlignment="Left" Margin="2,331,-2,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="FriendShip Status" HorizontalAlignment="Left" Margin="0,383,0,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="Funny Status" HorizontalAlignment="Left" Margin="0,435,0,0" VerticalAlignment="Top" Width="400" Height="66" />
        <Button Content="Hug Day Status" HorizontalAlignment="Left" Margin="2,487,0,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="Hurt Status" HorizontalAlignment="Left" Margin="0,539,0,0" VerticalAlignment="Top" Width="400" Height="66"/>

</Grid>

Answer: Wrap it with a ScrollViewer and you should be good to go. Also,  I'll suggest to use <Grid.RowDefinitions> and set each of your Button to its Grid.Row so that you won't need to set Margin property. You need to explicitly set the MaxHeight  as the ScrollViewer wouldn't know what would be the ViewPort for a scrollable area.
<ScrollViewer MaxHeight="700">
   <Grid>
        <Button Content="Angry Status" HorizontalAlignment="Left" Margin="0,27,0,0" VerticalAlignment="Top" Height="66" Click="Button_Click" Width="400"/>
        <Button Content="Attitude Status" HorizontalAlignment="Left" Margin="2,79,0,0" VerticalAlignment="Top" Width="400" Height="66" Click="Button_Click_1"/>
        <Button Content="Awesome Status" HorizontalAlignment="Left" Margin="0,131,0,0" VerticalAlignment="Top" Width="400" Height="66" Click="Button_Click_2" />
        <Button Content="Best Status" HorizontalAlignment="Left" Margin="2,183,-2,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="Break Up Status" HorizontalAlignment="Left" Margin="0,235,-2,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="Cool Status" HorizontalAlignment="Left" Margin="2,279,0,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="FriendShip Day Status" HorizontalAlignment="Left" Margin="2,331,-2,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="FriendShip Status" HorizontalAlignment="Left" Margin="0,383,0,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="Funny Status" HorizontalAlignment="Left" Margin="0,435,0,0" VerticalAlignment="Top" Width="400" Height="66" />
        <Button Content="Hug Day Status" HorizontalAlignment="Left" Margin="2,487,0,0" VerticalAlignment="Top" Width="400" Height="66"/>
        <Button Content="Hurt Status" HorizontalAlignment="Left" Margin="0,539,0,0" VerticalAlignment="Top" Width="400" Height="66"/>
   </Grid>
</ScrollViewer>


Are these quarters notes or just eighth notes?

Question: Are these quarter notes or eighth notes? Which ones are the quarter notes and which are the eighth notes? Are there quarter notes together with 8th notes or are all eighths? Like using the numbers and arrows to tell me which ones are the quarter or eighths?
Comment: Can you provide a link to the page you found this on or any of the description of this? It sort of looks like they are all 16th notes but that might just be the arm motion and not the strum itself.
Comment: https://tabs.ultimate-guitar.com/tab/print?flats=0&font_size=2&id=2270831&simplified=0&transpose=0
Comment: Baby Can I Hold You Official by Tracy Chapman
Answer: Those are sixteenth notes. There are two ways to know:

the double beam under each pair; and
the counting pattern. The number comes on each beat (i.e. each quarter note), and the "&" comes on the half beat (i.e., each eighth note). The stems between the numbers and "&"s are the sixteenths. They're often counted 1 e & a 2 e & a, etc.

The strumming pattern assumes that on each sixteenth note, there is a strum motion: down motion on the number and the "&"; up motion on each stem in between. The actual strums occur where indicated by the arrows.
Here is a recreation of the OP image with the common 16th-note counting pattern and up-down hand movement pattern indicated below the rhythm notation.
Comment: Impossible to tell whether this was intended in the original source but I'd say it's massive overkill to move your hand that much just to play "ching, ching -ga ching ching; ching ching chacha ching ching". In my opinion it's more plausible the sixteenths were just there to provide a frame so that the correct positioning of the third stroke can been seen exactly, rather than suggesting that "on each sixteenth note, there is a strum motion"
Comment: @JudyN. - do you play rhythm guitar?
Comment: @Tim Yes (Comments must be at least 15 characters in length)
Answer: Since they all look the same, with a stem and two beams each, they are definitely sixteenth notes (semi-quavers). That means in one bar there will be 16 of them, all equal. Counting 1-2-3-4 is usually done with 1e&a2e&a3e&a4e&a for each bar of the usual 4 in 4/4 time. Giving the count of 16. Each beat dividing into 4.
The arrows tell which way the strumming goes. But that's pre-determined. With 8 pulses in the bar, 1 down and 1 up. So, every 'number' and every '&' strum down, and every other one will be a return upstrum (fairly obvious!). No arrow means no audible strum, which will still physically take place. It's a rhythm after all, and any rhythm will retain a regular pattern.


C++ FSTREAM & classes

Question: Okay so when I started using classes to make functions, it gives me an error file is invalid, normally doesn't if I don't use classes. If you run it, enter in some info, and then run it again, normally it should read in the data correctly, it still reads it in, but it says there's an error. I don't really know what I'm doing wrong, any tips? Thanks!
<code>#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
using namespace std;

const int TEMP_SIZE = 10;
const int NAME_SIZE = 100;
const int BREED_SIZE = 100;
const int DESC_SIZE = 250;
const int REASON_SIZE = 250;
const int ID_SIZE = 50;

//creating the struct
struct animal
{
    char name[NAME_SIZE];
    char ID[ID_SIZE];
    char breed[BREED_SIZE];
    float age;
    float weight;
    char desc[DESC_SIZE];
    char reason[REASON_SIZE];
    int day;
    int month;
    int year;
    float length;
};

struct adopted
{
    char hostName[100];
    char hostAddress[100];
    int numPets;
};

class petAdoption
{
    public:
        petAdoption();
        //~petAdoption();
        void enroll(animal newAnimal[]);
        void read(animal newAnimal[]);
    private:
        int count;
        int numPets;
        int * pets;
};

petAdoption::petAdoption()
{
    count = 0;
    pets = NULL;
    numPets = 0;
}

void petAdoption::enroll(animal newAnimal[])
{
            cout << "Please enter your pet's name: ";
            cin.get(newAnimal[count].name, NAME_SIZE, '\n');
            cin.ignore(100, '\n');

            cout << "Please enter a unique ID for your pet (combinations of numbers EG: 432FD3): ";
            cin.get(newAnimal[count].ID, ID_SIZE, '\n');
            cin.ignore(100, '\n');

            cout << "What type of breed is your pet?: ";
            cin.get(newAnimal[count].breed, BREED_SIZE, '\n');
            cin.ignore(100, '\n');

            cout << "How old is your pet?: ";
            cin >> newAnimal[count].age;
            cin.ignore(100, '\n');

            cout << "How much does your pet weigh? (in LBS): ";
            cin >> newAnimal[count].weight;
            cin.ignore(100, '\n');

            cout << "Please describe your pet's personality!: ";
            cin.get(newAnimal[count].desc, DESC_SIZE, '\n');
            cin.ignore(100, '\n');

            cout << "Please explain why the pet is being put up for adoption: ";
            cin.get(newAnimal[count].reason, REASON_SIZE, '\n');
            cin.ignore(100, '\n');

            cout << "Please enter your pet's day of birth (1-31): ";
            cin >> newAnimal[count].day;
            cin.ignore(100, '\n');

            cout << "Please enter your pet's month of birth (1-12): ";
            cin >> newAnimal[count].month;
            cin.ignore(100, '\n');

            cout << "Please enter your pet's year of birth (1900-2012) : ";
            cin >> newAnimal[count].year;
            cin.ignore(100, '\n');

            cout << "Please enter the length of time your pet has spent in a shelter (in months): ";
            cin >> newAnimal[count].length;
            cin.ignore(100, '\n');
/*** WRITES the pet ID into the list of pets***/
            ofstream write;
            write.open("pets.txt", ios::app);
            write << newAnimal[count].name << '\n';
            write.close();

/*** WRITES EACH PET INFO ****/
//this opens the file / creates a file if it's not made yet
//and it writes the pet's information
        write.open(newAnimal[count].name, ios::app);
        write << newAnimal[count].name << '\n'
        << newAnimal[count].ID << '\n'
        << newAnimal[count].breed << '\n'
        << newAnimal[count].age << '\n'
        << newAnimal[count].weight << '\n'
        << newAnimal[count].desc << '\n'
        << newAnimal[count].reason << '\n'
        << newAnimal[count].day << '\n'
        << newAnimal[count].month << '\n'
        << newAnimal[count].year << '\n'
        << newAnimal[count].length << '\n';
//this closes the file
        write.close();
}

void petAdoption::read(animal newAnimal[])
{
    ifstream read;
//open the file apps.txt
    read.open("pets.txt");
//if apps.txt doesn't exist, then print out this error
    if(!read)
    {
        cout << "pets.txt doesn't exist! This is your first time!" <<endl;
    }
//else if it does exist, read in the names and store them back
//into the struct member name(s)
    else
    {
//while the document isn't empty
//read in each line
        while(!read.eof())
        {
        read.getline(newAnimal[count].name, NAME_SIZE, '\n');
        ++count;
        }
        count = count-1;
    }
//close the file
    read.close();
    for (int i = 0; i < count; ++i)
    {
//open the file of the name of the app
        read.open(newAnimal[count].name);
//if the file doesn't exist
//then we probably deleted it
//without removing it from the apps.txt
//but it prints out an error
        if( !read)
        {
            cout << "invalid file!" <<endl;
        }
//however if the file does exist,
//read in each line and store them back
//into the struct members
        while(!read.eof())
        {
            read.getline(newAnimal[count].name, NAME_SIZE, '\n');
            read.ignore(100, '\n');
            read.getline(newAnimal[count].ID, ID_SIZE, '\n');
            read.ignore(100, '\n');
            read.getline(newAnimal[count].breed, BREED_SIZE, '\n');
            read.ignore(100, '\n');
            read >> newAnimal[count].age;
            read.ignore(100, '\n');
            read >> newAnimal[count].weight;
            read.ignore(100, '\n');
            read.getline(newAnimal[count].desc, DESC_SIZE, '\n');
            read.ignore(100, '\n');
            read.getline(newAnimal[count].reason, REASON_SIZE, '\n');
            read.ignore(100, '\n');
            read >> newAnimal[count].day;
            read >> newAnimal[count].month;
            read >> newAnimal[count].year;
            read >> newAnimal[count].length;
            read.ignore(100, '\n');
        }
//close the file
        read.close();
    }
}

int main()
{
    animal newAnimal[10];
    petAdoption adopt;
    adopt.read(newAnimal);
    adopt.enroll(newAnimal);
}
</code>
Comment: Why would you ever have to use that? It's buggy and causes problems all around. If it's a teacher imposing it, do some research on why it's bad and present that to the teacher.
Comment: You mean "I have to ensure my program doesn't work"?
Comment: @user - The problem with `while(!read.eof())` is that it tells you if the previous read failed (too late!), not if the next one will succeed. Try `while(read.getline(...))` instead, to see if each input works.
Answer: I think I know what's going on. when you say read.open("pets.txt"); it should say read.open("pets.txt"),ios::app because then it so snot delete the data it already stores. Also go in to your file explorer and search pets.txt and read it to see what's going on. I hope I helped you.

C++ FSTREAM & classes


Differential Equation - Blood Alcohol

Question: Let C(t) be the concentration of alcohol in a person's bloodstream. We propose a mathematical model which states that, once a person stops drinking alcohol, C decreases at a rate that is proportional to C. Write down a differential equation consistent with that model.
Comment: Hint: the rate of decrease is the derivative of $C$ and is negative when the concentration is positive
Comment: Another Hint: saying that a function $f$ is proportional to a function $g$ means that there exists some $\alpha \in \Bbb{R}$ such that $f=\alpha g$. Next look at @marwalix solution, if you don't get it by yourself :D
Answer: And the solution is $$\frac{dC(t)}{dt}=-\alpha C(t)$$ where $\alpha \gt 0$. Solving the equation we have $$C(t)=C(0)\exp{(-\alpha t)}$$
Comment: Sorry typo corrected
Comment: Are you sure? At $t=0$ your solution is $0$! So the person is sober. :-)

Differential Equation - Blood Alcohol


How to get the equivalent of Apache's Alias "/foo" /path/to/foo working in nginx

Question: I'm trying to configure nginx in front of HHVM to serve up an API which has a landing page listing available versions at / and the actual installed API versions at /api/[version]/.
My nginx config so far is as follows:
server {
    listen *:80;
    server_name api.domain.com;

    # Character Set
    charset utf-8;

    # Logs
    access_log /www/vhosts/api.domain.com/logs/access_log.nginx;
    error_log /www/vhosts/api.domain.com/logs/error_log.nginx;

    # Directory Indices
    index index.php;

    # Document Root
    root /www/vhosts/api.domain.com/public;

    # Location
    location /assets {
        try_files $uri $uri/ =404;
    }
    location /api/1.0 {
        root /www/vhosts/api.domain.com/api/1.0/public;
        rewrite ^/api/1.0(.*)$ /index.php$1;
        try_files $uri $uri/ /index.php?$query_string;
    }
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { log_not_found off; access_log off; }
    location = /robots.txt  { log_not_found off; access_log off; }

    # Error Pages
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location ~ \.(hh|php)$ {
        fastcgi_keep_conn on;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    # Block access to .htaccess
    location ~ \.ht {
        deny all;
    }
}

Requests to http://api.domain.com/ serve up the landing page correctly, however requests to http://api.domain.com/api/1.0/foo are still sent through to the index.php at /www/vhosts/api.domain.com/public/index.php instead of the one at /www/vhosts/api.domain.com/api/1.0/public/index.php.
Does anyone know how I can solve this problem? The Apache configuration I am switching across from is below for reference:
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    ServerName api.domain.com

    DocumentRoot /www/vhosts/api.domain.com/public/
    <Directory /www/vhosts/api.domain.com/public/>
        Options -Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog /www/vhosts/api.domain.com/logs/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog /www/vhosts/api.domain.com/logs/access.log combined
    ServerSignature Off

    Alias /api/1.0 "/www/vhosts/api.domain.com/api/1.0/public/"
    <Directory /www/vhosts/api.domain.com/api/1.0/public/>
        Options -Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    Alias /api/latest "/www/vhosts/api.domain.com/api/1.0/public/"

    SetEnv APPLICATION_ENV testing
</VirtualHost>

On an unrelated note, can someone please tag this with hhvm for me? I need at least 300 reputation to create the tag, and apparently no-one's ever asked any hhvm-related questions on here yet. :/
EDIT:
As per krisFR's suggestion below, I've tried modifying the location /api/1.0 block as follows:
    location /api/1.0 {
        alias /www/vhosts/api.domain.com/api/1.0/public;
        try_files $uri $uri/ /index.php?$query_string;
    }

However, this loads the code from /www/vhosts/api.domain.com/public/index.php instead of the code I want it to load at /www/vhosts/api.domain.com/api/1.0/public/index.php. Any further ideas?
Comment: I think the main caveat has to do with the `location ~ \.(hh|php)$` block that always run `$document_root$fastcgi_script_name`...
Comment: Hmm… Shouldn't the `root /www/vhosts/api.domain.com/api/1.0/public;` in `location /api/1.0` override that, though?
Answer: NGinx also has an alias directive.
Give it a try :
location /api/1.0/ {
    alias /www/vhosts/api.domain.com/api/1.0/public/;
    ...
}

Edit :
You could try this :
location ^~ /api/1.0/ {
    alias /www/vhosts/api.domain.com/api/1.0/public/;
    ...
}

Comment: Hmm… `location /api/1.0 { alias …etc…; try_files …etc…; }` loads up the code from `/www/vhosts/api.domain.com/public`. Any ideas?
Comment: @TwoWholeWorms I've edited my answer
Comment: Nope. :( Still loads the code from /. :/
Comment: tried using root not alias `root /www/vhosts/api.domain.com/api/1.0/public` in location block?
Comment: did it work ?


How do I set up a VPN to access specific subnets?

Question: I would like to set up a point-to-site VPN that is only used to access a specific set of subnets so that I can access services via the VPN but without routing all traffic through it.
In my test setup, I have three servers, one of which (fra1-02) is running StrongSwan/IPSec:
          +-----------------+     +-----------------+
          |    client(s)    |---->|    internet     |
          +-----------------+     +-----------------+
                   |
                   v
          +-----------------+
          |  fra1-02 (vpn)  |
          +-----------------+
                   |
         +---------+---------+
         |                   |
         v                   v
+-----------------+ +-----------------+
|     fra1-01     | |     fra1-03     |
+-----------------+ +-----------------+

I want the clients to connect to the internet normally, but for three subnets (specifically the ones assigned to the three servers), traffic should go through the VPN.
The three servers have these subnets:

2a03:b0c0:3:e0::489:d000/124
2a03:b0c0:3:e0::493:1000/124
2a03:b0c0:3:e0::493:2000/124

I have configured IPSec to assign clients IP addresses from fd00:0::0/32
This is my ipsec.conf:
config setup
    uniqueids=no
conn ikev2-vpn
    auto=add
    compress=no
    type=tunnel
    keyexchange=ikev2
    fragmentation=yes
    forceencaps=yes
    dpdaction=clear
    dpddelay=300s
    rekey=no
    left=%any
    leftid=@{{ leftid }}
    leftcert=cert.pem
    leftsendcert=always
    leftsubnet=2a03:b0c0:3:e0::489:d000/124,2a03:b0c0:3:e0::493:1000/124,2a03:b0c0:3:e0::493:2000/124
    right=%any
    rightid=%any
    rightauth=eap-mschapv2
    rightsourceip=fd00:0::0/32
    rightdns={{ rightdns }}
    rightsendcert=never
    eap_identity=%identity

(the {{ variables }} will be filled in by Ansible).
I haven't configured any routing or anything else.
When I'm connected to the VPN from my laptop, I can still ping fra1-02, the vpn host, and the source address is now one assigned by IPSec and not my laptop's public address, but the other two hosts are not reachable at all.
I have also added this to /etc/sysctl.conf:
net.ipv6.conf.all.forwarding=1

These is (some of) the output of netstat -rn on my laptop (looks like exactly what I expected):
default                         fd00::    UGcI     ipsec0
2a03:b0c0:3:e0::489:d000/124    fd00::    UGSc     ipsec0
2a03:b0c0:3:e0::493:1000/124    fd00::    UGSc     ipsec0
2a03:b0c0:3:e0::493:2000/124    fd00::    UGSc     ipsec0
...

And the routing table on the VPN server is this:
root@fra1-02:~# ip -6 route list
::1 dev lo proto kernel metric 256 pref medium
2a03:b0c0:3:e0::/64 dev eth0 proto kernel metric 256 pref medium
fe80::/64 dev eth1 proto kernel metric 256 pref medium
fe80::/64 dev eth0 proto kernel metric 256 pref medium
default via 2a03:b0c0:3:e0::1 dev eth0 proto static metric 1024 pref medium

How do I set it up so that traffic to fra1-01 and fra1-03 is routed through the  VPN?
Answer: I have installed netfilter-persistent and added the following to /etc/iptables/rules.v6:
*nat
-A POSTROUTING -s fd00::/32 -o eth0 -j MASQUERADE
COMMIT

And now everything works great.


Can you run server 2003R2 as a guest OS in a server 2016 cluster

Question: We are in the process of specing out a project for a client to upgrade their cluster hardware and host OS. They are currently using a server 2012 R2 cluster. We are going to take them to a server 2016 cluster. However I found 2 server 2003R2 VMs. Turns out server 2003R2 is supported by 2012R2, but is not listed as a supported guest OS in a 2016 hyper-v cluster.
Either my google-fu isn't what it once was, or no one has written anything about it.
I am fairly sure it shouldn't be a problem, but I figured I'd ask first.
Has anyone got a 2003 guest OS running in a server 2016 hyper-v cluster and if so, have you had any issues?
Answer: Indeed, Windows Server 2003R2 is not supported on Hyper-V 2016 but it doesn't mean that it won't work at all.
You can create VM with first (legacy) generation and install integrated services from 2012R2 manually (https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/manage/manage-hyper-v-integration-services#install-or-update-integration-services).
Please be aware that since Windows Server 2003R2 is not supported there may be some unexpected errors.
I believe it's a good time to migrate OS to Windows Server 2008R2 which is still supported (https://support.microsoft.com/en-us/lifecycle/search/?p1=14134&wa=wsignin1.0) or to Windows Server 2012R2 and run legacy applications in compatibility mode.
Answer: Windows Server 2003R2 is past end of life. Microsoft will no longer support it, but it will certainly run (as a Generation 1 virtual machine only) on Hyper-V 2016.
Of course, this is a good time to plan your migration off of the obsolete server platform.


IQueryable Or IList

Question: I have some methods in my BLL that fetch some records from database and pass it to UI for binding to Data Controls such as Gridview or ...
I could choose my return data type of the methods whether IQueryable<t> or Ilist<t> .
 My question is which one would be better for me and why ?
Actually i don't know the difference between these two type and i don't know which one is best for which situations ?
Thank you
Answer: The difference is that IList<T> represents an actual list of results. It will have been "materialized" - fetched from the database, into memory. (In theory it's just an interface of course - it could still defer everything...)
IQueryable<T> represents a query - you can still compose extra query bits afterwards, for example. You can then evaluate the query by asking for the results. This will use deferred execution, only requesting results when it actually needs them.
As for which you should return... if you're just going to bind directly to the UI, it may well make sense to convert it to a list, so that you have more control over when the query is actually executed. On the other hand, if you want to be able to tweak the query, using IQueryable<T> will give the caller more flexibility.
Comment: @Shantanu this article has some useful info about IQueryable, see http://www.weirdlover.com/2010/05/11/iqueryable-can-kill-your-dog-steal-your-wife-kill-your-will-to-live-etc/
Comment: Thanks for explanation. I too got your point and would be looking for most simple example implementing both the things which will show difference among the situation specified above. I dont know how to implement interfaces in classes. i.e. I know what is interface and what functionality do they provide. But i dont know how to use them. eg. IDisposable interface, I know what it will do when implemented but how to implement is my problem same way this IQueryable interface as well
Comment: @Shantanu: You certainly shouldn't be implementing `IQueryable` yourself. That's what LINQ to SQL (or whatever) is for.
Comment: Could you please provide an example, could be a link representing their implementation and difference between the two. It would be a great help
Comment: @Matt: The url is quite funny but really worth a lot. I do appreciate for such a nice article as well as the writer who presented it as a chocolate. `If it's easier, think of IQueryable as an a*hole (figurative). Your college roommate, maybe. You ask him to clean the dishes. He says, "did it." You ask him to get groceries. He says, "did it." Then you say, "No you didn't." And then he does all of it all at once, and says, "Yeah I did. Right now."` **Nice Lines**
Answer: I suggest ICollection or IList
IQueryable - provides functionality to evaluate queries against a specific data source wherein the type of the data is known.
In any time you can call  ICollection.AsQueryable().

IQueryable Or IList


When I try to put a class into a header I get the error of member not found when I compile with strings in the class

Question: Here is the code:
Classes.h
#ifndef CLASSES_H
#define CLASSES_H
// Team Class
class Team {
public:
    string title, initials;
};
// End

// Player Class
class Player {
public:
    int skill, cost;
    string name;
};
// End

// Coach Class
class Coach {
    int cash, cost, players;
public:
    string name;
    void set_values (int, int);
    int total (void) {return (cash - cost);};
};
// End
#endif

Classes.cpp
#include "Classes.h"
// Set Total Cash for Coach
void Coach::set_values (int a, int b) {
    cash = a;
    cost = b;
}
// End

Main.cpp
#include <iostream>
#include <string>
#include "classes.h"

When I compile it does not find the initials member or the name members, meaning the strings. Why and how can I fix this.
I.E
main.cpp:22: error: 'class Player' has no member named 'name'
main.cpp:28: error: 'class Coach' has no member named 'name'
main.cpp:29: error: 'class Coach' has no member named 'name'
main.cpp:30: error: 'class Player' has no member named 'name'
main.cpp:35: error: 'class Team' has no member named 'title'
main.cpp:36: error: 'class Team' has no member named 'title'
main.cpp:38: error: 'class Team' has no member named 'initials'
main.cpp:39: error: 'class Team' has no member named 'initials'
main.cpp:40: error: 'class Player' has no member named 'name'
main.cpp:40: error: 'class Team' has no member named 'title'
main.cpp:41: error: 'class Team' has no member named 'initials'
main.cpp:41: error: 'class Player' has no member named 'name'
main.cpp:41: error: 'class Coach' has no member named 'name'

Or
In file included from main.cpp:9:
classes.h:7: error: 'string' does not name a type
classes.h:15: error: 'string' does not name a type
classes.h:23: error: 'string' does not name a type

Please help! I am a novice, so it is probably something I either can't do or a simple fix.
Answer: You need to #include <string> in the classes.h file and change string variable declarations to std::string.
For example:
class Team {
public:
std::string title, initials;
};

Answer: You need to use std::string the full qualification and also #include <string> to your header file.


Dynamically mapped components from array in state are not updating even after state changes

Question: I'm mapping an array in the state to build  dropdowns dynamically. I have two working methods to add and remove values in the array. When I remove and add values to the array I want the UI elements to also update as the state changes. Addition works but deletion fails every time. I have confirmed the array in the state is being changed correctly but I can only ever delete the newest component instead of a specific one. Thanks for your help.
 //
 handleToggle() {
    return this.state.AdditionQueryArray.map((array, index) => {
      let key = array.key;
      return (

          <Select
            onChange={(e) => this.AdditionalOperatorHandleChange(e, key)}
            options={this.state.OperatorOptions}
            placeholder="Select Operator"
            menuPortalTarget={document.body}
            menuPosition={"fixed"}
          />
          <button onClick={() => this.deleteAdditonalQuery(index)}>
            Delete
          </button>
          {this.forceUpdate}

      );
    });
  }

  createAdditionalQuery() {
    const state = this.state;

    let key = Math.random().toString(36).substring(7);

    var copyArr = [...this.state.AdditionQueryArray];

    copyArr.push({
      key: key,
      field: "fieldDefault",
      property: "propertyDefault",
      PropValue: "Propvalue",
    });
    this.setState({
      AdditionQueryArray: copyArr,
    });
  }

  deleteAdditonalQuery(indexVal) {
    var state = this.state;

    var copyArr = [...this.state.AdditionQueryArray];

    if (indexVal > -1) {
      copyArr.splice(indexVal, 1);
    }

    this.setState({
      AdditionQueryArray: copyArr,
    });
  }

  render() {
    return (

        <button onClick={this.createAdditionalQuery}>Add Query </button>
        {this.handleToggle()}

    );
  }
  ////

Comment: `{this.forceUpdate}` seems very suspect, but then again, you aren't even calling the function.
Answer: Shallow copy and array.splice is interesting way to remove an element from an array by index. I suggest using array.filter instead, it's much more clean. I suggest always using functional state updates when updated arrays stored in state, especially when used in callbacks attached in loops. This avoids any stale state enclosures.
deleteAdditonalQuery(indexVal) {
  this.setState(prevState => ({
    AdditionQueryArray: prevState.AdditionQueryArray.filter(
      (el, index) => index !== indexVal
    ),
  }));
}

Similarly in the add handler, use a functional state update.
createAdditionalQuery() {
  this.setState(prevState => ({
    AdditionQueryArray: prevState.AdditionQueryArray.concat({
      key: Math.random().toString(36).substring(7),
      field: "fieldDefault",
      property: "propertyDefault",
      PropValue: "Propvalue",
    }),
  }));
}

In handleToggle remove the "dead" force update code, it shouldn't be necessary. It's not being invoked anyway. Don't forget to add a React key to the outermost element being mapped.
handleToggle() {
  return this.state.AdditionQueryArray.map((array, index) => {
    const key = array.key;
    return (

 // <-- add React key!
        <Select
          onChange={(e) => this.AdditionalOperatorHandleChange(e, key)}
          options={this.state.OperatorOptions}
          placeholder="Select Operator"
          menuPortalTarget={document.body}
          menuPosition={"fixed"}
        />
        <button onClick={() => this.deleteAdditonalQuery(index)}>
          Delete
        </button>

    );
  });
}

Comment: Perfect! Also nice beard bro


Use netns to bind programs to specific IP addresses

Question: I have an IP address on my server, say, 192.168.0.3, I want to share in a net namespace, so to run apps there which will only be able to communicate to the internet using that 192.168.0.3.
I can "kind" of get it working with the macvlan device type... except, for having two mac addresses, the gateway will often favor my root or my namespace-bound interface.
Is there a way I could just mirror that IP inside a netns without affecting the external IP?
Here's what I've been trying:
ip netns add myns
ip link add link eth0 name en0 netns myns type macvlan
ip netns exec myns ip link set en0 up
ip netns exec myns ip addr add 192.168.0.3/24 dev en0
ip netns exec myns ip route add default via 192.168.0.1

And then I test with variations of netcat; either listening in a remote host and connecting from inside and outside the namespace, or listening inside and outside the namespace and connecting from the remote host.
With macvlan it is unreliable just because the immediate router will send packets to a mac address or the other, I need to reset the cached mac in the router (by sending a packet) before I can switch between the physical or macvlan interface. While this is understandable, I am missing a way to let the IPs be "shared" instead of "fought over".
My motivation for that is that I have just a few IPs in my server, and each already listen to services (that properly allows you to bind to specific IP/ports). And then I'm trying to create a chroot jail which would expose only one of these few IPs to apps running therein. So these jailed apps could bind to any (free) port of these IPs, but won't stand a chance of taking over any other IP addresses in the same server.
(I can think of other options like using LD_PRELOAD, or iptables NAT, but I really think I'm missing just a little to have it working with net namespaces)
Comment: If by "share" you mean the host has the same IP address as the network namespace, then you're just causing a collision by using the same IP address on two systems (consider the network namespace as an other system). Looks like an XY problem with a wrong Y part. You'll have to explain better X: the need to have applications use a specific IP address and why their configuration isn't enough.
Comment: Yes, I understand this is making a collision, and that's exactly why sometimes it works within the netns and then outside it. What I needed was a means to literally expose the outside .3 IP in the netns, such that apps within it could only bind to it.
Answer: You have two options:

Give the IP address 192.168.0.3 to an interface in that namespace, and don't use it outside of that namespace. This will allow that namespace to use the full range of ports without fear of collisions. For this, macvlan is a good option.
Share the IP address 192.168.0.3 between the host and the namespace. In this case, it has to be the same interface, you can't have separate interfaces using the same IP address on the same network. A solution for this would be to use a veth pair and set up forwarding on the host (making sure to use the correct interface/source address). This is similar to what containers do. That would NOT allow you to run a webserver on port 80 on both the host and the container though.

You can set up the veth pair like this:
# Create namespace
ip netns add myns
ip -n myns link set lo up
# Create devices
ip link add myveth0 type veth peer name myveth1
ip link set myveth0 netns myns
# Set addresses
ip -n myns addr add 10.64.0.1/24 dev myveth0
ip -n myns link set myveth0 up
ip addr add 10.64.0.2/24 dev myveth1
ip link set myveth1 up
# Enable forwarding between netns and outside network (customize the rules as needed)
sysctl -w net.ipv4.ip_forward=1
iptables -t filter -A FORWARD -i myveth1 -j ACCEPT
iptables -t filter -A FORWARD -o myveth1 -j ACCEPT
iptables -t nat -A POSTROUTING -s 10.64.0.0/24 -j MASQUERADE

Comment: Your second option is exactly what I wanted to do but couldn't find a way to. The first option you mentioned is what I am able to do but can't, because I already use the IP outside the netns. I just wanted to use the netns like a "mask" to expose only a range (or a single) IP address I have outside. I don't understand what you mean with _"use a veth pair and set up forwarding"_, at first it sounds exactly what I want to avoid (different IPs within the netns).
Comment: Sure, I added instructions for that. This will create a private interface with a private IP address in the namespace. Then you can forward packets on the host between the namespace and the outside network, using whatever routing and filtering rules you need. The problem w.r.t your initial request is that the namespace sees that private IP address, not `192.168.0.3`.
Comment: Thanks for sharing the alternative. This is exactly what I meant with _iptables NAT_ and _conceptually_ what Docker containers do to make services accessible from outside. I'm actually using the `LD_PRELOAD` alternative but still looking forward to a possibility to just use the same IP through different namespaces, if that's possible somehow.
Comment: Same address in different namespaces... why not just use a single namespace for all your jails? What are you namespacing? They have to share a single namespace of UDP and TCP ports if they use the same IP address, because of how those protocols work.
Comment: Because I need 192.168.0.3 also to programs outside the netns, that could bind to that IP and (hypotetically) another 192.168.0.2 address -- that I don't want jailed apps to be able to see or bind to. And I'll still want to get "address already in use" in case, from either netns, I try to bind to an already used port. That's a problem the iptables solution can't solve (yet the `LD_PRELOAD` one does).


I haven't gotten my Strunk & White badge

Question: I have done 80 post edits, but the Strunk & White badge isn't showing up in my profile.

Have I missed something?
Answer: Some badges are not triggered instantly. You have to wait a little. Sometimes even 1 day.
I see that at the time I'm writing this you already have the badge.
Comment: Yes it's Add to my list


Existe alguma forma de tratar todas as Exceptions do software?

Question: Estou criando uma DLL para uso em diversos projetos meus. Criei um método que captura a Source, a Message e outras variáveis que defini, monta um e-mail e envia para mim mesmo. (uma especie de log de erros por e-mail).
Existe alguma forma de referenciar esse método uma vez só no código e ele capturar todas as vezes que uma Exception for lançada mesmo sem Try... Catch?
Comment: Esqueci de comentar que o objetivo final não é tratar a Exception em si, quero apenas que ela seja enviada para meu email. Objetivo final é saber os bugs que acontecem nela após eu ter lançado sua primeira versão.
Comment: Você decide o que fazer quando uma exceção não tratada é detectada, ambas as respostas citam isso.
Answer: Você pode adicionar um  event handler para evento AppDomain.UnhandledException, esse evento será acionado quando uma exceção não é detectada/tratada.

Ele permite que o aplicativo registre informações sobre a exceção
  antes do manipulador padrão do sistema relatar a exceção para o
  usuário e encerrar o aplicativo. Se informações suficientes sobre o
  estado da aplicação está disponível, outras medidas podem ser tomadas
  - como salvar os dados do programa para a recuperação posterior.
Aconselha-se precaução, porque os dados do programa podem ser
  corrompidos quando exceções não são tratadas.

Exemplo retirado daqui em C#.
Adicione uma linha para o método principal (por padrão no arquivo Program.cs em um novo aplicativo do Windows):
namespace MyApp
{
  static class Program
  {
    ///
    /// The main entry point for the application.
    ///
    [STAThread]
    static void Main()
    {
      AppDomain.CurrentDomain.UnhandledException +=  new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
    }
  }
}

Na linha AppDomain.CurrentDomain... está referenciando uma função que ainda não existe, portanto, criaremos ela:
static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
{
  try
  {
    Exception ex = (Exception)e.ExceptionObject;
    MessageBox.Show("Erro! Entre em contato com os desenvolvedores com a seguinte"
          + " informação:\n\n" + ex.Message + ex.StackTrace,
          "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  }
  finally
  {
    Application.Exit();
  }
}

Agora suas exceções não tratadas estão sendo mostrados em um diálogo agradável, você pode fazer outras coisas por aqui - como registrar a exceção, ou tentar suavizar o golpe do acidente, você não pode no entanto, manter o programa rodando após um crash, não há uma maneira de pegar a exceção a esta altura e deixar o programa funcionando.
Em VB.NET deve ficar semelhante a isto:
Module MyApp
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      AddHandler currentDomain.UnhandledException, AddressOf MyHandler

      Throw New Exception("Foo")
   End Sub

   Sub MyHandler(sender As Object, args As UnhandledExceptionEventArgs)
      Dim e As Exception = DirectCast(args.ExceptionObject, Exception)

      Console.WriteLine("Erro! Entre em contato com os desenvolvedores com a seguinte : " + e.Message)
      ' Fazer alguma coisa aqui com a exceção não tratada.
   End Sub
End MyApp

Comment: Eu cai no mesmo erro, a pergunta é sobre vb.net.
Answer: Sim, existe. Antes tem algumas coisas que quero lhe dizer.
Salvo alguma exceção (com o perdão do trocadilho) muito bem justificada só existe um local onde você deve capturar a Exception. É próximo do encerramento da aplicação. Muitas vezes no Main() ou algum método chamado por ele. É ali que você deve capturar todas as exceções lançadas e que não foram capturadas antes. É ali onde deve fazer o que você indicou. E quase sempre a aplicação deve quebrar mesmo, pode até ser de uma forma "bonitinha" mas é o melhor a fazer quando o problema não pode ser consertado. E erros de programação não podem ser consertados em tempo de execução. O máximo que você pode fazer fazer para não deixar quebrar é começar de novo com um estado zerado. A aplicação não quebraria mas começaria tudo de novo como se fosse a primeira execução. Por isto deve estar no Main() ou bem próximo dele.
Mas se você realmente quer capturar algo que nem assim foi capturado existe uma forma:
'isto possivelmente vai no Main
Dim currentDomain = AppDomain.CurrentDomain
currentDomain.UnhandledException += new unhandledExceptionEventHandler(MyHandler)

Shared Sub MyHandler(object sender, UnhandledExceptionEventArgs args) {
   Dim e =  DirectCast(args.ExceptionObject, Exception)
   Console.WriteLine("Erro: {0}", e.Message)
   'aqui você pode fazer o que quiser
End Sub

Coloquei no GitHub para referência futura.
Documentação.
Eu aconselho evitar este método, isto talvez não faça o que você espera.


How can I achieve equivalent of .contains(SomeText) in Firebase Real time Database Android?

Question: I want to let my users search for some contents in my Firebase real time Database. The problem is that Firebase Query only lets me search/filter results with endAt() and startAt(). For Example Let's say my User searches for "rro" , then my searchview should generate suggestions as "Arrow" (after looking in my database if it finds entry with Arrow).
I am able to put suggestions in searchview myself but the problem is .startAt() and .endAt() cannot achieve / or find anything if "rro" is provided. I want filter like .contains();
How can I achieve this in Firebase for Android?
Comment: The Firebase Database is not a full-text search engine. If you need such capabilities, you'll have to add another component for that. Have a look at Kato's answer here for one option: https://stackoverflow.com/questions/22506531/how-to-perform-sql-like-operation-on-firebase
Comment: I don't want to use Firebase cloud functions because I currently have no good knowledge of node.js .  Is there any other way out. A effective and fast
Comment: It'll require an external text search engine. Maybe somebody else knows an easier option, but it's unlikely (this question is asked regularly and the one I linked is the de-facto answer).
Answer: I found a better answer for this situation that doens't requiere creating a special structure:

FirebaseDatabase.getInstance().getReference("users").orderByChild("LastName").startAt(queryText).endAt(queryText+"\uf8ff");

The character \uf8ff used in the query is a very high code point in
  the Unicode range (it is a Private Usage Area [PUA] code). Because it
  is after most regular characters in Unicode, the query matches all
  values that start with queryText.
In this way, searching by "Fre" I could get the records having "Fred,
  Freddy, Frey" as value in LastName property from the database.

The original answer is by Rizwan Khan.
Link: https://www.quora.com/How-would-you-search-a-Firebase-Realtime-Database-with-a-substring
Comment: Sergio, thanks for the answer. It's ok, but share pls links when you quotes any
Comment: @YuriyTsarkov sorry, didn't know if it was ok to publish a link to another page, I'll add it.
Comment: How would I go about finding "Walder Frey" using "Fre" as search term? Or "Mad Freddy has blue glasses"? Thanks
Answer: Make structure like this
- objects
  - UID1:Arrow
  - UID2:Rowboat
  - UID3:Bow
- searchable
  - arrow
    - UID1
  - rrow
    - UID1
  - row
    - UID1
    - UID2
  - ow
    - UID1
    - UID2
    - UID3
  - w
    - UID1
    - UID2
    - UID3
  - rowboat
    - UID2
  - owboat
    - UID2
  - wboat
    - UID2
  - boat
    - UID2
  - oat
    - UID2
  - oa
    - UID2
  - a
    - UID1
    - UID2
  - bow
    -UID3

Then its easy to search, just use a Query like
FirebaseDatabase.getInstance().getReference().child("searchable").orderByKey().startAt(input).endAt(input+"~");

When you create object like arrow you must use a .updateChildren() where you add the entries in searchable aswell. Also when arrow changes name you must update in searchable aswell, and I recommend convert all to lowercase, both your search text and the object names in searchable.
Comment: This is not what I want, I have a structure similar to this and have a node called searchable with keys as titles and values as url to body. This would make the searchable node filled with many keys, I don't want that.. I need optimization and as effective as it can be...
The Title will be generated by end user so he/she may give a title like "The King and the Prince" then there will be so many keys for this note.. (about 17Combination3) that would be ineffective and will occupy heavy on my database..
Comment: This would be a workaround true, but only if you have a few records, and as you can see in the example, you only have 3 UIDs, and yet more that 10 times the records you started with. What if you have 1000, or 100.000 UIDs? This solution is not viable.


Will shutil.rmtree() check for the root directory?

Question: If I call shutil.rmtree('/') Will I nuke my entire drive or does the function have an inner check for this case?
Comment: if you're not root, that will fail with permission denied, else... I wouldn't try that.
Comment: @Jean-FrançoisFabre Actually the `rm` utility in many distros, especially the more end user friendly like Ubuntu, *do* have a check for `/` and even if you run `rm /` as root it will refuse to delete the files. You have to add the option `--no-preserve-root` to shoot yourself in the foot (although I believe it can be fooled relatively easy, it's just to avoid typos on command line). ***[If you want to test this please use a docker container or a VM!]***
Comment: It has no inner check, but the operating system will usually reject it, due to not enough rights (unless it runs with the `root` user).
Comment: why would it check? does `rm` check?
Comment: The `/` directory normally has permissions like `drwxr-xr-x 24 root root`.
Comment: moreover the source code of `shutil.rmtree` is available (written in python, just navigate to it). Check, there aren't any checks.
Comment: oh like `rm -rf /$FOO` when `FOO` isn't defined :)
Comment: i'm just here to say i'm curious why OP even consider what it will do, wondering what kind of script that line's for
Comment: It's just there to remove some temp files in /tmp, but now I am terrified of what may happen if the /tmp suddenly becomes /
Comment: @Makogan: you should not remove `/tmp` either. Only files *in* the `/tmp`, and even that is not really some task you need to worry about. Let the OS take care of temporary files.
Comment: I have to get rid of the files, the SSD is getting saturated in a single run of the program
Answer: rmtree doesn't have any special logic in it. If you have permissions to / (e.g., the program is run by root), you will indeed wipe your installation.


Summing expression involving input variables

Question: I am doing optimization using Pyomo library. I am trying to create an expression which involves summing expressions involving input variables.
x = [k*model.input[i] for i in range(3)]
return [x[i] for i in range(3)]/sum([x[i] for i in range(3)])

I am getting below error :

TypeError: unsupported operand type(s) for /: 'list' and 'SumExpression'

What is the correct formulation for this?
Thanks
Answer: In your return line you have a list [x[i] for i in range(3)] divided by a sum sum([x[i] for i in range(3)]). The interpreter is telling it does not know what this division means. Are you trying to divide each entry of the list as in vector division? Then you can use:
x = [k*model.input[i] for i in range(3)]
denominator = sum([x[i] for i in range(3)])
return [x[i]/denominator for i in range(3)]


JkMount outside of the  using /sites-enabed/

Question: I have an Ubuntu 11.10 with Apache2 that is hosting some sites. I would like to add a site that is hosted in tomcat, so I installed mod_jk and set it up. The tomcat site is hosted under /app over ajp13.
When I include the line
JkMount /app/* ajp13_worker
in inside of the <virtualhost> in either 000-default or default-ssl, it works perfect. However instead I would rather use the Ubuntu convention of putting new sites in a seperate file inside /etc/apache2/sites-enabled/. I have other sites inside of this path using <Location> directives.
However, when I put the above line in a file in this path, it does not work. I just get a 404 when trying to access the site. Also, when I instead use something like
<Location /app/*>
  JkMount ajp13_worker
</Location>

I still get a 404. Any ideas why the JkMount does no work outside of the  even though other Locations do work like this?
Comment: Without more information about your config it is hard to tell. It sounds like you end up in the wrong virtualhost. Can you post your new config file containing the JkMount directive?
Answer: So I ended up moving over from mod_jk to mod_proxy_ajp, which I should have done a long time ago. It is much easier to configure and works out of the box. When using mod_proxy_ajp, adding a tomcat site is as easy as putting a file insite my /sites-enabled/ containing:
<IfModule mod_proxy_ajp.c>
        ProxyPass /app ajp://127.0.0.1:8009/app
</IfModule>


Sorting the files using the date from the filenames

Question: I have a bunch of files with names
32f245bb02abd408a6f0e997640f7e84d3cdf0e4May 2, 2016.java
a5c3fc386ee6ff7259f4004128baff8a961ec804May 3, 2016.java
eaefc7552ab8ce39ea26272f995476869ed91e1aMay 3, 2016.java

I want to arrange them with the dates (in the file names). I use regex to extract the date from the file names and sorted them but now I'm stuck at sorting the files according to date. I try renaming the files but dates are repeating and cant use the creation/modified/access dates as all are the same.
File directory2 = new File("path to files");

            String newfile="";
                Set<String> source= new HashSet<String>();

                ArrayList<String> datestring=new ArrayList<String>();
                try (Stream<Path> paths = Files.walk(Paths.get(directory2.toString()))) {
                     paths.skip(1)
                          .forEach(s->{source.add(s.toString());});
                    } catch (IOException e) {
                            e.printStackTrace();
                      }

                for(Iterator<String> it=source.iterator(); it.hasNext();) {
                        newfile = it.next().toString();
                        File f = new File(newfile);
                        String Date = f.getName();

                        String regex2 = "((?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Sept|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?))(\\s+)(\\d+)(,)(\\s+)((?:(?:[1]{1}\\d{1}\\d{1}\\d{1})|(?:[2]{1}\\d{3})))(?![\\d])";
                        Pattern pattern2 = Pattern.compile(regex2,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
                        Matcher m2 = pattern2.matcher(Date);
                        while(m2.find()) {
                            String file= m2.group(0);
                            datestring.add(file);
                        }
              }

              Collections.sort(datestring, new Comparator<String>() {
                        DateFormat f = new SimpleDateFormat("MMM dd, yyyy");
                        @Override
                        public int compare(String o1, String o2) {
                            try {
                                return f.parse(o1).compareTo(f.parse(o2));
                            } catch (ParseException e) {
                                throw new IllegalArgumentException(e);
                            }
                        }
                    });

        }

I try to rename the files after extracting the date as follows but still if the date is repeating its not possible to rename them and still no luck with sorting them according to the date.
for(Iterator<String> it=source.iterator(); it.hasNext();) {
                    newfile = it.next().toString();
                    File f = new File(newfile);
                    String Date = f.getName();
                    for (String datematch:datestring) {
                        if(Date.contains(datematch)) {
                            f.renameTo(new File("path to new directory"+datematch+".java"));

                        }
                    }

                }

Comment: Since the text before the date is of fixed length, why don't you just do a `substring` followed by `SimpleDateFormat`
Comment: Please elaborate on what works with your code and what doesn't and where the problem is. I undestand the problem is that the dates are not unique? Or do you have a problem with compiling your code?

What would you expect and what do you currently see if you try to compile / run it?
Comment: Im stcuk at how can I now use these dates to save the files and sort them?
Comment: okay you are proposing a simpler approach but question is again how can I sort he files?
Comment: Not answering your question, I recommend you stay away from `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated. Instead use `DateTimeFormatter` and `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/).
Comment: So what do you want to happen with the files that have the same date?
Answer: Here is a code in Java 8 to sort your files based on date on the filename.
public static void main(String[] args) throws IOException {

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.ENGLISH);

        try (Stream<Path> filesStream = Files.list(Paths.get("/tmp/stackoverflow-files"))) {
            List<String> files = filesStream.map(Path::getFileName)
                    .map(Path::toString)
                    .map(filename -> new Pair<>(filename, filename.substring(40).replace(".java", "")))// The hash seems to be fixed of size 40
                    .map(fileAndDate -> new Pair<>(fileAndDate.getKey(), LocalDate.parse(fileAndDate.getValue(), dateFormatter)))
                    .sorted(Comparator.comparing(Pair::getValue))
                    .map(Pair::getKey)
                    .collect(Collectors.toList());
            System.out.println(files);
        }
    }

What the code does :

get all files on a path
get file name
keep filename and manipulate a copy of it to have a localDate by :

removing the hash (of size 40 apparently)
removing .java
transform to LocalDate

sort by LocalDate
return only filenames list after sorting by date
print list of files

Output :
[32f245bb02abd408a6f0e997640f7e84d3cdf0e4May 2, 2016.java, eaefc7552ab8ce39ea26272f995476869ed91e1aMay 3, 2016.java, a5c3fc386ee6ff7259f4004128baff8a961ec804May 3, 2016.java]


Ver historico de numeros colocados no input

Question: Olá
Eu estou fazendo um projeto de site de apostas de números de 1 a 100 e preciso que o usuário consiga ver os números e valores apostados, tipo um histórico. Para esse projeto estou utilizando HTML, CSS e JS.
Toda ajuda é bem vinda.
Vou deixar o trecho do código que estou usando para validar as apostas do usuário.

Descubra o número de 1 a 100

Saldo: 100€

    Escolha um número
    <input type="number" id="bet" placeholder="Entre 1 a 100">

    Faça sua aposta:
    <input type="number" id="valorbet" placeholder="Superior a 0€">

    <button onclick="verifyNumber()">Sortear</button>

    <button onclick="historico()">Historico</button>

var numberToFind = 0;
var attempts = 0;
var saldo = 100;

function refresh(){

    var element = document.getElementById('bet');
    element.value = '';
    var element2 = document.getElementById('valorbet');
    element2.value = '';

    numberToFind = parseInt(Math.random() * 101);
    attempts = 0;

    console.log('The number to find: '+numberToFind);
}

refresh();

function verifyNumber(){
    var element = document.getElementById('bet');
    var bet = element.value;
    var valorbet = document.getElementById('valorbet');
    var vbet = Number(valorbet.value);

    let n = [];

    if(bet < 1){
        alert("GAME OVER!")
        window.location.reload(true);
        return;
    }

    if(saldo == 0){
        alert("FIM DE JOGO! Seu saldo é 0€. Você teve "+attempts+ " erros");
        window.location.reload(true);
        return;
    }

    if(vbet > saldo || vbet == 0){
        alert("Faça uma aposta superior a 0€ ou o saldo é insuficiente!");
        return;
    }
    if(bet > 100)
    {
        alert('Aposta é inválida');
        return;
    }

    if(bet > numberToFind)
    {
        attempts++;
        alert(' O número para ser encontrado é MENOR');
        document.body.style.background = "rgb(205, 46, 46)";
        saldo-=vbet;
        document.getElementById("saldo").innerHTML = `Saldo é ${saldo}€`;
        n.push(bet);
    }
    else if(bet < numberToFind)
    {

        attempts++;
        alert(' O número para ser encontrado é MAIOR')
        document.body.style.background = "rgb(205, 46, 46)";
        saldo-=vbet;
        document.getElementById("saldo").innerHTML = `Saldo é ${saldo}€`;

    }
    else
    {
        document.body.style.background = "rgb(32, 201, 32)";
        alert('✅ Parabéns você acertou!! Com '+attempts+' erros.Seus numeros'+ n);
        saldo+=vbet;
        document.getElementById("saldo").innerHTML = `Saldo é ${saldo}€`;
        refresh();
    }
}
Comment: Em vez de ter `attempts` como um número de tentativas, iniciando em 0, inicie como uma array vazia e vá adicionando a essa array as tentativas erradas. Quando precisar saber o número de tentativas realizadas, é `attempts.length`. O histórico pode até ficar sempre à mostra numa div: na `verifyNumber()`, depois de inserir a tentativa nova em `attempts`, você transforma a array em string com `attempts.join()` e coloca essa string na div do histórico.
Answer: Certo como você só colocou o HTML do botão do histórico suponho que você queira a resposta da lógica toda, se não falta informação, outro detalhe e que oriento que utilize os recursos do stackoverflow que tem essa opção de inserir HTML e JavaScript, se encontra na parte superior tem um ícone <>.
Mas vamos lá eu faria o seguinte:

var numberToFind = 0;
var attempts = 0;
var saldo = 100;

function refresh(){

    var element = document.getElementById('bet');
    element.value = '';
    var element2 = document.getElementById('valorbet');
    element2.value = '';

    numberToFind = parseInt(Math.random() * 101);
    attempts = 0;

    console.log('The number to find: '+numberToFind);
}

refresh();

var arrHistoricoSaldo =[]; // criei um array com o saldo inicial
var arrHistoricoNumeroApostado = []; // criei um array com os numeros iniciais de 1 a 100

function verifyNumber(){
    var element = document.getElementById('bet');
    var bet = element.value;
    var valorbet = document.getElementById('valorbet');
    var vbet = valorbet.value;

    arrHistoricoSaldo.push(bet);
    arrHistoricoNumeroApostado.push(vbet)
    // aqui toda vez que o usuario clica em sortear os numeros inseridos vao para dentro ddos respectivos arrays.

    let n = [];

    if(bet < 1){
        alert("GAME OVER!")
        window.location.reload(true);
        return;
    }

    if(saldo == 0){
        alert("FIM DE JOGO! Seu saldo é 0€. Você teve "+attempts+ " erros");
        window.location.reload(true);
        return;
    }

    if(vbet > saldo || vbet == 0){
        alert("Faça uma aposta superior a 0€ ou o saldo é insuficiente!");
        return;
    }
    if(bet > 100)
    {
        alert('Aposta é inválida');
        return;
    }

    if(bet > numberToFind)
    {
        attempts++;
        alert(' O número para ser encontrado é MENOR');
        document.body.style.background = "rgb(205, 46, 46)";
        saldo-=vbet;
        document.getElementById("saldo").innerHTML = `Saldo é ${saldo}€`;
        n.push(bet);
    }
    else if(bet < numberToFind)
    {

        attempts++;
        alert(' O número para ser encontrado é MAIOR')
        document.body.style.background = "rgb(205, 46, 46)";
        saldo-=vbet;
        document.getElementById("saldo").innerHTML = `Saldo é ${saldo}€`;

    }
    else
    {
        document.body.style.background = "rgb(32, 201, 32)";
        alert('✅ Parabéns você acertou!! Com '+attempts+' erros.Seus numeros'+ n);
        saldo+=vbet;
        document.getElementById("saldo").innerHTML = `Saldo é ${saldo}€`;
        refresh();
    }
}
n = 0
var element = document.getElementById('historic');
function historico() {

    document.getElementById("historicN").innerHTML = ` Numeros apostados: ${arrHistoricoNumeroApostado} : `
    document.getElementById("historicV").innerHTML = ` Valores apostados: ${arrHistoricoSaldo} `

}

Descubra o número de 1 a 100

Saldo: 100€

    Escolha um número
    <input type="number" id="bet" placeholder="Entre 1 a 100">

    Faça sua aposta:
    <input type="number" id="valorbet" placeholder="Superior a 0€">

    <button onclick="verifyNumber()">Sortear</button>
    <button onclick="historico()">Historico</button>

Numeros

Valores

Bom basicamente inseri dois arrays, e quando voce clica pra apostar, adiciona nesses arrays o que os valores do imput, depois basicamente imprimo o array
Comment: Obrigado pela ajuda Hairy Skull. Deu certo.


Routing Error Rails, dont undertand

Question: Are all correct but the error persists, i make the all codes to all you see
Routing Error

No route matches {:controller=>"posts", :user_id=>#<Post id: 1, title: "sa", content: "sasa", created_at: "2013-01-06 00:25:03", updated_at: "2013-01-06 00:25:03", image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil, user_id: 1>, :action=>"edit"}
Try running rake routes for more information on available routes.

My routes are:
  get "painel/index"

 resources :posts

  resources :user  do
    resources :posts,:comments

      end

and my models is:
user.rb

  attr_accessible :email, :password, :password_confirmation,:username
  has_many :posts
  has_many :comments

post.rb

  attr_accessible :content, :title  ,:image
  has_many :comments
  belongs_to :user

Comment: It looks like you've got a mismatch b/n the :posts resource and the :user/:posts resource... instead of setting controller to 'posts' you probably want it to be 'user/posts'...

Please show us how you are invoking that route (ie. the link_to call...).
Answer: 1) Check 'rake routes'
2) use the url or path you get in routes list. That will solve your error
If that does not solve your error,
paste your routes file and link_to call which is returning error.

Routing Error Rails, dont undertand


ReactJS Checkbox If Value In Array

Question: How to make checkbox input in reactjs checked if the value included inside an array?
I tried to filter the array inside the checked props but still not working
  const [productForm, setProductForm] = useState({
    sizes: ["41", "42", "43"],
  });

                [40, 41, 42, 43, 44, 45].map((size, index) => (

                          <input type="checkbox" className="form-check-input" name="sizes" value={size} onChange={e => handleCheckBox(e)} checked={productForm.sizes.includes(size)} />

                          {size}

                ))

Answer: Your logic is correct but you're looking for a number in an array of strings:
["40", "41", "42"].includes(40) // false

[40, 41, 42].includes("40") // false

[40, 41, 42].includes(Number("40")) // true

Comment: ahh i see, its work now after converting the value in array same as value in array like this, thanks...

ReactJS Checkbox If Value In Array


In what ways is a set's inversion different than its prime form?

Question: It is clear to me that an inversion shares the vast majority of its features with the prime form.
They have the same interval vector, same spread-evenness, the same number of generic intervals, the same number of imperfections, the same sameness and coherence quotients (as discussed by Carey 2007), the same number of trichords (or any other n_chord for that matter), more or less the same roughness measure (Vassilakis 2010), and so on.
With that being said, the very distinction between the prime form of a set and its inversion implies that there is some "difference" between them.
What are some (or the most prominent) features that set apart an inversion from its prime form?
(looking for anything, including structural features, acoustical features, mathematical features, social features, whatever distinction you can think of, I am interested in).
Many thanks!
Carey, N. (2007). "Coherence and sameness in well-formed and pairwise well-formed scales." Journal of Mathematics and Music 1(2): 79-98.
Vassilakis, P. N. and R. A. Kendall (2010). Psychoacoustic and cognitive aspects of auditory roughness: definitions, models, and applications. Human Vision and Electronic Imaging XV, International Society for Optics and Photonics.
Answer: It depends on the set. For diatonic subsets the differences are essential, and underpin much of the Western tradition. e.g. (037) is both the minor triad and it's inversion the major triad. Similarly (0258) as prime can be voiced as a half diminished seventh or a minor triad with added sixth, or as the 'Tristan-chord'; all of which sound and function completely differently to each other, and differently again from the inversion, which we know as the dominant seventh. With more complex sets it's the opposite problem. By ear you'd be hard pushed to tell if you were listening to 6-z4, 6-5 or 6-z6, however they were spaced, let alone whether they were in prime or inversion.
Comment: I understand that the inversion "sounds different" than the prime form. But I am after tangible, even quantifiable features. Can you think of any?
Comment: In other words, "It sounds different" is absolutely right, but it's not really tangible. If it acts differently, can you think of a way to formalize the unique behavior of a given set and its inversion?
Comment: For instance, by definition(-ish), the prime form is more compact than its inversion. That's one quantifiable feature I can think of.
Comment: i read the articles you cited and can't think of anything useful re application to sets - sorry
Answer: The difference between the minor triad and the major triad is a good case study. People are often surprised when they hear that they have the same interval vector, since they "sound so different".
The commonplace that minor and major triads, which have the same prime form, sound very different, can be put into question. I'm pretty sure that it takes quite a while for music students to reliably tell apart minor and major triads by ear. However, if we compare, say, the minor triad and a three-note cluster (comprised of C, C#, D in some inversion or transposition, Forte number 3-1), I am pretty certain that people with no musical background at all can learn to tell them apart pretty much immediately. So yes, the major and minor triad are different, but by far not as different as many of the other possible three-note chords/chordioids.
The reason that minor and major triads do not sound all that different is that they have the same interval vector, etc. etc.. Now to get to your question: what feature makes that they nonetheless sound different? It is a good question, and actually a bit mysterious to me. The best answer I can offer is in the way the overtone series of the three tones interact. On most instruments, one cannot hear very much of the overtone series. So it's important not to overemphasize the contribution of overtones to the overall sound of chords.
In trying to work this out I added the first five harmonic overtones to each of the three chord notes of a major and a minor triad. The resulting pitch collections are not inversions of each other and have a different interval vector, so this could be a good answer to your question.
The first five overtones are three different octaves, a fifth, and a major third. So on the level of the pitch class, we only need to add the fifth and major third to all three of the chord notes.
For C major (C, E, G), we get (C, D, E, G, Ab, B).
For C minor (C, Eb, G), we get (C, D, Eb, E, G, Bb, B)
As mentioned, these are not inversions of each other. (They do not even have the same cardinality.)
In other words, although the fundamentals of the major and minor triad have the same interval vector, as soon as you start to consider overtones, some divergences start to occur, which could explain the difference in sound.
As a sidenote: This train of thought would predict that major and minor chords made with pure sine waves would be harder to tell apart than the same chords made with more harmonic content. (Perhaps interesting to test this empirically?)
Finally, perhaps a simpler answer is that minor and major chords are typically embedded differently in harmonic progressions. And they also have different melodic implications. Perhaps that is the simpler explanation.
Comment: Your answer goes exactly along the lines of what I was looking for. I like your experimental proposal as well, it would serve as a good measure to test your hypothesis. Thank you for your thoughtful response!
Comment: I just re-read your answer two years later and I am still in awe of its insight. Thanks again for taking the time to write!
Answer: Prime form is just a canonical way of specifying all the pc-sets that are T- and I-related. It's the most "compact" way to express a set: in normal form and transposed to start at 0.
For example, see "Set Class and Prime Form" on OpenMusicTheory.com.

In order for a pitch-class set to be transpositionally or inversionally related to some other pitch class set, they must share the same collection of intervals....All pitch-class sets that are transpositionally and inversionally related belong to the same set class, and they are represented by the same prime form. (italics original)
Comment: I absolutely understand how the prime form and its inverse are defined. But that's not really what I'm asking. I'm looking for tangible, quantifiable features that set them apart. For instance, you can say that what sets a set apart from its transposition is frequency. or what sets a mode of a set from another is its relational context. What, then, sets the inverse apart from its prime form? What features? How can they be measured?
Comment: Right, and in that regard they are non-invertable because their inversion maps back to themselves. That's the case with the diatonic set as well. So of course my question does not apply to non-invertable sets.
Comment: A sets inversion has exactly the same interval vector by definition.
Comment: The kind of differences you're looking for don't apply to arbitrary sets. For example, the sets {0, 6}, {0, 4, 8}, {0, 3, 6, 9}, {0, 2, 4, 6, 8}, and {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, T, E} all share the quality that their prime forms and inversions are identical.
Comment: @MichaelSeltenreich you must analyze this as sounding by intervals, not by pitches. So you may predict some inversion differences.


How can search number in string?

Question: Hello? I want to know how can I find number in my string code.
This is my c++ code.
    string firSen;
    cout<<"write the senctence : "<<endl;
    getline(cin,firSen);
    int a=firSen.find("pizza");
    int b=firSen.find("hamburger");
    int aa=firSen.find(100);
    int bb=firSen.find(30);

I want to write
 I want to eat pizza 100g, hamburger 30g!!

and I want to know 100 and 30 address.
I know how to find pizza and hamburger address.(It's the right code)
but I don't know how to find number..(I think  int aa=firSen.find(100); int bb=firSen.find(30); is wrong code)
Could you help me?
Comment: `firSen.find("100");` would this work for you?
Comment: Loop into your string and once you got a character that is a number, iterate until your character is not a number anymore. Once you've done that, you have a string that contains a number. After that, you just need to convert your number into a string.
Answer: The std::string::find() function takes a std::string or a const char* as valid search keys.
If you want to search for 'generic numbers' you'll have to convert them to a std::string or use a const char* literal
 size_type aa=firSen.find("100");

or
 int num = 100;
 size_type aa=firSen.find(std::to_string(num));

See the std::to_string() function reference

As it looks from your input sample, you don't know the numeric values beforehand, thus looking up something like
 size_type aa=firSen.find("100");

renders useless.
What you actually need is some decent parser, that enables you reading the numeric values after some certain keywords, that require a numeric attribute (like weight in your sample).
The simplest way might be, to find your keywords like "hamburger" or "pizza", and move on from the found position, to find the next digit ('0-9'), and extract the number from that position.
Using std::regex as proposed in @deeiip's answer, might be a concise solution for your problem.
Comment: @deeiip Let's concentrate on what's actually asked in the OP. It's fault of the poster, don't having elaborate on that problem enough. (I'll retract my downvote on your answer)
Comment: I think the op wants to find any number, not specifically 100 or 30
Comment: @deeiip Well, the information given here should enable them to do it (I've mentioned _`'generic numbers'`_, didn't I?)
Comment: when I dont know how much pizza I'm expecting (say thats what i want to know) how will I know the value of num in your code?
Answer: I'd use this in your situation (if I was searching for just a number, not a specific number):
std::regex rgx("[0-9]+");
std::smatch res;
while (std::regex_search(firSen, res, rgx)) {
    std::cout << res[0] << std::endl;
    s =  res.suffix().str();
}

This is c++11 standard code using <regex>. What it does is: search for any occurence of a number. This is what [0-9]+ means. And It keep on searching for this pattern in your string.

This solution should only be used when I dont know what number I'm expecting otherwise it'll be much more expensive than other solution mentioned.
Comment: I think this is what the op wants. If I'm wrong, yes! my solution is expensive and complex.

How can search number in string?


Menu não altera a largura

Question: Estou fazendo um menu vertical e colocando a cor preta como background. O que estou passando é que quero deixar uma largura fixa de uns 200px para cada linha do menu, só que ele não altera. Ele deixa o tamanho de acordo com o tamanho do texto.
Código HTML:

A empresa

Nossos serviços

Nossos produtos

Vídeos & Downloads

Fale conosco

CSS:
ul{
  list-style: none;
  width: 100%;
}

ul li{
  display: block;
  margin-top:25px;
  float:none;
}

ul li a{
  background:#000;
  padding:10px;
  width: 200px;
}

Answer: Você está tratando o background dentro do elemento a. Faça dessa forma:
ul{
    list-style: none;
    width: 100%;
}

ul li{
    background:#000;
    display: block;
    margin-top:25px;
    float:none;
    padding:10px;
    width: 200px;
}

Se quiser personalizar especificadamente os links, daí sim você cria uma chamada no css para eles por meio do elemeno a:
ul li a{
    color: red;
}

Comment: deu certo, me salvou. Obrigado!
Comment: Que bom que funcionou. De nada [:

Menu não altera a largura


Definition of Basis for the Neighborhood System

Question: I'm trying to learn a bit about topology through independent study.
I've been using Bert Mendelson's "Introduction to Topology - 3rd edition". I'm having a lot of fun but I'm a bit confused regarding definition 4.9 on pg 45. I will reproduce it hereafter:

Definition 4.9 - Let $a$ be a point in metric space $X$. A collection of neighborhoods $\mathcal{B}_a$ is called a basis for the neighborhood system at $a$ if every neighborhood $N$ of $a$ contains some element $B$ in $\mathcal{B}_a$.

Here is the source of my confusion, please correct me if I am wrong:
1) Every neighborhood of $a$ must contain $a$ it self, so shouldn't any neighborhood of $a$ be automatically a basis of the neighborhood system at $a$?
2) If this is true (and I'm hoping it is false) what is the condition that forces $\mathcal{B}_a$ to grow beyond a trivial set such as $\mathcal{B}_a = \{a\}$?
Thank you.
Comment: The members of $\mathcal{B}_a$ are required to be nbhds of $a$; $\{a\}$ isn't a a nbhd of $a$ unless $a$ is an isolated point of $X$, in which case $\{\{a\}\}$ *is* a nbhd base at $a$.
Answer:
Yes, every neighborhood of $a$ must contain $a$; but it is not true that any particular neighborhood is a basis for the neighborhood system, because it may not be contained in every neighborhood. For example, consider the real line and $a=0$. The set $(-1,1)$ is a neighborhood of $a$, but is not by itself basis of the neighborhood system at $0$ because, for example, the neighborhood $(-1/3,1/2)$ does not contain the set $(-1,1)$.
A basis for the neighborhood system is a collection of neighborhoods with the property that any neighborhood contains (at least) one element of the system. They can be thought of as "small enough representatives" so that at least one of these representatives is contained in any given neighborhood.
First, note that $\mathcal{B}_a$ is a set of sets, not a set of elements of the space. Perhaps you mean $\mathcal{B}_a=\bigl\{\{a\}\bigr\}$, rather than $\mathcal{B}_a=\{a\}$. Second: if $\{a\}$ is a neighborhood of $a$ (it may not be: for example, it may not be open!) then it is true that one can take $\mathcal{B}_a$ to be just $\bigl\{\{a\}\bigr\}$. But for example, $\{\{0\}\}$ is not a basis of the neighborhood system for $0$ on the real line (with the usual topology), because $\{0\}$ is not even a neighborhood of $0$.
It is true that if there is a "smallest open set that contains $a$", then one can take that set alone to be a basis of the neighborhood system. But in many topological spaces, no such set exists. In the real numbers with the usual topology, there is no "smallest open set that contains $a$", so a basis of the neighborhood system at $a$ needs to have more than one element: given any open set that contains $a$, there is always a strictly smaller open set that contains $a$, so a basis for the neighborhood system in this topological space would necessarily have to contain infinitely many elements.
(An example of a basis of the neighborhood system at $a$ for the real numbers with their usual topology would be
$$\mathcal{B}_a = \left\{ \left.\left(a -\frac{1}{n},a+\frac{1}{n}\right)\right|\, n\in\mathbb{N}\right\}$$
which you can verify: each element of $\mathcal{B}_a$ is a neighborhood of $a$, and every neighborhood of $a$ contains at least one element of $\mathcal{B}_a$; you can also replace the sets in $\mathcal{B}_a$ with the corresponding closed intervals, which are also neighborhoods and have the relevant properties.)
Comment: I think you identified the source of my confusion. Thank you very much.


$|f(z)| \leq \frac{1}{1-|z|}$ implies $|f'(z)| \leq \frac{4}{(1 - |z|)^2}$

Question: I have the following question:

Suppose that $f$ is analytic in the unit disk and $|f(z)| \leq \frac{1}{1-|z|}$. Prove that $|f'(z)| \leq \frac{4}{(1 - |z|)^2}$ in the open unit disk.

I am not really sure where to start. Any help would be appreciated.
Answer: Fix $z, |z|=r, 0 \le r <1$
The idea for this is to apply Cauchy on a disc centered at $z$ of some radius $\rho < 1-r$ so it is contained in the unit disc and then minimize the estimate on $\rho$ to find best such.
Concretely $2\pi if'(z)=\int_{|w-z|=\rho}\frac{f(w)}{(w-z)^2}dw$, and since $|f(w)| \le 1/(1-|w|) \le 1/(1-(r+\rho))$ on the integration circle by hypothesis (as $|w| \le r+\rho$ there) while $|dw/(w-z)^2|=1/\rho$ we immediately get:
$|f'(z)| \le \frac{1}{(1-(r+\rho))\rho}, 0 < \rho < 1-r$.
A simple AM-GM inequality (or calculus or pick your favorite method) shows that $\frac{1}{(1-(r+\rho))\rho}$ is smallest when the two terms in the denominator are equal, or $\rho=\frac{1-r}{2}$, giving by substitution precisely that:
$|f'(z)| \le \frac{4}{(1-r)^2}=\frac{4}{(1-|z|)^2}$ so we are done!
Comment: Very impressive
Comment: happy to be of help - it is an interesting question how sharp the constant $4$ in there is


Carregar checkbox a partir de select

Question: Bom dia!
Tenho o seguinte select:
 <select name="category" class="form-control" id="categorias">
                    <option value="">Escolha uma categoria</option>
                    <optgroup label="Vehicle">
                    <option value="2">Aircraft</option>
                    <option value="3">Automotive Items & Parts</option>
                    <option value="4">Boats & Watercraft</option>
                    <option value="5">Cars</option>
                    <option value="6">Classic Cars</option>
                    <option value="7">Commercial Trucks & Tractor Trailers</option>
                    <option value="8">Off Road Vehicles</option>
                    <option value="9">RV & Motorhomes</option>
                    <option value="10">SUVs</option>
                    <option value="11">Utility & Work Trailers</option>
                    <option value="12">Vans</option>
                    </optgroup>
                    <optgroup label="Sevices">
                    <option value="2">Automotive Services</option>
                    <option value="3">Beauty & Salon Services</option>
                    <option value="4">Caregivers & Baby Sitting</option>
                    <option value="5">Cleaning Services</option>
                    <option value="6">Construction & Remodeling</option>
                    <option value="7">Financial Services</option>
                    <option value="8">Health & Wellness</option>
                    <option value="9">Home Services</option>
                    <option value="10">Insurance</option>
                    <option value="11">Office Services</option>
                    <option value="12">Real Estate Services</option>
                    </optgroup>
                    <optgroup label="Pets">
                    <option value="2">Birds</option>
                    <option value="3">Cats</option>
                    <option value="4">Dogs</option>
                    <option value="5">Fish & Reptile Pets</option>
                    <option value="6">Free Pets to Good Home</option>
                    <option value="7">Horses</option>
                    <option value="8">Pet Supplies</option>
                    </optgroup>
                  </select>

Queria carregar a div abaixo a partir do select de option value 3 por exemplo:

                Características

                     Touch Screen
                     Wi-fi
                     Bluetooth

                     Flash
                     Câmera Frontal
                     GPS

                     Tecnologia NFC
                     Extensão para Cartão de Memória

Estou usando o JS abaixo para fazer aparecer a div, mas não sei como especificar pra aparecer somente quando eu quero.

Answer: Basta comparar o valor_selecionado que você obteu com o valor que deseja, neste caso 3.
E em caso de ser o valor, passar o visibility = visible
// Selecionamos o menu dropdown, que possui os valores possíveis:
var menu_dropdown = document.getElementById("categorias");

// Requisitamos que a função handler (que copia o valor selecionado para a caixa de texto) [...]
// [...] seja executada cada vez que o valor do menu dropdown mude:
menu_dropdown.addEventListener("change", function(){
    // Como este código é executado após cada alteração, sempre obtemos o valor atualizado:
    var valor_selecionado = this.options[this.selectedIndex].value;

    // Altere este código se desejar resultados mais complexos:
    if(valor_selecionado == 3){
        document.getElementById("div_personalizar").style.visibility = "visible";
    } else {
        document.getElementById("div_personalizar").style.visibility = "hidden";
    }
});

Comment: Luis, muito obrigado pela ajuda.
Answer: Utilizando jQuery, já que foi apontado que à o uso dele:

Você pode testar aqui: http://jsfiddle.net/vvam97jn/1/
Comment: Alterado o código para escolher as categorias.
Comment: Entendi Francisco, mas e como eu faço pra abrir somente se a categoria X for selecionada?
Comment: Francisco, funcionou corretamente, mais uma dúvida só, se eu fizer a listagem das categorias dinamicamente, vindo o option value do BD, eu consigo tratar os ifs dinamicamente também? Por nome da categoria talvez? Desculpa não estar testando agora, é que estou em meu trabalho. Novamente obrigado pela sua ajuda.
Comment: Sim, é possível, você pode fazer de várias formas isso. Criar o javascript pelo backend, ou criar uma array pelo backend e enviar para o javascript.
Também pode fazer por Ajax a verificação e só enviar para a div o código necessário.

Carregar checkbox a partir de select


Jquery após reload

Question: Gostaria de saber se existe alguma maneira de fazer, pois tenho uma função que quando clico em um botão do menu ele captura via jquery a id da pagina porem se exemplo eu estiver na pagina INICIO que nao tem id e for para pagina serviço que tem ID ele da um reload e minha ação não funciona tem alguma maneira seila armazenamento nos coookies seila ?
<code> $('.sub-menu a').click(function() {

        var anchor;
        var link = $(this).attr('href');
        if (link.indexOf('#') !== -1) {
            anchor = '#' + link.split('#').pop();
            console.log('anchor',anchor);
        }

        $('.id-sub').slideUp(2000);
        if (anchor !== undefined) {
            $(anchor).slideDown(2000).addClass('fixed');
            $('html,body').animate({ 'scrollTop': $(anchor) }, 600, function(){
                window.location.hash = target;
            })
        }
    });
</code>
porque seguinte preciso esconder todos os conteudos que estao na class <code>('.id-sub')</code> mais quando eu saiu da pagina INICIO e clico na pagina SERVIÇO ele tinha que me mostrar somente a ID que eu cliquei e esconder o resto do conteudo mais como a pagina da reload ele esconde tudo e nao mostra a id que eu cliquei
Comment: Indique o que pretende fazer, ou seja, a funcionalidade que pretende implmentar.
Comment: assim tenho um menu que contem `INICIO` e `SERVIÇOS (com sub-menus)` cada sub-menus desses tem uma determinada `ID` quando eu estou na pagina INICIO e quero passar para a pagina SERVIÇO ele tem que ver a id que eu cliquei que a função acima já faz mostrar a id correta e esconder as outras pois se esse conteudo esta em uma pagina só
Comment: se eu estiver ja dentro da pagina `SERVIÇO` e clicar nas `id` ele funciona normalmente porém quando eu estou na pagina `INICIO` e clico em um `sub-menu` ele mostra todo o conteudo daquela pagina sendo que era para mostrar somente o conteudo da `id` clicada
Comment: deu para entender um pouco?
Comment: Lamento mas não consigo entender o propósito
Comment: tenho um `MENU` este menu tem `INICIO` e `SERVIÇO (com sub-menus de cada serviço)` se eu estiver na pagina menu e clicar nos sub-menus ele da um efeito de sliderUP e slideDown conforme a `id` que for clicada do sub-menu porém se eu estiver na pagina `INICIO`  e clicar em uma `id` do sub-menu ele teria que mostrar somente o conteudo da `id` que eu cliquei certo mais isso nao acontece ele simplesmente da reload na pagina e mostra todos conteudos de todas `id`
Comment: o que eu quero fazer é ao mudar de pagina ele me exiba somente o conteudo da `id` clicada
Answer: Consegui resolver o meu problema obrigado..
<code>//Efeito SliderDown/SliderUp
    $('.sub-menu a').click(function() {

        var anchor;
        var link = $(this).attr('href');
        if (link.indexOf('#') !== -1) {
            anchor = '#' + link.split('#').pop();
            console.log('anchor',anchor);
        }

        $('.id-sub').slideUp(2000);
        if (anchor !== undefined) {
            $(anchor).slideDown(2000).addClass('fixed');
            $('html,body').animate({ 'scrollTop': $(anchor) }, 600, function(){
                window.location.hash = target;
            })
        }
    });

    //Pre-Loader
    jQuery(window).load(function () {
        $('.id-sub').hide();
        $("#loading").fadeOut(2000,function(){
            $("#page").css("display","block").fadeIn("fast-slow");
            var currentPage = window.location.hash;//
            if (currentPage) {
                $(currentPage).slideDown(2000).addClass('fixed');
                $('html,body').animate({ 'scrollTop': $(currentPage).offset().top });
            }
        });

    });
</code>

Jquery após reload


Valor nulo está indo para a função de erro do ajax - ASP.NET MVC

Question: Estou desenvolvendo uma página de consulta de CEP onde o envio e o retorno das informações é feito em ajax:
<code>$.ajax({
        url: "@Url.Action("PesquisarCEP", "CEP")" + "?cep" + retirarMascara($("#dsCEP").val()),
        type: "GET",
        success: function (retorno) {
            if (retorno != null) {
                $("#Logradouro").val(retorno.Logradouro);
                $("#Bairro").val(retorno.Bairro);
                $("#Estado").val(retorno.IdMunicipio.IdEstado.ID);
                ajaxBuscarMunicipio(retorno.IdMunicipio.ID, retorno.IdMunicipio.IdEstado.ID)
            }
            else {
                $.notify("Não foi encontrado o CEP: " + $("#enderecoCEP").val() + ", Você pode preencher o endereço manualmente.", { status: "danger" });
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            bootbox.alert("Oops, Não foi possivel conectar-se ao servidor da Onofre, Tente mais tarde.");
        }
</code>
Este AJAX chama um método quer procura o endereço informando o CEP, caso não encontra, o método retorna null.
Método da Controller:
<code>    [HttpGet]
    public JsonResult PesquisarCEP(string cep)
    {
        try
        {
            CepRep repositorio = new CepRep();

            return Json(repositorio.PesquisarCEP(cep), JsonRequestBehavior.AllowGet);
        }
        catch (Exception)
        {

            throw new Exception("CEP não encontrado!!!!");
        }
    }
</code>
O problema é que, quando o método retorna null, em vez de ir para success, ele valor para o método "error" do ajax. Com o seguinte erro: "Unexpected end of JSON input".
Como fazer que o métodos "Sucess" receba o nulo normalmente?
Comment: Quando o cep não é encontrado cai sempre no catch?? Poderia tentar fazer return `Json(new{})`
Answer: Não retorne o valor direto, adicione a uma variável antes:
<code>Json(new { endereco = repositorio.PesquisarCEP(cep)}, JsonRequestBehavior.AllowGet)
</code>
Depois você checa se a mesma é nula no cliente:
<code>    ...
success: function (retorno) {
    if (retorno.endereco) {
    ...
    }
    else {
        $.notify("Não foi encontrado o CEP: " + $("#enderecoCEP").val() + ", Você pode preencher o endereço manualmente.", { status: "danger" });
    ...
</code>


In Vega-lite, how do I filter by time?

Question: I have a CSV with a row per 15-minute interval and columns for metrics like airflow and temperature. I'd like to filter the data so I can plot only the most recent day or week.
How do I add a filter for a date (Mar 9) or date range (Mar 6–12)? Is it more common to do filtering and aggregation (to hourly or daily averages) before handing the data to Vega-Lite?
Here's my code without a filter:
{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "title": "Average Airflow",
  "description": "Average Airflow in Rooms",
  "data": {"url": "hvac_data-wide.csv"},
  "mark": "line",
  "width": 608,
  "height": 342,
  "transform": [{
    "timeUnit":"dayhours",
    "field": "Date",
    "as": "hours"
  }],
  "encoding": {
    "x": {"field": "hours", "type": "temporal", "title": "Time"},
    "y": {"field": "SaFl", "type": "quantitative", "aggregate": "mean", "title": "Source Air CFM"},
    "color": {"field": "Floor", "type": "nominal"}
  }
}

Here's some sample data:
Date,Category,Floor,Name,HVACModeStatus,RmTmp,SaFl,EaFl,CO2,NPW,ChW,wh,kwh
2022-03-07 08:10,zone,1,Lab1115,4,70.88,374.717,1109.641,,,,,
2022-03-07 08:10,zone,1,Lab1121,4,70.16,1700.559,1897.229,,,,,
2022-03-07 08:10,zone,1,Lab1126,2,73.22,1061.672,1572.01,,,,,
2022-03-07 08:15,zone,1,Lab1115,4,70.88,349.848,1170.564,,,,,
2022-03-07 08:15,zone,1,Lab1121,4,70.16,1699.6,1870.382,,,,,
2022-03-07 08:15,zone,1,Lab1126,2,73.22,1092.875,1606.451,,,,,
2022-03-07 08:20,zone,1,Lab1115,4,70.88,376.867,1156.398,,,,,
2022-03-07 08:20,zone,1,Lab1121,4,70.16,1692.929,1875.636,,,,,
2022-03-07 08:20,zone,1,Lab1126,2,73.22,1148.222,1580.696,,,,,

Thank you in advance.
Answer: Short answer: Filters can be added within the transform.
Here's code to show a date range filter:
{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "title": "Average Airflow",
  "description": "Average Airflow in Rooms",
  "data": {"url": "hvac_data-wide.csv"},
  "mark": "line",
  "width": 608,
  "height": 342,
  "transform": [
    {
      "timeUnit":"dayhours",
      "field": "Date",
      "as": "hours"
    },
    {"filter": {"field": "Date",
    "range": [  {"year": 2022, "month": 3, "date": 8, "hours": 0},
                {"year": 2022, "month": 3, "date": 8, "hours": 24, "minutes": 59}]}}
  ],
  "encoding": {
    "x": {"field": "hours", "type": "temporal", "title": "Time"},
    "y": {"field": "SaFl", "type": "quantitative", "aggregate": "mean", "title": "Exhaust CFM"},
    "color": {"field": "Floor", "type": "nominal"}
  }
}

They can also be simple expression string, substitute this filter block: { "filter": "datum.Floor == 3"}
Or a primitive: { "filter": {"field": "Floor", "equal": 3}}
More info about filters on the Vega-Lite docs Predicate page.

In Vega-lite, how do I filter by time?


Programatically insert field value of for a taxonomy term

Question: I have a taxonomy vocabulary called, school and the machine name is field_school_name. The vocabulary has a field called school id (machine name:field_school_id). I am able to add a verb successfully using the following code. How do I add the field value programatically? I want to add '1234' as the school id associated with the verb 'ABCD' I created.
<code>$new_term = \Drupal\taxonomy\Entity\Term::create([
    'vid' => 'field_school_name',
    'name' => 'ABCD',
]);

$new_term->enforceIsNew();
$new_term->save();
</code>
Comment: where are you writing this code? I mean which hook or where this snippet is written
Comment: @ShreyaShetty It is inside a hook
Answer: Should just need to do:
<code>$new_term = \Drupal\taxonomy\Entity\Term::create([
 'vid' => 'field_school_name',
 'name' => 'ABCD',
 'field_school_id' => '1234'
]);
</code>
Comment: That worked! if the field_school_id is a reference entity how do I assign the value?
Comment: You'd need to give it the entity ID  of the entity you want to reference and the entity API should take care of the rest